NetFilter/iptables

From Unix Wiki
Jump to: navigation, search

Linux as Virtual Router using iptables (NAT)

It's good article to set your Linux as virtual router between two networks with sharing Internet connection and understaned ip forwarding meaning

Description

1. We have 3 machines/networks and one network gateway with following devices

Gateway - ip 192.168.0.1


Virtual Router - network 192.168.0.0, used to route packets between 192.168.5.0 and 192.168.7.0


eth0 - 192.168.0.10
eth1 - 192.168.5.1
eth2 - 192.168.7.1

Host 1 - network 192.168.5.0


eth0 - 192.168.5.10

Host 2 - network 192.168.7.0


eth0 - 192.168.7.10

2. Set default gateways

Virtual router


  • add GATEWAY=192.168.0.1 to /etc/syscofig/network-scripts/ifcfg-eth0
  • enable ip forwarding echo 1 > /proc/sys/net/ipv4/ip_forward

Host 1


  • add default gateway GATEWAY=192.168.5.1 to /etc/sysconfig/network file

Host 2


  • add default gateway GATEWAY=192.168.7.1 to /etc/sysconfig/network file


3. Tune ip forwading between networks

  • edit your /etc/sysconfig/iptables file like this
*nat
:PREROUTING ACCEPT [87:10842]
:POSTROUTING ACCEPT [4:288]
:OUTPUT ACCEPT [0:0]
#masquerading your traffic across eth0 interface from eth1 and eth2 connected networks
-A POSTROUTING -s 192.168.5.0/24 -o eth0 -j MASQUERADE 
-A POSTROUTING -s 192.168.7.0/24 -o eth0 -j MASQUERADE 
COMMIT
*filter
:INPUT ACCEPT [48:7036]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
#forward traffic between interfaces
#from eth0 to eth1 with RELATED and ESTABLISHED state
-A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
#vice versa but now all traffic passed from eth1 to eth0
-A FORWARD -i eth1 -o eth0 -j ACCEPT
#from eth0 to eth2 with RELATED and ESTABLISHED state
-A FORWARD -i eth0 -o eth2 -m state --state RELATED,ESTABLISHED -j ACCEPT
#vice versa but now all traffic passed from eth2 to eth0
-A FORWARD -i eth2 -o eth0 -j ACCEPT 
#all traffic from eth1 to eth2
-A FORWARD -i eth1 -o eth2 -j ACCEPT 
#vice-versa
-A FORWARD -i eth2 -o eth1 -j ACCEPT 
COMMIT

This is simple configuration and can be expanded to more complex