SSH is the front door to your Linux server, and it is the most attacked service on the internet. The good news: OpenSSH is very secure when configured well, and a handful of settings remove nearly all realistic risk. This guide goes through them in order of importance, explains what each one protects against, and shows how to apply changes without locking yourself out.
Golden rule: keep a session open
Before changing SSH settings:
- Keep your current SSH session open.
- Make the change and validate it with
sudo sshd -t. - Reload SSH and test a new connection from another terminal.
- Only then close the old session.
If something goes wrong, you can still fix it from the open session — or from the VNC console in your control panel, which does not use SSH at all.
Where to put settings
Modern OpenSSH reads drop-in files from /etc/ssh/sshd_config.d/. Put your settings there, in a file that sorts early (OpenSSH uses the first value it finds for most options):
sudo nano /etc/ssh/sshd_config.d/10-hardening.conf
Check that the main /etc/ssh/sshd_config contains Include /etc/ssh/sshd_config.d/*.conf near the top (it does on Ubuntu 22.04+, Debian 12 and RHEL 9 family).
After each change:
sudo sshd -t && sudo systemctl reload ssh # "sshd" on AlmaLinux / Rocky
sudo sshd -T | less # show the effective configuration
1. Use keys, disable passwords
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
This alone defeats password-guessing bots. Set up keys first: SSH key authentication.
2. No root login
PermitRootLogin no
Log in as a normal user and use sudo — see creating a sudo user. If you need root for automation, prohibit-password allows key-only root logins.
3. Allow only specific users or groups
AllowUsers deploy alice
# or
AllowGroups sshusers
Accounts created by packages (databases, web servers) can then never log in over SSH, even if someone sets a password on them. Using a group is easier to manage: sudo groupadd sshusers && sudo usermod -aG sshusers deploy.
4. Limit authentication attempts and time
MaxAuthTries 3
LoginGraceTime 30
MaxStartups 10:30:60
MaxAuthTries: failures allowed per connection.LoginGraceTime: seconds to complete login.MaxStartups: start dropping unauthenticated connections randomly when there are many at once — a defence against connection floods.
If you have many keys loaded in your agent, MaxAuthTries 3 can reject you before the right key is tried. Specify the key with IdentityFile and IdentitiesOnly yes in your ~/.ssh/config.
5. Change the port (optional)
Port 2222
A non-standard port does not stop a determined attacker, but it removes most automated noise from your logs. Before reloading:
- Open the new port in the firewall:
sudo ufw allow 2222/tcp(or firewalld equivalent). - On AlmaLinux/Rocky with SELinux:
sudo semanage port -a -t ssh_port_t -p tcp 2222. - Update Fail2ban’s
port =setting.
On Ubuntu 22.10 and later, SSH may be started by socket activation; there the port is set in ssh.socket. Check with systemctl status ssh.socket. If it is active, run sudo systemctl edit ssh.socket and add:
[Socket]
ListenStream=
ListenStream=2222
Then sudo systemctl daemon-reload && sudo systemctl restart ssh.socket.
6. Disable features you do not use
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no
PermitTunnel no
PermitUserEnvironment no
Port forwarding is useful for some workflows (accessing a database through an SSH tunnel, for example). If you need it, allow it per user with a Match block instead of globally:
Match User deploy
AllowTcpForwarding yes
7. Disconnect idle sessions
ClientAliveInterval 300
ClientAliveCountMax 2
An unresponsive client is disconnected after about 10 minutes. This also cleans up sessions left open by dropped connections.
8. Modern cryptography only
Current OpenSSH defaults are good, but older systems may still offer legacy algorithms. To restrict to modern ones:
KexAlgorithms sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
HostKeyAlgorithms ssh-ed25519,rsa-sha2-512,rsa-sha2-256
sshd -t will complain if an algorithm is not supported by your OpenSSH version — remove it from the list. Very old clients may no longer connect, which is usually the point.
Also regenerate weak host keys if your server still has a DSA or short RSA key (ls /etc/ssh/ssh_host_*).
9. Two-factor authentication (TOTP)
For high-value servers, require a key and a one-time code from an authenticator app:
sudo apt install libpam-google-authenticator # Debian / Ubuntu
google-authenticator # run as the user, scan the QR code
Add to /etc/pam.d/sshd:
auth required pam_google_authenticator.so
And in your SSH config:
KbdInteractiveAuthentication yes
AuthenticationMethods publickey,keyboard-interactive
On Debian/Ubuntu, also comment out @include common-auth in /etc/pam.d/sshd so a password is not requested in addition. Test thoroughly in a second session — 2FA misconfiguration is the most common way to lock yourself out.
10. Restrict by IP address
If you always connect from fixed IPs (office, VPN, a bastion host), allow SSH only from them in the firewall:
sudo ufw allow from 198.51.100.7 to any port 22 proto tcp
sudo ufw delete allow 22/tcp
This is the strongest protection of all, but keep the VNC console in mind for emergencies when your IP changes.
11. Use a jump host for many servers
With several servers, expose SSH on only one hardened bastion and reach the others through it:
# ~/.ssh/config on your computer
Host bastion
HostName 203.0.113.10
User deploy
Host db1
HostName 10.10.0.2
User deploy
ProxyJump bastion
ssh db1 now connects through the bastion automatically. Combined with a WireGuard private network, internal servers need no public SSH at all.
12. Watch the logs
sudo journalctl -u ssh --since today | grep -E "Accepted|Failed"
last -n 20
Accepted lines show successful logins — know which ones are yours. Add Fail2ban to ban noisy IPs automatically.
Complete example
# /etc/ssh/sshd_config.d/10-hardening.conf
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin no
AllowGroups sshusers
MaxAuthTries 3
LoginGraceTime 30
MaxStartups 10:30:60
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no
PermitTunnel no
ClientAliveInterval 300
ClientAliveCountMax 2
Audit your configuration
ssh-audit checks a server’s algorithms and reports weaknesses:
pip install ssh-audit # or download from its project page
ssh-audit 203.0.113.10