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 specified interface

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

Senario 1

lets 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 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 adestination

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

  • src 191.114.119.12
  • ourbox  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 translate 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 iP to 27.39.04.5  and mask the source ip 😀 , so our destination talk to our box ip then we will replay to the source

Senario 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 routing

One thought on “IPtables PREROUTING, POSTROUTING for mixed interfaces via DNAT & SNAT”

Leave a Reply

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

*