# 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.

URL: https://levelrail.com/learn/security/harden-ssh-server-configuration/
Updated: 2026-11-27

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](https://levelrail.com/learn/server-basics/log-in-with-ssh-keys/)) first. Then read [disable SSH password login](https://levelrail.com/learn/server-basics/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](https://levelrail.com/learn/server-basics/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:

```text
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](https://levelrail.com/learn/security/tune-fail2ban-jails-and-bans/)).

## 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](https://levelrail.com/learn/security/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

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `Permission denied (publickey)` after reload | Wrong user, missing key or permissions | Use the open session, check `~/.ssh/authorized_keys` and its permissions, see the permission-denied lesson |
| `sshd -t` prints `Bad configuration option` | Typo in a keyword | Fix the named line and run `sshd -t` again |
| Password login still works | An earlier drop-in sets `yes` | Rename your file to sort first, check with `sshd -T` |
| `ssh: connect to host ... port 22: Connection refused` | sshd stopped or wrong port | Use the provider console, `sudo systemctl status ssh` |
| `Connection timed out` | Firewall blocks the port | Check [ufw rules](https://levelrail.com/learn/security/advanced-ufw-firewall-rules/)) from the console |
| Pipeline user refused | Not in `AllowUsers` | Add the pipeline user and reload |
| `Too many authentication failures` | Client offers many keys | Use `-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
```

## Related lessons

- [Disable SSH password login](https://levelrail.com/learn/server-basics/disable-ssh-password-login/)): the first setting in this file, in detail.
- [Fix SSH permission denied (publickey)](https://levelrail.com/learn/troubleshooting/fix-ssh-permission-denied-publickey/)): what to check when the new login fails.
- [Tune fail2ban jails and bans](https://levelrail.com/learn/security/tune-fail2ban-jails-and-bans/)): ban clients that keep failing.
- [Advanced ufw firewall rules](https://levelrail.com/learn/security/advanced-ufw-firewall-rules/)): rate limit and restrict the SSH port.
- [Audit a Linux server](https://levelrail.com/learn/security/audit-a-linux-server/)): check logins and users after hardening.

## Next

Continue with [Tune fail2ban jails and bans](https://levelrail.com/learn/security/tune-fail2ban-jails-and-bans/)).

## 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

- [sshd_config manual](https://man7.org/linux/man-pages/man5/sshd_config.5.html)
- [Ubuntu Server docs, OpenSSH server](https://ubuntu.com/server/docs/openssh-server)
