Open SSH configuration file
sudo nano /etc/ssh/sshd_config
Recommended Options to Harden SSH Configuration
1. Limit the Number of Concurrent Sessions (per connection)
MaxSessions 2
Controls the maximum number of sessions per network connection. Lowering this reduces exposure to excessive simultaneous sessions.
2. Limit Unauthenticated Connection Attempts
MaxStartups 10:30:60
Limits unauthenticated connections:
- Allows up to 10 unauthenticated connections freely.
- Starts dropping connections at a rate of 30%.
- Refuses connections entirely after 60 attempts.
3. Use a Non-Standard Port for SSH
Port 2222
Changing the default SSH port (22) can reduce the likelihood of random attacks.
Note: Remember to allow this port in the firewall (e.g., sudo ufw allow 2222/tcp).
PermitRootLogin no
Disabling root login reduces the risk of brute-force attacks on the root account.
Instead, use a regular user with sudo privileges.
5. Allow Only Specific Users
AllowUsers your_username
Limits SSH access to specific users. Replace "your_username" with the actual username(s).
This reduces the attack surface by preventing login attempts for other accounts.
6. Disable Password Authentication (Use SSH Keys Only)
PasswordAuthentication no
Enforcing SSH key-based authentication eliminates the risk of password brute-forcing.
7. Set Client Timeout to Automatically Disconnect Idle Sessions
ClientAliveInterval 300
ClientAliveCountMax 2
Closes inactive sessions after a set period, reducing resource strain from idle connections.
- ClientAliveInterval 300: Sends a null packet every 300 seconds (5 minutes) to keep the connection alive.
- ClientAliveCountMax 2: Disconnects the client after 2 missed responses (10 minutes of inactivity).
8. Enable Rate-Limiting with UFW or iptables (Separate from sshd_config)
sudo ufw limit 22/tcp
Limits repeated connection attempts for SSH (default 6 attempts per 30 seconds).
If using iptables (alternative):
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
This limits connections to 3 per minute from any single IP.
Save Changes and Restart SSH Service
sudo systemctl restart sshd