iptables redirect from external interface to loopback's port?

innocent-world picture innocent-world · Sep 2, 2013 · Viewed 8.7k times · Source

I try to redirect port from my lxc-container to loopback.

My lxc-container configured with lxcbr1 bridge 11.0.3.1.

I try to connect with netcat from host to lxc, and from lxc to host. Success.

localhost:

# nc -l 1088

lxc:

# nc 11.0.3.1 1088
Hello!

And localhost See message: "Hello!". Success!

When I redirect port that way:

# iptables -t nat -A PREROUTING -i lxcbr1 -p tcp -d 11.0.3.1 --dport 1088  -j DNAT --to-destination 127.0.0.1:1088
# nc -l 127.0.0.1 1088

Thereafter, i try to connect from lxc-container:

# nc 11.0.3.1 1088
Hello !

But localhost doesn't see this message.

Where am i wrong?

I found this answer: https://serverfault.com/questions/211536/iptables-port-redirect-not-working-for-localhost

There sound words that loopback doesn't use PREROUTING. What should i do?

Answer

innocent-world picture innocent-world · Sep 3, 2013

DNAT for loopback traffic is not possible.

I found alot of similar questions. 1, 2, 3, etc...

According to RFC 5735, network 127.0.0.0/8 should not be routed outside host itself:

127.0.0.0/8 - This block is assigned for use as the Internet host loopback address. A datagram sent by a higher-level protocol to an address anywhere within this block loops back inside the host. This is ordinarily implemented using only 127.0.0.1/32 for loopback. As described in [RFC1122], Section 3.2.1.3, addresses within the entire 127.0.0.0/8 block do not legitimately appear on any network anywhere.

RFC 1700, page 5, «Should never appear outside a host».

There is one of exits: use inetd.

There are many inted servers, xinetd, etc.

My choice was rinetd.

I use this manual http://www.howtoforge.com/port-forwarding-with-rinetd-on-debian-etch

My config looks like this:

$ cat /etc/rinetd.conf 
# bindadress    bindport  connectaddress  connectport
11.0.3.1        1081            127.0.0.1       1081
11.0.3.1        1088            127.0.0.1       1088

I restart rinetd:

$ /etc/init.d/rinetd restart
Stopping internet redirection server: rinetd.
Starting internet redirection server: rinetd.

And redirection works like a charm.

I will not close this question by myself, cause I still in looking for more elegant solution for such task. It is unlikely to do this by any animal, netcat or inetd, it doesn't matter. This is my opinion.