I have a script which is handling iptables / nftables. It detects if nft or iptables command should be used (yeah, it could run in old machines without nft). The script is saving the current status, then it cleans current rules and does some modifications while running and at the end it restores the original state. I have two different questions (the easy and the harder).
First question, cleaning, saving and restoring
The first one (the easy) is just to corroborate that my approach is ok regarding cleaning, saving and restoring the rules for both environments (nft and iptables). Next table is my approach. Is it correct? can be improved in less commands?
IPTABLES
Save
iptables-save > file
Delete
iptables -F
iptables -t nat -F
iptables -t mangle -F
iptables -t raw -F
iptables -t security -F
iptables -X
iptables -t nat -X
iptables -t mangle -X
iptables -t raw -X
iptables -t security -X
Restore
iptables-restore < file
NFT
Save
nft list ruleset > file
Delete
nft flush ruleset
Restore
nft -f file
Second question, modify/delete only my own rules
The second question (the hard one) is that the script needs to create some rules with some kind of “mark” because different instances of the script could run in parallel and each one will have its own rules. It is already controlled that the first one is saving the original rules and the last exiting is restoring them. So each instance should be able to handle just its own rules. The approach I did is to create rules setting a comment with the number of the instance on it. This way:
IPTABLES
iptables ...... -m comment --comment "instance1"
NFT
nft ....... comment "instance1"
After setting them this way (using comments on rules), if one of the script instances ends its work, it should delete only its own rules and this is the part I don’t have clear how to do in an “elegant” way. My approach could be to list them all filtering (grep/awk) by the instance number to delete one by one (getting the handle number in the case of nft). Something like this:
IPTABLES
iptables -L | grep "instance1"
#Then using bash to loop to do on each one this:
iptables -D ......
#Then repeat for each table (nat, mangle, raw, security)... is not a way to list them all?
NFT
nft -a list ruleset | grep "instance1"
#Then using bash to loop and maybe awk to get the handle number to do on each one this:
nft delete rule <family_type> <table_name> handle <handle_number>
Better or more elegant ideas?