Linux – Mirror all traffic from one port to another on localhost using iptables

iptableslinuxnetworking

i need to mirror all packets from port 162 to another (for example 1162) on localhost.

I know that TEE can mirror packets but to some ip address.

Maybe it is possible in one rule change also destination port, but i can't find working solution.

Something like that:

iptables -t mangle -A PREROUTING -d 0.0.0.0:162 -j TEE –to-destination 0.0.0.0:1162

But from manual:
Send the cloned packet to the host reachable at the given IP address. Use of 0.0.0.0 (for IPv4 packets) or :: (IPv6) is invalid.

Thanks for any hint.

OS:RedHat 6.9

Best Answer

It seems that there are some misunderstanding :

I need to mirror all packets from port 162

your rule should include --sport 162 or --dport 162 if you meant "all packets arriving to port 162"

--to-destination 0.0.0.0:1162

In fact 0.0.0.0 does not match the localhost. You should use 127.0.0.1 instead.

Finally you can try for TCP traffic:

iptables -t mangle -A PREROUTING -p TCP --dport 162 -j TEE --gateway 127.0.0.2
iptables -t nat -A PREROUTING -d 127.0.0.2 -p TCP --dport 162 -j DNAT  --to 127.0.0.1:1162

The first rule copies the traffic to localhost 127.0.0.2:162. The second rule forwards traffic from 127.0.0.2:162 to 127.0.0.1:1162.

Please note that as traditional port forwarding which apply to POSTROUTING chain, the second rule applies to PREROUTING. This is because we deals with localhost addresses so that POSTROUTING chain of nat table is not crossed by packet.

An for UDP traffic:

iptables -t mangle -A PREROUTING -p UDP --dport 162 -j TEE --gateway 127.0.0.2
iptables -t nat -A PREROUTING -d 127.0.0.2 -p UDP --dport 162 -j DNAT  --to 127.0.0.1:1162
Related Question