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

Posted by GoldenNewby on Server Fault See other posts from Server Fault or by GoldenNewby
Published on 2012-04-05T02:21:11Z Indexed on 2012/04/05 5:31 UTC
Read the original article Hit count: 440

Filed under:
|
|

I will be awarding a +100 bounty to the correct answer once it is available in 48 hours

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

© Server Fault or respective owner

Related posts about security

Related posts about iptables