Use iptables nat to redirect gateway for LAN PCs

3

I have a Linux server which functions as the gateway for my home network. It has two ethernet devices:

  • p3p1: WAN, public IP address a.b.c.d
  • p2p1: LAN, private IP address 10.0.3.1/24

It also connects via a point-to-point OpenVPN tunnel to a remote Linux server (which I also administrate). This adds the device

  • tun2: VPN, private IP address 10.2.0.2/32

The question is: how do I make all traffic from clients on the LAN redirect through the OpenVPN tunnel?

I can redirect all traffic (including that originating from the gateway server) using the VPN client configuration option redirect-gateway def1. But that isn't what I want.

Would there be a way to do this using IPTables NAT?

Thanks!

Fela Maslen

Posted 2017-08-18T17:39:54.117

Reputation: 339

Answers

1

I managed to do this using policy based IP routing, as A. Fendt mentioned in a comment:

  1. Insert a new IP routing table:

$ echo "200 vpndef1" | sudo tee -a /etc/iproute2/rt_tables

  1. Add routes for the VPN redirect:

$ sudo ip route add 10.0.3.0/24 via 10.0.3.1 dev p2p1 table vpndef1 $ sudo ip route add default via 10.2.0.1 dev tun2 table vpndef1

  1. Insert a new rule to direct LAN traffic to the new routing table:

$ sudo ip rule add from 10.0.3.0/24 lookup vpndef1

Fela Maslen

Posted 2017-08-18T17:39:54.117

Reputation: 339

1

Here are the Steps you should do:

  1. In the first step your local DHCP Server has to configure the Client default gateway to your Server Address 10.0.3.1
  2. Then use the routing policy database to route your local network traffic to the VPN Default Gateway behind p2p1 and route your servers traffic to the default gateway behind p3p1
  3. After that you have to MASQUERADE your traffic which comes from your local network and goes into the VPN:
# enable ip forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

# configure iptables
iptables -t nat -A POSTROUTING -s 10.0.3.0/24 -d 10.2.0.2/32 -j MASQUERADE
iptables -P FORWARD DROP
iptables -A FORWARD -i p2p1 -o tun2 -j ACCEPT
iptables -A FORWARD -m state --state ESTABLISHED -j ACCEPT

A. Fendt

Posted 2017-08-18T17:39:54.117

Reputation: 73

The default gateway is already set to the server. I don't want to redirect all traffic, only traffic originating from the LAN (i.e. I don't want to redirect traffic from the server itself over the VPN). – Fela Maslen – 2017-08-18T22:25:36.560

2

In this case remove the redirect-gateway def1 directive and create some policy based routing entries: http://www.tldp.org/HOWTO/Adv-Routing-HOWTO/lartc.rpdb.simple.html As you said: every traffic from the local network goes to the VPN Default Gateway and the traffic of the server goes to the Default Gateway behind p3p1.

– A. Fendt – 2017-08-20T16:08:02.157