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
),便于恢復。