1. 安装SELinux及相关工具
Ubuntu默认未包含SELinux,需先通过以下命令安装核心组件及工具:
sudo apt update
sudo apt install selinux-basics selinux-policy-default auditd setools selinux-policy-dev
这些工具用于激活SELinux、管理策略及查看日志。
2. 激活SELinux
安装完成后,通过selinux-activate命令激活SELinux,系统会在启动时加载security=selinux内核参数:
sudo selinux-activate
激活后需重启系统使内核参数生效。
3. 配置SELinux模式(关键步骤)
SELinux有三种运行模式,需通过/etc/selinux/config文件永久设置:
编辑配置文件:
sudo nano /etc/selinux/config
修改以下行(以Enforcing为例):
SELINUX=enforcing
SELINUXTYPE=default # 策略类型,默认即可
保存后重启系统:
sudo reboot
临时切换模式(无需重启):
sudo setenforce 0;sudo setenforce 1。4. 验证SELinux状态
通过以下命令确认SELinux是否启用及运行模式:
sestatus
getenforce
若输出为Enforcing,则表示配置成功。
5. 管理SELinux策略(确保配置正确)
ls -Z(文件)、ps -Z(进程)查看安全上下文,确保其符合预期(如Web文件应为httpd_sys_content_t);sudo chcon -t httpd_sys_content_t /path/to/file;semanage fcontext添加规则,再用restorecon恢复:sudo semanage fcontext -a -t httpd_sys_content_t "/path/to/dir(/.*)?"
sudo restorecon -RvvF /path/to/dir
setsebool修改布尔值(永久生效需加-P):sudo setsebool -P httpd_enable_homedirs 1 # 允许Apache访问用户主目录
AVC拒绝(访问被阻止),通过日志分析生成自定义策略:grep avc /var/log/audit/audit.log | audit2allow -M mypolicy # 生成策略模块
sudo semodule -i mypolicy.pp # 加载模块
```。
6. 监控与调试SELinux
/var/log/audit/audit.log,使用以下工具分析:sudo ausearch -m avc -ts recent # 查找最近的AVC拒绝事件
sudo aureport -m avc # 生成AVC报告
ausearch定位具体拒绝规则,再用audit2why分析原因。注意事项
Enforcing模式,避免安全漏洞;/etc/selinux/config及重要数据;sudo systemctl disable apparmor);