2009-09-04

Routing a port through a machine that's not the default router

I have an OpenVPN machine on my network that hosts a VPN, but it is not the default router for the network. I wanted to forward a port for the OpenVPN clients so that they could see another machine on the local network. To do this requires a number of steps.

First, the machine that they'll be connecting to needs a default route added for the OpenVPN network, or the packets will never return. My OpenVPN network is 172.31.4.0 and my local network is 192.168.200.0 in these examples. The OpenVPN server is 172.31.4.1 and 192.168.200.70 on tun0 and eth0 respectively; the machine I want my OpenVPN clients to be able to connect to on port 6666 is 192.168.200.10.

route add -net 172.31.4.0 netmask 255.255.255.0 gw 192.168.200.70 dev eth0

This allows the server to return TCP. Of course, the machine must have its firewall set to allow port 6666 in, but that's simple.

Then, the OpenVPN server needs its forwarding enabled. The commands that worked for me were:

iptables -t nat -A PREROUTING -p tcp --dport 6666 -j DNAT --to 192.168.200.10
iptables -A FORWARD -p tcp -s 192.168.200.10 --sport 6666 -j ACCEPT
iptables -A FORWARD -p tcp -d 192.168.200.10 --dport 6666 -j ACCEPT

This allows the communication in, and the response back out. I had also added these lines to my INPUT and OUTPUT chains; I'm not sure if they were needed:

iptables -A firewall-input -p udp --dport 6666 -j ACCEPT
iptables -A firewall-output -p tcp -m state --state NEW -m tcp --dport 6666 -j ACCEPT

If not, they don't hurt anything.