Daily Shaarli

All links of one day in a single page.

January 28, 2024

Note: [nftables] How to create a ban list

Note (Français/French) : cet article est une aide mémoire sur l’utilisation de nftables nft, toutefois par habitude je l’ai rédigé en anglais, je m’en suis rendu compte un peu tard, juste avant publication pour quelque chose qui allait être en privé.

Note: this article is just a reminder how to use some nftables instructions.

Use option --handle/-a for displaying handles, which are required for deleting or for insertion for examples.

Create chain, named banned for example, but don’t use hook and priority:

nft create chain inet filter banned

Before it can be inserted, look for the handle to insert before, for example in the main chain INPUT from the table filter from the inet (IPv4 + IPv6) family:

nft --handle list chain inet filter INPUT

Note: it is possible to look through the whole table with this command nft --handle list table inet filter, but then all its chains are also displayed.

Add a jump statement to this newly created chain with the handle previously acquired from above command (replace "${HANDLE}"):
Notes:

  • this command adds a comment, it is only to display with list actions;
  • the double quotes are required for multiple worded comment, so when invoking nft, use single quotes or escape characters.
nft insert rule inet filter INPUT handle "${HANDLE}" jump banned comment '"lookup on the banned list"'

Now there is a jump statement to this newly chain, however the later is empty after creation.
Here how to add an IP address, either IPv4 or IPv6, or even a range, in this list, with a drop action:
Note: so see a number of packets, the counter statement is added

nft add rule inet filter banned ip saddr "${IP_ADDR_OR_RANGE}" counter drop

Same than previously, here how to display banned IP addresses, with their dedicated counters:

nft --handle list chain inet filter banned

It is also possible to allow an IP address, just replace the drop action by accept; however, because computation is done once a rule is matching, it is almost always better to insert a rule, nft insert rule […] instead of nft add rule […], so it appears at the top of the target chain:

nft insert rule inet filter banned ip saddr "${IP_TO_ALLOW}" counter accept