1. 查看SELinux状态与上下文信息
在配置context前,需先确认SELinux的运行状态及现有上下文。使用sestatus命令可查看SELinux是否启用(Enforcing/Permissive/Disabled)及当前模式;ls -Z用于查看文件/目录的SELinux上下文(如system_u:object_r:httpd_sys_content_t:s0),ps -Z可查看进程的上下文信息。这些命令是定位context问题的基础。
2. 临时与永久修改文件/目录context
chcon命令快速变更上下文(重启或restorecon后会失效)。例如,将/var/www/html/index.html设为httpd_sys_content_t类型:chcon -t httpd_sys_content_t /var/www/html/index.html;若需递归修改目录,添加-R参数:chcon -R -t httpd_sys_content_t /var/www/html。semanage fcontext添加自定义context规则(需安装policycoreutils-python包),再使用restorecon应用。例如,永久修改/var/www/html及其子内容的context为httpd_sys_content_t:semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?",随后执行restorecon -Rv /var/www/html使更改生效。3. 使用semanage管理context规则
semanage是SELinux context管理的核心工具,支持添加、删除、列出自定义规则。常用操作包括:
semanage fcontext -l;semanage fcontext -d "/path/to/file(/.*)?";chcon的临时性。4. 利用audit2allow生成自定义策略
当SELinux拒绝访问(如avc: denied日志)时,可通过audit2allow工具分析日志并生成自定义策略模块。步骤如下:
grep "denied" /var/log/audit/audit.log;grep "denied" /var/log/audit/audit.log | audit2allow -M my_custom_policy;semodule -i my_custom_policy.pp。5. 调整SELinux布尔值优化context行为
SELinux布尔值(Boolean)用于控制特定服务的context行为(如是否允许HTTP写入用户家目录)。使用setsebool命令修改布尔值,-P参数表示永久生效。例如:
setsebool -P httpd_enable_homedirs 1;setsebool -P allow_ftpd_anon_write 1。6. 监控与调试SELinux context问题
使用ausearch和aureport工具可监控SELinux事件,快速定位context问题:
ausearch -m avc -ts recent;aureport -m avc。7. 备份与恢复SELinux配置
修改SELinux context或策略前,务必备份现有配置,避免误操作导致系统无法启动。常用备份命令:
cp -R /etc/selinux /etc/selinux.bak;cp /etc/selinux/targeted/contexts/files/file_contexts /etc/selinux/targeted/contexts/files/file_contexts.bak。