Search This Blog

Monday, August 31, 2026

group iptables rules in chain

When managing multiple firewall rules for a specific application, service, or policy, adding them directly to default chains (like INPUT, FORWARD, or PREROUTING) makes bulk updates and cleanups difficult. If you need to remove or disable that policy later, you would normally have to delete every single rule one by one.

The cleanest solution in iptables is to create a custom user-defined chain. By grouping related rules inside their own chain and linking that chain to a default table, you can enable, disable, or flush all associated rules in a single command.


The Problem: Cluttered Default Chains

Consider applying several packet-marking or filtering rules for a specific service across different hooks:

iptables -t mangle -A PREROUTING -p udp --dport 4444 -j MARK --set-mark 100
iptables -t mangle -A INPUT -p udp --dport 4444 -j MARK --set-mark 100
iptables -t mangle -A OUTPUT -p udp --dport 4444 -j MARK --set-mark 200

Deleting these later requires referencing each specific rule line or rule number individually, which is tedious and error-prone in production environments.


The Solution: Group Rules into a Custom Chain

Step 1: Create the Custom Chain in the Target Table

Create a custom chain (e.g., MYCHAIN). Remember that user-defined chains exist only within the specific table where they are created (e.g., mangle, filter, or nat):

# Create MYCHAIN inside the mangle table
iptables -t mangle -N MYCHAIN

Step 2: Add Rules into Your Custom Chain

Populate your chain with the relevant match criteria and actions:

iptables -t mangle -A MYCHAIN -p udp --dport 4444 -j MARK --set-mark 100
iptables -t mangle -A MYCHAIN -p udp --sport 4444 -j MARK --set-mark 200

Step 3: Link Your Custom Chain to Built-in Chains

To make the rules active, direct traffic from the standard hooks (such as PREROUTING or INPUT) into your custom chain:

iptables -t mangle -A PREROUTING -j MYCHAIN
iptables -t mangle -A OUTPUT -j MYCHAIN

How to Easily Manage and Delete the Group

When you need to clear or completely remove the rule group, the workflow is clean and immediate:

  1. Unlink the Chain: Remove the single jump rule from the built-in chains:
    iptables -t mangle -D PREROUTING -j MYCHAIN
    iptables -t mangle -D OUTPUT -j MYCHAIN
  2. Flush the Rules: Clear all rules inside your custom chain in one step:
    iptables -t mangle -F MYCHAIN
  3. Delete the Empty Chain: Remove the custom chain definition:
    iptables -t mangle -X MYCHAIN

No comments:

Post a Comment