Prerequisites for Using SELinux on Ubuntu
Ubuntu does not enable SELinux by default (it uses AppArmor instead). To use SELinux, you must first install the required packages and activate the module:
sudo apt update && sudo apt install selinux-basics selinux-policy-default auditd sudo selinux-activate sudo reboot sestatus The output should show SELinux status: enabled and Current mode: enforcing.Steps to Enable a Specific Service with SELinux
Enabling a service in SELinux involves configuring the correct security context, adjusting boolean settings, and creating custom policies if needed. Below is a structured approach:
Before making changes, confirm SELinux is running in the desired mode (enforcing/permissive):
getenforce # Temporary check (current session) sestatus # Detailed status (including config file mode) If in permissive mode, switch to enforcing to apply policies:
sudo setenforce 1 Ensure the service’s executable, files, and ports have the correct SELinux labels. Use these commands:
ps -eZ | grep <service_name> Example for Apache: ps -eZ | grep httpd (should show httpd_t).ls -Z /path/to/service/files Example for Apache: ls -Z /var/www/html (should show httpd_sys_content_t).semanage port -l | grep <port_number> Example for HTTP: semanage port -l | grep 80 (should show http_port_t).Many services require specific boolean flags to allow actions (e.g., binding to non-standard ports, accessing user directories). List available booleans for your service:
sudo semanage boolean -l | grep <service_name> Example for Apache:
sudo semanage boolean -l | grep httpd To enable a boolean (e.g., allow Apache to access user home directories):
sudo setsebool -P httpd_enable_homedirs 1 The -P flag makes the change permanent.
If the service’s files or ports lack the correct labels, update them:
chcon -R -t <required_type> /path/to/service/files Example for Apache: chcon -R -t httpd_sys_content_t /web (allows Apache to read files in /web).semanage fcontext -a -t <required_type> "/path/to/service/files(/.*)?" restorecon -Rv /path/to/service/files Example for Apache:semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?" restorecon -Rv /web semanage port -a -t <port_type> -p <protocol> <port_number> Example for Apache on port 8080:semanage port -a -t http_port_t -p tcp 8080 If the service is still blocked after adjusting contexts and booleans, create a custom SELinux policy module to allow the denied action:
sudo ausearch -c '<service_name>' --raw | audit2why Example for a custom app myapp: sudo ausearch -c 'myapp' --raw | audit2why.sudo ausearch -c '<service_name>' --raw | audit2allow -M <module_name> Example: sudo ausearch -c 'myapp' --raw | audit2allow -M myapp_policy.sudo semodule -i <module_name>.pp Example: sudo semodule -i myapp_policy.pp.Verification and Troubleshooting
After making changes, verify the service works as expected. If issues persist:
sudo setenforce 0 sudo ausearch -m avc -ts recent