Using netfilter as a loopback device is surprisingly simple and can let you tap into that network conversation between components on a platform that tends to be hidden by the OS in its own loopback device. Here’s how:
iptables -t nat -A PREROUTING -s 192.168.122.2 -d 192.168.2.7 -p tcp --dport 80 -j DNAT --to 192.168.122.2:80 iptables -t nat -A POSTROUTING -s 192.168.122.2 -d 192.168.122.2 -p tcp --dport 80 -j SNAT --to 192.168.2.7
Well that’s the netfilter bit done! But of course there’s a bit more setup than this. Firstly you need to have your netfilter, soon to be loopback, host on the same subnet as the box that we are working with. Next you need to configure the client that makes the connection to the other component on the same box point to the netfilter host. Finally you need to work out which addresses and ports go where in the statements above when you execute them.
In the case above we are intercepting the communication between the HTTP client and server that are both hosted on the same box 192.168.122.2. The netfilter loopback is being hosted on 192.168.122.1. For my worked example here the client/server box is actually a virtual machine guest and the netfilter configuration is being placed on the virtual machine host. Note the third address I used here 192.168.2.7 is bound to another ethernet card in the virtual machine host. The third address is necessary, for no other reason than to help with the clarity of this example and to get the routing right.
Our first rule catches the inbound requests from our guest and redirects them back to the guest. Note that the rule is restricted to a specific initial destination, source, protocol and port so that no other hosts will be affected. In fact the rule will only catch the exact scenario that we want. However this is not the complete picture. If we were to try to browse from the client to 192.168.2.7 on port 80 and capture the chatter on 192.168.122.1 using tcpdump we would get the following:
16:54:37.800369 IP (tos 0x0, ttl 64, id 17896, offset 0, flags [DF], proto TCP (6), length 60) 192.168.122.2.41418 > 192.168.122.2.http: S, cksum 0x496b (correct), 901912667:901912667(0) win 5840E.. Here you see the first syn of the TCP three part handshake leaving the host and going back to the guest with the guest's IP address as the source! It is the packet going out of the host to the guest but the guest is not going to be able to route it back. This is where the second rule steps in. It is applied after the packet is routed by netfilter and it replaces the source address with 192.168.2.7. Now the client on the guest can communicate with the server on the guest and you can use tcpdump on the host to look at their conversation.