在 Ubuntu 上,SELinux 并不像在 RHEL/CentOS 上那样是默认的(Ubuntu 默认是 AppArmor)。如果你确实要在 Ubuntu 上使用 SELinux,需要:
下面我分 基础说明 → 策略写法 → 示例 → 调试 四部分讲。
sudo apt update
sudo apt install selinux-basics selinux-policy-default auditd
启用 SELinux:
sudo selinux-activate
sudo reboot
查看状态:
sestatus
如果看到
SELinux status: enabled就成功了
audit2allow(最简单,推荐新手)适合:已有拒绝日志,生成策略
sudo ausearch -m avc -ts recent
sudo ausearch -m avc -ts recent | audit2allow -m mypolicy
生成 .te 文件:
sudo ausearch -m avc -ts recent | audit2allow -M mypolicy
加载策略:
sudo semodule -i mypolicy.pp
SELinux 策略文件结构:
module myapp 1.0;
require {
type unconfined_t;
type etc_t;
class file { read open };
}
allow unconfined_t etc_t:file { read open };
nginx_t/data/wwwpolicy_module(myweb, 1.0)
require {
type nginx_t;
type usr_t;
class dir { read search };
class file { read open };
}
# 允许 nginx 访问 /data/www
type myweb_content_t;
files_type(myweb_content_t)
allow nginx_t myweb_content_t:dir { read search };
allow nginx_t myweb_content_t:file { read open };
checkmodule -M -m -o myweb.mod myweb.te
semodule_package -o myweb.pp -m myweb.mod
sudo semodule -i myweb.pp
sudo semanage fcontext -a -t myweb_content_t "/data/www(/.*)?"
sudo restorecon -Rv /data/www
type mytype_t;
allow source_t target_t:class { permissions };
filedirprocesstcp_socketunix_stream_socketreadwriteopenexecuteconnecttobind查看拒绝日志:
sudo ausearch -m avc -ts recent
临时放行(不推荐长期使用):
sudo setenforce 0 # Permissive
✅ 如果你只是想限制程序行为,Ubuntu 官方更推荐 AppArmor
✅ SELinux 在 Ubuntu 上可用,但生态不如 RHEL 完善
✅ 生产环境若必须用 SELinux,建议参考 RHEL 文档
如果你愿意,可以告诉我:
我可以直接帮你写一份可用的 .te 策略。