Hardening SSH Security: Best Practices for Securing Remote Access
Hardening SSH Security: Best Practices for Securing Remote Access
Introduction
SSH (Secure Shell) is a fundamental tool for managing remote servers, but it is also a common target for brute force attacks and exploits. Properly securing SSH access is crucial for protecting your infrastructure. This guide covers best practices to harden SSH security on your Linux server.
Step 1: Disable Root Login
- Open the SSH configuration file:
sudo nano /etc/ssh/sshd_config
- Find the following line:
PermitRootLogin yes
- Change it to:
PermitRootLogin no
- Save the file and restart SSH:
sudo systemctl restart ssh
Step 2: Change the Default SSH Port
- Open the SSH configuration file:
sudo nano /etc/ssh/sshd_config
- Find the line that specifies the port (usually port 22):
#Port 22
- Change it to a non-standard port, e.g.:
Port 2222
- Restart SSH to apply changes:
sudo systemctl restart ssh
Step 3: Use SSH Key Authentication
- Generate an SSH key pair on your local machine:
ssh-keygen -t rsa -b 4096
- Copy the public key to the server:
ssh-copy-id -p 2222 [email protected]
- Disable password authentication in
/etc/ssh/sshd_config
:
PasswordAuthentication no
- Restart SSH:
sudo systemctl restart ssh
Step 4: Limit SSH Access to Specific Users
- Open the SSH configuration file:
sudo nano /etc/ssh/sshd_config
- Add the following line at the end:
AllowUsers myuser
- Restart SSH to apply changes:
sudo systemctl restart ssh
Step 5: Enable Two-Factor Authentication (2FA) for SSH
- Install the Google Authenticator PAM module:
sudo apt install -y libpam-google-authenticator
- Run the setup for your user:
google-authenticator
-
Follow the prompts and scan the QR code with your 2FA app.
-
Edit the PAM SSH config:
sudo nano /etc/pam.d/sshd
- Add the following line:
auth required pam_google_authenticator.so
- Restart SSH:
sudo systemctl restart ssh
Step 6: Use Fail2Ban to Prevent Brute Force Attacks
- Install Fail2Ban:
sudo apt install -y fail2ban
- Create a custom SSH jail file:
sudo nano /etc/fail2ban/jail.local
- Add the following configuration:
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 5
bantime = 3600
- Restart Fail2Ban:
sudo systemctl restart fail2ban
Conclusion
By following these best practices, you significantly enhance the security of your SSH access. Disabling root login, changing the default port, using key authentication, restricting users, enabling 2FA, and using Fail2Ban will greatly reduce the risk of unauthorized access. Always monitor SSH logs and apply security updates to stay protected.