iptables Command
Introduction
iptables
is a powerful command-line firewall utility that uses policy chains to allow or block traffic. As the primary interface to the Linux kernel's netfilter framework, iptables enables system administrators to configure specific rules that will define how network traffic is handled. It serves as the traditional firewall tool for Linux systems, allowing fine-grained control over incoming and outgoing network packets.
Despite being gradually replaced by newer tools like nftables
and firewalld
in modern Linux distributions, iptables remains widely used due to its reliability, flexibility, and the extensive knowledge base surrounding it. Understanding iptables is essential for Linux system administrators who need to secure their servers and control network traffic.

Basic Concepts
Before diving into iptables commands, it's important to understand some key concepts:
Tables
Iptables organizes its rules into different tables, each serving a specific purpose:
- filter: The default table, used for packet filtering (allowing, dropping, or rejecting packets)
- nat: Used for Network Address Translation (changing source or destination addresses)
- mangle: Used for specialized packet alteration
- raw: Used to configure exemptions from connection tracking
- security: Used for Mandatory Access Control networking rules
Chains
Each table contains chains, which are lists of rules. The built-in chains are:
- INPUT: For packets destined to local sockets
- FORWARD: For packets being routed through the system
- OUTPUT: For locally-generated packets
- PREROUTING: For altering packets as they arrive
- POSTROUTING: For altering packets as they leave
Rules
Rules specify criteria for matching packets and actions (targets) to perform when a packet matches. Common targets include:
- ACCEPT: Allow the packet to proceed
- DROP: Discard the packet without notification
- REJECT: Discard the packet and send an error message to the sender
- LOG: Log the packet but continue processing rules
Installation
Iptables is typically pre-installed on most Linux distributions. If it's not available, you can install it using your distribution's package manager:
Debian/Ubuntu-based Systems
Red Hat/CentOS/Fedora Systems
Arch Linux
Basic Syntax
The basic syntax of the iptables command is:
Where:
- table: Specifies the table to operate on (-t filter, -t nat, etc.)
- action: Specifies what to do (-A to append, -D to delete, -I to insert, etc.)
- chain: Specifies the chain to operate on (INPUT, OUTPUT, etc.)
- matching criteria: Specifies the conditions for the rule (-p tcp, --dport 22, etc.)
- target: Specifies what happens when the rule matches (ACCEPT, DROP, etc.)
Basic Usage
Viewing Current Rules
To display the current iptables rules:
This shows all rules in the filter table with hostnames and service names resolved.
Viewing Rules with Numeric Output
To display rules with numeric IP addresses and port numbers:
Viewing Rules with Packet Counts
To display rules with packet and byte counters:
Viewing Rules for a Specific Table
To display rules for a specific table (e.g., nat):
Viewing Rules for a Specific Chain
To display rules for a specific chain (e.g., INPUT):
Managing Rules
Adding a Rule
To append a rule to the end of a chain:
This allows incoming SSH connections.
Inserting a Rule
To insert a rule at a specific position in a chain:
This inserts a rule at position 1 to allow incoming HTTP connections.
Deleting a Rule
To delete a rule by specification:
To delete a rule by its position in a chain:
This deletes the third rule in the INPUT chain.
Replacing a Rule
To replace a rule at a specific position:
This replaces the second rule in the INPUT chain.
Flushing Rules
To remove all rules from a specific chain:
To remove all rules from all chains:
Setting Chain Policies
To set the default policy for a chain:
This sets the default policy for the INPUT chain to DROP, meaning all incoming traffic will be dropped unless explicitly allowed by a rule.
Common Firewall Configurations
Setting Up a Basic Firewall
Here's a basic firewall setup that allows established connections, SSH, and drops all other incoming traffic:
Allowing Specific Services
HTTP and HTTPS
To allow incoming HTTP and HTTPS traffic:
FTP
To allow incoming FTP traffic:
For passive FTP, you'll also need to allow a range of ports:
DNS
To allow incoming DNS queries:
Mail Services
To allow incoming mail services:
Blocking Traffic
Blocking an IP Address
To block all traffic from a specific IP address:
Blocking a Range of IP Addresses
To block a range of IP addresses using CIDR notation:
Blocking a Specific Port
To block incoming traffic on a specific port:
Rate Limiting
To protect against brute force attacks, you can limit the rate of incoming connections:
This limits SSH connections to 3 per minute from the same IP address.
Advanced Usage
Port Forwarding
To forward incoming traffic on port 80 to a different IP address and port:
Masquerading (NAT)
To enable NAT for outgoing traffic from a private network:
Logging
To log dropped packets before dropping them:
Custom Chains
To create and use a custom chain:
Saving and Restoring Rules
Iptables rules are not persistent by default and will be lost after a system reboot. To save and restore rules:
Debian/Ubuntu
Red Hat/CentOS/Fedora
Manual Method (All Distributions)
Troubleshooting
Common Issues
Rules Not Taking Effect
If your rules don't seem to be taking effect, check:
- Rule order: Rules are processed in order, and processing stops at the first match
- Default policies: Check your chain default policies
- Conflicting rules: Look for rules that might be conflicting with each other
Locked Out of SSH
If you accidentally lock yourself out of SSH:
- Use the console access provided by your hosting provider
- Boot into rescue mode if available
- Restore a backup of your iptables rules
High CPU Usage
If iptables is causing high CPU usage:
- Simplify your ruleset
- Use more efficient matching criteria
- Consider using ipset for large sets of IP addresses
Debugging Tips
Tracing Packet Flow
To trace how a packet flows through iptables chains:
Then monitor the kernel log:
Testing Rules
Before implementing a complex ruleset, test your rules with the -C
option:
This checks if the rule exists without adding it.
Comparison with Modern Alternatives
iptables vs. nftables
nftables is the successor to iptables with several improvements:
- More consistent syntax
- Better performance
- Atomic rule updates
- Simplified table structure
Example nftables equivalent to an iptables rule:
iptables vs. firewalld
firewalld is a dynamic firewall manager that uses zones and services:
- More user-friendly interface
- Dynamic rule updates without disrupting connections
- Zone-based configuration
- D-Bus interface for applications
Example firewalld equivalent to an iptables rule:
Best Practices
Security Recommendations
- Default Deny: Start with a default deny policy and explicitly allow only necessary traffic
- Least Privilege: Allow only the minimum access required for services to function
- Stateful Filtering: Use connection tracking to allow related and established connections
- Regular Audits: Regularly review and audit your firewall rules
- Documentation: Document your firewall rules and the purpose of each rule
Performance Optimization
- Rule Order: Place frequently matched rules earlier in the chain
- Use Specific Matches: Be as specific as possible with matching criteria
- Limit Logging: Excessive logging can impact performance
- Consider Hardware Offloading: Some network cards support hardware offloading for iptables
Conclusion
Iptables remains a powerful and flexible tool for managing Linux firewalls, despite the emergence of newer alternatives. Its command-line interface provides granular control over network traffic, allowing system administrators to implement complex security policies.
While the learning curve can be steep, mastering iptables gives you the ability to secure your Linux systems effectively. Whether you're setting up a simple firewall for a personal server or implementing complex network security policies for an enterprise environment, iptables provides the capabilities you need.
As you become more comfortable with iptables, consider exploring its modern alternatives like nftables and firewalld, which offer improved syntax and additional features while maintaining the powerful packet filtering capabilities that make iptables so valuable.
Test Your Knowledge
Take a quiz to reinforce what you've learned
Exam Preparation
Access short and long answer questions for written exams