--- - name: Security Hardening and Backup hosts: all become: yes gather_facts: yes tasks: # SSH 安全配置检查 - name: Check SSH configuration security lineinfile: path: /etc/ssh/sshd_config regexp: "{{ item.regexp }}" line: "{{ item.line }}" backup: yes loop: - { regexp: '^#?PermitRootLogin', line: 'PermitRootLogin no' } - { regexp: '^#?PasswordAuthentication', line: 'PasswordAuthentication no' } - { regexp: '^#?X11Forwarding', line: 'X11Forwarding no' } - { regexp: '^#?MaxAuthTries', line: 'MaxAuthTries 3' } notify: restart ssh when: ansible_os_family == "Debian" # 防火墙状态检查 - name: Check UFW firewall status shell: ufw status register: ufw_status changed_when: false failed_when: false when: ansible_os_family == "Debian" - name: Display firewall status debug: msg: "🔥 Firewall Status: {{ ufw_status.stdout_lines }}" when: ansible_os_family == "Debian" and ufw_status.stdout_lines is defined # 检查可疑登录 - name: Check for failed login attempts shell: grep "Failed password" /var/log/auth.log | tail -10 register: failed_logins changed_when: false failed_when: false - name: Report suspicious login attempts debug: msg: "🚨 Recent failed logins: {{ failed_logins.stdout_lines }}" when: failed_logins.stdout_lines | length > 0 # 检查 root 用户活动 - name: Check recent root activity shell: grep "sudo.*root" /var/log/auth.log | tail -5 register: root_activity changed_when: false failed_when: false - name: Display root activity debug: msg: "👑 Recent root activity: {{ root_activity.stdout_lines }}" when: root_activity.stdout_lines | length > 0 # 备份重要配置文件 - name: Create backup directory file: path: /backup/configs state: directory mode: '0700' - name: Backup important configuration files copy: src: "{{ item }}" dest: "/backup/configs/{{ item | basename }}.{{ ansible_date_time.epoch }}" remote_src: yes backup: yes loop: - /etc/ssh/sshd_config - /etc/hosts - /etc/fstab - /etc/crontab failed_when: false # 检查系统完整性 - name: Check for world-writable files shell: find /etc /usr /bin /sbin -type f -perm -002 2>/dev/null | head -10 register: world_writable changed_when: false - name: Report world-writable files debug: msg: "⚠️ World-writable files found: {{ world_writable.stdout_lines }}" when: world_writable.stdout_lines | length > 0 # 检查 SUID 文件 - name: Check for SUID files shell: find /usr /bin /sbin -type f -perm -4000 2>/dev/null register: suid_files changed_when: false - name: Display SUID files count debug: msg: "🔐 Found {{ suid_files.stdout_lines | length }} SUID files" # 更新系统时间 - name: Sync system time shell: timedatectl set-ntp true failed_when: false - name: Check time synchronization shell: timedatectl status register: time_status - name: Display time sync status debug: msg: "🕐 Time sync: {{ time_status.stdout_lines | select('match', '.*synchronized.*') | list }}" handlers: - name: restart ssh systemd: name: ssh state: restarted when: ansible_os_family == "Debian"