Redirect IP to another IP using iptables

6,962

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!

Share:
6,962
Blindstealer
Author by

Blindstealer

Updated on September 18, 2022

Comments

  • Blindstealer
    Blindstealer over 1 year

    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

    • G-Man Says 'Reinstate Monica'
      G-Man Says 'Reinstate Monica' over 6 years
      Are you sure it doesn’t already?
    • Blindstealer
      Blindstealer over 6 years
      @G-Man this is true if you have a field "redirect-gateway def1" in your certificate, but I configured my OpenVPN server to not fill that field. Using that field 192.168.0.1 became your default gateway, but I want only traffic to 1.2.3.4 to go through the VPN (a ping to 8.8.8.8 should not go over the VPN in my scenario)
    • xR34P3Rx
      xR34P3Rx over 6 years
      Firstly, could you post what the output of ip route is? It should show that your default route is going through tun0.