Selective port forwarding

September 18, 2012

A short post to document the solution that was used in a somehow reoccurring situation.
A colleague had a machine in the internal network that he wanted to provide access to someone outside our network. Lets assume that the IP of the internal machine is xxx.xxx.xxx.xxx and the external IP of the other person is yyy.yyy.yyy.yyy.
The solution was to use his machine as a gateway and with port forwarding. The interesting part is what happens if we want to forward a port that a service already listens to. It his case the solution is easily done using iptables, using the following script:

echo "1" > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -j DNAT -p tcp -s yyy.yyy.yyy.yyy --dport pp --to-destination xxx.xxx.xxx.xxx:pp
iptables -t nat -A POSTROUTING -p tcp -s xxx.xxx.xxx.xxx -j MASQUERADE
iptables -t nat -A POSTROUTING -p tcp -d xxx.xxx.xxx.xxx -j MASQUERADE

In case the default policy for PREROUTING is DROP another rule is needed:

iptables -t nat -A PREROUTING -p tcp --dport pp -j ACCEPT

This way the machine with IP yyy.yyy.yyy.yyy can access the service in the internal machine, whereas the all the other machines will just use the service that runs in the local machine.

I can think a number of usages of this case. It can be done in order to provide a small authentication daemon on that same port, that when someone authenticates he can be added to the port forward chain, or a small service that bans IPs that try to connect to this service if they are not explicitly permitted

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: