Redirect an external IP to localhost?

Is it possible to redirect all calls to an external IP on internet, to localhost (without use of hosts)?

I have an old application and I don't have the source code and this application try to connect to a postgres server using an IP

Can I instruct ubuntu to redirect all callings to this external IP to localhost?

In this way, I'll be able to run a postgres server on localhost and work with my application.

note: the application uses the IP, not the dns.


Solution 1:

Iptables is the way to go.

sysctl -w net.ipv4.conf.eth0.route_localnet=1 # to enable redirecting to localhost
EXTERNAL_IP=8.8.8.8 #change this line to reflect external ipaddress
sudo iptables -t nat -A OUTPUT -d ${EXTERNAL_IP} -j DNAT --to-destination 127.0.0.1

Breaking it down

  • -t nat allows you to refer to 127.0.0.1 as a valid destination.

  • -A OUTPUT, appends to the OUTPUT chain of iptables. This is a built-in chain. Other built-in chains exist like INPUT, which applies to incoming packets and PREPROCESSING, which applies to all incoming packets before any other bulit-in chain gets to them. You can also make your own chains and append them to one of these built-in chains for better management of your settings.

  • -d ${EXTERNAL_IP} filters on the destination IP-address of packets going through OUTPUT chain.

  • -j DNAT sets the target of the rule to DNAT, which allows you to modify destination address of packets.

  • --to-destination 127.0.0.1 is parameter to the DNAT target that specifies what to change about these matching packets.

You can also limit redirected ports of an address by using --dports ${ORIGINAL_PORT_NUMBER} after -d ${EXTERNAL_IP} and have them re-route to specific port by appending port to 127.0.0.1 like so 127.0.0.1:${FINAL_PORT_NUMBER}.

Removal

use the following to remove from iptables.

# note: -A is replaced by -D
sudo iptables -t nat -D OUTPUT -d ${EXTERNAL_IP} -j DNAT --to-destination 127.0.0.1

and check iptables listings with sudo iptables -t nat -L -n -v where -t nat allows you to look at iptables mappings including ones that pertain to NAT.

Further actions

You may also need to masquerade or redirect packets from your postgres server to match external IP addresses and expected port if you plan to communicate with the application and the application checks source IP address and port.

Related

  • Using iptables to redirect all traffic to my localhost
  • solution adapted from this and this.
  • maybe relevant if you need to communicate with app (iptables solution) and (postgres xinetd solution).
  • read more about iptables architecture.