I have a utility that needs a free tcp port. As I don't want to alter existing configuration files I need to be able to dynamically add a rule to nftables.
There is an inet table called filter with input rules:
table inet filter {
chain input {
type filter hook input priority 0; policy drop;
# existing rules
}
}
Adding a rule to it is easy, e.g.:
nft add rule inet filter input tcp dport { 4848 } ct state new,established counter accept
The problem here is on how to do it in an idempotent way?
- If I run the same command twice, two identical rules are generated.
nft delete rule inet filter input handle ##
requires a handle number that changes and usingnft -n -a list ruleset | grep ...
to parse the handle number feels wrong- Adding a new chain with
nft -f
and flush it everytime also does not work because as stated here:
It is not possible for one chain to provide broader access (in the form of accept rules) than that provided by a chain with a reject (or drop) rule.