20.4. Securing Server Access
A default sshd is deliberately permissive: it wants logins to work. Production policy is the opposite direction - a defined set of accounts, no root, no passwords, and verification before every change. The practice instance on port 2222 already carries the hardened shape from Section 20.3; this section reads it deliberately, validates changes before they go live, restricts what individual keys can do, and keeps an administrator from locking themselves out while doing all of the above.
20.4.1. Restricting Users, Root Logins, and Authentication Methods
Read the practice instance's effective policy, on sshserver in the root shell:
# /usr/sbin/sshd -T -f /etc/ssh/sshd_config.ch20 | grep -E "^(permitrootlogin|passwordauthentication|authenticationmethods|allowusers|authorizedkeysfile)"
permitrootlogin no
passwordauthentication no
authorizedkeysfile none
allowusers john
authenticationmethods publickey
Each line is a deliberate restriction. PermitRootLogin no is the strict
end of a four-value ladder:
PermitRootLogin |
Effect |
|---|---|
yes |
Root may log in with keys or passwords. |
prohibit-password (shown as without-password) |
Root may log in with keys only - the observed setting of the lab's stock service, and a reasonable default. |
forced-commands-only |
Root keys may run only forced commands (Section 20.4.3); no interactive root login. |
no |
No root login over SSH at all; reach root through sudo from a named account, which is auditable. |
AllowUsers john is an allowlist: when present, only the listed
accounts (patterns allowed) may log in at all, and it is checked before
any authentication attempt. AuthenticationMethods publickey requires a
successful public-key authentication and nothing else; the compound form
AuthenticationMethods publickey,keyboard-interactive stacks a key
and an interactive challenge - the building block for key-plus-token
policies. PasswordAuthentication no and
KbdInteractiveAuthentication no remove the password paths entirely, so
there is nothing to brute-force.
Test the restrictions from sshadmin. Root is refused:
$ ssh -p 2222 root@sshserver true
root@192.168.221.20: Permission denied (publickey).
A nonexistent account is refused with an identical message:
$ ssh -p 2222 nobody@sshserver true
nobody@192.168.221.20: Permission denied (publickey).
sshd does not reveal which accounts exist - the answer to a wrong username and a wrong key is the same string, by design. Forcing a password attempt is refused too, and the parenthesized method list shows the server never offered one:
$ ssh -p 2222 -o PreferredAuthentications=password -o PubkeyAuthentication=no john@sshserver true
john@192.168.221.20: Permission denied (publickey).
On a server that still permits passwords, the same command would prompt for one; here the immediate refusal is the proof that the method is off. Note that these tests ran against the practice instance - the main service on port 22 keeps its own policy until the same directives are placed in its drop-in directory, and Section 20.4.4 is the procedure for doing that without risk.
20.4.2. Validating Configuration Before Reloading
Every configuration change in this chapter followed one order: write the
file, validate with sshd -t, then reload. The validation step is what
separates a policy change from an outage. A malformed file is caught
before the running daemon ever sees it. Make a copy of the practice
configuration with one nonsense line appended - PermitRootLogin maybe
as line 17 - and validate it, on sshserver in the root shell:
# /usr/sbin/sshd -t -f /etc/ssh/sshd_config.ch20.bad
/etc/ssh/sshd_config.ch20.bad line 17: unsupported option "maybe".
sshd -t exits nonzero, names the file and line, and changes nothing.
The same check catches bad values for known options, missing host key
files, and permission problems on files sshd must read - always with a
line number to start from. Because the bad file was never loaded, the
instance on port 2222 was unaffected throughout.
Reloading is the second half of the discipline. For the main service,
$ sudo systemctl reload ssh asks systemd to send sshd a SIGHUP; for
a standalone instance, the signal goes to the PID in its PidFile, as
Section 20.3.3 did:
# kill -HUP "$(cat /run/sshd-ch20.pid)"
The command is silent. On receiving SIGHUP, sshd re-reads its
configuration and keeps listening; sessions already established continue
under the rules they were authenticated with, and only new connections
get the new policy. That split is what makes a reload safe to watch:
after it, verify with a new connection while an old one stays open,
and if the new connection fails, the old session and the out-of-band
network are still there.
One refinement for complex files: settings inside a Match block apply
only to matching connections, so sshd -T alone shows the no-match
view. sshd -T -C user=john,host=sshserver,addr=192.168.221.30 prints
the effective settings for such a connection - the relay address a
jump-routed login actually arrives from in this topology - the same
validation, from the client's perspective.
20.4.3. Authorized Key Restrictions and Forced Commands
Server policy decides who gets in; per-key options decide what a
specific key may do once in. They live as a comma-separated prefix on
the authorized_keys line. Demonstrate on the main service, with a
key created for the purpose:
$ ssh-keygen -t ed25519 -C "john@sshadmin-forced" -f ~/.ssh/id_ed25519_forced
Generating public/private ed25519 key pair.
Your identification has been saved in /home/john/.ssh/id_ed25519_forced
Your public key has been saved in /home/john/.ssh/id_ed25519_forced.pub
The key fingerprint is:
SHA256:cOd+7GtjE/jfErE2On1+tqRD5H9AnvlQkD/zwIz/FGI john@sshadmin-forced
The key's randomart image is:
+--[ED25519 256]--+
| . |
| o |
| . . . + o |
| o o .E*+o|
| S ..++.B=|
| ....o% o|
| ..+=.X |
| oO.=oB|
| ooBo**|
+----[SHA256]-----+
Install its public half on sshserver, but instead of the plain line,
make it a forced-command key - this line in
/home/john/.ssh/authorized_keys on sshserver:
restrict,command="/usr/bin/id" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDVNzjugnRLga1suBEx2tNx1FLEuGq5RbNJ4ba4CnLtr john@sshadmin-forced
From sshadmin, log in with it:
$ ssh -i ~/.ssh/id_ed25519_forced sshserver hostname
uid=1001(john) gid=1001(john) groups=1001(john),27(sudo)
The client asked to run hostname; the server ran /usr/bin/id,
because the key's line says any session opened with it runs that command
and nothing else. The original request is available to the command in
SSH_ORIGINAL_COMMAND, so a wrapper script can log or dispatch it.
restrict disables everything else this key could do - no PTY, no
forwarding, no X11, no agent - and individual no-pty,
no-port-forwarding and friends exist for finer-grained versions.
Forced-command keys are how a backup job, a monitoring probe, or a git
server gets a key that cannot become an interactive shell.
authorized_keys option |
Description |
|---|---|
restrict |
Disable all features for this key (PTY, forwarding, X11, user-rc). |
command="..." |
Run this command instead of the client's request. |
from="pattern" |
Accept the key only from matching source addresses. |
no-pty / no-X11-forwarding / no-agent-forwarding / no-port-forwarding |
Disable one feature at a time. |
expiry-time="YYYYMMDD" |
The key stops working after the given date. |
The from= option gates by source address. Create the key:
$ ssh-keygen -t ed25519 -C "john@sshadmin-from" -f ~/.ssh/id_ed25519_from
Generating public/private ed25519 key pair.
Your identification has been saved in /home/john/.ssh/id_ed25519_from
Your public key has been saved in /home/john/.ssh/id_ed25519_from.pub
The key fingerprint is:
SHA256:RNIWzPxMDLS6PhNu+Fz1IeYxTmiXbeqsof8VQq/3Cn8 john@sshadmin-from
The key's randomart image is:
+--[ED25519 256]--+
| .*=+ |
| o*.o |
| .o+. |
| o oo+ |
| . S @ * |
| .o B X o |
| o..o * + |
| .o=o + = .E |
| o=+oo + oo. |
+----[SHA256]-----+
Install it with a from= pattern that cannot match this network - the
documentation address 192.0.2.99, from the reserved TEST-NET-1 block
that no practice interface uses - as this line on sshserver:
from="192.0.2.99" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJ0HzPuS41955hWS4d1mJXzLdJXeBQRoOUMLtbqQXhb3 john@sshadmin-from
The key is now unusable from here, which the isolation probe from Section 20.2.2 confirms:
$ ssh -F /dev/null -o IdentitiesOnly=yes -o IdentityAgent=none -o ProxyJump=john@192.168.220.30 -i ~/.ssh/id_ed25519_from sshserver hostname
john@sshserver: Permission denied (publickey).
One subtlety that matters in the jump-host layout of this chapter: the
address sshd matches against is the address the connection came from,
which is the jump host's 192.168.221.30 - its address on the internal
network, where the relay's own TCP connection to sshserver starts - not
sshadmin's own address. A from= list built without accounting for the
relay will fail in exactly this way - silently, from the client's view.
The certificate world has the same control as source-address=
(Section 20.3.2), with the same caveat.
20.4.4. Preserving Access While Changing SSH Policy
Every technique in this section so far has been applied to a host the administrator is connected to through the very service being changed. That is the standing hazard of remote administration: one bad directive can end the session that was going to fix it. The discipline has a fixed shape:
- Keep an independent session open. A second terminal on a different path - the administration network here, a console, or a second instance - that no planned change touches. Never close it until the change is verified.
- Rehearse on a second instance. New policy goes to a spare sshd on another port with its own configuration, exactly as the port 2222 instance has done all chapter, and only moves to the main service after it proves out.
- Validate before every reload.
sshd -t, every time (Section 20.4.2) - a syntax error caught by validation is a non-event. - Verify from a new connection while the old session stays open; established sessions survive reloads and prove nothing about new ones.
- When the stakes are high, schedule the rollback before the
change. A one-shot systemd timer that restores the previous
configuration and reloads after a few minutes turns a mistake into
a bounded outage; Section 18.3 demonstrates the
same timed-rollback pattern for firewall rules, and
systemd-run --on-active=...builds it.
The rehearsal, end to end. Its lifeline is a multiplexed master connection - the form Section 20.5.1 covers in detail. Open one to the main service - deliberately the one no practice change will touch - and put it in the background:
$ ssh -M -S ~/.ssh/preserve.sock -f -N sshserver
-M makes this connection a master, -S names its control socket,
-f sends it to the background once authenticated, and -N means no
remote command - a pure held-open session. It prints nothing. Check it:
$ ssh -S ~/.ssh/preserve.sock -O check sshserver
Master running (pid=24254)
Now make the policy change: reload the practice instance with its current configuration, on sshserver in the root shell:
# kill -HUP "$(cat /run/sshd-ch20.pid)"
Silent, as before. Back on sshadmin, the lifeline did not notice:
$ ssh -S ~/.ssh/preserve.sock -O check sshserver
Master running (pid=24254)
The same PID, the same session - reloads never touch established connections. The step that actually proves something is a new connection under the just-reloaded policy:
$ ssh -p 2222 sshserver hostname
sshserver
That new connection succeeded, so the change window closes: shut the
lifeline down with -O exit and carry on:
$ ssh -S ~/.ssh/preserve.sock -O exit sshserver
Exit request sent.
Had step four failed instead, the master session, the jump path, and the administration network would all still be available to repair or revert - and that is the whole method. The same preparation is what Section 29.3 requires before a release upgrade: an open session, a validated fallback, and no change that can remove the administrator's own hands from the keyboard. When access is lost anyway, the recovery paths are Chapter 16's rescue environment, a virtual machine's console (Chapter 24), or reprovisioning from automation (Chapter 27).