You need to implement policy routing, which means having two routing tables. We shall not touch the main
routing table which is already correctly setup. If you have enabled IPv4 forwarding, it will automatically push the packets from eth1 through your OpenVPN.
First, we need to learn how your OpenVP sets up the routing table. To this, end, start the OpenVPN client from the command line:
sudo openvpn --config YourConfigFile.conf
(or YourConfigFile.ovpn
, whichever you use). The last lines will tell you how it sets up the new routing table, for instance in my case it says:
Tue Jul 14 18:58:07 2015 /sbin/ip route add My.Server.Public.IPaddress/32 via 192.168.105.1
Tue Jul 14 18:58:07 2015 /sbin/ip route add 0.0.0.0/1 via 10.8.73.5
Tue Jul 14 18:58:07 2015 /sbin/ip route add 128.0.0.0/1 via 10.8.73.5
Tue Jul 14 18:58:07 2015 /sbin/ip route add 192.168.73.0/24 via 10.8.73.5
Tue Jul 14 18:58:07 2015 /sbin/ip route add 10.8.73.0/24 via 10.8.73.5
Tue Jul 14 18:58:07 2015 Initialization Sequence Completed
The routes above should be introduced into an executable file, except that some of these numbers are peculiar to this particular instance of the VPN. OpenVPN however provides useful environmental variables which will hold the values of the interfaces used above, and which come in very handy: in this specific case, they are
route_net_gateway -> 192.168.105.1 route_vpn_gateway -> 10.8.73.5
Thus the lines you need to add to a file (let's call it /etc/openvpn/route_up.sh
) are:
/sbin/ip route add Your.OpenVPN.Server.IPAddress/32 via $route_net_gateway table vpn /sbin/ip route add 0.0.0.0/1 via $route_vpn_gateway table vpn /sbin/ip route add 128.0.0.0/1 via $route_vpn_gateway table vpn /sbin/ip route add Remote.LAN.Net/24 via $route_vpn_gateway table vpn /sbin/ip route add 172.18.2.0/24 via $route_vpn_gateway table vpn
Remember to substitute, in the above, the IP address of your remote server, and of its local LAN if you use it; if you are just using the OpenVPN to obtain an IP of your server, then you do not need the next to the last statement at all. Remember to make the file executable, chmod 700 route_up.sh
.
Also, you will also have to create a new file, /etc/openvpn/route_down.sh
, also executable, which tears down exactly the same routes (just change add
to del
).
Now we need to tell your OpenVPN to avoid implementing the routes, because we will do this manually: in your YourConfigFile.conf, add the following lines:
route-nopull up /etc/openvpn/route_up.sh down /etc/openvpn/route_down.sh
Lastly, we need to setup the different routing table for the VPN. Add a new routing table, let's call it vpn
:
echo 200 vpn >> /etc/iproute2/rt_tables
Now we introduce a rule:
ip rule add from 10.0.0.0/24 table vpn
where I assumed that the network behind eth1
is 10.0.0.0/24
, if it is not please change accordingly.
Lastly, you will have to introduce a MASQUERADE iptables rule:
iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE
This is it.