温馨提示×

ubuntu selinux策略如何写

小樊
44
2026-10-21 21:37:26
栏目: 智能运维

在 Ubuntu 上,SELinux 并不像在 RHEL/CentOS 上那样是默认的(Ubuntu 默认是 AppArmor)。如果你确实要在 Ubuntu 上使用 SELinux,需要:

  1. 安装 SELinux 相关包
  2. 关闭 AppArmor(或共存,但不推荐)
  3. 编写 / 加载 SELinux 策略

下面我分 基础说明 → 策略写法 → 示例 → 调试 四部分讲。


一、Ubuntu 启用 SELinux(简要)

sudo apt update
sudo apt install selinux-basics selinux-policy-default auditd

启用 SELinux:

sudo selinux-activate
sudo reboot

查看状态:

sestatus

如果看到 SELinux status: enabled 就成功了


二、SELinux 策略的两种写法

1️⃣ 使用 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

2️⃣ 手写 SELinux 策略(.te 文件)

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 读自定义目录)

场景

  • nginx 运行在 nginx_t
  • 网站目录:/data/www

1️⃣ 定义类型

policy_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 };

2️⃣ 编译并加载

checkmodule -M -m -o myweb.mod myweb.te
semodule_package -o myweb.pp -m myweb.mod
sudo semodule -i myweb.pp

3️⃣ 打标签

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 };

常见 class

  • file
  • dir
  • process
  • tcp_socket
  • unix_stream_socket

常见权限

  • read
  • write
  • open
  • execute
  • connectto
  • bind

五、调试 SELinux

查看拒绝日志:

sudo ausearch -m avc -ts recent

临时放行(不推荐长期使用):

sudo setenforce 0   # Permissive

六、Ubuntu 上的建议

✅ 如果你只是想限制程序行为,Ubuntu 官方更推荐 AppArmor
✅ SELinux 在 Ubuntu 上可用,但生态不如 RHEL 完善
✅ 生产环境若必须用 SELinux,建议参考 RHEL 文档


如果你愿意,可以告诉我:

  • 你是要 限制某个程序
  • 还是 写自定义服务策略
  • 或是 排查某个 AVC 拒绝

我可以直接帮你写一份可用的 .te 策略。

0 踩