Table of Contents
-
- 1.1 The Netfilter Framework
- 1.2 How iptables Works
-
- 2.1 Built-in Chains
- 2.2 User-Defined Chains
- 2.3 Chain Policies
- 2.4 Chain Traversal Order
-
- 3.1 Terminating Targets: ACCEPT, DROP, REJECT
- 3.2 Non-Terminating Targets: LOG, ULOG
- 3.3 Special Targets: RETURN
- 3.4 NAT Targets: SNAT, DNAT, MASQUERADE, REDIRECT
-
How Chains and Targets Work Together
- 4.1 Packet Traversal Flow
- 4.2 Rule Matching Logic
-
- 5.1 Allowing SSH Access
- 5.2 Blocking a Specific IP Address
- 5.3 Logging Incoming Traffic
- 5.4 Using User-Defined Chains for Organization
- 5.5 Setting Up Basic NAT
-
- 6.1 Listing Rules
- 6.2 Saving and Restoring Rules
- 6.3 Debugging with Verbose Logs
What is iptables?
Before diving into chains and targets, let’s establish a foundational understanding of iptables.
1.1 The Netfilter Framework
iptables is not a firewall itself but a user-space tool that configures the netfilter framework—a set of hooks in the Linux kernel responsible for packet filtering, NAT, and packet mangling. These hooks act as checkpoints where packets can be inspected, modified, or dropped as they traverse the network stack.
The netfilter framework defines five key hooks where packet processing occurs:
- PREROUTING: Processes packets as they arrive (before routing decisions).
- INPUT: Processes packets destined for the local system (after routing).
- FORWARD: Processes packets routed through the system (not destined for the local system).
- OUTPUT: Processes packets generated by the local system (before routing).
- POSTROUTING: Processes packets after routing (before they leave the system).
1.2 How iptables Works
iptables allows users to define rules that specify actions for packets matching certain criteria (e.g., source IP, destination port, protocol). These rules are organized into chains, which are attached to netfilter hooks. When a packet reaches a hook, it is processed by the corresponding chain’s rules.
Each rule in a chain includes:
- Matching criteria: Conditions a packet must satisfy (e.g.,
-p tcp --dport 80for TCP port 80). - Target: The action to take if the packet matches (e.g.,
ACCEPT,DROP).
In short: Packets hit netfilter hooks → hooks trigger chains → chains process rules → rules apply targets.
Understanding iptables Chains
A chain is a ordered list of rules that process packets at a specific netfilter hook. Chains determine the path packets take and ensure rules are applied consistently.
2.1 Built-in Chains
iptables provides five built-in chains, each directly associated with a netfilter hook:
| Chain | Netfilter Hook | Purpose |
|---|---|---|
PREROUTING | PREROUTING | Processes incoming packets before routing (used for DNAT). |
INPUT | INPUT | Processes packets destined for the local system (e.g., SSH, HTTP). |
FORWARD | FORWARD | Processes packets routed through the system (e.g., a router). |
OUTPUT | OUTPUT | Processes packets generated by the local system (e.g., outgoing HTTP). |
POSTROUTING | POSTROUTING | Processes packets after routing (used for SNAT/MASQUERADE). |
2.2 User-Defined Chains
In addition to built-in chains, users can create custom chains to organize rules logically. For example, you might create a SSH_CHAIN to group all SSH-related rules, making management easier.
User-defined chains are not tied to netfilter hooks by default. To use them, you must “jump” to them from a built-in chain using the -j (jump) target.
2.3 Chain Policies
Every chain has a default policy—the action taken if a packet does not match any rule in the chain. Policies are critical for security: a misconfigured policy (e.g., default ACCEPT on INPUT) can leave your system exposed.
Common policies:
ACCEPT: Allow the packet (default for most chains).DROP: Silently discard the packet (no response sent to the sender).REJECT: Discard the packet and send an error response (e.g., “Connection refused”).
Example: Set the INPUT chain policy to DROP (deny all incoming traffic by default):
iptables -P INPUT DROP
2.4 Chain Traversal Order
Rules in a chain are processed top to bottom. The first rule that matches the packet determines the outcome (unless the target is non-terminating, like LOG). If no rules match, the chain’s default policy is applied.
Targets in iptables
A target is the action iptables takes when a packet matches a rule. Targets can terminate packet processing, modify packets, or log activity.
3.1 Terminating Targets
These targets stop further processing of the packet in the current chain:
-
ACCEPT: Allow the packet to proceed through the network stack.
Example: Allow HTTP traffic (port 80):iptables -A INPUT -p tcp --dport 80 -j ACCEPT -
DROP: Discard the packet without notifying the sender. Use for blocking malicious traffic.
Example: Block a suspicious IP:iptables -A INPUT -s 192.168.1.100 -j DROP -
REJECT: Discard the packet and send an ICMP error (e.g.,icmp-port-unreachable). Use when you want the sender to know the connection was refused.
Example: Reject SSH traffic from a specific IP:iptables -A INPUT -s 10.0.0.5 -p tcp --dport 22 -j REJECT --reject-with icmp-port-unreachable
3.2 Non-Terminating Targets
These targets log or modify packets but do not stop processing. The packet continues to the next rule in the chain.
-
LOG: Logs packet details to/var/log/syslog(ordmesg). Use--log-prefixto add context.
Example: Log incoming SSH attempts:iptables -A INPUT -p tcp --dport 22 -j LOG --log-prefix "SSH Attempt: " --log-level 4 -
ULOG: Similar toLOG, but sends logs to a user-space daemon (e.g.,ulogd). Useful for high-volume logging.
3.3 Special Targets
RETURN: Sends the packet back to the calling chain (the chain that jumped to the current chain). If the current chain is a built-in chain,RETURNtriggers the chain’s default policy.
Example: In a user-defined chain, return to theINPUTchain after processing:iptables -A MY_CHAIN -p udp --dport 53 -j RETURN # Send back to INPUT
3.4 NAT Targets
Network Address Translation (NAT) targets modify packet source/destination IPs or ports. They are used in PREROUTING, POSTROUTING, and OUTPUT chains.
-
SNAT(Source NAT): Rewrites the source IP of outgoing packets (e.g., for internal hosts to access the internet via a router’s public IP).
Example: Rewrite source IP to203.0.113.10for packets leaving viaeth0:iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 203.0.113.10 -
MASQUERADE: A dynamic version ofSNATfor interfaces with changing IPs (e.g., home routers with DHCP). Automatically uses the interface’s current IP.
Example: Masquerade traffic from the internal network (192.168.1.0/24) viaeth0:iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE -
DNAT(Destination NAT): Rewrites the destination IP/port of incoming packets (e.g., forward external traffic to an internal server).
Example: Forward external HTTP (port 80) to an internal server (192.168.1.5:8080):iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.5:8080 -
REDIRECT: Redirects packets to the local system (e.g., route port 80 to a local proxy on port 3128).
Example: Redirect HTTP traffic to a local proxy:iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 3128
How Chains and Targets Work Together
Chains and targets are interdependent: chains provide the structure, and targets provide the action. Let’s explore their interaction.
4.1 Packet Traversal Flow
A packet’s journey through iptables follows this general path (simplified):
-
Incoming Packet: Arrives at the network interface →
PREROUTINGchain (nat table) → routing decision.- If destined for the local system →
INPUTchain (filter table) → local process. - If routed through the system →
FORWARDchain (filter table) →POSTROUTINGchain (nat table) → outgoing interface.
- If destined for the local system →
-
Outgoing Packet: Generated by a local process →
OUTPUTchain (nat table) → routing decision →POSTROUTINGchain (nat table) → outgoing interface.
4.2 Rule Matching Logic
- Rules in a chain are checked in order. The first matching rule’s target is applied.
- Non-terminating targets (e.g.,
LOG) allow the packet to continue to subsequent rules. - If no rules match, the chain’s default policy is applied.
Practical Examples
Let’s apply chains and targets to common scenarios.
5.1 Allowing SSH Access
Permit SSH (port 22) from a trusted IP while blocking all other incoming traffic:
# Set default policy to DROP (deny all)
iptables -P INPUT DROP
# Allow SSH from 192.168.1.200
iptables -A INPUT -s 192.168.1.200 -p tcp --dport 22 -j ACCEPT
# Allow loopback traffic (critical for local services)
iptables -A INPUT -i lo -j ACCEPT
5.2 Blocking a Specific IP Address
Block all traffic from 203.0.113.5:
iptables -A INPUT -s 203.0.113.5 -j DROP
5.3 Logging Incoming Traffic
Log all incoming TCP packets before applying rules:
iptables -A INPUT -p tcp -j LOG --log-prefix "Incoming TCP: " --log-level 5
5.4 Using User-Defined Chains for Organization
Create a chain to manage web traffic (HTTP/HTTPS) and jump to it from INPUT:
# Create a user-defined chain
iptables -N WEB_TRAFFIC
# Add rules to the chain
iptables -A WEB_TRAFFIC -p tcp --dport 80 -j ACCEPT # HTTP
iptables -A WEB_TRAFFIC -p tcp --dport 443 -j ACCEPT # HTTPS
# Jump to WEB_TRAFFIC from INPUT
iptables -A INPUT -j WEB_TRAFFIC
5.5 Setting Up Basic NAT
Enable internet access for an internal network (10.0.0.0/24) using MASQUERADE:
# Enable IP forwarding (required for routing)
echo 1 > /proc/sys/net/ipv4/ip_forward
# Add MASQUERADE rule in the nat table
iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE
Troubleshooting iptables
6.1 Listing Rules
View all rules in the filter table (default):
iptables -L -v -n # -v (verbose), -n (numeric IPs/ports)
List rules in the nat table:
iptables -t nat -L -v -n
6.2 Saving and Restoring Rules
Rules are not persistent by default (lost on reboot). Save them:
# On Debian/Ubuntu
iptables-save > /etc/iptables/rules.v4
# On RHEL/CentOS
service iptables save
Restore rules:
iptables-restore < /etc/iptables/rules.v4
6.3 Debugging with Verbose Logs
Use --log-level debug with LOG targets to capture detailed packet info:
iptables -A INPUT -j LOG --log-prefix "DEBUG: " --log-level debug
Conclusion
iptables chains and targets are the building blocks of Linux firewall configuration. Chains organize rules by packet flow (via netfilter hooks), while targets define actions for matching packets. By mastering these concepts, you can secure systems, route traffic, and troubleshoot network issues with confidence.
Remember:
- Use built-in chains for core packet flow and user-defined chains for organization.
- Set restrictive default policies (e.g.,
DROP) and explicitly allow necessary traffic. - Test rules in a non-production environment before deploying.