How to Harden SSH Access Without Locking Yourself Out

To harden SSH access, switch from password authentication to public key authentication and then restrict who can reach the daemon at all. Do it in that order, and keep an independent path back into the machine open at every step, because the failure mode here is not a subtle bug: it is you, locked out of your own server.

The mechanics are simple enough. SSH is a stateful TCP protocol. The client connects, both sides negotiate algorithms, they perform a key exchange, and the server authenticates the client. The server decides which authentication methods it will offer based on its configuration and on the client's identity. When you harden SSH access, you are changing that server side policy: which methods are allowed, which users may log in, and from which addresses. The client does what it is told.

Before you touch anything: open a second session

Every change below takes effect on new connections, not on the one you are already using. That is your safety net, but only if you use it deliberately. Open a second terminal and log in over SSH as the same user. Keep that session open and idle while you make changes. If your next test connection fails, you still have a working shell to revert the config.

Better still, have a console. Most providers offer an out of band serial console or a web based terminal that does not depend on sshd at all. If you have one, you can recover from almost any SSH mistake. If you do not, treat the idle session as your only lifeline and do not close it until you have proven the new configuration works from a fresh connection.

Set up keys properly before disabling passwords

Key authentication works because the client proves possession of a private key without sending it. The server checks the corresponding public key against ~/.ssh/authorized_keys for that user. Your job is to get the right public key into that file, with the right permissions, before you remove the password fallback.

On your workstation, if you do not already have a key, generate one. Ed25519 is the sensible default for new keys:

ssh-keygen -t ed25519 -a 100 -C "you@workstation"
# creates ~/.ssh/id_ed25519 and ~/.ssh/id_ed25519.pub

Copy the public half to the server with ssh-copy-id, or paste the contents of the .pub file into ~/.ssh/authorized_keys on the server. Then verify the permissions, because sshd is strict and will silently ignore a key file it considers too open:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
ls -ld ~/.ssh ~/.ssh/authorized_keys

The expected shape is a directory with mode drwx------ and a file with -rw-------, both owned by the user who will log in. If the home directory itself is group writable, key authentication can fail for the same reason. Test a key login in your second session before going further.

Harden sshd_config without breaking your way in

The daemon reads /etc/ssh/sshd_config and any files included from /etc/ssh/sshd_config.d/ on most modern distributions. Directives set in an included file usually take precedence over the main file, and the first value seen for a given keyword wins, so check both places before you assume a setting is in force. Ask the daemon what it actually thinks, rather than what you believe you wrote:

sudo sshd -T | grep -Ei 'passwordauth|permitroot|pubkeyauth|allowusers|port|listen'
# passwordauthentication no
# permitrootlogin no
# pubkeyauthentication yes

sshd -T prints the effective configuration, which is the only version that matters. Once you are happy with what it shows, the directives you want are these:

PasswordAuthentication no
PubkeyAuthentication yes
PermitRootLogin no
AuthenticationMethods publickey
AllowUsers deploy ops

AuthenticationMethods publickey is the belt and braces line: it refuses password authentication even if something elsewhere re-enables it. AllowUsers is an allowlist, so anyone not named cannot authenticate at all, regardless of their key. That is a blunt instrument and a useful one. If you need finer control, Match blocks let you apply different rules per user or per source address.

Validate before you reload. A syntax error in the config will stop the daemon from restarting, and if you have already closed your sessions you are now locked out:

sudo sshd -t && sudo systemctl reload sshd

Reload, not restart, keeps existing connections alive. Then, from a third terminal, open a brand new connection and confirm you get in with your key and are refused with a password. Only after that should you close the idle session.

Restrict who can reach port 22 at all

Authentication hardening assumes an attacker can reach the daemon. The next layer is to stop most of them from doing so. Two mechanisms matter: a host firewall and a filtering layer in front of the host.

On the host, allow SSH only from addresses you control. With a firewall front end that manages rules for you, the shape is roughly:

sudo ufw allow from 203.0.113.0/24 to any port 22 proto tcp
sudo ufw enable
sudo ufw status verbose

Note the ordering trap. Enabling a default deny policy before adding your allow rule cuts your own connection. Add the allow rule first, confirm it is listed, and only then flip the default. The same logic applies to other firewall tools: write the rule, list it, then enforce.

For anything internet facing, a bastion or jump host is worth the effort. You close port 22 to the world on the application servers and permit SSH only from the bastion's address. Operators then reach the private hosts through ssh -J:

ssh -J bastion.example.net [email protected]

This gives you one hardened entry point to monitor instead of many, and it means a leaked key on a back end host is useless without a route to it. Some providers also offer a firewall at the network edge, outside the host, which keeps working even if the host's own firewall is misconfigured. Use both where you can: the edge rule protects you from host mistakes, and the host rule protects you from edge mistakes.

Keep a working way back in

Assume a key gets corrupted, a firewall rule goes wrong, or an allowlist excludes the one user who can fix it. Plan for recovery before you need it. Keep at least two independent keys in authorized_keys, stored in different places, so a lost or revoked one does not strand you. Keep a copy of the working sshd_config outside the directory you are editing, so a bad edit is a one line restore. Know how to reach the out of band console and how long it takes to get a session, because that is the real recovery time if everything else fails.

Log authentication activity somewhere you will see it. The journal records accepted and failed logins, and a sudden run of failures against a single user is the signal you care about:

sudo journalctl -u sshd --since "1 hour ago" | grep -i 'failed\|accepted'

Turn on key based logins first, prove them from a fresh connection, then disable passwords, then restrict source addresses, testing at each stage with an independent session open. Do the layers in that order and a mistake costs you a few minutes rather than an outage. Start with keys and a second session today; the firewall and bastion work can follow once you trust the first layer.

Related articles

Subscribe to our newsletter

Get the latest hosting tips, performance insights, and industry news.