CentOS SELinux Context 最佳实践
一 基础与运行模式
sestatus、getenforcesetenforce 0|1(0=Permissive,1=Enforcing)二 文件系统上下文管理
ls -Z 检查文件/目录上下文,确保与预期类型一致(如 Web 内容常为 httpd_sys_content_t)。semanage fcontext -a -t <type> "<path>(/.*)?"restorecon -Rv <path>(递归、显示过程)chcon -t <type> <path> 仅在紧急或测试时使用,系统重标记或策略更新后可能失效。semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?" && restorecon -Rv /var/www/htmlsemanage fcontext -a -t mysqld_db_t "/var/lib/mysql(/.*)?" && restorecon -Rv /var/lib/mysql三 排障与策略优化
ausearch -m avc -ts recentsealert -a /var/log/audit/audit.log(需安装 setroubleshoot 工具)ausearch -m avc -ts recent | audit2allow -M <name>semodule -i <name>.ppgetsebool <name>、setsebool -P <name> on|off(持久化加 -P)四 常见场景与端口管理
semanage port -a -t http_port_t -p tcp 12345semanage fcontext -a -t httpd_sys_content_t "/usr/share/nginx/html(/.*)?" && restorecon -Rv /usr/share/nginx/html五 运维与治理
cp -R /etc/selinux /etc/selinux.bak,以及自定义文件上下文(如 /etc/selinux/targeted/contexts/files/file_contexts.local)restorecon 覆盖范围与影响面semanage fcontext -l 定期检查,删除不再使用的规则(semanage fcontext -d -t <type> "<path>(/.*)?")yum/dnf update),定期审计 AVC 报表(aureport)