SELinux Management

SELinux management cheatsheet — semanage fcontext, semanage port, restorecon, audit2allow. Fix SELinux denials, manage ports and file contexts. setenforce 0/1 for permissive mode.

8 min read

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 type is 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.html has context system_u:object_r:httpd_sys_content_t:s0)
  • 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_t can read httpd_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:
    sestatus
    
    Example Output:
    SELinux 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):
    getenforce
    
    Output: Enforcing, Permissive, or Disabled

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/config and change SELINUX=enforcing or SELINUX=permissive. Example line in /etc/selinux/config:
    SELINUX=enforcing
    

Managing File Contexts

  • List SELinux contexts of files/directories:
    ls -Z /path/to/file_or_directory
    
    Example:
    ls -Z /var/www/html/
    
    Output:
    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:
    sudo chcon -t httpd_sys_content_t /var/www/html/new_page.html
    
    Explanation: Changes the type context of new_page.html to httpd_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.
    sudo restorecon -v /path/to/file_or_directory
    
    Example:
    sudo 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.
    sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/html/uploads(/.*)?"
    
    Explanation: Adds a rule to label /var/www/html/uploads and everything within it (/.*) with the httpd_sys_content_t type. You must run restorecon afterwards 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:
    sudo semanage boolean -l
    
    Example Output Snippet:
    [...]
    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:
    sudo getsebool httpd_can_network_relay
    
    Output: httpd_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 ausearch to query them.
    sudo ausearch -m avc -ts recent
    
    Explanation: Searches for Audit Messages (-m avc) since (-ts) recent (e.g., last 10 minutes).
    sudo ausearch -m avc -ts today
    
    Explanation: Searches for Audit Messages (-m avc) since (-ts) today.
    sudo ausearch -m avc -ts 11/01/2023 10:00:00
    
    Explanation: Searches for Audit Messages (-m avc) since (-ts) a specific date and time.
  • View denials for a specific process (PID):
    sudo ausearch -m avc -p 12345
    
    Explanation: Searches for Audit Messages (-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:
    sudo grep "SELinux is preventing" /var/log/audit/audit.log | audit2allow
    
    Explanation: Filters the audit log for denial messages and pipes them to audit2allow to suggest SELinux policy rules.
  • Generate a temporary policy module to allow a denial: This is a common troubleshooting step. It creates a .te file and a .pp (policy package) file.
    sudo grep "SELinux is preventing" /var/log/audit/audit.log | audit2allow -M mymodule
    
    Explanation: Creates mymodule.te and mymodule.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.
  • Use sealert for human-readable denial explanations: If setroubleshoot-server is installed, sealert provides more context.
    sudo sealert -a /var/log/audit/audit.log
    
    This command might output detailed reports or suggest specific actions.

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:
    sudo semodule -r module_name
    
    Example: sudo 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:
    sudo semanage port -a -t http_port_t -p tcp 8080
    
    Explanation: Allows TCP traffic on port 8080 to be treated as http_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:

    1. Check sestatus. Is it enforcing?
    2. Try sudo setenforce 0 to see if the issue disappears. If it does, SELinux is involved.
    3. Check web server logs (/var/log/httpd/error_log or /var/log/nginx/error.log).
    4. Check audit logs for denials: sudo ausearch -m avc -ts recent.
    5. If you see denials, use audit2allow to understand: sudo grep "SELinux is preventing" /var/log/audit/audit.log | audit2allow -w.
    6. Identify the file context: ls -Zd /path/to/problem/file. Is it httpd_sys_content_t or similar?
    7. If the context is wrong, restore it: sudo restorecon -Rv /path/to/web/directory.
    8. 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.
  • 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 restorecon or chcon on the root: Use this with extreme caution. It can take a long time.

    sudo touch /.autorelabel
    sudo reboot
    

    The system will relabel all files during the next boot.

Gotchas

  • chcon vs restorecon vs semanage fcontext:
    • chcon: Temporarily changes the context. Lost on relabeling or restorecon. 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 run restorecon afterwards to apply it to existing files. This is the most permanent way to manage file contexts.
  • Reboot required for setenforce changes to be permanent: Changes made with setenforce are temporary. To make them permanent, edit /etc/selinux/config and reboot.
  • audit2allow is powerful but dangerous: Blindly loading audit2allow modules 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: /.autorelabel is effective but can take hours on large filesystems.
  • Network access denials: Often require semanage port changes or specific booleans (e.g., httpd_can_network_connect). Check ausearch -m avc -ts recent for denials.
  • Contexts might vary: The exact context labels (httpd_sys_content_t, httpd_t, etc.) can differ slightly between SELinux policy versions. Use semanage fcontext -l and semanage type -l to verify.