给一个selinux的策略写法,保护文件只能被部分进程访问

要编写一个 SELinux 策略来保护文件只能被特定进程访问,需要完成以下步骤。这里以保护 /var/webapp/config.conf 文件只能被 httpd_t 进程访问为例:

1. 创建 SELinux 策略模块文件(.te 文件)

1
2
3
4
5
6
7
8
9
10
11
12
13
# 文件名:webapp_protect.te
policy_module(webapp_protect, 1.0)

# 定义新类型用于受保护文件
type protected_config_t;
files_type(protected_config_t) # 声明为文件类型

# 允许特定进程访问此类型
allow httpd_t protected_config_t:file { read open getattr };

# 可选:禁止其他域访问(SELinux 默认拒绝未明确允许的访问)
# 但显式拒绝可增强可读性
neverallow ~httpd_t protected_config_t:file *;

2. 编译并安装策略模块

1
2
3
4
5
6
# 生成 .mod 和 .pp 文件
checkmodule -M -m -o webapp_protect.mod webapp_protect.te
semodule_package -o webapp_protect.pp -m webapp_protect.mod

# 加载策略模块
semodule -i webapp_protect.pp

3. 标记受保护文件为新类型

1
2
3
4
5
6
7
# 设置文件安全上下文
semanage fcontext -a -t protected_config_t '/var/webapp/config.conf'
restorecon -v /var/webapp/config.conf

# 验证上下文
ls -Z /var/webapp/config.conf
# 应显示:unconfined_u:object_r:protected_config_t:s0

4. 验证策略效果

1
2
3
4
5
6
# 尝试用非授权进程访问(应失败)
runcon -t sshd_t cat /var/webapp/config.conf
# 预期错误:avc: denied

# 授权进程访问(应成功)
runcon -t httpd_t cat /var/webapp/config.conf

关键组件说明

  1. 类型定义 (protected_config_t):

    • 创建新类型标记受保护文件
    • files_type() 宏声明其为标准文件类型
  2. 访问规则

    1
    allow source_domain target_type:class permissions;
    • httpd_t: 允许访问的进程域
    • protected_config_t: 文件类型
    • file: 资源类
    • { read open getattr }: 最小权限集
  3. 显式拒绝 (neverallow):

    • 禁止所有非 httpd_t 域的访问
    • ~httpd_t 表示除 httpd_t 外的所有域

高级定制场景

场景 1:允许多个进程访问

1
2
# 允许 httpd_t 和 custom_app_t 访问
allow { httpd_t custom_app_t } protected_config_t:file { read write };

场景 2:自定义进程域

1
2
3
4
5
6
7
8
9
10
11
# 为自定义应用创建新域
type custom_app_t;
domain_type(custom_app_t) # 声明为进程域

# 允许从可执行文件类型转换
type custom_app_exec_t;
files_type(custom_app_exec_t)

# 域转换规则
allow initrc_t custom_app_t:process transition;
allow custom_app_t custom_app_exec_t:file { execute read open };

场景 3:目录保护

1
2
3
4
5
6
7
8
9
10
11
# 保护整个目录
type protected_config_dir_t;
files_type(protected_config_dir_t)

# 允许进程递归访问目录
allow httpd_t protected_config_dir_t:dir { read search open };
allow httpd_t protected_config_dir_t:file read;

# 标记目录
semanage fcontext -a -t protected_config_dir_t '/var/webapp/secure(/.*)?'
restorecon -R /var/webapp/secure

调试建议

  1. 查看拒绝日志

    1
    ausearch -m avc -ts recent | grep protected_config_t
  2. 生成自定义策略

    1
    2
    3
    # 根据拒绝记录生成允许规则
    audit2allow -a -M myfixes
    semodule -i myfixes.pp
  3. 临时测试权限

    1
    2
    # 临时允许所有访问(调试后需撤销)
    semanage permissive -a httpd_t

完整工作流

  1. 创建策略文件 .te
  2. 编译安装模块
  3. 标记文件系统对象
  4. 测试访问权限
  5. 根据审计日志调整策略
  6. 部署到生产环境

重要提示:实际部署前应在测试环境中验证。权限应遵循最小特权原则,仅授予必要权限(如 read 而非 *)。