Hardening SSH on a Linux server: keys, firewall, fail2ban and tunnels

Published

SSH is how you administer a Linux server, which also makes it the most attacked service on any machine with a public IP. Within minutes of going online, a new server starts receiving automated login attempts from all over the world. Most of them guess passwords. The good news is that a few well-chosen settings remove almost all of that risk.

This guide covers the practical steps for Ubuntu and Debian, in the order that keeps you from locking yourself out: set up keys, tighten the configuration, add a firewall and fail2ban, and learn to use SSH tunnels so you do not need to expose admin pages at all. Replace youruser and server with your own names.

Before you start

  • Keep a second way in. A console from your hosting provider, a hypervisor console, or a keyboard and screen. If you break SSH, this is how you fix it.
  • Keep your current SSH session open while you change settings, and test every change from a second terminal.
  • Make a backup of any file before editing it, for example sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.

1. Create and install an SSH key

On your own computer (not the server), generate a modern key:

ssh-keygen -t ed25519 -C "laptop"

Choose a passphrase. The key file stays on your machine, and the passphrase protects it if the machine is lost. Copy the public half to the server:

ssh-copy-id youruser@server

Now confirm that key login works before changing anything on the server:

ssh -o PreferredAuthentications=publickey youruser@server

If it logs you in (asking only for the key passphrase), you are ready. If it asks for the account password, the key was not installed correctly, so stop and fix that first.

2. Tighten the SSH configuration

Modern Ubuntu and Debian read extra files from /etc/ssh/sshd_config.d/. Putting your changes in a separate file keeps the main config untouched and survives package upgrades. Create /etc/ssh/sshd_config.d/10-hardening.conf:

PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
PermitRootLogin no
PermitEmptyPasswords no
MaxAuthTries 3
LoginGraceTime 30
X11Forwarding no
ClientAliveInterval 300
ClientAliveCountMax 2
AllowUsers youruser

What the important lines do:

  • PasswordAuthentication no and KbdInteractiveAuthentication no: nobody can log in by guessing a password. This is the single biggest improvement.
  • PermitRootLogin no: attackers cannot target the root account directly. Log in as a normal user and use sudo.
  • MaxAuthTries and LoginGraceTime: limit how long and how often a connection can try to authenticate.
  • ClientAlive...: drops idle sessions after about ten minutes of silence.
  • AllowUsers: only the listed accounts may log in over SSH. List every account that needs access, or you will lock one out.

The file name starts with 10- on purpose. SSH uses the first value it reads for each setting, and files are read in alphabetical order. Some cloud images ship a file such as 50-cloud-init.conf that re-enables password login, and yours must come before it.

3. Test, then apply

Check the syntax first. No output means it is valid:

sudo sshd -t

See what the server will actually use, after all files are merged:

sudo sshd -T | grep -E 'passwordauthentication|permitrootlogin|allowusers|authenticationmethods'

Then reload the service. On Ubuntu and Debian it is called ssh; on some other distributions it is sshd:

sudo systemctl reload ssh

Reloading keeps existing sessions alive. Now, without closing your first session, open a new terminal and log in with your key. Then confirm that passwords are really refused:

ssh -o PubkeyAuthentication=no youruser@server

That should fail with Permission denied, without ever asking for a password.

4. Add a firewall

A firewall means only the ports you choose are reachable. On Ubuntu, ufw is simple. Allow SSH before enabling it:

sudo ufw allow OpenSSH
sudo ufw limit OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status verbose

limit rate-limits SSH connections from one address, which slows brute-force attempts. Only open the other ports if the server really hosts websites.

Docker can publish container ports in a way that bypasses ufw rules, so publish only the ports you mean to, and put web apps behind a reverse proxy (see Run Caddy as a standalone reverse proxy in Docker).

If you have a fixed management address or a VPN, you can allow SSH only from there:

sudo ufw allow from 203.0.113.10 to any port 22 proto tcp

The strongest setup is to not expose SSH to the internet at all and reach it through a VPN. See Self-host a WireGuard VPN with wg-easy in Docker.

On cloud providers, apply the same rules in the provider's security groups as well.

5. Add fail2ban

fail2ban reads authentication logs and temporarily blocks addresses that keep failing. Key-only login already makes guessing pointless, but fail2ban reduces log noise and load, and protects other services too.

sudo apt install fail2ban

Create /etc/fail2ban/jail.d/sshd.local:

[sshd]
enabled = true
backend = systemd
maxretry = 5
findtime = 10m
bantime = 1h
ignoreip = 127.0.0.1/8 ::1 192.168.1.0/24

Replace the last range with your own trusted network, so you never ban yourself. Then start it and check:

sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd

To remove a ban by hand:

sudo fail2ban-client set sshd unbanip 203.0.113.50

6. Use SSH tunnels instead of exposing admin pages

Many tools have a web interface that should never be public: database admin pages, dashboards, management consoles. Instead of publishing them, reach them through SSH. A local port forward makes a remote port appear on your own computer:

ssh -L 8080:127.0.0.1:8080 youruser@server

While that session is open, http://localhost:8080 on your computer is the service listening on port 8080 of the server. All traffic travels inside the encrypted SSH connection, and the service itself is never exposed.

If you get channel open failed: connect failed: Connection refused, the server could not reach the target you named. The address after the first colon is resolved from the server's point of view. Check that something is listening there with ss -tlnp on the server, and remember that a Docker container's port is only reachable on the host if it is published or you use the container's own address.

You can also forward to a different machine behind the server, or jump through one:

ssh -L 8443:10.0.0.20:443 youruser@server
ssh -J youruser@server [email protected]

7. Make your life easier on the client

A ~/.ssh/config file saves typing and avoids mistakes:

Host myserver
    HostName server.example.com
    User youruser
    IdentityFile ~/.ssh/id_ed25519
    IdentitiesOnly yes

Now ssh myserver is enough. IdentitiesOnly yes stops your agent from offering every key it knows, which otherwise can trigger "Too many authentication failures".

Use a separate key per device, and remove a lost device's key from ~/.ssh/authorized_keys on the server.

Optional extras

  • Two-factor login: you can require a time-based one-time code in addition to the key by using a PAM module. It adds friction, so it is worth it mainly on high-value servers.
  • Changing the port: moving SSH off port 22 reduces log noise from bots, but it does not stop a targeted attacker. On recent Ubuntu versions the listening port can be controlled by a systemd socket unit, so check your version's documentation before changing it.
  • Restrict a key: in authorized_keys you can prefix a key with options such as from="203.0.113.10" so it only works from one address.
  • Keep the system updated. Security fixes for OpenSSH arrive through normal updates, and unattended-upgrades can apply them automatically.

Troubleshooting

  • Permission denied (publickey): the key is not accepted. Run ssh -v youruser@server to see which keys are offered. On the server, check permissions: ~/.ssh should be 700, authorized_keys should be 600, and the home directory must not be writable by others.
  • Locked out after enabling AllowUsers: your account was not in the list. Use the console, fix the file, and reload.
  • Passwords still work: another file overrides your setting. Check sudo sshd -T | grep passwordauthentication and look in /etc/ssh/sshd_config.d/ for a file that sorts earlier than yours.
  • ssh is not found as a service: try sshd, as the service name differs between distributions.
  • You banned yourself: unban your address with the fail2ban-client command above, and add your network to ignoreip.
  • Connection drops while idle: adjust ClientAliveInterval on the server, or add ServerAliveInterval 60 to your client config.

If everything fails, use the console, delete or rename /etc/ssh/sshd_config.d/10-hardening.conf, run sudo sshd -t, and reload the service. That puts you back on the original configuration.

Checklist

  • Key login tested before anything else is changed
  • Passwords and root login disabled
  • AllowUsers lists the accounts that need access
  • Firewall enabled with SSH allowed first
  • fail2ban running with your own network ignored
  • Admin web pages reached through tunnels or a VPN, not published
  • A console or second session available for recovery

Summary

Key-only login does most of the work. A drop-in config file keeps the changes tidy, the firewall and fail2ban cut down noise, and SSH tunnels or a VPN let you manage private services without exposing them. Make each change carefully, test it from a second terminal, and keep a console handy, and your server will be far harder to attack than the average one on the internet.

← All guides