# SSH Hardening
# Applies security best practices to SSH configuration: disables root login,
# enforces key-only authentication, and installs fail2ban for brute-force
# protection.
#
# Customize:
#   - Set INVENTORY_GROUP to target hosts
#   - Adjust SSH_PORT if using a non-standard port
#   - Set ALLOWED_USERS to restrict SSH access to specific accounts

name: ssh-hardening
description: SSH hardening with key-only auth, root login disabled, and fail2ban
tags: [security, ssh, hardening, fail2ban, linux]
tool: ansible
cloud_provider: agnostic
os_family: debian
risk_level: medium
compliance_tags: [SOC2, CIS]

vars:
  INVENTORY_GROUP: "{{INVENTORY_GROUP}}"
  SSH_PORT: "{{SSH_PORT}}"
  ALLOWED_USERS: "{{ALLOWED_USERS}}"

playbook: |
  ---
  - hosts: "{{ inventory_group }}"
    become: true
    tasks:
      - name: Install fail2ban
        apt:
          name: fail2ban
          state: present
          update_cache: yes

      - name: Disable root login
        lineinfile:
          path: /etc/ssh/sshd_config
          regexp: "^#?PermitRootLogin"
          line: "PermitRootLogin no"
        notify: restart sshd

      - name: Disable password authentication
        lineinfile:
          path: /etc/ssh/sshd_config
          regexp: "^#?PasswordAuthentication"
          line: "PasswordAuthentication no"
        notify: restart sshd

      - name: Set SSH port
        lineinfile:
          path: /etc/ssh/sshd_config
          regexp: "^#?Port"
          line: "Port {{ ssh_port | default(22) }}"
        notify: restart sshd

      - name: Restrict SSH to allowed users
        lineinfile:
          path: /etc/ssh/sshd_config
          regexp: "^#?AllowUsers"
          line: "AllowUsers {{ allowed_users | default('deploy') }}"
        when: allowed_users is defined
        notify: restart sshd

      - name: Enable fail2ban service
        systemd:
          name: fail2ban
          enabled: yes
          state: started

    handlers:
      - name: restart sshd
        systemd:
          name: sshd
          state: restarted
