Iptables – OpenVPN route remote traffic depending of the subnet

iptablesopenvpn

I achieved to setup an OpenVPN to route all the traffic through a remote openvpn server.

The OpenVPN server have two interfaces :
eth0 -> Internet access
eth1 -> Private network : 192.168.1.0/24

Now, all the traffic is natted with Eth0.

server.conf

# SERVER UDP/9494
mode server
proto udp
port 9494
dev tun
tcp-queue-limit 128
tun-mtu 1500
mssfix 1300
tun-mtu-extra 32
txqueuelen 15000
# KEYS
ca ca.crt
cert server.crt
key server.key
dh dh2048.pem
tls-auth ta.key 0
cipher AES-256-CBC
# NETWORK
server 192.168.2.0 255.255.255.0
push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 4.4.4.4"
push "dhcp-option DNS 8.8.8.8"
keepalive 10 120
# SECURITY
user nobody
group nogroup
chroot /etc/openvpn/jail
persist-key
persist-tun
comp-lzo
# LOGS
verb 3
mute 20
status openvpn-status.log
; log-append /var/log/openvpn.log

Iptables :

iptables -A INPUT -p udp --dport 9494 -d $SERVER_IP --sport 1024:65535 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -I FORWARD -i tun0 -j ACCEPT 
iptables -I FORWARD -o tun0 -j ACCEPT 
iptables -I OUTPUT -o tun0 -j ACCEPT 
iptables -A FORWARD -i tun0 -o eth0 -j ACCEPT 
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE 
iptables -t nat -A POSTROUTING -s 192.168.2.0/24 -o eth0 -j MASQUERADE  

I want to do the same except for the range 192.168.1.0/24 who have to be natted to Eth1

How can I do that with iptables ?

Thanks for advices

Best Answer

I think you should add the rules for the private network in the POSTROUTING and FORWARD too, but should define them before the rest of the POSTROUTING rules.

Also, if I see correctly the first POSTROUTING rule without any source network specification matches all your packets so the next line will never match - remove this.

So I think your iptables rules should look like this:

iptables -A INPUT -p udp --dport 9494 -d $SERVER_IP --sport 1024:65535 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -I FORWARD -i tun0 -j ACCEPT
iptables -I FORWARD -o tun0 -j ACCEPT
iptables -I OUTPUT -o tun0 -j ACCEPT
iptables -A FORWARD -i tun0 -o eth0 -j ACCEPT
iptables -A FORWARD -i tun0 -o eth1 -j ACCEPT
iptables -t nat -A POSTROUTING -s 192.168.2.0/24 -d 192.168.1.0/24 -o eth1 -j MASQUERADE
iptables -t nat -A POSTROUTING -s 192.168.2.0/24 -o eth0 -j MASQUERADE

Maybe you should put some logging in place to see if you need reconfiguration or have missed anything.

After the above rules add:

iptables -A FORWARD -j LOG --log-prefix 'iptables-forward: '
iptables -t nat -A POSTROUTING -j LOG --log-prefix 'iptables-postrouting: '
Related Topic