iptables Builder

Linux iptables Firewall Rule Builder & Shell Script Generator

Construct Linux iptables firewall rules for INPUT, FORWARD, and OUTPUT chains, stateful inspection, SYN flood mitigation, NAT port forwarding, and export production shell scripts.

Firewall Presets
Add Firewall Rule
Configured Rules (5)Toggle checkbox to enable/disable
#1INPUTTCP :22
ACCEPT
#2INPUTTCP :80
ACCEPT
#3INPUTTCP :443
ACCEPT
#4INPUTTCP :9100 from 10.0.0.0/16
ACCEPT
#5INPUTALL
LOG
#!/usr/bin/env bash
# ==============================================================================
# Linux iptables Firewall Configuration Script
# Generated by ToolsAA iptables Rule Generator (https://toolsaa.com)
# 100% Client-Side Netfilter Firewall Builder
# ==============================================================================
set -euo pipefail

# Verify root privileges
if [[ $EUID -ne 0 ]]; then
   echo "Error: This script must be executed as root (e.g. sudo bash $0)" >&2
   exit 1
fi

# Find iptables binaries
IPTABLES="$(command -v iptables || echo '/sbin/iptables')"
SYSCTL="$(command -v sysctl || echo '/sbin/sysctl')"

echo "==> Applying Linux iptables firewall rules..."

# ------------------------------------------------------------------------------
# 1. Kernel Parameter Hardening & Anti-Spoofing (sysctl)
# ------------------------------------------------------------------------------
$SYSCTL -w net.ipv4.tcp_syncookies=1 >/dev/null
$SYSCTL -w net.ipv4.conf.all.rp_filter=1 >/dev/null
$SYSCTL -w net.ipv4.conf.default.rp_filter=1 >/dev/null
$SYSCTL -w net.ipv4.conf.all.accept_source_route=0 >/dev/null
$SYSCTL -w net.ipv4.conf.all.accept_redirects=0 >/dev/null
$SYSCTL -w net.ipv4.icmp_echo_ignore_broadcasts=1 >/dev/null
$SYSCTL -w net.ipv4.icmp_ignore_bogus_error_responses=1 >/dev/null

# ------------------------------------------------------------------------------
# 2. Flush Existing Rules & Reset Counters
# ------------------------------------------------------------------------------
$IPTABLES -F
$IPTABLES -X
$IPTABLES -Z
$IPTABLES -t nat -F || true
$IPTABLES -t nat -X || true
$IPTABLES -t mangle -F || true
$IPTABLES -t mangle -X || true
$IPTABLES -t raw -F || true
$IPTABLES -t raw -X || true

# ------------------------------------------------------------------------------
# 3. Set Default Chain Policies
# ------------------------------------------------------------------------------
$IPTABLES -P INPUT DROP
$IPTABLES -P FORWARD DROP
$IPTABLES -P OUTPUT ACCEPT

# ------------------------------------------------------------------------------
# 4. Core Defensive Rules: Loopback, Conntrack & Invalid Drops
# ------------------------------------------------------------------------------
# Allow unlimited loopback traffic (localhost)
$IPTABLES -A INPUT -i lo -j ACCEPT -m comment --comment "Allow all loopback inbound"
$IPTABLES -A OUTPUT -o lo -j ACCEPT -m comment --comment "Allow all loopback outbound"
# Drop packets in INVALID connection state immediately
$IPTABLES -A INPUT -m conntrack --ctstate INVALID -j DROP -m comment --comment "Drop invalid packets"
# Stateful connection tracking: Allow established and related traffic
$IPTABLES -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT -m comment --comment "Stateful allow established/related"
$IPTABLES -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT -m comment --comment "Stateful allow established/related"

# ------------------------------------------------------------------------------
# 5. Anti-DDoS: TCP SYN Flood Protection Chain
# ------------------------------------------------------------------------------
$IPTABLES -N SYN_FLOOD || true
$IPTABLES -A INPUT -p tcp --syn -j SYN_FLOOD
$IPTABLES -A SYN_FLOOD -m limit --limit 1/s --limit-burst 4 -j RETURN
$IPTABLES -A SYN_FLOOD -j DROP -m comment --comment "Drop excess SYN flood packets"

# ------------------------------------------------------------------------------
# 6. Port Scan & Malicious Flag Mitigation
# ------------------------------------------------------------------------------
# Drop NULL packets (no flags set)
$IPTABLES -A INPUT -p tcp --tcp-flags ALL NONE -j DROP -m comment --comment "Drop NULL scan packets"
# Drop XMAS packets (FIN, PSH, URG flags)
$IPTABLES -A INPUT -p tcp --tcp-flags ALL ALL -j DROP -m comment --comment "Drop XMAS scan packets"
$IPTABLES -A INPUT -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP -m comment --comment "Drop XMAS variants"
# Drop SYN-FIN scans
$IPTABLES -A INPUT -p tcp --tcp-flags SYN,FIN SYN,FIN -j DROP -m comment --comment "Drop SYN-FIN packets"
# Drop SYN-RST scans
$IPTABLES -A INPUT -p tcp --tcp-flags SYN,RST SYN,RST -j DROP -m comment --comment "Drop SYN-RST packets"

# ------------------------------------------------------------------------------
# 7. ICMP / Ping Echo-Request Control
# ------------------------------------------------------------------------------
$IPTABLES -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s --limit-burst 2 -j ACCEPT -m comment --comment "Rate-limited ICMP ping"
$IPTABLES -A INPUT -p icmp --icmp-type echo-request -j DROP -m comment --comment "Drop excess ICMP pings"

# ------------------------------------------------------------------------------
# 8. SSH Anti-Bruteforce Rate Limiter (iptables recent module)
# ------------------------------------------------------------------------------
$IPTABLES -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set --name SSH_ATTEMPTS
$IPTABLES -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 -j DROP -m comment --comment "Drop SSH bruteforce flood"

# ------------------------------------------------------------------------------
# 9. User-Configured Filter Chain Rules
# ------------------------------------------------------------------------------
# Rule 1: SSH administration (protected by recent anti-bruteforce)
$IPTABLES -A INPUT -i eth0 -p tcp --dport 22 -j ACCEPT -m comment --comment "SSH administration (protected by recent anti-bruteforce)"
# Rule 2: Standard HTTP Web traffic
$IPTABLES -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT -m comment --comment "Standard HTTP Web traffic"
# Rule 3: Encrypted HTTPS / TLS Web traffic
$IPTABLES -A INPUT -i eth0 -p tcp --dport 443 -j ACCEPT -m comment --comment "Encrypted HTTPS / TLS Web traffic"
# Rule 4: Prometheus node exporter restricted to private VPC
$IPTABLES -A INPUT -i eth0 -p tcp -s 10.0.0.0/16 --dport 9100 -j ACCEPT -m comment --comment "Prometheus node exporter restricted to private VPC"
# Rule 5: Log dropped unsolicited incoming packets
$IPTABLES -A INPUT -m limit --limit 5/min -j LOG --log-prefix "[IPT-DROP-WEB]: " --log-level 4 -m comment --comment "Log dropped unsolicited incoming packets"

echo "==> Linux iptables firewall rules successfully applied!"
echo "==> Active rules summary:"
$IPTABLES -L -v -n --line-numbers | head -n 35
Active Filter Rules
5 Rules · 0 NAT Ports
NAT Directives
SYN Flood · Anti-SSH
Hardening Directives
Bash .sh · rules.v4 · systemd

100% Private Client-Side Firewall Builder

Zero server communication or telemetry. Your server IP addresses, subnets, internal ports, and network topology are processed strictly inside your browser memory.

Stateful Inspection & DDoS Hardening

Configure stateful packet filtering (conntrack), SYN flood burst rate limits, invalid packet dropping, loopback interfaces, and spoofing protection (rp_filter).

Production Shell Script & Systemd Export

Export ready-to-run Bash shell scripts with safe rollback timers, iptables-save dump compatibility, and persistent systemd service installation commands.

Technical Reference & Architecture Guide

Linux iptables Firewall Rule Builder & Shell Script Generator — Reference Guide

Construct iptables rules for INPUT/FORWARD/OUTPUT chains, stateful inspection, SYN flood protection, NAT port forwarding, and script export.

Key Parameters & Controls

Chain & Default Policystring enum

Target netfilter chain (INPUT, FORWARD, OUTPUT) paired with default baseline policy (-P DROP, ACCEPT, REJECT).

Default: INPUT DROP
Protocol & Match Extensionsstring

Transport protocol (-p tcp, udp, icmp, all) combined with kernel match modules (-m conntrack, -m multiport, -m limit).

Default: tcp -m conntrack
Source / Destination FiltersIPv4/CIDR / Port List

Source (-s) or destination (-d) IP ranges alongside source/destination ports (--sport, --dport, --dports).

Default: -s 0.0.0.0/0 --dport 22,80,443
Connection State (ctstate)string list

Stateful tracking states (NEW, ESTABLISHED, RELATED, INVALID, UNTRACKED) for bi-directional firewall logic.

Default: ESTABLISHED,RELATED
Jump Target Actionstring enum

Action executed upon rule match (-j ACCEPT, DROP, REJECT, LOG, MASQUERADE, DNAT, SNAT, REDIRECT).

Default: ACCEPT

Pro Tips & Best Practices

Stateful Conntrack Optimization

Always place 'iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT' at the very top of your ruleset. This bypasses rule evaluation for existing connections, reducing CPU latency under heavy traffic.

Anti-Lockout Fallback Protocol

Before altering default chain policy to DROP on remote servers, execute an auto-revert timer in a separate shell: 'sleep 300 && iptables -P INPUT ACCEPT && iptables -F'. Alternatively, verify with 'iptables-apply' to test rules safely.

SYN Flood Rate Limiting

Mitigate TCP SYN flood volumetric attacks by rate-limiting unestablished handshakes: 'iptables -A INPUT -p tcp --syn -m limit --limit 25/s --limit-burst 100 -j ACCEPT' followed by a DROP rule.

Loopback & ICMP Diagnostic Pinning

Never drop loopback traffic ('-i lo -j ACCEPT') as local UNIX daemons rely on localhost IPC. Permit controlled ICMP Echo Requests ('-p icmp --icmp-type echo-request -m limit --limit 5/s -j ACCEPT') to maintain network diagnostic visibility without vulnerability to ping floods.

Common Gotchas & Troubleshooting

Remote SSH Connection Dropped Immediately Upon Applying Rules

Default INPUT policy was set to DROP before explicitly permitting port 22 or ESTABLISHED connections. Regain access via out-of-band console (IPMI/VNC), run 'iptables -P INPUT ACCEPT', and ensure 'iptables -A INPUT -p tcp --dport 22 -j ACCEPT' precedes policy shifts.

Kernel Error: 'nf_conntrack: table full, dropping packet'

High packet volume exhausted the connection tracking hash table. Raise capacity via sysctl ('sysctl -w net.netfilter.nf_conntrack_max=262144'), optimize timeout thresholds ('net.netfilter.nf_conntrack_tcp_timeout_established=600'), or bypass tracking for high-throughput stateless ports using '-t raw -A PREROUTING -p tcp --dport 80 -j NOTRACK'.

Docker Overwrites or Ignores Custom FORWARD and NAT Rules

Docker manipulates iptables directly and inserts its own chains (DOCKER, DOCKER-USER). Instead of editing the FORWARD chain directly, place custom ingress/egress filtering in the 'DOCKER-USER' chain to prevent Docker daemon restarts from overriding network policies.

Frequently Asked Questions

What is the structural difference between iptables, nftables, and UFW/firewalld?▼

iptables interfaces directly with legacy Linux Netfilter kernel hooks through static tables (filter, nat, mangle). nftables is its modern kernel successor offering unified rule syntax and atomic commits. UFW and firewalld are higher-level service daemons that dynamically generate iptables or nftables rules under the hood.

Why is DROP generally preferred over REJECT on public-facing internet interfaces?▼

DROP silently discards incoming packets without sending any response, forcing port scanners and attackers to wait for connection timeouts while hiding system presence. REJECT sends back ICMP port-unreachable or TCP RST packets, confirming that the host IP is active and consuming outbound bandwidth.

How do NAT PREROUTING and POSTROUTING chains differ in port forwarding?▼

PREROUTING is evaluated before routing decisions to alter destination addresses (-j DNAT --to-destination IP:port), directing incoming external packets to an internal server. POSTROUTING is evaluated after routing to alter source addresses (-j MASQUERADE or -j SNAT --to-source IP), enabling internal private subnets to route outbound traffic through a public interface.

How are iptables rules persisted across Linux server reboots?▼

iptables rules reside in volatile kernel memory and clear on reboot. On Debian/Ubuntu, install 'iptables-persistent' and execute 'netfilter-persistent save'. On RHEL/Rocky Linux/AlmaLinux, install 'iptables-services' and execute 'iptables-save > /etc/sysconfig/iptables' followed by enabling the systemd service.

How do I inspect live packet hit counts and byte throughput for active rules?▼

Execute 'iptables -nvL --line-numbers' to display line indices alongside packet and byte counters. For live real-time rule inspection during load testing, use 'watch -n 1 iptables -nvL INPUT' to observe counter increments dynamically.

Related Tools & Utilities

All Tools →