Security

Secure SSH on Ubuntu: keys, no passwords, fail2ban

Key-only logins, a hardened sshd_config.d file, the Ubuntu 24.04 socket-activation trap when you change the port, and fail2ban, each step tested on Ubuntu 24.04.

TL;DR

  • Log in with an SSH key as your own user with sudo, then turn off password and root logins in a file of your own in /etc/ssh/sshd_config.d/.
  • OpenSSH keeps the first value it reads and Ubuntu reads the sshd_config.d files before the main file, in name order: name yours 10-something so a cloud image's 50-cloud-init.conf cannot turn passwords back on.
  • Check with sudo sshd -t and sudo sshd -T before you reload, keep your current session open until a new login works, then add fail2ban.
  • On Ubuntu 24.04 SSH starts through a systemd socket, so a new Port needs systemctl daemon-reload and systemctl restart ssh.socket; restarting ssh alone keeps port 22.
On this page

To secure an SSH server on Ubuntu, log in with a key as your own user with sudo instead of root, and turn off password and root logins in a file of your own under /etc/ssh/sshd_config.d/. Check it, reload, and prove from a second terminal that your key still works and a password does not; then add fail2ban and a firewall rule for SSH. On Ubuntu 24.04, a cloud image's own file can quietly win over yours, and changing the port needs two extra commands.

This is the first step of our checklist for hardening an Ubuntu 24.04 server. Every command here was run on Ubuntu 24.04.5 LTS (OpenSSH 9.6p1, fail2ban 1.0.2) on 11 November 2026, in two containers that run systemd like a server does: one as the server, one as the laptop logging in.

What Ubuntu 24.04 does differently

Drop-in files come first, and the first value wins. Ubuntu's /etc/ssh/sshd_config starts with Include /etc/ssh/sshd_config.d/*.conf, and OpenSSH's manual says that "for each keyword, the first obtained value will be used". So the files in sshd_config.d override the main file, and among them the one whose name sorts first wins. Put your settings in your own file there instead of editing the main one: package upgrades leave it alone.

Cloud images bring their own file. cloud-init, which sets up many cloud servers on their first boot, can write /etc/ssh/sshd_config.d/50-cloud-init.conf with a PasswordAuthentication line. We tested the effect: with PasswordAuthentication yes in 50-cloud-init.conf, our 10-hardening.conf still won and sshd -T showed passwordauthentication no; renamed to 60-hardening.conf, ours lost and passwords were on again. Name your file with a low number.

SSH starts through a systemd socket. On 24.04, ssh.socket holds port 22 and starts sshd when the first connection arrives, so ssh.service can show as inactive on a healthy server. Ubuntu's own sshd_config says so in a comment: after changing Port, AddressFamily or ListenAddress, run systemctl daemon-reload and systemctl restart ssh.socket.

Before you start: keep a way back in

A mistake in the SSH configuration can lock you out of a server that only answers SSH. Two habits make that harmless:

  • Keep your current session open until a fresh login in a second terminal works. A reload doesn't end sessions that are already open.
  • Know your provider's console. Hetzner Cloud's console and DigitalOcean's Recovery Console open the server's screen in your browser, without SSH; DigitalOcean (opens in a new tab)'s works even when sshd has failed. You log in there with a password, not a key, so the password you give your user in step 1 is your way back. Find the console before you need it.

1. Create your own user with sudo

Logging in as root means every typo runs with full power, and every attacker knows the user name. Create a user for yourself (we use deploy throughout; any name works) and give it sudo:

sudo adduser deploy
sudo usermod -aG sudo deploy

adduser asks for a password. Set a long one: with password logins off, it is used by sudo and by the provider's console, never for SSH.

2. Put your key on the server

If you don't have a key yet, make one on your own computer. Ed25519 keys are short and fast, and Ubuntu's documentation recommends them:

ssh-keygen -t ed25519 -C "you@laptop"

While password logins still work, copy the public half from your computer with ssh-copy-id:

ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@your-server

If you created the server with a key and log in as root, copy root's key to the new user instead, on the server:

sudo install -d -m 700 -o deploy -g deploy /home/deploy/.ssh
sudo install -m 600 -o deploy -g deploy /root/.ssh/authorized_keys /home/deploy/.ssh/authorized_keys

Now open a second terminal and log in as the new user:

ssh deploy@your-server
sudo whoami   # prints root

Don't go on until this works.

3. Write your hardening file

Create /etc/ssh/sshd_config.d/10-hardening.conf:

# Keys only: no passwords, no keyboard-interactive prompts
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthenticationMethods publickey
# No direct root logins; use your own user and sudo
PermitRootLogin no
# Only these users may log in over SSH
AllowUsers deploy
# Fewer tries per connection, less time to log in
MaxAuthTries 3
LoginGraceTime 30
# Features a web server does not need
X11Forwarding no
What each line does, with OpenSSH's default
SettingDefaultWhy change it
PasswordAuthentication noyesNobody can guess their way in.
KbdInteractiveAuthentication noyes upstream; Ubuntu's file already sets noCloses the other way a password can be asked for, through PAM.
AuthenticationMethods publickeyanyOnly a key completes a login, whatever another file says.
PermitRootLogin noprohibit-passwordroot can't log in at all, even with a key.
AllowUsers deployeveryoneAccounts a package creates can never log in over SSH. List every user who needs SSH, separated by spaces.
MaxAuthTries 36Fewer key or password tries per connection.
LoginGraceTime 30120 secondsHalf-open logins are dropped sooner.
X11Forwarding nono upstream; Ubuntu's file sets yesA server has no use for remote graphical windows.

Warning

AllowUsers locks out every user it doesn't name, root included. If your deploy workflow logs in as another user, add that user to the line before you reload.

4. Check, then reload

Check the syntax first. sshd -t prints nothing when the configuration is valid:

sudo sshd -t

Then read the values SSH will really use, which catches a file that loses to another one:

sudo sshd -T | grep -E '^(passwordauthentication|kbdinteractiveauthentication|authenticationmethods|permitrootlogin|allowusers|maxauthtries) '

In our test it printed:

maxauthtries 3
permitrootlogin no
passwordauthentication no
kbdinteractiveauthentication no
allowusers deploy
authenticationmethods publickey

Then apply it. Ubuntu's documentation restarts the service (sudo systemctl restart ssh.service); we reload instead, which also keeps open sessions connected:

sudo systemctl try-reload-or-restart ssh

Plain reload can fail: with socket activation, ssh.service stays inactive until the first connection after a boot (or after the socket restarts), and in our test systemctl reload ssh then failed with "ssh.service is not active, cannot reload". try-reload-or-restart does nothing in that case, which is right: the next connection starts a fresh sshd that reads the new file. While you are logged in over SSH the service is active, and it simply reloads.

5. Prove it from outside

From your computer, in a new terminal, check both sides:

# Your key still works
ssh deploy@your-server whoami

# A password-only attempt is refused
ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password deploy@your-server

The second command must end with Permission denied (publickey). without ever asking for a password. In our test, root was refused too, even with a valid key in its authorized_keys, and the server's log said why:

sshd[1657]: User root from 172.21.0.3 not allowed because not listed in AllowUsers

Only now close your first session.

Changing the SSH port on Ubuntu 24.04

If you move SSH off port 22, do it in this order, because a firewall that doesn't know the new port locks you out:

  1. Allow the new port in your firewall: sudo ufw allow 2222/tcp, and in the provider's firewall if you use one.

  2. Add the port to your own file, or to a new one, such as /etc/ssh/sshd_config.d/20-port.conf with the single line Port 2222.

  3. Check it, then regenerate and restart the socket:

    sudo sshd -t
    sudo systemctl daemon-reload
    sudo systemctl restart ssh.socket
  4. Log in on the new port from a second terminal (ssh -p 2222 deploy@your-server) before you remove the old firewall rule. Update fail2ban (its port setting), your deploy workflow and any monitoring that connects over SSH.

We tested what happens without step 3's last two commands: after systemctl restart ssh, the server still listened on port 22 only. After daemon-reload and restart ssh.socket, it listened on 2222 only, because a generator writes the socket's ListenStream lines from sshd_config:

# /run/systemd/generator/ssh.socket.d/addresses.conf
[Socket]
ListenStream=
ListenStream=0.0.0.0:2222
ListenStream=[::]:2222

Add fail2ban

fail2ban reads the login log and blocks addresses that keep failing. On Ubuntu 24.04 it is ready for SSH as soon as it is installed:

sudo apt install fail2ban

The package ships /etc/fail2ban/jail.d/defaults-debian.conf, which turns on the sshd jail, reads SSH's messages from the systemd journal (backend = systemd) and bans with nftables. The defaults from fail2ban's jail.conf apply: five failures within ten minutes ban the address for ten minutes. To keep repeat offenders out longer, create /etc/fail2ban/jail.local:

[sshd]
enabled  = true
maxretry = 5
findtime = 10m
bantime  = 1h

Then restart it and look at the jail:

sudo systemctl restart fail2ban
sudo fail2ban-client status sshd

We tested it from the second container: six login attempts as a user that doesn't exist, then the status showed the address under Banned IP list, its next connection got Connection refused, and the ban lived in fail2ban's own nftables table:

table inet f2b-table {
	set addr-set-sshd {
		type ipv4_addr
		elements = { 172.21.0.3 }
	}
	chain f2b-chain {
		type filter hook input priority filter - 1; policy accept;
		tcp dport 22 ip saddr @addr-set-sshd reject with icmp port-unreachable
	}
}

If you ban yourself, wait for the ban to end, log in from another address, or use the provider's console and run:

sudo fail2ban-client set sshd unbanip 203.0.113.10

To never ban your own fixed address, add it to ignoreip under [DEFAULT] in jail.local: ignoreip = 127.0.0.1/8 ::1 203.0.113.10.

Limit who can reach SSH at all

Keys decide who can log in; a firewall decides who can even try. Two places can hold the rule:

ufw on the server. Allow SSH before you turn ufw on, or you cut your own connection:

sudo ufw allow OpenSSH
sudo ufw enable

OpenSSH is the application profile the openssh-server package installs; it means TCP port 22. If you always connect from a fixed address, allow only that one instead: sudo ufw allow from 203.0.113.10 to any port 22 proto tcp.

The provider's firewall. Hetzner Cloud Firewalls and DigitalOcean Cloud Firewalls are free, and both block inbound traffic that no rule allows. They are applied outside your server, so nothing on the server can open a hole in them. That matters on a Docker (opens in a new tab) host, where published ports bypass ufw, as we show in Docker ignores your UFW firewall. SSH itself is not affected, but the provider's firewall is the one place that covers every port.

The strongest option is not to expose SSH to the internet at all: put your laptop and the server on a private WireGuard (opens in a new tab) network and let SSH answer only there. It is more work to set up and to recover from, so do it once the basics above are in place.

More ways to secure an SSH server on Ubuntu

  • Keep the server patched. OpenSSH fixes reach you through Ubuntu's security updates; check they install by themselves with our guide to automatic security updates on Ubuntu.
  • Two-factor logins with a hardware key (FIDO/U2F) or a one-time code are documented in Ubuntu's server guide. Worth it for a server several people reach.
  • Watch the log. sudo journalctl -u ssh --since today shows today's logins and refusals. Our guide to monitoring a small server covers alerts.
  • The deploy key. A GitHub Actions (opens in a new tab) deploy usually logs in as a user in the docker group, and Docker's documentation warns that this group grants root-level privileges. Treat that key like a root key: one per server, kept only in the repository's encrypted secrets.
  • The rest of the server. The Ubuntu server hardening checklist covers the firewall, updates, backups and monitoring.

Doing this with OpsCrew

OpsCrew is an open-source tool that sets up and checks servers like this one, and shows every change before it makes it. On a server it creates at Hetzner Cloud (opens in a new tab) or DigitalOcean, or on a server you already have, it sets up a deploy user with key-only SSH, no password logins, SSH limited to modern algorithms, a firewall that lets in only SSH and web traffic, and fail2ban (what OpsCrew sets up).

On your own server, the SSH settings go into their own file, /etc/ssh/sshd_config.d/10-opscrew.conf, checked with sshd -t before SSH reloads, and they run under a safety switch: the server schedules its own undo, and OpsCrew cancels it only after new logins work, so a bad change puts the old settings back by itself. Each change is listed in a host plan you approve first. npx opscrew secure checks the hardening over SSH, and --deep adds ssh-audit and Lynis. Once your computer is on the app's private network, OpsCrew can also close public SSH entirely.

Key facts

FactValueSource
OpenSSH's default for PasswordAuthenticationyesPassword logins are on unless a configuration file turns them off.sshd_config(5), OpenBSD manual pages (opens in a new tab)Verified on
OpenSSH's default for PermitRootLoginprohibit-passwordroot may log in with a key, not with a password.sshd_config(5), OpenBSD manual pages (opens in a new tab)Verified on
Which value wins when a setting appears twiceThe first one sshd reads"Unless noted otherwise, for each keyword, the first obtained value will be used." Ubuntu's sshd_config includes /etc/ssh/sshd_config.d/*.conf on its first lines.sshd_config(5), OpenBSD manual pages (opens in a new tab)Verified on
fail2ban's default ban5 failures within 10 minutes ban an address for 10 minutesmaxretry, findtime and bantime in fail2ban 1.0.2's jail.conf, the version Ubuntu 24.04 ships.fail2ban 1.0.2, config/jail.conf (opens in a new tab)Verified on
Versions in this article's testsUbuntu 24.04.5 LTS, OpenSSH 9.6p1 (package 1:9.6p1-3ubuntu13.20), fail2ban 1.0.2, ufw 0.36.2Tested on 11 November 2026 in containers running systemd.Ubuntu 24.04 LTS release notes (opens in a new tab)Verified on

Frequently asked questions

Is changing the SSH port worth it?

It cuts the number of automated login attempts in your logs, but it does not stop anyone who scans all ports, and with password logins off those attempts cannot succeed anyway. Change it if the log noise bothers you, after keys-only is in place.

Do I still need fail2ban if I only allow SSH keys?

It is no longer what keeps attackers out, because there is no password to guess. It still blocks addresses that keep trying, which cuts load and log noise, and it protects you if a password login is turned on again by mistake.

Sources

  1. OpenSSH server (Ubuntu Server documentation) (opens in a new tab), Canonical, accessed on
  2. Ubuntu 24.04 LTS release notes (opens in a new tab), Canonical, accessed on
  3. sshd_config(5) (opens in a new tab), OpenBSD (OpenSSH), accessed on
  4. Cannot disable PasswordAuthentication due to 50-cloud-init.conf (issue 5934) (opens in a new tab), Canonical (cloud-init), accessed on
  5. Module reference, ssh_pwauth (cloud-init documentation) (opens in a new tab), Canonical (cloud-init), accessed on
  6. fail2ban 1.0.2, config/jail.conf (opens in a new tab), fail2ban, accessed on
  7. Hetzner Cloud Firewalls overview (opens in a new tab), Hetzner, accessed on
  8. DigitalOcean Cloud Firewalls (opens in a new tab), DigitalOcean, accessed on
  9. How to Connect to a Droplet with the Recovery Console (opens in a new tab), DigitalOcean, accessed on
  10. Hetzner Cloud console (VNC) (opens in a new tab), Hetzner, accessed on
  11. Linux post-installation steps for Docker Engine (opens in a new tab), Docker, accessed on
Edit this article
  • Deploying

    Cloudflare Tunnel for a self-hosted app: setup, Docker and SSH

    What a Cloudflare Tunnel is, quick tunnels and named tunnels, a tested Docker Compose setup with a tunnel token, SSH through Cloudflare Access, and the limits that come with sending every request through Cloudflare.

    11 min read

  • AI and DevOps

    Is it safe to let AI run commands on your server?

    It can be, with limits. The five real risks of giving an AI agent server access (destructive commands, leaked secrets, prompt injection, broad credentials, unreviewed changes), from OWASP and the vendors' docs, and the controls for each.

    11 min read

  • Deploying

    Deploy a Docker Compose app to Hetzner with GitHub Actions

    A Hetzner Cloud server set up by a tested cloud-init file, behind Hetzner's firewall, updated by a GitHub Actions workflow that builds your image, pushes it to GHCR and deploys it over SSH.

    10 min read

Put OpsCrew to work on your app.

Run npx opscrew init in your app's repository. It checks your tools and tokens first, for free.