BLOG POSTS
    MangoHost Blog / iptables Essentials – Common Firewall Rules and Commands
iptables Essentials – Common Firewall Rules and Commands

iptables Essentials – Common Firewall Rules and Commands

iptables is the command-line utility that’s been the backbone of Linux firewall management for years, acting as the interface to the kernel’s netfilter framework. If you’re managing Linux servers, understanding iptables isn’t optional—it’s essential for securing your infrastructure, controlling network traffic, and debugging connectivity issues. This guide will walk you through the fundamental concepts, practical command examples, and real-world scenarios that every sysadmin and developer should know to effectively configure and troubleshoot firewall rules.

How iptables Works

iptables operates on a system of tables, chains, and rules that process network packets as they traverse different points in the kernel’s network stack. The most commonly used table is the “filter” table, which contains three built-in chains:

  • INPUT – handles packets destined for the local system
  • OUTPUT – processes packets originating from the local system
  • FORWARD – manages packets being routed through the system

Each chain contains rules that are evaluated sequentially. When a packet matches a rule, the specified target action is taken (ACCEPT, DROP, REJECT, or jump to another chain). If no rules match, the chain’s default policy is applied.

The other important tables include:

Table Purpose Common Chains
filter Packet filtering (default) INPUT, OUTPUT, FORWARD
nat Network Address Translation PREROUTING, POSTROUTING, OUTPUT
mangle Packet modification PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING
raw Connection tracking exemptions PREROUTING, OUTPUT

Essential Commands and Syntax

Before diving into specific rules, let’s cover the basic command structure and essential operations you’ll use daily.

Viewing Current Rules

# List all rules in all chains with line numbers
iptables -L -n --line-numbers

# List rules for specific chain
iptables -L INPUT -n -v

# Show rules in command format (easier to copy/modify)
iptables -S

# List rules for specific table
iptables -t nat -L -n

Basic Rule Management

# Add rule to end of chain
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Insert rule at specific position
iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT

# Delete rule by line number
iptables -D INPUT 3

# Delete rule by specification
iptables -D INPUT -p tcp --dport 22 -j ACCEPT

# Flush all rules in chain
iptables -F INPUT

# Flush all rules in all chains
iptables -F

Common Firewall Rules and Patterns

Allow SSH Access

# Allow SSH from anywhere (not recommended for production)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow SSH from specific IP
iptables -A INPUT -p tcp -s 192.168.1.100 --dport 22 -j ACCEPT

# Allow SSH from specific subnet
iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 22 -j ACCEPT

# Rate limit SSH connections (prevent brute force)
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 -j DROP

Web Server Rules

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

# Allow HTTP/HTTPS with connection state tracking
iptables -A INPUT -p tcp -m multiport --dports 80,443 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -m multiport --sports 80,443 -m conntrack --ctstate ESTABLISHED -j ACCEPT

Database Access Control

# Allow MySQL from application servers only
iptables -A INPUT -p tcp -s 10.0.1.100 --dport 3306 -j ACCEPT
iptables -A INPUT -p tcp -s 10.0.1.101 --dport 3306 -j ACCEPT

# Allow PostgreSQL with source validation
iptables -A INPUT -p tcp -s 192.168.2.0/24 --dport 5432 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT

Advanced Rule Examples

Port Knocking Implementation

# Create custom chains for port knocking sequence
iptables -N GATE1
iptables -N GATE2
iptables -N GATE3

# First knock - port 1234
iptables -A INPUT -p tcp --dport 1234 -m recent --name knock1 --set -j DROP
iptables -A INPUT -p tcp --dport 2345 -m recent --name knock1 --rcheck -m recent --name knock2 --set -j DROP
iptables -A INPUT -p tcp --dport 3456 -m recent --name knock2 --rcheck -m recent --name knock3 --set -j DROP

# Allow SSH after successful knock sequence
iptables -A INPUT -p tcp --dport 22 -m recent --name knock3 --rcheck -j ACCEPT

Traffic Shaping and Limiting

# Limit connections per IP
iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 10 -j REJECT

# Rate limit by IP address
iptables -A INPUT -p tcp --dport 80 -m hashlimit --hashlimit-name http --hashlimit 5/minute --hashlimit-burst 10 --hashlimit-mode srcip -j ACCEPT

# Limit bandwidth using tc (requires iproute2)
iptables -A FORWARD -o eth0 -m mark --mark 1 -j ACCEPT

NAT and Port Forwarding

Basic NAT Configuration

# Enable IP forwarding first
echo 1 > /proc/sys/net/ipv4/ip_forward

# Basic SNAT for outgoing traffic
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

# Static SNAT with specific source IP
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 203.0.113.10

Port Forwarding Examples

# Forward external port 8080 to internal web server
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.100:80
iptables -A FORWARD -p tcp -d 192.168.1.100 --dport 80 -j ACCEPT

# Forward SSH to internal server with different port
iptables -t nat -A PREROUTING -p tcp --dport 2222 -j DNAT --to-destination 192.168.1.50:22
iptables -A FORWARD -p tcp -d 192.168.1.50 --dport 22 -j ACCEPT

# Load balancing between multiple servers
iptables -t nat -A PREROUTING -p tcp --dport 80 -m statistic --mode nth --every 2 --packet 0 -j DNAT --to-destination 192.168.1.10:80
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.11:80

Security-Focused Rule Sets

Default Deny Policy

# Set restrictive default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Allow loopback traffic
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

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

Anti-DDoS and Attack Mitigation

# Drop invalid packets
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP

# Rate limit new connections
iptables -A INPUT -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j ACCEPT

# Protect against port scans
iptables -A INPUT -m recent --name portscan --rcheck --seconds 86400 -j DROP
iptables -A INPUT -m recent --name portscan --remove
iptables -A INPUT -p tcp --tcp-flags ALL FIN,URG,PSH -m recent --name portscan --set -j DROP

# Block common attack patterns
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

Troubleshooting and Debugging

Logging and Monitoring

# Log dropped packets
iptables -A INPUT -j LOG --log-prefix "iptables-dropped: " --log-level 4

# Log and drop with rate limiting
iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables-denied: "
iptables -A INPUT -j DROP

# Create custom logging chain
iptables -N LOGDROP
iptables -A LOGDROP -j LOG --log-prefix "DROPPED: "
iptables -A LOGDROP -j DROP

# Use the custom chain
iptables -A INPUT -p tcp --dport 23 -j LOGDROP

Testing and Validation

# Test rule without applying (use iptables-restore with --test)
iptables-save > /tmp/current-rules.txt
# Edit rules file
iptables-restore --test < /tmp/modified-rules.txt

# Monitor packet counters
watch -n 1 'iptables -L -n -v'

# Trace packet path (requires iptables raw table)
iptables -t raw -A PREROUTING -p tcp --dport 80 -j TRACE
iptables -t raw -A OUTPUT -p tcp --sport 80 -j TRACE

# Check logs
tail -f /var/log/messages | grep iptables

Performance Considerations and Best Practices

Rule Optimization

Practice Good Bad Impact
Rule Order Most frequent matches first Random order High - affects all packets
Interface Matching Use -i/-o when possible Ignore interface Medium - reduces rule checks
Connection Tracking Use conntrack for established Check every packet individually High - major performance gain
Chain Organization Custom chains for complex logic All rules in INPUT/OUTPUT Medium - improves readability

Optimized Rule Structure

# Efficient rule ordering example
iptables -A INPUT -i lo -j ACCEPT                          # Loopback first (high traffic)
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT  # Established connections
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP   # Drop invalid early
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT  # SSH
iptables -A INPUT -p tcp -m multiport --dports 80,443 -m conntrack --ctstate NEW -j ACCEPT  # Web
iptables -A INPUT -j DROP                                  # Default deny

Common Pitfalls and Solutions

Lock-out Prevention

# Always test with a safety mechanism
# Method 1: Automatic reset
(sleep 300; iptables -F INPUT; iptables -P INPUT ACCEPT) &
# Apply your rules here
# If everything works: kill %1

# Method 2: Using at command
echo "iptables -F INPUT && iptables -P INPUT ACCEPT" | at now + 5 minutes

# Method 3: Screen/tmux session with timeout
timeout 300 bash -c 'read -p "Press enter if rules work correctly"' || iptables -F INPUT

Common Issues and Fixes

# Issue: Rules not persisting after reboot
# Solution: Save and restore rules
iptables-save > /etc/iptables/rules.v4

# On Debian/Ubuntu - install iptables-persistent
apt-get install iptables-persistent

# On CentOS/RHEL - use iptables service
service iptables save

# Issue: Connection tracking table full
# Check current connections
cat /proc/net/nf_conntrack | wc -l
cat /proc/sys/net/netfilter/nf_conntrack_max

# Increase limit
echo 65536 > /proc/sys/net/netfilter/nf_conntrack_max

Integration with Modern Tools

Container and Docker Integration

# Allow Docker container access
iptables -A INPUT -i docker0 -j ACCEPT
iptables -A FORWARD -i docker0 -o docker0 -j ACCEPT

# Block container from accessing host services except specific ports
iptables -A INPUT -i docker0 -p tcp --dport 22 -j DROP
iptables -A INPUT -i docker0 -p tcp --dport 3306 -j DROP

Kubernetes Considerations

When working with Kubernetes, be aware that kube-proxy manages many iptables rules automatically. Check existing rules before adding custom ones:

# View Kubernetes-managed rules
iptables -t nat -L -n | grep KUBE

# Add rules to avoid conflicts with Kubernetes
iptables -I INPUT 1 -p tcp --dport 6443 -s 10.0.0.0/8 -j ACCEPT

Alternatives and Modern Approaches

Tool Best For Pros Cons
nftables Modern Linux systems Better syntax, atomic updates Learning curve, limited tooling
ufw Ubuntu/desktop users Simple syntax, good defaults Less flexible than iptables
firewalld RHEL/CentOS systems Dynamic management, zones Complex for simple setups
pf (OpenBSD) BSD systems Clean syntax, integrated QoS Not available on Linux

For production environments, consider using configuration management tools like Ansible, Puppet, or Chef to manage iptables rules consistently across your infrastructure. Tools like fwbuilder can also help generate complex rule sets through a GUI interface.

Understanding iptables remains crucial even as container orchestration and cloud-native tools handle more networking complexity. The concepts and troubleshooting skills translate directly to debugging connectivity issues in containerized environments and understanding how traffic flows through your infrastructure.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked