SELinux管理文件权限的核心逻辑与操作指南
SELinux(Security-Enhanced Linux)通过强制访问控制(MAC)机制,以“安全上下文”为核心,实现对文件权限的细粒度管理。与传统Linux的“自主访问控制(DAC,如rwx权限)”不同,SELinux不仅检查文件属主、用户权限,还会验证进程类型与文件类型的匹配性,即使root用户也无法绕过SELinux策略访问未授权的文件。
安全上下文是SELinux为每个文件、进程分配的“身份标签”,格式为:用户:角色:类型:级别(级别可选)。其中:
httpd_sys_content_t表示Web内容文件,var_t表示系统变量文件)。system_u表示系统用户,object_r表示对象角色)。通过ls -Z命令可查看文件的SELinux上下文,例如:
ls -Z /var/www/html/index.html
# 输出示例:system_u:object_r:httpd_sys_content_t:s0
SELinux有三种运行模式,控制策略的强制执行程度:
/var/log/audit/audit.log)。通过getenforce命令查看当前模式,setenforce 0/1临时切换模式(0=Permissive,1=Enforcing)。永久修改需编辑/etc/selinux/config文件,设置SELINUX=enforcing/permissive/disabled。
使用ls -Z命令查看文件/目录的SELinux上下文,例如:
ls -Z /var/www/html
# 输出示例:system_u:object_r:httpd_sys_content_t:index.html
使用chcon命令临时更改文件的类型(重启或restorecon后会失效),语法:
chcon -t <目标类型> <文件路径>
# 示例:将/var/www/html/test.txt设置为httpd_sys_content_t类型
chcon -t httpd_sys_content_t /var/www/html/test.txt
若需永久生效,需使用semanage fcontext定义默认规则,再用restorecon应用:
# 1. 添加默认规则(如为/custom/web目录下的所有文件设置httpd_sys_content_t类型)
semanage fcontext -a -t httpd_sys_content_t "/custom/web(/.*)?"
# 2. 恢复目录及子文件的默认上下文
restorecon -Rv /custom/web
注:semanage需安装policycoreutils-python工具(yum install policycoreutils-python)。
restorecon恢复:mv /old/path/file.txt /new/path/
restorecon -v /new/path/file.txt
当进程无法访问文件时,SELinux会将违规信息记录到/var/log/audit/audit.log。使用ausearch过滤AVC(访问控制拒绝)日志:
ausearch -m avc -ts recent
# 示例输出:type=AVC msg=audit(1724987654.123:456): avc: denied { read } for pid=1234 comm="httpd" name="test.txt" dev="sda1" ino=789 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:var_t:s0 tclass=file
若日志显示“denied”错误,可通过audit2allow工具生成自定义策略模块,允许被拦截的操作:
# 1. 从日志提取规则并生成.te文件
audit2allow -a -M myrule
# 2. 编译并加载策略模块
semodule -i myrule.pp
注:自定义策略需谨慎使用,避免过度放宽权限。
/etc/selinux/config、/var/log/audit/audit.log)。