HOWTO set up Wireguard and SSH to connect two hosts behind NAT

Ángel Ortega

Use case: you have two Linux hosts, budgie and severin, both behind different NATs, that you want to connect via SSH to one another. You also have a Linux host directly connected to the Internet, siouxsie, that will be used as a Wireguard server and SSH 'jump host'.

Execute this on the three servers:

wg genkey | tee /etc/wireguard/privatekey | \
wg pubkey | tee /etc/wireguard/publickey

On siouxsie, write the following into file /etc/wireguard/wg0.conf:

# /etc/wireguard/wg0.conf on siouxsie
[Interface]
ListenPort = 51820
PrivateKey = {content of /etc/wireguard/privatekey on siouxsie}
Address = 10.2.1.1/24

[Peer]
# budgie
PublicKey = {content of /etc/wireguard/publickey on budgie}
AllowedIPs = 10.2.1.2/32

[Peer]
# severin
PublicKey = {content of /etc/wireguard/publickey on severin}
AllowedIPs = 10.2.1.3/32

On budgie, write the following into file /etc/wireguard/wg0.conf:

# /etc/wireguard/wg0.conf on budgie
[Interface]
PrivateKey = {content of /etc/wireguard/privatekey on budgie}
Address = 10.2.1.2/24

[Peer]
PublicKey = {content of /etc/wireguard/publickey on siouxsie}
EndPoint = siouxsie.fqdn:51820
AllowedIPs = 10.2.1.1/32
PersistentKeepalive = 60

On severin, write the following into file /etc/wireguard/wg0.conf:

# /etc/wireguard/wg0.conf on severin
[Interface]
PrivateKey = {content of /etc/wireguard/privatekey on severin}
Address = 10.2.1.3/24

[Peer]
PublicKey = {content of /etc/wireguard/publickey on siouxsie}
EndPoint = siouxsie.fqdn:51820
AllowedIPs = 10.2.1.1/32
PersistentKeepalive = 60

On every server, execute the following to enable Wireguard and make the setup permanent (this is for systemd; in any other case, do your own investigation on how to do it):

systemctl enable wg-quick@wg0

After the connections are established (not immediately), you'll have direct access to hosts budgie on IP 10.2.1.2 and severin on IP 10.2.1.3 from siouxsie.

Add then the following to file /etc/hosts on siouxsie:

10.2.1.2 budgie
10.2.1.3 severin

And now you can connect from budgie to severin by simply running:

ssh -J siouxsie.fqdn severin

You can make it even easier by adding the following to ~/.ssh/config on budgie:

host severin
     ProxyJump siouxsie.fqdn

To simply run

ssh severin
If you found this post useful, you may buy Ángel a coffee.