Friday, January 10, 2014

Some iptables magic

Here's a quick run down of something I had to do a while ago. So the situation was that I needed to redirect traffic to a different server only for a certain port and allow other traffic to flow as normal. The redirected traffic had to appear to come from the original source as well. This isn't too complicated but here were the details.

Basic Layout (server with iptables in the middle)
Here was the very basic iptables configuration.

  • eth0 is the internet side
  • eth1 is to the masquerade server at the top (10.0.0.1)
  • eth2 is to the switch (internal net)
  • Below is for port 80 redirection but should work for others
  • 192.168.1.2 is the client computer


$#Set up IPtables
$iptables --flush
$iptables --table nat --flush
$iptables --delete-chain
$iptables --table nat --delete-chain
$iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE
$echo 1 > /proc/sys/net/ipv4/ip_forward
$iptables -A FORWARD -j ACCEPT -d 192.168.1.2
$iptables -A FORWARD -p tcp --dport 80 -j DROP
$iptables -A FORWARD --in-interface eth2 -j ACCEPT
$iptables -A INPUT -j ACCEPT
$iptables -A OUTPUT -j ACCEPT
$#Redirecting port 80 stuff
$iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 10.0.0.1:80
$iptables -t nat -A POSTROUTING -j MASQUERADE

The line "iptables -A FORWARD -p tcp --dport 80 -j DROP" can be a little misleading. This should ideally never get a hit. The prerouting should be sending the packet off before the forward table gets applied. It was added as more of a just-in-caseThis config should allow all other traffic to the internet as normal but any port 80 traffic will get redirected to the specified server. The ip address for the client will continue to show the original destination IP on any returned packets as well. How does it do that? 
  • The client does a DNS lookup for the hostname entered (or use a direct IP)
  • Forms the packet and sends it off to the iptables server
  • The iptables server sees teh destination is one that it is configured to send elsewhere
  • The iptables remember the original ip address and forward it on to the masquerade server
  • When the traffic returns, iptables rewrites the returning packet with the original IP address it should of had
  • Rinse and repeat

The ability to use this for traffic interception has been very useful for monitoring rogue applications or setting up a tarpit to accept anything and log/alert for what you configured in iptables. Yeah yeah you could just block the port or destination, but something like this is for when you want to find out more about what is happening by allowing a conversation to happen. You can even go deeper and configured your masquerade server to be whatever the rogue connection is expecting (http, pop, smtp, dns, etc).

No comments:

Post a Comment