How to configure SELinux policies in Linux
How to Configure SELinux Policies in Linux
Security-Enhanced Linux (SELinux) is a mandatory access control (MAC) security mechanism that provides fine-grained access control over system resources. Originally developed by the National Security Agency (NSA), SELinux has become an essential security feature in enterprise Linux distributions like Red Hat Enterprise Linux, CentOS, and Fedora. This comprehensive guide will walk you through everything you need to know about configuring SELinux policies, from basic concepts to advanced customization techniques.
Table of Contents
1. [Understanding SELinux Fundamentals](#understanding-selinux-fundamentals)
2. [Prerequisites and Requirements](#prerequisites-and-requirements)
3. [SELinux Modes and Configuration](#selinux-modes-and-configuration)
4. [Working with SELinux Contexts](#working-with-selinux-contexts)
5. [Managing SELinux Policies](#managing-selinux-policies)
6. [Creating Custom SELinux Policies](#creating-custom-selinux-policies)
7. [Practical Examples and Use Cases](#practical-examples-and-use-cases)
8. [Troubleshooting Common Issues](#troubleshooting-common-issues)
9. [Best Practices and Security Tips](#best-practices-and-security-tips)
10. [Conclusion and Next Steps](#conclusion-and-next-steps)
Understanding SELinux Fundamentals
SELinux operates on the principle of least privilege, where every process and file is assigned a security context that determines what actions are permitted. Unlike traditional discretionary access control (DAC) systems that rely on file permissions and ownership, SELinux implements mandatory access control that cannot be overridden by users or applications.
Key SELinux Concepts
Security Contexts: Every file, process, and system resource has a security context consisting of four components:
- User: SELinux user identity (different from Linux users)
- Role: Defines what the user can do
- Type: The most important component for policy decisions
- Level: Used in Multi-Level Security (MLS) environments
Policy Types: SELinux supports different policy types:
- Targeted: Default policy focusing on network services
- Minimum: Minimal policy for basic protection
- MLS: Multi-Level Security for classified environments
Booleans: Runtime switches that enable or disable specific policy rules without recompiling the entire policy.
Prerequisites and Requirements
Before configuring SELinux policies, ensure your system meets the following requirements:
System Requirements
- Linux distribution with SELinux support (RHEL, CentOS, Fedora, or compatible)
- Root or sudo access
- Basic understanding of Linux file permissions and processes
- Familiarity with command-line operations
Required Packages
Install the necessary SELinux management tools:
```bash
On RHEL/CentOS/Fedora
sudo yum install policycoreutils policycoreutils-python setools-console
On newer systems with dnf
sudo dnf install policycoreutils policycoreutils-python-utils setools-console
Verify installation
rpm -qa | grep selinux
```
Checking SELinux Status
Before making changes, check your current SELinux configuration:
```bash
Check SELinux status
sestatus
Check current mode
getenforce
View detailed status
sestatus -v
```
SELinux Modes and Configuration
SELinux operates in three distinct modes, each serving different purposes in system security and troubleshooting.
Understanding SELinux Modes
Enforcing Mode: SELinux actively enforces security policies, denying unauthorized actions and logging violations.
Permissive Mode: SELinux logs policy violations but doesn't block actions. Ideal for testing and troubleshooting.
Disabled Mode: SELinux is completely turned off. Not recommended for production systems.
Changing SELinux Modes
Temporary Mode Changes
Change the mode temporarily (reverts after reboot):
```bash
Switch to permissive mode
sudo setenforce 0
Switch to enforcing mode
sudo setenforce 1
Verify the change
getenforce
```
Permanent Mode Changes
Modify the SELinux configuration file for permanent changes:
```bash
Edit the SELinux configuration file
sudo vi /etc/selinux/config
Set the desired mode
SELINUX=enforcing # or permissive, or disabled
SELINUXTYPE=targeted # policy type
```
Important: Changing from disabled to enforcing requires a system reboot and file relabeling, which can take considerable time.
Enabling SELinux on Previously Disabled Systems
If SELinux was disabled, follow these steps to enable it safely:
```bash
1. Edit the configuration file
sudo vi /etc/selinux/config
Set SELINUX=permissive
2. Reboot the system
sudo reboot
3. After reboot, relabel the filesystem
sudo fixfiles -f relabel
4. Switch to enforcing mode
sudo setenforce 1
5. Update configuration for permanent enforcing
sudo sed -i 's/SELINUX=permissive/SELINUX=enforcing/' /etc/selinux/config
```
Working with SELinux Contexts
Understanding and managing SELinux contexts is crucial for proper policy configuration.
Viewing SELinux Contexts
Display contexts for files and processes:
```bash
View file contexts
ls -Z /etc/passwd
ls -lZ /var/www/html/
View process contexts
ps -eZ | grep httpd
View current user context
id -Z
```
Managing File Contexts
Restoring Default Contexts
Use `restorecon` to restore default SELinux contexts:
```bash
Restore context for a single file
sudo restorecon /var/www/html/index.html
Restore contexts recursively
sudo restorecon -R /var/www/html/
Restore with verbose output
sudo restorecon -Rv /var/www/html/
```
Setting Custom Contexts
Manually set SELinux contexts when needed:
```bash
Set context for a specific file
sudo chcon -t httpd_exec_t /usr/local/bin/custom-httpd
Set context recursively
sudo chcon -R -t httpd_exec_t /usr/local/apache/
Copy context from another file
sudo chcon --reference=/var/www/html/index.html /var/www/html/newfile.html
```
Managing Context Mappings
Define persistent context mappings:
```bash
Add a file context mapping
sudo semanage fcontext -a -t httpd_exec_t "/usr/local/apache/bin/httpd"
Apply the mapping
sudo restorecon /usr/local/apache/bin/httpd
List current mappings
sudo semanage fcontext -l | grep httpd
Delete a mapping
sudo semanage fcontext -d "/usr/local/apache/bin/httpd"
```
Managing SELinux Policies
SELinux policies define the rules that govern system access. Understanding how to manage these policies is essential for system administrators.
Working with SELinux Booleans
Booleans provide runtime policy customization without recompiling:
```bash
List all booleans
sudo getsebool -a
Check specific boolean
sudo getsebool httpd_can_network_connect
Set boolean temporarily
sudo setsebool httpd_can_network_connect on
Set boolean permanently
sudo setsebool -P httpd_can_network_connect on
List booleans with descriptions
sudo semanage boolean -l | grep httpd
```
Managing SELinux Modules
SELinux uses modular policies that can be loaded and unloaded:
```bash
List loaded modules
sudo semodule -l
Install a policy module
sudo semodule -i custom_policy.pp
Remove a policy module
sudo semodule -r custom_policy
Upgrade a policy module
sudo semodule -u updated_policy.pp
List modules with versions
sudo semodule -l -v
```
Port Management
Configure SELinux port policies for network services:
```bash
List port contexts
sudo semanage port -l | grep http
Add a port to a service
sudo semanage port -a -t http_port_t -p tcp 8080
Modify an existing port assignment
sudo semanage port -m -t http_port_t -p tcp 8080
Delete a port assignment
sudo semanage port -d -p tcp 8080
```
Creating Custom SELinux Policies
Sometimes default policies don't meet specific application requirements, necessitating custom policy creation.
Using audit2allow for Policy Generation
The `audit2allow` tool generates policy rules from SELinux denial logs:
```bash
Generate policy from audit log
sudo audit2allow -a
Generate policy for specific service
sudo grep httpd /var/log/audit/audit.log | audit2allow
Create a policy module
sudo grep httpd /var/log/audit/audit.log | audit2allow -M myhttpd
Install the generated module
sudo semodule -i myhttpd.pp
```
Manual Policy Creation
For complex requirements, create policies manually:
```bash
Create policy source file
cat > custom_app.te << EOF
module custom_app 1.0;
require {
type unconfined_t;
type user_home_t;
class file { read write };
}
Allow custom_app to read/write user home files
allow custom_app_t user_home_t:file { read write };
EOF
Compile the policy
sudo checkmodule -M -m -o custom_app.mod custom_app.te
Create policy package
sudo semodule_package -o custom_app.pp -m custom_app.mod
Install the policy
sudo semodule -i custom_app.pp
```
Testing Custom Policies
Always test custom policies in permissive mode:
```bash
Switch to permissive mode
sudo setenforce 0
Test your application
Monitor /var/log/audit/audit.log for denials
Review and refine policy
sudo audit2allow -a -w
Switch back to enforcing when satisfied
sudo setenforce 1
```
Practical Examples and Use Cases
Example 1: Configuring SELinux for Web Server
Setting up SELinux for a custom web server installation:
```bash
1. Set proper context for web content
sudo semanage fcontext -a -t httpd_exec_t "/opt/webapp/bin/webapp"
sudo semanage fcontext -a -t httpd_config_t "/opt/webapp/conf(/.*)?"
sudo semanage fcontext -a -t httpd_log_t "/opt/webapp/logs(/.*)?"
2. Apply contexts
sudo restorecon -R /opt/webapp/
3. Allow web server to bind to custom port
sudo semanage port -a -t http_port_t -p tcp 8080
4. Enable necessary booleans
sudo setsebool -P httpd_can_network_connect on
sudo setsebool -P httpd_can_network_connect_db on
```
Example 2: Database Server Configuration
Configuring SELinux for a PostgreSQL installation in a custom location:
```bash
1. Set database contexts
sudo semanage fcontext -a -t postgresql_exec_t "/opt/pgsql/bin/postgres"
sudo semanage fcontext -a -t postgresql_db_t "/opt/pgsql/data(/.*)?"
sudo semanage fcontext -a -t postgresql_log_t "/opt/pgsql/logs(/.*)?"
2. Apply contexts
sudo restorecon -R /opt/pgsql/
3. Configure port access
sudo semanage port -a -t postgresql_port_t -p tcp 5432
4. Allow database network connections if needed
sudo setsebool -P postgresql_can_rsync on
```
Example 3: Application with Custom Requirements
Creating policy for an application that needs special permissions:
```bash
1. Run application in permissive mode and collect denials
sudo setenforce 0
Run your application and generate some denials
2. Generate initial policy
sudo grep myapp /var/log/audit/audit.log | audit2allow -M myapp_policy
3. Review generated policy
cat myapp_policy.te
4. Install and test
sudo semodule -i myapp_policy.pp
sudo setenforce 1
```
Troubleshooting Common Issues
Analyzing SELinux Denials
When SELinux blocks an action, it logs the denial. Here's how to analyze and resolve these issues:
```bash
View recent denials
sudo ausearch -m AVC -ts recent
Search for specific service denials
sudo ausearch -m AVC -c httpd
Use sealert for detailed analysis
sudo sealert -a /var/log/audit/audit.log
```
Common SELinux Problems and Solutions
Problem 1: Web Server Can't Access Files
Symptoms: HTTP 403 errors, "Permission denied" in logs
Solution:
```bash
Check file contexts
ls -lZ /var/www/html/
Restore proper contexts
sudo restorecon -R /var/www/html/
Or set correct context manually
sudo chcon -t httpd_exec_t /var/www/html/script.cgi
```
Problem 2: Service Can't Bind to Port
Symptoms: "Permission denied" when starting service on custom port
Solution:
```bash
Check current port assignments
sudo semanage port -l | grep http_port_t
Add your custom port
sudo semanage port -a -t http_port_t -p tcp 8080
```
Problem 3: Database Connection Issues
Symptoms: Applications can't connect to database
Solution:
```bash
Enable database connection boolean
sudo setsebool -P httpd_can_network_connect_db on
Check for port issues
sudo semanage port -l | grep postgresql_port_t
```
Using SELinux Troubleshooting Tools
setroubleshoot
Install and use setroubleshoot for automated suggestions:
```bash
Install setroubleshoot
sudo yum install setroubleshoot-server
Analyze audit log
sudo sealert -a /var/log/audit/audit.log
Browse suggestions in web interface
sudo sealert -b
```
Manual Log Analysis
When automated tools aren't sufficient:
```bash
Extract denials for specific time period
sudo ausearch -m AVC -ts today
Filter by specific context
sudo ausearch -m AVC -sc httpd_t
Combine with audit2allow for policy generation
sudo ausearch -m AVC -ts today | audit2allow -w
```
Best Practices and Security Tips
Security Best Practices
1. Never Disable SELinux in Production: Always use permissive mode for troubleshooting instead of disabling SELinux completely.
2. Regular Policy Updates: Keep your SELinux policies updated with system updates:
```bash
sudo yum update selinux-policy\*
```
3. Minimal Custom Policies: Create the most restrictive custom policies possible. Avoid overly permissive rules.
4. Document Custom Changes: Maintain documentation of all custom SELinux configurations:
```bash
# Document your changes
sudo semanage fcontext -l > /root/selinux-fcontexts-backup.txt
sudo semanage port -l > /root/selinux-ports-backup.txt
```
Monitoring and Maintenance
Regular Monitoring
Set up monitoring for SELinux denials:
```bash
Create monitoring script
cat > /usr/local/bin/selinux-monitor.sh << 'EOF'
#!/bin/bash
LOGFILE="/var/log/selinux-denials.log"
ausearch -m AVC -ts today >> $LOGFILE 2>/dev/null
if [ -s $LOGFILE ]; then
echo "SELinux denials detected on $(hostname)" | mail -s "SELinux Alert" admin@example.com
fi
EOF
Make executable and add to cron
sudo chmod +x /usr/local/bin/selinux-monitor.sh
echo "0 /6 /usr/local/bin/selinux-monitor.sh" | sudo crontab -
```
Policy Backup and Recovery
Regularly backup your SELinux configuration:
```bash
Backup script
#!/bin/bash
BACKUP_DIR="/root/selinux-backup-$(date +%Y%m%d)"
mkdir -p $BACKUP_DIR
Backup current policy
semodule -l > $BACKUP_DIR/modules.txt
semanage fcontext -l > $BACKUP_DIR/fcontexts.txt
semanage port -l > $BACKUP_DIR/ports.txt
getsebool -a > $BACKUP_DIR/booleans.txt
cp /etc/selinux/config $BACKUP_DIR/
```
Performance Considerations
SELinux has minimal performance impact when properly configured:
1. Avoid Excessive Custom Policies: Too many custom rules can slow down policy lookups.
2. Regular Policy Cleanup: Remove unused custom modules:
```bash
# List modules and their usage
sudo semodule -l
# Remove unused modules
sudo semodule -r unused_module
```
3. Monitor System Performance: Use tools like `top` and `iotop` to monitor any performance impact.
Advanced Configuration Techniques
Multi-Level Security (MLS)
For high-security environments, configure MLS:
```bash
Install MLS policy
sudo yum install selinux-policy-mls
Configure for MLS
sudo sed -i 's/SELINUXTYPE=targeted/SELINUXTYPE=mls/' /etc/selinux/config
Reboot and relabel
sudo touch /.autorelabel
sudo reboot
```
User and Role Management
Manage SELinux users and roles:
```bash
List SELinux users
sudo semanage user -l
Map Linux user to SELinux user
sudo semanage login -a -s user_u john
Create custom SELinux user
sudo semanage user -a -R "user_r" -r s0 custom_user_u
```
Integration with Configuration Management
Integrate SELinux with automation tools:
```yaml
Ansible example
- name: Set SELinux file context
sefcontext:
target: '/opt/myapp(/.*)?'
setype: httpd_exec_t
state: present
- name: Apply SELinux context
command: restorecon -R /opt/myapp
```
Conclusion and Next Steps
Configuring SELinux policies effectively requires understanding the fundamental concepts of mandatory access control, security contexts, and policy management. Throughout this guide, we've covered everything from basic mode configuration to advanced custom policy creation.
Key Takeaways
1. SELinux provides robust security through mandatory access control that complements traditional file permissions
2. Proper context management is crucial for SELinux to function correctly
3. Custom policies should be minimal and well-tested before deployment in production
4. Regular monitoring and maintenance ensure ongoing security effectiveness
5. Never disable SELinux in production - use permissive mode for troubleshooting instead
Next Steps
To further enhance your SELinux expertise:
1. Practice in Lab Environment: Set up a test environment to experiment with different configurations
2. Study Existing Policies: Examine how standard services are configured in the default policy
3. Learn Policy Language: Dive deeper into SELinux policy language for complex custom policies
4. Implement Monitoring: Set up comprehensive SELinux monitoring and alerting
5. Stay Updated: Follow SELinux project updates and security advisories
Additional Resources
- SELinux Project Wiki: Comprehensive documentation and examples
- Red Hat SELinux Guide: Official documentation for RHEL environments
- SELinux Coloring Book: Visual guide to SELinux concepts
- Community Forums: Active communities for troubleshooting and best practices
By following the practices and techniques outlined in this guide, you'll be well-equipped to implement and maintain secure SELinux configurations that protect your Linux systems while allowing necessary functionality. Remember that SELinux configuration is an iterative process - start with basic configurations and gradually implement more sophisticated policies as your understanding and requirements grow.
The investment in properly configuring SELinux policies pays dividends in system security, helping protect against both external threats and internal security breaches. With the knowledge gained from this comprehensive guide, you're ready to implement robust SELinux security policies that meet your organization's specific requirements while maintaining system functionality and performance.