Ahmad Mahfouz

Random notes

IPtables PREROUTING, POSTROUTING for mixed interfaces via DNAT & SNAT

hello world,

let’s hit the point directly

1 – we have traffic coming from Source IP to our box and we need to Route it to another destination ( traffic forwarding )

2- we have traffic coming from Source IP to our box and we need to Route it to another destination ( traffic forwarding )  through a specified interface

iptables come with a chain called PREROUTING  , this chain guarantee forwarding packets before it responds ( as the packets come as it sent ) via NAT table

Scenario 1

let’s make a small scenario

we have source traffic from IP 191.114.119.12

out server, IP is 27.39.03.30

we want to tell the server when we receive a packet from this IP or CIDR  send this traffic to 89.23.39.84

the packets will leave 191.114.119.12  to our box 27.39.03.30 , this mean 191.114.119.12 will call 27.39.03.30 as a destination

once we receive the call from 191.114.119.12 we want to ROUTE it to 89.23.39.84

  • src 191.114.119.12
  • our box  27.39.03.30
  • destination  89.23.39.84

191.114.119.12 <=> 27.39.03.30 <=> 89.23.39.84

-t nat ( this where it happen as it translates the packet’s source field or destination field )

-A PREROUTING (append to PREROUTING chain )

-s ( we all agree this is the source )

-j DNAT  (  jump will Destination NAT )

–to-destination ( final destination )

so we need to tell our box traffic going FOR destination  89.23.39.84 set the Source IPto 27.39.04.5  and mask the source IP 😀 , so our destination talk to our box IP then we will replay to the source

Scenario 2

We have multi interfaces with different IPs and the traffic goes out from IP of eth1

eth0: 27.39.03.30

eth1: 27.39.04.5

eth2: 27.39.24.1

and we user POSTROUTING ( after we got the packet )

here we did use SNAT for changing the source packets

now packet flow will be like this

191.114.119.12 <=> 27.39.03.30  <=>27.39.04.5 <=> 89.23.39.84

the bold lines is our box ips

and one last step till the kernel to enable ip forwarding.

happy networking

2 thoughts on “IPtables PREROUTING, POSTROUTING for mixed interfaces via DNAT & SNAT

  • om4rezz
    July 14, 2016 at 5:01 pm

    good topic, bro.!
    I really liked. 😉

  • minion
    September 12, 2019 at 3:57 pm

    This post save my live today. You are awesome.

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.