Put a new VPS on the internet and its SSH port starts collecting login attempts almost immediately, from bots trying common usernames and leaked passwords. The fix everyone recommends is keys only, no passwords, and often a non-default port. The settings themselves are four or five lines. The hard part is applying them without locking yourself out, and making sure they actually take effect, because modern images ship drop-in files that can silently override what you wrote, and recent Ubuntu releases don't even read the port from the place you'd expect.
This guide does it in an order where every step is tested before the next one removes a way back in.
What each change buys you
Be clear about this before you start. Disabling password authentication is the change that matters. A key-only server can't be brute-forced in any practical sense, no matter how many guesses a bot makes. Moving the port is noise reduction. Most mass scanners only try port 22, so your auth log goes quiet and real anomalies stand out, but anyone who scans all ports finds sshd in seconds. It's a reasonable thing to do, as long as you don't count it as protection.
Root login is the third piece. The OpenSSH default for PermitRootLogin is already prohibit-password, which means root can log in with a key. Logging in as a normal user and using sudo is better: you get a per-person audit trail and an attacker has to know a username. That means creating that user first, which is where we start.
Step 1: a sudo user with a working key
On your own machine, create an Ed25519 key if you don't have one, and give it a passphrase. A key without a passphrase is a password stored in a file.
ssh-keygen -t ed25519 -C "laptop-2026"On the server, still logged in as root, create the user and add it to the admin group (sudo on Debian and Ubuntu, wheel on RHEL-family systems):
adduser deploy
usermod -aG sudo deployThen copy the public key from your machine. ssh-copy-id appends it to ~/.ssh/authorized_keys and sets the permissions sshd insists on:
ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@203.0.113.10Now open a new terminal and log in as deploy. It should ask for your key's passphrase (or nothing, if your agent has it), not the account password. Run sudo -v to confirm sudo works. Don't go further until both are true. The full setup for deploy accounts, including restricted sudo rules, is in setting up deploy users with sudo and SSH keys.
Step 2: why editing sshd_config is often not enough
The sshd_config manual has a rule that catches a lot of people: unless noted otherwise, for each keyword the first value sshd reads is the one it uses. Later lines for the same keyword are ignored.
Debian, Ubuntu and current Fedora and RHEL put Include /etc/ssh/sshd_config.d/*.conf at the top of the main file. Included files are read in lexical order, before anything below the Include line. So a drop-in file beats the main file, and a drop-in named 10-… beats one named 50-….
That matters because cloud images write their own drop-ins. Cloud-init, for example, writes its password setting to /etc/ssh/sshd_config.d/50-cloud-init.conf, and on some images that file contains PasswordAuthentication yes. Edit the main file to say no and nothing changes: the drop-in was read first. The same goes for your own file if you name it 99-hardening.conf.
So put your settings in a drop-in that sorts first:
# /etc/ssh/sshd_config.d/00-hardening.conf
Port 22
Port 2222
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
AllowUsers deploy
MaxAuthTries 3
LoginGraceTime 30Some notes on these lines:
Portis one of the keywords that may appear more than once. Listing 22 and 2222 makes sshd listen on both, so you can test the new port while the old one still works. You remove 22 at the end.KbdInteractiveAuthentication nocloses the second way to type a password. With PAM enabled, as it is on Debian and Ubuntu, keyboard-interactive auth can still prompt for the account password even whenPasswordAuthenticationis off.ChallengeResponseAuthenticationis the old, deprecated name for the same option.AuthenticationMethods publickeymakes the intent explicit: a key is the only accepted method.AllowUsersrestricts logins to the listed accounts. Forget to add a second admin here and they're locked out too, so keep the list in mind.MaxAuthTries(default 6) andLoginGraceTime(default 120 seconds) are tightened mainly to free connection slots sooner.
On the port number: stay below 32768. Linux picks source ports for outgoing connections from ip_local_port_range, which defaults to 32768–60999 according to the kernel's networking sysctl docs. A listening port inside that range can, rarely, already be taken by an outgoing connection when sshd starts. Plenty of guides suggest 49152, which falls right in it.
Step 3: test the effective configuration
Two commands, both as root. sshd -t checks syntax and the host keys and prints nothing on success. A typo looks like this, with a non-zero exit:
/etc/ssh/sshd_config.d/00-hardening.conf: line 4: Bad configuration option: PasswordAuthenticaton
/etc/ssh/sshd_config.d/00-hardening.conf: terminating, 1 bad configuration optionssshd -T is the one people skip, and it's the one that answers "did my setting win?". It prints the effective configuration after every include and the first-value rule have been applied. Per the sshd manual, -C evaluates Match blocks for a given connection, which matters if a provider image adds Match rules:
sudo sshd -t
sudo sshd -T -C user=deploy,host=example.com,addr=198.51.100.7 \
| grep -Ei '^(port|permitrootlogin|passwordauthentication|kbdinteractiveauthentication|authenticationmethods|allowusers) 'You want passwordauthentication no in that output. If it says yes, some file read earlier is still setting it: grep -ri passwordauthentication /etc/ssh/ finds it.
Step 4: open the firewall before sshd moves
Allow the new port before sshd listens on it, or you'll test against a closed door. With ufw:
sudo ufw limit 2222/tcp
sudo ufw status numberedA limit rule, documented in the ufw manual, allows the connection but denies a source address that opens 6 or more connections within 30 seconds. It's a cheap brake on scanners, though it can also trip on your own tools if they open many parallel SSH sessions. Use it instead of allow, not as well: ufw stops at the first matching rule, so a plain allow 2222/tcp listed earlier would accept everything before the limit is ever checked. Leave the existing port 22 rule alone for now. If your provider has its own network firewall or security group, open the port there too; it sits in front of ufw and you can't see it from the server.
On RHEL, Fedora and other SELinux systems, sshd is only allowed to bind ports labelled ssh_port_t. Add the label with semanage port -a -t ssh_port_t -p tcp 2222, as the semanage-port manual shows, or sshd will fail to start on the new port.
Step 5: apply it, the way your system expects
On Debian and RHEL-family systems, restart the service. It's called ssh on Debian and Ubuntu and sshd on RHEL:
sudo systemctl restart sshRecent Ubuntu releases are different: they start sshd through socket activation, and the port comes from ssh.socket, not from sshd. A generator reads your sshd config and writes matching ListenStream= lines for the socket. Ubuntu's openssh packaging notes say to run these two commands after changing Port or ListenAddress:
sudo systemctl daemon-reload
sudo systemctl restart ssh.socketRestart only ssh.service on such a system and the authentication settings apply but the port doesn't move. Run systemctl is-active ssh.socket to see which setup you have, and ss -tlnp | grep -E ':(22|2222)\b' afterwards to see what's listening.
Your current session normally survives either restart, since each connection has its own sshd process and the packaged units use KillMode=process (check yours with systemctl show ssh -p KillMode). Keep it open anyway. It's your way back in.
Step 6: test from a second terminal, then remove port 22
Add a host entry on your machine so you never have to remember the port:
# ~/.ssh/config
Host myvps
HostName 203.0.113.10
User deploy
Port 2222
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yesThen check three things from a new terminal: ssh myvps logs you in; ssh -p 2222 root@203.0.113.10 is refused; and a password login is refused, which you can force with ssh -o PubkeyAuthentication=no -p 2222 deploy@203.0.113.10. The last two should end in Permission denied (publickey)., which tells you the server offers nothing but key authentication.
When all three pass, delete the Port 22 line, run sshd -t, apply again as in step 5, and close the old port in the firewall with sudo ufw delete allow 22/tcp (or by its number from ufw status numbered; if you added the default OpenSSH profile, delete that instead). Leaving 22 open in the firewall after sshd stops listening on it doesn't expose anything, but it makes your rule set lie about what's running.
If you lock yourself out anyway
Every VPS provider has a web or serial console that doesn't go through SSH. Log in there as root (with the root password, which still works on the console because sshd settings don't apply to it), fix the drop-in, run sshd -t and restart. Find that console before you change anything, and make sure you know the root password or have a recovery path, because some providers' consoles need it.
The most common lockouts, in order: the firewall or provider security group doesn't allow the new port, the key is in root's authorized_keys but not the new user's, AllowUsers doesn't list the account, and on Ubuntu the socket still listens on 22 only because ssh.socket wasn't restarted.
With passwords off, the auth log becomes useful: it's mostly key failures from bots, and a successful login from an address you don't recognise is worth an alert. Watching for that, along with the usual disk and memory checks, is part of self-hosted server monitoring. If you run your own long-lived services on the box, sandboxing systemd services is the natural next layer.














