Mastering Netfilter: How Linux Firewall Works and How to Configure iptables
This article explains the Netfilter traffic‑processing framework built into the Linux kernel, its implementation with hook points and chains, the core concepts of rules, chains and tables, and provides a comprehensive guide to using the iptables command‑line tool for firewall configuration, NAT, SNAT, DNAT and practical examples.
Netfilter Traffic Processing Framework
Netfilter, developed in 1998 and merged into the Linux kernel in version 2.4 (2000), provides a framework for IP packet control and filtering, including:
Stateless packet filtering (IPv4, IPv6)
Stateful packet filtering (IPv4, IPv6)
Connection tracking (CT) based on protocol type
NAT and NAPT (IPv4, IPv6)
Flexible and extensible architecture
Third‑party extension APIs, e.g., invoked by iptables
Netfilter Implementation Principle
Netfilter sets multiple hook points in the kernel L3 subsystem. By placing hooks on the mandatory path of IP traffic, it can inspect, filter, intercept, or otherwise process every packet.
PASS : do not modify the packet, continue normal processing.
MODIFY : e.g., perform NAT editing, then continue processing.
DROP : e.g., enforce iptables security policies.
There are five hook points, each registering handler functions that are invoked when a packet reaches the hook.
#define NF_IP_PRE_ROUTING 0 /* After promisc drops, checksum checks. */
#define NF_IP_LOCAL_IN 1 /* If the packet is destined for this box. */
#define NF_IP_FORWARD 2 /* If the packet is destined for another interface. */
#define NF_IP_LOCAL_OUT 3 /* Packets coming from a local process. */
#define NF_IP_POST_ROUTING 4 /* Packets about to hit the wire. */
#define NF_IP_NUMHOOKS 5The five hooks correspond to five built‑in chains:
PREROUTING : before routing decision.
INPUT : packets destined for the local host after routing.
FORWARD : packets routed through the host to another destination.
OUTPUT : packets generated locally and sent out.
POSTROUTING : before the packet leaves the network interface.
After a hook handler processes a packet, it returns a verdict that determines the next action. Possible results are:
// include/uapi/linux/netfilter.h
#define NF_DROP 0 // packet is dropped
#define NF_ACCEPT 1 // packet is accepted and continues processing
#define NF_STOLEN 2 // packet is consumed by the handler
#define NF_QUEUE 3 // packet is queued to userspace
#define NF_REPEAT 4 // handler should be called againNetfilter Working Principle
Netfilter designs three core concepts for packet control and filtering:
Rules : each rule defines match conditions and an action (e.g., modify, jump, accept, drop).
Chains : ordered lists of rules; packets are matched against rules sequentially.
Tables : collections of chains grouped by usage scenario (e.g., filter, nat, mangle, raw, conntrack).
Rules
Rules are user‑defined firewall entries. Each rule consists of:
Match conditions (interface, protocol, source/destination IP, source/destination port, etc.)
An action such as ACCEPT, DROP, REJECT, SNAT, DNAT, MASQUERADE, LOG, QUEUE, RETURN, REDIRECT, MARK, etc.
Chains
A chain is an ordered list of rules. The order is critical: stricter rules should appear earlier, and the default rule is evaluated last.
Netfilter provides five built‑in chains, and users can create custom chains.
INPUT : packets destined for the local host.
OUTPUT : packets generated locally.
FORWARD : packets forwarded through the host.
PREROUTING : before routing decision.
POSTROUTING : after routing decision.
Tables
Tables categorize chains for specific scenarios:
filter (default): packet filtering, e.g., firewall rules.
nat : network address translation, e.g., SNAT/DNAT.
mangle : packet alteration, e.g., TOS/DSCP changes.
raw : early packet marking, e.g., bypass connection tracking.
conntrack : connection tracking table, foundation for stateful firewalls.
iptables CLI
iptables is a userspace tool for configuring Netfilter. It works with IPv4; ip6tables handles IPv6. The newer nftables framework (kernel ≥ 3.13) will eventually replace iptables.
iptables‑service
Most Linux distributions provide iptables as a service. Starting the service activates the firewall rules; stopping it deactivates them.
# Stop firewalld service
systemctl stop firewalld
# Disable firewalld permanently
systemctl mask firewalld
yum install -y iptables
yum install iptables-services
systemctl enable iptables.service
systemctl start iptables.serviceConfiguration files are typically:
/etc/sysconfig/iptables
/etc/iptables/iptables.rules
Command Usage
Typical workflow for defining iptables rules:
Select a table (e.g., filter, nat) which determines how packets are processed.
Select a chain (e.g., INPUT, OUTPUT) which determines where the packet traverses.
Choose match conditions (e.g., source IP, protocol, ports).
Choose an action (e.g., ACCEPT, DROP).
Basic syntax:
$ iptables [ -t table ] <options> [ chain ] [ match ] [ -j target ]Viewing Rules
$ iptables -nvL [--line-numbers] [-t table] [chain]Options:
--line-numbers: show rule numbers.
Five tables: raw, nat, filter, mangle, conntrack.
Five built‑in chains: INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING.
Adding Rules
# Append a rule to the end of a chain
iptables -A INPUT -s 192.168.1.5 -j DROP
# Insert a rule at the beginning of a chain
iptables -I INPUT -p tcp --dport 17500 -s 10.0.0.85 -j ACCEPT -m comment --comment "Friendly Dropbox"Deleting Rules
# Delete a rule by its number
iptables -D INPUT 8Modifying Rules
# Replace an existing rule
iptables -R INPUT 2 -s 127.0.0.1 -d 127.0.0.1 -i lo -j ACCEPTSaving and Loading Rules
Changes made via the command line do not automatically update the configuration files; they must be saved manually.
# Backup and save current rules
cp /etc/sysconfig/iptables /etc/sysconfig/iptables.bak
iptables-save > /etc/sysconfig/iptablesReload the service to apply changes:
systemctl reload iptablesOr load a rule file directly:
iptables-restore < /path/to/rule_file-n, --noflush: do not flush existing rules.
-t, --test: analyze rule set without committing.
Match Conditions (Xmatch)
Match conditions are divided into basic and extended matches.
Basic matches require no extra modules:
-p protocol (tcp/udp/icmp/all)
-s source address
-d destination address
-i input interface
-o output interface
! logical NOTExtended matches need additional kernel modules. Examples include:
multiport : match multiple ports (up to 15).
iprange : match a range of IP addresses.
time : match packets within a time window.
string : match application‑layer strings.
connlimit : limit concurrent connections per client IP.
limit : rate‑limit packets.
state : track connection state (INVALID, ESTABLISHED, NEW, RELATED, UNTRACKED).
NAT / NAPT
Private networks use private IP addresses, while the Internet uses public IPs. NAT (Network Address Translation) enables communication between them.
SNAT (Source NAT): used when private hosts access the public Internet.
DNAT (Destination NAT): used when the public Internet accesses services inside a private network.
PAT (Port Address Translation): usually combined with DNAT for port mapping.
SNAT
SNAT allows multiple internal hosts to share a single public IP address.
# SNAT: source address translation (internal → external)
iptables -t nat -I POSTROUTING -s 192.168.0.0/24 -o eth1 -j SNAT --to 198.51.100.3When the external IP is dynamic, MASQUERADE (dynamic SNAT) is used.
# MASQUERADE for dynamic IPs
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADEDNAT
DNAT changes the destination address of incoming packets.
# DNAT: destination address translation (external → internal)
iptables -t nat -I PREROUTING -p tcp -d 198.51.100.3 --dport 80 -j DNAT --to 192.168.0.2Forwarding must be allowed in the filter table's FORWARD chain, and IP forwarding must be enabled in the kernel.
PAT
PAT (port mapping) is often used together with DNAT, e.g., mapping public port 2222 to an internal host's port 22.
iptables -t nat -A PREROUTING -d 210.14.67.127 -p tcp --dport 2222 -j DNAT --to-dest 192.168.188.115:22
# Test
ssh [email protected] -p 2222Application Examples
Allow all hosts to access the local httpd service :
# Inbound rule
iptables -t filter -A INPUT -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
# Outbound rule
iptables -t filter -A OUTPUT -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPTPort redirection (e.g., redirect port 80 to 8080):
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
# Apply the same rule to local loopback traffic
iptables -t nat -A OUTPUT -o lo -p tcp --dport 80 -j REDIRECT --to-port 8080Specify outgoing network interface (affects OUTPUT, FORWARD, POSTROUTING):
iptables -A FORWARD -o eth0Block Windows worm attacks (drop packets containing the string "cmd.exe"):
iptables -I INPUT -j DROP -p tcp -s 0.0.0.0/0 -m string --algo kmp --string "cmd.exe"Prevent SYN flood attacks :
iptables -A INPUT -p tcp --syn -m limit --limit 5/second -j ACCEPTHow this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
