linux-sre-handbook

02-SELinux与AppArmor

MAC vs DAC

SELinux (RHEL 系默认)

三种模式

getenforce                    # 查看当前模式
setenforce 0                  # 切换为 Permissive (不阻断, 只记录)
setenforce 1                  # 切换为 Enforcing

# /etc/selinux/config
SELINUX=enforcing
模式 行为
Enforcing 强制执行策略,拒绝违规操作
Permissive 仅记录违规,不拒绝 (调试用)
Disabled 完全关闭

核心概念

常用命令

# 查看上下文
ls -Z /var/www/html/
ps -eZ | grep httpd

# 修改文件上下文
chcon -t httpd_sys_content_t /var/www/html/index.html
restorecon -v /var/www/html/index.html  # 恢复默认

# 布尔值开关
getsebool -a | grep httpd
setsebool -P httpd_can_network_connect on  # 持久化

# 审计日志排查
ausearch -m avc -ts recent
# 或
journalctl -t setroubleshoot

# 生成策略模块
audit2allow -a -M mypolicy
semodule -i mypolicy.pp

AppArmor (Ubuntu/Debian 默认)

# 查看状态
aa-status

# 模式切换
aa-complain /path/to/profile    # 仅记录 (类似 permissive)
aa-enforce /path/to/profile     # 强制执行

# 生成 profile
aa-autodep /usr/sbin/nginx
aa-genprof /usr/sbin/nginx      # 交互式生成

SRE 实践建议

延伸阅读