NFT(8)

๐Ÿฆ‹ NFT(8): nft โ€” the girliepop guide ๐Ÿฆ‹

๐Ÿ’– NAME ๐Ÿ’–

nft โ€” Administration tool of the nftables framework for packet filtering and classification. Thatโ€™s the whole vibe, bestie.

โœจ SYNOPSIS โœจ

nft [ -nNscaeSupyjtT ] [ -I directory ] [ -f filename | -i | cmd ...]
nft -h
nft -v

๐ŸŒธ DESCRIPTION ๐ŸŒธ

Okay so nft is literally the command line tool you use to set up, maintain and inspect packet filtering and classification rules in the Linux kernel, inside the nftables framework. Iconic.

The Linux kernel subsystem is known as nf_tables, and โ€˜nfโ€™ stands for Netfilter. iykyk ๐Ÿ’…

๐ŸŽ€ OPTIONS ๐ŸŽ€

The command accepts several different options which are documented here in groups for better understanding of their meaning. You can get information about options by running nft --help. go off, help flag ๐Ÿซถ

๐ŸŒˆ General options ๐ŸŒˆ

  • -h, --help โ€” Show help message and all options.
  • -v, --version โ€” Show version.
  • -V โ€” Show long version information, including compile-time configuration.

๐Ÿ“ Ruleset input handling options ๐Ÿ“

These are the options that specify how to load rulesets:

  • -f, --file filename โ€” Read input from filename. If filename is -, read from stdin. The directory path to this file is inserted at the beginning the list of directories to be searched for included files (see -I/--includepath).
  • -D, --define name=value โ€” Define a variable. You can only combine this option with -f.
  • -i, --interactive โ€” Read input from an interactive readline CLI. You can use quit to exit, or use the EOF marker, normally this is CTRL-D.
  • -I, --includepath directory โ€” Add the directory directory to the list of directories to be searched for included files. This option may be specified multiple times.
  • -c, --check โ€” Check commands validity without actually applying the changes.
  • -o, --optimize โ€” Optimize your ruleset. You can combine this option with -c to inspect the proposed optimizations.

โญ Ruleset list output formatting โญ

These modify the output of the list ruleset command:

  • -a, --handle โ€” Show object handles in output.
  • -s, --stateless โ€” Omit stateful information of rules and stateful objects.
  • -t, --terse โ€” Omit contents of sets from output.
  • -S, --service โ€” Translate ports to service names as defined by /etc/services.
  • -N, --reversedns โ€” Translate IP address to names via reverse DNS lookup. This may slow down your listing since it generates network traffic.
  • -u, --guid โ€” Translate numeric UID/GID to names as defined by /etc/passwd and /etc/group.
  • -n, --numeric โ€” Print fully numerical output.
  • -y, --numeric-priority โ€” Display base chain priority numerically.
  • -p, --numeric-protocol โ€” Display layer 4 protocol numerically.
  • -T, --numeric-time โ€” Show time, day and hour values in numeric format.

๐Ÿ’œ Command output formatting ๐Ÿ’œ

  • -e, --echo โ€” When inserting items into the ruleset using add, insert or replace commands, print notifications just like nft monitor.
  • -j, --json โ€” Format output in JSON. See libnftables-json(5) for a schema description.
  • -d, --debug level โ€” Enable debugging output. The debug level can be any of scanner, parser, eval, netlink, mnl, proto-ctx, segtree, all. You can combine more than one by separating by the , symbol, for example -d eval,mnl.

๐Ÿงš INPUT FILE FORMATS ๐Ÿงš

๐ŸŒธ LEXICAL CONVENTIONS ๐ŸŒธ

Input is parsed line-wise. When the last character of a line, just before the newline character, is a non-quoted backslash (\), the next line is treated as a continuation. Multiple commands on the same line can be separated using a semicolon (;).

A hash sign (#) begins a comment. All following characters on the same line are ignored. love a clean comment moment ๐Ÿ’…

Identifiers begin with an alphabetic character (a-z,A-Z), followed by zero or more alphanumeric characters (a-z,A-Z,0-9) and the characters slash (/), backslash (\), underscore (_) and dot (.). Identifiers using different characters or clashing with a keyword need to be enclosed in double quotes (").

๐Ÿฆ‹ INCLUDE FILES ๐Ÿฆ‹

include filename

Other files can be included by using the include statement. The directories to be searched for include files can be specified using the -I/--includepath option. You can override this behaviour either by prepending ./ to your path to force inclusion of files located in the current working directory (i.e. relative path) or / for file location expressed as an absolute path.

If -I/--includepath is not specified, then nft relies on the default directory that is specified at compile time. You can retrieve this default directory via the -h/--help option.

Include statements support the usual shell wildcard symbols (,?,[]). Having no matches for an include statement is not an error, if wildcard symbols are used in the include statement. This allows having potentially empty include directories for statements like include "/etc/firewall/rules/". The wildcard matches are loaded in the collation order of the C locale. Files beginning with dot (.) are not matched by include statements.

๐Ÿ“ SYMBOLIC VARIABLES ๐Ÿ“

define variable = expr
undefine variable
redefine variable = expr
$variable

Symbolic variables can be defined using the define statement. Variable references are expressions and can be used to initialize other variables. The scope of a definition is the current block and all blocks contained within. Symbolic variables can be undefined using the undefine statement, and modified using the redefine statement.

Using symbolic variables:

define int_if1 = eth0
define int_if2 = eth1
define int_ifs = { $int_if1, $int_if2 }
redefine int_if2 = wlan0
undefine int_if2

filter input iif $int_ifs accept

โœจ ADDRESS FAMILIES โœจ

okay so address families are literally the whole vibe-check of what kind of packets you're dealing with ๐Ÿฆ‹ for every family, the kernel has these little things called hooks sitting at specific stages of the packet-processing path, and they only fire up nftables if you actually have rules for those hooks. no rules = no vibes = nothing happens, iykyk.

  • ip โ€” the IPv4 address family ๐Ÿ’œ
  • ip6 โ€” the IPv6 address family ๐Ÿ’œ
  • inet โ€” the Internet address family, aka IPv4/IPv6 both at once ๐ŸŒˆ
  • arp โ€” the ARP address family, handles IPv4 ARP packets ๐ŸŽ€
  • bridge โ€” the bridge address family, handles packets that traverse a bridge device ๐ŸŒ‰
  • netdev โ€” the Netdev address family, handles packets on ingress and egress ๐Ÿšช

and bestie, here's the thing โ€” every nftables object lives in an address-family-specific namespace, so every identifier comes with an address family attached. if you specify an identifier with no address family? it just defaults to the ip family. no cap ๐Ÿ‘‘


๐ŸŒธ IPV4/IPV6/INET ADDRESS FAMILIES ๐ŸŒธ

The IPv4/IPv6/Inet families handle IPv4 packets, IPv6 packets, or literally both. They've got five hooks at different packet-processing stages in the network stack (and then there's a sixth one hanging out in the table below, ingress, which is inet-only โ€” keep reading, it's giving special guest energy โœจ).

Table 1. IPv4/IPv6/Inet address family hooks

  • prerouting โ€” all packets entering the system get processed by the prerouting hook. it's invoked before the routing process, and it's used for early filtering or for changing packet attributes that affect routing ๐ŸŽ€
  • input โ€” packets delivered to the local system get processed by the input hook ๐Ÿซถ
  • forward โ€” packets forwarded to a different host get processed by the forward hook ๐Ÿ“จ
  • output โ€” packets sent by local processes get processed by the output hook ๐Ÿ’Œ
  • postrouting โ€” all packets leaving the system get processed by the postrouting hook ๐Ÿš€
  • ingress โ€” all packets entering the system get processed by this hook. it's invoked before layer 3 protocol handlers, hence before the prerouting hook, and it can be used for filtering and policing ๐Ÿ‘ฎโ€โ™€๏ธ
heads up bestie: ingress is only available for the Inet family (since Linux kernel 5.10) ๐Ÿ’€ don't come for me, that's just what the kernel says.

๐Ÿฆ‹ ARP ADDRESS FAMILY ๐Ÿฆ‹

The ARP address family handles ARP packets received and sent by the system. it's commonly used to mangle ARP packets for clustering, which honestly? iconic use case ๐Ÿ’…

Table 2. ARP address family hooks

  • input โ€” packets delivered to the local system get processed by the input hook ๐Ÿ’–
  • output โ€” packets send by the local system get processed by the output hook ๐Ÿ’–

(and yes, the original really does say "send" there โ€” we're keeping it fr fr, character for character ๐ŸŽ€)


๐ŸŒ‰ BRIDGE ADDRESS FAMILY ๐ŸŒ‰

The bridge address family handles Ethernet packets traversing bridge devices. that's it, that's the family.

the list of supported hooks is identical to the IPv4/IPv6/Inet address families above โญ so scroll back up if you need a refresher, bestie, we're not retyping the whole thing.


๐Ÿšช NETDEV ADDRESS FAMILY ๐Ÿšช

The Netdev address family handles packets from the device ingress and egress path. this family lets you filter packets of any ethertype, like ARP, VLAN 802.1q, VLAN 802.1ad (Q-in-Q), and also plain old IPv4 and IPv6 packets. versatile queen ๐Ÿ‘‘

Table 3. Netdev address family hooks

  • ingress โ€” all packets entering the system get processed by this hook. it's invoked after the network taps (ie. tcpdump), right after tc ingress and before layer 3 protocol handlers. it can be used for early filtering and policing ๐Ÿ•ต๏ธโ€โ™€๏ธ
  • egress โ€” all packets leaving the system get processed by this hook. it's invoked after layer 3 protocol handlers and before tc egress. it can be used for late filtering and policing ๐Ÿšฆ

Tunneled packets (such as vxlan) are processed by netdev family hooks both in decapsulated and encapsulated (tunneled) form. so a packet can be filtered on the overlay network and on the underlying network. double the slay, double the filtering ๐ŸŒ€โœจ

Note that the order of netfilter and tc is mirrored on ingress versus egress โ€” this ensures symmetry for NAT and other packet mangling ๐Ÿชž

and now the important caveat, listen up ๐Ÿ™ˆ:

Ingress packets that are redirected out some other interface are only processed by netfilter on egress if they have passed through netfilter ingress processing before. So: ingress packets redirected by tc are not subjected to netfilter. But they are if they're redirected by netfilter on ingress.

conceptually, tc and netfilter can be thought of as layers, with netfilter layered above tc: if the packet hasn't been passed up from the tc layer to the netfilter layer, it's not subjected to netfilter on egress. simple as that, bestie ๐Ÿ“


๐Ÿ‘‘ RULESET ๐Ÿ‘‘

{list | flush} ruleset [family]

The ruleset keyword is used to identify the whole set of tables, chains, etc. currently chilling in the kernel โ€” like the entire collection, all of it, the whole wardrobe ๐Ÿ’…

The following ruleset commands exist:

  • list โ€” print the ruleset in human-readable format ๐Ÿ“–
  • flush โ€” clear the whole ruleset. Note that, unlike iptables, this will remove all tables and whatever they contain, effectively leading to an empty ruleset โ€” no packet filtering will happen anymore, so the kernel accepts any valid packet it receives ๐Ÿ’€๐Ÿ”ฅ
okay so that flush thing is genuinely dramatic โ€” you're wiping the ENTIRE ruleset, not just one table. the kernel will just vibe there accepting literally any valid packet it gets. be so careful with this one ๐Ÿ™ˆ

It's possible to limit list and flush to a specific address family only ๐ŸŽ€ for a list of valid family names, see the section called "ADDRESS FAMILIES" above (yes, that one, the big one with all the tables โฌ†๏ธ).

and here's a genuinely gorgeous design choice: by design, the list ruleset command output may be used as input to nft -f โœจ effectively, this is the nft-equivalent of iptables-save and iptables-restore. save it, restore it, slay it, periodt ๐Ÿ’–

โœจ TABLES โœจ

{add | create} table [family] table [{ [comment comment ;] [flags flags ;] }]
{delete | destroy | list | flush} table [family] table
list tables [family]
delete table [family] handle handle
destroy table [family] handle handle

Okay so tables are the little containers for chains, sets, and stateful objects, bestie. Every table is identified by its address family and its name. The address family has to be one of ip, ip6, inet, arp, bridge, or netdev. The inet family is a dummy family used to create hybrid IPv4/IPv6 tables โ€” iconic behavior tbh. The meta expression nfproto keyword can be used to test which family (ipv4 or ipv6) context the packet is being processed in. When no address family is specified, ip is used by default. The only difference between add and create is that add will not return an error if the specified table already exists, while create will return an error. Periodt.

๐ŸŽ€ Table 4. Table flags

  • dormant โ€” table is not evaluated any more (base chains are unregistered).
  • owner โ€” table is owned by the creating process.
  • persist โ€” table shall outlive the owning process.

Creating a table with flag owner excludes other processes from manipulating it or its contents. By default, it will be removed when the process exits. Setting flag persist will prevent this, and the resulting orphaned table will accept a new owner, e.g. a restarting daemon maintaining the table. Thatโ€™s the whole lore, no cap.

โœจ Add, change, delete a table โœจ

# start nft in interactive mode
nft --interactive

# create a new table.
create table inet mytable

# add a new base chain: get input packets
add chain inet mytable myin { type filter hook input priority filter; }

# add a single counter to the chain
add rule inet mytable myin counter

# disable the table temporarily -- rules are not evaluated anymore
add table inet mytable { flags dormant; }

# make table active again:
add table inet mytable
  • add โ€” Add a new table for the given family with the given name.
  • delete โ€” Delete the specified table.
  • destroy โ€” Delete the specified table, it does not fail if it does not exist.
  • list โ€” List all chains and rules of the specified table.
  • flush โ€” Flush all chains and rules of the specified table.

๐Ÿฆ‹ CHAINS ๐Ÿฆ‹

{add | create} chain [family] table chain [{ type type hook hook [DEVICE] priority priority ; [policy policy ;] [comment comment ;] }]
{delete | destroy | list | flush} chain [family] table chain
list chains [family]
delete chain [family] table handle handle
destroy chain [family] table handle handle
rename chain [family] table chain newname

DEVICE := {device DEVICE_NAME | devices = { DEVICE_LIST }}
DEVICE_LIST := DEVICE_NAME [, DEVICE_LIST]
DEVICE_NAME := string | string*

Chains are containers for rules, bestie. They come in two kinds: base chains and regular chains. A base chain is an entry point for packets from the networking stack. A regular chain may be used as a jump target and is used for better rule organization. Regular chains can be anonymous โ€” see VERDICT STATEMENT examples for details. iykyk ๐Ÿ’…

  • add โ€” Add a new chain in the specified table. When a hook and priority value are specified, the chain is created as a base chain and hooked up to the networking stack.
  • create โ€” Similar to the add command, but returns an error if the chain already exists.
  • delete โ€” Delete the specified chain. The chain must not contain any rules or be used as jump target.
  • destroy โ€” Delete the specified chain, it does not fail if it does not exist. The chain must not contain any rules or be used as jump target.
  • rename โ€” Rename the specified chain.
  • list โ€” List all rules of the specified chain.
  • flush โ€” Flush all rules of the specified chain.

For base chains, type, hook, and priority parameters are mandatory. Mandatory, babes. No skipping.

๐Ÿ’ซ Table 5. Supported chain types

  • filter โ€” Families: all; Hooks: all. Standard chain type to use in doubt.
  • nat โ€” Families: ip, ip6, inet; Hooks: prerouting, input, output, postrouting. Chains of this type perform Native Address Translation based on conntrack entries. Only the first packet of a connection actually traverses this chain - its rules usually define details of the created conntrack entry (NAT statements for instance).
  • route โ€” Families: ip, ip6, inet; Hooks: output. If a packet has traversed a chain of this type and is about to be accepted, a new route lookup is performed if relevant parts of the IP header have changed. This allows one to e.g. implement policy routing selectors in nftables.

Apart from the special cases illustrated above (e.g. nat type not supporting forward hook or route type only supporting output hook), there are three further quirks worth noticing:

  • The netdev family supports merely two combinations, namely filter type with ingress hook and filter type with egress hook. Base chains in this family also require the DEVICE parameter to be present since they exist per interface only.
  • The arp family supports only the input and output hooks, both in chains of type filter.
  • The inet family also supports the ingress hook (since Linux kernel 5.10), to filter IPv4 and IPv6 packet at the same location as the netdev ingress hook. This inet hook allows you to share sets and maps between the usual prerouting, input, forward, output, postrouting and this ingress hook.

The device parameter accepts a network interface name as a string, and is required when adding a base chain that filters traffic on the ingress or egress hooks. Any ingress or egress chains will only filter traffic from the interface specified in the device parameter. The same base chain may be used for multiple devices by using the devices parameter instead.

With newer kernels there is also basic support for wildcards in DEVICE_NAME by specifying an asterisk suffix. The chain will apply to all interfaces matching the given prefix. Use the list hooks command to see the current status. โœจ slay that interface matching โœจ

Okay so the priority parameter? It takes a signed integer or one of the standard priority names, and honestly it's just the order in which chains that share the same hook value get traversed โ€” and that's regardless of which table they belong to, bestie. It's ascending, okay: for each hook, chains with lower priority values get evaluated before chains with higher ones. And if two chains have the exact same priority? The ordering is undefined โ€” total coin-flip energy, don't build your setup on it. ๐Ÿช™

With nat type chains there's a lower excluding limit of -200 for priority values, because conntrack hooks at this priority and NAT requires it. So like, respect the floor, fr fr.

The standard priority values can be swapped for easily memorizable names. Not every name makes sense in every family with every hook (peep the compatibility matrices below ๐Ÿ‘€) but their numerical value can still be used for prioritizing chains โ€” the number is the number.

These names and values are defined and made available based on what priorities are used by xtables when registering their default chains.

Most of the families use the same values, but bridge uses different ones from the others. Here are the tables with the values and compatibility:

Table 6. Standard priority names, family and hook compatibility matrix

  • raw โ€” value -300 โ€” families: ip, ip6, inet โ€” hooks: all
  • mangle โ€” value -150 โ€” families: ip, ip6, inet โ€” hooks: all
  • dstnat โ€” value -100 โ€” families: ip, ip6, inet โ€” hooks: prerouting
  • filter โ€” value 0 โ€” families: ip, ip6, inet, arp, netdev โ€” hooks: all
  • security โ€” value 50 โ€” families: ip, ip6, inet โ€” hooks: all
  • srcnat โ€” value 100 โ€” families: ip, ip6, inet โ€” hooks: postrouting

Table 7. Standard priority names and hook compatibility for the bridge family

  • dstnat โ€” value -300 โ€” hooks: prerouting
  • filter โ€” value -200 โ€” hooks: all
  • out โ€” value 100 โ€” hooks: output
  • srcnat โ€” value 300 โ€” hooks: postrouting

โœจ And here's a cute little trick: basic arithmetic expressions (addition and subtraction) work with these standard names too, so relative prioritizing is lowkey effortless โ€” e.g. mangle - 5 stands for -155. Values will also be printed like this until the value is not further than 10 from the standard value. So close to a standard name = you get the name back. ๐Ÿ’…

Base chains also let you set the chain's policy, i.e. what happens to packets that weren't explicitly accepted or refused inside the contained rules. Supported policy values are accept (which is the default) or drop.


๐Ÿ“œ RULES ๐Ÿ“œ

{add | insert} rule [family] table chain [handle handle | index index] statement ... [comment comment]
replace rule [family] table chain handle handle statement ... [comment comment]
{delete | reset} rule [family] table chain handle handle
destroy rule [family] table chain handle handle
reset rules [family] [table [chain]]

Rules get added to chains in the given table. If you don't specify the family, the ip family is used. Rules are built from two kinds of components according to a set of grammatical rules: expressions and statements.

The add and insert commands support an optional location specifier, which is either a handle or the index (starting at zero) of an existing rule. Internally, rule locations are always identified by handle, and the translation from index happens in userspace. This has two potential implications in case a concurrent ruleset change happens after the translation was done:

  • The effective rule index might change if a rule was inserted or deleted before the referred one.
  • If the referred rule was deleted, the command is rejected by the kernel just as if an invalid handle was given. ๐Ÿ’€

A comment is a single word or a double-quoted (") multi-word string which can be used to make notes regarding the actual rule.

Note: If you use bash for adding rules, you have to escape the quotation marks, e.g. \"enable ssh for servers\". Don't forget or bash will eat your comment and leave you confused. ๐Ÿ˜ญ
  • add โ€” Add a new rule described by the list of statements. The rule is appended to the given chain unless a location is specified, in which case the rule is inserted after the specified rule.
  • insert โ€” Same as add except the rule is inserted at the beginning of the chain or before the specified rule.
  • replace โ€” Similar to add, but the rule replaces the specified rule.
  • delete โ€” Delete the specified rule.
  • destroy โ€” Delete the specified rule, and it does not fail if it does not exist. No-drama deletion, we stan. ๐Ÿซถ
  • reset โ€” Reset rule-contained state, e.g. counter and quota statement values.

๐ŸŒธ Adding a rule to the ip table output chain:

nft add rule filter output ip daddr 192.168.0.0/24 accept # 'ip filter' is assumed
# same command, slightly more verbose
nft add rule ip filter output ip daddr 192.168.0.0/24 accept

๐Ÿฆ‹ Deleting a rule from the inet table:

# nft -a list ruleset
table inet filter {
        chain input {
                type filter hook input priority filter; policy accept;
                ct state established,related accept # handle 4
                ip saddr 10.1.1.1 tcp dport ssh accept # handle 5
          ...
# delete the rule with handle 5
nft delete rule inet filter input handle 5

๐ŸŒˆ OVERALL EVALUATION OF THE RULESET ๐ŸŒˆ

okay bestie, this is the โœจbig pictureโœจ of how the ruleset actually gets evaluated. it's giving flow-chart energy, ngl.

  • ๐Ÿ’– even if a packet is accepted by the ruleset, it may still get yeeted by other means โ€” like, Linux generally ignores various ICMP types, and there are sysctl options such as net.ipv{4,6}.conf.*.forwarding or net.ipv4.conf.*.rp_filter. so "accepted" is not always "lived happily ever after", bestie ๐Ÿ˜ญ
  • ๐Ÿ’… tables are merely a concept of nftables to structure the ruleset. they are not relevant to the evaluation of the ruleset. periodt.
  • ๐Ÿฆ‹ packets traverse the network stack and at various hooks (peep the section called "ADDRESS FAMILIES" above for the lists of hooks per address family) they're evaluated by any base chains attached to these hooks.
  • ๐ŸŒธ base chains may call regular chains (via jump and goto). regular chains can call other regular chains. evaluation continues in the called chain. chains residing in a different table cannot be called. no cap, that's the rule.
  • โญ for each hook, the attached chains are evaluated in order of their priorities. chains with lower priority values are evaluated before those with higher ones. the order of chains with the same priority value is undefined โ€” so don't come crying to me when it's vibes-only ๐Ÿ’€
  • ๐Ÿ‘‘ an accept verdict (including an implicit one via the base chain's policy) ends the evaluation of the current base chain. it is not relevant if the accept verdict is issued in the base chain itself or in a regular chain called from the base chain. the packet advances to the next base chain. thus a packet is ultimately accepted if and only if no (matching) rule or base chain policy issues a drop verdict. all of this applies to verdict-like statements that imply accept, for example the NAT statements. so iconic of NAT to sneak in like that ๐Ÿซถ
  • ๐Ÿ”ฅ a drop verdict (including an implicit one via the base chain's policy) immediately ends the evaluation of the whole ruleset. no further chains of any hook are consulted. it is therefore not possible to have a drop verdict changed to an accept in a later chain. this also applies to other terminal statements that imply drop, for example reject. so if any base chain uses drop as its policy, the same base chain (or a regular chain directly or indirectly called by it) must contain at least one matching accept rule or the packet will be dropped. fr fr, this is the drama of the whole page ๐Ÿ’€
  • ๐ŸŒˆ given the semantics of accept/drop, and only with respect to the ultimate decision of whether a packet is accepted or dropped, the ordering of the various base chains per hook via their priorities matters only in so far as any of them modifies the packet or its meta data and that has an influence on the verdicts issued by the chains โ€” other than that, the ordering shouldn't matter (except for performance and other side effects). it also means short-circuiting the ultimate decision is only possible via drop verdicts (respectively verdict-like statements that imply drop, for example reject). main character energy: only drop gets to slam the door ๐Ÿ’…
  • ๐ŸŽ€ a jump verdict causes the current position to be stored in the call stack of chains and evaluation to continue at the beginning of the called regular chain. called chains must be from the same table and cannot be base chains. when the end of the called chain is reached, an implicit return verdict is issued. other verdicts (respectively verdict-like statements) are processed as described above and below. it remembers where it was โ€” unlike me after a 3-hour scroll session ๐Ÿ˜ญ
  • ๐Ÿฆ‹ a goto verdict is equal to jump except that the current position is not stored in the call stack of chains. no callback, no number, we're just gone โœจ
  • ๐Ÿ’œ a return verdict ends the evaluation of the current chain, pops the most recently added position from the call stack of chains, and causes evaluation to continue after that position. when there's no position to pop (which is the case when the current chain is either the base chain or a regular chain that was reached solely via goto verdicts) it ends the evaluation of the current base chain (and any regular chains called from it) using the base chain's policy as implicit verdict. pop off, literally ๐Ÿ“

๐Ÿงš examples for jump / goto / return ๐Ÿงš

these are the little scenarios, and honestly they eat:

  • base {jump}โ†’ regular-1 {jump}โ†’ regular-2 โ€” at the end of regular-2 or when a return is issued in that, evaluation continues after the jump position in regular-1. at the end of regular-1 or when a return is issued in that, evaluation continues after the jump position in base.
  • base {jump}โ†’ regular-1 {goto}โ†’ regular-2 โ€” at the end of regular-2 or when a return is issued in that, evaluation continues after the jump position in base.
  • base {jump}โ†’ regular-1 {jump}โ†’ regular-2 {goto}โ†’ regular-3 โ€” at the end of regular-3 or when a return is issued in that, evaluation continues after the jump position in regular-1. at the end of regular-1 or when a return is issued in that, evaluation continues after the jump position in base.
  • base {jump}โ†’ regular-1 {goto}โ†’ regular-2 {goto}โ†’ regular-3 โ€” at the end of regular-3 or when a return is issued in that, evaluation continues after the jump position in base.

  • ๐Ÿ’€ verdicts (that is: accept, drop, jump, goto, return and continue) as well as statements that imply a verdict (like reject or the NAT statements) also end the evaluation of any later statements in their respective rules (respectively cause an error when loading such rules). for example, in ... counter accept the counter statement is processed, but in ... accept counter it is not. this does not apply to the comment statement, which is always evaluated. the way comment is just always there for you ๐Ÿฅนโœจ

๐ŸŒธ SETS ๐ŸŒธ

okay bestie, so nftables is giving you two whole flavors of set concept, and they're lowkey different vibes โœจ

Anonymous sets are the sets with no specific name โ€” very mystery, very no-label. The set members are wrapped in curly braces, with commas separating the elements, right there in the rule where the set gets used. And once that rule is removed? The set is gone too. Poof. ๐Ÿ’จ They are not updatable โ€” like, once an anonymous set is declared it literally cannot be changed anymore, except by removing/altering the rule that uses the anonymous set. No cap.

Using anonymous sets to accept particular subnets and ports:

nft add rule filter input ip saddr { 10.0.0.0/8, 192.168.0.0/16 } tcp dport { 22, 443 } accept

Named sets are the sets that need to be defined first before they can be referenced in rules. The way this one is actually the main character: unlike anonymous sets, elements can be added to or removed from a named set at any time ๐Ÿ”ฅ Sets are referenced from rules using an @ prefixed to the set's name.

Using named sets to accept addresses and ports:

nft add rule filter input ip saddr @allowed_hosts tcp dport @allowed_ports accept

The sets allowed_hosts and allowed_ports need to be created first, bestie โ€” you can't just reference a set that doesn't exist yet, that's not how any of this works ๐Ÿ™ˆ The next section describes nft set syntax in more detail.

add set [family] table set { type type | typeof expression ; [flags flags ;] [timeout timeout ;] [gc-interval gc-interval ;] [elements = { element[, ...] } ;] [size size ;] [comment comment ;] [policy 'policy ;] [auto-merge ;] }
{delete | destroy | list | flush | reset } set [family] table set
list sets [family] [table]
delete set [family] table handle handle
{add | delete | destroy } element [family] table set { element[, ...] }

Sets are element containers of a user-defined data type, they are uniquely identified by a user-defined name and attached to tables. Their behaviour can be tuned with the flags that can be specified at set creation time ๐Ÿ‘‘

See Set and Map flags below for more details.

  • add โ€” Add a new set in the specified table. See the Set specification table below for more information about how to specify properties of a set.
  • delete โ€” Delete the specified set.
  • destroy โ€” Delete the specified set, it does not fail if it does not exist. (iconic forgiving behaviour tbh ๐Ÿซถ)
  • list โ€” Display the elements in the specified set.
  • flush โ€” Remove all elements from the specified set.
  • reset โ€” Reset state in all contained elements, e.g. counter and quota statement values.

๐ŸŽ€ Table 8. Set specifications ๐ŸŽ€

  • type โ€” data type of set elements. Type: string: ipv4_addr, ipv6_addr, ether_addr, inet_proto, inet_service, mark
  • typeof โ€” data type of set element. Type: expression to derive the data type from
  • flags โ€” set flags. Type: string: constant, dynamic, interval, timeout. Used to describe the set's properties.
  • timeout โ€” time an element stays in the set, mandatory if set is added to from the packet path (ruleset). Type: string, decimal followed by unit. Units are: d, h, m, s
  • gc-interval โ€” garbage collection interval, only available when timeout or flag timeout are active. Type: string, decimal followed by unit. Units are: d, h, m, s
  • elements โ€” elements contained by the set. Type: set data type
  • size โ€” maximum number of elements in the set, mandatory if set is added to from the packet path (ruleset). Type: unsigned integer (64 bit)
  • policy โ€” set policy. Type: string: performance [default], memory
  • auto-merge โ€” automatic merge of adjacent/overlapping set elements (only for interval sets)

The gc-interval doesn't affect element timeout, but it does affect memory reclaim ๐Ÿง โœจ A large set that rarely has elements that time out can use a higher (less frequent) garbage collection to save cpu time, whereas sets that see many updates with short-lived elements will benefit from a lower interval. Lower intervals ensure the set stays below its maximum size. Internally, a timed-out entry stays around until it is removed by the garbage collector, which also decrements the set's element count. This also means that it is possible to have a set that can not accept more elements, even if all elements timed out, if the gc-interval is set too large ๐Ÿ˜ญ (yes really, that's the vibe check and it failed)

The size defines the upper limit of the amount of elements that the set can support. Mandatory for sets that are added to from the ruleset with the add and update keywords. Providing the size keyword for sets that are only added to via nft add element allows for a more compact (memory conserving) set implementation selection, but it is not required ๐Ÿ’…

The optional policy keyword can be used to request a more memory-conserving set implementation ๐Ÿ“

auto-merge instructs the nftables frontend to merge adjacent and overlapping ranges. Example: When the set contains range 1.2.3.1-1.2.3.4, then adding element 1.2.3.2 has no effect. Adding 1.2.3.5 changes the existing range to cover 1.2.3.1-1.2.3.5. Without this flag, 1.2.3.2 can not be added and 1.2.3.5 is inserted as a new entry. Slay for tidy ranges ๐ŸŒˆ

Equality of a value with a set is given if the value matches exactly one value in the set (which for intervals means that it's contained in any of them). See the section called "BITMASK TYPE" for the subtle differences between syntactically similarly looking equality checks of sets and bitmasks ๐Ÿ‘€โœจ

๐Ÿ—บ๏ธ MAPS ๐Ÿ—บ๏ธ

okay bestie, maps are the whole โ€œstore data based on some specific key used as inputโ€ situation ๐Ÿ’… They are uniquely identified by a user-defined name and attached to tables. slay.

add map [family] table map { type type | typeof expression [flags flags ;] [elements = { element[, ...] } ;] [size size ;] [comment comment ;] [policy 'policy ;] }
{delete | destroy | list | flush | reset } map [family] table map
list maps [family] [table]
  • add โ€” Add a new map in the specified table. โœจ
  • delete โ€” Delete the specified map.
  • destroy โ€” Delete the specified map, it does not fail if it does not exist.
  • list โ€” Display the elements in the specified map.
  • flush โ€” Remove all elements from the specified map.
  • reset โ€” Reset state in all contained elements, e.g. counter and quota statement values.

Table 9. Map specifications โ€” the columns were Keyword, Description, Type, and hereโ€™s every single row ๐Ÿซถ

  • type โ€” data type of map elements. Type: string: ipv4_addr, ipv6_addr, ether_addr, inet_proto, inet_service, mark, counter, quota. Counter and quota canโ€™t be used as keys ๐Ÿ’€
  • typeof โ€” data type of set element. Type: expression to derive the data type from.
  • flags โ€” map flags. Type: string, same as set flags.
  • elements โ€” elements contained by the map. Type: map data type.
  • size โ€” maximum number of elements in the map. Type: unsigned integer (64 bit).
  • policy โ€” map policy. Type: string: performance [default], memory.

Users can specify the properties/features that the set/map must support. This allows the kernel to pick an optimal internal representation. If a required flag is missing, the ruleset might still work, as nftables will auto-enable features if it can infer this from the ruleset. This may not work for all cases, however, so it is recommended to specify all required features in the set/map definition manually. Also, some features are mutually exclusive. For example, it is not possible for a set to support intervals and insertion from the packet path. not me having to say โ€œmutually exclusiveโ€ but ok ๐Ÿ˜ญ

Table 10. Set and Map flags โ€” iconic little flag list, no cap:

  • constant โ€” Set contents will never change after creation.
  • dynamic โ€” Set must support updates from the packet path with the add, update or delete keywords.
  • interval โ€” Set must be able to store intervals (ranges). Cannot be combined with the dynamic flag.
  • timeout โ€” Set must support element timeouts (auto-removal of elements once they expire).

๐Ÿงฉ ELEMENTS ๐Ÿงฉ

{add | create | delete | destroy | get | reset } element [family] table set { ELEMENT[, ...] }

ELEMENT := key_expression OPTIONS [: value_expression]
OPTIONS := [timeout TIMESPEC] [expires TIMESPEC] [comment string]
TIMESPEC := [numd][numh][numm][num[s]]

Element-related commands allow one to change contents of named sets and maps. key_expression is typically a value matching the set type. value_expression is not allowed in sets but mandatory when adding to maps, where it matches the data part in its type definition. When deleting from maps, it may be specified but is optional as key_expression uniquely identifies the element. iykyk โœจ

create command is similar to add with the exception that none of the listed elements may already exist.

get command is useful to check if an element is contained in a set which may be non-trivial in very large and/or interval sets. In the latter case, the containing interval is returned instead of just the element itself. the way that actually matters in giant sets ๐Ÿฆ‹

reset command resets state attached to the given element(s), e.g. counter and quota statement values.

Table 11. Element options โ€” tiny table, big energy:

  • timeout โ€” timeout value for sets/maps with flag timeout.
  • expires โ€” the time until given element expires, useful for ruleset replication only.
  • comment โ€” per element comment field.

๐ŸŒŠ FLOWTABLES ๐ŸŒŠ

{add | create} flowtable [family] table flowtable { hook hook priority priority ; devices = { DEVICE_LIST } ; }
list flowtables [family] [table]
{delete | destroy | list} flowtable [family] table flowtable
delete flowtable [family] table handle handle

DEVICE_LIST := DEVICE_NAME [, DEVICE_LIST]
DEVICE_NAME := string | string*

Flowtables allow you to accelerate packet forwarding in software. Flowtables entries are represented through a tuple that is composed of the input interface, source and destination address, source and destination port; and layer 3/4 protocols. Each entry also caches the destination interface and the gateway address - to update the destination link-layer address - to forward packets. The ttl and hoplimit fields are also decremented. Hence, flowtables provides an alternative path that allow packets to bypass the classic forwarding path. Flowtables reside in the ingress hook that is located before the prerouting hook. You can select which flows you want to offload through the flow expression from the forward chain. Flowtables are identified by their address family and their name. The address family must be one of ip, ip6, or inet. The inet address family is a dummy family which is used to create hybrid IPv4/IPv6 tables. When no address family is specified, ip is used by default. main character forwarding behavior honestly ๐Ÿ‘‘

The priority can be a signed integer or filter which stands for 0. Addition and subtraction can be used to set relative priority, e.g. filter + 5 equals to 5. math but make it firewall ๐Ÿ“

With newer kernels there is basic support for wildcards in DEVICE_LIST by specifying an asterisk suffix. The flowtable will apply to all interfaces matching the given prefix. Use the list hooks command to see the current status. prefix slay ๐ŸŽ€

  • add โ€” Add a new flowtable for the given family with the given name.
  • delete โ€” Delete the specified flowtable.
  • destroy โ€” Delete the specified flowtable, it does not fail if it does not exist.
  • list โ€” List all flowtables.

โœจ STATEFUL OBJECTS โœจ

okay bestie, these are the lil โœจliveโœจ things that actually remember stuff between packets. here's the whole grammar, keep it close:

{add | delete | destroy | list | reset} counter [family] table object
{add | delete | destroy | list | reset} quota [family] table object
{add | delete | destroy | list} limit [family] table object
delete counter [family] table handle handle
delete quota [family] table handle handle
delete limit [family] table handle handle
destroy counter [family] table handle handle
destroy quota [family] table handle handle
destroy limit [family] table handle handle
list { counters | limits | quotas } [family] [table]
reset { counters | quotas } [family] [table]

Stateful objects live inside tables and each one has a unique name of its own โ€” like a whole little main-character identity ๐ŸŽ€. The way they work: they scoop up all the stateful info from your rules, and then you point at them from rules with the keywords type name, e.g. counter name. iykyk ๐Ÿ’…

  • add โ€” adds a brand new stateful object in the table you specified โœจ
  • delete โ€” deletes the object you named ๐Ÿ—‘๏ธ
  • destroy โ€” deletes the object too, but here's the slay part: it does not fail if the object doesn't even exist. no drama, no error, just vibes ๐Ÿ˜Œ
  • list โ€” shows off the stateful info the object is holding ๐Ÿ‘€
  • reset โ€” list-and-reset. it shows you the info and zeroes it out, iconic combo ๐Ÿซถ

๐Ÿงš CT HELPER

add ct helper [family] table name { type type protocol protocol ; [l3proto family ;] }
delete ct helper [family] table name
list ct helpers

The ct helper is what you use to define connection-tracking helpers, and then you can pair them up with the ct helper set statement. type and protocol are mandatory โ€” no skipping, bestie โ€” and l3proto gets derived from the table family by default. so like, in the inet table the kernel will try to load both the ipv4 and ipv6 helper backends, as long as the kernel actually supports them ๐Ÿ’–

Table 12. conntrack helper specifications

  • type โ€” name of helper type โ€” quoted string (e.g. "ftp")
  • protocol โ€” layer 4 protocol of the helper โ€” string (e.g. ip)
  • l3proto โ€” layer 3 protocol of the helper โ€” address family (e.g. ip)
  • comment โ€” per ct helper comment field โ€” string

defining and assigning ftp helper ๐ŸŸ

Unlike iptables, helper assignment needs to be performed after the conntrack lookup has completed, for example with the default 0 hook priority.
table inet myhelpers {
  ct helper ftp-standard {
     type "ftp" protocol tcp
  }
  chain prerouting {
      type filter hook prerouting priority filter;
      tcp dport 21 ct helper set "ftp-standard"
  }
}

โฐ CT TIMEOUT

add ct timeout  [family] table name { protocol protocol ; policy = { state: value [, ...] } ; [l3proto family ;] }
delete ct timeout [family] table name
list ct timeouts

Ct timeout is the glow-up for your connection tracking timeout values ๐ŸŒธ. You assign timeout policies with the ct timeout set statement. protocol and policy are mandatory, and l3proto comes from the table family by default.

Table 13. conntrack timeout specifications

  • protocol โ€” layer 4 protocol of the timeout object โ€” string (e.g. ip)
  • state โ€” connection state name โ€” string (e.g. "established")
  • value โ€” timeout value for connection state โ€” unsigned integer
  • l3proto โ€” layer 3 protocol of the timeout object โ€” address family (e.g. ip)
  • comment โ€” per ct timeout comment field โ€” string

the tcp connection state names that can have a specific timeout value are:

close, close_wait, established, fin_wait, last_ack, retrans, syn_recv, syn_sent, time_wait and unack.

you can use sysctl -a |grep net.netfilter.nf_conntrack_tcp_timeout_ to view and change the system-wide defaults ๐Ÿ‘‘. ct timeout lets you do flow-specific settings without touching the global timeouts โ€” obsessed, honestly.

for example, tcp port 53 could have much lower settings than other traffic ๐Ÿ”ฅ

the udp state names that can have a specific timeout value are replied and unreplied.

defining and assigning ct timeout policy:

table ip filter {
        ct timeout customtimeout {
                protocol tcp;
                l3proto ip
                policy = { established: 2m, close: 20s }
        }

        chain output {
                type filter hook output priority filter; policy accept;
                ct timeout set "customtimeout"
        }
}

testing the updated timeout policy:

% conntrack -E

It should display:

[UPDATE] tcp      6 120 ESTABLISHED src=172.16.19.128 dst=172.16.19.1
sport=22 dport=41360 [UNREPLIED] src=172.16.19.1 dst=172.16.19.128
sport=41360 dport=22

๐Ÿ”ฎ CT EXPECTATION

add ct expectation  [family] table name { protocol protocol ; dport dport ; timeout timeout ; size size ; [l3proto family ;] }
delete ct expectation  [family] table name
list ct expectations

Ct expectation makes connection expectations โ€” like, it's manifesting connections before they even show up, we love a forward-thinking queen โœจ. You assign expectations with the ct expectation set statement. protocol, dport, timeout and size are all mandatory bestie, no cutting corners ๐Ÿ’… and l3proto is derived from the table family by default.

So the ct expectation spec table, because bestie you know we need the full rundown ๐Ÿ’…:

Table 14. conntrack expectation specifications

  • protocol โ€” the layer 4 protocol of the expectation object; type is string (e.g. ip)
  • dport โ€” destination port of the expected connection; type is unsigned integer
  • timeout โ€” timeout value for the expectation; type is unsigned integer
  • size โ€” size value for the expectation; type is unsigned integer
  • l3proto โ€” layer 3 protocol of the expectation object; type is address family (e.g. ip)
  • comment โ€” per ct expectation comment field; type is string

And here's what defining + assigning a ct expectation policy actually looks like, no cap:

table ip filter {
        ct expectation expect {
                protocol udp
                dport 9876
                timeout 2m
                size 8
                l3proto ip
        }

        chain input {
                type filter hook input priority filter; policy accept;
                ct expectation set "expect"
        }
}

๐ŸŽ€ COUNTER

add counter [family] table name [{ [ packets packets bytes bytes ; ] [ comment comment ; }]
delete counter [family] table name
list counters

Table 15. Counter specifications

  • packets โ€” initial count of packets; type is unsigned integer (64 bit)
  • bytes โ€” initial count of bytes; type is unsigned integer (64 bit)
  • comment โ€” per counter comment field; type is string

Using named counters, like so:

nft add counter filter http
nft add rule filter input tcp dport 80 counter name "http"

Using named counters with maps ๐Ÿค (this is the good stuff):

nft add counter filter http
nft add counter filter https
nft add rule filter input counter name tcp dport map { 80 : "http", 443 : "https" }

๐ŸŒธ QUOTA

add quota [family] table name { [over|until] bytes BYTE_UNIT [ used bytes BYTE_UNIT ] ; [ comment comment ; ] }
BYTE_UNIT := bytes | kbytes | mbytes
delete quota [family] table name
list quotas

Table 16. Quota specifications

  • quota โ€” quota limit, used as the quota name; type is two arguments, an unsigned integer (64 bit) and a string: bytes, kbytes, mbytes. "over" and "until" go before these arguments ๐Ÿ‘ˆ
  • used โ€” initial value of used quota; type is two arguments, an unsigned integer (64 bit) and a string: bytes, kbytes, mbytes
  • comment โ€” per quota comment field; type is string

Using named quotas:

nft add quota filter user123 { over 20 mbytes }
nft add rule filter input ip saddr 192.168.10.123 quota name "user123"

Using named quotas with maps โ€” one quota per bestie, obsessed:

nft add quota filter user123 { over 20 mbytes }
nft add quota filter user124 { over 20 mbytes }
nft add rule filter input quota name ip saddr map { 192.168.10.123 : "user123", 192.168.10.124 : "user124" }

โœจ EXPRESSIONS โœจ

Okay so expressions represent values. Like, values values โ€” either constants (network addresses, port numbers, etc.) or data gathered from the packet while the ruleset is being evaluated. Expressions can be combined using binary, logical, relational and other types of expressions to form complex or relational (match) expressions. They also get used as arguments to certain types of operations โ€” NAT, packet marking, etc. ๐Ÿซถ

Every expression has a data type, and that data type decides the size, parsing and representation of symbolic values, plus type compatibility with other expressions. iykyk.

๐Ÿ’œ DESCRIBE COMMAND

describe expression | data type

The describe command shows info about the type of an expression and its data type. You can also hand it a data type, and then nft will display more information about that type. Little lore drop, love that for us.

The describe command in action:

$ nft describe tcp flags
payload expression, datatype tcp_flag (TCP flag) (basetype bitmask, integer), 8 bits

predefined symbolic constants:
fin                           0x01
syn                           0x02
rst                           0x04
psh                           0x08
ack                           0x10
urg                           0x20
ecn                           0x40
cwr                           0x80

๐ŸŒˆ DATA TYPES

Data types determine the size, parsing and representation of symbolic values and the type compatibility of expressions. A bunch of global data types exist, and on top of that some expression types define further data types that are specific to that expression type. Most data types have a fixed size โ€” but some can have a dynamic size, f.i. the string type. Some types also come with predefined symbolic constants, and you can list those with the nft describe command:

$ nft describe ct_state
datatype ct_state (conntrack state) (basetype bitmask, integer), 32 bits

pre-defined symbolic constants (in hexadecimal):
invalid                         0x00000001
new ...

Types may be derived from lower order types โ€” f.i. the IPv4 address type is derived from the integer type, which means an IPv4 address can also be specified as an integer value. Cute, right? ๐Ÿฆ‹

And in certain contexts (set and map definitions, bestie), you have to explicitly specify a data type. Each type has a name, and that name is what you use for it.

๐Ÿงš INTEGER TYPE

  • Name: Integer
  • Keyword: integer
  • Size: variable
  • Base type: -

Okay so the integer type is what you use for numeric values โ€” and yes bestie, it can be written as a decimal, hexadecimal, or octal number, dealer's choice ๐Ÿ’…. It does not have a fixed size, though โ€” its size gets decided by whichever expression it's being used in. Vibes-based sizing, literally.

๐Ÿ”น BITMASK TYPE

  • Name โ€” Bitmask
  • Keyword โ€” bitmask
  • Size โ€” variable
  • Base type โ€” integer

The bitmask type (bitmask) is the one you reach for when you're dealing with bitmasks โœจ.

In expressions, the bits of a bitmask can be written as bit[,bit]... where each bit is either the value of that bit or a pre-defined symbolic constant, if one exists (for example, bit 0x1 of ct state has the symbolic constant new, iykyk).

Equality of a value with a bitmask like that is satisfied if the value has any of the bitmask's bits set โ€” and optionally others too, we're not picky ๐Ÿซถ.

The syntax

expression value / mask

is identical to

expression and mask == value

so like, for example:

tcp flags syn,ack / syn,ack,fin,rst

is the same as:

tcp flags and (syn|ack|fin|rst) == syn|ack
โš ๏ธ Note bestie: the expression bit[,bit]... is not generally the same as the expression {bit[,bit]...}, and same deal with a named set. Those latter forms are lookups in a set and will only match if the set contains exactly one value that matches. They are effectively the same though (with matching bitmasks typically being faster) when all the bits are semantically mutually exclusive ๐ŸŒธ.

Examples, because obviously:

  • tcp flags syn,ack โ€” matches packets that have the SYN flag, the ACK flag, or both SYN and ACK set. Other flags? Ignored, we don't care about them ๐Ÿ’€
  • tcp flags { syn, ack } โ€” matches packets that have either only the SYN or only the ACK flag set. All other flags must be unset, strict queen behaviour ๐Ÿ‘‘
  • ct state established,related and ct state { established, related } match exactly the same packets, because the bits of ct state are all mutually exclusive โ€” slay, no difference ๐Ÿ’–

As usual, the nft describe command may be used to get details on a data type, which for bitmasks shows you the symbolic names and values of the bits. Iconic little lookup tool, ngl.

๐Ÿ”น STRING TYPE

  • Name โ€” String
  • Keyword โ€” string
  • Size โ€” variable
  • Base type โ€” -

The string type is for character strings ๐ŸŽ€. A string begins with an alphabetic character (a-zA-Z) followed by zero or more alphanumeric characters or the characters /, -, _ and .. Also โ€” anything wrapped in double quotes (") is recognized as a string, no questions asked.

String specification, look:

# Interface name
filter input iifname eth0

# Weird interface name
filter input iifname "(eth0)"

See? Weird names get the quotes treatment ๐Ÿ’…

  • Name โ€” Link layer address
  • Keyword โ€” lladdr
  • Size โ€” variable
  • Base type โ€” integer

The link layer address type is for link layer addresses ๐Ÿฆ‹. You specify them as a variable amount of groups of two hexadecimal digits, separated using colons (:).

Link layer address specification:

# Ethernet destination MAC address
filter input ether daddr 20:c9:d0:43:12:d9

Cute little colon-separated hex groups, we love to see it โœจ

๐Ÿ”น IPV4 ADDRESS TYPE

  • Name โ€” IPV4 address
  • Keyword โ€” ipv4_addr
  • Size โ€” 32 bit
  • Base type โ€” integer

The IPv4 address type is for IPv4 addresses ๐ŸŒˆ. Addresses are specified in either dotted decimal, dotted hexadecimal, dotted octal, decimal, hexadecimal, octal notation โ€” or as a host name. A host name will be resolved using the standard system resolver, so yeah, that's a whole lookup happening for you ๐Ÿ’–

IPv4 address specification:

# dotted decimal notation
filter output ip daddr 127.0.0.1

# host name
filter output ip daddr localhost

๐Ÿ”น IPV6 ADDRESS TYPE

  • Name โ€” IPv6 address
  • Keyword โ€” ipv6_addr
  • Size โ€” 128 bit
  • Base type โ€” integer

The IPv6 address type is for IPv6 addresses ๐Ÿงš. Addresses are specified as a host name or as hexadecimal halfwords separated by colons. And heads up โ€” addresses might be enclosed in square brackets ([]) to differentiate them from port numbers, lowkey crucial detail ๐Ÿ‘€

IPv6 address specification:

# abbreviated loopback address
filter output ip6 daddr ::1

IPv6 address specification with bracket notation:

# without [] the port number (22) would be parsed as part of the
# ipv6 address
ip6 nat prerouting tcp dport 2222 dnat to [1ce::d0]:22

See that? Without the [] the port number (22) would get parsed as part of the IPv6 address and everything falls apart ๐Ÿ˜ญ Brackets are the moment.

๐Ÿ”น BOOLEAN TYPE

  • Name โ€” Boolean
  • Keyword โ€” boolean
  • Size โ€” 1 bit
  • Base type โ€” integer

The boolean type is a syntactical helper type in userspace ๐ŸŽ€. Its whole job is sitting on the right-hand side of a (typically implicit) relational expression to turn whatever's on the left-hand side into a boolean check โ€” usually for existence, iykyk.

Table 17. The following keywords will automatically resolve into a boolean type with given value:

  • exists โ€” value 1
  • missing โ€” value 0

Table 18. expressions support a boolean comparison:

  • fib โ€” Check route existence.
  • exthdr โ€” Check IPv6 extension header existence.
  • tcp option โ€” Check TCP option header existence.

Boolean specification, bestie:

# match if route exists
filter input fib daddr . iif check exists

# match only non-fragmented packets in IPv6 traffic
filter input exthdr frag missing

# match if TCP timestamp option is present
filter input tcp option timestamp exists

Three little examples, three little vibes, all ate ๐Ÿ’…

๐Ÿ”น ICMP TYPE TYPE

  • Name โ€” ICMP Type
  • Keyword โ€” icmp_type
  • Size โ€” 8 bit
  • Base type โ€” integer

The ICMP Type type is the convenient way to specify the ICMP header's type field ๐Ÿ”ฅ One keyword, the whole field, obsessed.

๐ŸŒธ ICMP TYPE ๐ŸŒธ

So the ICMP type field is like... a whole thing, and you can just throw raw numbers at it, but why would you when these keywords exist ๐Ÿ’… Table 19 is the cheat sheet, bestie โ€” keywords you can use when specifying the ICMP type:

  • echo-reply โ†’ 0
  • destination-unreachable โ†’ 3
  • source-quench โ†’ 4
  • redirect โ†’ 5
  • echo-request โ†’ 8
  • router-advertisement โ†’ 9
  • router-solicitation โ†’ 10
  • time-exceeded โ†’ 11
  • parameter-problem โ†’ 12
  • timestamp-request โ†’ 13
  • timestamp-reply โ†’ 14
  • info-request โ†’ 15
  • info-reply โ†’ 16
  • address-mask-request โ†’ 17
  • address-mask-reply โ†’ 18

That's the ICMP Type specification, periodt โœจ And here's it in action โ€” matching ping packets, iconic behavior honestly:

# match ping packets
filter output icmp type { echo-request, echo-reply }

๐ŸŽ€ ICMP CODE TYPE ๐ŸŽ€

  • Name: ICMP Code
  • Keyword: icmp_code
  • Size: 8 bit
  • Base type: integer

The ICMP Code type is here to conveniently specify the ICMP header's code field ๐Ÿซถ That's literally its whole job and it does it slayfully.


๐Ÿฆ‹ ICMPV6 TYPE TYPE ๐Ÿฆ‹

  • Name: ICMPv6 Type
  • Keyword: icmpv6_type
  • Size: 8 bit
  • Base type: integer

The ICMPv6 Type type is used to conveniently specify the ICMPv6 header's type field. Same energy, but v6, no cap ๐Ÿ’œ

Table 20 โ€” keywords you can use when specifying the ICMPv6 type:

  • destination-unreachable โ†’ 1
  • packet-too-big โ†’ 2
  • time-exceeded โ†’ 3
  • parameter-problem โ†’ 4
  • echo-request โ†’ 128
  • echo-reply โ†’ 129
  • mld-listener-query โ†’ 130
  • mld-listener-report โ†’ 131
  • mld-listener-done โ†’ 132
  • mld-listener-reduction โ†’ 132
  • nd-router-solicit โ†’ 133
  • nd-router-advert โ†’ 134
  • nd-neighbor-solicit โ†’ 135
  • nd-neighbor-advert โ†’ 136
  • nd-redirect โ†’ 137
  • router-renumbering โ†’ 138
  • ind-neighbor-solicit โ†’ 141
  • ind-neighbor-advert โ†’ 142
  • mld2-listener-report โ†’ 143
Not me noticing mld-listener-done and mld-listener-reduction both sit at 132 โ€” that's exactly how the original listing has it, so don't come for me ๐Ÿ™ˆ Copy it as-is, bestie.

ICMPv6 Type specification, and yes the example is giving main character energy:

# match ICMPv6 ping packets
filter output icmpv6 type { echo-request, echo-reply }

๐ŸŒˆ ICMPV6 CODE TYPE ๐ŸŒˆ

  • Name: ICMPv6 Code
  • Keyword: icmpv6_code
  • Size: 8 bit
  • Base type: integer

The ICMPv6 Code type is used to conveniently specify the ICMPv6 header's code field โญ Lowkey the most straightforward type in this whole section and I respect it for that.

๐Ÿ’– CONNTRACK TYPES ๐Ÿ’–

okay bestie, the conntrack types have entered the chat and they are lowkey iconic. Table 21 is the whole lineup โ€” names, keywords, sizes, base types, all the receipts. No cap. ๐Ÿซถ

Table 21. overview of types used in ct expression and statement

  • conntrack state โ€” keyword ct_state, size 4 byte, base type bitmask ๐Ÿ’…
  • conntrack direction โ€” keyword ct_dir, size 8 bit, base type integer โœจ
  • conntrack status โ€” keyword ct_status, size 4 byte, base type bitmask ๐ŸŽ€
  • conntrack event bits โ€” keyword ct_event, size 4 byte, base type bitmask ๐Ÿฆ‹
  • conntrack label โ€” keyword ct_label, size 128 bit, base type bitmask ๐ŸŒธ

โœจ For each of the types above, keywords are available for convenience โœจ โ€” literally a little gift from the syntax gods, iykyk.

Table 22. conntrack state (ct_state)

  • invalid โ€” value 1
  • established โ€” value 2
  • related โ€” value 4
  • new โ€” value 8
  • untracked โ€” value 64

Table 23. conntrack direction (ct_dir)

  • original โ€” value 0
  • reply โ€” value 1

Table 24. conntrack status (ct_status) โ€” this one is giving full lore, bestie ๐Ÿ‘‘

  • expected โ€” value 1 โ€” Expected connection; conntrack helper set it up
  • seen-reply โ€” value 2 โ€” Conntrack has seen packets in both directions
  • assured โ€” value 4 โ€” Conntrack entry will not be removed if hash table is full
  • confirmed โ€” value 8 โ€” Initial packet processed
  • snat โ€” value 16 โ€” Original source address differs from reply destination
  • dnat โ€” value 32 โ€” Original destination differs from reply source
  • seq-adjust โ€” value 64 โ€” tcp sequence number rewrite due to conntrack helper or synproxy
  • snat-done โ€” value 128 โ€” tried to find matching snat/masquerade rule
  • dnat-done โ€” value 256 โ€” tried to find matching dnat/redirect rule
  • dying โ€” value 512 โ€” Connection about to be deleted
  • fixed-timeout โ€” value 1024 โ€” entry expires even if traffic is active
  • helper โ€” value 8192 โ€” connection is monitored by conntrack helper
  • offload โ€” value 16384 โ€” connection is offloaded to a flow table
  • hw-offload โ€” value 32768 โ€” connection is offloaded to hardware

Table 25. conntrack event bits (ct_event)

  • new โ€” value 1
  • related โ€” value 2
  • destroy โ€” value 4
  • reply โ€” value 8
  • assured โ€” value 16
  • protoinfo โ€” value 32
  • helper โ€” value 64
  • mark โ€” value 128
  • seqadj โ€” value 256
  • secmark โ€” value 512
  • label โ€” value 1024

Possible keywords for conntrack label type (ct_label) are read at runtime from /etc/connlabel.conf. ๐Ÿซถ

๐Ÿฆ‹ DCCP PKTTYPE TYPE ๐Ÿฆ‹

okay so picture the glow-up table for this one, bestie:

  • Name โ€” DCCP packet type
  • Keyword โ€” dccp_pkttype
  • Size โ€” 4 bit
  • Base type โ€” integer

The DCCP packet type abstracts all the different legal values of that respective four bit field in the DCCP header, exactly as stated by RFC4340. Heads up though: possible values 10-15 are considered reserved and therefore not allowed to be used. In iptables' dccp match, these values are aliased INVALID. With nftables, you may simply match on the numeric value range, i.e. 10-15. no drama, just vibes ๐Ÿ’…

Table 26. keywords may be used when specifying the DCCP packet type โœจ

  • request โ†’ 0
  • response โ†’ 1
  • data โ†’ 2
  • ack โ†’ 3
  • dataack โ†’ 4
  • closereq โ†’ 5
  • close โ†’ 6
  • reset โ†’ 7
  • sync โ†’ 8
  • syncack โ†’ 9

๐Ÿ’ซ PRIMARY EXPRESSIONS ๐Ÿ’ซ

The lowest order expression is a primary expression, and it's literally representing either a constant or a single datum from a packet's payload, meta data or a stateful module. tiny but mighty, yk? ๐Ÿซถ

๐ŸŒˆ META EXPRESSIONS ๐ŸŒˆ

meta {length | nfproto | l4proto | protocol | priority}
[meta] {mark | iif | iifname | iiftype | oif | oifname | oiftype | skuid | skgid | nftrace | rtclassid | ibrname | obrname | pkttype | cpu | iifgroup | oifgroup | cgroup | random | ipsec | iifkind | oifkind | time | hour | day }

A meta expression refers to meta data associated with a packet. it's giving "packet lore" honestly ๐Ÿ’€

So there are two types of meta expressions: unqualified and qualified. Qualified meta expressions require the meta keyword before the meta key, and unqualified meta expressions can be specified by using the meta key directly or as qualified meta expressions. Both slay, just different access levels โœจ

Meta l4proto is useful to match a particular transport protocol that is part of either an IPv4 or IPv6 packet. It will also skip any IPv6 extension headers present in an IPv6 packet. very considerate of it honestly ๐Ÿ‘‘

meta iif, oif, iifname and oifname are used to match the interface a packet arrived on or is about to be sent out on. classic.

iif and oif are used to match on the interface index, whereas iifname and oifname are used to match on the interface name. and bestie, this is not the same thing โ€” assuming the rule:

filter input meta iif "foo"

Then this rule can only be added if the interface "foo" exists. Also, the rule will continue to match even if the interface "foo" is renamed to "bar". iconic behavior, honestly ๐ŸŒธ

This is because internally the interface index is used. In case of dynamically created interfaces, such as tun/tap or dialup interfaces (ppp for example), it might be better to use iifname or oifname instead. lowkey the move for those ๐Ÿ™ˆ

In these cases, the name is used so the interface doesn't have to exist to add such a rule; it will stop matching if the interface gets renamed, and it will match again in case the interface gets deleted and later a new interface with the same name is created. it's giving phoenix rising from the ashes ngl ๐Ÿ”ฅ

Like with iptables, wildcard matching on interface name prefixes is available for iifname and oifname matches by appending an asterisk (*) character. but note however that unlike iptables, nftables does not accept interface names consisting of the wildcard character only โ€” users are supposed to just skip those always matching expressions. In order to match on a literal asterisk character, one may escape it using backslash (\). ๐ŸŽ€

fr fr don't try the lone * thing, it's not gonna go how you think ๐Ÿ˜ญ

Table 27. Meta expression types โ€” aka the โœจmetaโœจ bag, the stuff that's not really in the packet but is definitely about the packet ๐Ÿ’…

Okay bestie, quick vibe check first: these are meta expressions. They don't reach into the payload โ€” they're the gossip the kernel already knows about the packet. Read them like a group chat screenshot: no cap, all context ๐Ÿซถ

  • length โ€” Length of the packet in bytes ยท type: integer (32-bit) ๐Ÿ“
  • nfproto โ€” real hook protocol family, useful only in inet table ยท type: integer (32 bit) ๐Ÿ‘€ (iykyk โ€” it's the real one, not the pretend one, and it only pulls its weight inside inet)
  • l4proto โ€” layer 4 protocol, skips ipv6 extension headers ยท type: integer (8 bit) ๐Ÿงš (it literally hops right over those extension headers, main character energy)
  • protocol โ€” EtherType protocol value ยท type: ether_type ๐ŸŽ€
  • priority โ€” TC packet priority ยท type: tc_handle โญ
  • mark โ€” Packet mark ยท type: mark ๐Ÿท๏ธ
  • iif โ€” Input interface index ยท type: iface_index ๐Ÿšช
  • iifname โ€” Input interface name ยท type: ifname ๐ŸŒธ
  • iiftype โ€” Input interface type ยท type: iface_type ๐Ÿฆ‹
  • oif โ€” Output interface index ยท type: iface_index ๐Ÿšช
  • oifname โ€” Output interface name ยท type: ifname ๐ŸŒธ
  • oiftype โ€” Output interface hardware type ยท type: iface_type ๐Ÿฆ‹
  • sdif โ€” Slave device input interface index ยท type: iface_index ๐Ÿซถ
  • sdifname โ€” Slave device interface name ยท type: ifname ๐Ÿซถ
  • skuid โ€” UID associated with originating socket ยท type: uid ๐Ÿ‘‘
  • skgid โ€” GID associated with originating socket ยท type: gid ๐Ÿ‘‘
  • rtclassid โ€” Routing realm ยท type: realm ๐ŸŒˆ
  • ibrname โ€” Input bridge interface name ยท type: ifname ๐ŸŒ‰
  • obrname โ€” Output bridge interface name ยท type: ifname ๐ŸŒ‰
  • pkttype โ€” packet type ยท type: pkt_type ๐Ÿ“ฆ
  • cpu โ€” cpu number processing the packet ยท type: integer (32 bit) ๐Ÿ’€ (yes, this one's serving multi-core realness)
  • iifgroup โ€” incoming device group ยท type: devgroup ๐Ÿซ‚
  • oifgroup โ€” outgoing device group ยท type: devgroup ๐Ÿซ‚
  • cgroup โ€” control group net_cls.classid (for matching on cgroupv2, see socket cgroupv2) ยท type: integer (32 bit) ๐Ÿงฎ
  • random โ€” pseudo-random number ยท type: integer (32 bit) ๐ŸŽฒ (iconic for chaos gremlin rules)
  • ipsec โ€” true if packet was ipsec encrypted ยท type: boolean (1 bit) ๐Ÿ”
  • iifkind โ€” Input interface kind ยท no type listed in the table ๐Ÿ™ˆ
  • oifkind โ€” Output interface kind ยท no type listed in the table ๐Ÿ™ˆ
  • time โ€” Absolute time of ยท type: Integer (32 bit) or โฐ
ngl the last one got cut off mid-sentence by the typesetter โ€” time is literally still typingโ€ฆ stay tuned ๐Ÿ’–
  • packet reception โ€” literally just a string, no big deal ๐ŸŽ€
  • day โ€” day of the week, and it takes either an Integer (8 bit) or a string ๐Ÿฆ‹
  • hour โ€” hour of day, and it's a String value in the form HH:MM or HH:MM:SS. Values are expected to be less than 24:00, although for technical reasons, 23:59:60 is accepted, too (yes bestie, leap second said hi ๐Ÿ’€)

Table 28. Meta expression specific types ๐Ÿ‘‘

okay so this is the roster of the meta-specific types, and honestly? iconic lineup:

  • iface_index โ€” Interface index (32 bit number). Can be specified numerically or as name of an existing interface ๐Ÿ’…
  • ifname โ€” Interface name (16 byte string). Does not have to exist. (she's aspirational, we love that for her โœจ)
  • iface_type โ€” Interface type (16 bit number).
  • uid โ€” User ID (32 bit number). Can be specified numerically or as user name.
  • gid โ€” Group ID (32 bit number). Can be specified numerically or as group name.
  • realm โ€” Routing Realm (32 bit number). Can be specified numerically or as symbolic name defined in /etc/iproute2/rt_realms.
  • devgroup_type โ€” Device group (32 bit number). Can be specified numerically or as symbolic name defined in /etc/iproute2/group.
  • pkt_type โ€” Packet type, and the options are:
    • host (addressed to local host)
    • broadcast (to all)
    • multicast (to group)
    • other (addressed to another host)
  • ifkind โ€” Interface kind (16 byte string). See TYPES in ip-link(8) for a list.
  • time โ€” Either an integer or a date in ISO format. For example: "2019-06-06 17:00". Hour and seconds are optional and can be omitted if desired. If omitted, midnight will be assumed. The following three would be equivalent: "2019-06-06", "2019-06-06 00:00" and "2019-06-06 00:00:00". Use a range expression such as "2019-06-06 10:00"-"2019-06-10 14:00" for matching a time range. When an integer is given, it is assumed to be a UNIX timestamp โฐ
  • day โ€” Either a day of week ("Monday", "Tuesday", etc.), or an integer between 0 and 6. Strings are matched case-insensitively, and a full match is not expected (e.g. "Mon" would match "Monday" โ€” she's flexible like that ๐Ÿซถ). When an integer is given, 0 is Sunday and 6 is Saturday. Use a range expression such as "Monday"-"Wednesday" for matching a week day range. Hump day detection: unlocked ๐Ÿ”“
  • hour โ€” A string representing an hour in 24-hour format. Seconds can optionally be specified. For example, 17:00 and 17:00:00 would be equivalent. Use a range expression such as "17:00"-"19:00" for matching a time range.

Using meta expressions. (a.k.a. the part where it all comes together, no cap ๐Ÿ’–)

# qualified meta expression
filter output meta oif eth0
filter forward meta iifkind { "tun", "veth" }

# unqualified meta expression
filter output oif eth0

# incoming packet was subject to ipsec processing
raw prerouting meta ipsec exists accept

# match incoming packet from 03:00 to 14:00 local time
raw prerouting meta hour "03:00"-"14:00" counter accept

๐Ÿงฆ SOCKET EXPRESSION ๐Ÿงฆ

socket {transparent | mark | wildcard}
socket cgroupv2 level NUM

Socket expression can be used to search for an existing open TCP/UDP socket and its attributes that can be associated with a packet. It literally goes looking for an established or non-zero bound listening socket (possibly with a non-local address โ€” she's worldly like that ๐ŸŒ).

You can also use it to match on the socket cgroupv2 at a given ancestor level, e.g. if the socket belongs to cgroupv2 a/b, ancestor level 1 checks for a matching on cgroup a and ancestor level 2 checks for a matching on cgroup b. it's giving family tree energy ๐ŸŒณโœจ

the socket attributes, aka the receipts ๐Ÿ’… (Table 29)

ok so these are the attributes you can pull off a socket, bestie:

  • transparent โ€” the value of the IP_TRANSPARENT socket option in the found socket. it can be 0 or 1. type: boolean (1 bit) โœจ
  • mark โ€” the value of the socket mark (SOL_SOCKET, SO_MARK). type: mark ๐ŸŽ€
  • wildcard โ€” tells you whether the socket is wildcard-bound (e.g. 0.0.0.0 or ::0). type: boolean (1 bit) ๐Ÿฆ‹
  • cgroupv2 โ€” cgroup version 2 for this socket (path from /sys/fs/cgroup). type: cgroupv2 ๐ŸŒธ

Using socket expression. the actual slay, in code:

# Mark packets that correspond to a transparent socket. "socket wildcard 0"
# means that zero-bound listener sockets are NOT matched (which is usually
# exactly what you want).
table inet x {
    chain y {
        type filter hook prerouting priority mangle; policy accept;
        socket transparent 1 socket wildcard 0 mark set 0x00000001 accept
    }
}
# Trace packets that corresponds to a socket with a mark value of 15
table inet x {
    chain y {
        type filter hook prerouting priority mangle; policy accept;
        socket mark 0x0000000f nftrace set 1
    }
}
# Set packet mark to socket mark
table inet x {
    chain y {
        type filter hook prerouting priority mangle; policy accept;
        tcp dport 8080 mark set socket mark
    }
}
# Count packets for cgroupv2 "user.slice" at level 1
table inet x {
    chain y {
        type filter hook input priority filter; policy accept;
        socket cgroupv2 level 1 "user.slice" counter
    }
}

๐Ÿ” OSF EXPRESSION ๐Ÿ”

osf [ttl {loose | skip}] {name | version}

okay so the osf expression does passive operating system fingerprinting. it's literally the detective of the ruleset ๐Ÿ•ต๏ธโ€โ™€๏ธ. this expression compares some data (Window Size, MSS, options and their order, DF, and others) from packets with the SYN bit set. iykyk.

Table 30. Available osf attributes โ€” the whole menu, no skips:

  • ttl โ€” do TTL checks on the packet to determine the operating system. type: string
  • version โ€” do OS version checks on the packet. (no type listed, she's mysterious like that ๐Ÿ™ˆ)
  • name โ€” name of the OS signature to match. all signatures can be found at pf.os file. use "unknown" for OS signatures that the expression could not detect. type: string

Available ttl values.

if no TTL attribute is passed, it makes a true IP header and does fingerprint TTL true comparison. this generally works for LANs. ๐Ÿ’ซ

  • loose โ€” check if the IP header's TTL is less than the fingerprint one. works for globally-routable addresses.
  • skip โ€” do not compare the TTL at all. periodt.

Using osf expression.

# Accept packets that match the "Linux" OS genre signature without comparing TTL.
table inet x {
    chain y {
        type filter hook input priority filter; policy accept;
        osf ttl skip name "Linux"
    }
}

๐ŸŒˆ FIB EXPRESSIONS ๐ŸŒˆ

fib FIB_TUPLE FIB_RESULT
FIB_TUPLE := { saddr | daddr} [ . { iif | oif } . mark ]
FIB_RESULT  := { oif | oifname | check | type }

a fib expression queries the fib (forwarding information base) to obtain information such as the output interface index. it's giving library-runner energy fr fr ๐Ÿ“š

the first arguments to the fib expression are the input keys to be passed to the fib lookup function. one of saddr or daddr is mandatory โ€” and heads up bestie, they are also mutually exclusive. pick one, you can't have both ๐Ÿ’…

mark, iif and oif keywords are optional modifiers to influence the search result, see the FIB_TUPLE keyword table below for a description. the iif and oif tuple keywords are also mutually exclusive. again: choose one ๐ŸŒธ

the last argument to the fib expression is the desired result type.

  • oif โ€” asks to obtain the interface index that would be used to send packets to the packets source (saddr key) or destination (daddr key). if no routing entry is found, the returned interface index is 0. ๐Ÿ˜ญ
  • oifname โ€” like oif, but it fills the interface name instead. this is useful to check dynamic interfaces such as ppp devices. if no entry is found, an empty interface name is returned.
  • type โ€” returns the address type such as unicast or multicast. a complete list of supported address types can be shown with nft describe fib_addrtype. โœจ

Table 31. FIB_TUPLE keywords โ€” the flags, explained:

  • daddr โ€” perform a normal route lookup: search fib for route to the destination address of the packet.
  • saddr โ€” perform a reverse route lookup: search the fib for route to the source address of the packet.
  • mark โ€” consider the packet mark (nfmark) when querying the fib.
  • iif โ€” if fib lookups provides a route then check its output interface is identical to the packets input interface.
  • oif โ€” if fib lookups provides a route then check its output interface is identical to the packets output interface. this flag can only be used with the type result. ๐Ÿ‘‘
ok real talk ๐Ÿซถ those last two are mutual-exclusive-adjacent AND oif has a whole extra rule about only working with type โ€” don't come for me if you mix them, the manpage said it first ๐Ÿ’€

๐ŸŽ€ Table 32. FIB_RESULT keywords ๐ŸŽ€

Bestie, hereโ€™s the keyword tea โ˜• โ€” these are the columns Keyword, Description, and Result Type, and yes, every single row is staying:

  • oif โ€” Output interface index โ€” result type: iface_index
  • check โ€” Output interface check โ€” result type: boolean
  • oifname โ€” Output interface name โ€” result type: ifname
  • type โ€” Address type โ€” result type: fib_addrtype (see nft describe fib_addrtype for a list)

The oif and oifname result is only valid in the prerouting, input and forward hooks. The type can be queried from any one of prerouting, input, forward output and postrouting.

For type, the presence of the iif keyword in the FIB_TUPLE modifiers restrict the available hooks to those where the packet is associated with an incoming interface, i.e. prerouting, input and forward. Likewise, the oif keyword in the FIB_TUPLE modifier list will limit the available hooks to forward, output and postrouting.

Using fib expressions. โœจ

# drop packets without a reverse path
filter prerouting fib saddr . iif oif missing drop

In this example, saddr . iif looks up a route to the source address of the packet and restricts matching results to the interface that the packet arrived on, then stores the output interface index from the obtained fib route result.

If no route was found for the source address/input interface combination, the output interface index is zero. Hence, this rule will drop all packets that do not have a strict reverse path (hypothetical reply packet would be sent via the interface the tested packet arrived on).

If only saddr oif is used as the input key, then this rule would only drop packets where the fib cannot find a route. In most setups this will never drop packets because the default route is returned.

# drop packets if the destination ip address is not configured on the incoming interface
filter prerouting fib daddr . iif type != { local, broadcast, multicast } drop

This queries the fib based on the current packets' destination address and the incoming interface.

If the packet is sent to a unicast address that is configured on a different interface, then the packet will be dropped as such an address would be classified as unicast type. Without the iif modifier, any address configured on the local machine is local, and unicast addresses not configured on any interface would return the type unicast.

# perform lookup in a specific 'blackhole' table (0xdead, needs ip appropriate ip rule)
filter prerouting meta mark set 0xdead fib daddr . mark type vmap { blackhole : drop, prohibit : jump prohibited, unreachable : drop }

๐ŸŒˆ ROUTING EXPRESSIONS ๐ŸŒˆ

rt [ip | ip6] {classid | nexthop | mtu | ipsec}

A routing expression refers to routing data associated with a packet. Lowkey iconic behavior, honestly ๐Ÿ’…

๐Ÿง Table 33. Routing expression types ๐Ÿง

  • classid โ€” Routing realm โ€” type: realm
  • nexthop โ€” Routing nexthop โ€” type: ipv4_addr/ipv6_addr
  • mtu โ€” TCP maximum segment size of route โ€” type: integer (16 bit)
  • ipsec โ€” route via ipsec tunnel or transport โ€” type: boolean

๐Ÿ“ Table 34. Routing expression specific types ๐Ÿ“

  • realm โ€” Routing Realm (32 bit number). Can be specified numerically or as symbolic name defined in /etc/iproute2/rt_realms.

Using routing expressions. ๐Ÿฆ‹

# IP family independent rt expression
filter output rt classid 10

# IP family dependent rt expressions
ip filter output rt nexthop 192.168.0.1
ip6 filter output rt nexthop fd00::1
inet filter output rt ip nexthop 192.168.0.1
inet filter output rt ip6 nexthop fd00::1

# outgoing packet will be encapsulated/encrypted by ipsec
filter output rt ipsec exists

๐Ÿ” IPSEC EXPRESSIONS ๐Ÿ”

ipsec {in | out} [ spnum NUM ]  {reqid | spi}
ipsec {in | out} [ spnum NUM ]  {ip | ip6} {saddr | daddr}

An ipsec expression refers to ipsec data associated with a packet.

The in or out keyword needs to be used to specify if the expression should examine inbound or outbound policies. The in keyword can be used in the prerouting, input and forward hooks. The out keyword applies to forward, output and postrouting hooks. The optional keyword spnum can be used to match a specific state in a chain, it defaults to 0.

๐Ÿ”‘ Table 35. Ipsec expression types ๐Ÿ”‘

  • reqid โ€” Request ID โ€” type: integer (32 bit)
  • spi โ€” Security Parameter Index โ€” type: integer (32 bit)
  • saddr โ€” Source address of the tunnel โ€” type: ipv4_addr/ipv6_addr
  • daddr โ€” Destination address of the tunnel โ€” type: ipv4_addr/ipv6_addr
โš ๏ธ Note: When using xfrm_interface, this expression is not useable in output hook as the plain packet does not traverse it with IPsec info attached - use a chain in postrouting hook instead.

๐ŸŽฒ NUMGEN EXPRESSION ๐ŸŽฒ

numgen {inc | random} mod NUM [ offset NUM ]

Create a number generator. The inc or random keywords control its operation mode: In inc mode, the last returned value is simply incremented. In random mode, a new random number is returned. The value after mod keyword specifies an upper boundary (read: modulus) which is not reached by returned numbers. The optional offset allows one to increment the returned value by a fixed offset.

A typical use-case for numgen is load-balancing:

Using numgen expression. ๐Ÿซถ

# round-robin between 192.168.10.100 and 192.168.20.200:
add rule nat prerouting dnat to numgen inc mod 2 map \
        { 0 : 192.168.10.100, 1 : 192.168.20.200 }

# probability-based with odd bias using intervals:
add rule nat prerouting dnat to numgen random mod 10 map \
        { 0-2 : 192.168.10.100, 3-9 : 192.168.20.200 }

๐Ÿงฌ HASH EXPRESSIONS ๐Ÿงฌ

jhash {ip saddr | ip6 daddr | tcp dport | udp sport | ether saddr} [. ...] mod NUM [ seed NUM ] [ offset NUM ]
symhash mod NUM [ offset NUM ]

Use a hashing function to generate a number. The functions available are jhash, known as Jenkins Hash, and symhash, for Symmetric Hash. The jhash requires an expression to determine the parameters of the packet header to apply the hashing, concatenations are possible as well. The value after the mod keyword specifies an upper boundary (read: modulus) which is not reached by returned numbers. The optional seed is used to specify an init value used as seed in the hashing function. The optional offset allows one to increment the returned value by a fixed offset.

A typical use-case for jhash and symhash is load-balancing:

Using hash expressions.

# load balance based on source ip between 2 ip addresses:
add rule nat prerouting dnat to jhash ip saddr mod 2 map \
        { 0 : 192.168.10.100, 1 : 192.168.20.200 }

# symmetric load balancing between 2 ip addresses:
add rule nat prerouting dnat to symhash mod 2 map \
        { 0 : 192.168.10.100, 1 : 192.168.20.200 }

๐ŸŒธ PAYLOAD EXPRESSIONS ๐ŸŒธ

Payload expressions refer to data from the packet's payload. Like, the actual stuff inside the packet โ€” very main character energy for your rules ๐Ÿ’…

๐ŸŽ€ ETHERNET HEADER EXPRESSION ๐ŸŽ€

ether {daddr | saddr | type}

Table 36. Ethernet header expression types

  • daddr โ€” Destination MAC address โ€” type ether_addr
  • saddr โ€” Source MAC address โ€” type ether_addr
  • type โ€” EtherType โ€” type ether_type

๐Ÿฆ‹ VLAN HEADER EXPRESSION ๐Ÿฆ‹

vlan {id | dei | pcp | type}

The vlan expression is used to match on the vlan header fields. Heads up bestie ๐Ÿ˜ญ โ€” this expression will not work in the ip, ip6 and inet families, unless the vlan interface is configured with the reorder_hdr off setting. The default is reorder_hdr on, which will automatically remove the vlan tag from the packet. See ip-link(8) for more information. For these families it's easier to match the vlan interface name instead, using the meta iif or meta iifname expression. iykyk ๐Ÿซถ

Table 37. VLAN header expression

  • id โ€” VLAN ID (VID) โ€” type integer (12 bit)
  • dei โ€” Drop Eligible Indicator โ€” type integer (1 bit)
  • pcp โ€” Priority code point โ€” type integer (3 bit)
  • type โ€” EtherType โ€” type ether_type

โœจ ARP HEADER EXPRESSION โœจ

arp {htype | ptype | hlen | plen | operation | saddr { ip | ether } | daddr { ip | ether }
No cap, that synopsis line above is exactly how the page gives it โ€” the curly braces close out where they close out. Copy it verbatim, don't go "fixing" it ๐Ÿ’€

Table 38. ARP header expression

  • htype โ€” ARP hardware type โ€” type integer (16 bit)
  • ptype โ€” EtherType โ€” type ether_type
  • hlen โ€” Hardware address len โ€” type integer (8 bit)
  • plen โ€” Protocol address len โ€” type integer (8 bit)
  • operation โ€” Operation โ€” type arp_op
  • saddr ether โ€” Ethernet sender address โ€” type ether_addr
  • daddr ether โ€” Ethernet target address โ€” type ether_addr
  • saddr ip โ€” IPv4 sender address โ€” type ipv4_addr
  • daddr ip โ€” IPv4 target address โ€” type ipv4_addr

๐Ÿ’œ IPV4 HEADER EXPRESSION ๐Ÿ’œ

ip {version | hdrlength | dscp | ecn | length | id | frag-off | ttl | protocol | checksum | saddr | daddr }

...and Table 39 is the full IPv4 header roster, bestie โ€” every field you can peek at, what it actually is, and what type you're getting back:

  • version โ€” IP header version (4). Type: integer (4 bit) โœจ
  • hdrlength โ€” IP header length including options. Type: integer (4 bit) โ€” note the literal FIXME scaling situation going on there ๐Ÿ™ˆ
  • dscp โ€” Differentiated Services Code Point. Type: dscp
  • ecn โ€” Explicit Congestion Notification. Type: ecn
  • length โ€” Total packet length. Type: integer (16 bit)
  • id โ€” IP ID. Type: integer (16 bit)
  • frag-off โ€” Fragment offset. Type: integer (16 bit)
  • ttl โ€” Time to live. Type: integer (8 bit)
  • protocol โ€” Upper layer protocol. Type: inet_proto
  • checksum โ€” IP header checksum. Type: integer (16 bit)
  • saddr โ€” Source address. Type: ipv4_addr
  • daddr โ€” Destination address. Type: ipv4_addr
โš ๏ธ Lowkey be careful when you're matching on ip length, okay? The Linux kernel might aggregate several packets into one big packet that is larger than MTU. And on top of that, if the GRO/GSO maximum size is larger than 65535 (peep man ip-link(8), specifically gro_ipv4_max_size and gso_ipv4_max_size), then ip length might be 0 for such jumbo packets ๐Ÿ˜ญ. meta length is your girl for that โ€” it lets you match on the packet length including the IP header size. Slay.

๐Ÿฉบ ICMP HEADER EXPRESSION

icmp {type | code | checksum | id | sequence | gateway | mtu}

This expression refers to ICMP header fields, periodt. When you use it in inet, bridge or netdev families, it will cause an implicit dependency on IPv4 to be created โ€” like it just invites IPv4 to the party whether you asked or not ๐Ÿซถ. So if you wanna match on unusual cases like ICMP over IPv6, you have to add an explicit meta protocol ip6 match to the rule. No cap, that's the whole vibe check.

Table 40, the ICMP field lineup:

  • type โ€” ICMP type field. Type: icmp_type
  • code โ€” ICMP code field. Type: integer (8 bit)
  • checksum โ€” ICMP checksum field. Type: integer (16 bit)
  • id โ€” ID of echo request/response. Type: integer (16 bit)
  • sequence โ€” sequence number of echo request/response. Type: integer (16 bit)
  • gateway โ€” gateway of redirects. Type: integer (32 bit)
  • mtu โ€” MTU of path MTU discovery. Type: integer (16 bit)

๐Ÿ“ฃ IGMP HEADER EXPRESSION

igmp {type | mrt | checksum | group}

Same energy, different protocol: this expression refers to IGMP header fields ๐Ÿ’œ. And yeah โ€” used in inet, bridge or netdev families, it also creates an implicit dependency on IPv4. To match on unusual cases like IGMP over IPv6, you gotta add an explicit meta protocol ip6 match to the rule. Iconic behavior, honestly.

Table 41, IGMP edition:

  • type โ€” IGMP type field. Type: igmp_type
  • mrt โ€” IGMP maximum response time field. Type: integer (8 bit)
  • checksum โ€” IGMP checksum field. Type: integer (16 bit)
  • group โ€” Group address. Type: integer (32 bit)

๐ŸŒˆ IPV6 HEADER EXPRESSION

ip6 {version | dscp | ecn | flowlabel | length | nexthdr | hoplimit | saddr | daddr}

This expression refers to the ipv6 header fields ๐Ÿฆ‹.

โš ๏ธ Real talk โ€” caution when using ip6 nexthdr. The value only refers to the next header, i.e. ip6 nexthdr tcp will only match if the ipv6 packet does not contain any extension headers ๐Ÿ˜ณ. Packets that are fragmented, or that e.g. contain routing extension headers, will not be matched. So if you wish to match the real transport header and ignore any additional extension headers instead, please use meta l4proto. That's the move, iykyk ๐Ÿ’…

Okay so Table 42. IPv6 header expression โ€” here's the whole ip6 moment, every keyword, what it even is, and its type ๐Ÿ’–

  • version โ€” IP header version (always 6 bestie) โ€” type: integer (4 bit)
  • dscp โ€” Differentiated Services Code Point โ€” type: dscp
  • ecn โ€” Explicit Congestion Notification โ€” type: ecn
  • flowlabel โ€” Flow label โ€” type: integer (20 bit)
  • length โ€” Payload length โ€” type: integer (16 bit)
  • nexthdr โ€” Nexthdr protocol โ€” type: inet_proto
  • hoplimit โ€” Hop limit โ€” type: integer (8 bit)
  • saddr โ€” Source address โ€” type: ipv6_addr
  • daddr โ€” Destination address โ€” type: ipv6_addr

Careful with matching on ip6 length, fr fr ๐Ÿšจ The Linux kernel might aggregate several packets into one big packet that is larger than MTU. Moreover, if GRO/GSO maximum size is larger than 65535 (see man ip-link(8), specifically gro_max_size and gso_max_size), then ip6 length might be 0 for such jumbo packets. meta length allows you to match on the packet length including the IPv6 header size.

Using ip6 header expressions. Like, actually using them ๐Ÿ’…

# matching if first extension header indicates a fragment
ip6 nexthdr ipv6-frag

๐ŸŒˆ ICMPV6 HEADER EXPRESSION ๐ŸŒˆ

icmpv6 {type | code | checksum | parameter-problem | packet-too-big | id | sequence | max-delay | taddr | daddr}

This expression refers to ICMPv6 header fields. When using it in inet, bridge or netdev families, it will cause an implicit dependency on IPv6 to be created ๐Ÿ‘€. To match on unusual cases like ICMPv6 over IPv4, one has to add an explicit meta protocol ip match to the rule. iykyk ๐Ÿซถ

Table 43. ICMPv6 header expression โ€” the full roster โœจ

  • type โ€” ICMPv6 type field โ€” type: icmpv6_type
  • code โ€” ICMPv6 code field โ€” type: integer (8 bit)
  • checksum โ€” ICMPv6 checksum field โ€” type: integer (16 bit)
  • parameter-problem โ€” pointer to problem โ€” type: integer (32 bit)
  • packet-too-big โ€” oversized MTU โ€” type: integer (32 bit)
  • id โ€” ID of echo request/response โ€” type: integer (16 bit)
  • sequence โ€” sequence number of echo request/response โ€” type: integer (16 bit)
  • max-delay โ€” maximum response delay of MLD queries โ€” type: integer (16 bit)
  • taddr โ€” target address of neighbor solicit/advert, redirect or MLD โ€” type: ipv6_addr
  • daddr โ€” destination address of redirect โ€” type: ipv6_addr

๐Ÿฆ‹ TCP HEADER EXPRESSION ๐Ÿฆ‹

tcp {sport | dport | sequence | ackseq | doff | reserved | flags | window | checksum | urgptr}

TCP header expression (Table 44) ๐Ÿงต

okay so tcp gives you the whole TCP header to poke at, and every field is its own little keyword. here's the full roster:

  • sport โ€” source port, type inet_service ๐ŸŽ€
  • dport โ€” destination port, type inet_service ๐ŸŽ€
  • sequence โ€” the sequence number, type integer (32 bit)
  • ackseq โ€” the acknowledgement number, type integer (32 bit)
  • doff โ€” data offset, type integer (4 bit) ... and yes, the manpage literally says FIXME scaling right there, no cap, that's a real note in the docs ๐Ÿ’€
  • reserved โ€” the reserved area, type integer (4 bit)
  • flags โ€” TCP flags, type tcp_flag
  • window โ€” the window, type integer (16 bit)
  • checksum โ€” checksum, type integer (16 bit)
  • urgptr โ€” urgent pointer, type integer (16 bit)

UDP header expression (Table 45) ๐Ÿฆ‹

the grammar is short and sweet bestie:

udp {sport | dport | length | checksum}

and the fields themselves:

  • sport โ€” source port, type inet_service โœจ
  • dport โ€” destination port, type inet_service โœจ
  • length โ€” total packet length, type integer (16 bit)
  • checksum โ€” checksum, type integer (16 bit)

lowkey the most chill header out there, it's giving minimalism ๐Ÿ’…


UDP-Lite header expression (Table 46) ๐ŸŒธ

she's UDP's artsy cousin, and she's smaller:

udplite {sport | dport | checksum}
  • sport โ€” source port, type inet_service ๐Ÿซถ
  • dport โ€” destination port, type inet_service ๐Ÿซถ
  • checksum โ€” checksum, type integer (16 bit)

that's it, that's the whole vibe. no length here, she doesn't do that ๐ŸŽ€


SCTP header expression (Table 47) ๐Ÿ”ฅ

okay SCTP is the main character of this section, ngl. she's got a whole grammar and everything. here it is, verbatim, don't come for me:

sctp {sport | dport | vtag | checksum}
sctp chunk CHUNK [ FIELD ]

CHUNK := data | init | init-ack | sack | heartbeat |
           heartbeat-ack | abort | shutdown | shutdown-ack | error |
           cookie-echo | cookie-ack | ecne | cwr | shutdown-complete
           | asconf-ack | forward-tsn | asconf

FIELD := COMMON_FIELD | DATA_FIELD | INIT_FIELD | INIT_ACK_FIELD |
           SACK_FIELD | SHUTDOWN_FIELD | ECNE_FIELD | CWR_FIELD |
           ASCONF_ACK_FIELD | FORWARD_TSN_FIELD | ASCONF_FIELD

COMMON_FIELD := type | flags | length
DATA_FIELD := tsn | stream | ssn | ppid
INIT_FIELD := init-tag | a-rwnd | num-outbound-streams |
                num-inbound-streams | initial-tsn
INIT_ACK_FIELD := INIT_FIELD
SACK_FIELD := cum-tsn-ack | a-rwnd | num-gap-ack-blocks |
                num-dup-tsns
SHUTDOWN_FIELD := cum-tsn-ack
ECNE_FIELD := lowest-tsn
CWR_FIELD := lowest-tsn
ASCONF_ACK_FIELD := seqno
FORWARD_TSN_FIELD := new-cum-tsn
ASCONF_FIELD := seqno

and the actual header fields you can grab:

  • sport โ€” source port, type inet_service โญ
  • dport โ€” destination port, type inet_service โญ
  • vtag โ€” verification tag, type integer (32 bit)
  • checksum โ€” checksum, type integer (32 bit)
  • chunk โ€” searches for a chunk in the packet. type-wise it's a little special: without FIELD, it's a boolean indicating existence ๐Ÿ‘‘

so sctp chunk data = "does this packet have a data chunk, yes or no", and sctp chunk data tsn = "gimme the actual tsn field from it". iconique behaviour, honestly ๐Ÿงš

๐Ÿ“‹ Table 48 โ€” the SCTP chunk fields, decoded for you

okay bestie, this is the big one โ€” every field you can pull out of an SCTP chunk, how wide it is, which chunk it actually shows up in, and what it means. no cap, it's a lot, but we're getting through it together ๐Ÿ’–

  • type โ€” 8 bits โ€” shows up in all chunks โ€” lowkey not useful, because it's defined by the chunk type itself
  • flags โ€” 8 bits โ€” shows up in all chunks โ€” the semantics are defined on a per-chunk basis
  • length โ€” 16 bits โ€” shows up in all chunks โ€” length of this chunk in bytes, excluding padding
  • tsn โ€” 32 bits โ€” data chunks โ€” transmission sequence number
  • stream โ€” 16 bits โ€” data chunks โ€” stream identifier
  • ssn โ€” 16 bits โ€” data chunks โ€” stream sequence number
  • ppid โ€” 32 bits โ€” data chunks โ€” payload protocol identifier
  • init-tag โ€” 32 bits โ€” init, init-ack โ€” initiate tag
  • a-rwnd โ€” 32 bits โ€” init, init-ack, sack โ€” advertised receiver window credit
  • num-outbound-streams โ€” 16 bits โ€” init, init-ack โ€” number of outbound streams
  • num-inbound-streams โ€” 16 bits โ€” init, init-ack โ€” number of inbound streams
  • initial-tsn โ€” 32 bits โ€” init, init-ack โ€” initial transmit sequence number
  • cum-tsn-ack โ€” 32 bits โ€” sack, shutdown โ€” cumulative transmission sequence number acknowledged
  • num-gap-ack-blocks โ€” 16 bits โ€” sack โ€” number of Gap Ack Blocks included
  • num-dup-tsns โ€” 16 bits โ€” sack โ€” number of duplicate transmission sequence numbers received
  • lowest-tsn โ€” 32 bits โ€” ecne, cwr โ€” lowest transmission sequence number
  • seqno โ€” 32 bits โ€” asconf-ack, asconf โ€” sequence number
  • new-cum-tsn โ€” 32 bits โ€” forward-tsn โ€” new cumulative transmission sequence number

like, that's the whole roster ๐Ÿซถ screenshot it, memorise it, whatever works for you.


๐ŸŒˆ DCCP HEADER EXPRESSION ๐ŸŒˆ

and now for something completely different โ€” DCCP headers, which are honestly so much chiller:

dccp {sport | dport | type}

that's it. that's the whole vibe โœจ sport, dport, or type โ€” pick your fighter, the expression gives you the field you asked for. iconic behaviour honestly ๐ŸŽ€

Table 49. DCCP header expression ๐ŸŽ€

  • sport โ€” source port, typed as inet_service
  • dport โ€” destination port, typed as inet_service
  • type โ€” packet type, typed as dccp_pkttype

AUTHENTICATION HEADER EXPRESSION ๐Ÿซถ

ah {nexthdr | hdrlength | reserved | spi | sequence}

Table 50. AH header expression

  • nexthdr โ€” next header protocol, typed as inet_proto
  • hdrlength โ€” AH header length, typed as integer (8 bit)
  • reserved โ€” reserved area, typed as integer (16 bit)
  • spi โ€” Security Parameter Index, typed as integer (32 bit)
  • sequence โ€” sequence number, typed as integer (32 bit)

ENCRYPTED SECURITY PAYLOAD HEADER EXPRESSION โœจ

esp {spi | sequence}

Table 51. ESP header expression

  • spi โ€” Security Parameter Index, typed as integer (32 bit)
  • sequence โ€” sequence number, typed as integer (32 bit)

IPCOMP HEADER EXPRESSION ๐ŸŒธ

comp {nexthdr | flags | cpi}

Table 52. IPComp header expression

  • nexthdr โ€” next header protocol, typed as inet_proto
  • flags โ€” flags, typed as bitmask
  • cpi โ€” compression Parameter Index, typed as integer (16 bit)

GRE HEADER EXPRESSION ๐Ÿฆ‹

gre {flags | version | protocol}
gre ip {version | hdrlength | dscp | ecn | length | id | frag-off | ttl | protocol | checksum | saddr | daddr }
gre ip6 {version | dscp | ecn | flowlabel | length | nexthdr | hoplimit | saddr | daddr}

The gre expression is literally your girl for matching on the gre header fields โ€” and it also lets you reach inside and match on the IPv4 or IPv6 packet nestled within that gre header. it's giving nested-encapsulation realness ๐Ÿ’…

Table 53. GRE header expression

  • flags โ€” checksum, routing, key, sequence and strict source route flags, typed as integer (5 bit)
  • version โ€” gre version field, 0 for GRE and 1 for PPTP, typed as integer (3 bit)
  • protocol โ€” EtherType of encapsulated packet, typed as integer (16 bit)

Matching inner IPv4 destination address encapsulated in gre โ€” yes bestie, this is the whole vibe:

netdev filter ingress gre ip daddr 9.9.9.9 counter

GENEVE HEADER EXPRESSION ๐Ÿ’œ

geneve {vni | flags}
geneve ether {daddr | saddr | type}
geneve vlan {id | dei | pcp | type}
geneve ip {version | hdrlength | dscp | ecn | length | id | frag-off | ttl | protocol | checksum | saddr | daddr }
geneve ip6 {version | dscp | ecn | flowlabel | length | nexthdr | hoplimit | saddr | daddr}
geneve tcp {sport | dport | sequence | ackseq | doff | reserved | flags | window | checksum | urgptr}
geneve udp {sport | dport | length | checksum}

So the geneve expression matches on the geneve header fields. Heads up though: the geneve header encapsulates an ethernet frame within a udp packet, so this expression requires that you restrict your matching to udp packets (usually at port 6081 according to IANA-assigned ports). no skipping that part, it's not optional ๐Ÿ™ˆ

Table 54. GENEVE header expression

  • protocol โ€” EtherType of encapsulated packet, typed as integer (16 bit)
  • vni โ€” Virtual Network ID (VNI), typed as integer (24 bit)

Matching inner TCP destination port encapsulated in geneve โ€” look at her go:

netdev filter ingress udp dport 4789 geneve tcp dport 80 counter

GRETAP HEADER EXPRESSION ๐Ÿ“

gretap {vni | flags}
gretap ether {daddr | saddr | type}
gretap vlan {id | dei | pcp | type}
gretap ip {version | hdrlength | dscp | ecn | length | id | frag-off | ttl | protocol | checksum | saddr | daddr }
gretap ip6 {version | dscp | ecn | flowlabel | length | nexthdr | hoplimit | saddr | daddr}
gretap tcp {sport | dport | sequence | ackseq | doff | reserved | flags | window | checksum | urgptr}
gretap udp {sport | dport | length | checksum}

The gretap expression is for matching on the encapsulated ethernet frame within the gre header. And when you wanna match on the gre header fields themselves? That's what the gre expression is for, bestie โ€” different tool, different job ๐Ÿ‘‘

Matching inner TCP destination port encapsulated in gretap:

netdev filter ingress gretap tcp dport 80 counter

๐Ÿฆ‹ VXLAN HEADER EXPRESSION ๐Ÿฆ‹

vxlan {vni | flags}
vxlan ether {daddr | saddr | type}
vxlan vlan {id | dei | pcp | type}
vxlan ip {version | hdrlength | dscp | ecn | length | id | frag-off | ttl | protocol | checksum | saddr | daddr }
vxlan ip6 {version | dscp | ecn | flowlabel | length | nexthdr | hoplimit | saddr | daddr}
vxlan tcp {sport | dport | sequence | ackseq | doff | reserved | flags | window | checksum | urgptr}
vxlan udp {sport | dport | length | checksum}

Okay bestie, the vxlan expression is how you match on the vxlan header fields. The vxlan header encapsulates a ethernet frame within a udp packet. This expression requires that you restrict the matching to udp packets (usually at port 4789 according to IANA-assigned ports). Like, donโ€™t just let it vibe-check every packet on the block, okay? ๐Ÿ’…

Table 55. VXLAN header expression

  • flags โ€” vxlan flags, type: integer (8 bit).
  • vni โ€” Virtual Network ID (VNI), type: integer (24 bit).

Matching inner TCP destination port encapsulated in vxlan:

netdev filter ingress udp dport 4789 vxlan tcp dport 80 counter

๐ŸŒธ RAW PAYLOAD EXPRESSION ๐ŸŒธ

@base,offset,length

The raw payload expression instructs to load length bits starting at offset bits. Bit 0 refers to the very first bit โ€” in the C programming language, this corresponds to the topmost bit, i.e. 0x80 in case of an octet. They are useful to match headers that do not have a human-readable template expression yet. Note that nft will not add dependencies for Raw payload expressions. If you e.g. want to match protocol fields of a transport header with protocol number 5, you need to manually exclude packets that have a different transport header, for instance by using meta l4proto 5 before the raw expression. No cap, the dependency fairy is not coming to save you here ๐Ÿงš

Table 56. Supported payload protocol bases

  • ll โ€” Link layer, for example the Ethernet header.
  • nh โ€” Network header, for example IPv4 or IPv6.
  • th โ€” Transport Header, for example TCP.
  • ih โ€” Inner Header / Payload, i.e. after the L4 transport level header.

Matching destination port of both UDP and TCP:

inet filter input meta l4proto {tcp, udp} @th,16,16 { 53, 80 }

The above can also be written as:

inet filter input meta l4proto {tcp, udp} th dport { 53, 80 }

It is more convenient, but like the raw expression notation no dependencies are created or checked. It is the users responsibility to restrict matching to those header types that have a notion of ports. Otherwise, rules using raw expressions will errnously match unrelated packets, e.g. mis-interpreting ESP packets SPI field as a port. Thatโ€™s the drama โ€” raw expressions are powerful but they will absolutely not hold your hand. ๐Ÿ˜ญ

Rewrite arp packet target hardware address if target protocol address matches a given address:

input meta iifname enp2s0 arp ptype 0x0800 arp htype 1 arp hlen 6 arp plen 4 @nh,192,32 0xc0a88f10 @nh,144,48 set 0x112233445566 accept

โœจ EXTENSION HEADER EXPRESSIONS โœจ

Extension header expressions refer to data from variable-sized protocol headers, such as IPv6 extension headers, TCP options and IPv4 options.

nftables currently supports matching (finding) a given ipv6 extension header, TCP option or IPv4 option.

hbh {nexthdr | hdrlength}
frag {nexthdr | frag-off | more-fragments | id}
rt {nexthdr | hdrlength | type | seg-left}
dst {nexthdr | hdrlength}
mh {nexthdr | hdrlength | checksum | type}
srh {flags | tag | sid | seg-left}
tcp option {eol | nop | maxseg | window | sack-perm | sack | sack0 | sack1 | sack2 | sack3 | timestamp | mptcp } tcp_option_field
ip option { lsrr | ra | rr | ssrr } ip_option_field

The following syntaxes are valid only in a relational expression with boolean type on right-hand side for checking header existence only:

exthdr {hbh | frag | rt | dst | mh}
tcp option {eol | nop | maxseg | window | sack-perm | sack | sack0 | sack1 | sack2 | sack3 | timestamp | mptcp }
ip option { lsrr | ra | rr | ssrr }
dccp option dccp_option_type

Table 57. IPv6 extension headers

  • hbh โ€” Hop by Hop.
  • rt โ€” Routing Header.
  • frag โ€” Fragmentation header.
  • dst โ€” dst options.
  • mh โ€” Mobility Header.
  • srh โ€” Segment Routing Header.

Table 58. TCP Options ๐ŸŒธ โ€” this is literally the whole menu of TCP option keywords bestie, plus what fields each one gives you to play with:

  • eol โ€” End if option list ๐Ÿ โ€” fields: -
  • nop โ€” 1 Byte TCP Nop padding option โ€” fields: -
  • maxseg โ€” TCP Maximum Segment Size โ€” fields: length, size
  • window โ€” TCP Window Scaling โ€” fields: length, count
  • sack-perm โ€” TCP SACK permitted โ€” fields: length
  • sack โ€” TCP Selective Acknowledgement (alias of block 0) โ€” fields: length, left, right
  • sack0 โ€” TCP Selective Acknowledgement (block 0) โ€” fields: length, left, right
  • sack1 โ€” TCP Selective Acknowledgement (block 1) โ€” fields: length, left, right
  • sack2 โ€” TCP Selective Acknowledgement (block 2) โ€” fields: length, left, right
  • sack3 โ€” TCP Selective Acknowledgement (block 3) โ€” fields: length, left, right
  • timestamp โ€” TCP Timestamps โ€” fields: length, tsval, tsecr
  • mptcp โ€” Multipath TCP โ€” fields: subtype

Data types can be queried with nft describe tcp option keyword [ fieldname ]. ๐Ÿ’…

TCP option matching also supports raw expression syntax to access arbitrary options โ€” yes you can just vibe in there manually:

tcp option

tcp option @number,offset,length

Table 59. IP Options ๐Ÿฆ‹ โ€” the IP-flavoured options, same energy:

  • lsrr โ€” Loose Source Route โ€” fields: length, ptr, addr
  • ra โ€” Router Alert โ€” fields: length, value
  • rr โ€” Record Route โ€” fields: length, ptr, addr
  • ssrr โ€” Strict Source Route โ€” fields: length, ptr, addr

And here's the example reel, bestie ๐ŸŽ€ โ€” a handful of little snippets doing their thing:

finding TCP options:

filter input tcp option sack-perm exists counter

matching TCP options:

filter input tcp option maxseg size lt 536

matching IPv6 exthdr:

ip6 filter input frag more-fragments 1 counter

finding IP option:

filter input ip option lsrr exists counter

finding DCCP option:

filter input dccp option 40 exists counter

๐Ÿ’œ CONNTRACK EXPRESSIONS ๐Ÿ’œ

Conntrack expressions refer to meta data of the connection tracking entry associated with a packet. Basically: all the receipts conntrack is keeping about that connection ๐Ÿ‘€

There are three types of conntrack expressions. Some conntrack expressions require the flow direction before the conntrack key, others must be used directly because they are direction agnostic. The packets, bytes and avgpkt keywords can be used with or without a direction. If the direction is omitted, the sum of the original and the reply direction is returned. Same deal for the zone โ€” if a direction is given, the zone is only matched if the zone id is tied to the given direction. Directionless girlies stay summing both ways, no cap ๐Ÿ’ซ

ct {state | direction | status | mark | expiration | helper | label | count | id}
ct [original | reply] {l3proto | protocol | bytes | packets | avgpkt | zone}
ct {original | reply} {proto-src | proto-dst}
ct {original | reply} {ip | ip6} {saddr | daddr}

The conntrack-specific types in this table are described in the sub-section CONNTRACK TYPES above. โฌ†๏ธ (iykyk, go scroll back up bestie)

Table 60. Conntrack expressions ๐Ÿ’…

Okay so this is the full menu of conntrack things you can match on โ€” every single one, no skips, bestie:

  • state โ€” the state of the connection. Type: ct_state.
  • direction โ€” which way the packet is going, relative to the connection. Type: ct_dir.
  • status โ€” the status of the connection. Type: ct_status.
  • mark โ€” the connection mark. Type: mark.
  • expiration โ€” when this connection expires. Type: time.
  • helper โ€” the helper that's associated with the connection. Type: string.
  • label โ€” conntrack label bit, or the symbolic name defined in connlabel.conf in the nftables include path. Type: ct_label.
  • l3proto โ€” layer 3 protocol of the connection. Type: nf_proto.
  • saddr โ€” source address of the connection, for the given direction. Type: ipv4_addr/ipv6_addr.
  • daddr โ€” destination address of the connection, for the given direction. Type: ipv4_addr/ipv6_addr.
  • protocol โ€” layer 4 protocol of the connection, for the given direction. Type: inet_proto.
  • proto-src โ€” layer 4 protocol source, for the given direction. Type: integer (16 bit).
  • proto-dst โ€” layer 4 protocol destination, for the given direction. Type: integer (16 bit).
  • packets โ€” packet count seen in the given direction, or the sum of original and reply. Type: integer (64 bit).
  • bytes โ€” byte count seen; see the description for the packets keyword. Type: integer (64 bit).
  • avgpkt โ€” average bytes per packet; see the description for the packets keyword. Type: integer (64 bit).
  • zone โ€” conntrack zone. Type: integer (16 bit).
  • count โ€” number of current connections. Type: integer (32 bit).
  • id โ€” connection id. Type: ct_id.

And here's the actual glow-up use case โ€” restricting how many parallel connections one server can have ๐Ÿซถ:

nft add set filter ssh_flood '{ type ipv4_addr; flags dynamic; }'
nft add rule filter input tcp dport 22 add @ssh_flood '{ ip saddr ct count over 2 }' reject

โœจ STATEMENTS โœจ

Statements are the do-something parts, bestie. They're the actions. Some of them mess with control flow (like return, jumping to another chain, accept, or drop) and some of them just do a thing โ€” log it, reject the packet, etc.

So there's exactly two flavors of statement, and the distinction is lowkey important:

  • Terminal statements unconditionally end evaluation of the current rule. Like, that's it, we're done here, periodt.
  • Non-terminal statements either only conditionally end evaluation, or never end it at all โ€” in other words, from the rule-evaluation perspective, they're just vibing passively in the background.

You can stack an arbitrary amount of non-terminal statements in a rule. But terminal statements? Only one, and it has to be the final statement. That's the rule, no cap. ๐Ÿ‘‘

๐Ÿ”ฅ VERDICT STATEMENTS

Verdict statements are the ones that change control flow across your whole ruleset and hand down the actual policy decisions for packets. Main character energy:

{accept | drop | continue | return}
{jump | goto} CHAIN

CHAIN := chain_name | { statement ... }

accept and drop are absolute verdicts โ€” they terminate chain evaluation, as if the packet had reached the end of the base chain with that same policy decision set. If you want the full lore, go read the section called โ€œOVERALL EVALUATION OF THE RULESETโ€. โœจ

  • accept โ€” terminate evaluation early. Evaluation then continues in the next base chain of higher or possibly equal priority from the same hook, or in the first base chain of a later hook, if there is one. Which means โ€” and this is the messy part โ€” the packet can still get dropped in another base chain, or in any chain called from it. For example: an accept verdict in a chain of the forward hook still leaves room for someone to drop the packet in another forward hook base chain (or a chain called from it) that has a higher priority number, or in a chain attached to the postrouting hook. ๐Ÿ˜ญ It's giving "not actually the final say".
  • drop โ€” bye bye packet ๐Ÿ’€ drop it immediately and terminate ruleset evaluation, like, full stop. No further evaluation happens at all. And bestie, listen: it is not possible to override a drop verdict. Not a thing. Periodt.
  • jump CHAIN โ€” save your spot ๐Ÿ“Œ store the current position in the call stack of chains, then keep evaluating starting at the first rule of CHAIN. When you hit the end of CHAIN, an implicit return verdict gets issued. And if an absolute verdict gets issued (or implied by a verdict-like statement) inside CHAIN, evaluation terminates exactly like described above. Slay.
  • goto CHAIN โ€” literally jump except the current position is not stored in the call stack of chains. Same vibes, no save point.
  • return โ€” end evaluation of the current chain, pop the most recently added position off the call stack of chains, and keep evaluating after that position ๐Ÿซถ. And when there's nothing to pop โ€” which is the case when the current chain is either the base chain or a regular chain that was reached solely via goto verdicts โ€” it ends evaluation of the current base chain (and any regular chains called from it) using the base chain's policy as the implicit verdict.
  • continue โ€” just keep going with the next rule โœจ. This is the default behaviour when a rule issues no verdict at all. Main character energy: move on.

So instead of naming an existing regular chain in CHAIN, you can also just make an anonymous chain ad-hoc ๐ŸŽ€ Like with anonymous sets, it can't be referenced from another rule, and it gets removed along with the rule that contains it. It's giving limited edition.

Everything above applies analogously to statements that imply a verdict, ngl: redirect, dnat, snat and masquerade internally issue an accept verdict at the end of their respective actions. reject and synproxy internally issue a drop verdict at the end of their respective actions. So those statements behave just like their implied verdicts, but with side effects ๐Ÿ˜Œ.

๐ŸŒธ Using verdict statements ๐ŸŒธ

# process packets from eth0 and the internal network in from_lan
# chain, drop all packets from eth0 with different source addresses.

filter input iif eth0 ip saddr 192.168.0.0/24 jump from_lan
filter input iif eth0 drop

# jump and goto statements support anonymous chain creation
filter input iif eth0 jump { ip saddr 192.168.0.0/24 drop ; udp dport domain drop; }

๐Ÿงš PAYLOAD STATEMENT ๐Ÿงš

payload_expression set value

The payload statement alters packet content ๐Ÿ’… it can be used for example to set the ip DSCP (diffserv) header field or ipv6 flow labels.

route some packets instead of bridging.

# redirect tcp:http from 192.160.0.0/16 to local machine for routing instead of bridging
# assumes 00:11:22:33:44:55 is local MAC address.
bridge input meta iif eth0 ip saddr 192.168.0.0/16 tcp dport 80 meta pkttype set host ether daddr set 00:11:22:33:44:55

Set IPv4 DSCP header field.

ip forward ip dscp set 42

๐Ÿฆ‹ EXTENSION HEADER STATEMENT ๐Ÿฆ‹

extension_header_expression set value

The extension header statement alters packet content in variable-sized headers ๐Ÿ‘‘ currently this can be used to alter the TCP Maximum segment size of packets, similar to the TCPMSS target in iptables.

change tcp mss.

tcp flags syn tcp option maxseg size set 1360
# set a size based on route information:
tcp flags syn tcp option maxseg size set rt mtu

You can also remove tcp options via the reset keyword ๐Ÿซถ.

remove tcp option.

tcp flags syn reset tcp option sack-perm

๐Ÿ’– LOG STATEMENT ๐Ÿ’–

log [prefix quoted_string] [level syslog-level] [flags log-flags]
log group nflog_group [prefix quoted_string] [queue-threshold value] [snaplen size]
log level audit

The log statement enables logging of matching packets ๐Ÿ“. When this statement is used from a rule, the Linux kernel will print some information on all matching packets โ€” like header fields and stuff โ€” via the kernel log, where it can be read with dmesg(1) or read in the syslog.

In the second form of invocation (if nflog_group is specified), the Linux kernel will pass the packet to nfnetlink_log, which will send the log through a netlink socket to the specified group. One userspace process may subscribe to the group to receive the logs ๐Ÿ‘€ โ€” see man(8) ulogd for the Netfilter userspace log daemon, and the libnetfilter_log documentation for details in case you would like to develop a custom program to digest your logs.

In the third form of invocation (if level audit is specified), the Linux kernel writes a message into the audit buffer suitably formatted for reading with auditd. Therefore no further formatting options (such as prefix or flags) are allowed in this mode ๐Ÿšซ.

This is a non-terminating statement, so rule evaluation continues after the packet is logged. It's giving "noted, moving on".

Table 61. log statement options

  • prefix โ€” log message prefix ๐Ÿ’ฌ โ€” type: quoted string
  • level โ€” syslog level of logging โ€” type: string: emerg, alert, crit, err, warn [default], notice, info, debug, audit
  • group โ€” NFLOG group to send messages to โ€” type: unsigned integer (16 bit)
  • snaplen โ€” length of packet payload to include in netlink message โ€” type: unsigned integer (32 bit)
  • queue-threshold โ€” number of packets to queue inside the kernel before sending them to userspace โ€” type: unsigned integer (32 bit)

Table 62. log-flags

  • tcp sequence โ€” log TCP sequence numbers ๐Ÿ”ข
  • tcp options โ€” log options from the TCP packet header
  • ip options โ€” log options from the IP/IPv6 packet header
  • skuid โ€” log the userid of the process which generated the packet
  • ether โ€” decode MAC addresses and protocol ๐ŸŽ€
  • all โ€” enable all log flags listed above ๐Ÿ‘‘

Using log statement.

# log the UID which generated the packet and ip options
ip filter output log flags skuid flags ip options

# log the tcp sequence numbers and tcp options from the TCP packet
ip filter output log flags tcp sequence,options

# enable all supported log flags
ip6 filter output log flags all

๐Ÿ˜ญ REJECT STATEMENT ๐Ÿ˜ญ

reject [ with REJECT_WITH ]

REJECT_WITH := icmp icmp_reject_code |
                 icmpv6 icmpv6_reject_code |
                 icmpx icmpx_reject_code |
                 tcp reset

So like, a reject statement literally tries to yeet an error packet back at whoever sent the matched packet, and then internally issues a drop verdict. So yeah, it's a terminating statement, with every single consequence that comes with that (go peek at the section called โ€œOVERALL EVALUATION OF THE RULESETโ€ and the section called โ€œVERDICT STATEMENTSโ€ if you need the tea โ˜•). Heads up though: this statement is only valid in base chains that use the prerouting, input, forward or output hooks, plus regular chains that are only called from those chains. No exceptions bestie ๐Ÿ’…

Table 63. Keywords you can use to reject when specifying the ICMP code โœจ

  • net-unreachable โ†’ 0
  • host-unreachable โ†’ 1
  • prot-unreachable โ†’ 2
  • port-unreachable โ†’ 3
  • frag-needed โ†’ 4
  • net-prohibited โ†’ 9
  • host-prohibited โ†’ 10
  • admin-prohibited โ†’ 13

Table 64. Keywords you can use to reject when specifying the ICMPv6 code ๐Ÿฆ‹

  • no-route โ†’ 0
  • admin-prohibited โ†’ 1
  • addr-unreachable โ†’ 3
  • port-unreachable โ†’ 4
  • policy-fail โ†’ 5
  • reject-route โ†’ 6

The ICMPvX Code type abstraction is basically a set of values that overlap between the ICMP and ICMPv6 Code types, and it's the one you use from the inet family. iykyk ๐ŸŒˆ

Table 65. Keywords you can use when specifying the ICMPvX code ๐ŸŽ€

  • no-route โ†’ 0
  • port-unreachable โ†’ 1
  • host-unreachable โ†’ 2
  • admin-prohibited โ†’ 3

The common default ICMP code to reject is port-unreachable. That's the vibe, that's the default ๐Ÿ’–

Also lowkey important: in the bridge family, the reject statement is only allowed in base chains that hook into input or prerouting. Fr fr, don't try it anywhere else ๐Ÿ™ˆ

๐Ÿ”ข COUNTER STATEMENT

A counter statement sets the hit count of packets, along with the number of bytes. It's giving "I'm keeping receipts" energy ๐Ÿ’€

counter packets number bytes number
counter { packets number | bytes number }

๐Ÿงต CONNTRACK STATEMENT

The conntrack statement is your go-to for setting the conntrack mark and conntrack labels. Slay.

ct {mark | event | label | zone} set value

So the ct statement sets meta data that's associated with a connection. Big thing to know: the zone id has to be assigned before a conntrack lookup takes place โ€” like, this has to be done in prerouting and possibly output (that's if locally generated packets need to be placed in a distinct zone), with a hook priority of raw (-300). Don't skip that step, bestie ๐Ÿ˜ญ

And unlike iptables, where the helper assignment happens in the raw table, here the helper needs to be assigned after a conntrack entry has been found. Which basically means it will not work when used with hook priorities equal to or before -200. Not me warning you twice ๐Ÿ’…

Table 66. Conntrack statement types ๐Ÿ‘‘

  • event โ€” conntrack event bits โ€” value: bitmask, integer (32 bit)
  • helper โ€” name of ct helper object to assign to the connection โ€” value: quoted string
  • mark โ€” Connection tracking mark โ€” value: mark
  • label โ€” Connection tracking label โ€” value: label
  • zone โ€” conntrack zone โ€” value: integer (16 bit)

Save packet nfmark in conntrack, iconic behaviour:

ct mark set meta mark

Set zone mapped via interface โ€” chef's kiss example โœจ

table inet raw {
  chain prerouting {
      type filter hook prerouting priority raw;
      ct zone set iif map { "eth1" : 1, "veth1" : 2 }
  }
  chain output {
      type filter hook output priority raw;
      ct zone set oif map { "eth1" : 1, "veth1" : 2 }
  }
}

Restrict events reported by ctnetlink (look at her go ๐Ÿฆ‹):

ct event set new,related,destroy

๐Ÿšซ NOTRACK STATEMENT

The notrack statement lets you disable connection tracking for certain packets. Periodt.

notrack
Ngl, for this statement to actually be effective, it has to be applied to packets before a conntrack lookup happens. So it needs to sit in a chain with either the prerouting or output hook, and a hook priority of -300 (raw) or less. Put it anywhere else and it's just decoration ๐Ÿ’€

See SYNPROXY STATEMENT for an example usage. ๐Ÿ’–


๐Ÿท๏ธ META STATEMENT

A meta statement sets the value of a meta expression. The existing meta fields are: priority, mark, pkttype, nftrace.

meta {mark | priority | pkttype | nftrace | broute} set value

A meta statement sets meta data that's associated with a packet. Very demure, very mindful ๐ŸŽ€

Table 67. Meta statement types ๐ŸŒธ

  • priority โ€” TC packet priority โ€” value: tc_handle
  • mark โ€” Packet mark โ€” value: mark
  • pkttype โ€” packet type โ€” value: pkt_type
  • nftrace โ€” ruleset packet tracing on/off. Use monitor trace command to watch traces โ€” value: 0, 1
  • broute โ€” broute on/off. packets are routed instead of being bridged โ€” value: 0, 1

๐Ÿ’ง LIMIT STATEMENT ๐Ÿ’ง

okay so this one is literally the rate-limiter of your dreams, bestie. watch:

limit rate [over] packet_number / TIME_UNIT [burst packet_number packets]
limit rate [over] byte_number BYTE_UNIT / TIME_UNIT [burst byte_number BYTE_UNIT]

TIME_UNIT := second | minute | hour | day
BYTE_UNIT := bytes | kbytes | mbytes

so a limit statement matches at a limited rate, using a token bucket filter (yes, actual token bucket, we love a classic ๐ŸŒˆ). a rule with this statement will keep matching until the limit is reached โ€” that's the whole vibe check. pair it with the log statement and congrats, you've got yourself limited logging ๐ŸŽ€. the optional over keyword is what makes it match over the specified rate.

now the burst value? that's your bucket size, a.k.a. your jitter tolerance ๐Ÿซถ. with a packet-based limit the bucket holds exactly burst packets โ€” by default five. if you specify packet burst it must be a non-zero value, no cap, no zero, not negotiable ๐Ÿ™…โ€โ™€๏ธ. with a byte-based limit the bucket's minimum size is the given rate's byte value, and the burst value adds on top of that โ€” default zero bytes.

Table 68. limit statement values โœจ

  • packet_number โ€” Number of packets โ€” type: unsigned integer (32 bit)
  • byte_number โ€” Number of bytes โ€” type: unsigned integer (32 bit)

๐Ÿฆ‹ NAT STATEMENTS ๐Ÿฆ‹

buckle up bestie, this is the glow-up section ๐Ÿ’…

snat [[ip | ip6] [ prefix ] to] TARGET_SPEC [FLAGS]
dnat [[ip | ip6] [ prefix ] to] TARGET_SPEC [FLAGS]
masquerade [to :PORT_SPEC] [FLAGS]
redirect [to :PORT_SPEC] [FLAGS]

TARGET_SPEC := ADDR_SPEC | [ADDR_SPEC] :PORT_SPEC
ADDR_SPEC := address | address - address
PORT_SPEC := port | port - port

FLAGS  := FLAG [, FLAGS]
FLAG  := persistent | random | fully-random

k so the nat statements are only valid from nat chain types. periodt.

  • the snat and masquerade statements say: hey, the source address/port of the packet should be modified. snat is only valid in the postrouting and input chains, while masquerade makes sense only in postrouting.
  • the dnat and redirect statements are only valid in the prerouting and output chains โ€” they say the destination address/port of the packet should be modified.

you can also use non-base chains that are called from base chains of nat chain type, too ๐Ÿซถ. and heads up: all future packets in this connection will also be mangled, and rules should cease being examined. like, the decision is made, moving on โœจ.

masquerade is a special form of snat that always uses the outgoing interface's IP address to translate to. it's highkey the icon for gateways with dynamic (public) IP addresses ๐Ÿ‘‘.

redirect is a special form of dnat that always translates the destination address to the local host's one. super handy for intercepting traffic passing a router and feeding it to a locally running daemon โ€” e.g. when you're building a transparent proxy or application-layer gateway ๐Ÿงš.

for TARGET_SPEC you can specify addresses, ports, or both. if no address or no port is specified, the respective packet header field remains unchanged.

when used in the inet family (available with kernel 5.2), the dnat and snat statements require the use of the ip and ip6 keyword in case an address is provided โ€” see the examples below ๐ŸŒธ.

โš ๏ธ before kernel 4.18, nat statements require both prerouting and postrouting base chains to be present, since otherwise packets on the return path won't be seen by netfilter and therefore no reverse translation will take place. not me forgetting the postrouting chain ๐Ÿ˜ญ

the optional prefix keyword lets you map n source addresses to n destination addresses. see Advanced NAT examples below ๐Ÿ’–.

๐Ÿšจ if the address for dnat is an IPv4 loopback address (i.e. 127.0.0.0/8) the "net.ipv4.conf.*.route_localnet" sysctl for the input interface needs to be set to 1. otherwise packets will be dropped by the routing code as "martians". literally aliens. ๐Ÿ’€

Table 69. NAT statement values

  • address โ€” Specifies that the source/destination address of the packet should be modified. You may specify a mapping to relate a list of tuples composed of arbitrary expression key with address value. โ€” type: ipv4_addr, ipv6_addr, e.g. abcd::1234, or you can use a mapping, e.g. meta mark map { 10 : 192.168.1.2, 20 : 192.168.1.3 }
  • port โ€” Specifies that the source/destination port of the packet should be modified. โ€” type: port number (16 bit)

Table 70. NAT statement flags ๐ŸŽ€

  • persistent โ€” Gives a client the same source-/destination-address for each connection.
  • random โ€” In kernel 5.0 and newer this is the same as fully-random. In earlier kernels the port mapping will be randomized using a seeded MD5 hash mix using source and destination address and destination port.
  • fully-random โ€” If used then port mapping is generated based on a 32-bit pseudo-random algorithm.

๐ŸŒˆ Using NAT statements.

like, just look at her go:

# create a suitable table/chain setup for all further examples
add table nat
add chain nat prerouting { type nat hook prerouting priority dstnat; }
add chain nat postrouting { type nat hook postrouting priority srcnat; }

# translate source addresses of all packets leaving via eth0 to address 1.2.3.4
add rule nat postrouting oif eth0 snat to 1.2.3.4

# redirect all traffic entering via eth0 to destination address 192.168.1.120
add rule nat prerouting iif eth0 dnat to 192.168.1.120

# translate source addresses of all packets leaving via eth0 to whatever
# locally generated packets would use as source to reach the same destination
add rule nat postrouting oif eth0 masquerade

# redirect incoming TCP traffic for port 22 to port 2222
add rule nat prerouting tcp dport 22 redirect to :2222

# inet family:
# handle ip dnat:
add rule inet nat prerouting dnat ip to 10.0.2.99
# handle ip6 dnat:
add rule inet nat prerouting dnat ip6 to fe80::dead
# this masquerades both ipv4 and ipv6:
add rule inet nat postrouting meta oif ppp0 masquerade

๐Ÿ”ฅ Advanced NAT examples.

this is the part where it gets actually iconic, ngl:

# map prefixes in one network to that of another, e.g. 10.141.11.4 is mangled to 192.168.2.4,
# 10.141.11.5 is mangled to 192.168.2.5 and so on.
add rule nat postrouting snat ip prefix to ip saddr map { 10.141.11.0/24 : 192.168.2.0/24 }

# map a source address, source port combination to a pool of destination addresses and ports:
add rule nat postrouting dnat to ip saddr . tcp dport map { 192.168.1.2 . 80 : 10.141.10.2-10.141.10.5 . 8888-8999 }

# The above example generates the following NAT expression:
#
# [ nat dnat ip addr_min reg 1 addr_max reg 10 proto_min reg 9 proto_max reg 11 ]
#
# which expects to obtain the following tuple:
# IP address (min), source port (min), IP address (max), source port (max)
# to be obtained from the map. The given addresses and ports are inclusive.

# This also works with named maps and in combination with both concatenations and ranges:
table ip nat {
        map ipportmap {
                typeof ip saddr : interval ip daddr . tcp dport
                flags interval
                elements = { 192.168.1.2 : 10.141.10.1-10.141.10.3 . 8888-8999, 192.168.2.0/24 : 10.141.11.5-10.141.11.20 . 8888-8999 }
        }
                   chain prerouting {
                           type nat hook prerouting priority dstnat; policy accept;
                           ip protocol tcp dnat ip to ip saddr map @ipportmap
                   }
           }

Okay so @ipportmap is out here mapping network prefixes to a whole range of hosts and ports ๐Ÿ˜Œ The new destination gets pulled straight outta the range that the map element hands over. Same deal for the destination port. Iconic, no notes ๐Ÿ’…

Now โ€” did you clock the "interval" keyword in the typeof description? ๐ŸŽ€ That one's lowkey mandatory, because nftables needs to know it's gotta ask for twice the storage per key-value pair in the map. Like, the map is thicc, it needs room ๐Ÿซถ

Meanwhile : ipv4_addr . inet_service would only let you associate one address and one port with each key. But babes, in this case, for every single key you're storing two addresses and two ports โ€” the min and the max for both ๐Ÿ˜ญ So yeah. That's the whole reason.


๐ŸŒˆ TPROXY STATEMENT ๐ŸŒˆ

Tproxy redirects the packet to a local socket without changing the packet header in any way โœจ Periodt, headers stay untouched. And if any of the arguments is missing? The data from the incoming packet just gets used as the parameter. Very "we'll figure it out" of it ๐Ÿ™ˆ

Heads up though: tproxy matching requires another rule that makes sure the transport protocol header presence is specified ๐Ÿ‘€

tproxy to address:port
tproxy to {address | :port}

This syntax slaps in ip/ip6 tables where the network layer protocol is obvious ๐Ÿ’– Either the IP address or the port can be specified, but bestie, at least one of them is necessary ๐Ÿ˜ค

tproxy {ip | ip6} to address[:port]
tproxy to :port

And this syntax is for inet tables ๐Ÿฆ‹ The ip/ip6 parameter defines which family the rule matches, and the address parameter must be of that family. When only the port is defined, do not specify the address family โ€” in that case the rule matches for both families โœจ

Table 71. tproxy attributes ๐ŸŽ€

  • address โ€” IP address the listening socket with IP_TRANSPARENT option is bound to.
  • port โ€” Port the listening socket with IP_TRANSPARENT option is bound to.

Example ruleset for the tproxy statement โ€” look at her go ๐Ÿ‘‘

table ip x {
    chain y {
        type filter hook prerouting priority mangle; policy accept;
        tcp dport ntp tproxy to 1.1.1.1 accept
        udp dport ssh tproxy to :2222 accept
    }
}
table ip6 x {
    chain y {
       type filter hook prerouting priority mangle; policy accept;
       tcp dport ntp tproxy to [dead::beef] accept
       udp dport ssh tproxy to :2222 accept
    }
}
table inet x {
    chain y {
        type filter hook prerouting priority mangle; policy accept;
        tcp dport 321 tproxy to :22 accept
        tcp dport 99 tproxy ip to 1.1.1.1:999 accept
        udp dport 155 tproxy ip6 to [dead::beef]:smux accept
    }
}

Okay so important vibe check: the tproxy statement is non-terminal, which is on purpose โ€” it lets packets get post-processed ๐Ÿ’œ So you can log packets for debugging and update the mark to make sure packets are delivered locally through policy routing rules. Multi-tasking queen ๐Ÿ‘‘

Example ruleset for tproxy statement with logging and meta mark:

table inet x {
    chain y {
        type filter hook prerouting priority mangle; policy accept;
        udp dport 9999 goto {
            tproxy to :1234 log prefix "packet tproxied: " meta mark set 1 accept
            log prefix "no socket on port 1234 or not transparent?: " drop
        }
    }
}
๐Ÿšจ Real talk: since packet headers are unchanged, packets might get forwarded instead of delivered locally. As mentioned up above, you dodge that by adding policy routing rules and the packet mark. Don't skip this step bestie ๐Ÿ˜ญ

Example policy routing rules for local redirection:

ip rule add fwmark 1 lookup 100
ip route add local 0.0.0.0/0 dev lo table 100

And ngl, this is a change in behavior compared to the legacy iptables TPROXY target, which is terminal ๐Ÿ’€ So if you wanna terminate packet processing after the tproxy statement, remember to issue a verdict as in the example above. Don't just leave her hanging ๐Ÿ™ˆ


๐Ÿฆ‹ SYNPROXY STATEMENT ๐Ÿฆ‹

This statement processes the TCP three-way-handshake parallel in netfilter context to protect either a local or backend system โœจ It's giving bodyguard energy. Real talk though: this statement requires connection tracking, because sequence numbers need to be translated ๐Ÿ˜ค No conntrack, no synproxy, iykyk.

synproxy [mss mss_value] [wscale wscale_value] [SYNPROXY_FLAGS]

Table 72. synproxy statement attributes ๐ŸŽ€

  • mss โ€” Maximum segment size announced to clients. This must match the backend.
  • wscale โ€” Window scale announced to clients. This must match the backend.

Table 73. synproxy statement flags โญ

  • sack-perm โ€” Pass client selective acknowledgement option to backend (will be disabled if not present).
  • timestamp โ€” Pass client timestamp option to backend (will be disabled if not present, also needed for selective acknowledgement and window scaling).

Example ruleset for synproxy statement ๐Ÿ’– First up: determine the tcp options used by the backend, from an external system ๐Ÿ‘‡

tcpdump -pni eth0 -c 1 'tcp[tcpflags] == (tcp-syn|tcp-ack) && port 80' &
telnet 192.0.2.42 80
18:57:24.693307 IP 192.0.2.42.80 > 192.0.2.43.48757:
    Flags [S.], seq 360414582, ack 788841994, win 14480,
    options [mss 1460,sackOK,
    TS val 1409056151 ecr 9690221,
    nop,wscale 9],
    length 0

Then switch tcp_loose mode off, so conntrack will mark out-of-flow packets as state INVALID ๐Ÿ”ฅ

echo 0 > /proc/sys/net/netfilter/nf_conntrack_tcp_loose

Next: make SYN packets untracked ๐Ÿซถ

table ip x {
        chain y {
                type filter hook prerouting priority raw; policy accept;
                tcp flags syn notrack
        }
}

Then catch UNTRACKED (SYN packets) and INVALID (3WHS ACK packets) states and send them to SYNPROXY โœจ This rule will respond to SYN packets with SYN+ACK syncookies, create ESTABLISHED for a valid client response (3WHS ACK packets) and drop incorrect cookies. Flags combinations not expected during 3WHS will not match and will continue (e.g. SYN+FIN, SYN+ACK). Finally โ€” drop invalid packets, because those are the out-of-flow packets that weren't matched by SYNPROXY ๐Ÿ’…

table ip x {
        chain z {
                type filter hook input priority filter; policy accept;
                ct state invalid, untracked synproxy mss 1460 wscale 9 timestamp sack-perm
                ct state invalid drop
        }
}

๐ŸŒธ FLOW STATEMENT ๐ŸŒธ

A flow statement lets you select which flows you wanna accelerate by bypassing the layer 3 network stack ๐ŸŒˆ Main character forwarding energy only. You have to specify the flowtable name where you want to offload this flow, though ๐Ÿ‘‘

flow add @flowtable

๐Ÿ’œ QUEUE STATEMENT ๐Ÿ’œ

This statement passes the packet to userspace using the nfnetlink_queue handler โœจ The packet gets put into the queue identified by its 16-bit queue number. Userspace can inspect it and optionally modify it if it wants to โ€” no pressure ๐Ÿซถ Userspace must provide a drop or accept verdict though. And in the case of accept, processing resumes with the next base chain hook, not the rule following the queue verdict ๐Ÿ˜ณ Yeah. That's the plot twist. See libnetfilter_queue documentation for details ๐Ÿ“š

queue [flags QUEUE_FLAGS] [to queue_number]
queue [flags QUEUE_FLAGS] [to queue_number_from - queue_number_to]
queue [flags QUEUE_FLAGS] [to QUEUE_EXPRESSION ]

QUEUE_FLAGS := QUEUE_FLAG [, QUEUE_FLAGS]
QUEUE_FLAG  := bypass | fanout
QUEUE_EXPRESSION := numgen | hash | symhash | MAP STATEMENT

So QUEUE_EXPRESSION can be used to compute a queue number at run-time with the hash or numgen expressions ๐Ÿงš It also lets you use the map statement to assign fixed queue numbers based on external inputs โ€” like the source ip address or interface names ๐Ÿ’…โœจ Custom queue numbers, made to order. Obsessed.

okay so picking right back up with the queue statement deets ๐Ÿ’… here's everything it's packing:

  • queue_number โ€” sets the queue number, and the default is 0. type: unsigned integer (16 bit).
  • queue_number_from โ€” sets the initial queue in the range, if fanout is used. type: unsigned integer (16 bit).
  • queue_number_to โ€” sets the closing queue in the range, if fanout is used. type: unsigned integer (16 bit).

and the flags ๐Ÿ‘‘

  • bypass โ€” lets packets go through if the userspace application cannot back off. โš ๏ธ before you even think about using this flag, go read the libnetfilter_queue documentation for performance tuning recommendations, ok?
  • fanout โ€” distributes packets between several queues. spreading the love fr fr ๐ŸŒธ

๐Ÿฆ‹ DUP STATEMENT

the dup statement is your duplicator bestie โ€” it duplicates a packet and sends the copy off to a totally different destination. iconic.

dup to device
dup to address device device

here's what goes in it:

  • address โ€” says the copy of the packet should be sent to a new gateway. type: ipv4_addr, ipv6_addr, e.g. abcd::1234, or you can use a mapping, e.g. ip saddr map { 192.168.1.2 : 10.1.1.1 }.
  • device โ€” says the copy should be transmitted via device. type: string.

using the dup statement, live in action:

# send to machine with ip address 10.2.3.4 on eth0
ip filter forward dup to 10.2.3.4 device "eth0"

# copy raw frame to another interface
netdev ingress dup to "eth0"
dup to "eth0"

# combine with map dst addr to gateways
dup to ip daddr map { 192.168.7.1 : "eth0", 192.168.7.2 : "eth1" }

๐Ÿ’œ FWD STATEMENT

the fwd statement redirects a raw packet to another interface. heads up tho โ€” it's only available in the netdev family ingress and egress hooks ๐Ÿซถ it's basically dup's sibling except no copy gets made. periodt.

you can also specify the address of the next hop and the device to forward the packet to. this updates the source and destination MAC address of the packet by transmitting it through the neighboring layer. it also decrements the ttl field of the IP packet. so it's giving "effectively bypass the classical forwarding path", which means it skips the fib (forwarding information base) lookup entirely. slay.

fwd to device
fwd [ip | ip6] to address device device

using the fwd statement:

# redirect raw packet to device
netdev ingress fwd to "eth0"

# forward packet to next hop 192.168.200.1 via eth0 device
netdev ingress ether saddr set fwd ip to 192.168.200.1 device "eth0"

โœจ SET STATEMENT

the set statement is how you dynamically add or update elements in a set straight from the packet path. a couple things you NEED to know bestie:

  • the set setname must already exist in the given table.
  • it must have been created with one or both of the dynamic and the timeout flags.
  • the dynamic flag is required if the set statement expression includes a stateful object.
  • the timeout flag is implied if the set is created with a timeout, and it's required if the set statement updates elements, rather than adding them.

and like, also โ€” these sets should specify both a maximum set size (to prevent memory exhaustion ๐Ÿ˜ญ) and their elements should have a timeout (so their number will not grow indefinitely), either from the set definition or from the statement that adds or updates them. do this and you can do stuff like create dynamic blacklists. main character behaviour honestly.

dynamic updates are also supported with maps ๐Ÿ—บ๏ธ in that case, the add or update rule needs to provide both the key and the data element (value), separated via :.

{add | update} @setname { expression [timeout timeout] [comment string] }

example for a simple blacklist:

# declare a set, bound to table "filter", in family "ip".
# Timeout and size are mandatory because we will add elements from packet path.
# Entries will timeout after one minute, after which they might be
# re-added if limit condition persists.
nft add set ip filter blackhole \
    "{ type ipv4_addr; flags dynamic; timeout 1m; size 65536; }"

# declare a set to store the limit per saddr.
# This must be separate from blackhole since the timeout is different
nft add set ip filter flood \
    "{ type ipv4_addr; flags dynamic; timeout 10s; size 128000; }"

# whitelist internal interface.
nft add rule ip filter input meta iifname "internal" accept

# drop packets coming from blacklisted ip addresses.
nft add rule ip filter input ip saddr @blackhole counter drop

# add source ip addresses to the blacklist if more than 10 tcp connection
# requests occurred per second and ip address.
nft add rule ip filter input tcp flags syn tcp dport ssh \
    add @flood { ip saddr limit rate over 10/second } \
    add @blackhole { ip saddr } \
    drop

# inspect state of the sets.
nft list set ip filter flood
nft list set ip filter blackhole

# manually add two addresses to the blackhole.
nft add element filter blackhole { 10.2.3.4, 10.23.1.42 }

๐ŸŽ€ MAP STATEMENT

the map statement looks up data based on some specific input key. it's giving dictionary energy, iykyk ๐Ÿงš

expression map { MAP_ELEMENTS }

MAP_ELEMENTS := MAP_ELEMENT [, MAP_ELEMENTS]
MAP_ELEMENT  := key : value

the key is a value returned by expression.

using the map statement:

# select DNAT target based on TCP dport:
# connections to port 80 are redirected to 192.168.1.100,
# connections to port 8888 are redirected to 192.168.1.101
nft add rule ip nat prerouting dnat tcp dport map { 80 : 192.168.1.100, 8888 : 192.168.1.101 }

# source address based SNAT:
# packets from net 192.168.1.0/24 will appear as originating from 10.0.0.1,
# packets from net 192.168.2.0/24 will appear as originating from 10.0.0.2
nft add rule ip nat postrouting snat to ip saddr map { 192.168.1.0/24 : 10.0.0.1, 192.168.2.0/24 : 10.0.0.2 }

๐ŸŒˆ VMAP STATEMENT

the verdict map (vmap) statement works analogous to the map statement, except it's holding verdicts as the values. same vibe, different payload โœจ

expression vmap { VMAP_ELEMENTS }

VMAP_ELEMENTS := VMAP_ELEMENT [, VMAP_ELEMENTS]
VMAP_ELEMENT  := key : verdict

using the vmap statement:

# jump to different chains depending on layer 4 protocol type:
nft add rule ip filter input ip protocol vmap { tcp : jump tcp-chain, udp : jump udp-chain , icmp : jump icmp-chain }

๐ŸŒธ XT STATEMENT

this one is literally an xt statement straight out of the xtables compat interface. it's the fallback option for when translation isn't available or isn't complete ๐Ÿซถ

xt TYPE NAME

TYPE := match | target | watcher

if you're seeing this, it means the ruleset (or parts of it) were created by iptables-nft, and you should use that to manage it. no cap.

โš ๏ธ BEWARE: nftables won't restore these statements. like, at all. ๐Ÿ’€

โœจ ADDITIONAL COMMANDS โœจ

okay so these are the extra lil commands that ship inside nft itself โ€” not the big ruleset stuff, just the handy side quests ๐Ÿ’…


๐Ÿ” LIST HOOKS

This one shows you the list of functions that have been registered for the protocol family you ask about โ€” and yes, that includes the sneaky ones registered implicitly by kernel modules like nf_conntrack ๐Ÿซถ

list hooks [family]
list hooks netdev [ device DEVICE_NAME ]

list hooks on its own is literally enough to display everything that's active on the system. Hooks in the netdev family are tied to a network device, so if you don't give a device name, nft will query all network devices in the current network namespace. iykyk โœจ

Example usage โ€” list all active netfilter hooks in either the ip or ip6 stack:

% nft list hooks inet
family ip {
        hook prerouting {
                -0000000400 ipv4_conntrack_defrag [nf_defrag_ipv4]
                -0000000200 ipv4_conntrack_in [nf_conntrack]
                -0000000100 nf_nat_ipv4_pre_routing [nf_nat]
        }
        hook input {
                 0000000000 chain inet filter input [nf_tables]
                +0000000100 nf_nat_ipv4_local_in [nf_nat]
[..]

so the above is a host that has nat, conntrack and ipv4 packet defragmentation enabled, bestie ๐ŸŒธ For each hook location for the queried family, you get a list of active hooks in this format:

priority identifier [module_name]

The priority value dictates the order in which the hooks are called. The list is sorted, and the lowest number runs first ๐Ÿ”ฅ

The priority value of hooks registered by the kernel cannot be changed. For basechains registered by nftables, this value corresponds to the priority value specified in the base chain definition.

After the numerical value, you get info about the hook. For basechains defined in nftables, that includes the table family, the table name and the basechain's name. For hooks coming from kernel modules, the function name is used instead.

If a module name is given, the hook was registered by the kernel module with this name. You can use modinfo module name to obtain more information about the module ๐Ÿงš

This functionality requires a kernel built with the option CONFIG_NETFILTER_NETLINK_HOOK enabled, either as a module or builtin. The module is named nfnetlink_hook.

๐Ÿ‘€ MONITOR

The monitor command lets you listen to Netlink events produced by the nf_tables subsystem. Those are either related to creation and deletion of objects, or to packets for which meta nftrace was enabled ๐Ÿ‘‘ When they happen, nft prints the monitored events to stdout in either JSON or native nft format.

monitor [new | destroy] MONITOR_OBJECT
monitor trace

MONITOR_OBJECT := tables | chains | sets | rules | elements | ruleset

To filter events related to a concrete object, use one of the keywords in MONITOR_OBJECT.

To filter events related to a concrete action, use keyword new or destroy ๐Ÿ’€

The second form of invocation takes no further options and exclusively prints events generated for packets with nftrace enabled.

Hit ^C to finish the monitor operation ๐Ÿซถ

Listen to all events, report in native nft format:

% nft monitor

Listen to deleted rules, report in JSON format:

% nft -j monitor destroy rules

Listen to both new and destroyed chains, in native nft format:

% nft monitor chains

Listen to ruleset events such as table, chain, rule, set, counters and quotas, in native nft format:

% nft monitor ruleset

Trace incoming packets from host 10.0.0.1:

% nft add rule filter input ip saddr 10.0.0.1 meta nftrace set 1
% nft monitor trace

๐Ÿ˜ญ ERROR REPORTING

When an error is detected, nft shows the line(s) containing the error, the position of the erroneous parts in the input stream, and marks up the erroneous parts using carets (^). If the error results from the combination of two expressions or statements, the part imposing the constraints which are violated is marked using tildes (~) ๐Ÿ’…

For errors returned by the kernel, nft cannot detect which parts of the input caused the error, so the entire command is marked. no cap.

Error caused by single incorrect expression:

<cmdline>:1:19-22: Error: Interface does not exist
filter output oif eth0
                  ^^^^

Error caused by invalid combination of two expressions:

<cmdline>:1:28-36: Error: Right hand side of relational expression (==) must be constant
filter output tcp dport == tcp dport
                        ~~ ^^^^^^^^^

Error returned by the kernel:

<cmdline>:0:0-23: Error: Could not process rule: Operation not permitted
filter output oif wlan0
^^^^^^^^^^^^^^^^^^^^^^^

๐Ÿšช EXIT STATUS

  • 0 โ€” on success, nft exits with a status of 0 โœจ
  • 1 โ€” unspecified errors cause it to exit with a status of 1
  • 2 โ€” memory allocation errors, status 2 ๐Ÿ˜ญ
  • 3 โ€” unable to open Netlink socket, status 3

๐Ÿฆ‹ SEE ALSO

libnftables(3), libnftables-json(5), iptables(8), ip6tables(8), arptables(8), ebtables(8), ip(8), tc(8)

There is an official wiki at: https://wiki.nftables.org โ€” go lurk, it's giving lore ๐ŸŒˆ


๐Ÿ’– AUTHORS

nftables was written by Patrick McHardy and Pablo Neira Ayuso, among many other contributors from the Netfilter community ๐Ÿซถ absolute icons, the whole crew.


Copyright ยฉ 2008-2014 Patrick McHardy <kaber@trash.net> Copyright ยฉ 2013-2018 Pablo Neira Ayuso <pablo@netfilter.org>

nftables is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation.

This documentation is licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0 license, CC BY-SA 4.0 http://creativecommons.org/licenses/by-sa/4.0/.


and that's the whole page bestie, we ate and left zero crumbs ๐Ÿ’…โœจ this one's the NFT(8) man page, dated 12/05/2025 โ€” go forth and firewall, mwah ๐ŸŽ€๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from