[olug] IP Tables for port forwarding

Christopher Cashell topher-olug at zyp.org
Mon Nov 2 23:08:41 UTC 2009


On Mon, Nov 2, 2009 at 11:17 AM, Todd Christopher Hamilton
<netarttodd at gmail.com> wrote:
> If you receive a connection from ip 10.1.1.2 on port 8081 then forward
> the connection to ip 10.1.1.3 on port 8082.
>
> What do you think?

This is definitely doable.

First thing to do (after making sure you have iptables installed) is
to make sure that you have IP Forwarding enabled.  You can verify it
with:

# cat /proc/sys/net/ipv4/ip_forward

or

# sysctl net.ipv4.ip_forward

It should return a value of 1.  If it returns a value of 0, you need
to enable it via one of the following methods:

# echo '0' > /proc/sys/net/ipv4/ip_forward

or

# sysctl -w net.ipv4.ip_forward=1

or

add the line 'net.ipv4.ip_forward=1' to /etc/sysctl.conf and run
'sysctl -p' (this last option is probably the best if you want to use
this beyond testing, as it will ensure that IP Forwarding gets enabled
if the machine reboots).

> If you receive a connection from ip 10.1.1.2 on port 8081 then forward
> the connection to ip 10.1.1.3 on port 8082.

Now, after you've gotten IP Forwarding turned on, you can start adding
your iptables rules.  Based on the requirements you listed, I'd
probably use the following rule:

iptables -t nat -A PREROUTING -i eth0 -s 10.1.1.2 -p tcp --dport 8081
-j DNAT --to-destination 10.1.1.3:8082
iptables -A FORWARD -i eth0 -s 10.1.1.2 -d 10.1.1.3 -p tcp --dport
8082 -j ACCEPT
iptables -A FORWARD -j DROP

In English: Add a rule to the NAT table to alter matching packets
before processed for routing by the the system.  If the packets come
in on interface eth0, from a source of 10.1.1.2, are TCP packets, and
the destination port is 8081, then rewrite the packet's destination to
10.1.1.3, port 8082.  Add another rule to allow packets coming in on
interface eth0 from 10.1.1.2 being sent to 10.1.1.3, destination port
8082, to be passed through the system.  Note that by the time this
rule is processed, the packet headers have already been rewritten, so
we need to match on the new destination.  The last rule ensures that
we're only forwarding packets that we've previously explicitly
allowed. Security first. ;-)

If you want to forward all connections on port 8081, regardless of the
source, you can leave out the '-s' bit and use:

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8081 -j DNAT
--to-destination 10.1.1.3:8082
iptables -A FORWARD -i eth0 -d 10.1.1.3 -p tcp --dport 8082 -j ACCEPT
iptables -A FORWARD -j DROP

Same rule as above, but now we aren't limiting the match to only
packets with a source of
 10.1.1.2.

Hopefully the above made sense.  If not, please let me know and I'll
try to clarify or explain better.  Also, note that each line above
begins with 'iptables'.  If any of them wrapped in the e-mail, you
might need to recombine them.

-- 
Christopher



More information about the OLUG mailing list