2

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 using nft -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.

2
  • If you're always adding the same kind of rule there are ways to solve this without a complex method. If each added rule can be completely different that's an other thing. So could you describe a bit more the use case?
    – A.B
    Dec 23, 2021 at 16:04
  • 1
    It is always the same rule that needs to be added.
    – adroste
    Dec 25, 2021 at 13:44

1 Answer 1

0

It will be easier to manage it using sets:

table inet filter {
    set myport_tcp {
        type inet_service
        elements = { 4848 }
    }   

    chain input {
        type filter hook input priority 0; policy drop;
        # existing rules
        tcp dport @myport_tcp ct state new,established counter accept
        # more existing rules
    }
}

You can empty the set by:

nft flush set inet filter myport_tcp 

And you can add a new port to the set by:

nft add element inet filter myport_tcp elements = { 4949 }

Or add a multiple ports to the set by:

nft add element inet filter myport_tcp elements = { 14949, 9494 }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .