Table of Contents
- Understanding iptables: Core Concepts
- 1.1 Tables
- 1.2 Chains
- 1.3 Rules and Targets
- Installing iptables
- Basic iptables Commands
- 3.1 Listing Rules
- 3.2 Flushing Rules
- 3.3 Checking Rule Existence
- Configuring Basic Traffic Rules
- 4.1 Allowing Loopback Traffic
- 4.2 Allowing Established Connections
- 4.3 Allowing Incoming Traffic (e.g., SSH, HTTP)
- Blocking Traffic
- 5.1 Blocking Specific IP Addresses
- 5.2 Blocking Ports or Protocols
- 5.3 DROP vs. REJECT: What’s the Difference?
- Advanced Rule Configuration
- 6.1 Rate Limiting (Preventing Brute-Force Attacks)
- 6.2 Logging Traffic
- 6.3 Custom Chains for Organization
- Saving and Persisting Rules
- Troubleshooting iptables
- Conclusion
- References
Understanding iptables: Core Concepts
Before diving into commands, let’s clarify the key components of iptables:
1.1 Tables
iptables organizes rules into tables, each designed for a specific purpose. The most commonly used tables are:
| Table | Purpose |
|---|---|
filter | Default table for packet filtering (allow/block traffic). |
nat | Network Address Translation (e.g., port forwarding, masquerading). |
mangle | Modify packet headers (e.g., TOS, TTL values). |
raw | Bypass connection tracking for specific packets (rarely used). |
security | Mandatory Access Control (MAC) rules (e.g., SELinux integration). |
For basic traffic filtering, we’ll focus on the filter table.
1.2 Chains
Within each table, rules are grouped into chains—predefined sequences of rules that process packets at specific stages of their lifecycle. The filter table uses three core chains:
| Chain | When It Processes Packets |
|---|---|
INPUT | Packets destined for the local system (e.g., SSH to your server). |
OUTPUT | Packets originating from the local system (e.g., your server pinging a remote IP). |
FORWARD | Packets routed through the system (e.g., a Linux router forwarding traffic between networks). |
Other tables (like nat) have additional chains (e.g., PREROUTING, POSTROUTING), but these are beyond the scope of basic filtering.
1.3 Rules and Targets
A rule is a condition that matches packets (e.g., “source IP 192.168.1.100” or “destination port 22”). When a packet matches a rule, iptables applies a target (action). Common targets include:
| Target | Action |
|---|---|
ACCEPT | Allow the packet to pass through. |
DROP | Silently discard the packet (no response sent to the sender). |
REJECT | Discard the packet and send an error response (e.g., “Connection refused”). |
LOG | Log details about the packet (e.g., to /var/log/kern.log). |
Installing iptables
Most Linux distributions include iptables by default, but if not, install it using your package manager:
Debian/Ubuntu:
sudo apt update && sudo apt install iptables
RHEL/CentOS/Rocky Linux:
sudo dnf install iptables-services
Note: Newer systems may use
nftablesas the default firewall backend, but iptables commands still work (via a compatibility layer). To use legacy iptables, installiptables-legacy(Debian/Ubuntu) or enable theiptablesservice (RHEL).
Basic iptables Commands
Let’s start with essential commands to manage rules.
3.1 Listing Rules
To view all rules in the default filter table:
sudo iptables -L
For verbose output (including interfaces, packet counts, and timestamps):
sudo iptables -L -v
To list rules numerically (IP addresses/ports instead of hostnames/services):
sudo iptables -L -n
To list rules with line numbers (useful for deleting rules later):
sudo iptables -L --line-numbers
To list rules in a specific table (e.g., nat):
sudo iptables -t nat -L
3.2 Flushing Rules
To delete all rules in the filter table (use with caution!):
sudo iptables -F
To flush a specific chain (e.g., INPUT):
sudo iptables -F INPUT
To reset packet/byte counters for all rules:
sudo iptables -Z
3.3 Checking Rule Existence
To check if a specific rule exists (e.g., allow SSH on port 22):
sudo iptables -C INPUT -p tcp --dport 22 -j ACCEPT
If the rule exists, the command returns 0; otherwise, it returns 1.
Configuring Basic Traffic Rules
Let’s build a foundational rule set for a typical server.
4.1 Allowing Loopback Traffic
The loopback interface (lo) is critical for local services (e.g., databases, web servers) to communicate. Always allow loopback traffic:
# Allow incoming loopback traffic
sudo iptables -A INPUT -i lo -j ACCEPT
# Allow outgoing loopback traffic
sudo iptables -A OUTPUT -o lo -j ACCEPT
4.2 Allowing Established Connections
To avoid breaking existing connections (e.g., SSH sessions, HTTP requests), allow traffic related to established connections:
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-m conntrack: Uses theconntrackmodule to track connection states.--ctstate ESTABLISHED: Matches packets part of an existing connection.RELATED: Matches packets related to an established connection (e.g., FTP data transfer).
4.3 Allowing Incoming Traffic
Allow specific services by port. For example:
Allow SSH (Port 22):
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Allow HTTP (Port 80) and HTTPS (Port 443):
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT # HTTP
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT # HTTPS
Allow Custom Port (e.g., 8080 for a web app):
sudo iptables -A INPUT -p tcp --dport 8080 -j ACCEPT
-A INPUT: Append the rule to theINPUTchain.-p tcp: Match TCP protocol (use-p udpfor UDP).--dport 22: Match destination port 22.
Blocking Traffic
Use DROP or REJECT to block unwanted traffic.
4.4 Blocking Specific IP Addresses
To block all traffic from a malicious IP (e.g., 192.168.1.100):
sudo iptables -A INPUT -s 192.168.1.100 -j DROP
-s: Source IP address.
4.5 Blocking Ports or Protocols
To block incoming traffic on a specific port (e.g., port 3306 for MySQL, if not needed externally):
sudo iptables -A INPUT -p tcp --dport 3306 -j DROP
To block all UDP traffic (use with caution!):
sudo iptables -A INPUT -p udp -j DROP
4.6 DROP vs. REJECT: What’s the Difference?
DROP: Silently discards packets. The sender waits for a timeout, which can hide that the server exists.REJECT: Sends an ICMP error (e.g., “Connection refused”) to the sender, revealing the server is active.
Example of REJECT with a custom message:
sudo iptables -A INPUT -s 192.168.1.100 -j REJECT --reject-with icmp-port-unreachable
Advanced Rule Configuration
5.1 Rate Limiting (Preventing Brute-Force Attacks)
Use the limit module to restrict repeated connections (e.g., SSH brute-force attempts):
# Allow 5 SSH connections per minute, burst of 10
sudo iptables -A INPUT -p tcp --dport 22 -m limit --limit 5/min --limit-burst 10 -j ACCEPT
# Block excess SSH attempts
sudo iptables -A INPUT -p tcp --dport 22 -j DROP
--limit 5/min: Allow 5 connections per minute.--limit-burst 10: Allow up to 10 initial connections before enforcing the limit.
5.2 Logging Traffic
Log denied traffic to debug or monitor attacks. Use the LOG target before DROP/REJECT:
sudo iptables -A INPUT -j LOG --log-prefix "iptables-denied: " --log-level 6
sudo iptables -A INPUT -j DROP
--log-prefix: Adds a label to log entries (e.g.,iptables-denied:).--log-level 6: Logs at “info” level (view logs in/var/log/kern.log).
5.3 Custom Chains for Organization
For complex rule sets, create custom chains to group related rules. Example: a WEB_TRAFFIC chain for HTTP/HTTPS:
# Create a custom chain
sudo iptables -N WEB_TRAFFIC
# Add rules to the chain
sudo iptables -A WEB_TRAFFIC -p tcp --dport 80 -j ACCEPT
sudo iptables -A WEB_TRAFFIC -p tcp --dport 443 -j ACCEPT
# Jump to the custom chain from INPUT
sudo iptables -A INPUT -j WEB_TRAFFIC
Saving and Persisting Rules
By default, iptables rules are temporary and reset on reboot. To save them:
6.1 Saving Rules Manually
Use iptables-save to export rules to a file:
sudo iptables-save > /etc/iptables/rules.v4
To restore rules later:
sudo iptables-restore < /etc/iptables/rules.v4
6.2 Persisting Rules Across Reboots
Debian/Ubuntu:
Install iptables-persistent to auto-save/restore rules:
sudo apt install iptables-persistent
# Save rules when prompted, or run:
sudo netfilter-persistent save
RHEL/CentOS:
Enable the iptables service to load rules on boot:
sudo systemctl enable --now iptables
sudo service iptables save # Saves to /etc/sysconfig/iptables
Troubleshooting iptables
Common Issues and Fixes:
- Locked out of SSH: If you flush rules or block port 22, use a console (e.g., AWS EC2 Console, physical access) to restore rules.
- Rules not working: Check rule order (iptables processes top-to-bottom). Allow critical rules (e.g., SSH) before blocking.
- No internet access: Ensure
ESTABLISHED,RELATEDis allowed inINPUTandOUTPUTchains. - Logs not showing: Verify
--log-level(use6for info,4for warnings) and check/var/log/kern.log.
Conclusion
iptables is a versatile tool for securing Linux networks by filtering traffic based on granular rules. By mastering tables, chains, and targets, you can enforce strict access policies, block threats, and monitor traffic. Remember to:
- Start with basic rules (loopback, established connections).
- Allow only necessary services (e.g., SSH, HTTP).
- Persist rules to avoid losing them on reboot.
- Test rules in a non-production environment first!
With practice, iptables will become an indispensable part of your network security toolkit.