A stolen SSH key is only as dangerous as what the account behind it is allowed to do. When I closed my k3s API to the internet, my CI runners still needed a way in. I gave them an SSH user that can open exactly one tunnel and do nothing else: no shell, no other port, no agent, no X11.
This guide covers how that restriction works, how I check that sshd enforces it, what it costs, and where it still falls short.
SSH hardening in one paragraph
Hardening SSH means shrinking two things: who can reach the daemon, and what an authenticated session may do once it is in. The first is a firewall question. The second is an sshd question, and most of the work is there.
That work comes down to four habits:
- Narrow each account to the one job it exists for.
- Put the same limits in two places, so one mistake does not open everything.
- Validate the configuration before sshd loads it.
- Ask sshd what it will really do for a given connection, instead of trusting what you wrote.
On my servers SSH is keys only. Everything below builds on that.
Server-wide settings also belong to hardening, for example password authentication, root login and algorithm lists. Their defaults differ between OpenSSH versions and distribution packages, so this guide does not list them. Check sshd_config(5) for the version you run.
How it works
What sshd does with a connection
sshd listens for connections and forks a new process for each one. That child handles key exchange, authentication, command execution and data exchange for that one client. Each stage is a point where a limit can apply:
sequenceDiagram
participant C as Client
participant L as sshd (listener)
participant S as sshd (per-connection child)
participant Sh as User's shell
C->>L: TCP connection on port 22
L->>S: fork
C->>S: key exchange
C->>S: authentication (public key)
C->>S: session requests: pty, X11, TCP forwarding, agent
Note over S: each request is checked against sshd_config and the key's options
C->>S: shell or command request
S->>Sh: runs the command through the user's shell with -cThe last step matters for a locked-down account. Whatever command reaches the shell, the shell is what runs it. If the shell is nologin, nothing else runs.
Where the limits come from
Two layers decide what an SSH key can do on my control-plane node, and the firewall sits in front of both.
- The firewall decides what can be reached at all. On the Contabo cluster, Ansible turns on ufw and allows port 6443, the Kubernetes API, only from my administrator addresses. Port 22 stays open, because GitHub's runners connect from changing addresses.
- sshd's own configuration applies per-user rules. A
Match Userblock in a drop-in file under/etc/ssh/sshd_config.d/holds them. - The key's options in
authorized_keysnarrow that one key further, whatever the server-wide settings say.
A connection only gets what all three allow:
flowchart LR
runner["CI runner<br/>(changing addresses)"] -->|"port 22: allowed"| ufw["ufw on master-1"]
runner -.->|"port 6443: refused"| ufw
ufw --> sshd["sshd"]
sshd --> cfg["/etc/ssh/sshd_config.d/50-kube-tunnel.conf<br/>Match User kube-tunnel"]
sshd --> keys["kube-tunnel's authorized_keys<br/>restrict, permitopen, command"]
cfg --> fwd["local forward to 127.0.0.1:6443 only"]
keys --> fwd
fwd --> api["k3s API on the node itself"]
cfg --> deny["no TTY, no agent, no X11,<br/>no tun device, command = nologin"]
keys --> denyThe key options and the Match block overlap on purpose. If someone edits the key line and drops an option, the Match block still holds. If a later sshd file loosens a global setting, the key line still holds.
How sshd reads its configuration
sshd reads /etc/ssh/sshd_config as keyword-argument pairs. Unless the manual says otherwise for a keyword, the first value sshd obtains is the one it uses. Debian's package puts Include /etc/ssh/sshd_config.d/*.conf at the start of that file, so a setting in a drop-in wins over the same setting in the main file.
The same package also sets X11Forwarding yes in sshd_config. That is one reason my Match block says X11Forwarding no explicitly instead of relying on a default.
sshd rereads its configuration when it receives SIGHUP, by re-executing itself. Existing sessions keep running, which is what makes the "keep a session open" safety net below work.
A worked example
The example is the kube-tunnel user on my k3s control-plane node, master-1. GitHub Actions uses it to reach the API through a tunnel. The full CI side is in the tunnel deployment write-up (opens in a new tab). Here I only cover the sshd side.
1. The account
My playbook creates kube-tunnel as a system user with /usr/sbin/nologin as its shell. Its .ssh directory is owned by root, so the user cannot change its own keys.
That second detail matters. Without it, anyone holding the key could try to rewrite the options that limit them. It is the same idea as running a systemd service as a dedicated, locked-down user, which the Linux section of the interview prep guide (opens in a new tab) touches on.
2. The key
The workflow that rotates the tunnel key generates a fresh ed25519 key on every run:
ssh-keygen -q -t ed25519 -N '' -C kube-tunnel -f ./kube-tunnel-q keeps it quiet, so success prints nothing and leaves ./kube-tunnel and ./kube-tunnel.pub. The -N '' gives the key no passphrase. CI needs that, and it is also why the key's own limits matter so much.
The public half then goes into authorized_keys, prefixed with options:
printf 'restrict,port-forwarding,permitopen="127.0.0.1:6443",command="/usr/sbin/nologin" %s kube-tunnel\n' \
"$(cut -d' ' -f1,2 ./kube-tunnel.pub)"The cut keeps the key type and the base64 key and drops the comment, because the line supplies its own. Options are comma-separated, with no spaces except inside double quotes. Read them left to right:
restrictturns everything off.port-forwardingturns local forwarding back on.permitopen="127.0.0.1:6443"limits forwarding to the API on the node itself.command="/usr/sbin/nologin"replaces anything the client asks to run.
My playbook writes this line as the only authorized key. Each rotation therefore invalidates the previous key.
3. The sshd rules
The same limits go into sshd, scoped to this user with a Match block:
sudo tee /etc/ssh/sshd_config.d/50-kube-tunnel.conf > /dev/null <<'EOF'
Match User kube-tunnel
AllowTcpForwarding local
PermitOpen 127.0.0.1:6443
AllowAgentForwarding no
AllowStreamLocalForwarding no
X11Forwarding no
PermitTTY no
PermitTunnel no
ForceCommand /usr/sbin/nologin
EOFAllowTcpForwarding defaults to yes. local allows -L forwards but not remote ones. PermitOpen repeats the single target. AllowAgentForwarding and AllowStreamLocalForwarding both default to yes, so they are switched off here, together with X11, terminals and tun devices. ForceCommand mirrors the key's command=.
4. Validate before anything reloads
A broken sshd file can lock you out of a remote server. sshd -t checks only the validity of the configuration and the sanity of the keys. My playbook runs it first and deletes the file if sshd refuses it. By hand, that looks like this:
if sudo sshd -t; then
echo "sshd config OK"
else
sudo rm -f /etc/ssh/sshd_config.d/50-kube-tunnel.conf
echo "sshd rejected 50-kube-tunnel.conf; removed it"
fiWhen the file is valid, sshd -t prints nothing and the script prints sshd config OK. Only then reload the SSH service. Its unit name differs between distributions, so check yours. Keep the session you are working in open until a fresh login works.
5. Ask sshd what it will actually do
sshd -t only proves the file parses. It does not prove the rules apply to the user you meant.
sshd -T prints the effective configuration and runs the same checks as -t. On its own it shows what a connection gets when no Match block applies. Adding -C describes a connection, using the keywords user, host, addr, laddr, lport and rdomain, and sshd evaluates every Match block against it.
My playbook checks that kube-tunnel gets the restriction and root does not:
sudo sshd -T -C user=kube-tunnel,host=localhost,addr=127.0.0.1 | grep -i '^permitopen'
sudo sshd -T -C user=root,host=localhost,addr=127.0.0.1 | grep -i '^permitopen'For kube-tunnel, the playbook expects this line:
permitopen 127.0.0.1:6443For root, that value must not appear. If it does, the Match condition is wider than you think. If it is missing for kube-tunnel, the block is not matching that user at all.
6. Prove the key opens no shell
Logging in with the tunnel key gives no terminal, then nologin's message:
ssh -i ./kube-tunnel kube-tunnel@master-1PTY allocation request failed on channel 0
This account is currently not available.The two lines map to the stages in the first diagram. The session stage refuses the pty request. The command stage then runs nologin, which prints its message and exits.
That is the result I want: a valid key, an accepted login, and nothing to do with it.
7. Use it for the one thing it is for
The runner opens the tunnel in the background and fails fast if the forward is refused:
ssh -i ./kube-tunnel -o IdentitiesOnly=yes -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=30 \
-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=./known_hosts -o ExitOnForwardFailure=yes \
-f -N -L "127.0.0.1:16443:127.0.0.1:6443" kube-tunnel@master-1Each client option has a job:
BatchMode=yesstops any prompt from hanging a CI job.IdentitiesOnly=yesstops the client from offering other keys.ExitOnForwardFailure=yesmakes a refused forward an error instead of a silent no-op.-Nasks for no remote command.-fbackgrounds the tunnel once it is up.
My CI-access workflow also tests the negative side after every rotation. It tries to run id and to forward to port 22 through kube-tunnel, and fails the run if either works. The run on 30 November ended with this line among the token checks:
kube-tunnel: no command, no other portTrade-offs and pitfalls
| Measure | What it buys | What it costs |
|---|---|---|
Key options (restrict, permitopen, command) | Limits travel with the key | Easy to drop when someone edits the line by hand |
Match User block in a drop-in | Server-side limits, regardless of the key line | One more file whose scope you must check with sshd -T -C |
Root-owned .ssh for the user | User cannot rewrite its own limits | Key rotation needs root, so it needs automation |
| Firewall: 6443 for admins only, 22 open | API off the internet | SSH remains the exposed surface |
StrictHostKeyChecking=accept-new | No host key to pre-distribute to runners | Trusts the host key on first sight |
The failure modes I would watch for:
- Locking yourself out. A typo in an sshd file on a remote box is the classic one. Run
sshd -tbefore every reload, and do not close your working session until a new login succeeds. - Trusting the file instead of the result. A
Matchblock that matches nobody, or everybody, still parses cleanly. A plainsshd -Tdoes not show it either.sshd -T -Cwith a real user, host and address is the check that catches it. Run it for the restricted user and for root. - Losing to an earlier value. For most keywords the first value wins, and Debian-style packaging includes the drop-ins before the rest of
sshd_config. A setting in your drop-in beats the main file, and a drop-in whose name sorts earlier beats yours.sshd -T -Cshows which one won. - Assuming the forwarding switches are enough. The
sshd_configmanual warns that disabling TCP, Unix-socket or agent forwarding does not improve security unless users are also denied shell access, because they can always install their own forwarders. The shell is what makes the forwarding limits real. That is whykube-tunnelgetsnologinas its shell and as its forced command, and why my workflow tests that a forward to port 22 fails. - Assuming a nologin shell is enough. The reverse also holds. The shell decides what runs, not what gets forwarded. That is why forwarding is limited separately, in both places.
- Port 22 is still on the internet. Mine is keys only, and a stolen tunnel key opens no shell and reaches only the API. It is still an open port. Turning on the provider's firewall in front of it is next on my list.
- First-sight host key trust. With
accept-new, a runner would accept an impostor's host key the first time. In my setup, the cluster's CA certificate is what proves the far end, because the kubeconfig verifies the API against it. Without a second check like that, pin the host key instead.
The Match block limits what kube-tunnel may do. It does not limit who else may log in. By default sshd allows every user and group. AllowUsers and AllowGroups narrow that, and deny directives are processed before allow directives. If you add an allow list, the tunnel user has to be on it.
When is this too much? If an account only ever logs in interactively as a person, the forwarding limits add little. The Match-plus-key pattern pays off for machine accounts with one narrow purpose, such as a tunnel, a backup pull, or a deploy hook.
Further reading
- How GitHub Actions deploys to my k3s cluster through an SSH tunnel (opens in a new tab) covers the CI half: the composite action, per-repository ServiceAccounts and the workflow that rotates keys and tokens.
- sshd_config(5) (opens in a new tab) is the reference for
Match, the forwarding settings and the access-control keywords. The Debian trixie page (opens in a new tab) adds the packaging details, including the drop-in include and the non-default options. - sshd(8) (opens in a new tab) documents
-t,-Tand-C, the login sequence, and theauthorized_keysformat. ssh_config(5)covers the client options used in step 7, andssh-keygen(1)covers key generation.- The OpenSSH release notes for your installed version. Check them before copying any algorithm or option list from an older guide.
- SSH limits what a login can do. They do not help against a kernel bug once someone is on the box. What Kubernetes teams should take away from 948 privilege-escalation exploits (opens in a new tab) covers that side of keeping nodes patched.
Next, run step 5 on one of your own servers for each account that logs in non-interactively. Any account whose effective settings allow more forwarding than its job needs is the first one to restrict.



Discussion comments
No comments yet. Start the discussion.