Master iptables: From Basics to Advanced Firewall Rules for Enterprise Security
This comprehensive guide walks you through iptables fundamentals, four‑table architecture, common use cases, environment setup, step‑by‑step rule creation, NAT configuration, advanced attack mitigation, rule management, best practices, troubleshooting, performance monitoring, and backup strategies for building a robust Linux firewall.
Overview
iptables is the core firewall tool on Linux, built on the Netfilter framework. It provides packet filtering, NAT, traffic shaping and is essential for protecting servers against DDoS, port scans, brute‑force attacks and more.
Technical Features
Four tables (filter, nat, mangle, raw) and five chains (PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING)
Fine‑grained filtering based on IP, port, protocol, state, connection count, etc.
Full NAT support (SNAT, DNAT, port forwarding)
Strong defense against SYN Flood, ICMP Flood, port scans, brute‑force attacks
High performance with kernel‑mode processing
Rule persistence across reboots
Applicable Scenarios
Web server protection – only expose ports 80/443
Database server – allow access from application servers only
Bastion host – whitelist SSH access
Load balancer – DNAT for traffic distribution
NAT gateway – internal network Internet access
VPN server – secure port forwarding
Environment Requirements
OS: CentOS 7+/Ubuntu 18.04+
Kernel: 3.10+ (4.x recommended)
iptables version: 1.4.21+ (CentOS) or iptables‑persistent (Ubuntu)
Root privileges required
Detailed Steps
Preparation
# Check OS version
cat /etc/os-release
uname -r
# Verify iptables installation
iptables --version
# View current firewall status
iptables -L -n -v
# Check firewalld status (conflicts with iptables)
systemctl status firewalld
# List network interfaces
ip addr show
ifconfig -a
# Show current connections
ss -tunlp
netstat -tunlpInstallation and Basic Setup
# CentOS/RHEL
sudo systemctl stop firewalld
sudo systemctl disable firewalld
sudo systemctl mask firewalld
sudo yum install -y iptables-services
sudo systemctl start iptables
sudo systemctl enable iptables
sudo systemctl status iptables
# Ubuntu/Debian
sudo apt update
sudo apt install -y iptables-persistent
sudo netfilter-persistent saveBackup Existing Rules
# Backup current rules
sudo iptables-save > /root/iptables-backup-$(date +%Y%m%d_%H%M%S).rules
mkdir -p /data/iptables_backup
iptables-save > /data/iptables_backup/iptables-$(date +%Y%m%d_%H%M%S).rulesCore Configuration
# Basic syntax
iptables -t <table> -A <chain> <match> -j <target>
# Example: allow HTTP
iptables -t filter -A INPUT -p tcp --dport 80 -j ACCEPTDefault Drop Policy (Recommended)
# Flush existing rules
iptables -F
iptables -X
iptables -Z
iptables -t nat -F
iptables -t nat -X
# Set default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Allow loopback and established connections
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow SSH (custom port recommended)
iptables -A INPUT -p tcp --dport 22 -j ACCEPTAdvanced Protection
# SYN Flood mitigation
iptables -A INPUT -p tcp --syn -m limit --limit 10/s --limit-burst 20 -j ACCEPT
iptables -A INPUT -p tcp --syn -j DROP
# Port scan detection (30 s, >15 ports)
iptables -N port-scan
iptables -A port-scan -m recent --name portscan --set
iptables -A port-scan -m recent --update --seconds 30 --hitcount 15 -j LOG --log-prefix "Port scan detected: " --log-level 4
iptables -A port-scan -m recent --update --seconds 30 --hitcount 15 -j DROP
iptables -A INPUT -p tcp --tcp-flags SYN,ACK,FIN,RST RST -j port-scan
# SSH brute‑force protection
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --name ssh_attack --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j LOG --log-prefix "SSH brute force: "
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROPNAT Configuration
# Enable IP forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
sed -i 's/net.ipv4.ip_forward = 0/net.ipv4.ip_forward = 1/' /etc/sysctl.conf
sysctl -p
# SNAT (internal network to Internet)
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j SNAT --to-source 203.0.113.10
# DNAT (port forwarding)
iptables -t nat -A PREROUTING -d 203.0.113.10 -p tcp --dport 80 -j DNAT --to-destination 192.168.1.100:80
iptables -A FORWARD -p tcp -d 192.168.1.100 --dport 80 -j ACCEPTRule Management and Persistence
# Show current rules
iptables -t filter -L -n -v --line-numbers
iptables -t nat -L -n -v
# Save rules (CentOS)
service iptables save
# Save rules (Ubuntu)
iptables-save > /etc/iptables/rules.v4
netfilter-persistent saveBest Practices
Place the most frequently matched rules at the top of the chain.
Use ipset for large IP allow/deny lists.
Increase nf_conntrack_max for high‑traffic servers.
Apply the principle of least privilege – default DROP, only open required ports.
Change default service ports (e.g., SSH) to reduce automated attacks.
Enable logging for dropped packets and forward logs to a central syslog server.
Troubleshooting
# Verify SSH access
iptables -L INPUT -n -v | grep 22
iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT
# Check web service ports
iptables -L INPUT -n -v | grep -E "dpt:(80|443)"
# Diagnose NAT issues
cat /proc/sys/net/ipv4/ip_forward
iptables -t nat -L -n -v
ip route show
# Real‑time rule hit counters
watch -n 1 'iptables -L -n -v'Performance Monitoring
# Rule statistics
iptables -L -n -v
# Connection tracking usage
cat /proc/sys/net/netfilter/nf_conntrack_count
cat /proc/sys/net/netfilter/nf_conntrack_max
# Simple monitoring script (cron every 5 min)
#!/bin/bash
LOG=/var/log/iptables_monitor.log
echo "$(date) - iptables stats" >> $LOG
iptables -L INPUT -n -v >> $LOG
iptables -t nat -L -n -v >> $LOGBackup and Restore
# Automated backup (daily at 02:00)
#!/bin/bash
DIR=/data/iptables_backup
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $DIR
iptables-save > $DIR/iptables-$DATE.rules
gzip $DIR/iptables-$DATE.rules
# Retain 30 days
find $DIR -name "*.gz" -mtime +30 -delete
# Restore example
gunzip -c $DIR/iptables-20240315_020000.rules.gz | iptables-restore
service iptables save # CentOS
netfilter-persistent reload # UbuntuConclusion
The four‑table, five‑chain model of iptables provides a flexible foundation for building enterprise‑grade firewalls. By adopting a default‑DROP policy, ordering rules efficiently, leveraging modules such as limit, recent, and connlimit, and persisting configurations, administrators can achieve robust security, high performance, and reliable operation across diverse Linux environments.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
