Iptables - Redirect outbound traffic on a port to inbound traffic on 127.0.0.1

Is there a way to redirect traffic set to go out of the server to another IP, back to the server on localhost (preferably as if it was coming from the original destination)?

I'd basically like to be able to set up my own software that listens on say, port 80, and receives traffic that was sent to say, 1.2.3.4.

So as an example with some code. Here would be the server:

my $server = IO::Socket::INET->new(

    LocalAddr => '127.0.0.1',
    LocalPort => '80',
    Listen => 128,

);

And that would receive traffic from the following client:

my $client = IO::Socket::INET->new(

    PeerAddr => 'google.com',
    PeerPort => '80',

)

So rather than having the client be connecting to google.com, it would be connecting to the server I have listening on localhost for that same server.

My intention is to use this to catch malware connecting to remote hosts.

I don't specifically need the traffic to be redirected to 127.0.0.1, but it needs to be redirected to an IP the same machine can listen to.

Edit: I've tried the following, and it doesn't work--

echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 127.0.0.1:80
iptables -t nat -A POSTROUTING -j MASQUERADE

Solution 1:

You want to use the iptables REDIRECT target.

iptables -t nat -A OUTPUT -p tcp -d 1.2.3.4 --dport 80 -j REDIRECT

The iptables manpage specifies a single option to REDIRECT that allows you to change the port.

That option is --to-ports.