1

In this answer, How can I open a range of ports in ubuntu using (g)ufw, a simple command for opening a range of ports is given.

For example, using this command I can open the ports 1000-1999 very easily for my firewall on my local machine.

Now, though, I would like to set-up port forwarding on the local machine, so that:

  • Port 1001 forwards to port 1
  • Port 1002 forwards to port 2
  • Port 1003 forwards to port 3
  • ... etc
  • -

Does anyone have a simple bash script for doing this?

I have to do this for multiple machines on a local network. Constraints by the router are making this more difficult than it needs to be.

So machine A, ports 1000-1999 on the router would be opened to link to machine A. On machine A, they would be forwarded to the traditional port. For machine B, ports 2000-2999 on the router would be used (mapped to the appropriate port locally). Etc

1 Answers1

1

[Mostly Stolen from the Internet]

Enable IP forwarding:

sysctl net.ipv4.ip_forward=1

Use the "nat" table to forward traffic:

iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination X.X.X.X:80

Don't forget about HTTPS:

iptables -t nat -A PREROUTING -p tcp --dport 443 -j DNAT --to-destination X.X.X.X:443

Ask iptables to masquerade:

 iptables -t nat -A POSTROUTING -j MASQUERADE

....and if you want that for each port in a range, i suggest something alike:

 #!/bin/bash
 y=0;  //first port to map to = 1, but y++ happens before mapping, so 0
 for i in {2000..2999}
    do
       ((y++));  
       echo "forwarding port $i to port $y";
       iptables -t nat -A PREROUTING -p tcp --dport $i -j DNAT --to-destination X.X.X.X:$y;
 done

Note:

  • system ports 1-1000 are reserved, so the above script is a bad idea ;)
  • offcourse substitute X.X.X.X with localhost or wherever you want to nat-forward
Gewure
  • 363