Suppose you’ve setup a VM and configured it as a site-to-site VPN with OpenVPN, using
staticclients. You are using this VM as a default gateway for other VMs and now want to forward all traffic from the VMs not through the default gateway‘s adapter, but through the VPN tunnel.
Why would you want to do this? One use-case might be because you want your VMs to have the same originating IP address as the VPN server.
To get started, make sure you add these commands in a terminal on your default gateway:
ip route add ip-address-of-vpn-server/32 via default-gateway-ip dev enp0s5 (providing enp0s5 is your current adapter)
ip route del default
ip route add default via 192.168.159.14 dev tun0 (providing 192.168.159.14 is the private IP you got from your VPN)
The commands above will make sure your gateway can still reach the VPN server. Once the default route is deleted, we add a new default route that goes through the tunnel.
On the other side of the tunnel, on your VPN server, you will need to add these commands:
iptables -I FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -I FORWARD -i tun0 -o eth0 -s 192.168.159.0/24 -m conntrack --ctstate NEW -j ACCEPT
iptables -t nat -I POSTROUTING -s 192.168.159.0/24 -o eth0 -j MASQUERADE
iptables -t nat -I POSTROUTING -o tun0 -j MASQUERADE
iptables -I FORWARD -i eth0 -o tun0 -j ACCEPT
iptables -I FORWARD -i tun0 -o eth0 -j ACCEPT
iptables -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
Now the VMs will be able to connect through the VPN tunnel and use the VPN server as default gateway.