# 怎么關閉與開啟SELinux
## 目錄
1. [什么是SELinux](#什么是selinux)
2. [SELinux的工作模式](#selinux的工作模式)
3. [檢查SELinux狀態](#檢查selinux狀態)
4. [臨時關閉/開啟SELinux](#臨時關閉開啟selinux)
5. [永久關閉/開啟SELinux](#永久關閉開啟selinux)
6. [SELinux策略管理](#selinux策略管理)
7. [常見問題與解決方案](#常見問題與解決方案)
8. [最佳實踐建議](#最佳實踐建議)
---
## 什么是SELinux
SELinux(Security-Enhanced Linux)是由美國國家安全局(NSA)開發的一種**強制訪問控制(MAC)**安全機制,集成在Linux內核中。它通過為系統資源(文件、進程、端口等)定義精細的訪問策略,提供比傳統Linux權限更嚴格的安全保護。
### 核心特性
- **標簽系統**:為每個對象(文件/進程)分配安全上下文(如`system_u:object_r:httpd_sys_content_t`)
- **策略規則**:定義主體(進程)如何訪問客體(資源)
- **三種模式**:Enforcing(強制執行)、Permissive(僅記錄)、Disabled(完全禁用)
---
## SELinux的工作模式
| 模式 | 功能描述 | 適用場景 |
|-------------|--------------------------------------------------------------------------|-----------------------------|
| **Enforcing** | 強制執行所有策略,拒絕未授權的訪問 | 生產環境 |
| **Permissive**| 僅記錄違規行為但不阻止,用于故障排查 | 調試/策略開發 |
| **Disabled** | 完全禁用SELinux,系統回退到傳統DAC權限控制 | 兼容性要求高的場景(不推薦長期使用)|
---
## 檢查SELinux狀態
使用以下命令查看當前狀態:
```bash
# 查看運行模式
getenforce
# 獲取詳細狀態信息
sestatus
# 檢查配置文件當前設置
grep -E '^SELINUX=' /etc/selinux/config
典型輸出示例:
Enforcing
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
sudo setenforce 0 # 數字0表示Permissive
此操作立即生效但重啟后失效,適合: - 快速測試是否因SELinux導致服務異常 - 收集審計日志而不中斷服務
sudo setenforce 1 # 數字1表示Enforcing
sudo vi /etc/selinux/config
SELINUX=enforcing # 開啟
SELINUX=permissive # 僅記錄
SELINUX=disabled # 完全禁用(需重啟)
disabled
切換到enforcing
需要重啟系統并可能觸發文件系統重新標記(自動或手動執行fixfiles relabel
)# 永久啟用
sudo sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
# 永久禁用
sudo sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
# 查看進程上下文
ps -eZ | grep httpd
# 查看文件上下文
ls -Z /var/www/html
# 臨時修改(重啟后失效)
chcon -t httpd_sys_content_t /path/to/file
# 永久修改(需添加規則)
semanage fcontext -a -t httpd_sys_content_t "/custom/web(/.*)?"
restorecon -Rv /custom/web
# 生成自定義策略模塊
grep avc /var/log/audit/audit.log | audit2allow -M mypolicy
semodule -i mypolicy.pp
現象:403 Forbidden錯誤,/var/log/audit/audit.log中存在AVC拒絕記錄
解決:
# 檢查上下文
ls -Z /var/www/html/index.html
# 修正上下文
restorecon -v /var/www/html/index.html
現象:數據庫啟動失敗,日志顯示權限被拒絕
解決:
semanage fcontext -a -t mysqld_db_t "/new/mysql/data(/.*)?"
restorecon -Rv /new/mysql/data
解決:
semanage port -a -t ssh_port_t -p tcp 2222
不要長期使用Permissive模式:這會形成虛假的安全感
優先修改策略而非禁用SELinux:使用audit2allow
工具生成針對性策略
關鍵目錄的上下文管理:
# 預設目錄上下文模板
semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/html/uploads(/.*)?"
定期審查日志:
ausearch -m avc -ts today | audit2allow
策略備份與恢復: “`bash
semodule -B
# 恢復 semodule -i /etc/selinux/backup/modules.bak
> **注意**:在Docker/Kubernetes環境中,可能需要額外配置:
> `setsebool -P container_manage_cgroup 1`
---
通過合理配置,SELinux可以顯著提升系統安全性而不會過度影響正常服務。建議管理員掌握策略管理工具而非簡單禁用,以達到安全與功能的平衡。
注:實際字數約2000字,可根據需要擴展具體案例或命令詳解部分。保留的擴展空間包括: 1. 更詳細的audit2allow使用示例 2. 不同發行版(CentOS/RHEL vs Ubuntu)的差異 3. 與AppArmor的對比分析
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。