I am trying to understand how exactly NAT works to solve another bigger problem, here is my linux box setup:
Interface eth0 connected to internet (public IP address)
eth1 connected to local network and acts as gateway (has IP 192.168.1.1 ) for all internal nodes to provide internet access.
Following iptable rules are used:
1)$iptables -A FORWARD -i eth0 -o eth1 -m state --state ESTABLISHED,RELATED -j ACCEPT 2)$iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT 3)$iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
Now I would like to understand what exactly rules 1,2 and 3 do?
Now take this example :
PC1 with IP address 192.168.1.5 and MAC address MAC1 needs to access url www.google.com, it constructs the packet like this
Assuem mac address of gateway is MAC2
source MAC | destination MAC | source ip | destination ip| payload MAC1 MAC2 192.168.1.5 <google ip> <data>
Now gateway(192.168.1.1) receives this packet on interface eth1 and alters the source ip to ip address of interface eth0 and updates some table with a entry to reverse lookup when the response is received.Which rules is responsible for this operation rule1/rule 2?
And when the response is received on eth0, it alters the destination ip by looking up the table entry and drops the packet on eth1. what exactly rule3 do here?
Say an application on gateway needs to access internet and creates packet and sends over eth0, when the response is received how the packet is routed to application on the gateway instead of transmitting the packet over interface eth1 according to rule1?
When sending a packet rule3 alters the source ip and it is called soruce NAT, simlarly when a reply packet is received on eth0, destination address changed, is it not destination NAT? why isn't a rule for that.?
Suppose say there is another interface eth2 which is also connected to internet with a public ip and a default route exists in the routing table to route the traffic through this device :
$ip route add default via <IP> dev eth2 scope link
iptables forward chain rules of filter table say to exit the packets over eth0 but the routing table has default route through eth2, in this case which interface is used for internet?
Is it possible to route the traffic that is forwarded from eth1(local n/w) to eth0 and the application data traffic that originate on gateway over interface eth2?