I am looking for a way to configure my VPN on my VPS in a way that my SSH connection will go through regular network, but all other traffic that goes out of that VPS will go through VPN.
I decided to use policy routing for this.
I've added a new routing table called VPN to /etc/iptables2/rt_tables file
Then I've marked all the packets that are not SSH
iptables -t mangle -A PREROUTING -p tcp ! --dport 22 -j MARK --set-mark 1 iptables -t mangle -A PREROUTING ! -p tcp -j MARK --set-mark 2 iptables -t mangle -A OUTPUT -p tcp ! --sport 22 -j MARK --set-mark 3 iptables -t mangle -A OUTPUT ! -p tcp -j MARK --set-mark 4
And assigned them to newly created policy:
ip rule add fwmark 1 table VPN ip rule add fwmark 2 table VPN ip rule add fwmark 3 table VPN ip rule add fwmark 4 table VPN
now since OpenVPN will by default add all routes to main routing table, I used the --route-noexec to prevent that from happening and created a script that will simply add default route to the VPN routing table using the Environmental variables:
openvpn --config [config file] --script-security 2 --route-noexec --route-up /home/user/script.sh
And the script itself is just:
#cat script.sh #!/bin/bash ip route add default via $route_vpn_gateway table VPN
After executing this command I am still logged in to the VPS but I have no connection to the outside world.
Here's what I can see in my routing tables:
# ip route show table VPN default via 10.7.7.1 dev tun0 # ip route show table main default via [VPS Gateway] dev eth0 10.7.7.0/24 dev tun0 proto kernel scope link src 10.7.7.210 [VPS Gateway] dev ens3 scope link
Now my understanding is that the second line from the main routing table should not be there, but I'm not sure how to move it to the VPN table.
Any clues? Also - any ideas what else am I missing in this config?