SSH is the front door of almost every Ubuntu server, and it is attacked constantly. The good news: a few settings remove nearly all of that risk. This lesson takes you from a default install to key-only, named-user, validated SSH with a safe sudo policy.
Keep your current session open. Do not close the SSH session you are using until a second session proves the new settings work. Have console access ready.
Step 1: update first
sudo apt update && sudo apt full-upgrade -y
sudo reboot # if /var/run/reboot-required existsHardening a stale system is wasted effort, because known flaws outrank configuration.
Step 2: named admins, no shared accounts
Each human gets their own account, so logs show who did what.
sudo adduser alice # create the user
sudo usermod -aG sudo alice # give admin via the sudo group
sudo passwd -l root # lock root's password (sudo still works)Step 3: generate and install an SSH key
On your workstation (not the server):
ssh-keygen -t ed25519 -a 100 -C "alice@workstation"
ssh-copy-id alice@SERVER_IP
ssh alice@SERVER_IP # confirm key login works BEFORE disabling passwordsed25519 keys are small, fast and strong. Protect the private key with a passphrase, and keep it off shared machines.
Step 4: the sshd hardening drop-in
Ubuntu reads extra settings from /etc/ssh/sshd_config.d/*.conf. Use a drop-in rather than editing the main file, so package upgrades never overwrite your work.
sudo tee /etc/ssh/sshd_config.d/00-hardening.conf >/dev/null <<'EOF'
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
PermitEmptyPasswords no
MaxAuthTries 3
LoginGraceTime 30
MaxSessions 4
ClientAliveInterval 300
ClientAliveCountMax 2
X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no
AllowGroups sshusers
LogLevel VERBOSE
EOF
sudo groupadd -f sshusers && sudo usermod -aG sshusers aliceThe first-match-wins trap. For most sshd settings the first value read wins, and drop-ins are read in filename order. Cloud images often ship
50-cloud-init.confcontainingPasswordAuthentication yes. If your file sorts after it, your setting is silently ignored. Name yours00-hardening.confso it is read first, then prove the result withsshd -Tbelow.
Notes on the choices:
AllowGroups sshusersis an allow-list: only members may log in. Add every admin to the group before you reload.AllowTcpForwarding nostops SSH being used as a tunnel. If you rely on tunnels or jump hosts, relax it for the specific users that need it.- Modern OpenSSH already defaults to strong ciphers and key exchange. Do not cargo-cult long
Cipherslists; they age badly.
Step 5: validate, reload, test
sudo sshd -t # syntax check: no output means OK
sudo sshd -T | grep -Ei 'permitrootlogin|passwordauthentication|authenticationmethods|allowgroups|maxauthtries'
sudo systemctl reload ssh # apply without dropping sessionsNow open a second terminal and log in as alice with the key. Then confirm the bad paths are closed:
ssh -o PubkeyAuthentication=no alice@SERVER_IP # should be refused: no password login
ssh root@SERVER_IP # should be refusedA note on ports and socket activation. On recent Ubuntu releases the SSH daemon is socket-activated (
ssh.socketlistens and starts sshd). That means thePortsetting insshd_configcan be ignored; changing the port means editing the socket unit, and guides disagree on the exact steps across releases. Moving SSH to another port is obscurity, not security. Skip it unless you have a specific reason, and if you do, test on a throwaway VM first. Check what is in charge withsystemctl status ssh ssh.socket.
Step 6: a safe sudo policy
Ubuntu 26.04 ships
sudo-rs(a Rust rewrite) as the default sudo, with the original kept assudo.ws. Everyday use is the same, but sudo-rs supports a subset of sudoers options. After any edit, runsudo visudo -cand test in a second session.
sudo visudo -f /etc/sudoers.d/10-hardeningDefaults use_pty
Defaults timestamp_timeout=5sudo visudo -c # must report the files parse OK
sudo -l # what can I run? (test as alice)
journalctl _COMM=sudo --since today # sudo activity is logged to the journalRules of thumb: grant sudo through groups, avoid NOPASSWD except for narrow, specific commands, and never edit /etc/sudoers directly (always visudo).
Step 7: password quality and an account audit
Key-only SSH makes password rules matter less for remote login, but local and sudo passwords still count.
sudo apt install -y libpam-pwquality
sudo sed -i 's/^# *minlen.*/minlen = 14/' /etc/security/pwquality.confAudit what already exists:
awk -F: '($3==0){print $1}' /etc/passwd # only root should be listed
sudo awk -F: '($2==""){print $1}' /etc/shadow # accounts with EMPTY passwords (should be none)
sudo awk -F: '($2!~/^[!*]/){print $1}' /etc/shadow # accounts that can log in with a password
getent group sudo # who has admin
lastlog | grep -v 'Never' # who has ever logged in
sudo passwd -l olduser # lock accounts nobody needsWant MFA on SSH? Add
libpam-google-authenticatorand requirepublickey,keyboard-interactiveinAuthenticationMethods. It adds real protection for internet-facing admin hosts, but test thoroughly and keep a break-glass path.
Back-out: delete /etc/ssh/sshd_config.d/00-hardening.conf, run sudo sshd -t && sudo systemctl reload ssh, or restore your snapshot from the console.
🧪 Lab
- Create a named admin, generate an ed25519 key, install it and confirm key login.
- Apply the drop-in, validate with
sshd -tandsshd -T, reload, and test from a second session. - Prove password login and root login are refused.
- Run the account audit commands and lock anything you cannot justify.
Checkpoint
- Why name the drop-in
00-hardening.confrather than99-hardening.conf? - What do
sshd -tandsshd -Teach tell you? - Why keep a second SSH session open while changing settings?
- Why is changing the SSH port not a real security control?
- What command checks the sudoers files after an edit, and why is it especially important on Ubuntu 26.04?