Understanding SELinux Network Restrictions in CentOS
SELinux (Security-Enhanced Linux) is a mandatory access control (MAC) mechanism in CentOS that enforces strict security policies on network access. It uses contexts (labels for processes, ports, and files), booleans (runtime toggles for specific permissions), and modules (predefined or custom policies) to regulate whether a process can initiate or accept network connections, bind to ports, or access network resources. By default, SELinux operates in Enforcing mode (actively blocking unauthorized actions), which can prevent services like Nginx, Apache, or SSH from functioning correctly if their network operations are not explicitly permitted.
Key Steps to Manage SELinux Network Restrictions
Before making changes, verify if SELinux is enabled and its current mode. Run:
sestatus
Use the semanage command to list allowed ports and their types (e.g., http_port_t for web traffic):
semanage port -l
This helps identify if a required port (e.g., 8080 for a custom web app) is missing from the default policy.
If a service needs to use a non-standard port (e.g., running a web app on TCP 8080), add it to the appropriate port type using semanage:
sudo semanage port -a -t http_port_t -p tcp 8080
-a: Add a new rule.-t http_port_t: Assign the port to the “http” port type (required for web services).-p tcp: Specify the protocol (TCP or UDP).8080: The port number.Booleans are toggleable options that enable/disable common network permissions. For example:
sudo setsebool -P httpd_can_network_connect 1
The -P flag makes the change persistent across reboots.sudo setsebool -P httpd_can_network_connect_ipv4 1
sudo setsebool -P httpd_can_network_connect_ipv6 0
Use getsebool -a to view all available booleans.When SELinux blocks a network operation, it logs the event to /var/log/audit/audit.log. Use these tools to diagnose and resolve issues:
grep avc /var/log/audit/audit.log
audit2allow):sudo ausearch -m avc -ts recent | audit2why
This command shows why the action was blocked and suggests a fix (e.g., “allow httpd_t to connect to any port”).sudo ausearch -m avc -ts recent | audit2allow -M my_custom_policy
sudo semodule -i my_custom_policy.pp
Replace my_custom_policy with a descriptive name. The -M flag generates both the .te (policy source) and .pp (compiled module) files.If a file or directory has an incorrect SELinux context (e.g., a web app’s root directory), use restorecon to reset it to the default:
sudo restorecon -Rv /var/www/html
-R: Recursively apply to directories.-v: Show verbose output.Best Practices for SELinux Network Security
ausearch and audit2why to monitor for unauthorized network access attempts.setenforce 0) to verify they work without breaking functionality.