Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 3 · Networking and hardening · Lesson 04 · 55 minutes

Run and harden an SSH server

After this lesson you can
  • Install an SSH server, connect to it and log in with a key instead of a password
  • Set the options that matter in the server configuration, and check the file before you restart
  • Show that each rule works with a login that fails, and stop the service
Lab files of this lesson (4)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A new operator, kr_ops, needs a shell on a test server. Your team lead says: "Key login only. No root login over SSH. Only the people that I name may log in at all. Show me that each rule works." You install the server on your practice system and connect to it on localhost, so that you are both the client and the server. Then you harden it, and for each rule you show the login that fails.

Recall

Why do you set the policy of a firewall chain to drop last, and not first?

A chain with policy drop and no allow rules drops every packet, including your own SSH session. Add the allow rules first, switch the policy after.

Which file does the resolver read before it asks a DNS server?

/etc/hosts. A name in that file never reaches DNS.

The idea

SSH (secure shell) gives you a shell on another machine over an encrypted connection. The program ssh is the client, and sshd is the server, which listens on port 22. The server proves who it is with a host key. You prove who you are with a password or, better, with a key pair: a private key that stays with you, and a public key that you put on the server. The server accepts you if your public key is a line in ~/.ssh/authorized_keys of the account that you log in to. The private key never leaves your machine, only a signature does.

Login with a key pair
YouServerI am kr_ops, may I use this public key?key is allowed: send a signaturesign the session ID with the private keyhere is the signatureit fits the public key, welcomeYouServer12345
  1. You → Server: I am kr_ops, may I use this public key?
  2. Server → You: key is allowed: send a signature
  3. You: sign the session ID with the private key
  4. You → Server: here is the signature
  5. Server → You: it fits the public key, welcome

The first time you connect to a server, ssh does not know its host key. It shows the fingerprint (a short hash of the key) and asks you to accept it, and then it saves the key in ~/.ssh/known_hosts. Later, if the key is different, ssh stops. This protects you from a machine that pretends to be the server.

The server settings are in /etc/ssh/sshd_config, and Ubuntu also reads /etc/ssh/sshd_config.d/*.conf. For each option the first value that sshd reads wins, so a drop-in file with a low number such as 01- is read first.

OptionWhat it doesHardened value
PermitRootLoginMay root log in over SSH?no
PasswordAuthenticationMay a password open a login?no
KbdInteractiveAuthenticationMay the server ask questions at a prompt? With PAM, one question can be a password, so this is a second way in for a password.no
PubkeyAuthenticationMay a key open a login?yes
AllowUsersOnly these accounts may log in.the names you choose
PortThe port that sshd listens on (lesson 5 changes it).22, or another

Worked example

1. Install the server and check it

apt install installs a package. systemctl enable --now ssh starts the service now and at every boot. ss -tlnp (lesson 1) shows the listener. Use sudo, so that the process of root is shown too.

sudo apt install -y openssh-server
sudo systemctl enable --now ssh
sudo ss -tlnp | grep ':22 '
LISTEN 0      4096         0.0.0.0:22        0.0.0.0:*    users:(("sshd",pid=14067,fd=3),("systemd",pid=1,fd=107))
LISTEN 0      4096            [::]:22           [::]:*    users:(("sshd",pid=14067,fd=4),("systemd",pid=1,fd=108))

The server listens on every address. Your lab accounts get weak passwords in step 2, so limit the server to this machine first. The option ListenAddress names the address that sshd listens on. tee writes the file, because sudo stands before it.

Ubuntu 24.04 only. A socket unit, ssh.socket, listens in place of sshd. It does not follow ListenAddress and Port reliably: 24.04 builds them into the socket only after a reload, and older releases ignore them. Turn it off, so that sshd listens itself.

echo "ListenAddress 127.0.0.1" | sudo tee /etc/ssh/sshd_config.d/01-krlab.conf > /dev/null
sudo systemctl disable --now ssh.socket
sudo systemctl restart ssh
sudo ss -tlnp | grep ':22 '
LISTEN 0      128        127.0.0.1:22        0.0.0.0:*    users:(("sshd",pid=100555,fd=3))

Only programs on this machine can reach the server now.

2. Make the lab accounts and connect for the first time

useradd -m -s /bin/bash NAME makes an account with a home folder and a shell. chpasswd sets a password from the text NAME:PASSWORD. The password here is only for the lab. The accounts kr_ops and kr_guest are the people on the server.

sudo useradd -m -s /bin/bash kr_ops
sudo useradd -m -s /bin/bash kr_guest
echo 'kr_ops:Lab-pass-1' | sudo chpasswd
echo 'kr_guest:Lab-pass-2' | sudo chpasswd
ssh kr_ops@localhost hostname

ssh USER@HOST COMMAND logs in as USER on HOST and runs the command. The first connection asks about the host key. Answer yes, then type the password of kr_ops.

The authenticity of host 'localhost (127.0.0.1)' can't be established.
ED25519 key fingerprint is SHA256:g6vIA3Tf4WfE5pKF/jwFDhrc2lx72uSIKJWWbyWCuPU.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'localhost' (ED25519) to the list of known hosts.
kr_ops@localhost's password:
krbox

Your fingerprint is different. On a real server, compare it with the one of the owner before you say yes.

3. Make a key pair

ssh-keygen makes the pair. -t ed25519 picks a modern key type, -f is the file name, -N "" means no passphrase (acceptable only in this lab: a real key gets a passphrase), and -C adds a comment.

mkdir -p ~/krlab/linux-advanced/ssh && cd ~/krlab/linux-advanced/ssh
ssh-keygen -t ed25519 -f ./lab_key -N "" -C "you@krbox"
ls -l lab_key lab_key.pub
-rw------- 1 you you 399 Nov 21 11:21 lab_key
-rw-r--r-- 1 you you  91 Nov 21 11:21 lab_key.pub

The private key lab_key has mode 600: ssh refuses to use a key that others can read. The public key is one line, and that line goes into authorized_keys:

The public key line
ssh-ed25519the key typeAAAAC3Nz...the public key itselfyou@krboxthe comment from -Cssh-ed25519the key typeAAAAC3Nz...the public key itselfyou@krboxthe comment from -C

4. Log in with the key

ssh-copy-id -i PUBLICKEY USER@HOST logs in with the password once and appends the public key to ~/.ssh/authorized_keys of that account. After that, the key opens the door.

ssh-copy-id -i lab_key.pub kr_ops@localhost
ssh -i lab_key kr_ops@localhost 'whoami'
sudo ls -ld /home/kr_ops/.ssh
sudo ls -l /home/kr_ops/.ssh
Number of key(s) added: 1
kr_ops
drwx------ 2 kr_ops kr_ops 4096 Nov 21 11:21 /home/kr_ops/.ssh
total 4
-rw------- 1 kr_ops kr_ops 91 Nov 21 11:21 authorized_keys

The first command types the password of kr_ops. The second needs none. The folder has mode 700 and the file 600, and sshd ignores the file if others can write it.

5. Show the weak settings

To prove two rules later, give the same key to kr_guest and to root. tee -a appends the key to both files. chown -R kr_guest: gives the folder and everything below it to kr_guest and to that user's own group (a colon with no group name means the login group). chmod then sets the strict modes that sshd wants.

sudo mkdir -p /home/kr_guest/.ssh /root/.ssh
sudo tee -a /home/kr_guest/.ssh/authorized_keys /root/.ssh/authorized_keys < lab_key.pub > /dev/null
sudo chown -R kr_guest: /home/kr_guest/.ssh && sudo chmod 700 /home/kr_guest/.ssh
sudo chmod 600 /home/kr_guest/.ssh/authorized_keys

Now read the effective settings with sshd -T (the settings that sshd really uses, in lower case). Then try a key login for three accounts. for u in A B C; do COMMAND; done is a loop: it runs the command once for each word of the list, with the word in $u. In the command, -o NAME=VALUE sets one client option for one run: IdentitiesOnly=yes offers only the key that you named, and PasswordAuthentication=no forbids the password.

sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|allowusers)'
for u in root kr_guest kr_ops; do ssh -i lab_key -o IdentitiesOnly=yes -o PasswordAuthentication=no $u@localhost id -un; done
permitrootlogin without-password
pubkeyauthentication yes
passwordauthentication yes
kbdinteractiveauthentication no
root
kr_guest
kr_ops

without-password is the older name of prohibit-password (a newer OpenSSH, such as that of Ubuntu 26.04, prints prohibit-password; it means the same): root may log in with a key, but not with a password. All three accounts get in. That is the situation that you must change.

6. Harden the server and check the file

Save this drop-in file as 01-krlab.conf in your lab folder, and copy it to /etc/ssh/sshd_config.d/. It replaces the one-line file of step 1 and keeps its first line. Then sshd -t tests the configuration and prints nothing if it is valid. Make a mistake on purpose to see what a bad file looks like, and remove it.

01-krlab.conf

ListenAddress 127.0.0.1
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AllowUsers kr_ops
sudo cp 01-krlab.conf /etc/ssh/sshd_config.d/01-krlab.conf
echo "PermitRootLogin maybe" | sudo tee /etc/ssh/sshd_config.d/02-bad.conf > /dev/null
sudo sshd -t; echo "sshd -t exit: $?"
sudo rm /etc/ssh/sshd_config.d/02-bad.conf
sudo sshd -t; echo "sshd -t exit: $?"
/etc/ssh/sshd_config.d/02-bad.conf line 1: unsupported option "maybe".
sshd -t exit: 255
sshd -t exit: 0

Never restart sshd before sshd -t says nothing: a broken file stops the server. If you work in a remote session, keep Terminal 2 of lesson 0 logged in before you reload: it is the way back if the new file locks you out. systemctl reload ssh makes the running server read the file again, and it keeps your open sessions. Then repeat the loop of step 5.

sudo systemctl reload ssh
for u in root kr_guest kr_ops; do ssh -i lab_key -o IdentitiesOnly=yes -o PasswordAuthentication=no $u@localhost id -un; done
ssh -o PubkeyAuthentication=no kr_ops@localhost id -un
root@localhost: Permission denied (publickey).
kr_guest@localhost: Permission denied (publickey).
kr_ops
kr_ops@localhost: Permission denied (publickey).
Three accounts, one key, one answer each
ClientServerrootkr_guestkr_opssshd123ClientServerrootkr_guestkr_opssshd123
  1. root → sshd (blocked): valid key, PermitRootLogin no
  2. kr_guest → sshd (blocked): valid key, not in AllowUsers
  3. kr_ops → sshd: valid key, allowed

The last login, with the key switched off, is refused too: the server no longer offers a password, and the message lists only publickey.

Test the rule "the first value wins". Put a file with a lower number and the opposite value in front of 01-krlab.conf. sshd -T reads the files and needs no restart. Then remove the file.

echo "PermitRootLogin yes" | sudo tee /etc/ssh/sshd_config.d/00-test.conf > /dev/null
sudo sshd -T | grep permitrootlogin
sudo rm /etc/ssh/sshd_config.d/00-test.conf
sudo sshd -T | grep permitrootlogin
permitrootlogin yes
permitrootlogin no

The file 00-test.conf is read first and wins, although 01-krlab.conf says no. An old file that you forgot can undo your rule, so always read the result with sshd -T.

7. Stop the service and clean up

systemctl disable --now ssh stops the service and keeps it from starting at boot. Then remove what the lab left behind: the lab key in the file of root (sed -i '/you@krbox/d' deletes the line with the key comment), the account kr_guest (userdel -r also deletes its home folder), and the password of kr_ops (passwd -l locks it, and the key still works). If userdel says that the account is in use, wait and run it again.

sudo systemctl disable --now ssh
sudo sed -i '/you@krbox/d' /root/.ssh/authorized_keys
sudo userdel -r kr_guest
sudo passwd -l kr_ops
ss -tln | grep ':22 '
ssh -i lab_key kr_ops@localhost id -un
ssh: connect to host localhost port 22: Connection refused

The grep prints nothing, because no listener is left. The file 01-krlab.conf stays in /etc/ssh/sshd_config.d/, and lesson 5 uses it.

Your turn

Add a second operator. There are no steps here: use the commands of the worked example. The server must run (sudo systemctl enable --now ssh), with the file 01-krlab.conf of step 6.

  1. Make the account kr_audit, with a home folder and the shell /bin/bash.
  2. Make a key pair with the file name audit_key and the comment audit@krbox in ~/krlab/linux-advanced/ssh.
  3. Install the public key for kr_audit by hand, not with ssh-copy-id: create the folder .ssh and the file authorized_keys with the right modes and owner.
  4. Add kr_audit to AllowUsers, check the file, reload the server and log in with the command echo $((6*7)).

Now take kr_audit out of AllowUsers again, reload the server and repeat the login. Then write a file bad.conf that holds the line PermitRootLogin maybe, and check it with sshd -t -f bad.conf (-f names the file to check).

Stop the service when you are done, and delete the account with sudo userdel -r kr_audit.

Check yourself

You set "PasswordAuthentication no" before you copied your key. What happens?

You lock yourself out: no password is accepted and the server has no key of yours. Copy and test the key first, keep a second session open, and set the option last.

Why do you run "sshd -t" before you reload or restart the service?

A file with an error stops the server from starting, and on a remote machine you then have no way in. sshd -t finds the error and changes nothing.

A new line appears in ~/.ssh/authorized_keys and you did not add it. What does it mean?

Someone can log in to this account without a password. It may be a backdoor. Compare it with your own keys, find out when the file changed, and treat the account as compromised until you know.

Field notes

  • Add MaxAuthTries 3, LoginGraceTime 30 and ClientAliveInterval to the drop-in file. Tools such as fail2ban read the log and block a source that fails again and again. The log is in journalctl -u ssh.
  • In authorized_keys a line can start with options such as from="192.0.2.10", command="/usr/bin/backup" and no-port-forwarding. They limit what one key can do, so use them for automation keys.
  • Protect the private key with a passphrase and ssh-agent. Use one key for each machine, and remove a key from every authorized_keys when its machine is lost.
  • The CIS Benchmarks for Linux ask for no root login and a list of allowed users.