Iptables – Redirecting traffic based on ports (iptables)

firewalliptableslinux-networkingnetworkingredirect

I am currently working on an application that is able to conduct ARP poisoning so as to become the man in the middle and do some intelligent filtering. I will explain the problem in details in steps so as to let you guys know what is going on.

I have 4 hosts namely:

  • A – 192.168.1.1
  • B – 192.168.1.2
  • C – 192.168.1.3
  • D – 192.168.1.4

Host A is the man in the middle so all traffic within the network will be redirected to him.

Say Host B wants to ping Host C, but since host A is the MITM, the ping will be redirected to host A. My application at host A must be able to forward the ping packet to host C (its original intended route).

However, the application can decide certain packets that it wants to forward.

For example, if Host B wants to FTP to Host C this time, I would like for host A to mangle with the destination ip address for the packets so that host B's packets actually goes to host D instead (just an example, the ftp connection might not work, its ok)

The basic idea is that the application is able to redirect traffic depending on the protocol.

This is where the problem comes in, I am not sure of how can I go about doing this. I've read up on iptables and it seems that (correct me if I am wrong), iptables is able to mangle with the destination address of packets with prerouting functions.

I've also done up some searching on a particular module called libnetfilter_queue (nfqueue) which seems to be able to mangle with packets as well, though I am not exactly sure how.

Can anybody advice me on what is the correct approach that I should take? If possible, can you provide some examples which will be able to solve the problem in the scenario above?

Best Answer

if it is ineed true what u say and all the traffic is going trough host A, then u can use iptables on host A to redirect the traffic to other hosts then intended.

f.e.: Reroute traffic from D --> C on port 80 to B

iptables -t NAT -A PREROUTING -p tcp --dport 80 -s 192.168.1.4 -d 192.168.1.3 -j DNAT --to-destination 192.168.1.2:80 

as for your example (the FTP from B to C)

iptables -t NAT -A PREROUTING -p tcp --dport 21 -s 192.168.1.2 -d 192.168.1.3 -j DNAT --to-destinatin 192.168.1.4:21

Rerouting ALL traffic coming from B intended for C to D:

iptables -t NAT -A PREROUTING -p tcp -s 192.168.1.2 -d 192.168.1.3 -j DNAT --to-destination 192.168.1.4

if more examples are needed I can make up some more