SELinux Deep Dive

Custom policy creation, boolean management, file context transitions, and troubleshooting.

Core Concepts

SELinux enforces mandatory access control (MAC) using labels (user:role:type:level) and policies that define what each domain can access.

# Current mode
getenforce

# Detailed status
sestatus

# View file labels
ls -lZ /etc/passwd

# View process domain
ps -eZ | grep httpd

# View port labels
semanage port -l | grep http

# View boolean list
getsebool -a

Boolean Management

# Search for a boolean
getsebool -a | grep httpd

# Enable a boolean (runtime)
sudo setsebool httpd_can_network_connect on

# Enable permanently
sudo setsebool -P httpd_can_network_connect on

# Common booleans:
# httpd_can_network_connect    — allow httpd outbound connections
# httpd_can_network_connect_db — allow httpd to connect to databases
# httpd_read_user_content      — allow httpd to read ~/public_html
# ftpd_anon_write              — allow FTP anonymous writes
# sftpd_anon_write             — allow SFTP anonymous writes

File Context Transitions

# View default context for a path
semanage fcontext -l | grep /var/www

# Add a custom file context rule
sudo semanage fcontext -a -t httpd_sys_content_t "/data/www(/.*)?"

# Apply the context to existing files
sudo restorecon -Rv /data/www

# Verify
ls -lZ /data/www/

# Remove a file context rule
sudo semanage fcontext -d "/data/www(/.*)?"

# Temporarily change context (lost on restorecon)
sudo chcon -t httpd_sys_content_t /data/www

# Restore to default context
sudo restorecon -Rv /var/www/

Custom Policy Creation

# Install policy tools
sudo dnf install -y policycoreutils-python-utils

# Audit recent AVC denials
sudo ausearch -m avc -ts recent

# Generate policy module from audit log
sudo ausearch -c 'myapp' --raw | audit2allow -M myapp_policy

# Review the generated module (myapp_policy.te)
cat myapp_policy.te

# Install the module
sudo semodule -i myapp_policy.pp

# Verify installation
sudo semodule -l | grep myapp

# Remove module
sudo semodule -r myapp_policy

# Full workflow for a new application:
# 1. Run app in permissive mode temporarily
sudo setenforce 0
# 2. Perform all required operations
# 3. Re-enable enforcing
sudo setenforce 1
# 4. Collect denials and generate policy
sudo ausearch -m avc -ts recent | audit2allow -M myapp
sudo semodule -i myapp.pp

Troubleshooting

# Install sealert for human-readable analysis
sudo dnf install -y setroubleshoot-server

# Analyze denials
sudo sealert -a /var/log/audit/audit.log

# Analyze specific denial
sudo sealert -l <uuid-from-audit-log>

# Generate fix suggestions
sudo sealert -a /var/log/audit/audit.log -m

# Clear audit log (rotate via logrotate, do NOT use auditctl -D)
# auditctl -D deletes audit RULES, not the log
# sudo ausearch -m avc -ts recent  # Review denials first

# View denial summary
sudo ausearch -m avc -ts today | audit2why