Firewall ConfigurationLinux Networking BasicsLinux Security GuideLinux Tutorials

25 Essential iptables Firewall Rules Every Linux Administrator Must Know (Examples & Best Practices)

iptables rules remain a fundamental tool for Linux administrators who need precise control over network traffic. This guide covers 25 practical, real-world iptables rules with clear examples and reliable best practices to help you secure servers on Debian, Ubuntu, RHEL/CentOS and other distributions. Whether you are auditing an existing firewall, hardening a host, or preparing rulesets for automation, these examples demonstrate common tasks: listing rules, blocking IPs, allowing services, rate-limiting, NAT/port forwarding, using conntrack, logging, ipset for scalable blocking, and saving/restoring configurations. The instructions and examples below are tailored for production use and include safety tips so you can apply iptables rules without losing remote access.

Essential iptables commands — list and inspect tables

Start by inspecting the active rules and tables. Use verbose and numeric output to avoid DNS delays and to see packet/byte counters. The iptables command below shows the filter table (default) with counters and without resolving names.

iptables -L -n -v

Chain INPUT (policy ACCEPT 1K packets, 64K bytes)
 pkts bytes target     prot opt in     out     source               destination
 1200  72K ACCEPT     tcp  --  eth0   *       192.168.1.0/24        0.0.0.0/0            tcp dpt:22
 300   18K DROP       all  --  eth0   *       203.0.113.10          0.0.0.0/0
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain OUTPUT (policy ACCEPT 500 packets, 32K bytes)
 pkts bytes target     prot opt in     out     source               destination

The -L flag lists rules, -n shows numeric addresses/ports, and -v enables verbose counters. Use this to verify whether rules are matching traffic.

Start, stop and restart iptables service (systemd and SysVinit)

How you manage iptables service depends on your init system. On modern distributions with systemd, use systemctl; older systems use the init script.

systemctl start iptables

# (no output on success; use systemctl status iptables to verify)

systemctl controls the iptables service unit. If the service is masked or not provided, your distro may use firewalld or nftables. Always check systemctl status iptables after starting.

/etc/init.d/iptables start

Starting iptables: [  OK  ]

SysVinit scripts are still used on some older RHEL/CentOS or minimal environments. The script returns OK status on success.

Check rules in a specific table (NAT example)

Inspect the NAT table to review port forwarding and postrouting rules.

iptables -t nat -L -v -n

Chain PREROUTING (policy ACCEPT 12 packets, 720 bytes)
 pkts bytes target     prot opt in     out     source               destination
  10  800 REDIRECT     tcp  --  eth0   *       0.0.0.0/0            0.0.0.0/0            tcp dpt:25 redir ports 2525
Chain POSTROUTING (policy ACCEPT 5 packets, 300 bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)

The -t nat option selects the NAT table. Use this to validate DNAT/REDIRECT rules and ensure forwarding works as intended.

Block and unblock a specific IP address

To block abusive IPs add a DROP rule to the INPUT chain; delete the rule to unblock. Be careful not to lock yourself out if you administer remotely.

iptables -A INPUT -s 203.0.113.45 -j DROP

# (no output on success; rule appended)

-A INPUT appends the rule to the INPUT chain; -s specifies source address; -j DROP discards matching packets. Use this for temporary blocking.

iptables -D INPUT -s 203.0.113.45 -j DROP

# (no output on success; rule deleted)

Use -D to remove the exact rule. If you can't delete because matching parameters differ, list rules with line numbers (iptables -L --line-numbers) and delete by index.

Block or allow specific ports and multiple ports

Control service access by matching destination ports. Use multiport to handle multiple ports in one rule.

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

# (no output on success; accepts TCP to port 8080)

-p tcp restricts the rule to TCP; –dport selects the destination port.

iptables -A INPUT -p tcp -m multiport --dports 22,80,443 -j ACCEPT

# (no output on success; accepts SSH, HTTP, HTTPS)

Use -m multiport –dports to match multiple destination ports in a single rule (more efficient and readable).

Allow a network range to a service (example: SSH)

Limit access to a port to a trusted subnet to reduce exposure.

iptables -A INPUT -p tcp -s 192.168.100.0/24 --dport 22 -j ACCEPT

# (no output on success; allows SSH from the 192.168.100.0/24 network)

This rule permits SSH from the private subnet only; place it above global DROP rules by using -I if necessary.

Block a site or network (example: Facebook CIDR)

Blocking large remote networks is better done selectively. Use up-to-date ASN/CIDR lists rather than single-host lookups.

iptables -A OUTPUT -p tcp -d 66.220.144.0/20 -j DROP

# (no output on success; drops outbound TCP to that CIDR)

Block outbound TCP traffic to an IP block by specifying -d destination network and the appropriate protocol. Note that major services use many ranges; consider DNS and CDN implications.

Port forwarding (NAT) — redirect port 25 to 2525

Use NAT prerouting to redirect incoming traffic on one port to another local port or service.

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 25 -j REDIRECT --to-port 2525

# (no output on success; packets to tcp/25 redirected to 2525)

This sends packets arriving on eth0 destined for port 25 to local port 2525. Use for local mail filtering or to run a non-privileged MTA.

Rate-limit connection flood to a web port

Protect services from low-volume DoS attempts or abusive scanners by rate-limiting matches.

iptables -A INPUT -p tcp --dport 80 -m limit --limit 100/minute --limit-burst 200 -j ACCEPT

# (no output on success; accepts up to 100 connections/min with burst 200)

-m limit enforces a matching rate; –limit sets average rate and –limit-burst sets the token bucket size for short bursts.

Block only ICMP echo requests (ping) — avoid blocking all ICMP

Do not drop all ICMP; block specific types like echo-request if needed.

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

# (no output on success; blocks ICMP echo request / ping)

–icmp-type echo-request limits the rule to ping packets. Avoid blocking other ICMP types that provide path MTU discovery and error reporting.

Allow loopback traffic

Never block loopback; local services rely on 127.0.0.1.

iptables -A INPUT -i lo -j ACCEPT

# (no output on success; allows inbound localhost traffic)

-i lo matches the loopback interface. Also allow OUTPUT for loopback where applicable.

Log dropped packets with a prefix

Logging helps identify why traffic is dropped. Send logs to syslog or journal and watch for rate impacts—use a dedicated LOG rule before DROP.

iptables -A INPUT -i eth0 -j LOG --log-prefix "IPTables-Dropped: "

Sep  3 12:05:23 host kernel: IPTables-Dropped: IN=eth0 OUT= MAC=00:... SRC=198.51.100.23 DST=203.0.113.10 LEN=60 TOS=0x00 PROTO=TCP SPT=43352 DPT=22 WINDOW=29200 RES=0x00 SYN URGP=0

The LOG target emits an entry to the kernel log (visible via journalctl -k or /var/log/messages). Include a unique prefix to filter log lines easily. Beware of high log volume.

Block by MAC address

MAC filtering only applies on local broadcast domains and can be trivially spoofed, but it’s useful for basic layer-2 restrictions on physical networks.

iptables -A INPUT -m mac --mac-source 00:11:22:33:44:55 -j DROP

# (no output on success; drops packets from that MAC)

-m mac –mac-source matches the source MAC address. Use sparingly and in addition to IP-level controls.

Limit concurrent connections per IP (SSH example)

Restrict the number of simultaneous connections per client to reduce brute-force and resource exhaustion.

iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 3 -j REJECT

# (no output on success; rejects SSH connection attempts beyond 3 per source)

–syn matches initial TCP handshake; -m connlimit enforces per-source connection limits. Use REJECT for client-friendly responses or DROP to be silent.

Use ipset for scalable blacklists (recommended over thousands of iptables rules)

iptables scales poorly with thousands of DROP rules. ipset stores large sets in kernel memory and matches them efficiently from iptables.

ipset create blacklist hash:ip

Name: blacklist
Type: hash:ip
Revision: 1
Header: family inet hashsize 1024 maxelem 65536
Size in memory: 16512
References: 0

Create an ipset set and then add IPs. Match it from iptables with -m set --match-set. This keeps iptables ruleset compact and fast.

ipset add blacklist 198.51.100.23

# (no output on success; IP added to set)

After populating an ipset, reference it:

iptables -I INPUT -m set --match-set blacklist src -j DROP

# (no output on success; packets from ipset members dropped)

This single iptables rule enforces blocking for the entire ipset; it's efficient and ideal for large, dynamic blacklists.

Create a custom chain and use it

User-defined chains help structure a large ruleset by grouping related checks.

iptables -N custom-filter

# (no output on success; custom chain created)

Use iptables -A INPUT -j custom-filter to jump to the chain and place multiple checks there. It improves readability and manageability.

Flush rules and flush specific table

Flushing clears tables—use with caution. In production, save current rules before flushing.

iptables -F

# (no output on success; all chains flushed)

-F flushes all chains in the selected table (filter default). To flush NAT table use -t nat -F.

Save and restore rules

Persist rules across reboots using iptables-save and iptables-restore, or use distribution-specific tools (iptables-persistent, firewalld, nftables). Always verify the saved file before restoring.

iptables-save > ~/iptables.rules

# (file written; contains current ruleset)

Redirect the rules into a file for storage or version control. Keep copies off-host for recovery.

iptables-restore < ~/iptables.rules

# (no output on success; rules restored)

iptables-restore reads a saved ruleset and applies it atomically. Use this in automated provisioning and boot scripts.

Allow established and related connections; drop invalid

A robust ruleset begins with allowing established traffic and rejecting invalid packets to avoid breaking legitimate sessions.

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

# (no output on success; accepts established/related packets)

This preserves response traffic for connections initiated by the host or already permitted sessions.

iptables -A INPUT -m conntrack --ctstate INVALID -j DROP

# (no output on success; drops invalid packets)

Dropping INVALID packets reduces noise and attack surface from malformed connections.

Block traffic from specific interface

Filter traffic based on interface to protect services bound to public NICs while allowing internal networks.

iptables -A INPUT -i eth0 -s 198.51.100.0/24 -j DROP

# (no output on success; drops packets from that source on eth0)

Use -i to target incoming interface and -o for outgoing.

Block outgoing mail (preventing unauthorized SMTP)

To prevent compromised hosts from sending mail, block SMTP ports on OUTPUT. Use multiport to group ports.

iptables -A OUTPUT -p tcp -m multiport --dports 25,465,587 -j REJECT

# (no output on success; outbound SMTP blocked)

Blocking SMTP at the firewall reduces risks from spam originating on your machines. Replace REJECT with DROP depending on policy.

Safety tips, IPv6 and migration notes

Always: (1) run rules locally first and test with a second SSH session before closing existing sessions; (2) use iptables -I to insert test rules at top and remove them on failures; (3) consider ip6tables for IPv6 traffic; (4) for modern systems evaluate nftables and firewalld — nftables is the kernel’s next-generation packet filter; (5) prefer ipset for large blocklists; (6) keep backups of your rules.

Conclusion

iptables remains a powerful and flexible firewall for Linux servers. The 25 rules and best practices in this guide cover daily tasks administrators use to secure systems: listing and inspecting rules, blocking IPs/ports, rate-limiting, NAT, logging, ipset for scale, conntrack usage, and persistence via save/restore. Use these examples as templates, adapt them to your environment, validate changes with safe procedures (secondary admin session, test hosts), and consider migration paths to firewalld/nftables where appropriate. Properly structured and tested iptables rulesets significantly reduce risk while maintaining necessary service availability.

Komentariši

Vaša email adresa neće biti objavljivana. Neophodna polja su označena sa *