Networking – Redirect IP to another IP using iptables

iptablesnetworkingopenvpn

I have a machine connected to a openvpn server on address 1.2.3.4. My machine has an IP 192.168.1.0/24 and it can reach the 1.2.3.4 address. Once I connect to the openvpn server a new interface tun0 is created and the IP address 192.168.0.6 is assigned to it. I can ping the machine hosting the VPN on IP address 192.168.0.1. Traffic goes through interface tun0 as expected.

Can I set some iptables rules to force traffic to go through tun0 even if I ping directly 1.2.3.4? In particular I would like to limit this only to port 80 of 1.2.3.4

Best Answer

So firstly we need to change our default route. Running ip route should show that the current default route is the gateway for the 192.168.0.0/24 VPN network. This needs to be changed (while connected to the VPN) by removing the current default route and creating a new one pointing to your local network's gateway/router (not vpn). So if your local network gateway is 172.16.2.1 you would run:

  • sudo ip route del default
  • sudo ip route default via 172.16.2.1

Now if you run ip route and route -n you should see that the new default route is now pointing to your local network and no traffic should be going through your VPN tunnel by default.

Now we can move on to redirecting all outgoing traffic on port 80/443 to your VPN's gateway.

  • sudo iptables -t nat -A OUTPUT -p tcp --dport 80 -j DNAT --to-destination 192.168.0.1:80
  • sudo iptables -t nat -A OUTPUT -p tcp --dport 443 -j DNAT --to-destination 192.168.0.1:443

Now this should forward/redirect any web traffic going outbound to your VPN's default gateway/router and all other traffic to go out locally by default.

Give it a try and let me know if it achevies what you are looking for!