Testing Your iptables Rules

Tutorials · Published 2019-08-24 · Revised 2026-11-14
Author-approved revision; target-platform validation outstanding · Joomla source

9,431 Total views across this article’s versions; includes the historical baseline where available.

It may not be obvious, but you need to test your rules—both routing rules (via ip rule) and iptables rules—before you cement them in place.

One useful thing about testing rules before making them permanent is that changes made only to the running configuration do not normally survive a reboot. If you make a catastrophic screw-up, restarting the server may get you back to a working configuration—provided nothing saves or reloads those changes at startup.

Before you rely on that, check how your server loads its firewall rules, routing rules, and routes. A reboot can bring the same problem right back if a startup service or script reapplies the changes.

Make sure you have a way to recover before you begin testing. For a remote server, that means access to a local console, a hosting provider’s console, or another management connection that doesn’t depend on the network configuration you’re changing. If rebooting is your recovery plan, confirm that you can initiate it through that independent access and that the server’s startup configuration is known to work.

Before you make your changes permanent, it’s critical to thoroughly test them, lest you lock yourself out of your server. I can’t stress this enough, especially with a headless or remote server.

I’ve found the best way to do this is to create custom scripts that populate your RPDB and iptables rules. You can populate your route tables the same way, and I’ll show you a basic example below.

Listing Rules by Number

Here’s how to list the rules in every chain of the default filter table, with line numbers. This can be useful when troubleshooting or identifying a rule for deletion.

Run the administrative commands in this article as root.

iptables -L -v -n --line-numbers

If you want to focus on a particular table, specify its name after -t. For example, to list the rules in the nat table:

iptables -t nat -L -v -n --line-numbers

You can narrow the listing further by specifying a chain after -L. For example, to inspect the OUTPUT chain in the mangle table:

iptables -t mangle -L OUTPUT -v -n --line-numbers

Remember, rule numbers belong to a particular chain within a particular table. They can change when you add or remove rules, so check the current listing before using a rule number.

Shell Scripts

The names can be a bit confusing. iproute2 is the tool suite, but the command you type is ip. You may also encounter the package name iproute in older documentation; that package supplied the same ip command. The name alone doesn’t tell you which version is installed.

Use ip -V to check the utility’s version and uname -r to check the running kernel. Both matter when comparing older instructions with your server. The removal of the old IPv4 route cache was a kernel change, not simply a change from a package named iproute to one named iproute2.

Create two independent scripts: one for iptables, and one for your RPDB rules and routes. Keeping them separate makes each part easier to review and lets each run at the right point during startup. The firewall script no longer calls the routing script.

A script reaching its last line doesn’t necessarily mean everything worked. Check the result of each command, and stop if a required step fails. Each script must report its own failure to the shell or service that started it.

Remember, stopping the script doesn’t undo changes it has already made. You’ll still need the recovery method discussed earlier.

You should also be able to run the script again without accumulating duplicate rules. Check for the rule you intend to create before adding it, and limit route updates to entries your script manages. If you find a conflicting configuration, stop and investigate rather than clearing it automatically.

Before adapting the example, identify the source address you want to match, the gateway traffic should use, the outgoing interface, and the routing table. Choose an explicit rule priority that fits your existing policy. These values describe different parts of your network; don’t assume the sample values will work on your server.

iptables Shell Script

Open your favorite text editor and begin a new file:

nano /etc/iptables-script.sh

The purpose of this example is to show how the scripts fit together. You’ll need to supply the firewall rules and routing policy your server requires.

Before adding commands that clear existing rules, check what those commands will remove. Flushing an entire table also removes rules created by other scripts or services. Limit any cleanup to rules your script manages.

The earlier example also included a rule that copied connection marks onto outgoing packets, without showing how those marks were assigned or used. I’ve left that out here because it needs a more complete example to explain its purpose.

This script is the early firewall stage. It must work before addresses are assigned and without DNS or a connection to another server. Your policy needs to allow the traffic used to configure the network, such as DHCP where applicable, and cover each enabled address family.

Replace the placeholder function with your reviewed rules and checks. Setting RULES_REVIEWED=yes alone isn’t enough: the unchanged placeholder deliberately reports failure so an empty policy cannot be mistaken for protection.

#! /bin/bash

# Early firewall stage; not a complete firewall configuration.
# This script must not call the routing script or wait for networking.

# Set to yes only after adding and reviewing your own rules below.
RULES_REVIEWED=no

run() {
    "$@" || {
        status=$?
        printf 'Failed (%s): %s\n' "$status" "$*" >&2
        exit "$status"
    }
}

if [ "$RULES_REVIEWED" != yes ]; then
    printf 'Add and review your firewall rules before running this outline.\n' >&2
    exit 1
fi

apply_firewall_rules() {
    # Replace this stub with your server-specific firewall rules and checks.
    # Use run for required commands; verify existing rules before adding them.
    # Treat inspection errors as failures, not as proof a rule is absent.
    # Limit cleanup to entries this script manages.
    # Do not require DNS, a configured address, or a reachable remote host.
    # Allow necessary setup traffic and cover every enabled address family.
    printf 'No firewall policy has been supplied.\n' >&2
    return 1
}

run apply_firewall_rules

exit 0

Save the file. We’ll set ownership and permissions for both scripts after the routing script is ready.

Routing and RPDB Rules Shell Script

You’ll now create the script that manages your routing rules and routes. This example uses a dedicated numeric table ID, so it doesn’t require a table-name mapping. If you prefer a name, see The Master Routing Table for the original explanation.

Begin a new file. Use the same filename in the separate routing service described in the Persistence article:

nano /etc/routing-script.sh

This example covers IPv4 traffic originating on the server, with a source address already assigned to the outgoing interface and a different gateway on the same directly attached subnet. It doesn’t cover forwarded traffic, VPNs, VRFs, or multipath routing. Reserve a dedicated table and priority for this script, and run only one instance at a time. No other service should manage those entries.

Fill in the source address, actual subnet prefix, gateway, interface, table ID, and priority. Confirm the subnet and gateway reachability yourself before setting CONFIGURATION_REVIEWED=yes. The script checks the assigned source address and existing entries, but those checks don’t establish that your network design will work.

On a repeated run, matching entries are left alone and missing entries are added. Conflicting or unfamiliar entries stop the script for review. Changing the configuration values is a separate migration: this example doesn’t remove entries belonging to an earlier configuration. Remember, this is just a sample file. Do not use it verbatim!

#! /bin/bash
# Narrow IPv4 example for traffic originating on this server.
# Separate routing stage: its service requires successful firewall startup.
# A direct manual invocation does not enforce that service dependency.
# One directly attached subnet, one gateway, and one dedicated routing table.
# Run one instance at a time; no other service may manage this table/priority.
# This is not a forwarding, VPN, VRF, or multipath example.
export LC_ALL=C

# Fill in and review every value. Do not copy another server's settings.
CONFIGURATION_REVIEWED=no
SOURCE_IP=''       # Address already assigned to this server's interface
LINK_PREFIX=''     # Canonical directly attached subnet, such as a.b.c.0/24
GATEWAY=''         # A different, directly reachable router in that subnet
INTERFACE=''       # Actual outgoing interface name
TABLE_ID=''        # Dedicated numeric table ID, 1-252 in this example
RULE_PRIORITY=''   # Unused priority, 1-32765; review existing policy order

fail() {
    printf '%s\n' "$2" >&2
    exit "$1"
}

run() {
    "$@" || {
        status=$?
        fail "$status" "Failed ($status): $*"
    }
}

if [ "$CONFIGURATION_REVIEWED" != yes ]; then
    fail 1 'Configure and review the network settings before running this sample.'
fi
for value in "$SOURCE_IP" "$LINK_PREFIX" "$GATEWAY" "$INTERFACE"; do
    case "$value" in
        ''|*[[:space:]]*) fail 1 'Network settings must be filled in without whitespace.' ;;
    esac
done
for value in "$TABLE_ID" "$RULE_PRIORITY"; do
    case "$value" in
        ''|0*|*[!0-9]*) fail 1 'Use positive decimal IDs without leading zeros.' ;;
    esac
    [ "${#value}" -le 5 ] || fail 1 'ID is outside this example range.'
done
[ "$TABLE_ID" -le 252 ] || fail 1 'Choose a dedicated table ID from 1 through 252.'
[ "$RULE_PRIORITY" -le 32765 ] || fail 1 'Choose a priority from 1 through 32765.'
[ "$SOURCE_IP" != "$GATEWAY" ] || fail 1 'Source and gateway must differ in this example.'

# Read everything before making any changes; failures stop the script.
addresses=$(ip -4 -o address show dev "$INTERFACE") || {
    status=$?; fail "$status" 'Could not inspect the interface addresses.'
}
source_found=no
while read -r -a fields; do
    for ((i=0; i<${#fields[@]}-1; i++)); do
        if [ "${fields[i]}" = inet ] && [ "${fields[i+1]%/*}" = "$SOURCE_IP" ]; then
            source_found=yes
        fi
    done
done <<< "$addresses"
[ "$source_found" = yes ] || fail 1 'SOURCE_IP is not assigned to INTERFACE.'

rules=$(ip -4 -N rule show) || {
    status=$?; fail "$status" 'Could not inspect routing rules.'
}
rule_count=0
while read -r priority from source lookup table extra; do
    if [ "$priority" = "$RULE_PRIORITY:" ]; then
        [ "$from" = from ] && [ "$lookup" = lookup ] &&
        [ "$table" = "$TABLE_ID" ] && [ -z "$extra" ] || fail 1 'Rule priority conflict.'
        case "$source" in
            "$SOURCE_IP"|"$SOURCE_IP/32") ;;
            *) fail 1 'Source address conflicts at the chosen priority.' ;;
        esac
        rule_count=$((rule_count + 1))
    else
        # Conservatively refuse any other rule referencing this table.
        case " $priority $from $source $lookup $table $extra " in
            *" lookup $TABLE_ID "*) fail 1 'Another rule already uses this table.' ;;
        esac
    fi
done <<< "$rules"
[ "$rule_count" -le 1 ] || fail 1 'Duplicate rules exist at the chosen priority.'

# An unused table may not exist yet. Inspect all tables first so an error
# querying a particular table is never mistaken for an empty table.
all_routes=$(ip -4 -N -o route show table all) || {
    status=$?; fail "$status" 'Could not inspect routing tables.'
}
table_present=no
while read -r line; do
    case " $line " in
        *" table $TABLE_ID "*) table_present=yes ;;
    esac
done <<< "$all_routes"
routes=''
if [ "$table_present" = yes ]; then
    routes=$(ip -4 -o route show table "$TABLE_ID") || {
        status=$?; fail "$status" 'Could not inspect the dedicated table.'
    }
fi
link_count=0
default_count=0
while read -r line; do
    # Exact, deliberately conservative comparisons: unfamiliar attributes
    # require review rather than silently replacing an existing route.
    case "$line" in
        '') ;;
        "$LINK_PREFIX dev $INTERFACE scope link") link_count=$((link_count + 1)) ;;
        "default via $GATEWAY dev $INTERFACE") default_count=$((default_count + 1)) ;;
        *) fail 1 "Unexpected route in dedicated table: $line" ;;
    esac
done <<< "$routes"
[ "$link_count" -le 1 ] && [ "$default_count" -le 1 ] || fail 1 'Duplicate routes found.'

# Confirm manually that LINK_PREFIX is the actual attached subnet and
# GATEWAY is reachable on it; command success is not a connectivity test.
# Populate routes before installing the rule that selects this table.
if [ "$link_count" -eq 0 ]; then
    run ip -4 route add "$LINK_PREFIX" dev "$INTERFACE" scope link table "$TABLE_ID"
fi
if [ "$default_count" -eq 0 ]; then
    run ip -4 route add default via "$GATEWAY" dev "$INTERFACE" table "$TABLE_ID"
fi
if [ "$rule_count" -eq 0 ]; then
    run ip -4 rule add priority "$RULE_PRIORITY" from "$SOURCE_IP/32" lookup "$TABLE_ID"
fi

# Request invalidation of cached IPv4 routing state
run ip -4 route flush cache

# Reached only if all required commands succeeded. No automatic rollback.
exit 0

The final command requests a flush of cached IPv4 routing state after the routing changes. It doesn’t load your rules or routes; the preceding commands have already made those changes.

Linux removed the old IPv4 route cache in kernel 3.6, so older explanations of this step can be misleading. Don’t assume a manual cache flush is required for every routing change. Its relevance should be checked against the kernel and networking tools on your server.

Save the file.

Testing the Scripts

Once you’ve saved both scripts, make sure root owns them and set their permissions. Run these commands from a root shell:

chown root:root /etc/iptables-script.sh /etc/routing-script.sh
chmod 755 /etc/iptables-script.sh /etc/routing-script.sh

Check both scripts for Bash syntax errors before running them:

bash -n /etc/iptables-script.sh
bash -n /etc/routing-script.sh

Fix any reported errors before proceeding. Passing these checks doesn’t tell you whether the rules and routes are correct.

Once you’ve completed the configuration, reviewed both scripts, and confirmed your recovery access, execute the firewall script using its full path:

/etc/iptables-script.sh

Inspect the firewall rules and confirm that it completed successfully. Stop and investigate if it failed. Once the required interface and source address are configured, test the routing script separately:

/etc/routing-script.sh

Running scripts directly doesn’t enforce their service dependencies. During these manual tests, you’re responsible for checking that the firewall succeeded before proceeding. Don’t run a script manually while its service or another instance is changing the same configuration.

Check what changed. Inspect the firewall tables and chains your rules use, the routing policy, and your dedicated routing table. Then test the traffic the configuration is intended to handle.

These read-only examples illustrate configuration inspection. Replace custom-table-name with your numeric table ID (or its mapped name), and choose the firewall tables and chains your own rules use.

iptables -t nat -L -v -n --line-numbers
iptables -t mangle -L OUTPUT -v -n --line-numbers
ip rule show
ip route show table custom-table-name

If you’re administering the server remotely, open a new administrative connection as well. An existing connection that stays open doesn’t prove that a new one will succeed.

Finally, repeat the test to confirm that another run doesn’t add duplicate entries. Test failure handling in an isolated environment where an intentional failure won’t interrupt access to your server.

systemd and the Start-Up Process

Once you’ve tested your scripts, it’s time to decide how to run them at startup. You don’t need systemd to perform the manual tests in this article, but the custom service method in the next article uses it.

The examples now use two startup stages. datahacker-firewall.service runs /etc/iptables-script.sh before normal network configuration. datahacker-routing.service runs /etc/routing-script.sh after network setup and requires the firewall service to have started successfully. Saving your iptables rules alone doesn’t preserve the routing script’s changes.

That ordering gives each script the conditions it needs. The Persistence article now demonstrates NetworkManager with a drop-in that requires successful firewall activation before NetworkManager.service can start. This applies to startup through that service, not to networking already configured or continuous verification of firewall rules. Validate the dependency and console recovery on your platform.

For the next step, see Persistence: Making iptables Changes Stick. Use the same script paths, configuration values, and failure handling you’ve tested here when adapting its startup method.

After enabling automatic startup, reboot with your recovery access available and repeat the configuration and connectivity checks. A successful service status doesn’t prove that the network behaves as intended. Also remember that stopping the service doesn’t automatically remove the rules or routes its scripts installed.

Download the Example Files

These are the same examples shown above. Review and configure them before use.