Linux Firewall: iptables

Linux iptables

Tables comprise of Chains. Chains are lists of rules (followed in order).

You will mostly be working with eighther default table called "filter" or NAT/portforwarding table called "nat"

To see the current rules:

iptables -nvL

INPUT, FORWARD, and OUTPUT are 3 of the 5 chains. A packet goes through only ONE of the 3 chains. Input means packet coming from network interface to local process. OUTPUT means going from local process to outside world (via network iface). FORWARD chain is for packets that are being routed. They are comming from outside and are going outside.

Other 2 chains are PREROUTING and POSTROUTING. As the name implies they are touched before and after a routing decision has been made.

PREROUTING just after arrival of the packet on machine interface. POSTROUTING at the end (after routing/FORWARDing or OUTPUT are evaluated).

MASQUERADE is form/type of source nat (SNAT) suitable for dynamic outgoing/public addresses. MASQUERADE is used when you do not know which address will be the outgoing IP (for outside world/lan) for example, in case the you are connecting with dynamically allocated IP from your ISP. With Link-Down/Up the MASQUERADE ip address is automatically re-determined. If you have statically allocated public IP, then you should use SNAT.

DNAT is mostly used for Port Forwarding where you want packets arriving at router to be delivered to inside LAN network/machine.

Examples:

In a typical setup where Tomcat Server is serving web application, you want to close all ports except 8080 and SSH port 22. A typical ruleset will be like:

iptables -F iptables -X iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT ACCEPT iptables -t nat -F iptables -t mangle -F iptables -A INPUT -s 127.0.0.1 -j ACCEPT iptables -I INPUT -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT iptables -I INPUT -p tcp --dport 8080 -m state --state NEW,ESTABLISHED -j ACCEPT iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT service iptables save