iptables is a classic firewall tool developed for the Linux system based on the netfilter kernel framework, focusing on IPv4 packet filtering and NAT rule configuration. As a built-in component of the Linux kernel, it features efficiency and flexibility, supporting core capabilities such as state detection and fine-grained traffic control. It is the most commonly used low-level firewall solution in server operations and network security management, suitable for various scenarios from personal computers to enterprise-level servers.
1. Core Introduction to iptables
iptables is a firewall management tool based on the Netfilter framework in the Linux system, primarily used to configure IPv4 packet filtering rules and Network Address Translation (NAT) rules. It is the most mainstream and fundamental firewall solution in the Linux ecosystem.
Main Features
- Based on a packet filtering mechanism, it directly acts on the kernel network stack, ensuring high processing efficiency.
- Supports connection state detection (such as ESTABLISHED and NEW states), making rule matching smarter.
- Fully supports NAT functions (SNAT/DNAT/MASQUERADE), suitable for scenarios like LAN sharing of internet access and port forwarding.
- Flexible rule configuration allows for fine-grained control of traffic based on IP, port, protocol, network interface, and more.
- Deeply integrated with the Linux kernel, requiring no additional dependencies, ensuring strong compatibility.
2. Core Concepts of iptables
1. Table
iptables divides functional modules through different “tables,” with each table corresponding to specific network processing tasks, containing predefined “chains”:
| Table Name | Core Function | Common Chains |
|---|---|---|
| filter | Default table responsible for packet filtering | INPUT (incoming), OUTPUT (outgoing), FORWARD (forwarding) |
| nat | Network Address Translation (address mapping) | PREROUTING (before routing), POSTROUTING (after routing), INPUT, OUTPUT |
| mangle | Packet modification (TOS/TTL/marking) | All chains (INPUT/OUTPUT/FORWARD/PREROUTING/POSTROUTING) |
| raw | Bypass connection tracking (to improve performance) | PREROUTING, OUTPUT |
2. Chain
A chain is the necessary path for packets in the system, determining the processing flow of packets:
- INPUT: Processes incoming packets with the destination address of the local machine.
- OUTPUT: Processes outgoing packets initiated by the local machine.
- FORWARD: Processes packets forwarded through the local machine (e.g., in a router scenario).
- PREROUTING: Processes packets before routing decisions (mainly used for DNAT port forwarding).
- POSTROUTING: Processes packets after routing decisions (mainly used for SNAT address translation).
3. Target
Actions executed when packets match rules (core actions):
- ACCEPT: Allows packets to pass through and continue the subsequent process.
- DROP: Discards packets directly without returning any response (highly stealthy).
- REJECT: Rejects packets and returns a rejection response (e.g., ICMP unreachable).
- LOG: Records packet information to the system log (for auditing purposes).
- SNAT: Source address translation (e.g., LAN sharing public IP for internet access).
- DNAT: Destination address translation (e.g., public port forwarding to internal server).
- MASQUERADE: Dynamic SNAT (suitable for scenarios where public IP is not fixed, such as dial-up internet).
3. Basic Commands of iptables
1. View Rules
# View all rules in the filter table (default table), -n shows IP/port in numeric format, -v shows detailed information
iptables -L -n -v
# View all rules in a specified table (e.g., nat table)
ipcables -t nat -L -n -v
# View rules with line numbers (for easy deletion/modification)
ipcables -L -n --line-numbers
# View rules in a specific chain (e.g., INPUT chain)
ipcables -L INPUT -n -v
2. Clear Rules
# Clear all rules in all tables (use with caution!)
ipcables -F
# Clear rules in a specified table (e.g., nat table)
ipcables -t nat -F
# Reset the match counters for all rules (packet count/byte count)
ipcables -Z
# Delete a specific rule by number in a specified chain (e.g., delete the first rule in the INPUT chain)
ipcables -D INPUT 1
# Clear all custom chains and rules
ipables -X
3. Set Default Policy
The default policy is the action executed when packets do not match any rules. It is recommended to follow the “least privilege” principle:
# Set default policy to DROP for INPUT/FORWARD chains, and ACCEPT for OUTPUT chain (common security configuration)
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
4. Common Rule Practical Examples
1. Basic Security Rules (General Server Configuration)
# 1. First set the default policy (deny incoming/forwarding, allow outgoing)
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# 2. Allow local loopback interface (lo) communication (required by internal system components)
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# 3. Allow established connections and related connections (do not interrupt existing network sessions)
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# 4. Allow SSH connections (port 22, essential for remote server management)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# 5. Allow HTTP (port 80) and HTTPS (port 443) services
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# 6. Allow ICMP ping requests (optional, facilitates network connectivity testing)
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
2. Access Restriction Rules (Enhancing Security)
# Only allow specific IP (e.g., 192.168.1.100) to access the SSH port
iptables -A INPUT -p tcp --dport 22 -s 192.168.1.100 -j ACCEPT
# Only allow specific IP range (e.g., 192.168.1.0/24) to access the HTTP port
iptables -A INPUT -p tcp --dport 80 -s 192.168.1.0/24 -j ACCEPT
# Limit SSH connection frequency (prevent brute force attacks: max 3 new connections per minute)
iptables -A INPUT -p tcp --dport 22 -m limit --limit 3/min -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j DROP
3. NAT Rule Examples (Gateway/Router Scenario)
# 1. Enable kernel IP forwarding (must be configured, otherwise packets cannot be forwarded)
echo 1 > /proc/sys/net/ipv4/ip_forward
# 2. Dynamic SNAT (MASQUERADE): LAN sharing public IP for internet access (eth0 is the public network interface)
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# 3. Static SNAT: LAN (192.168.1.0/24) accessing the internet through a fixed public IP (203.0.113.1)
iptables -t nat -A POSTROUTING -o eth0 -s 192.168.1.0/24 -j SNAT --to-source 203.0.113.1
# 4. Port forwarding: Forward public port 80 to internal server (192.168.1.100:80)
iptables -t nat -A PREROUTING -i eth0 -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 ACCEPT
4. Logging Rules (Auditing and Troubleshooting)
# Log all dropped packets (log prefix: IPTABLES-DROPPED, log level 4)
iptables -A INPUT -j LOG --log-prefix "IPTABLES-DROPPED: " --log-level 4
# View logs (default path: /var/log/syslog or /var/log/messages)
grep IPTABLES-DROPPED /var/log/syslog
5. Advanced Function Applications
1. Enhanced State Detection
# Only allow established connections to enter, deny all new unauthorized connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Only allow new SSH connections, deny all other new connections
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT
iptables -A INPUT -m state --state NEW -j DROP
2. Rate Limiting (Preventing Attacks)
# Limit new SSH connection frequency (3 per minute, deny if exceeded)
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m limit --limit 3/min -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j DROP
# Limit ping request frequency (1 per second, to avoid ping flood attacks)
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT
iptables -A INPUT -p icmp --icmp-type echo-request -j DROP
3. Batch Configuration for Multiple Ports
# Allow a single rule to match multiple ports (e.g., 80, 443, 8080)
iptables -A INPUT -p tcp -m multiport --dports 80,443,8080 -j ACCEPT
# Allow multiple source IP ranges to access multiple ports
iptables -A INPUT -p tcp -m multiport --dports 22,3389 -s 192.168.1.0/24,10.0.0.0/8 -j ACCEPT
4. IP Sets (Efficient Management of Black and White Lists)
First, install the ipset tool (Debian/Ubuntu: apt-get install ipset; CentOS/RHEL: yum install ipset):
# Create an IP blacklist set (hash:ip type, stores individual IPs)
ipset create blacklist hash:ip
# Add IPs to the blacklist (supports batch addition)
ipset add blacklist 192.168.1.100
ipset add blacklist 203.0.113.5
# Apply blacklist rules (deny incoming from blacklisted IPs)
iptables -A INPUT -m set --match-set blacklist src -j DROP
# View the blacklist set
ipset list blacklist
# Remove an IP from the blacklist
ipset del blacklist 192.168.1.100
6. Rule Saving and Automatic Loading on Boot
iptables rules are stored in memory by default and will be lost after a system reboot. They need to be manually saved and configured for automatic loading on boot:
1. Save Rules
# Debian/Ubuntu systems
iptables-save > /etc/iptables.rules
# CentOS/RHEL 7+ systems (requires installation of iptables-services)
yum install iptables-services -y
systemctl enable iptables
systemctl start iptables
iptables-save > /etc/sysconfig/iptables
2. Restore Rules
# Debian/Ubuntu systems
iptables-restore < /etc/iptables.rules
# CentOS/RHEL systems
iptables-restore < /etc/sysconfig/iptables
3. Automatic Loading on Boot (Permanent Effect)
# Debian/Ubuntu systems: Create a script to load before network startup
cat > /etc/network/if-pre-up.d/iptables << EOF
#!/bin/sh
iptables-restore < /etc/iptables.rules
EOF
chmod +x /etc/network/if-pre-up.d/iptables
# CentOS/RHEL systems: Enable iptables service (automatically loads /etc/sysconfig/iptables)
systemctl enable iptables
systemctl restart iptables
7. Best Practices
- Default deny principle: First set the default DROP for INPUT/FORWARD chains, then gradually open necessary ports to minimize the attack surface.
- Allow local loopback: Must allow lo interface communication; otherwise, internal services (like databases, local processes) may malfunction.
- Retain established connections: Prioritize adding ESTABLISHED,RELATED allow rules to avoid interrupting existing network sessions.
- Open ports as needed: Only open ports essential for business (like web services 80/443, SSH 22), disable unused ports.
- Limit management access: Try to restrict management ports like SSH to specific IPs/IP ranges to avoid global exposure.
- Log auditing: Configure logs for denied packets, regularly analyze abnormal traffic (like frequently connecting IPs).
- Regularly clean up rules: Remove expired or unused rules to avoid decreased matching efficiency due to excessive rules.
- Test before applying: Validate rules in a test environment first, or operate through existing SSH sessions (to avoid being locked out).
8. Troubleshooting
1. Locked out of the server (SSH connection failure)
- Log in directly through the server console (physical machine/cloud server console).
- Temporarily add allow rule: iptables -A INPUT -p tcp –dport 22 -j ACCEPT, then investigate existing rules.
2. Rules not taking effect
- Check rule order: iptables matches rules in order; allow rules must be before deny rules.
- View rule counters: iptables -L -n -v, confirm if rules have matching counts (if 0, the rule did not hit).
- Check if the table/chain is correct: NAT rules must be configured in the nat table, not the filter table.
3. NAT forwarding failure
- Confirm IP forwarding is enabled: cat /proc/sys/net/ipv4/ip_forward, output 1 indicates it is enabled (otherwise execute echo 1 > /proc/sys/net/ipv4/ip_forward).
- Check FORWARD chain rules: must allow forwarding packets (e.g., iptables -A FORWARD -j ACCEPT, or more refined forwarding rules).
- Verify nat table rules: iptables -t nat -L -n -v, confirm if PREROUTING/POSTROUTING rules are correct.
9. Alternatives
While iptables is powerful, its rule configuration can be complex. Modern Linux systems provide more user-friendly alternative tools:
- firewalld: Default firewall for CentOS/RHEL 7+, supports dynamic rules (no need to restart services), zone management.
- ufw (Uncomplicated Firewall): Default firewall for Ubuntu, simplifies iptables commands, suitable for beginners.
- nftables: Next-generation replacement for iptables, natively supported by the kernel, with simpler rule syntax and better performance.
However, iptables remains a core tool for understanding Linux network filtering principles and is still widely used in server operations and automation scripts.
Technical accumulation, every encounter is fate.
Welcome to leave comments for discussion.