I wish to test a subsystems which communicates with another subsystems via tcp. I have used the following:
"iptables -A OUTPUT -p tcp --dport "+port_number" -j DROP" to stop the traffic on a port so that I could via a script send my own data to the system under test. This worked really well.
I now wish however to forward the traffic to my script instead of simply dropping it. I then wish to manipulate the data in my script before forwarding it to the subsystem under test.
Can I do this using iptables? Is there a better approach?
1 Answer
You could try this (incoming traffic to port 1234 will be redirected to 4321 in the localhost, where you could have your script listening):
iptables -I INPUT -p tcp --dport 1234 -j ACCEPT iptables -I INPUT -p tcp --dport 4321 -j ACCEPT iptables -t nat -I PREROUTING -p tcp --dport 1234 -j REDIRECT --to-ports 4321 If you want to access the port 1234 from the same machine as well, you'll need to add an OUTPUT rule, as PREROUTING isn't used by the loopback interface:
iptables -t nat -I OUTPUT -p tcp -o lo --dport 1234 -j REDIRECT --to-ports 4321 Now, on the server, you can try listening with nc -l 4321 (here you could use your own script). On a client, try nc server_host_name_or_ip 1234 and write anything to verify the server is correctly doing the redirection.
Don't forget to save the iptables configuration!