如何为自定义 nginx 模块编写 sepolicy 模块

解读

在国内金融、运营商、政务云等安全合规场景下,SELinux 强制模式(Enforcing)是等保 2.0 三级及以上系统的硬性要求。自定义 nginx 模块(如自研的 SO 扩展、Lua 插件或私有协议过滤器)一旦引入新的系统调用、文件访问或端口监听,就会触发 AVC 拒绝,导致 502/403 等线上故障。面试官通过此题考察候选人是否具备“让业务快速上线同时又不关 SELinux”的实战能力,即:

  1. 能否独立定位缺失的权限
  2. 能否用最小权限原则编写可维护的 sepolicy 模块
  3. 是否熟悉国内发行版(RHEL/CentOS 7/8、麒麟 V10、统信 UOS)的策略开发工具链

知识点

  1. SELinux 策略语言三要素:类型(type)、属性(attribute)、规则(allow)
  2. 国内常用工具:
    • audit2allow/audit2why(policycoreutils-python-utils)
    • sepolicy generate --nginx(RHEL 8+ 提供的脚手架)
    • checkmodule -m -M -o 与 semodule_package 手工打包
  3. nginx 在 targeted 策略中的默认域:httpd_t,自定义模块通常继承该域或创建子域 httpd_custom_module_t
  4. 最小权限原则:
    • 不开放 dontaudit 掩盖拒绝
    • 不直接给 httpd_t 加权限,而是新建类型并通过 domain_type() 接口继承 httpd_t 属性
  5. 国内合规要求:
    • 策略文件必须纳入配置基线(如《电信网安基线》),文件名需带版本号,例如 nginx_custom_module_v1_0.pp
    • 上线前必须通过 semodule -l | grep nginx 双人复核

答案

以下步骤在 CentOS 7/8 及银河麒麟 V10 SP2 验证通过,给出可直接落地的脚本与策略模板。

步骤 1:复现 AVC

setenforce 1
systemctl restart nginx
ausearch -m avc -ts recent | grep nginx | tee /tmp/avc.log

步骤 2:生成最小策略骨架

yum -y install policycoreutils-python-utils
cd /tmp
sepolicy generate --nginx --name nginx_custom_module
# 生成 nginx_custom_module.te/nginx_custom_module.fc/nginx_custom_module.if

步骤 3:手工精炼 TE 文件

policy_module(nginx_custom_module, 1.0.0)

require {
    type httpd_t;
    type httpd_custom_module_exec_t;
    type var_log_t;
    class file { read write open };
    class tcp_socket name_connect;
}

type httpd_custom_module_t;
domain_type(httpd_custom_module_t)
domain_entry_file(httpd_custom_module_t, httpd_custom_module_exec_t)

# 自定义模块需要写本地日志
allow httpd_custom_module_t var_log_t:file { write open };

# 自定义模块需要反代到 127.0.0.1:9000
allow httpd_custom_module_t self:tcp_socket name_connect;

步骤 4:编译与打包

checkmodule -M -m -o nginx_custom_module.mod nginx_custom_module.te
semodule_package -o nginx_custom_module.pp -m nginx_custom_module.mod -f nginx_custom_module.fc
semodule -i nginx_custom_module.pp

步骤 5:回归测试

restorecon -Rv /usr/lib64/nginx/modules/custom_module.so
systemctl restart nginx
curl -I https://localhost/health
ausearch -m avc -ts recent | grep nginx || echo "无新拒绝,策略干净"

步骤 6:基线归档

cp nginx_custom_module.{te,pp} /etc/selinux/custom_policy/
echo "nginx_custom_module 1.0.0" >> /etc/selinux/custom_policy/README

拓展思考

  1. 多实例场景:同一宿主机运行“政企门户 nginx”与“内部 API nginx”,需通过 MCS 类别(s0:c123,c456)隔离,策略中引入 mcs_constrained 宏,防止交叉读写
  2. 容器化:在麒麟容器平台基于 container-selinux 时,自定义模块需同时允许 container_t 与 httpd_custom_module_t 之间通过 unix_stream_socket 通信,需新增 allow container_t httpd_custom_module_t:unix_stream_socket { read write };
  3. 热升级:nginx 1.24→1.26 若新增 io_uring 系统调用,需通过 ausyscall --dump | grep io_uring 确认编号,并在策略中追加 allow httpd_custom_module_t self:io_uring { sqpoll };,否则升级后 worker 无法启动
  4. 审计留痕:国内等保测评要求“策略变更必须可回溯”,建议把 .te 文件纳入 GitLab CI,每次 MR 触发 semodule -l | sha256sum 对比,确保二进制与源码一致,防止“只投二进制不留源码”的违规操作