You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建自定义SELinux策略以过滤特定bash脚本的auditd日志

如何创建自定义SELinux策略以过滤特定bash脚本的auditd日志

我来帮你搞定这个问题——核心思路是给你的目标bash脚本分配一个专属的SELinux上下文(比如你提到的test_script_t),同时创建足够宽松的策略让它能执行所有需要的操作(避免持续出现SELinux拒绝日志),最后配置auditd过滤掉这个上下文产生的所有审计日志。这样既不用关闭SELinux,也不会影响用户bob的其他操作日志,具体步骤如下:

1. 创建自定义SELinux策略模块

首先我们要编写策略文件,定义test_script_t这个类型以及它的权限:

1.1 编写策略定义文件(test_script.te)

在任意目录创建一个名为test_script.te的文件,内容如下:

policy_module(test_script, 1.0)

# 定义自定义类型和执行类型
type test_script_t;
type test_script_exec_t;
domain_type(test_script_t)
domain_entry_file(test_script_t, test_script_exec_t)

# 允许进程基础操作
allow test_script_t self:process { fork execmem signal };
allow test_script_t self:fd use;
allow test_script_t self:fifo_file rw_file_perms;
allow test_script_t self:unix_stream_socket create_stream_socket_perms;

# 允许访问bob的家目录(脚本和日志可能在这里)
allow test_script_t user_home_t:dir rw_dir_perms;
allow test_script_t user_home_t:file rw_file_perms;

# 允许执行脚本用到的系统命令(mkdir/top/grep等)
allow test_script_t bin_t:file execute;
allow test_script_t usr_t:file execute;
allow test_script_t bin_t:lnk_file read;

# 允许读取系统proc信息(top/jstack需要)
allow test_script_t proc_t:dir search;
allow test_script_t proc_t:file read;

# 允许终端操作(脚本可能需要交互或输出到终端)
allow test_script_t devpts_t:chr_file rw_file_perms;

# 允许写入系统日志目录(如果脚本输出到/var/log)
allow test_script_t var_log_t:dir add_name;
allow test_script_t var_log_t:file create_file_perms;

# 标记执行类型为可被shell执行
corecmd_shell_exec(test_script_exec_t)

1.2 编写上下文匹配文件(test_script.fc)

创建test_script.fc文件,指定你的脚本路径对应的SELinux执行上下文,假设脚本路径是/home/bob/scripts/monitor.sh:

/home/bob/scripts/monitor.sh    --    gen_context(system_u:object_r:test_script_exec_t:s0)

1.3 编译并加载策略

执行以下命令编译和安装自定义策略:

# 编译模块
checkmodule -M -m -o test_script.mod test_script.te
# 打包成策略包
semodule_package -o test_script.pp -m test_script.mod
# 加载策略
semodule -i test_script.pp

2. 给脚本标记SELinux上下文

执行以下命令让脚本应用我们定义的上下文:

restorecon -v /home/bob/scripts/monitor.sh

你可以用ls -Z /home/bob/scripts/monitor.sh验证,输出里应该包含test_script_exec_t。

3. 配置auditd过滤自定义上下文的日志

现在要让auditd忽略test_script_t上下文产生的所有日志:

  1. 编辑auditd规则文件:
vi /etc/audit/rules.d/audit.rules
  1. 添加以下规则:
# 过滤test_script_t上下文的所有审计日志
-a never,exclude -F subj_type=test_script_t
  1. 重启auditd服务生效:
systemctl restart auditd

4. 测试与策略调整

运行你的脚本,然后用ausearch -m avc检查是否还有SELinux拒绝日志。如果还有新的拒绝,你可以用audit2allow工具自动生成需要的规则并添加到test_script.te里:

ausearch -m avc | audit2allow -m test_script >> test_script.te

之后重新编译加载策略即可。如果想更彻底避免拒绝日志,也可以添加宽泛的允许规则(比如允许访问大部分文件系统),但要注意这会降低一点安全性,不过符合你“允许几乎所有操作”的需求。

备注:内容来源于stack exchange,提问作者VenomousDuck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 11:33:06