NAT ports - how do they work?

Posted by Davidoper on Server Fault See other posts from Server Fault or by Davidoper
Published on 2012-10-30T00:13:25Z Indexed on 2012/10/30 5:05 UTC
Read the original article Hit count: 478

I have the following network schema:


  • Computer A: three nics:
    • NIC 1 (eth0): dhcp, public internet
    • NIC 2 (eth1): static 192.168.1.1, gateway for Computer B
    • NIC 3 (eth2): static 192.168.2.1, gateway for Computer C

  • Computer B: static 192.168.1.2, using gateway 192.168.1.1 (NIC 2).

  • Computer C: static 192.168.2.2, using gateway 192.168.2.1 (NIC 3).

So I applied this to get NAT working:

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Every computer can connect to the internet now. I have been applying rules to the main computer (Computer A), like dropping connections to some ports, e.g ssh:

iptables -A INPUT -p tcp --dport 22 -j DROP

But for instance, now I would like only allow connections for ports 20,21,22,53 and 80 in Computer C, and ignore the outside traffic if it's not related to those ports. The allowed connections should be FROM Computer C to outside, but not from outside to Computer C (I mean - Computer C is not hosting any HTTP or SSH, but it is going to use them as a client).

I guess this sould be done like this:

iptables -A OUTPUT -i eth2 -o eth0 -p tcp --dport 21 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -i eth2 -o eth0 -p tcp --sport 21 -m state --state ESTABLISHED -j ACCEPT

The last rule (dropping any other traffic different from those) is at the end of the configuration, so -A should be working correctly.

The thing is... it is not working. If I put the last rule like this:

iptables -A FORWARD -i eth2 -o eth0 -j DROP

It just drops everything and, for instance, port 21 (previously opened as you can see above) is not either working.

Can you tell me what could I have done wrong? I have been struggling with this problem for some time and I am unable to solve it. Thanks!

© Server Fault or respective owner

Related posts about networking

Related posts about iptables