I have the following code run on my server to allow me to SSH into my server even when the server is connected to a VPN. The code below runs as a service after startup.
ip addr add 192.168.1.113 dev enp1s0 label enp1s0:0
ip rule add from 192.168.1.113 table 402
ip route add default via 192.168.1.1 dev enp1s0:0 table 402
This works with openvpn but it doesn't with wireguard because my wireguard client adds a couple of rules in front of my rule above.
0: from all lookup local
32761: from all lookup main suppress_prefixlength 0
32762: not from all fwmark 0xca6c lookup 51820
32763: from 192.168.1.113 lookup 402
32766: from all lookup main
32767: from all lookup default
If I add the rule from 192.168.1.113 lookup 402
after the wireguard connection then I can SSH into the server. So I'm assuming it is an issue of priority.
How can I ensure my rule (32763
) keeps priority even after wireguard connects and adds those couple (32761
, 32762
) of rules?
FAILED SOLUTION:
I learned the numbers on the left are priorities. I then tried to set the priority of my rule lower..
ip rule add from 192.168.1.113 table 402 prio 300
.. but after I connected to wireguard vpn, the wireguard client simply put their rules below mine at priority 299
, and 298
.
298: from all lookup main suppress_prefixlength 0
299: not from all fwmark 0xca6c lookup 51820
300: from 192.168.1.113 lookup 402
Is there anyway to prevent this? I suppose I could put a PostUp
command in the wireguard conf file that changes the priority but I feel like there has to be a cleaner solution.
The manipulation of your routing rules is performed by the
wg-quick
script; you can see the relevant section here. Since it adds the rules without setting an explicit priority, they will always be added "below" any existing rules in the table.You need to ensure that your custom rule gets added only after
wg-quick
has configured the interface and routing tables. You can do that by moving your custom configuration to a post-up hook. Add aPostUp
directive to your interface configuration file:(The
%i
will be replaced with the interface name.)This will cause
wg-quick
to execute the given command after bringing up the interface. In yourPostUp
script (here it's/etc/wireguard/scripts/example-postup.sh
, but it could be anywhere), add your custom rule. E.g.:You will probably want to add another script (perhaps a
PreUp
or maybe aPostDown
) to remove that custom rule; otherwise next time you bring up the interface you'll run into the same problem (because the rule will already exist whenwg-quick
adds its custom rules).