CentOS SELinux Context恢复方法
restorecon是SELinux内置工具,用于将文件/目录恢复至策略定义的默认context,是最常用的恢复方式。
操作步骤:
cp /etc/selinux/config /etc/selinux/config.backup(避免操作失误导致策略丢失)。cp /etc/selinux/targeted/policy/policy.31 /etc/selinux/config(targeted为CentOS默认策略类型,可根据实际情况替换)。setenforce 1(若处于Permissive模式,需切换至Enforcing模式以应用更改)。restorecon -Rv /path/to/target(如/var/www/html或根目录/,-R表示递归,-v显示详细过程)。若context被semanage fcontext修改(如新增了错误的规则),需通过以下步骤清理并恢复:
操作步骤:
semanage fcontext -l(筛选出非默认规则,如用户手动添加的/data/www相关规则)。/etc/selinux/targeted/contexts/files/file_contexts.local(自定义规则的存储文件),删除或注释掉不需要的规则(如/data/www(/.*)? user_u:object_r:httpd_sys_content_t:s0)。restorecon -Rv /path/to/target(针对修改过的路径重新应用默认context)。若需快速验证某文件/目录的context是否正确,可使用chcon手动调整,但此操作不会持久化(下次SELinux策略重载会恢复默认),仅用于测试:
操作步骤:
ls -Z /path/to/file(如unconfined_u:object_r:default_t:s0)。chcon -R system_u:object_r:default_t:s0 /path/to/file(-R递归,system_u为用户,object_r为角色,default_t为类型,s0为级别)。restorecon -Rv /path/to/file固化修改。若提前备份了SELinux context(如使用semanage fcontext -E -o导出),可通过备份文件快速恢复:
操作步骤:
semanage fcontext -F -l /path/to/fcontext_backup.txt(-F强制覆盖现有规则,-l从文件读取规则)。restorecon -Rv /path/to/target(确保规则生效)。sudo或切换至root用户)。Enforcing模式,部分操作可能被拦截,可临时切换至Permissive模式(setenforce 0)进行测试,完成后切回Enforcing(setenforce 1)。