Iptables – Create route through OpenVPN via specific IP address / virtual interface on Linux

iptablesopenvpnrouting

I have a Linux server at home, on which I run an OpenVPN client connected to some server on the Net. What I want to archive is this: I want my home server to expose an interface (e.g. an IP address), which I can put as the default gateway on another machine in my local network, which will then route traffic through the OpenVPN.

For example, if my home server has the internal IP 192.168.1.1, the OpenVPN IP 10.0.1.1, my external server has the OpenVPN IP 10.0.1.2 and public IP 1.2.3.4, while another computer on my network has the internal IP 192.168.1.2, I would want a traceroute to public IP 9.8.7.6 like this:


(192.168.1.2) => (192.168.1.1 > 10.0.1.1) => (10.0.1.2, 1.2.3.4) => ... => (9.8.7.6)

where each (.*) represents one computer.
I have searched through the net and didn't find a similar setup yet. The idea behind this is to have one stable (always-up) VPN tunnel instead of have to install it on all the machines. I'm guessing this has to be accomplished with iptables, but am currently at a loss of what needs to be done.

Best Answer

OpenVPN settings on 192.168.1.1

dev tun0

script-security 3

remote 1.2.3.4
port 1234

ifconfig 10.0.1.1 10.0.1.2

secret static.key

user nobody
group nobody

comp-lzo

ping 15
ping-restart 45
ping-timer-rem
persist-tun
persist-key

log /var/log/openvpn.log

verb 3

OpenVPN settings on 1.2.3.4

dev tun0

script-security 3

local 1.2.3.4
port 1234

ifconfig 10.0.1.2 10.0.1.1

secret static.key

user nobody
group nobody

comp-lzo

ping 15
ping-restart 45
ping-timer-rem
persist-tun
persist-key

log /var/log/openvpn.log

verb 3

After openvpn tunnel successfully running up you need to add the following rule on the 192.168.1.1

# iptables -t nat -I POSTROUTING -s 192.168.1.2 ! -d 192.168.0.0/16 -j SNAT --to-source 10.0.1.1

On the 192.168.1.1 you need to add the following rule

# iptables -t nat -I POSTROUTING -s 10.0.1.1 -j SNAT --to-source 1.2.3.4

Note: dont't forgot to enable ip forwarding on both side

# echo 1 > /proc/sys/net/ipv4/ip_forward
Related Topic