Getting Started with iptables

Getting Started with iptables

iptables provides direct access to netfilter capabilities through a command-line interface. While powerful, its syntax can be complex, requiring careful attention to rule order and syntax. Before implementing any iptables configuration, it's crucial to understand the current state and have a recovery plan in case of misconfiguration.

First, check your current iptables configuration:

# List all current rules with line numbers
sudo iptables -L -n -v --line-numbers

# Save current configuration for backup
sudo iptables-save > /backup/iptables-backup-$(date +%Y%m%d).rules

# Check if iptables service is enabled
sudo systemctl status iptables

For web servers, start with a clean slate and build your ruleset systematically:

# Flush all existing rules (WARNING: This will remove all firewall rules)
sudo iptables -F
sudo iptables -X
sudo iptables -Z

# Set default policies - drop all traffic by default
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

# Allow loopback traffic (essential for many applications)
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT

The basic structure for web server protection begins with allowing established connections:

# Allow established and related connections
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow SSH from specific IP range (replace with your admin network)
sudo iptables -A INPUT -p tcp -s 10.0.0.0/24 --dport 22 -j ACCEPT

# Allow HTTP and HTTPS from anywhere
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT