StackPractices
intermediate By Mathias Paulenko

Configure iptables Firewall Rules with Bash

Set up a hardened iptables firewall with bash: SSH-safe rules, NAT port forwarding, IP blocking and reboot-proof persistence.

Topics: security

Overview

A fresh server with a public IP starts getting scanned within minutes, and one bad iptables line is all it takes to lock yourself out of your own box. I’ve hit both ends of that — so this recipe builds a sane baseline: SSH and web traffic in, everything else dropped, NAT and port forwarding when you actually need them, and rules that still exist after a reboot. On modern distros iptables fronts nftables (iptables-nft), but everything here works on both.

Once the basics are solid, Advanced iptables Firewall Rules and Hardening picks up where this stops: DDoS limits, fail2ban, port knocking.

When to Use

  • You’re setting up a new Linux server and need basic firewall protection.
  • You want to restrict incoming traffic to specific ports or source IPs.
  • You need NAT or port forwarding on a host acting as a router.
  • You’re hardening a server before deploying to production.

Skip it if you only need simple allow/deny on Ubuntu — ufw covers that with less syntax to get wrong — or if the server sits behind cloud security groups that already filter inbound traffic.

Solution

Basic firewall setup

#!/bin/bash
set -euo pipefail

# Flush existing rules and counters
iptables -F
iptables -X
iptables -Z
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X

# Allow rules first — open the door before you close it, so a
# line-by-line paste over SSH can't lock you out
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP

# Allow SSH, HTTP, HTTPS
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Log dropped packets (optional, rate-limited)
iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables-dropped: " --log-level 4

# Now set default policies — outbound stays open, inbound and routing drop
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

echo "Firewall configured. SSH, HTTP, HTTPS allowed; outbound DNS covered by ESTABLISHED."

Rate limiting SSH connections

#!/bin/bash

# Use this INSTEAD of the plain `--dport 22 ACCEPT` from the basic setup —
# that earlier rule matches first and the limiter would never trigger
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --set --name SSH
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 --name SSH -j DROP
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT

echo "SSH rate limiting configured: max 3 new connections per minute"

Port forwarding with NAT

#!/bin/bash

# Enable IP forwarding (runtime) — persist it in /etc/sysctl.conf
# or a file under /etc/sysctl.d/ so it survives reboots
echo 1 > /proc/sys/net/ipv4/ip_forward

# Forward port 8080 to port 80 on 192.168.1.100
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.100:80
iptables -t nat -A POSTROUTING -p tcp -d 192.168.1.100 --dport 80 -j MASQUERADE
# On a static public IP prefer: -j SNAT --to-source <public-ip> (less overhead)

# Allow forwarding in BOTH directions — without this, replies from the
# backend hit the FORWARD DROP policy and the forward only works one way
iptables -A FORWARD -p tcp -d 192.168.1.100 --dport 80 -j ACCEPT
iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

echo "Port forwarding: 8080 -> 192.168.1.100:80"

Block specific IP addresses

#!/bin/bash
set -euo pipefail

BLOCKED_IPS=(
    "203.0.113.50"
    "198.51.100.23"
    "192.0.2.100"
)

# Insert (-I), don't append (-A): a block rule must be evaluated BEFORE
# the port allows, otherwise SSH/HTTP/HTTPS from that IP is accepted first
for ip in "${BLOCKED_IPS[@]}"; do
    iptables -I INPUT -s "$ip" -j DROP
    echo "Blocked: $ip"
done

Allow traffic from specific subnet only

#!/bin/bash
set -euo pipefail

# Only allow SSH from 10.0.0.0/24
iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j DROP

echo "SSH restricted to 10.0.0.0/24"

Persist rules across reboots

#!/bin/bash
set -euo pipefail

# The dir doesn't exist until the package is installed (or created)
mkdir -p /etc/iptables

# Debian/Ubuntu: install first, then save — netfilter-persistent reloads
# these files on boot
apt-get install -y iptables-persistent
iptables-save > /etc/iptables/rules.v4
ip6tables-save > /etc/iptables/rules.v6
netfilter-persistent save

# RHEL/Fedora equivalent: install iptables-services and run
#   service iptables save   (writes /etc/sysconfig/iptables)
# — or use firewalld, which those distros ship by default.

# Or restore manually on boot via systemd
cat > /etc/systemd/system/iptables-restore.service << 'EOF'
[Unit]
Description=Restore iptables rules
Wants=network-pre.target
Before=network-pre.target

[Service]
Type=oneshot
ExecStart=/sbin/iptables-restore /etc/iptables/rules.v4
ExecStart=/sbin/ip6tables-restore /etc/iptables/rules.v6

[Install]
WantedBy=multi-user.target
EOF

systemctl enable iptables-restore.service

echo "Rules persisted to /etc/iptables/rules.v4 and rules.v6"

Firewall reset script

#!/bin/bash
set -euo pipefail

iptables -F
iptables -X
iptables -Z
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X

iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

echo "All iptables rules cleared. Default: ACCEPT all."

List and verify rules

#!/bin/bash
set -euo pipefail

echo "=== Filter table ==="
iptables -L -n -v --line-numbers

echo ""
echo "=== NAT table ==="
iptables -t nat -L -n -v --line-numbers

echo ""
echo "=== Mangle table ==="
iptables -t mangle -L -n -v --line-numbers

Explanation

iptables walks the chain top to bottom and stops at the first rule that matches — which is why order matters more than the rules themselves. If nothing matches, the default policy (-P) decides.

Packet flow through the baseline firewall: an incoming packet hits the INPUT chain, gets accepted if it matches loopback, an established connection, SSH, HTTP or HTTPS, and hits the DROP policy otherwise

Key concepts:

  • Chains: INPUT (incoming), OUTPUT (outgoing), FORWARD (routed).
  • Tables: filter (default), nat (address translation), mangle (packet modification).
  • Targets: ACCEPT, DROP, REJECT, LOG, MASQUERADE.
  • State matching: ESTABLISHED,RELATED allows return traffic for connections initiated from the server.

The -m recent module remembers each source IP’s recent hits, which is how the SSH limiter below works — you can watch it live in /proc/net/xt_recent/.

Variants

Companion files: all these scripts live in the bash-iptables-firewall companion repo, one runnable .sh per use case.

ApproachToolComplexityUse When
iptablesiptablesMediumStandard Linux servers
nftablesnftMediumModern Linux (replaces iptables)
UFWufwLowUbuntu/Debian quick setup
firewalldfirewall-cmdLowRHEL/CentOS/Fedora

Best Practices

  • Keep a second SSH session open while you test rules — if you lock yourself out of the first, the second is how you get back in.
  • Verify with iptables -L -n -v --line-numbers after every change; rule order is the bug source nine times out of ten.
  • Persist with iptables-persistent/netfilter-persistent or a systemd unit — rules vanish on reboot otherwise.
  • Use REJECT instead of DROP on internal networks: REJECT answers, DROP leaves clients hanging.
  • For containers, the rules on the Docker side differ — see Docker Network Isolation and Inter-Container Security.
  1. Use conntrack instead of state for new setups. The state module is deprecated in favor of conntrack which provides the same functionality with better performance:
# Old (deprecated)
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# New (recommended)
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
  1. Set kernel parameters for hardening. Combine iptables with sysctl settings for defense in depth:
# Enable SYN cookies
echo 1 > /proc/sys/net/ipv4/tcp_syncookies
# Disable IP forwarding (unless this is a router)
echo 0 > /proc/sys/net/ipv4/ip_forward
# Ignore ICMP broadcasts (smurf attacks)
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
# Reverse path filtering
echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter

Common Mistakes

  • Pasting rules line-by-line over a remote session with INPUT DROP already set. Apply the allow rules before the policies — the basic script above is ordered that way on purpose.
  • Not persisting rules. They disappear on reboot and the server is unprotected or unreachable.
  • Forgetting IPv6. ip6tables is a separate ruleset — an open IPv6 port bypasses every IPv4 rule you wrote.
  • Blocking an IP with iptables -A after the port allows. First match wins, so the block never fires — use -I to insert it ahead of them.
  • Using DROP for internal traffic. It makes troubleshooting harder — REJECT gives clients immediate feedback.

See Also

Frequently Asked Questions

What is the difference between iptables and nftables?

nftables is the successor to iptables, introduced in Linux kernel 3.13. It uses a unified syntax, supports both IPv4 and IPv6 in one table, and has better performance. iptables rules can be translated to nftables with iptables-translate.

How do I allow a range of ports?
iptables -A INPUT -p tcp --dport 8000:8100 -j ACCEPT

That opens TCP ports 8000 through 8100 — handy for dev servers that listen on a range.

Can I block all traffic from a country?

Use ipset with a country IP range list:

ipset create blocklist hash:net
# Add IP ranges (from a geoip database)
ipset add blocklist 203.0.113.0/24
iptables -A INPUT -m set --match-set blocklist src -j DROP
Why is my packet still being dropped?

Add a LOG rule before the DROP rule:

iptables -A INPUT -p tcp --dport 22 -j LOG --log-prefix "SSH-DROP: "
iptables -A INPUT -p tcp --dport 22 -j DROP

The entries land in /var/log/syslog (or /var/log/messages on RHEL). Remove the LOG rule when you're done — it gets noisy fast on a busy host.

How do I migrate from iptables to nftables?

Use iptables-translate to convert existing rules. The tool outputs the equivalent nftables syntax:

iptables-translate -A INPUT -p tcp --dport 22 -j ACCEPT
# Output: nft add rule ip filter INPUT tcp dport 22 counter accept

For full rule sets, translate the saved file:

iptables-save > rules.v4
iptables-restore-translate -f rules.v4 > rules.nft
nft -f rules.nft
Should I use DROP or REJECT for external traffic?

Use DROP for external traffic coming from the internet. DROP gives no response, making port scanning slower and giving away less information. Use REJECT for internal networks where you want clients to receive immediate feedback that a port is closed.