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
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(编译后的模块)。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问题
/var/log/audit/audit.log中,可使用以下命令过滤AVC(访问控制)拒绝:sudo ausearch -m avc -ts recent
audit2why工具解释日志中的拒绝事件,指导策略调整:sudo ausearch -m avc -ts recent | audit2why
输出会提示拒绝的具体原因(如缺少allow规则)及建议的修复命令。注意事项
/etc/selinux/config),便于恢复。