1. 确保SELinux处于Enforcing模式
SELinux的核心防护依赖Enforcing模式(强制模式),此时违反策略的访问会被直接阻止。需通过以下步骤确认并设置:
sestatus(输出应显示“Current mode: enforcing”);sudo setenforce 1(立即生效,重启失效);/etc/selinux/config文件,将SELINUX=的值改为enforcing,保存后重启系统。2. 为服务配置正确的SELinux上下文
SELinux通过安全上下文(Security Context)标识进程、文件和用户的权限,其中**类型(Type)**是关键(如httpd_t用于Apache、mysqld_t用于MySQL)。需确保服务进程和关联文件的上下文匹配:
ps auxZ | grep <服务名>(如ps auxZ | grep httpd,输出应包含httpd_t);ls -lZ /path/to/service/files(如ls -lZ /var/www/html,输出应包含httpd_sys_content_t);semanage fcontext添加持久化规则(如sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?"),再用restorecon -Rv /var/www/html恢复默认上下文。3. 遵循最小权限原则配置服务域
避免服务运行在unconfined_t(无约束域,权限过大),尽量使用专有域(如httpd_t、mysqld_t)。若需自定义权限,可通过以下方式细化:
setsebool调整布尔值(如允许Apache连接网络:sudo setsebool -P httpd_can_network_connect 1);/var/log/myapp.log): sepolgen --init;.te文件(定义规则,如allow my_process_t my_log_t:file read;);make -f /usr/share/selinux/devel/Makefile && sudo semodule -i my_process.pp。4. 分析并处理SELinux拒绝日志
SELinux的AVC(Access Vector Cache)日志记录了所有被阻止的访问尝试,是排查问题的关键。需定期分析并处理:
ausearch -m avc -ts today(或sudo ausearch -m avc -ts recent);ausearch -m avc -ts today | audit2why(输出会提示拒绝的原因及可能的解决方法);audit2allow生成策略模块(如grep nginx /var/log/audit/audit.log | audit2allow -M nginx),安装后即可允许该操作。5. 定期监控与维护SELinux策略
SELinux的防护效果依赖于持续的监控与优化:
sealert工具分析SELinux警报(如sealert -a /var/log/audit/audit.log),获取详细的修复建议;sudo apt update && sudo apt upgrade selinux-*(保持策略与系统版本同步)。6. 辅助安全措施(强化整体防护)
SELinux需与其他安全措施配合,才能最大化防护效果:
sudo apt autoremove),关闭未使用的服务(如sudo systemctl stop <服务名>),减少攻击面;Port 2222)、禁用root登录(PermitRootLogin no)、使用密钥认证(PasswordAuthentication no);ufw(Uncomplicated Firewall)限制入站流量(如sudo ufw allow 22/tcp),仅开放必要端口。