首先需明确SELinux是否启用及当前运行模式,这是诊断的基础。常用命令:
sestatus:显示SELinux状态(enabled/disabled)、运行模式(enforcing/permissive/targeted)、策略类型等详细信息。getenforce:快速查看当前运行模式(enforcing/permissive/disable)。SELinux的错误信息主要记录在**/var/log/audit/audit.log**(审计日志)中,需通过以下命令筛选AVC(Access Vector Cache)拒绝记录(最常见的SELinux错误类型):
sudo tail -f /var/log/audit/audit.log | grep avc:实时查看最新的AVC拒绝记录。sudo ausearch -m avc -ts recent:搜索指定时间范围(recent)内的AVC拒绝事件,输出包含违规进程、操作类型(如read/write)、上下文等关键信息。sudo grep -i "denied" /var/log/audit/audit.log(Ubuntu系统):过滤日志中的“denied”关键字,定位SELinux拒绝事件。原始日志信息较晦涩,需通过工具解析以明确问题根源:
ausearch + audit2allow:用ausearch提取AVC拒绝事件,通过audit2allow生成允许规则(示例:sudo ausearch -m avc -ts today | audit2allow)。但需注意,audit2allow会强制允许错误,可能降低系统安全性,非必要不推荐直接使用。sealert(推荐):安装setroubleshoot工具(sudo yum install setroubleshoot或sudo apt-get install setroubleshoot),通过sealert -a /var/log/audit/audit.log生成可视化报告,包含违规原因、受影响进程、推荐的解决方案(如修改布尔值、调整文件上下文),更直观且安全。SELinux通过安全上下文(security context)控制对象(文件、进程、端口)的访问权限,上下文错误是常见问题根源。常用命令:
ls -Z:查看文件/目录的SELinux上下文(示例:drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 /var/www/html),重点关注类型(type)(如httpd_sys_content_t)。id -Z:查看当前用户的SELinux上下文(示例:unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023)。restorecon:恢复文件/目录的默认上下文(示例:sudo restorecon -R /path/to/directory),适用于上下文被误修改的情况。根据日志和上下文检查结果,选择合适的策略调整方式:
getsebool -a | grep service_name查看相关布尔值,用setsebool -P boolean_name=1永久启用(示例:sudo setsebool -P httpd_can_network_connect=1允许Apache访问网络)。sudo semanage port -a -t http_port_t -p tcp 8080将8080端口添加到http_port_t类型)。audit2allow生成自定义策略(示例:sudo ausearch -m avc -ts today | audit2allow -M mymodule生成模块,sudo semodule -i mymodule.pp加载模块),但需评估安全性。**setroubleshoot**是SELinux问题诊断的图形化工具,可简化日志分析过程:
sealert命令查看告警,点击“Report”生成详细报告,包含问题描述、可能的原因及推荐的解决方案(如“修改httpd_sys_content_t上下文”),适合新手使用。若问题严重影响系统使用,可临时禁用SELinux以确认是否为SELinux导致:
sudo setenforce 0(从enforcing切换到permissive,仅记录违规不阻止操作)。/etc/selinux/config文件,将SELINUX=enforcing改为SELINUX=disabled,重启系统生效。