Linux – Iptables: how to easily group rules in chain

firewalliptableslinux

I have some netfilter rules like this:

iptables -I INPUT -j NFQUEUE -p udp --dport 4444
iptables -t mangle -I INPUT -j MARK --set-mark 100 -p udp --dport 4444
iptables -I OUTPUT -j NFQUEUE -p udp --sport 4444
iptables -t mangle -I OUTPUT -j MARK --set-mark 200 -p udp --sport 4444

I need a simple way to group this rules, aim to delete them all together, like this

iptables -N MYCHAIN

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

# Fast deleting
iptables -F MYCHAIN 
iptables -X MYCHAIN 

But it doesn't works, surely I have to connect default chain with MYCHAIN, but I don't figure how. Are there better or simpler solutions?

Best Answer

Your chain is in the filter table (since you did not specify a table when it was created, it ends up there by default), but you are trying to reference it from the mangle table, where it does not exist.

You would need to specify the correct table, like this:

iptables -t mangle -N MYCHAIN

In addition, in order to use the NFQUEUE target, you need to have the nfnetlink_queue kernel module loaded. The MARK target needs to be set in the PREROUTING chain of the mangle table. In your example above it is set in the INPUT chain.

So,to summarize, in order to make this work, you would probably need to do something like this:

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

And then reference this in the relevant tables, like this:

iptables -t mangle -I PREROUTING -j MYCHAIN

The flushing and deleting of the chain should not happen in the same script file, since it effectively eliminates any possibility of the rules ever getting executed.