How to manage SELinux contexts → semanage fcontext -a -t httpd_sys_content_t "/srv/www(/.*)?"; restorecon -Rv /srv/www

How to Manage SELinux Contexts: Complete Guide to semanage fcontext and restorecon Table of Contents 1. [Introduction](#introduction) 2. [Prerequisites](#prerequisites) 3. [Understanding SELinux Contexts](#understanding-selinux-contexts) 4. [The semanage fcontext Command](#the-semanage-fcontext-command) 5. [The restorecon Command](#the-restorecon-command) 6. [Step-by-Step Implementation](#step-by-step-implementation) 7. [Practical Examples](#practical-examples) 8. [Common Use Cases](#common-use-cases) 9. [Troubleshooting](#troubleshooting) 10. [Best Practices](#best-practices) 11. [Advanced Techniques](#advanced-techniques) 12. [Conclusion](#conclusion) Introduction Security-Enhanced Linux (SELinux) is a mandatory access control security mechanism that provides fine-grained access control over system resources. One of the most critical aspects of SELinux administration is properly managing file contexts, especially when setting up web servers or moving content to non-standard directories. This comprehensive guide will teach you how to effectively use the `semanage fcontext` and `restorecon` commands to manage SELinux contexts, with a specific focus on configuring web content directories. You'll learn not only how to execute these commands but also understand the underlying concepts, troubleshoot common issues, and implement best practices for SELinux context management. By the end of this article, you'll be able to confidently manage SELinux contexts for web directories, understand the relationship between policy contexts and file system labels, and troubleshoot SELinux-related access issues in your environment. Prerequisites Before diving into SELinux context management, ensure you have the following: System Requirements - A Linux system with SELinux enabled (RHEL, CentOS, Fedora, or similar) - Root or sudo privileges - SELinux in enforcing or permissive mode - Basic understanding of Linux file permissions Required Packages Install the necessary SELinux management tools: ```bash For RHEL/CentOS/Fedora sudo dnf install policycoreutils-python-utils selinux-policy-targeted For older systems sudo yum install policycoreutils-python selinux-policy-targeted ``` Verification Commands Verify your SELinux status: ```bash Check SELinux status sestatus Verify SELinux mode getenforce Check if semanage is available which semanage ``` Understanding SELinux Contexts What Are SELinux Contexts? SELinux contexts are security labels assigned to files, processes, and other system objects. These contexts determine what actions are allowed under the SELinux security policy. Every file and directory in an SELinux-enabled system has a context consisting of four parts: ``` user:role:type:level ``` - User: SELinux user identity - Role: SELinux role - Type: The most important part for file contexts - Level: Multi-Level Security (MLS) level Viewing Current Contexts You can view SELinux contexts using various commands: ```bash View context of files and directories ls -Z /var/www/html View context of a specific file stat -c %C /var/www/html/index.html View context of current process ps -Z ``` Context Types for Web Content Common SELinux types for web content include: - `httpd_sys_content_t`: Standard web content - `httpd_sys_rw_content_t`: Read-write web content - `httpd_sys_script_exec_t`: Executable web scripts - `httpd_config_t`: Web server configuration files The semanage fcontext Command Overview The `semanage fcontext` command manages the SELinux file context policy. It modifies the file context database that determines what contexts should be applied to files and directories. This command doesn't immediately change file contexts but defines the policy for what contexts should be applied. Basic Syntax ```bash semanage fcontext [OPTIONS] [COMMAND] [ARGUMENTS] ``` Common Options - `-a`: Add a new file context rule - `-d`: Delete a file context rule - `-m`: Modify an existing file context rule - `-l`: List current file context rules - `-t`: Specify the SELinux type - `-s`: Specify the SELinux user - `-r`: Specify the SELinux role Understanding the Example Command Let's break down the example command: ```bash semanage fcontext -a -t httpd_sys_content_t "/srv/www(/.*)?"; ``` - `semanage fcontext`: The base command for managing file contexts - `-a`: Add a new context rule - `-t httpd_sys_content_t`: Set the type to `httpd_sys_content_t` - `"/srv/www(/.*)?"`: Regular expression pattern matching `/srv/www` and all subdirectories The regular expression `(/.*)?` means: - `/`: Literal forward slash - `.`: Any character (.) zero or more times () - `?`: The entire group `(/.*)?` is optional This pattern matches `/srv/www` exactly and `/srv/www/` followed by any path. The restorecon Command Overview The `restorecon` command applies the file context policy defined by `semanage fcontext` to actual files and directories. While `semanage fcontext` defines the policy, `restorecon` enforces it on the file system. Basic Syntax ```bash restorecon [OPTIONS] [FILE/DIRECTORY] ``` Common Options - `-R`: Recursive operation - `-v`: Verbose output - `-n`: Show what would be done without making changes - `-F`: Force reset of context to match file_context Understanding the Example Command ```bash restorecon -Rv /srv/www ``` - `restorecon`: The command to restore file contexts - `-R`: Apply recursively to all subdirectories and files - `-v`: Verbose output showing what's being changed - `/srv/www`: Target directory Step-by-Step Implementation Step 1: Assess Current Context Before making changes, examine the current context of your target directory: ```bash Check if directory exists ls -la /srv/ View current context if directory exists ls -Z /srv/www 2>/dev/null || echo "Directory does not exist" Check what context should be applied matchpathcon /srv/www ``` Step 2: Create the Directory Structure If the directory doesn't exist, create it: ```bash Create the directory structure sudo mkdir -p /srv/www Create some sample content sudo mkdir -p /srv/www/html sudo echo "

Test Page

" > /srv/www/html/index.html ``` Step 3: Add the File Context Policy Add the new file context rule to the SELinux policy: ```bash Add the context rule sudo semanage fcontext -a -t httpd_sys_content_t "/srv/www(/.*)?" Verify the rule was added sudo semanage fcontext -l | grep "/srv/www" ``` Expected output: ``` /srv/www(/.*)? all files system_u:object_r:httpd_sys_content_t:s0 ``` Step 4: Apply the Context Apply the newly defined context to the actual files: ```bash Apply context recursively with verbose output sudo restorecon -Rv /srv/www ``` Expected output: ``` Relabeled /srv/www from unconfined_u:object_r:var_t:s0 to system_u:object_r:httpd_sys_content_t:s0 Relabeled /srv/www/html from unconfined_u:object_r:var_t:s0 to system_u:object_r:httpd_sys_content_t:s0 Relabeled /srv/www/html/index.html from unconfined_u:object_r:var_t:s0 to system_u:object_r:httpd_sys_content_t:s0 ``` Step 5: Verify the Changes Confirm that the contexts have been applied correctly: ```bash Check the new contexts ls -Z /srv/www/ ls -Z /srv/www/html/ Verify with matchpathcon matchpathcon /srv/www/html/index.html ``` Practical Examples Example 1: Setting Up Multiple Web Directories Setting up contexts for multiple virtual hosts: ```bash Add contexts for multiple sites sudo semanage fcontext -a -t httpd_sys_content_t "/srv/site1(/.*)?" sudo semanage fcontext -a -t httpd_sys_content_t "/srv/site2(/.*)?" sudo semanage fcontext -a -t httpd_sys_content_t "/srv/site3(/.*)?" Create directories sudo mkdir -p /srv/{site1,site2,site3}/html Apply contexts sudo restorecon -Rv /srv/site1 /srv/site2 /srv/site3 ``` Example 2: Read-Write Web Content For directories that need write access (like upload directories): ```bash Add read-write context sudo semanage fcontext -a -t httpd_sys_rw_content_t "/srv/www/uploads(/.*)?" Create directory sudo mkdir -p /srv/www/uploads Apply context sudo restorecon -Rv /srv/www/uploads Set appropriate permissions sudo chmod 755 /srv/www/uploads sudo chown apache:apache /srv/www/uploads ``` Example 3: CGI Script Directory For executable web content: ```bash Add executable context sudo semanage fcontext -a -t httpd_sys_script_exec_t "/srv/www/cgi-bin(/.*)?" Create directory sudo mkdir -p /srv/www/cgi-bin Apply context sudo restorecon -Rv /srv/www/cgi-bin Make scripts executable sudo chmod 755 /srv/www/cgi-bin ``` Example 4: Temporary Context Changes Sometimes you need to temporarily change contexts: ```bash Temporarily change context (not persistent) sudo chcon -t httpd_sys_content_t /tmp/web-content Make it persistent sudo semanage fcontext -a -t httpd_sys_content_t "/tmp/web-content" sudo restorecon /tmp/web-content ``` Common Use Cases Web Server Migration When migrating web content from standard locations to custom directories: ```bash Standard Apache directory ls -Z /var/www/html New custom location sudo mkdir -p /opt/myapp/web sudo cp -r /var/www/html/* /opt/myapp/web/ Set context policy sudo semanage fcontext -a -t httpd_sys_content_t "/opt/myapp/web(/.*)?" Apply context sudo restorecon -Rv /opt/myapp/web ``` Docker and Container Volumes Setting up SELinux contexts for container-mounted volumes: ```bash Set context for Docker volume sudo semanage fcontext -a -t httpd_sys_content_t "/docker/volumes/web(/.*)?" sudo mkdir -p /docker/volumes/web sudo restorecon -Rv /docker/volumes/web Alternative: Use container_file_t for general container access sudo semanage fcontext -a -t container_file_t "/docker/volumes/data(/.*)?" ``` Network File Systems When using NFS or other network file systems: ```bash For NFS-mounted web content sudo semanage fcontext -a -t httpd_sys_content_t "/mnt/nfs/web(/.*)?" sudo restorecon -Rv /mnt/nfs/web Enable NFS home directories (if needed) sudo setsebool -P httpd_use_nfs on ``` Troubleshooting Common Issues and Solutions Issue 1: Permission Denied Errors Symptom: Web server returns 403 Forbidden errors despite correct file permissions. Diagnosis: ```bash Check SELinux denials sudo ausearch -m avc -ts recent Check file contexts ls -Z /srv/www/ ``` Solution: ```bash Verify and fix contexts sudo restorecon -Rv /srv/www/ sudo systemctl restart httpd ``` Issue 2: Context Not Applied After restorecon Symptom: `restorecon` runs without errors but contexts don't change. Diagnosis: ```bash Check if policy exists sudo semanage fcontext -l | grep "/srv/www" Check for conflicting policies sudo semanage fcontext -l | grep "/srv" ``` Solution: ```bash Remove conflicting rules if found sudo semanage fcontext -d "/srv/www(/.*)?" Re-add the correct rule sudo semanage fcontext -a -t httpd_sys_content_t "/srv/www(/.*)?" sudo restorecon -Rv /srv/www/ ``` Issue 3: Regular Expression Pattern Issues Symptom: Context only applies to the directory, not subdirectories. Common Mistake: ```bash Wrong - missing regex pattern sudo semanage fcontext -a -t httpd_sys_content_t "/srv/www" ``` Correct Solution: ```bash Correct - includes subdirectories sudo semanage fcontext -a -t httpd_sys_content_t "/srv/www(/.*)?" ``` Issue 4: SELinux Booleans Symptom: Correct contexts but still getting denials. Diagnosis: ```bash Check relevant booleans getsebool -a | grep httpd ``` Solution: ```bash Enable necessary booleans sudo setsebool -P httpd_can_network_connect on sudo setsebool -P httpd_can_network_relay on sudo setsebool -P httpd_read_user_content on ``` Debugging Commands Useful Diagnostic Commands ```bash Check SELinux status sestatus -v View recent denials sudo ausearch -m avc -ts recent Check what context should be applied matchpathcon /srv/www/html/index.html Test context changes without applying restorecon -Rvn /srv/www/ View all file context rules sudo semanage fcontext -l | less Check for SELinux errors in logs sudo grep "SELinux" /var/log/messages ``` Creating Custom Policies For complex scenarios, you might need custom policies: ```bash Generate policy from denials sudo ausearch -m avc -ts recent | audit2allow -M mypolicy Review the generated policy cat mypolicy.te Install if appropriate sudo semodule -i mypolicy.pp ``` Best Practices Planning and Documentation 1. Document Changes: Keep records of all context modifications: ```bash Create a documentation file echo "$(date): Added httpd_sys_content_t context to /srv/www" >> /root/selinux-changes.log ``` 2. Test Before Production: Always test context changes in a development environment first. 3. Use Specific Patterns: Be as specific as possible with regex patterns to avoid unintended consequences. Security Considerations 1. Principle of Least Privilege: Use the most restrictive context that still allows functionality: ```bash Use httpd_sys_content_t for read-only content Use httpd_sys_rw_content_t only when write access is needed Use httpd_sys_script_exec_t only for executable content ``` 2. Regular Audits: Periodically review your file context policies: ```bash Review all custom contexts sudo semanage fcontext -l | grep -v "^/" ``` 3. Backup Policies: Before making significant changes: ```bash Export current policy sudo semanage fcontext -l > /root/fcontext-backup-$(date +%Y%m%d).txt ``` Automation and Scripting Create reusable scripts for common tasks: ```bash #!/bin/bash setup-web-context.sh WEBDIR="$1" CONTEXT_TYPE="${2:-httpd_sys_content_t}" if [ -z "$WEBDIR" ]; then echo "Usage: $0 [context_type]" exit 1 fi echo "Setting up SELinux context for $WEBDIR" sudo semanage fcontext -a -t "$CONTEXT_TYPE" "$WEBDIR(/.*)?" sudo restorecon -Rv "$WEBDIR" echo "Context setup complete" ``` Monitoring and Maintenance 1. Set up monitoring for SELinux denials: ```bash Add to crontab echo "0 root ausearch -m avc -ts hour-ago | mail -s 'SELinux Denials' admin@company.com" >> /etc/crontab ``` 2. Regular context verification: ```bash #!/bin/bash verify-contexts.sh for dir in /srv/www /opt/webapp /var/myapp; do if [ -d "$dir" ]; then echo "Checking $dir" restorecon -Rvn "$dir" | grep -v "not reset" fi done ``` Advanced Techniques Equivalency Rules Use file equivalency for similar directory structures: ```bash Make /srv/www equivalent to /var/www sudo semanage fcontext -a -e /var/www /srv/www sudo restorecon -Rv /srv/www ``` Custom File Types For specialized applications, create custom file types: ```bash This requires policy development skills Create custom .te file with new types Compile and install custom policy module ``` Integration with Configuration Management Ansible Example ```yaml --- - name: Set SELinux context for web directory selinux: target: "/srv/www(/.*)?" setype: httpd_sys_content_t state: present - name: Apply SELinux context command: restorecon -Rv /srv/www ``` Puppet Example ```puppet selinux::fcontext { '/srv/www(/.*)?': seltype => 'httpd_sys_content_t', } exec { 'restorecon-srv-www': command => '/sbin/restorecon -Rv /srv/www', require => Selinux::Fcontext['/srv/www(/.*)?'], } ``` Conclusion Managing SELinux contexts effectively is crucial for maintaining both security and functionality in modern Linux environments. The combination of `semanage fcontext` and `restorecon` provides a powerful toolkit for defining and applying security contexts to files and directories. Key Takeaways 1. Two-Step Process: Always remember that `semanage fcontext` defines the policy while `restorecon` applies it to the filesystem. 2. Regular Expressions Matter: Proper regex patterns ensure contexts are applied to all intended files and subdirectories. 3. Testing is Essential: Always test context changes in development environments before applying to production systems. 4. Documentation and Monitoring: Keep detailed records of changes and monitor for SELinux denials to catch issues early. 5. Security First: Use the most restrictive contexts that still allow required functionality. Next Steps After mastering basic context management, consider exploring: - Advanced SELinux policy development - Integration with configuration management systems - Custom SELinux modules for specialized applications - SELinux troubleshooting and performance optimization - Multi-Level Security (MLS) implementations Final Verification To ensure your implementation is working correctly, perform these final checks: ```bash Verify contexts are correct ls -Z /srv/www/ Test web server functionality sudo systemctl status httpd curl -I http://localhost/ Check for any SELinux denials sudo ausearch -m avc -ts recent Confirm policy persistence sudo semanage fcontext -l | grep "/srv/www" ``` By following this comprehensive guide, you now have the knowledge and tools necessary to effectively manage SELinux contexts in your environment. Remember that SELinux context management is an ongoing process that requires regular attention and maintenance to ensure optimal security and functionality.