Iptables as Tunnel

1 minute read

My requirement is: I have a service listening to only, I want to make it accessible on port 4040 of any IP address, not just, so other host in the LAN can access it.

I usually use SSH Tunnel (with -L) to achieve this. It’s easy and works on most scenarios, as long as I have access to a SSH shell, even when iptables is not installed. But I decided to practice my knowledge by using iptables.

My thought was to DNAT . It’s basically correct, only I got stuck:

iptables -t nat -A OUTPUT -p tcp -d --dport 4040 -j DNAT --to-destination

It doesn’t work. Googling shows I need to set the route_local to 1:

sysctl -w net.ipv4.conf.eth0.route_localnet=1
sysctl -p

It’s due to security reason. Like ip_forward, we have to explicitly change the kernel setting to allow traffic forwarded to loopback interface.

Plus this is required for accessing from the host itself:

iptables -t nat -A OUTPUT -p tcp --dport $port -j DNAT --to

For the scenario of forwarding to another host, I also put notes here (Listening to 80 on (host with the iptables rules) and forwarding the traffic to :

iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination
iptables -t nat -A POSTROUTING -p tcp -d --dport 8080 -j SNAT --to-source



Categories: Tech