Linux iptables Firewall Mastery
Linux iptables Firewall Mastery
Iptables remains widely deployed despite being superseded by nftables, making proficiency essential for Linux administrators. The iptables framework operates through tables and chains, processing packets according to defined rules. Understanding packet flow through these structures enables creation of efficient, secure firewall configurations protecting Linux systems from network-based attacks.
The filter table handles general packet filtering through INPUT, OUTPUT, and FORWARD chains. Basic iptables configuration starts with default policies:
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
These commands establish a secure baseline, dropping unsolicited inbound traffic while allowing established connections and loopback communication.
Complex iptables rules leverage modules for advanced matching. The multiport module efficiently handles multiple ports: iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
. Rate limiting prevents denial-of-service attacks: iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH -m recent --update --seconds 60 --hitcount 4 --rset --name SSH -j DROP
. This rule limits SSH connections to 4 per minute per source IP.
Network Address Translation (NAT) configuration uses the nat table for masquerading and port forwarding. Enable IP forwarding in /etc/sysctl.conf
with net.ipv4.ip_forward=1
. Configure masquerading for outbound traffic:
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o eth1 -m state --state ESTABLISHED,RELATED -j ACCEPT
Save iptables rules persistently using iptables-save > /etc/iptables/rules.v4
on Debian-based systems or service iptables save
on Red Hat-based systems.