`set_iptables` creates duplicate NAT rules when executed multiple times
Description
The set_iptables command does not check whether the REDSOCKS chain or its rules already exist.
The script currently contains:
iptables -t nat -N REDSOCKSfollowed by multiple iptables -t nat -A ... commands.
Because the script does not use set -e or check the return status of each command, running set_iptables more than once can result in:
iptables -N REDSOCKSfailing because the chain already exists.- The subsequent
-Acommands still executing. - Duplicate rules being appended to the existing
REDSOCKSchain. - Duplicate
PREROUTINGrules being added.
The script itself currently has the comment:
# TODO: check if rule existSteps to reproduce
On a Linux/OpenWrt system with iptables:
./start set_iptables
./start set_iptablesThen inspect the NAT table:
iptables -t nat -L REDSOCKS --line-numbers
iptables -t nat -L PREROUTING --line-numbersThe second execution can leave duplicate rules.
Expected behavior
Running:
./start set_iptablesmultiple times should be idempotent: existing chains/rules should be detected and not added again.
Suggested fix
Before creating the chain/rules, check whether they already exist, or make set_iptables idempotent by deleting/recreating the managed rules safely.
For example, the script could check:
iptables -t nat -L REDSOCKS >/dev/null 2>&1 || \
iptables -t nat -N REDSOCKSand similarly check the individual rules before adding them.
The cleanup operation should also remain safe when the rules/chain do not exist.
Source: XX-net/XX-Net