What it is
SELinux (Security-Enhanced Linux) is a mandatory access control (MAC) system that provides a flexible, fine-grained security policy for Linux systems. You reach for SELinux management tools when you need to understand, control, or troubleshoot access denials based on security policies.
Installation
Linux
SELinux is typically installed by default on many enterprise Linux distributions (e.g., RHEL, CentOS, Fedora). If not, you can usually install the necessary tools using your distribution’s package manager.
On RHEL/CentOS/Fedora:
sudo yum install policycoreutils policycoreutils-python selinux-policy-devel setools-console
# or
sudo dnf install policycoreutils policycoreutils-python selinux-policy-devel setools-console
Mac
SELinux is not native to macOS.
Windows
SELinux is not native to Windows.
Core Concepts
- Security Context (Label): Every process and file object on an SELinux-enabled system has a security context. This context includes a user, role, type, and optionally level. The
typeis the most crucial part for policy enforcement.- Process Context:
user:role:type:level(e.g.,unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023) - File Context:
user:role:object_type:level(e.g.,/var/www/html/index.htmlhas contextsystem_u:object_r:httpd_sys_content_t:s0)
- Process Context:
- Policy: A set of rules that define what types of processes can access what types of objects, and what actions they can perform. Policies are compiled and loaded into the kernel.
- Type Enforcement (TE): The primary mechanism of SELinux. It defines relationships between types (e.g.,
httpd_tcan readhttpd_sys_content_t). - Booleans: On/off switches that allow you to tweak SELinux policy behavior without recompiling the entire policy.
- Modes:
- Enforcing: SELinux policy is actively enforced. Denials are logged.
- Permissive: SELinux policy is not enforced, but denials are logged. Useful for troubleshooting.
- Disabled: SELinux is completely turned off.
Commands / Usage
Checking SELinux Status and Mode
- Check current SELinux status and mode:
Example Output:sestatusSELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: enforcing Mode from config file: enforcing Policy MLS status: enabled Policy deny_unknown status: allowed Memory protection checking: actual (secure) Max kernel policy version: 33 - Check current SELinux mode (shorter):
Output:getenforceEnforcing,Permissive, orDisabled
Changing SELinux Mode
- Temporarily set SELinux to Permissive mode (until reboot):
sudo setenforce 0 - Temporarily set SELinux to Enforcing mode (until reboot):
sudo setenforce 1 - Permanently set SELinux mode (requires reboot):
Edit
/etc/selinux/configand changeSELINUX=enforcingorSELINUX=permissive. Example line in/etc/selinux/config:SELINUX=enforcing
Managing File Contexts
- List SELinux contexts of files/directories:
Example:ls -Z /path/to/file_or_directory
Output:ls -Z /var/www/html/drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 . -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 index.html - Relabel a file or directory to a specific context:
Explanation: Changes the type context ofsudo chcon -t httpd_sys_content_t /var/www/html/new_page.htmlnew_page.htmltohttpd_sys_content_t. This change is temporary and will be lost on a filesystem relabel. - Recursively relabel a directory and its contents:
sudo chcon -R -t httpd_sys_content_t /var/www/html/ - Restore default SELinux contexts for a file/directory (permanent):
This command uses the SELinux policy database to apply the correct, default context.
Example:sudo restorecon -v /path/to/file_or_directorysudo restorecon -v /var/www/html/ - Recursively restore default SELinux contexts:
sudo restorecon -Rv /path/to/directory - View the SELinux policy rules for file contexts:
semanage fcontext -l - Add a custom SELinux file context rule:
This tells SELinux what context to apply to new files matching a pattern.
Explanation: Adds a rule to labelsudo semanage fcontext -a -t httpd_sys_content_t "/var/www/html/uploads(/.*)?"/var/www/html/uploadsand everything within it (/.*) with thehttpd_sys_content_ttype. You must runrestoreconafterwards to apply it to existing files.sudo restorecon -Rv /var/www/html/uploads - Delete a custom SELinux file context rule:
sudo semanage fcontext -d "/var/www/html/uploads(/.*)?"
Managing SELinux Booleans
- List all available SELinux booleans:
Example Output Snippet:sudo semanage boolean -l[...] httpd_can_network_relay (on,off) httpd_can_sendmail (off,off) httpd_enable_httpd_log_read (off,off) [...] - Check the current status of a specific boolean:
Output:sudo getsebool httpd_can_network_relayhttpd_can_network_relay --> off - Enable a boolean (temporarily):
sudo setsebool httpd_can_network_relay on - Disable a boolean (temporarily):
sudo setsebool httpd_can_network_relay off - Enable a boolean persistently (across reboots):
sudo setsebool -P httpd_can_network_relay on - Disable a boolean persistently (across reboots):
sudo setsebool -P httpd_can_network_relay off - Search for booleans related to a service:
sudo semanage boolean -l | grep httpd
Troubleshooting Denials (Audit Logs)
- View SELinux denial messages:
SELinux denials are logged in the audit log. Use
ausearchto query them.
Explanation: Searches for Audit Messages (sudo ausearch -m avc -ts recent-m avc) since (-ts)recent(e.g., last 10 minutes).
Explanation: Searches for Audit Messages (sudo ausearch -m avc -ts today-m avc) since (-ts)today.
Explanation: Searches for Audit Messages (sudo ausearch -m avc -ts 11/01/2023 10:00:00-m avc) since (-ts) a specific date and time. - View denials for a specific process (PID):
Explanation: Searches for Audit Messages (sudo ausearch -m avc -p 12345-m avc) for process ID (-p)12345. - View denials related to a specific file:
sudo ausearch -m avc -f /path/to/denied/file - Generate a summary of denials:
Explanation: Filters the audit log for denial messages and pipes them tosudo grep "SELinux is preventing" /var/log/audit/audit.log | audit2allowaudit2allowto suggest SELinux policy rules. - Generate a temporary policy module to allow a denial:
This is a common troubleshooting step. It creates a
.tefile and a.pp(policy package) file.
Explanation: Createssudo grep "SELinux is preventing" /var/log/audit/audit.log | audit2allow -M mymodulemymodule.teandmymodule.pp.- To load this temporary module:
sudo semodule -i mymodule.pp - To remove the temporary module:
sudo semodule -r mymodule - Note: It’s generally better to understand why a denial is happening and fix the underlying cause (e.g., wrong file context, incorrect boolean) rather than blindly loading modules. However, this is invaluable for quick fixes or understanding required permissions.
- To load this temporary module:
- Use
sealertfor human-readable denial explanations: Ifsetroubleshoot-serveris installed,sealertprovides more context.
This command might output detailed reports or suggest specific actions.sudo sealert -a /var/log/audit/audit.log
Managing Policy Modules
- List installed SELinux policy modules:
sudo semodule -l - Install a policy module package (.pp file):
sudo semodule -i /path/to/your_module.pp - Remove a policy module:
Example:sudo semodule -r module_namesudo semodule -r httpd_userdir - List available SELinux types:
sudo semanage type -l - List available SELinux ports:
sudo semanage port -l - Add a custom port context:
Explanation: Allows TCP traffic on portsudo semanage port -a -t http_port_t -p tcp 80808080to be treated ashttp_port_t. - Delete a custom port context:
sudo semanage port -d -t http_port_t -p tcp 8080
Common Patterns
-
Troubleshooting a web server (Apache/Nginx) access issue:
- Check
sestatus. Is it enforcing? - Try
sudo setenforce 0to see if the issue disappears. If it does, SELinux is involved. - Check web server logs (
/var/log/httpd/error_logor/var/log/nginx/error.log). - Check audit logs for denials:
sudo ausearch -m avc -ts recent. - If you see denials, use
audit2allowto understand:sudo grep "SELinux is preventing" /var/log/audit/audit.log | audit2allow -w. - Identify the file context:
ls -Zd /path/to/problem/file. Is ithttpd_sys_content_tor similar? - If the context is wrong, restore it:
sudo restorecon -Rv /path/to/web/directory. - If a specific feature isn’t working (e.g., web server writing logs), check booleans:
sudo semanage boolean -l | grep httpd. Try enabling relevant ones persistently:sudo setsebool -P httpd_enable_homedirs on.
- Check
-
Allowing a custom application to bind to a non-standard port:
# Assume your app needs to bind to port 9999 and requires http_port_t context sudo semanage port -a -t http_port_t -p tcp 9999 sudo systemctl restart your_app.service -
Allowing a service to access user home directories:
# Example: Allowing httpd to read files in user home directories sudo setsebool -P httpd_enable_homedirs on sudo systemctl restart httpd -
Relabeling an entire filesystem after a
restoreconorchconon the root: Use this with extreme caution. It can take a long time.sudo touch /.autorelabel sudo rebootThe system will relabel all files during the next boot.
Gotchas
chconvsrestoreconvssemanage fcontext:chcon: Temporarily changes the context. Lost on relabeling orrestorecon. Use for quick tests.restorecon: Resets the context to the one defined in the policy database for that file path. Use when you’ve moved files or need to ensure the "correct" default context is applied.semanage fcontext -a: Defines a new rule in the policy database. This rule tells SELinux what context to apply to files matching a pattern in the future. You must runrestoreconafterwards to apply it to existing files. This is the most permanent way to manage file contexts.
- Reboot required for
setenforcechanges to be permanent: Changes made withsetenforceare temporary. To make them permanent, edit/etc/selinux/configand reboot. audit2allowis powerful but dangerous: Blindly loadingaudit2allowmodules can weaken your security posture. Always try to understand the denial and fix the root cause (e.g., correct file context, enable the right boolean) before resorting to custom policy modules.- Filesystem relabeling takes time:
/.autorelabelis effective but can take hours on large filesystems. - Network access denials: Often require
semanage portchanges or specific booleans (e.g.,httpd_can_network_connect). Checkausearch -m avc -ts recentfor denials. - Contexts might vary: The exact context labels (
httpd_sys_content_t,httpd_t, etc.) can differ slightly between SELinux policy versions. Usesemanage fcontext -landsemanage type -lto verify.