iptables Command: Tutorial & Examples

Show and configure the kernel's firewall

iptables is a powerful command-line utility used to configure the Linux kernel's built-in firewall. It allows administrators to set up, maintain, and inspect tables of rules that govern the filtering and manipulation of network packets. This article provides an in-depth overview of how iptables works, its common usage, practical examples, and important considerations for managing firewall rules on a Linux server.

The Linux kernel implements firewall functionality via different tables containing chains of rules. Each chain is a list of rules that match packets based on various criteria and specify what action (target) to take, such as accepting or dropping the packet. Understanding these concepts, along with common parameters and usage patterns, is essential for effective firewall management.

How iptables Works

iptables operates by managing several tables within the Linux kernel, each designed for different packet processing tasks. The most commonly used table is the filter table, which handles packet filtering (accepting, dropping, rejecting packets). Other tables include:

  • nat: Handles Network Address Translation, used for modifying source/destination addresses, commonly for masquerading or port forwarding.
  • mangle: Used for specialized packet alteration like changing Type of Service (TOS) bits or TTL.
  • raw: Allows configuration of exemptions from connection tracking.
  • security: Integrates with Linux Security Modules (LSM) like SELinux.

Each table contains one or more chains, which are ordered lists of rules that packets traverse. The three built-in chains for the filter table are:

  • INPUT: For packets destined for the local system.
  • OUTPUT: For packets originating from the local system.
  • FORWARD: For packets routed through the system (acting as a router).

When a packet arrives at the system, it is processed according to the rules in these chains. Each rule checks the packet against matching criteria (such as protocol, source/destination IP, port, interface), and if a match occurs, the specified target action is executed. Targets can be:

  • ACCEPT: Allow the packet.
  • DROP: Silently discard the packet.
  • REJECT: Reject with an error message.
  • LOG: Log the packet details.
  • Other specialized targets (e.g., DNAT, SNAT in the nat table).

If no rule matches, the chain's policy (default action) is applied, typically ACCEPT or DROP.

Why iptables Is Important

Linux servers often run services exposed to networks and the internet, making them potential targets for attacks. A firewall provides a critical layer of defense by controlling incoming and outgoing network traffic according to security policies.

iptables was introduced to leverage the Linux kernel's packet filtering framework, providing fine-grained control over network traffic. It allows system administrators to enforce security policies, prevent unauthorized access, mitigate denial-of-service attacks, and implement network address translation.

Although iptables has been the standard firewall tool for many years, it is being gradually replaced by the newer nft command and the Netfilter framework's nftables system, which offers a more flexible and efficient syntax.

Common iptables Parameters

Understanding the most important iptables command-line options helps in managing firewall rules effectively:

  • -A chain rule-specification: Append a new rule at the end of the specified chain.
  • -I chain [rulenum] rule-specification: Insert a rule at the given position (defaults to 1).
  • -D chain rule-specification or -D chain rulenum: Delete a rule matching the specification or at the given position.
  • -L [chain]: List all rules in the specified chain or all chains if none specified.
  • -F [chain]: Flush (delete) all rules in the specified chain or all chains if none specified.
  • -P chain target: Set the default policy for the specified chain.
  • -N chain: Create a new user-defined chain.
  • -X chain: Delete a user-defined chain.
  • -v: Verbose output (shows packet and byte counters).
  • -n: Numeric output of addresses and ports (skip DNS resolution).
  • -s address[/mask]: Match packets with source IP address.
  • -d address[/mask]: Match packets with destination IP address.
  • -p protocol: Match protocol (tcp, udp, icmp, etc.).
  • --dport port: Match destination port (requires -p tcp or -p udp).
  • --sport port: Match source port.
  • -j target: Specify the target action for matching packets.

Basic Usage Examples

Below are common usage examples illustrating how to use iptables commands.

1. Allow Incoming HTTP Traffic

iptables -A INPUT -p tcp --dport 80 -j ACCEPT

This command appends a rule to the INPUT chain to accept incoming TCP packets destined for port 80 (HTTP).

2. Block Incoming Traffic from a Specific IP

iptables -A INPUT -s 192.168.1.100 -j DROP

Drops all packets coming from IP address 192.168.1.100.

3. Allow Established and Related Connections

iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

Allows packets that are part of or related to existing connections, essential for proper stateful firewall behavior.

4. Drop All Incoming ICMP Echo Requests (Ping)

iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

Prevents ping requests from reaching the server.

5. List All Rules Verbosely

iptables -L -v -n

Lists all rules with packet and byte counters, showing numeric IP addresses and ports.

6. Set Default Policy to DROP for INPUT Chain

iptables -P INPUT DROP

Sets the default policy of the INPUT chain to DROP, so any unmatched packet will be discarded.

7. Delete a Specific Rule by Specification

iptables -D INPUT -p tcp --dport 80 -j ACCEPT

Deletes the rule allowing TCP port 80 traffic from the INPUT chain.

Practical Examples Using iptables

Here are more comprehensive examples showing typical use cases.

Example: Basic Firewall Setup

iptables -F

iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT

This flushes all existing rules, sets default policies to DROP for incoming and forwarded packets, and allows outgoing traffic. It permits established connections, SSH (port 22), HTTP (80), HTTPS (443), and loopback interface traffic.

Example: Port Forwarding with NAT

Assuming the server acts as a router forwarding incoming port 8080 traffic to an internal server on port 80:

iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.10:80
iptables -A FORWARD -p tcp -d 192.168.1.10 --dport 80 -j ACCEPT

This uses the nat table to redirect incoming traffic and allows forwarding.

Potential Problems and Pitfalls

  • Locking Yourself Out: Setting restrictive rules without allowing SSH (port 22) can block remote access.
  • Rule Order Matters: Rules are evaluated in order; placing a broad ACCEPT rule before DROP rules can bypass intended blocking.
  • Default Policies: If default policies are DROP, forgetting to allow essential traffic can cause service disruption.
  • Flushing Rules: Running iptables -F removes all rules, potentially exposing services.
  • Kernel Module Dependencies: Some modules must be loaded for certain matches or targets.
  • Stateful Filtering: Not using connection tracking can cause legitimate packets to be dropped.

Common Errors and Troubleshooting

  • Use iptables -L -v -n to inspect rules and counters.
  • Check that required kernel modules (e.g., nf_conntrack) are loaded.
  • Ensure no conflicting firewall services (firewalld, ufw) are running.
  • Use dmesg or /var/log/syslog to check kernel messages for errors.
  • Remember to save rules persistently as changes are not saved automatically.

Scripting and Automation

To save current firewall rules to a file:

iptables-save > /etc/iptables/rules.v4

To restore saved rules:

iptables-restore < /etc/iptables/rules.v4

Many Linux distributions provide mechanisms to load iptables rules on boot, such as scripts in /etc/network/if-pre-up.d/ or via systemd services.

Security Considerations

  • Follow the principle of least privilege: allow only necessary traffic.
  • Regularly audit firewall rules.
  • Combine iptables with other security measures like SELinux and intrusion detection.
  • Avoid overly permissive rules that expose services unnecessarily.
  • Keep iptables and kernel updated to fix vulnerabilities.

Comparison with Alternatives

iptables is mature and widely supported but has limitations in syntax complexity and performance with large rule sets. The newer nft command provides a modern replacement with simpler syntax and better scalability. Tools like firewalld and ufw offer user-friendly frontends to iptables or nftables.

See Also

Further Reading

As an Amazon Associate, I earn from qualifying purchases.

The text above is licensed under CC BY-SA 4.0 CC BY SA