Chapter 10 · Lesson 1 of 10
Server security

Harden SSH server configuration (sshd drop-in file)

Hardening SSH means restricting sshd to key-based logins for named users and no root login, set in a drop-in file and validated with sshd -t before you reload.

By the end you will

Lock sshd down to key-only logins for named users with a drop-in file, validate it and reload without losing access.

Time
20 min
Level
Intermediate
Check
4 questions
You need
  • An Ubuntu or Debian server with a sudo user
  • Working SSH key login

How a hardened SSH server decides who gets in

A hardened server lets SSH through the firewall, accepts only keys, and only for the users you list.
  1. Your connection reaches the firewall, which lets SSH through, optionally only from your own address.
  2. The firewall passes the connection to sshd, the SSH daemon.
  3. sshd refuses passwords and asks for a key, because PasswordAuthentication is set to no.
  4. Your laptop proves it holds the private key, which never leaves it.
  5. sshd checks AllowUsers and PermitRootLogin, then opens a shell for your named user, never for root.
Static diagram
  1. Your laptopport 22Firewall
  2. Firewallallowedsshd
  3. sshdkey onlyYour laptop
  4. Your laptopsigned keysshd
  5. sshdAllowUsersShell

To harden SSH on an Ubuntu or Debian server, put your restrictions in a small drop-in file under /etc/ssh/sshd_config.d/, validate it with sshd -t, reload the service, and test a fresh login before you close the session you started with. The three settings that matter most are key-only authentication, no direct root login, and a list of the users allowed to log in at all.

A mistake here can lock you out of the server. Read the whole lesson before you change anything, and do not skip the second-session step.

How it works#

sshd is the SSH daemon. It reads /etc/ssh/sshd_config at start and on reload. On current Ubuntu and Debian releases that file begins with a line like Include /etc/ssh/sshd_config.d/*.conf, which pulls in every .conf file from the drop-in directory, in alphabetical order. Your own file lives there, so a package upgrade that replaces the main config does not erase it.

One rule trips people up: for most keywords, the first value sshd reads wins. Cloud images often ship 50-cloud-init.conf with PasswordAuthentication yes. If your file is named 99-hardening.conf, it is read later and ignored. Name yours 00-hardening.conf so it sorts first. You can always check the result with sshd -T, which prints the settings sshd actually uses.

The diagram above shows the path a login takes: network, firewall, sshd checks (user allowed, key valid, root refused), then a shell.

Step 1: Confirm key login works first#

Before you turn password login off, prove that your key works. From your laptop, log in and check:

bash
ssh deploy@203.0.113.10

If this asks for a password, stop. Fix key-based login first. Then read disable SSH password login, which this lesson builds on.

Also make sure the user has sudo, so you do not need root over SSH. See create a sudo user.

Step 2: Open a second session and note your fallback#

Open two terminal windows connected to the server. Leave the second one alone until the end. An open session keeps working after sshd reloads, which makes it your undo button.

Also find your provider’s web console or recovery mode now. If both SSH sessions break, the console is how you get back in. Knowing where it is before you need it saves a bad hour.

Step 3: Write the drop-in file#

Create the file with a name that sorts first:

bash
sudo nano /etc/ssh/sshd_config.d/00-hardening.conf

Put this inside, replacing deploy with your own username:

output
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
PermitRootLogin no
AllowUsers deploy
MaxAuthTries 3
LoginGraceTime 30

What each line does:

  • PasswordAuthentication no refuses password logins, so guessing passwords is pointless.
  • KbdInteractiveAuthentication no closes the other route that can prompt for a password on some setups.
  • PermitRootLogin no refuses direct root logins. You log in as a normal user and use sudo.
  • AllowUsers deploy lets only the listed accounts in. Separate several names with spaces. Any other user is refused even with a valid key.
  • MaxAuthTries and LoginGraceTime shorten how long a failing client can keep trying.

Do not add AllowUsers unless you are sure of the exact account name. A typo here locks everyone out.

Step 4: Validate before you reload#

bash
sudo sshd -t

No output means the syntax is valid. An error names the file and line, for example /etc/ssh/sshd_config.d/00-hardening.conf line 3: Bad configuration option. Fix it before going on. Then check what sshd will really use:

bash
sudo sshd -T | grep -Ei 'passwordauthentication|permitrootlogin|allowusers'

If a value does not match your file, another file read earlier is overriding it. Look in the other drop-ins with grep -r PasswordAuthentication /etc/ssh/.

Step 5: Reload and test a new login#

bash
sudo systemctl reload ssh

On some distributions the unit is called sshd. Now, from a third terminal and not the old ones, log in again:

bash
ssh deploy@203.0.113.10

If that works, test that the restrictions hold. Try ssh root@203.0.113.10, which should be refused, and try a login with -o PubkeyAuthentication=no, which should fail with Permission denied (publickey). Only after the new login works should you close the original sessions.

If the new login fails, use the open second session to delete or fix the drop-in file, run sudo sshd -t, and reload again.

Step 6: Changing the port is a separate step#

Many guides move SSH to another port. It cuts log noise a little but is not real protection. If you do it, change the firewall first and test before you remove the old port. On recent Ubuntu releases SSH may be started through a systemd socket, so a port change can need extra care there. Check the Ubuntu server documentation for your release before you try it. Most servers are fine staying on port 22 with the settings above plus fail2ban.

Check it worked#

bash
sudo sshd -T | grep -Ei 'passwordauthentication|permitrootlogin|allowusers'
sudo journalctl -u ssh --since "10 minutes ago"

You should see passwordauthentication no, permitrootlogin no and your allowusers line. The journal should show your successful public key login and refused attempts for anything else. For wider checks see audit a Linux server.

Edge cases and gotchas#

  • First value wins. A cloud-init file that sorts before yours can override your setting. Use sshd -T as the source of truth, not the file you wrote.
  • Match blocks. A Match block applies to the end of the file or to the next Match. Settings placed after one can apply only to that group, so keep general settings above any Match.
  • Automation breaks. Deploy pipelines that log in as another user or as root stop working after AllowUsers or PermitRootLogin no. List the pipeline user too.
  • Agent forwarding and keys. If login fails with the right user, the key may not be loaded. Run ssh -v and see which keys are offered.
  • Reload is not restart. reload keeps existing sessions alive. A restart usually does too, but reload is the safer habit.
  • Provider keys. Some providers inject keys through their own agent. Check that your key is also in ~/.ssh/authorized_keys.

Troubleshooting#

SymptomLikely causeFix
Permission denied (publickey) after reloadWrong user, missing key or permissionsUse the open session, check ~/.ssh/authorized_keys and its permissions, see the permission-denied lesson
sshd -t prints Bad configuration optionTypo in a keywordFix the named line and run sshd -t again
Password login still worksAn earlier drop-in sets yesRename your file to sort first, check with sshd -T
ssh: connect to host ... port 22: Connection refusedsshd stopped or wrong portUse the provider console, sudo systemctl status ssh
Connection timed outFirewall blocks the portCheck ufw rules from the console
Pipeline user refusedNot in AllowUsersAdd the pipeline user and reload
Too many authentication failuresClient offers many keysUse -o IdentitiesOnly=yes -i ~/.ssh/key

Quick reference#

bash
sudo nano /etc/ssh/sshd_config.d/00-hardening.conf
sudo sshd -t
sudo sshd -T | grep -Ei 'passwordauth|permitroot|allowusers'
sudo systemctl reload ssh
ssh deploy@203.0.113.10     # test from a NEW terminal

Next#

Continue with Tune fail2ban jails and bans.

Try it: Harden sshd with a drop-in file

Write a hardening drop-in, validate it and reload sshd. Keep a second session open on a real server.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1Which command validates the sshd configuration without applying it?
2Two files in sshd_config.d set PasswordAuthentication to different values. Which one applies?
3What should you do right after reloading sshd with new restrictions?
4What does AllowUsers deploy admin do?

Frequently asked questions

Where should I put my sshd settings on Ubuntu?

Put them in a file under /etc/ssh/sshd_config.d/ ending in .conf. Ubuntu's main sshd_config has an Include line for that directory, so your file survives package upgrades of the main config.

Why is my sshd setting ignored?

For most sshd options the first value read wins. Files in sshd_config.d are read in alphabetical order, and an earlier file such as 50-cloud-init.conf can set the option before yours. Name your file with a lower number, like 00-hardening.conf.

How do I test sshd_config without restarting SSH?

Run sudo sshd -t. It checks syntax and prints nothing when the config is valid. Use sudo sshd -T to print the settings sshd would actually use.

What if I lock myself out of SSH?

Use your provider's web console or recovery mode to log in locally and revert the drop-in file. This is why you keep a second session open and test a new login before closing the old one.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios