Ansible实现安全审计:自动化配置合规检查与漏洞扫描

引言:为什么需要自动化安全审计
在现代IT基础设施中,安全合规和漏洞管理已经成为企业运营的核心需求。传统的手动安全审计方式存在效率低下、容易出错、难以持续等问题。Ansible作为一款强大的自动化工具,能够帮助我们实现安全审计的自动化,确保系统配置符合安全标准,并及时发现潜在漏洞。
通过Ansible进行安全审计的主要优势包括:
一致性
:确保所有系统按照相同的安全标准进行检查
可重复性
:审计过程可以定期自动执行
可追溯性
:所有审计结果都有详细记录
效率提升
:减少人工操作,快速发现和修复问题
安全审计的核心概念
1. 配置合规检查
配置合规检查主要验证系统设置是否符合安全策略和行业标准,包括:
操作系统安全配置
服务安全设置
用户权限管理
网络安全策略
日志审计配置
2. 漏洞扫描
漏洞扫描是识别系统中已知安全漏洞的过程,包括:
软件包版本检查
CVE漏洞识别
安全补丁状态
服务配置弱点
使用Ansible进行配置合规检查
1. 基础安全配置检查
首先,我们需要创建一个Ansible Playbook来检查基础安全配置。以下是一个完整的示例:
—
– name: 基础安全配置合规检查
hosts: all
become: yes
vars:
# 安全基线标准
min_password_length: 12
max_password_age: 90
idle_timeout: 300

tasks:
# 检查密码复杂度策略
– name: 检查密码最小长度配置
lineinfile:
path: /etc/login.defs
regexp: ‘^PASS_MIN_LEN’
state: present
line: “PASS_MIN_LEN {{ min_password_length }}”
check_mode: yes
register: password_length_check

– name: 报告密码长度检查结果
debug:
msg: “密码长度配置符合要求: {{ min_password_length }}”
when: password_length_check is changed

– name: 报告密码长度配置问题
debug:
msg: “警告:密码长度配置不符合标准,当前配置可能过短”
when: password_length_check is not changed

# 检查SSH安全配置
– name: 检查SSH协议版本
lineinfile:
path: /etc/ssh/sshd_config
regexp: ‘^Protocol’
state: present
line: “Protocol 2”
check_mode: yes
register: ssh_protocol_check

– name: 检查SSH空密码登录设置
lineinfile:
path: /etc/ssh/sshd_config
regexp: ‘^PermitEmptyPasswords’
state: present
line: “PermitEmptyPasswords no”
check_mode: yes
register: ssh_empty_pw_check

– name: 检查SSH根用户登录设置
lineinfile:
path: /etc/ssh/sshd_config
regexp: ‘^PermitRootLogin’
state: present
line: “PermitRootLogin no”
check_mode: yes
register: ssh_root_login_check

# 检查文件权限
– name: 检查/etc/passwd文件权限
file:
path: /etc/passwd
mode: ‘0644’
check_mode: yes
register: passwd_perm_check

– name: 检查/etc/shadow文件权限
file:
path: /etc/shadow
mode: ‘0000’
check_mode: yes
register: shadow_perm_check

# 生成合规报告
– name: 收集所有检查结果
set_fact:
compliance_results:
password_length: “{{ password_length_check is changed }}”
ssh_protocol: “{{ ssh_protocol_check is changed }}”
ssh_empty_pw: “{{ ssh_empty_pw_check is changed }}”
ssh_root_login: “{{ ssh_root_login_check is changed }}”
passwd_permissions: “{{ passwd_perm_check is changed }}”
shadow_permissions: “{{ shadow_perm_check is changed }}”

– name: 生成合规报告
copy:
content: |
安全合规检查报告
=================
主机: {{ inventory_hostname }}
检查时间: {{ ansible_date_time.iso8601 }}

检查项目:
– 密码长度配置: {{ ‘通过’ if compliance_results.password_length else ‘失败’ }}
– SSH协议版本: {{ ‘通过’ if compliance_results.ssh_protocol else ‘失败’ }}
– SSH空密码登录: {{ ‘通过’ if compliance_results.ssh_empty_pw else ‘失败’ }}
– SSH根用户登录: {{ ‘通过’ if compliance_results.ssh_root_login else ‘失败’ }}
– /etc/passwd权限: {{ ‘通过’ if compliance_results.passwd_permissions else ‘失败’ }}
– /etc/shadow权限: {{ ‘通过’ if compliance_results.shadow_permissions else ‘失败’ }}

总体状态: {{ ‘合规’ if compliance_results.values()|list|count == compliance_results.values()|list|selectattr(‘==’, true)|list|count else ‘需要整改’ }}
dest: “/var/log/security_audit_{{ inventory_hostname }}_{{ ansible_date_time.epoch }}.txt”
delegate_to: localhost
2. CIS基准检查
CIS(Center for Internet Security)基准是业界公认的安全配置标准。我们可以创建一个角色来实现CIS基准检查:
# roles/cis_audit/tasks/main.yml
—
– name: 创建CIS审计目录
file:
path: /opt/cis_audit
state: directory
mode: ‘0755’

# 1. 内核参数安全检查
– name: 检查IP转发设置
sysctl:
name: net.ipv4.ip_forward
value: ‘0’
state: present
check_mode: yes
register: ip_forward_check

– name: 检查ICMP重定向接受设置
sysctl:
name: net.ipv4.conf.all.accept_redirects
value: ‘0’
state: present
check_mode: yes
register: icmp_redirect_check

# 2. 文件系统安全检查
– name: 检查/tmp目录挂载选项
mount:
path: /tmp
src: “{{ ansible_mounts | selectattr(‘mount’, ‘equalto’, ‘/tmp’) | map(attribute=’device’) | first | default(‘none’) }}”
fstype: “{{ ansible_mounts | selectattr(‘mount’, ‘equalto’, ‘/tmp’) | map(attribute=’fstype’) | first | default(‘ext4’) }}”
opts: “noexec,nosuid,nodev”
state: present
check_mode: yes
register: tmp_mount_check
when: ansible_mounts | selectattr(‘mount’, ‘equalto’, ‘/tmp’) | list | count > 0

# 3. 用户账户安全检查
– name: 获取密码过期设置
shell: “awk -F: ‘($3 < 1000) {print $1}' /etc/passwd | xargs -I {} chage -l {} | grep 'Password expires'" register: password_expiry_info changed_when: false failed_when: false - name: 检查空密码账户 shell: "awk -F: '($2 == \"\") {print $1}' /etc/shadow" register: empty_password_users changed_when: false failed_when: false - name: 报告空密码账户 debug: msg: "警告:发现空密码账户: {{ empty_password_users.stdout }}" when: empty_password_users.stdout != "" # 4. 服务安全检查 - name: 检查不必要的服务状态 service: name: "{{ item }}" state: stopped enabled: no check_mode: yes loop: - telnet - rsh - rlogin register: service_security_check # 5. 生成CIS审计报告 - name: 收集CIS检查结果 set_fact: cis_results: ip_forward: "{{ ip_forward_check is changed }}" icmp_redirect: "{{ icmp_redirect_check is changed }}" tmp_mount: "{{ tmp_mount_check is changed if tmp_mount_check is defined else 'skipped' }}" empty_passwords: "{{ empty_password_users.stdout_lines | count == 0 }}" unwanted_services: "{{ service_security_check.results | map(attribute='changed') | list | select('equalto', true) | list | count == 0 }}" - name: 生成CIS审计报告 template: src: cis_report.j2 dest: "/opt/cis_audit/cis_report_{{ inventory_hostname }}_{{ ansible_date_time.epoch }}.txt" delegate_to: localhost 对应的Jinja2模板(templates/cis_report.j2): CIS安全基准审计报告 ===================== 主机: {{ inventory_hostname }} 审计时间: {{ ansible_date_time.iso8601 }} 审计版本: CIS Benchmarks v2.1.0 审计结果: 1. 内核安全 - IP转发控制: {{ '通过' if cis_results.ip_forward else '失败' }} - ICMP重定向控制: {{ '通过' if cis_results.icmp_redirect else '失败' }} 2. 文件系统安全 - /tmp目录挂载选项: {{ '通过' if cis_results.tmp_mount else '失败' }} 3. 用户账户安全 - 无空密码账户: {{ '通过' if cis_results.empty_passwords else '失败' }} 4. 服务安全 - 不必要服务已禁用: {{ '通过' if cis_results.unwanted_services else '失败' }} 总体合规状态: {{ '符合CIS基准' if cis_results.values()|list|select('equalto', true)|list|count == cis_results.values()|list|count else '部分不符合' }} 建议措施: {% if not cis_results.ip_forward %} - 禁用IP转发: sysctl -w net.ipv4.ip_forward=0{% endif %} {% if not cis_results.icmp_redirect %} - 禁用ICMP重定向: sysctl -w net.ipv4.conf.all.accept_redirects=0{% endif %} {% if not cis_results.tmp_mount %} - 重新挂载/tmp目录并添加noexec,nosuid,nodev选项{% endif %} {% if not cis_results.empty_passwords %} - 为所有空密码账户设置强密码{% endif %} {% if not cis_results.unwanted_services %} - 禁用不必要的服务{% endif %} 使用Ansible进行漏洞扫描 1. 基于包管理器的漏洞扫描 --- - name: 系统漏洞扫描 hosts: all become: yes vars: # 定义需要扫描的CVE列表 critical_cves: - CVE-2021-44228 # Log4j - CVE-2021-45046 - CVE-2021-44832 - CVE-2020-1472 # Zerologon # 需要更新的关键软件包 critical_packages: - openssl - openssh - kernel - glibc tasks: # 检查系统更新状态 - name: 检查可用的系统更新 apt: upgrade: dist update_cache: yes cache_valid_time: 3600 check_mode: yes register: system_updates when: ansible_os_family == "Debian" - name: 检查RedHat系统更新 yum: name: '*' state: latest update_cache: yes check_mode: yes register: system_updates when: ansible_os_family == "RedHat" # 检查特定软件包版本 - name: 获取关键软件包版本信息 package_facts: manager: auto - name: 检查关键软件包版本 debug: msg: "软件包 {{ item }} 版本: {{ ansible_facts.packages[item][0].version }}" loop: "{{ critical_packages }}" when: item in ansible_facts.packages # 检查已知的高危漏洞 - name: 检查Log4j漏洞 find: paths: / patterns: "log4j*.jar" recurse: yes size: 1k register: log4j_files ignore_errors: yes changed_when: false - name: 报告Log4j漏洞检测结果 debug: msg: "警告:发现Log4j文件,可能存在CVE-2021-44228漏洞: {{ log4j_files.files | map(attribute='path') | list }}" when: log4j_files.matched > 0

# 检查OpenSSL漏洞
– name: 检查OpenSSL版本
shell: |
openssl version | awk ‘{print $2}’
register: openssl_version
changed_when: false
failed_when: false

– name: 验证OpenSSL版本安全性
debug:
msg: “OpenSSL版本 {{ openssl_version.stdout }} 可能存在已知漏洞,请升级到最新版本”
when:
– openssl_version.stdout is version(‘1.1.1’, ‘<') - openssl_version.stdout is version('1.0.2', '>=’)

# 生成漏洞扫描报告
– name: 收集漏洞扫描结果
set_fact:
vulnerability_report:
scan_time: “{{ ansible_date_time.iso8601 }}”
hostname: “{{ inventory_hostname }}”
system_updates_available: “{{ system_updates is changed }}”
log4j_detected: “{{ log4j_files.matched > 0 }}”
openssl_version: “{{ openssl_version.stdout }}”
critical_vulnerabilities: []

– name: 添加Log4j漏洞到报告
set_fact:
vulnerability_report: “{{ vulnerability_report | combine({‘critical_vulnerabilities’: vulnerability_report.critical_vulnerabilities + [‘CVE-2021-44228’]}) }}”
when: log4j_files.matched > 0

– name: 生成漏洞扫描报告
copy:
content: |
系统漏洞扫描报告
=================
主机: {{ vulnerability_report.hostname }}
扫描时间: {{ vulnerability_report.scan_time }}

扫描结果:
– 系统更新状态: {{ ‘有可用更新’ if vulnerability_report.system_updates_available else ‘已是最新’ }}
– Log4j漏洞检测: {{ ‘发现风险’ if vulnerability_report.log4j_detected else ‘未发现’ }}
– OpenSSL版本: {{ vulnerability_report.openssl_version }}

高危漏洞列表:
{% for cve in vulnerability_report.critical_vulnerabilities %}
– {{ cve }}
{% endfor %}

{% if vulnerability_report.critical_vulnerabilities | length > 0 %}
建议: 立即修复已发现的高危漏洞
{% else %}
状态: 未发现已知高危漏洞
{% endif %}
dest: “/var/log/vulnerability_scan_{{ inventory_hostname }}_{{ ansible_date_time.epoch }}.txt”
delegate_to: localhost
2. 集成第三方漏洞扫描工具
—
– name: 集成OpenVAS漏洞扫描
hosts: all
become: yes
vars:
openvas_server: “192.168.1.100”
scan_profile: “Full and Fast”

tasks:
# 安装OpenVAS客户端工具
– name: 安装OpenVAS CLI工具
package:
name: openvas-cli
state: present
when: ansible_os_family == “Debian”

# 创建扫描任务
– name: 创建OpenVAS扫描任务
uri:
url: “http://{{ openvas_server }}:9392/omp”
method: POST
body_format: form-urlencoded
body:
command: create_target
name: “{{ inventory_hostname }}-{{ ansible_date_time.epoch }}”
hosts: “{{ ansible_default_ipv4.address }}”
user: admin
password: “{{ openvas_password }}”
register: scan_target
delegate_to: “{{ openvas_server }}”
run_once: true

# 执行扫描
– name: 启动漏洞扫描
uri:
url: “http://{{ openvas_server }}:9392/omp”
method: POST
body_format: form-urlencoded
body:
command: start_task
task_id: “{{ scan_target.json.id }}”
user: admin
password: “{{ openvas_password }}”
delegate_to: “{{ openvas_server }}”
run_once: true

# 获取扫描结果
– name: 获取扫描报告
uri:
url: “http://{{ openvas_server }}:9392/omp”
method: POST
body_format: form-urlencoded
body:
command: get_report
report_id: “{{ scan_target.json.id }}”
user: admin
password: “{{ openvas_password }}”
register: scan_results
delegate_to: “{{ openvas_server }}”
run_once: true

– name: 保存扫描报告
copy:
content: “{{ scan_results.content }}”
dest: “/var/log/openvas_report_{{ inventory_hostname }}_{{ ansible_date_time.epoch }}.xml”
delegate_to: localhost
高级安全审计策略
1. 定期审计计划
—
– name: 安全审计计划配置
hosts: all
become: yes

tasks:
# 配置cron任务定期执行安全审计
– name: 创建安全审计脚本
copy:
content: |
#!/bin/bash
# 安全审计脚本
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LOG_DIR=”/var/log/security_audit”
mkdir -p $LOG_DIR

# 执行Ansible审计Playbook
ansible-playbook /opt/security/playbooks/compliance_audit.yml -i /opt/security/inventory/hosts –limit $HOSTNAME > $LOG_DIR/compliance_$TIMESTAMP.log 2>&1
ansible-playbook /opt/security/playbooks/vulnerability_scan.yml -i /opt/security/inventory/hosts –limit $HOSTNAME > $LOG_DIR/vulnerability_$TIMESTAMP.log 2>&1

# 清理30天前的日志
find $LOG_DIR -name “*.log” -mtime +30 -delete

# 发送报告邮件(如果配置了邮件服务器)
if [ -f /usr/bin/mail ]; then
cat $LOG_DIR/compliance_$TIMESTAMP.log | mail -s “安全审计报告 – $HOSTNAME – $TIMESTAMP” security@company.com
fi
dest: /usr/local/bin/security_audit.sh
mode: ‘0755’

– name: 配置定期安全审计
cron:
name: “每日安全审计”
minute: “0”
hour: “2”
job: “/usr/local/bin/security_audit.sh”
user: root

# 配置审计日志轮转
– name: 配置审计日志轮转
copy:
content: |
/var/log/security_audit/*.log {
daily
rotate 30
compress
delaycompress
missingok
notifempty
create 0640 root root
}
dest: /etc/logrotate.d/security_audit
2. 实时监控与告警
—
– name: 实时安全监控配置
hosts: all
become: yes

tasks:
# 配置文件完整性监控
– name: 安装AIDE(文件完整性检查工具)
package:
name: aide
state: present

– name: 初始化AIDE数据库
command: aideinit -y -f
args:
creates: /var/lib/aide/aide.db.new

– name: 启用AIDE数据库
command: mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db
args:
creates: /var/lib/aide/aide.db

# 配置实时日志监控
– name: 创建日志监控脚本
copy:
content: |
#!/bin/bash
# 实时监控安全相关日志
tail -f /var/log/auth.log | while read line; do
# 检测SSH暴力破解
if echo “$line” | grep -q “Failed password”; then
echo “$(date): $line” >> /var/log/security_alerts.log
# 发送告警(需要配置邮件或webhook)
echo “SSH暴力破解告警: $line” | mail -s “安全告警” security@company.com
fi

# 检测sudo使用
if echo “$line” | grep -q “sudo.*COMMAND”; then
echo “$(date): $line” >> /var/log/sudo_audit.log
fi
done
dest: /usr/local/bin/log_monitor.sh
mode: ‘0755’

# 配置systemd服务
– name: 创建日志监控服务
copy:
content: |
[Unit]
Description=Security Log Monitor
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/log_monitor.sh
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
dest: /etc/systemd/system/security-monitor.service

– name: 启用并启动监控服务
systemd:
name: security-monitor
enabled: yes
state: started
安全审计报告与分析
1. 统一报告生成
—
– name: 生成统一安全审计报告
hosts: localhost
connection: local
gather_facts: no

vars:
report_dir: “/var/log/security_reports”
audit_date: “{{ ansible_date_time.iso8601 }}”

tasks:
– name: 创建报告目录
file:
path: “{{ report_dir }}”
state: directory
mode: ‘0755’

– name: 收集所有主机的审计结果
find:
paths: /var/log
patterns: “security_audit_*.txt,vulnerability_scan_*.txt”
register: audit_files

– name: 解析审计结果
set_fact:
compliance_results: “{{ lookup(‘file’, item) | from_yaml }}”
loop: “{{ audit_files.files | map(attribute=’path’) | list }}”
when: item is search(‘compliance’)
ignore_errors: yes

– name: 生成综合报告
copy:
content: |
企业安全审计综合报告
======================
生成时间: {{ audit_date }}
审计主机数: {{ audit_files.files | count }}

合规性检查统计:
{% for host in groups[‘all’] %}
{% if hostvars[host] is defined and hostvars[host].compliance_results is defined %}
– {{ host }}: {{ ‘合规’ if hostvars[host].compliance_results.values()|list|select(‘equalto’, true)|list|count == hostvars[host].compliance_results.values()|list|count else ‘需要整改’ }}
{% endif %}
{% endfor %}

漏洞统计:
– 发现漏洞的主机数: {{ audit_files.files | select(‘search’, ‘vulnerability’) | list | count }}

建议措施:
1. 定期执行安全审计
2. 及时修复发现的漏洞
3. 更新安全策略
4. 加强访问控制
dest: “{{ report_dir }}/comprehensive_report_{{ ansible_date_time.epoch }}.txt”
最佳实践与注意事项
1. 安全考虑
凭证管理
:使用Ansible Vault加密敏感数据
权限控制
:遵循最小权限原则
审计日志
:确保审计过程本身的安全性
2. 性能优化
并行执行
:合理配置fork数量
增量扫描
:只检查变化的部分
资源限制
:避免审计过程影响业务
3. 持续改进
定期更新
:更新安全基线和漏洞库
反馈机制
:根据审计结果调整策略
培训提升
:提高团队安全意识
结论
通过Ansible实现安全审计自动化,企业可以:
提高效率
:减少人工操作,快速完成大规模审计
保证一致性
:确保所有系统按照统一标准检查
及时发现风险
:定期扫描及时发现安全问题
便于追溯
:完整的审计记录便于问题追踪和合规证明
建议企业根据自身环境特点,选择合适的审计策略,并持续优化审计流程,建立完善的安全防护体系。