Forwarding a Localhost:Port to an ExternalIP:NewPort

We have got an application running on our linux server. From that application, when we try and access localhost(127.0.0.1):localport, it should be forwarded to an external IP. Users will only try and access the localhost on a certain port which will be automatically forwarded.
I read up on iptables nat table, but PREROUTING and POSTROUTING will not be applicable if am right since I am accessing a port on localhost from localhost itself which doesn’t touch the network interface at all. Wondering OUTPUT table might be useful but when I tried some combinations, it didn’t work. Am I using the right thing or is it not possible at all to do it?

Can someone point me in the right direction?

Asked By: keerthi

||

The easiest way of accomplishing this is to install netcat and inetd (Debian has this in openbsd-inetd).

Add a line to /etc/inetd.conf:

127.0.0.1:1234 stream tcp nowait root /bin/nc nc ex.ter.nal.ip 1234

Replace the 1234 with the real port number and ex.ter.nal.ip with the real external IP address. You may need to append .1000 or some larger number to the nowait option if more than 128 connections per minute need to be made; this is to prevent runaway connections from loading your system unneccessarily.

I also have -q 4 -w 10 as nc options as that helps in my situation, but you might not need it.

Reload inetd after modifying the inetd.conf file.

Doing it this way uses nc started by inetd as a relay process, which works quite well.

Answered By: wurtel

I have figured to do this myself.

2 rules and a flag should be set to achieve this.

Example used here is for telnet localhost XXXX, should forward packets to Ext.er.nal.IP:YYYY.

sysctl -w net.ipv4.conf.all.route_localnet=1

This flag unfortunately exists only on quite latest Linux kernels and not available on an old kernel (there isn’t any alternate flag as well in the old kernel). Am quite not sure which exact kernel is the flag available from though. I believe it is available on kernel versions 3.XX.

This flag is to consider the loopback addresses as a proper source or destination address.

Source for ip sysctl command.

iptables -t nat -A OUTPUT -p tcp --dport XXXX -j DNAT --to-destination Ext.er.nal.IP:YYYY

The above command will alter the packets that is to localhost:XXXX with the destination IP as Ext.er.nal.IP:YYYY

iptables -t nat -A POSTROUTING -j MASQUERADE

The command will alter the source IP as the public ip of your machine.

You could make your rules a bit more strict by adding appropriate source and destination IP and interfaces using -s, -d, -i and -o. See man iptables.

Thanks to John WH Smith and Wurtel. Suggestions were very helpful.

Answered By: keerthi
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.