Master Linux iptables: From Basics to Advanced Firewall Rules

This comprehensive guide explains Linux's software firewall architecture, the relationship between iptables and netfilter, common use cases, hook functions, packet flow, rule composition, command syntax, matching options, extensions, best‑practice optimizations, and how to persist rules across reboots.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Linux iptables: From Basics to Advanced Firewall Rules

Software Firewall

Linux provides a software firewall called iptables, which acts as a user‑space client that forwards user‑defined security policies to the kernel‑space framework netfilter. The iptables command manipulates netfilter to filter packets, perform NAT, and more.

In CentOS 7, firewalld replaces iptables as the default firewall.

iptables is the command‑line tool that passes configured rules to the kernel‑space netfilter firewall framework.

What is iptables

iptables is an open‑source, packet‑filtering firewall tool.

iptables Use Cases

1. Host firewall (filter table INPUT chain).
2. LAN sharing (nat table POSTROUTING chain) – basic router/NAT.
3. Port and IP mapping (nat table PREROUTING chain).
4. One‑to‑one IP mapping.

Netfilter Hooks and Packet Flow

Netfilter defines five hook functions (INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING). Users write rules with iptables, which are stored in tables and chains.

Three packet flows:

1) Incoming to local host: PREROUTING → INPUT → user process.
2) Outgoing from local host: user process → OUTPUT → POSTROUTING.
3) Forwarding: PREROUTING → FORWARD → POSTROUTING.

iptables components include five built‑in chains (INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING) and five tables (filter, nat, mangle, raw, security) with specific purposes.

Priority order of tables (high to low): security → raw → mangle → nat → filter.

Example: View Default Tables

# iptables -vnL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
# iptables -vnL -t filter
... (output omitted for brevity) ...

Considerations When Adding Rules

1) Desired function – which table?
2) Packet path – which chain?
3) Direction – source and destination?
4) Matching criteria – business needs.

Common Actions

1) Built‑in actions: ACCEPT, DROP, REJECT, SNAT, DNAT, MASQUERADE, MARK, LOG.
2) Custom chains for complex scenarios.
3) Whitelist: allow only specified hosts.
4) Blacklist: block specified hosts, allow others.

On CentOS 7/8, firewalld must be disabled to use iptables rules effectively:

# systemctl disable --now firewalld

iptables Usage

Help: man 8 iptables General syntax:

iptables [-t table] {-A|-C|-D} chain rule-specification
iptables [-t table] -I chain [rulenum] rule-specification
iptables [-t table] -R chain rulenum rule-specification
iptables [-t table] -D chain rulenum
iptables [-t table] -S [chain [rulenum]]
iptables [-t table] {-F|-L|-Z} [chain [rulenum]] [options...]
iptables [-t table] -N chain
iptables [-t table] -X [chain]
iptables [-t table] -P chain target
iptables [-t table] -E old-chain-name new-chain-name
rule-specification = [matches...] [target]
match = -m matchname [per‑match‑options]
target = -j targetname [per‑target‑options]

Key options:

-t table: specify table (raw, mangle, nat, filter (default))
-N: create new chain
-E: rename chain
-X: delete empty custom chain
-P: set default policy (ACCEPT or DROP)
-L: list rules (use -n, -v, --line-numbers for details)
-F: flush chain
-Z: zero counters

Rule Management Examples

# iptables -F OUTPUT
# iptables -A INPUT -s 172.31.0.18,172.31.0.7 -j REJECT
# iptables -I INPUT -i lo -j ACCEPT
# iptables -A INPUT -s 172.31.0.1 -j ACCEPT
# iptables -A INPUT -s 172.31.0.1 -j REJECT
# iptables -P INPUT DROP
# iptables -A INPUT -i lo -j ACCEPT
# iptables -A INPUT -s 172.31.0.17 -j ACCEPT
# iptables -A INPUT -s 172.31.0.1 -j REJECT

Best‑Practice Optimizations

1. Allow ESTABLISHED/RELATED connections first for efficiency.
2. Be cautious when allowing new inbound requests.
3. Place explicit deny rules before allow rules for special functions.
4. Order same‑application rules by specificity.
5. Order different‑application rules by broader match first.
6. Consolidate multiple similar rules into one.
7. Prefer a whitelist default policy.

Saving Rules Persistently

Method 1 (manual restore):

# iptables-save > /home/iptables.rules
# iptables-restore < /home/iptables.rules
# echo "iptables-restore < /home/iptables.rules" >> /etc/rc.d/rc.local
# chmod +x /etc/rc.d/rc.local

Method 2 (iptables‑services on CentOS 7/8):

# yum install iptables-services
# iptables-save > /etc/sysconfig/iptables
# systemctl start iptables
# systemctl enable --now iptables

Extension Modules (Examples)

TCP options:

--source-port/--sport port[:port]
--destination-port/--dport port[:port]
--tcp-flags mask comp

UDP options:

--source-port/--sport port[:port]
--destination-port/--dport port[:port]

ICMP options:

--icmp-type type[/code]

Multiport example (reject several ports):

# iptables -A INPUT -s 172.31.0.18 -p tcp -m multiport --dports 80,22,21 -j REJECT

IP range example:

# iptables -A INPUT -m iprange --src-range 172.31.0.1-172.31.0.7 -j REJECT

MAC source example:

# iptables -A INPUT -m mac --mac-source 00:0c:29:43:04:9b -j REJECT

String match example:

# iptables -A OUTPUT -p tcp --sport 80 -m string --algo bm --from 62 --string "google" -j REJECT

Time‑based rule example:

# iptables -A INPUT -s 172.31.0.0/16 -d 172.31.0.17 -p tcp --dport 80 -m time --timestart 16:00 --timestop 16:10 -j REJECT

Connection‑limit example (max 2 connections):

# iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 2 -j REJECT

Rate‑limit example (10 ICMP echo requests per minute, burst 5):

# iptables -A INPUT -p icmp --icmp-type 8 -m limit --limit 10/minute --limit-burst 5 -j ACCEPT
# iptables -A INPUT -p icmp -j REJECT

State match example (allow established, reject new):

# iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT
# iptables -A INPUT -m state --state NEW -j REJECT

Logging Example

# iptables -A INPUT -s 172.31.0.0/16 -p tcp -m multiport --dports 80,21:23 -m state --state NEW -j LOG --log-prefix "new connections: "

Check logs with tail -f /var/log/messages to see entries such as:

May 8 16:55:20 localhost kernel: new connections: IN=eth0 OUT= MAC=00:0c:29:51:72:00 SRC=172.31.0.18 DST=172.31.0.17 PROTO=TCP SPT=35722 DPT=80

Target Types

Common targets include custom chains, ACCEPT, DROP, REJECT, RETURN, LOG, SNAT, DNAT, REDIRECT, MASQUERADE. LOG can be used with --log-level and --log-prefix to record packets before they are accepted or dropped.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

firewallnetwork securityiptablesnetfilter
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.