温馨提示×

Ubuntu下SELinux策略如何管理

小樊
89
2025-10-05 23:36:36
栏目: 智能运维

1. 安装SELinux及相关工具
Ubuntu默认未安装SELinux,需先通过以下命令安装核心组件与管理工具:

sudo apt update
sudo apt install selinux-basics selinux-policy-default selinux-utils policycoreutils-python-utils

安装完成后,SELinux会自动处于disabled状态。

2. 查看SELinux当前状态
使用sestatus命令可快速查看SELinux的启用状态、运行模式(enforcing/permissive/disabled)及策略类型(如targeted):

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
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Memory protection checking:     actual (secure)
Max kernel policy version:      31

此外,getenforce命令可快速返回当前模式(enforcing/permissive/disabled)。

3. 切换SELinux运行模式

  • 临时切换:使用setenforce命令可立即更改模式(无需重启),例如切换至permissive模式(仅记录违规不阻止):
    sudo setenforce 0
    
    切换至enforcing模式(强制执行策略):
    sudo setenforce 1
    
  • 永久切换:编辑/etc/selinux/config文件,修改SELINUX=参数为所需模式(enforcing/permissive/disabled),保存后重启系统生效:
    sudo nano /etc/selinux/config
    # 修改为:SELINUX=enforcing
    sudo reboot
    
    注意:从enforcing切换至disabled需重启两次(第一次进入permissive,第二次彻底禁用)。

4. 管理SELinux策略

  • 查看策略模块:使用semodule -l命令列出所有已加载的策略模块:
    semodule -l
    
  • 自定义策略模块
    a. 当SELinux拒绝访问时,使用ausearch收集拒绝日志(如Apache相关):
    sudo ausearch -c 'httpd' --raw | grep denied
    
    b. 通过audit2allow生成自定义策略模块(以httpd为例):
    sudo ausearch -c 'httpd' --raw | audit2allow -M my_httpd_policy
    
    此命令会生成两个文件:my_httpd_policy.te(策略源码)和my_httpd_policy.pp(编译后的模块)。
    c. 加载自定义模块:
    sudo semodule -i my_httpd_policy.pp
    
    d. 验证模块是否加载成功:
    semodule -l | grep my_httpd_policy
    
  • 管理文件上下文:使用semanage fcontext命令修改文件/目录的安全上下文(如允许Apache访问/var/www/custom目录):
    sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/custom(/.*)?"
    sudo restorecon -Rv /var/www/custom  # 递归恢复上下文
    
    查看现有文件上下文规则:
    sudo semanage fcontext -l
    ```。
    
    
    

5. 调试SELinux问题

  • 查看审计日志:SELinux拒绝事件会记录在/var/log/audit/audit.log中,可使用以下命令过滤AVC(访问控制)拒绝:
    sudo ausearch -m avc -ts recent
    
  • 分析拒绝原因:使用audit2why工具解释日志中的拒绝事件,指导策略调整:
    sudo ausearch -m avc -ts recent | audit2why
    
    输出会提示拒绝的具体原因(如缺少allow规则)及建议的修复命令。

注意事项

  • 自定义策略前,建议在permissive模式下测试,避免影响系统稳定性;
  • 禁用SELinux会降低系统安全性,仅在测试环境或不需要强制访问控制的场景下使用;
  • 修改配置文件前备份原始文件(如/etc/selinux/config),便于恢复。

0