Perfect Cheat Sheet for Port Forwarding with iptables

CentOS,Firewall,Infrastructure,Security,Ubuntuiptables,linux

For example, we assume that the packets received at the Node A’s interface “192.168.0.3" will be forwarded from another interface “172.20.0.1" to the destination Node B “172.20.0.11".

Forward From Node A (192.168.0.3) to Node B (172.20.0.11)

In the following example, all packets coming to ports 31000 – 31999 are forwarding to the same ports of Node B.

#TCP
iptables -t nat -I PREROUTING -p tcp -m tcp --dst 192.168.0.3 --dport 31000:31999 -j DNAT --to-destination 172.20.0.11:31000-31999	
iptables -t nat -A POSTROUTING -m tcp -p tcp --dst 172.20.0.11 --dport 31000:31999 -j SNAT --to-source 172.20.0.1
iptables -A FORWARD -m tcp -p tcp --dst 172.20.0.11 --dport  31000:31999 -j ACCEPT

If you want to do same things about udp packets, replace “tcp" to “udp" on above commands.


Allow Input Packets

Also, you need to allow those input packets.

##COMMON Allow input packets to 31000:31999 ports
iptables -A INPUT -p tcp -m multiport --dports 31000:31999 -j ACCEPT
iptables -A INPUT -p udp -m multiport --dports 31000:31999 -j ACCEPT


Allow Return Packets (Opposite Direction)

In some cases, you need to allow return packets.

iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT


How To Delete iptables’ Entries

If you add wrong entries to the iptables, you can delete them with the following steps.

Step 1. Check rule number.

iptables -L --line-numbers

Result example: You can see the rule number at the left of each entry.

$ iptables -L --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination
1    ACCEPT     tcp  --  anywhere             anywhere             multiport dports 31000:34000
2    ACCEPT     udp  --  anywhere             anywhere             multiport dports 31000:34000

Chain FORWARD (policy DROP)
num  target     prot opt source               destination
1    DOCKER-USER  all  --  anywhere             anywhere
2    DOCKER-ISOLATION-STAGE-1  all  --  anywhere             anywhere
3    ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
4    DOCKER     all  --  anywhere             anywhere
5    ACCEPT     all  --  anywhere             anywhere
6    ACCEPT     all  --  anywhere             anywhere
7    ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
8    DOCKER     all  --  anywhere             anywhere
9    ACCEPT     all  --  anywhere             anywhere
10   ACCEPT     all  --  anywhere             anywhere
11   ACCEPT     tcp  --  anywhere             node_b               tcp dpts:31000:31999
12   ACCEPT     udp  --  anywhere             node_b               udp dpts:31000:31999

Step 2. By using the rule number, delete a rule.

iptables -D [CHAIN NAME] [RULE NUMBER]

Example: Delete 11th rule at the “FORWARD" chain.

iptables -D FORWARD 11