SELinux(Security-Enhanced Linux)是美国国家安全局(NSA)开发的一种强制访问控制(MAC)安全机制,集成在Linux内核中。它通过为系统资源(文件、进程、设备等)提供细粒度的访问控制,显著增强了Linux系统的安全性。
SELinux为所有系统对象(文件、进程、端口等)分配安全上下文,包含: - 用户(user):SELinux用户标识 - 角色(role):连接用户和类型的桥梁 - 类型(type):决定访问权限的主要属性 - 级别(level):MLS/MCS多级安全使用的敏感度级别
SELinux策略定义了主体(通常是进程)如何访问客体(文件、套接字等),基本格式:
allow source_type target_type : class permission_set;
# 查看当前状态
getenforce
# 临时切换模式
setenforce 0 # Permissive
setenforce 1 # Enforcing
# 永久修改(需重启)
vim /etc/selinux/config
# 查看文件上下文
ls -Z /etc/passwd
# 查看进程上下文
ps -Z
# 修改文件上下文
chcon -t httpd_sys_content_t /var/www/html/index.html
# 恢复默认上下文
restorecon -v /var/www/html/index.html
# 查看布尔值
getsebool -a
# 设置布尔值
setsebool -P httpd_can_network_connect on
# 生成自定义策略模块
audit2allow -a -M mypolicy
semodule -i mypolicy.pp
# 查看SELinux拒绝日志
grep "AVC" /var/log/audit/audit.log
# 使用sealert分析
sealert -a /var/log/audit/audit.log
服务无法启动:
audit2allow
生成新策略或调整文件上下文文件访问被拒绝:
# 1. 确认是否是SELinux问题
setenforce 0
# 如果能访问,则是SELinux问题
# 2. 查看正确上下文
ls -Z /path/to/similar/file
# 3. 应用正确上下文
chcon -R --reference=/path/to/similar/file /path/to/problem/file
网络服务问题:
getsebool -a | grep service_name
semanage port -l
restorecon
而非chcon
进行永久性更改sealert
工具帮助诊断问题checkpolicy
编译自定义策略SELinux虽然增加了系统管理的复杂性,但为Linux系统提供了强大的安全保护层。通过理解其原理和掌握基本操作,可以有效地在安全性和可用性之间取得平衡。