The problem: some web-server listens on 127.0.0.1:8090. How to make in accessible from certain external IP using iptables rules?
Solution:
# 1. Let eth0 accept and route packets to/from 127.0.0.0/8 sysctl -w net.ipv4.conf.eth0.route_localnet=1 echo 'net.ipv4.conf.eth0.route_localnet = 1' > /etc/sysctl.d/90-route-localnet.conf # 2. Redirect the allowed client's traffic to the loopback listener iptables -t nat -A PREROUTING -i eth0 -p tcp -s 100.64.0.2 --dport 8090 -j DNAT --to-destination 127.0.0.1:8090 # 3. Close the hole route_localnet opens (see below), then accept the DNATed flow. # After DNAT, INPUT sees dst=127.0.0.1, so match on that, not the public IP. iptables -I INPUT 1 -i eth0 -d 127.0.0.0/8 -m conntrack ! --ctstate RELATED,ESTABLISHED,DNAT -j DROP iptables -I INPUT 2 -i eth0 -p tcp -s 100.64.0.2 -d 127.0.0.1 --dport 8090 -m conntrack --ctstate DNAT -j ACCEPT
We can’t DNAT to 127.0.0.1 with iptables rules alone. By default the kernel drops any packet that arrives on a non-loopback interface with a destination in 127.0.0.0/8, because it treats it as a “martian” address. You have to allow this with route_localnet on the external interface first. After that, it’s a standard DNAT.
In the rules above, eth0 is the external interface and 100.64.0.2 is the allowed client.
The risky part - route_localnet=1 means any host that can put packets on that interface’s L2 segment can send traffic with destination 127.0.0.1 to your MAC. That traffic would reach every loopback-only service on the box, not just this one. (See CVE-2020-8558 in kube-proxy for details). The DROP rule in step 3 handles this by dropping everything to 127/8 on eth0 that wasn’t created by our DNAT. We have to keep that rule above any broad ACCEPT in INPUT.
Test from 100.64.0.2 with curl -v http://
For debugging: conntrack -L -p tcp --dport 8090 shows whether the DNAT is happening. sysctl -w net.ipv4.conf.all.log_martians=1 will log drops in dmesg if route_localnet isn’t taking effect for some reason. If the OUTPUT policy is DROP, we’ll also need to allow the reply traffic.
There are two cleaner alternatives to the proposed solution:
1. Rebind the server to the public IP or 0.0.0.0 and filter with a plain -s 100.64.0.2 --dport 8090 -j ACCEPT. Then we don’t need route_localnet and NAT.
2. A reverse proxy (HAProxy, nginx, or even socat) listening on the public IP and forwarding to 127.0.0.1:8090. This keeps the loopback boundary intact. The trade-off is that the app sees the proxy’s IP unless we pass X-Forwarded-For HTTP-header or the PROXY protocol.