linux文件权限风险需“先审计、再收敛、后固化”:聚焦/etc/shadow等高危文件权限基线,用find快速发现、ansible批量修复,ci/cd嵌入检查实现持续防护。

Linux文件权限混淆风险通常源于误设(如敏感配置文件被设为全局可写)、部署脚本缺陷或权限继承异常。批量修正不能靠手动,需结合策略校验 + 自动化修复,核心是“先审计、再收敛、后固化”。
明确高危权限模式并建立基线清单
不是所有非默认权限都危险,需聚焦真正暴露面:
- /etc/shadow、/etc/passwd、/etc/sudoers 必须为 root 只读(644)或仅 root 可读写(600/440),禁止 group/other 写权限(即不能含 2 或 6 的八进制位)
- SSH 私钥(~/.ssh/id_rsa)、Web 配置(/etc/nginx/*.conf) 不能有 group/other 可读(即权限不能 ≥644 且非 600/400)
- 可执行目录(如 /usr/local/bin) 不应允许 other 写(即不能是 777、737 等)
建议用 find 搭配 -perm 快速生成初始问题集,例如:find /etc -type f \( -perm -2 -o -perm -20 \) 2>/dev/null | head -20(查其他用户可写文件)
用 ansible 批量校准权限(推荐生产环境)
Ansible 能跨主机统一执行、自带幂等性、失败可回溯,比 shell 脚本更可控:
- 定义权限规则 YAML(如
permissions.yml):
- path: "/etc/shadow" mode: "0600" owner: "root" group: "root" - path: "/etc/sudoers" mode: "0440" owner: "root" group: "root" - path: "/root/.bash_history" mode: "0600"
- 编写 playbook(
fix-perms.yml)调用file模块:
- hosts: all
tasks:
- name: Apply baseline permissions
file:
path: "{{ item.path }}"
mode: "{{ item.mode }}"
owner: "{{ item.owner | default('root') }}"
group: "{{ item.group | default('root') }}"
state: file
loop: "{{ lookup('file', 'permissions.yml') | from_yaml }}"
运行:ansible-playbook -i inventory.ini fix-perms.yml --check 先试运行,确认无误后去掉 --check 实际执行。
用 shell + find 实现轻量级快速修复(适合单机或临时场景)
若无 Ansible,可用组合命令精准清理,避免“一刀切”:
- 清空其他用户对关键目录的写权限(保留读和执行):
find /etc /var/log -type d -perm /002 -exec chmod o-w {} \;
- 收紧敏感文件的读写范围(仅 root):
find /etc -type f \( -name "shadow" -o -name "gshadow" -o -name "sudoers" \) -exec chmod 600 {} \;
- 修复常见 Web 目录权限(防止 .git 泄露或配置覆盖):
find /var/www -type f -name "*.conf" -exec chmod 644 {} \;
find /var/www -type d -exec chmod 755 {} \;
⚠️ 注意:执行前务必 find ... -ls 预览匹配结果,避免误改。
固化防护:在 CI/CD 或部署流程中嵌入权限检查
自动化修复只是补救,真正的安全在于不产生问题:
- 在 Jenkins/GitLab CI 中增加权限扫描步骤,用
auditctl或自定义脚本检测新部署文件是否符合策略,失败则阻断发布 - 使用
inotifywait监控关键路径(如 /etc),当文件被修改时自动触发校验脚本 - 在 Dockerfile 中显式声明
RUN chmod 600 /app/config.yaml,而非依赖基础镜像默认值
权限治理不是一次操作,而是把“谁可以改、改成什么样”变成可验证、可追踪、不可绕过的环节。










