3

Suppose I have a a wireguard network called wg0 on 10.0.0.1/24. I use systemd to start it on boot:

# systemctl enable wg-quick@wg0

I want sshd to only listen on the wireguard address, 10.0.0.1, instead of 0.0.0.0. So I set the ListenAddress in /etc/ssh/sshd_config:

ListenAddress  10.0.0.1
#ListenAddress  ::
AddressFamily  inet

Note: I set the address family because I'm only using IPv4 and not IPv6 here. I think if it's not set, ssh will continue to listen to :: on IPv6.

If I save the config and restart sshd, it works great. But after the server restarts, ssh fails to start, despite being enabled in systemd. The syslog output tells us why:

sshd[xxx]: error: Bind to port 22 on 10.0.0.1 failed: Cannot assign requested address.

Clearly, we have a race condition where sshd is trying (and failing) to start before the wireguard interface is ready.

The obvious solution is to edit /etc/systemd/system/sshd.service and add wg-quick@wg0 as a dependency. However, no combination of After=, Wants=, or Requires= does the trick. It seems that wg-quick@wg0 reports that it's finished, even though the network interface isn't actually ready yet.

1 Answer 1

6

Systemd will wait for the interface to be ready if sys-devices-virtual-net-XXX.device is listed as a dependency. So to have sshd wait for the wg0 interface, add these lines to the [Unit] section of /etc/systemd/system/sshd.service:

After=network.target [email protected]
Requires=sys-devices-virtual-net-wg0.device

This should work for any service listening on a wireguard address. SSH also requires After=auditd.service. Items in After= can be space seperated or be on multiple After= lines.

Finally, reload the daemon and restart the service:

# systemctl daemon-reload
# systemctl restart sshd
2
  • 5
    Note you can use systemctl edit sshd and then add a [Unit] block and the lines above; then you won't need to make modifications to the built-in service file, and you don't need to execute a daemon-reload. Jan 6, 2021 at 20:11
  • I was having another issue with dnsmasq, but this line Requires=sys-devices-virtual-net-wg0.device helped me there too. Thanks for the great tip!
    – taiyodayo
    Feb 24, 2022 at 4:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .