#027 · 2025-01-20✓ PASS
SELinux 安全管理
SELinux 安全上下文、布尔值、排错技巧及与 Nginx 等服务整合的实战指南。
SELinux(Security-Enhanced Linux)是 Linux 内核的强制访问控制(MAC)系统,提供比传统 DAC 更精细的安全策略。
一、SELinux 基础概念
三种运行模式
# 查看当前模式
getenforce
# 查看配置文件中的模式
cat /etc/selinux/config
| 模式 | 说明 |
|---|---|
Enforcing | 强制执行 SELinux 策略,拒绝违规访问并记录日志 |
Permissive | 不拒绝访问,但记录所有违规操作(排错用) |
Disabled | 完全禁用 SELinux |
模式切换
# 临时切换
setenforce 0 # Permissive
setenforce 1 # Enforcing
# 永久修改
vim /etc/selinux/config
# SELINUX=enforcing
# 注意:Disabled → Enforcing 需要重启
二、安全上下文(Context)
SELinux 使用安全上下文标记所有文件和进程:
system_u:object_r:httpd_sys_content_t:s0
└──┬──┘ └──┬───┘ └────────┬────────┘ └┬┘
用户 角色 类型 级别
查看安全上下文
# 查看文件上下文
ls -Z /var/www/html/index.html
# -rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 index.html
# 查看进程上下文
ps auxZ | grep nginx
# system_u:system_r:httpd_t:s0 nginx: master process
# 查看目录默认上下文
semanage fcontext -l | grep /var/www
三、常用操作命令
chcon — 修改文件上下文
# 临时修改(restorecon 会恢复)
chcon -t httpd_sys_content_t /path/to/file
chcon -R -t httpd_sys_content_t /var/www/custom/
# 参考已有目录设置
chcon -R --reference=/var/www/html /var/www/newapp
restorecon — 恢复默认上下文
# 恢复单个文件
restorecon -v /var/www/html/index.html
# 递归恢复整个目录
restorecon -Rv /var/www/
semanage — 永久修改默认上下文
# 设置目录默认上下文
semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
restorecon -Rv /web
# 修改端口上下文
semanage port -a -t http_port_t -p tcp 8080
# 查看已定义的端口
semanage port -l | grep http
四、SELinux 布尔值
布尔值用于快速启用/禁用特定安全策略:
# 查看所有布尔值
getsebool -a
# 查看特定服务的布尔值
getsebool -a | grep httpd
# 设置布尔值
setsebool httpd_can_network_connect on
setsebool -P httpd_enable_homedirs on # -P 永久生效
# 常用 Nginx/HTTP 布尔值
setsebool -P httpd_can_network_connect on
setsebool -P httpd_can_network_connect_db on
setsebool -P httpd_enable_cgi on
五、排错实战
日志分析
# SELinux 审计日志位置
tail -f /var/log/audit/audit.log | grep AVC
# 使用 sealert 分析
sealert -a /var/log/audit/audit.log
audit2allow
# 从日志生成策略模块
grep nginx /var/log/audit/audit.log | audit2allow -M nginx_custom
semodule -i nginx_custom.pp
# 查看建议但仅生成可读报告(不应用)
audit2allow -w -a
audit2why < /var/log/audit/audit.log
六、Nginx + SELinux 整合
Nginx 部署时常见的 SELinux 问题及解决方案:
# 1. 非标准目录
semanage fcontext -a -t httpd_sys_content_t "/opt/web(/.*)?"
restorecon -Rv /opt/web
# 2. 反向代理连接后端
setsebool -P httpd_can_network_connect on
# 3. 非标准端口
semanage port -a -t http_port_t -p tcp 8888
# 4. CGI/FastCGI
setsebool -P httpd_enable_cgi on
# 5. 文件上传目录
chcon -R -t httpd_sys_rw_content_t /var/www/uploads/
七、SELinux 状态检查清单
# 全面检查 SELinux 配置
sestatus
# 输出示例:
# SELinux status: enabled
# SELinuxfs mount: /sys/fs/selinux
# SELinux root directory: /etc/selinux
# Loaded policy name: targeted
# Current mode: enforcing
# Mode from config file: enforcing
八、最佳实践
- 永远不要禁用 SELinux — 使用 Permissive 模式排错
- 用 semanage 代替 chcon — 避免 restorecon 或 relabel 后丢失设置
- 关注 AVC 日志 —
/var/log/audit/audit.log - 善用 sealert — 自动给出修复建议
- SELinux + Firewalld 双重防护 — 纵深防御
- 测试环境验证 — 先在 Permissive 模式下测试,确认无误再开启 Enforcing