June 2, 2020

Networks up, then SSH server

Avoid a condition which cause SSH server to not accept connections.

Networks up, then SSH server

If sshd starts before, let's say, an office VPN connection, sshd may fail to bind to the (non-existant) VPN adapter IP address. This will result in connection attempts being denied and require accessing the machine some other way.

systemd's service files let us define conditions for starting a service. If a service B need another service A to already be started, we just need to specify that in B.service Β Let's look at the service file for the OpenSSH server, sshd.service:

[Unit]
Description=OpenBSD Secure Shell server
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target auditd.service
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run
[unit] block for /etc/ssh/sshd_config 

In the [unit] block, we find the line After=network.target auditd.service. The arguments in the After statement forms a list of services that we require to have already been started, before sshd starts. We can edit sshd.service and make additions to the After= line. The example uses a Wireguard connection wg0. The systemd service for the Wireguard interface is wg-quick@wg0.service.


sudo nano /etc/systemd/system/sshd.service
[Unit]
Description=OpenBSD Secure Shell server
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target auditd.service wg-quick@wg0.service
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run

[Service]
EnvironmentFile=-/etc/default/ssh
ExecStartPre=/usr/sbin/sshd -t
ExecStart=/usr/sbin/sshd -D $SSHD_OPTS
ExecReload=/usr/sbin/sshd -t
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartPreventExitStatus=255
Type=notify
RuntimeDirectory=sshd
RuntimeDirectoryMode=0755

[Install]
WantedBy=multi-user.target
Alias=sshd.service
Wireguard interface added to /etc/systemd/system/sshd.service-

After editing a .service file, reload systemd to apply the changes.

sudo systemctl daemon-reload

Now sshd.service will wait for the VPN service and it's interface to initialize before starting.