Zum Inhalt

SSHD Hardening role

Harden SSH daemon configuration by disabling password authentication and root login, enforcing key-based authentication only.

Usage

Configure the role in your inventory:

1
2
# vars/main.yml
sshd_hardening_enabled: true

Include the role in your playbook:

1
2
3
- hosts: all
  roles:
    - role: sshd_hardening

The role provides this tag: - ssh-hardening - Apply SSH security hardening

Docs

Apply SSH hardening to all hosts:

1
ansible-playbook -i inventory/hosts.yml your-playbook.yml --tags ssh-hardening

Warning: Ensure you have SSH key-based access configured before running this role, as password authentication will be disabled!

What Gets Changed

The role modifies /etc/ssh/sshd_config with these security improvements:

  1. Enable Public Key Authentication

    1
    PubkeyAuthentication yes
    

  2. Disable Root Login

    1
    PermitRootLogin no
    

  3. Disable Password Authentication

    1
    PasswordAuthentication no
    

Security Benefits

  • Key-Based Auth Only: Eliminates brute-force password attacks
  • No Root Login: Prevents direct root access, forces use of sudo
  • Attack Surface Reduction: Removes password-based authentication vector

Prerequisites

Before running this role, ensure:

  1. SSH Keys are Installed: Copy your public key to target hosts

    1
    ssh-copy-id user@host
    

  2. Test Key Access: Verify you can login without password

    1
    ssh user@host
    

  3. Sudo Access: Ensure your user has sudo privileges for administrative tasks

Post-Deployment

After applying hardening: - Password login attempts will fail - Root cannot login directly (use sudo instead) - Only users with authorized SSH keys can connect

Testing

Test SSH access after hardening:

1
2
3
4
5
6
7
8
# Should work (with key)
ssh user@host

# Should fail (no password prompt)
ssh -o PubkeyAuthentication=no user@host

# Should fail (root disabled)
ssh root@host

Reverting Changes

To re-enable password authentication (not recommended):

1
2
sudo sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
sudo systemctl restart sshd

Handler

The role includes a handler that automatically restarts the SSH service when configuration changes are made, ensuring settings take effect immediately.

Best Practices

Additional SSH hardening recommendations (not included in this role): - Use non-standard SSH port - Configure fail2ban for additional protection - Use SSH key passphrases - Limit SSH access by IP (AllowUsers, AllowGroups) - Disable empty passwords - Set ClientAliveInterval and ClientAliveCountMax