Linux – iptables port forwarding to localhost

iptableslinuxnetworkingSecurity

On my linux server, using iptables on the same box, I'd like to redirect traffic to my external interface on port 1234/tcp to the loopback interface on 32400/tcp in order to hide plex server default port.
I can't apply filtering based on IP addresses, as I'm using this from different IPs.

I'm doing this:

# enables forwarding output traffic from eth0 to 1234/tcp to 127.0.0.1:32400 tcp
iptables -t nat -I PREROUTING -i eth0 -p tcp --dport 1234 -j DNAT --to 127.0.0.1:32400
iptables -I FORWARD -p tcp -d 127.0.0.1 --dport 32400 -j ACCEPT
# let the kernel accept public IPs accessing loopback interface
echo 1 > /proc/sys/net/ipv4/conf/all/route_localnet
echo 1 > /proc/sys/net/ipv4/conf/all/forwarding

This only works if I keep port 32400/tcp allowed to the external traffic using:

iptables -I INPUT -p tcp --dport 32400 -j ACCEPT
iptables -I INPUT -p tcp --dport 1234 -j ACCEPT

I only want to have 1234/tcp open to the outside and block 32400/tcp
Any idea on why I'm failing here?

Thanks

Best Answer

In order to meet your goal, just specify the interfaces where the port should be allowed.

In your case limiting 32400 to loopback interface by adding -i lo should do the trick:

iptables -I INPUT -i lo -p tcp --dport 32400 -j ACCEPT

Please take into account that you are adding rules with -I and you didn't paste a whole ruleset, and it might be relevant.

Also, you may consider just reconfiguring your service to use a port different from 32400.