4

I have got the following scenario:

I have a Linux box with two NICs and all network traffic comes in trough one NIC and goes out to the other one. So basically I'm already the man in the middle.

But now, I want to redirect all traffic which has the destination IP-address "xyz" and target port 500 to port 500 on my local machine, where my own deamon is running. Then after a certain event I want to stop the redirection (by just removing the rule or so) and just let the traffic pass, like all other traffic.

I wonder whether I can do this with iptables or some other tool already included in Linux? So far I have not found a working solution. I also have problems to run commands as root from a shell script I invoked with system(). It doesn't start as root even though I changed the ownership and privileges of the script to root. I wanted to use the shellscript to revoke the redirection (when I manage to get it working).

fuero
  • 9,591
  • 1
  • 35
  • 40
Florian
  • 41
  • 1
  • 2

2 Answers2

3

This is how you do what you asked with iptables:

sysctl net.ipv4.ip_forward=1
iptables -t nat -A PREROUTING -p tcp -d x.x.x.x --dport 500 -j DNAT --to-destination 127.0.0.1:500
iptables -t nat -A POSTROUTING -j MASQUERADE

As for your shell scripting problems, you either have to setuid the script (bad idea) or use popen() to run sudo /path/to/yourscript and configure sudo to allow the user running the C program to do this.

fuero
  • 9,591
  • 1
  • 35
  • 40
  • The Iptables command is working, thanks alot! I'm still strungling with the problem to not be able to perform a root command from my script. I have the setuid for the program and the script but i can't get it running. It always claims to need root privileges. – Florian Oct 08 '14 at 13:14
  • `127.0.0.1` won't work as the `to-destination`, it's necessary to use the local machine's IP address. – user202729 Apr 15 '19 at 16:11
  • I need to do something like that in a production box, but I'm afraid of locking myself out with the `-A POSTROUTING -j MASQUERADE`, is there any risk in running that? – Marcel May 28 '20 at 12:29
0

You should be able to do this with an iptables rule in the nat table and PREROUTING change. Something like this:

iptables -t nat -A PREROUTING -d xyz -p tcp --dport 500 -j DNAT --to-destination zyx:1111

This is assuming you have ipv4 forwarding enabled via sysctl, which I assume you are since traffic is already passing through the router.

I'm unable to test this at the moment, but that should be a good starting ground.

Gene
  • 3,663
  • 20
  • 39