Ubuntu – NAT rules betweek 2 network interfaces (with iptables)

iptablesnat;Ubuntu

this is the current network that I have:

UBUNTU:
  eth0:
    ip: 212.83.10.10
    bcast: 212.83.10.10
    netmask 255.255.255.255
    gateway 62.x.x.x
  eth1:
    ip: 192.168.1.1
    bcast: 192.168.1.255
    netmask: 255.255.255.0
    gateway ?

CENTOS:
  eth0:
    ip: 192.168.1.2
    bcast: 192.168.1.255
    netmask 255.255.255.0
    gateway 192.168.1.1

I basically want this:

Make specific NAT rules from the internet to specific internal servers depending on the port:

Connections incoming to port 80 must be redirected to 192.168.1.2:80

Connections incoming to port 3306 must be redirected to 192.168.1.3:3306

and so on…

I also need one NAT rule to allow the servers in the subnet 192.168.1.x to browse the internet. I need to route the requests on eth0 to eth1 to be able to exit to internet.

Can I do this on the UBUNTU machine with iptables?

Thanks!

Best Answer

For the fist requirement you will need to use DNAT or destination natting it's used like this,

iptables -t nat -A PREROUTING -p tcp --dport TARGETPORT -j DNAT --to TARGET-IP:TARGETPORT

Example:

iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to 192.168.1.2:80

For Internet browsing you will need Source Natting:

iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j SNAT --to-source GATEWAY-IP

Or you can use masquarding instead of Source Natting like this:

iptables -t nat -A POSTROUTING -o eth0 -s 192.168.1.0/24 -j MASQUERADE

Also don't forget to open the needed ports on the servers.