HARDENING SSH ACCESS

Key-only logins, a sane sshd_config, fail2ban, 2FA, and the VPN endgame that takes port 22 off the public internet.

Hardening SSH access on a dedicated server

 

Hardening SSH access on a dedicated server

SSH is the single door into most dedicated servers, which makes SSH hardening the security job that pays off first. A fresh public IP starts drawing automated login attempts on port 22 within minutes, every hour of every day, forever. The good news is that a secure SSH server is not hard to build: key-only authentication, a short config file, and a couple of supporting tools cover almost the whole risk.

This guide runs the full sequence on Ubuntu 24.04 LTS, with every command ready to paste. It deepens the one-paragraph SSH note in our getting-your-server-online guide, which is the baseline you should already have in place: your own admin user, current patches, and a host firewall. Server.Biz sells unmanaged servers, so the sshd config and the keys are yours to run.

Start with an honest threat model

Internet-wide scanners find port 22 the moment it is reachable. They are not targeting you; they sweep the entire address space continuously, and a login prompt is a login prompt. What they try is cheap and repetitive: common usernames (root, admin, ubuntu, git) against lists of leaked and default passwords, plus a smaller trade in old or exposed private keys. This is credential stuffing at internet scale, and it works often enough to be worth their electricity.

Here is the frame that matters. sshd itself, kept patched, is rarely the hole. Remote code execution bugs in OpenSSH are rare and get fixed fast. The break-ins that happen are almost always credentials and habits: a password that could be guessed, a key with no passphrase copied onto a laptop that got stolen, a root login left enabled, a stale account nobody removed. Fix the credentials and the habits and the scanner noise becomes exactly that, noise.

So the target posture is simple to state. A key-only, patched sshd with root login off gives an opportunistic scanner nothing to work with: no password to guess, no interactive prompt to brute-force, and no path to root even if a lower account leaked. Everything below builds toward that and then goes further.

Minutes
Typical gap between a fresh public IP and the first automated login attempt on port 22
Passwords
The credential class nearly every opportunistic SSH break-in depends on
Key-only
A patched sshd with password auth off leaves scanners nothing to guess

SSH keys done right

Key authentication is the foundation, so get the keys right before touching the server config. Use ed25519: the keys are short, fast, and based on modern elliptic-curve cryptography with no awkward key-size choices to make. Generate one on each device you log in from, always with a passphrase, and never share a single private key between machines. A per-device key means a lost laptop revokes one key, not your access from everywhere.

The passphrase is what protects the key at rest. On its own it would mean typing a long secret on every connection, so ssh-agent holds the decrypted key in memory for your session: you enter the passphrase once and the agent answers challenges after that. This is the everyday workflow, and it is why a passphrase costs almost nothing in practice.

Generate an ed25519 key on your laptop, not on the server. The -a 100 raises the number of passphrase-hashing rounds, which makes a stolen key file slower to crack. The comment after -C is just a label so you can tell keys apart later.

shell
ssh-keygen -t ed25519 -a 100 -C "youruser@laptop-2026"

Start the agent for your session and load the key. You type the passphrase here once; connections after this do not ask again until you log out.

shell
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

Install the public key on the server with ssh-copy-id. Replace youruser and the IP address. This appends your key to the server's ~/.ssh/authorized_keys and fixes the file permissions for you.

shell
ssh-copy-id -i ~/.ssh/id_ed25519.pub youruser@203.0.113.10

Keep authorized_keys tidy on the server. It should hold one line per key you actually use, each with a recognisable comment, and nothing else. Prune keys for devices you no longer own. Treat rotation as a habit rather than a fire drill: generate fresh keys once or twice a year, add the new one, confirm it works, then remove the old line. When a key was on a device you lost, rotate the same day.

The sshd_config that matters

Ubuntu 24.04 ships an sshd_config that includes everything in /etc/ssh/sshd_config.d/ near the top of the file, and the first matching directive wins. That means a drop-in file placed there overrides the defaults cleanly, and you never have to edit the distribution config. Put the whole hardening set in one file so it is easy to read and easy to audit.

Create this drop-in. Set AllowUsers to your real admin username. Each line is explained below the block.

/etc/ssh/sshd_config.d/hardening.conf
# Key-only, no passwords, no interactive fallback.
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes

# Root cannot log in over SSH at all.
PermitRootLogin no

# Cut off guessing and idle sockets fast.
MaxAuthTries 3
LoginGraceTime 20

# Only these accounts may connect. Space-separated list.
AllowUsers youruser

# Nothing here needs X11.
X11Forwarding no

PasswordAuthentication no is the line that ends password guessing outright: with no password accepted, the scanners' entire method stops working. KbdInteractiveAuthentication no closes the interactive fallback that some setups leave open as a second password path. PermitRootLogin no means an attacker cannot aim at root even with the right secret; they must first get a normal account and then escalate, which is a much taller wall. The alternative, prohibit-password, allows root in but only by key, and it exists for one honest case: automation or recovery tooling that must land as root by key. If a human ever logs in as root interactively, use no and sudo instead.

MaxAuthTries 3 drops a connection after three failed attempts in one session, and LoginGraceTime 20 gives an unauthenticated connection twenty seconds to finish before it is closed, which starves slow socket-holding attacks. AllowUsers is the allowlist: only the accounts you name can connect, so a forgotten service account or a new user added later is not reachable over SSH unless you add it here on purpose. AllowGroups works the same way against a group (say, ssh-users) if you would rather manage membership than edit this file per person. X11Forwarding no removes a forwarding surface you almost certainly do not need on a server.

Never reload blind. Validate the config first, and only reload once it parses. The golden rule underneath: keep your current SSH session open the whole time and prove the new config in a second, fresh connection before you trust it. A typo in this file can lock you out. The way back in is then the management console (the BMC, sometimes called IPMI), which support gives you access to on request: it reaches the machine below the firewall and below sshd.

Validate, then reload, never the reverse

This is the pattern for every sshd change in this guide. sshd -t parses the config and prints any error without touching the running service. Only if it is silent do you reload.

Check the config, then reload the service so the running sshd re-reads it. Existing sessions are not dropped by a reload.

shell
sudo sshd -t && sudo systemctl reload ssh

Now, without closing your first session, open a second terminal and connect fresh. Only when this succeeds should you trust the change.

shell
ssh youruser@203.0.113.10

Keep the door open while you test

Your live SSH session survives a reload, so it is your safety line. Never log out of it until a brand-new connection has proven the new config works. If you ever do lock yourself out, ask support for access to the management console: it reaches the server below the firewall, so a bad line can be undone from there.

Port-moving and knocking: what actually helps

Two popular tricks deserve an honest verdict. Moving sshd off port 22 to something like 2222 does one real thing: it drops the volume of automated noise in your logs, because most bulk scanners only hit 22. That is a comfort, not a control. A targeted attacker runs a port scan and finds the new port in seconds, and the security of a key-only sshd is identical on any port number. Change the port if quieter logs help you spot real events, but do not count it as a defence.

Port knocking, where the firewall opens SSH only after you tap a secret sequence of ports, is mostly complexity for its weight. It adds a moving part that can fail and lock you out, it breaks ordinary tooling, and against anyone watching your traffic it offers little. What actually raises the bar is unglamorous and already in this guide: keys only with passwords off, fail2ban to slow and blunt bulk attempts, and, as the real endgame, moving SSH onto a private VPN plane so the public internet cannot reach it at all. Spend effort there, not on obscurity.

fail2ban for sshd

fail2ban watches the auth log and bans an IP that fails too many times, then unbans it later. Be clear about what this buys on a key-only server: it does not stop a break-in that passwords already prevent. Its real value is log hygiene and rate control. It keeps the journal readable by kicking noisy hosts, and it slows credential-stuffing floods so they cannot hammer the service. On Ubuntu 24.04 it reads the systemd journal directly, so there is nothing to point at a log file.

Install and enable it. The service starts watching sshd immediately with sane defaults.

shell
sudo apt update
sudo apt install -y fail2ban
sudo systemctl enable --now fail2ban

Override the defaults in a jail.local so package updates never touch your settings. Put your own trusted IP ranges in ignoreip so you can never ban yourself. Replace 203.0.113.0/24 with your real office or home range.

/etc/fail2ban/jail.local
[DEFAULT]
# Never ban these. Add your own static IPs and ranges here.
ignoreip = 127.0.0.1/8 ::1 203.0.113.0/24

# A first offence: ban for an hour after 5 fails inside 10 minutes.
bantime  = 1h
findtime = 10m
maxretry = 5

# Repeat offenders get progressively longer bans, up to a week.
bantime.increment = true
bantime.factor    = 2
bantime.maxtime   = 1w

[sshd]
enabled = true

Reload fail2ban to pick up the file, then check the jail. The status shows currently banned IPs and running totals.

shell
sudo systemctl reload fail2ban
sudo fail2ban-client status sshd

The escalation is the useful part: a host that keeps trying earns a doubling ban, from an hour toward a week, so persistent scanners take themselves out of your logs for long stretches. The ignoreip whitelist is not optional; without your own ranges in it, a fat-fingered passphrase a few times over can lock you out just like an attacker. If it does, console access through support is again the way back in.

Two-factor where it earns its place

Two-factor authentication on SSH answers one specific risk: a private key that leaks. If your key can never be stolen, a second factor adds friction for little gain, so weigh it against how your keys actually live. Where 2FA fits well is a mixed setup, or one where keys sit on laptops that travel. The clean pattern is to require both a key and a time-based code (TOTP), so a stolen key alone is not enough.

Install the TOTP PAM module and enrol the current user. The interactive tool prints a QR code you scan into an authenticator app, plus recovery codes to store safely.

shell
sudo apt install -y libpam-google-authenticator
google-authenticator

Tell PAM to ask for the code during keyboard-interactive auth. Add this line at the top of the sshd PAM stack.

/etc/pam.d/sshd
auth required pam_google_authenticator.so

Require key AND code together in a second drop-in. The comma means both methods must pass; this deliberately re-enables the interactive prompt that hardening.conf switched off, because the TOTP arrives that way.

/etc/ssh/sshd_config.d/2fa.conf
KbdInteractiveAuthentication yes
AuthenticationMethods publickey,keyboard-interactive

Validate and reload with the same sshd -t pattern, and test in a second session before trusting it, because a broken PAM stack locks out password and key alike. Enrol every user who logs in; a user without a TOTP secret will be refused under this policy. One honest caveat: the recovery codes are a bypass, so store them where a leak of them is as protected as the key itself.

A hardware key is often the better second factor

There is frequently a better second factor than TOTP. A hardware-backed SSH key, ed25519-sk, keeps the private key inside a security token (a YubiKey or similar) that must be physically present and tapped to authenticate. The key cannot be copied off a stolen laptop because it never leaves the token, which removes the exact risk 2FA was added to cover, and there is no code to type. Generate one with the command below and install its public half like any other key. Where hardware tokens are practical for your team, prefer them.

Generate a hardware-backed key. Touch the token when it flashes. The private half stays on the device; only the .pub is ever copied to servers.

shell
ssh-keygen -t ed25519-sk -C "youruser@yubikey"

The tradeoff to weigh honestly: TOTP works from any phone and costs nothing, while ed25519-sk needs a token in every authorised hand but removes the leaked-key risk more completely than a code can. Pick TOTP when keys live on many devices you cannot equip with tokens, and ed25519-sk when you can hand out hardware and want the stronger guarantee.

The VPN pattern: take port 22 off the internet

The strongest move is to stop exposing SSH to the public internet at all. Put the server on a WireGuard VPN, then allow SSH only from the VPN's private range and drop it everywhere else. A scanner sweeping port 22 from outside finds nothing listening, because nothing is. This is the endgame that makes most of the earlier layers a backstop rather than the front line. Our wireguard-vpn-server guide walks the tunnel setup end to end; the firewall change here is what closes the door afterward.

With the VPN up and the server reachable at its tunnel address, allow SSH only from the VPN range (10.8.0.0/24 in the WireGuard guide). This does not open anything to the public internet.

shell
sudo ufw allow from 10.8.0.0/24 to any port 22 proto tcp

Only after you have confirmed SSH works over the VPN in a fresh session, remove the public rule so port 22 is no longer reachable from the open internet.

shell
sudo ufw delete allow 22/tcp
sudo ufw status verbose

The order is the whole safety story. Open the VPN path, prove it in a second session, and only then delete the public rule. If a step goes wrong and you cannot reach the box any longer, ask support for access to the management console, which reaches the server below both ufw and the tunnel.

SSH certificates for teams and scale

authorized_keys works fine for a couple of servers and one or two people. It stops scaling the moment you have a handful of each: every new hire means editing files on every host, every departure means hunting keys down, and stale keys accumulate quietly. An SSH certificate authority (CA) fixes this. You sign each user's key with a CA key, the server trusts the CA once, and access is granted by short-lived certificates instead of files full of public keys.

Create the CA keypair once, on an offline or tightly held machine. Guard the private half like your most important secret; anyone with it can mint access to every server that trusts it.

shell
ssh-keygen -t ed25519 -f ssh_user_ca -C "Server.Biz user CA 2026"

Sign a user's public key. -I is an identity label for the logs, -n lists the principals (the usernames this cert may log in as), and -V sets validity, here twelve weeks. The cert lands next to the key as id_ed25519-cert.pub.

shell
ssh-keygen -s ssh_user_ca -I roy@laptop -n roy,admin -V +12w id_ed25519.pub

On every server, trust the CA in a drop-in and reload. Now any key the CA signs is accepted, with no per-user file to maintain.

/etc/ssh/sshd_config.d/ca.conf
TrustedUserCAKeys /etc/ssh/ssh_user_ca.pub

The payoff is that expiring certificates beat authorized_keys sprawl. Access lapses on its own: a twelve-week cert simply stops working, so a forgotten leaver loses access without anyone editing a single server. Onboarding is one signing command, and principals let you grant someone the admin role on some hosts and not others from the same key. This is real setup work, so it earns its keep from roughly a handful of servers and people upward; below that, well-kept authorized_keys files are simpler.

Auditing and hygiene

Hardening is a state you keep, not a task you finish. Two habits hold the line: know who logged in, and know whose keys are on the box. Both are a couple of commands, and both belong in a periodic check.

See recent logins with source addresses, and read the sshd journal for accepted and failed attempts. This is where you notice a login you did not expect.

shell
last -a | head -n 20
sudo journalctl -u ssh --since "yesterday" | grep -iE "accepted|failed"

Audit every authorized_keys on the machine in one pass. Read the output and question any key or comment you do not recognise.

shell
sudo find /root /home -name authorized_keys -printf '\n== %p ==\n' -exec cat {} \;

Remove a leaver cleanly. Lock the account so it cannot authenticate, then remove it and its home directory once you are sure nothing else depends on it.

shell
sudo usermod --lock --expiredate 1 formeruser
sudo deluser --remove-home formeruser

Removing a person's account takes their keys with it, which is why per-user accounts beat a shared login: revocation is deleting one user, not editing files that everyone shares. Turn the who-logged-in question into an alert rather than a chore by wiring successful logins into monitoring; our self-hosted-monitoring guide covers shipping the sshd journal and firing a notification when a session opens, so an unexpected login reaches you the same minute it happens.

What each measure actually stops

The layers stack, and each one is worth doing on its own. Roughly in order of return for effort:

Measure What it stops Effort
Key-only auth, passwords off Password guessing and credential stuffing outright Low
Root login off + AllowUsers Direct root attacks and access via forgotten accounts Low
fail2ban on sshd Log noise and the pace of bulk brute-force floods Low
2FA (TOTP or ed25519-sk) A leaked or stolen key being enough on its own Medium
SSH behind WireGuard The entire public attack surface on port 22 Medium
SSH certificate authority authorized_keys sprawl and stale access across many hosts Higher, pays off at scale

The short version

Generate a passphrase-protected ed25519 key per device, install it with ssh-copy-id, then put PasswordAuthentication no, PermitRootLogin no and AllowUsers in a sshd_config.d drop-in. Validate with sshd -t and reload while keeping your session open, with console access through support as the way back in. Add fail2ban for log hygiene, 2FA where keys might leak, and, as the real endgame, move SSH behind a WireGuard VPN so port 22 is off the public internet. Do the getting-your-server-online baseline first; it is the ground this stands on.

Continue reading

Need help choosing?

Our experts can help you find the perfect server for your needs.

Contact us »