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 tablechain with
nft -fand flush it everytime also does not work and throws an errorbecause as stated here:
#!/usr/sbin/nft -f
add table inet filter2
add chain inet filter2 input
flush chain inet filter2 input
table inet filter2 {
chain input { # ERROR: Could not process rule: Operation not supported
type filter hook input priority -1; policy accept; # Is this even correct?
tcp dport { 4848 } ct state new,established counter accept
}
}
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.