SELinux权限设置指南
SELinux(Security-Enhanced Linux)通过**强制访问控制(MAC)**机制,以“安全上下文”为核心,实现对进程、文件等资源的细粒度权限管理。以下是SELinux权限设置的关键步骤及方法:
在调整权限前,需先确认SELinux是否启用及当前模式:
sestatus
输出示例:
SELinux status: enabled
Current mode: enforcing
Mode from config file: enforcing
enabled表示启用,disabled表示禁用;enforcing(强制模式,违反策略的操作会被阻止并记录)、permissive(宽容模式,仅记录违规行为,不阻止)、disabled(完全禁用)。sudo setenforce 0 # 设为Permissive模式(记录违规但不阻止)
sudo setenforce 1 # 设为Enforcing模式(强制执行策略)
编辑SELinux配置文件/etc/selinux/config,修改以下行:
SELINUX=enforcing # 可选:enforcing/permissive/disabled
保存后重启系统使更改生效。
SELinux通过安全上下文(格式:用户:角色:类型:级别,如unconfined_u:object_r:httpd_sys_content_t:s0)控制访问权限,其中**类型(Type)**是最核心的属性。
ls -Z /path/to/file_or_directory # 查看文件/目录的上下文
ls -Zd /path/to/directory # 查看目录的上下文(包含子项)
使用chcon命令修改单个文件/目录的上下文:
sudo chcon -t target_type /path/to/file_or_directory
# 示例:将/var/www/html/index.html设为httpd_sys_content_t类型(Web服务器文件类型)
sudo chcon -t httpd_sys_content_t /var/www/html/index.html
-t:指定目标类型(如httpd_sys_content_t、ssh_home_t等);-R:递归修改目录及其子项(如chcon -R -t target_type /path/to/dir)。使用semanage fcontext添加永久规则,再用restorecon应用:
# 安装policycoreutils-python(若未安装)
sudo yum install policycoreutils-python # CentOS/RHEL 7及以下
sudo dnf install policycoreutils-python-utils # CentOS/RHEL 8及以上
# 添加永久上下文规则(支持通配符)
sudo semanage fcontext -a -t target_type "/path/to/file_or_directory(/.*)?"
# 示例:将/var/www/html目录及其所有子文件设为httpd_sys_content_t类型
sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?"
# 应用新的上下文规则
sudo restorecon -Rv /path/to/file_or_directory
# 示例:恢复/var/www/html目录的上下文
sudo restorecon -Rv /var/www/html
-a:添加新规则;-d:删除规则(如semanage fcontext -d "/path/to/file_or_directory(/.*)?")。SELinux布尔值是策略中的“开关”,用于快速启用/禁用特定功能(如允许Apache访问用户家目录)。常见布尔值可通过getsebool查看:
getsebool -a # 查看所有布尔值及其状态(on/off)
getsebool httpd_can_network_connect # 查看Apache是否能访问网络
getsebool ftp_home_dir # 查看FTP是否能访问用户家目录
sudo setsebool boolean_name on/off
# 示例:允许Apache访问网络
sudo setsebool httpd_can_network_connect on
sudo setsebool -P boolean_name on/off
# 示例:永久允许FTP访问用户家目录
sudo setsebool -P ftp_home_dir on
-P:使设置永久生效(保存到SELinux策略文件)。当遇到“权限拒绝”问题(如Web服务器无法访问文件),可按以下步骤排查:
sudo ausearch -m avc -ts recent # 查看最近的AVC(访问控制)拒绝事件
sudo journalctl | grep AVC # 通过journalctl过滤AVC日志
日志会显示拒绝的原因(如“type mismatch”类型不匹配、“avc: denied”操作被拒绝)。
若日志显示需要放行某些操作,可使用audit2allow自动生成策略模块:
sudo ausearch -c '程序名' --raw | audit2allow -M my_custom_policy
# 示例:针对httpd服务的拒绝事件生成策略
sudo ausearch -c 'httpd' --raw | audit2allow -M my_httpd_policy
# 加载生成的策略模块
sudo semodule -i my_custom_policy.pp
-M:生成策略模块(.te源文件和.pp二进制文件);-i:安装策略模块。/etc/selinux/config);通过以上步骤,可有效管理SELinux权限,平衡系统安全与功能需求。