Port Forwarding in Different Network Scenarios

Port forwarding is a useful technique for rerouting network traffic from one port to another, or even to a different machine altogether. This blog post will guide you on how to forward a port on one machine to another port on a different machine using iptables. In this example, we will use the subnet in the 192.0.0.0/16 range.

Network Configuration

  • ClientIP 192.168.0.240
  • Machine1 192.168.0.2 port 2020
  • Machine2 192.168.1.2 port 1010

Enabling IP Forwarding

The kernel needs to allow forwarding. To do this temporarily, use the sysctl command:

sysctl -w net.ipv4.ip_forward=1

To make it permanent, modify /etc/sysctl.conf and add the following line:

net.ipv4.ip_forward = 1

You can check if IP forwarding is enabled by viewing the content of the /proc/sys/net/ipv4/ip_forward file:

cat /proc/sys/net/ipv4/ip_forward

Setting Up IPTables Rules

Now we need to set up iptables rules to redirect the source port to Machine2’s IP and port. We also need to masquerade the traffic so Machine2 answers to Machine1, which in turn answers to the client.

iptables -t nat -A PREROUTING -p tcp --dport 2020 -j DNAT --to-destination 192.168.1.2:1010
iptables -t nat -A POSTROUTING -j MASQUERADE -s 192.168.0.240 -d 192.168.1.2

Since traffic is moving from PREROUTING to FORWARD to POSTROUTING, we need to make the FORWARD chain aware and accept the traffic from the client and not drop it before it reaches POSTROUTING.

iptables -A FORWARD -s 192.168.0.240 -d 192.168.1.2 -j ACCEPT
iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -s 192.168.1.2 -d 192.168.0.240

To monitor the iptables rules, use these commands:

watch iptables -t nat -L -n -v
watch iptables -L -n -v

Forwarding to Internal Localhost

To forward to localhost, you need to enable it on the kernel for the interface in question:

sysctl -w net.ipv4.conf.ens18.route_localnet=1

You can set up the forwarding from one host, from one subnet, or even from one MAC address:

iptables -t nat -A PREROUTING -i ens18 -p tcp -s 192.168.0.123 --dport 8001 -j DNAT --to-destination 127.0.0.1:8001
iptables -t nat -A PREROUTING -i ens18 -p tcp -d 192.168.0.0/24 --dport 8001 -j DNAT --to-destination 127.0.0.1:8001
iptables -t nat -A PREROUTING -i ens18 -p tcp -m mac --mac-source 00:0F:EA:91:04:07 --dport 8001 -j DNAT --to-destination 127.0.0.1:8001

You can even block all traffic except for a specific MAC address:

/sbin/iptables -A INPUT -p tcp --dport 22 -m mac ! --mac-source YOUR-MAC-ADDRESS-HERE -j DROP

Remember to save the iptables rules:

/sbin/service iptables save

By using these steps, you should be able to successfully forward traffic from one machine to another, or from one network to another, with iptables.



Buy Me a Coffee