IPTablesPortRedirection

5th June 2017 at 1:17pm
TechnicalNotes

This is also helpful when dealing with applications that need access to a port number less than 1024, that should not be run as root.

iptables -t nat -A PREROUTING -p tcp --dport 5600 -j REDIRECT --to-ports 25

What this does:

  • This specifies -t nat to indicate the nat table. Typically rules are added to the "filter" table (if you do not specify another table), and this is where the majority of the traffic is handled. In this case, however, we require the use of the nat table.
  • This rules appends (-A), which means to add the rule at the bottom of the list.
  • This rule is added to the PREROUTING chain.
  • For the tcp protocol (-p tcp)
  • The destination port (--dport) is 5600 - this is the port that the client is trying to access on your server.
  • The traffic is jumped (-j) to the REDIRECT action. This is the action that is taken when the rule matches.
  • The port is redirected to port 25 on the server.

By changing the protocol to either tcp or udp or by adjusting the dport number and the to-ports number, you can redirect any port incoming to any listening port on the server. Just remember that the dport is the port the client machine is trying to connect to (the port they configure in the mail client, for example).

We can take this further. Say for example you have a website. You don't have a load balancer or a firewall set up, but you want to split off your email traffic to a second server to reduce strain on your web server. Essentially, you want to take incoming port 25 and redirect it ... to ANOTHER SERVER. With iptables, you can make this work:

iptables -t nat -A PREROUTING -p tcp -d 200.200.200.200 --dport 25 -j DNAT --to-destination 10.10.10.10:25

What this does:

  • It specifies a destination (-d) IP address. This is not needed, but if you want to limit the email redirection to a single address, this is how you can do it.
  • It is jumped to DNAT, which stands for destination nat.
  • The destination and port are specified as arguments on to-destination

This forwards all traffic on port 25 to an internal IP address.

Now, say you want to redirect from a different incoming port to a port on another server:

iptables -t nat -A PREROUTING -p tcp --dport 5600 -j DNAT --to-destination 10.10.10.10:25
iptables -t nat -A POSTROUTING -p tcp --dport 25 -j MASQUERADE

In this example, the incoming port is different, so we need to change it back to the standard port on the way back out through the primary server.

See also: http://www.revsys.com/writings/quicktips/nat.html