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 fromfilename. Iffilenameis-, 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 usequitto exit, or use the EOF marker, normally this isCTRL-D.-I,--includepath directoryโ Add the directorydirectoryto 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-cto 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/passwdand/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 usingadd,insertorreplacecommands, print notifications just likenft monitor.-j,--jsonโ Format output in JSON. Seelibnftables-json(5)for a schema description.-d,--debug levelโ Enable debugging output. The debug level can be any ofscanner,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 thepreroutinghook. 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 theinputhook ๐ซถforwardโ packets forwarded to a different host get processed by theforwardhook ๐จoutputโ packets sent by local processes get processed by theoutputhook ๐postroutingโ all packets leaving the system get processed by thepostroutinghook ๐ingressโ all packets entering the system get processed by this hook. it's invoked before layer 3 protocol handlers, hence before thepreroutinghook, and it can be used for filtering and policing ๐ฎโโ๏ธ
heads up bestie:ingressis only available for the Inet family (since Linux kernel5.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 theinputhook ๐outputโ packets send by the local system get processed by theoutputhook ๐
(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 aftertc ingressand 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 beforetc 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, unlikeiptables, 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 theaddcommand, 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
netdevfamily supports merely two combinations, namelyfiltertype withingresshook andfiltertype withegresshook. Base chains in this family also require theDEVICEparameter to be present since they exist per interface only. - The
arpfamily supports only theinputandoutputhooks, both in chains of typefilter. - The
inetfamily also supports theingresshook (since Linux kernel5.10), to filter IPv4 and IPv6 packet at the same location as thenetdevingress hook. Thisinethook allows you to share sets and maps between the usualprerouting,input,forward,output,postroutingand thisingresshook.
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: allmangleโ value-150โ families:ip,ip6,inetโ hooks: alldstnatโ value-100โ families:ip,ip6,inetโ hooks:preroutingfilterโ value0โ families:ip,ip6,inet,arp,netdevโ hooks: allsecurityโ value50โ families:ip,ip6,inetโ hooks: allsrcnatโ value100โ families:ip,ip6,inetโ hooks:postrouting
Table 7. Standard priority names and hook compatibility for the bridge family
dstnatโ value-300โ hooks:preroutingfilterโ value-200โ hooks: alloutโ value100โ hooks:outputsrcnatโ value300โ 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 usebashfor 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 asaddexcept the rule is inserted at the beginning of the chain or before the specified rule.replaceโ Similar toadd, 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.counterandquotastatement 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.*.forwardingornet.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
jumpandgoto). 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 usesdropas its policy, the same base chain (or a regular chain directly or indirectly called by it) must contain at least one matchingacceptrule 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: onlydropgets 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
returnverdict 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
jumpexcept 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
gotoverdicts) 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 areturnis issued in that, evaluation continues after the jump position in regular-1. at the end of regular-1 or when areturnis 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 areturnis 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 areturnis issued in that, evaluation continues after the jump position in regular-1. at the end of regular-1 or when areturnis 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 areturnis issued in that, evaluation continues after the jump position in base.
- ๐ verdicts (that is:
accept,drop,jump,goto,returnandcontinue) as well as statements that imply a verdict (likerejector 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 acceptthecounterstatement is processed, but in... accept counterit is not. this does not apply to thecommentstatement, which is always evaluated. the waycommentis 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,marktypeofโ data type of set element. Type: expression to derive the data type fromflagsโ 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,sgc-intervalโ garbage collection interval, only available when timeout or flagtimeoutare active. Type: string, decimal followed by unit. Units are:d,h,m,selementsโ elements contained by the set. Type: set data typesizeโ 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],memoryauto-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 theadd,updateordeletekeywords.intervalโ Set must be able to store intervals (ranges). Cannot be combined with thedynamicflag.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 flagtimeout.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 integerl3protoโ 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 isstring(e.g.ip)dportโ destination port of the expected connection; type isunsigned integertimeoutโ timeout value for the expectation; type isunsigned integersizeโ size value for the expectation; type isunsigned integerl3protoโ layer 3 protocol of the expectation object; type isaddress family(e.g.ip)commentโ per ct expectation comment field; type isstring
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 isunsigned integer (64 bit)bytesโ initial count of bytes; type isunsigned integer (64 bit)commentโ per counter comment field; type isstring
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, anunsigned integer (64 bit)and astring:bytes,kbytes,mbytes."over"and"until"go before these arguments ๐usedโ initial value of used quota; type is two arguments, anunsigned integer (64 bit)and astring:bytes,kbytes,mbytescommentโ per quota comment field; type isstring
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 expressionbit[,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,relatedandct state { established, related }match exactly the same packets, because the bits ofct stateare 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 ๐
๐น LINK LAYER ADDRESS TYPE
- 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โ value1missingโ value0
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โ0destination-unreachableโ3source-quenchโ4redirectโ5echo-requestโ8router-advertisementโ9router-solicitationโ10time-exceededโ11parameter-problemโ12timestamp-requestโ13timestamp-replyโ14info-requestโ15info-replyโ16address-mask-requestโ17address-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โ1packet-too-bigโ2time-exceededโ3parameter-problemโ4echo-requestโ128echo-replyโ129mld-listener-queryโ130mld-listener-reportโ131mld-listener-doneโ132mld-listener-reductionโ132nd-router-solicitโ133nd-router-advertโ134nd-neighbor-solicitโ135nd-neighbor-advertโ136nd-redirectโ137router-renumberingโ138ind-neighbor-solicitโ141ind-neighbor-advertโ142mld2-listener-reportโ143
Not me noticingmld-listener-doneandmld-listener-reductionboth sit at132โ 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โ value1establishedโ value2relatedโ value4newโ value8untrackedโ value64
Table 23. conntrack direction (ct_dir)
originalโ value0replyโ value1
Table 24. conntrack status (ct_status) โ this one is giving full lore, bestie ๐
expectedโ value1โ Expected connection; conntrack helper set it upseen-replyโ value2โ Conntrack has seen packets in both directionsassuredโ value4โ Conntrack entry will not be removed if hash table is fullconfirmedโ value8โ Initial packet processedsnatโ value16โ Original source address differs from reply destinationdnatโ value32โ Original destination differs from reply sourceseq-adjustโ value64โ tcp sequence number rewrite due to conntrack helper or synproxysnat-doneโ value128โ tried to find matching snat/masquerade rulednat-doneโ value256โ tried to find matching dnat/redirect ruledyingโ value512โ Connection about to be deletedfixed-timeoutโ value1024โ entry expires even if traffic is activehelperโ value8192โ connection is monitored by conntrack helperoffloadโ value16384โ connection is offloaded to a flow tablehw-offloadโ value32768โ connection is offloaded to hardware
Table 25. conntrack event bits (ct_event)
newโ value1relatedโ value2destroyโ value4replyโ value8assuredโ value16protoinfoโ value32helperโ value64markโ value128seqadjโ value256secmarkโ value512labelโ value1024
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โ0responseโ1dataโ2ackโ3dataackโ4closereqโ5closeโ6resetโ7syncโ8syncackโ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 ininettable ยท type:integer (32 bit)๐ (iykyk โ it's the real one, not the pretend one, and it only pulls its weight insideinet)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 groupnet_cls.classid(for matching on cgroupv2, seesocket 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 anInteger (8 bit)or astring๐ฆhourโ hour of day, and it's aString value in the form HH:MM or HH:MM:SS. Values are expected to be less than24:00, although for technical reasons,23:59:60is 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 bitnumber). Can be specified numerically or as name of an existing interface ๐ifnameโ Interface name (16 bytestring). Does not have to exist. (she's aspirational, we love that for her โจ)iface_typeโ Interface type (16 bitnumber).uidโ User ID (32 bitnumber). Can be specified numerically or as user name.gidโ Group ID (32 bitnumber). Can be specified numerically or as group name.realmโ Routing Realm (32 bitnumber). Can be specified numerically or as symbolic name defined in/etc/iproute2/rt_realms.devgroup_typeโ Device group (32 bitnumber). 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 bytestring). SeeTYPESinip-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 between0and6. 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,0is Sunday and6is 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:00and17:00:00would 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 theIP_TRANSPARENTsocket option in the found socket. it can be0or1. 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.0or::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:stringversionโ 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 atpf.osfile. 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 (saddrkey) or destination (daddrkey). if no routing entry is found, the returned interface index is0. ๐ญoifnameโ likeoif, but it fills the interface name instead. this is useful to check dynamic interfaces such aspppdevices. if no entry is found, an empty interface name is returned.typeโ returns the address type such asunicastormulticast. a complete list of supported address types can be shown withnft 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 thetyperesult. ๐
ok real talk ๐ซถ those last two are mutual-exclusive-adjacent ANDoifhas a whole extra rule about only working withtypeโ 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_indexcheckโ Output interface check โ result type:booleanoifnameโ Output interface name โ result type:ifnametypeโ Address type โ result type:fib_addrtype(seenft describe fib_addrtypefor 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:realmnexthopโ Routing nexthop โ type:ipv4_addr/ipv6_addrmtuโ 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_addrdaddrโ Destination address of the tunnel โ type:ipv4_addr/ipv6_addr
โ ๏ธ Note: When usingxfrm_interface, this expression is not useable inoutputhook as the plain packet does not traverse it with IPsec info attached - use a chain inpostroutinghook 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 โ typeether_addrsaddrโ Source MAC address โ typeether_addrtypeโ EtherType โ typeether_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) โ typeinteger (12 bit)deiโ Drop Eligible Indicator โ typeinteger (1 bit)pcpโ Priority code point โ typeinteger (3 bit)typeโ EtherType โ typeether_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 โ typeinteger (16 bit)ptypeโ EtherType โ typeether_typehlenโ Hardware address len โ typeinteger (8 bit)plenโ Protocol address len โ typeinteger (8 bit)operationโ Operation โ typearp_opsaddr etherโ Ethernet sender address โ typeether_addrdaddr etherโ Ethernet target address โ typeether_addrsaddr ipโ IPv4 sender address โ typeipv4_addrdaddr ipโ IPv4 target address โ typeipv4_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 literalFIXME scalingsituation going on there ๐dscpโ Differentiated Services Code Point. Type:dscpecnโ Explicit Congestion Notification. Type:ecnlengthโ 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_protochecksumโ IP header checksum. Type:integer (16 bit)saddrโ Source address. Type:ipv4_addrdaddrโ Destination address. Type:ipv4_addr
โ ๏ธ Lowkey be careful when you're matching onip 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 (peepman ip-link(8), specificallygro_ipv4_max_sizeandgso_ipv4_max_size), thenip lengthmight be0for such jumbo packets ๐ญ.meta lengthis 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_typecodeโ 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_typemrtโ 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 usingip6 nexthdr. The value only refers to the next header, i.e.ip6 nexthdr tcpwill 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 usemeta 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 (always6bestie) โ type:integer (4 bit)dscpโ Differentiated Services Code Point โ type:dscpecnโ Explicit Congestion Notification โ type:ecnflowlabelโ Flow label โ type:integer (20 bit)lengthโ Payload length โ type:integer (16 bit)nexthdrโ Nexthdr protocol โ type:inet_protohoplimitโ Hop limit โ type:integer (8 bit)saddrโ Source address โ type:ipv6_addrdaddrโ Destination address โ type:ipv6_addr
Careful with matching onip6 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 than65535(seeman ip-link(8), specificallygro_max_sizeandgso_max_size), then ip6 length might be0for such jumbo packets.meta lengthallows 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_typecodeโ 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_addrdaddrโ 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, typeinet_service๐dportโ destination port, typeinet_service๐sequenceโ the sequence number, typeinteger (32 bit)ackseqโ the acknowledgement number, typeinteger (32 bit)doffโ data offset, typeinteger (4 bit)... and yes, the manpage literally saysFIXME scalingright there, no cap, that's a real note in the docs ๐reservedโ the reserved area, typeinteger (4 bit)flagsโ TCP flags, typetcp_flagwindowโ the window, typeinteger (16 bit)checksumโ checksum, typeinteger (16 bit)urgptrโ urgent pointer, typeinteger (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, typeinet_serviceโจdportโ destination port, typeinet_serviceโจlengthโ total packet length, typeinteger (16 bit)checksumโ checksum, typeinteger (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, typeinet_service๐ซถdportโ destination port, typeinet_service๐ซถchecksumโ checksum, typeinteger (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, typeinet_serviceโญdportโ destination port, typeinet_serviceโญvtagโ verification tag, typeinteger (32 bit)checksumโ checksum, typeinteger (32 bit)chunkโ searches for a chunk in the packet. type-wise it's a little special: withoutFIELD, 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 itselfflagsโ 8 bits โ shows up in all chunks โ the semantics are defined on a per-chunk basislengthโ 16 bits โ shows up in all chunks โ length of this chunk in bytes, excluding paddingtsnโ 32 bits โ data chunks โ transmission sequence numberstreamโ 16 bits โ data chunks โ stream identifierssnโ 16 bits โ data chunks โ stream sequence numberppidโ 32 bits โ data chunks โ payload protocol identifierinit-tagโ 32 bits โ init, init-ack โ initiate taga-rwndโ 32 bits โ init, init-ack, sack โ advertised receiver window creditnum-outbound-streamsโ 16 bits โ init, init-ack โ number of outbound streamsnum-inbound-streamsโ 16 bits โ init, init-ack โ number of inbound streamsinitial-tsnโ 32 bits โ init, init-ack โ initial transmit sequence numbercum-tsn-ackโ 32 bits โ sack, shutdown โ cumulative transmission sequence number acknowledgednum-gap-ack-blocksโ 16 bits โ sack โ number of Gap Ack Blocks includednum-dup-tsnsโ 16 bits โ sack โ number of duplicate transmission sequence numbers receivedlowest-tsnโ 32 bits โ ecne, cwr โ lowest transmission sequence numberseqnoโ 32 bits โ asconf-ack, asconf โ sequence numbernew-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 asinet_servicedportโ destination port, typed asinet_servicetypeโ packet type, typed asdccp_pkttype
AUTHENTICATION HEADER EXPRESSION ๐ซถ
ah {nexthdr | hdrlength | reserved | spi | sequence}
Table 50. AH header expression
nexthdrโ next header protocol, typed asinet_protohdrlengthโ AH header length, typed asinteger (8 bit)reservedโ reserved area, typed asinteger (16 bit)spiโ Security Parameter Index, typed asinteger (32 bit)sequenceโ sequence number, typed asinteger (32 bit)
ENCRYPTED SECURITY PAYLOAD HEADER EXPRESSION โจ
esp {spi | sequence}
Table 51. ESP header expression
spiโ Security Parameter Index, typed asinteger (32 bit)sequenceโ sequence number, typed asinteger (32 bit)
IPCOMP HEADER EXPRESSION ๐ธ
comp {nexthdr | flags | cpi}
Table 52. IPComp header expression
nexthdrโ next header protocol, typed asinet_protoflagsโ flags, typed asbitmaskcpiโ compression Parameter Index, typed asinteger (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 asinteger (5 bit)versionโ gre version field,0for GRE and1for PPTP, typed asinteger (3 bit)protocolโ EtherType of encapsulated packet, typed asinteger (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 asinteger (16 bit)vniโ Virtual Network ID (VNI), typed asinteger (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,sizewindowโ TCP Window Scaling โ fields:length,countsack-permโ TCP SACK permitted โ fields:lengthsackโ TCP Selective Acknowledgement (alias of block 0) โ fields:length,left,rightsack0โ TCP Selective Acknowledgement (block 0) โ fields:length,left,rightsack1โ TCP Selective Acknowledgement (block 1) โ fields:length,left,rightsack2โ TCP Selective Acknowledgement (block 2) โ fields:length,left,rightsack3โ TCP Selective Acknowledgement (block 3) โ fields:length,left,righttimestampโ TCP Timestamps โ fields:length,tsval,tsecrmptcpโ 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,addrraโ Router Alert โ fields:length,valuerrโ Record Route โ fields:length,ptr,addrssrrโ 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 inconnlabel.confin 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 thepacketskeyword. Type:integer (64 bit).avgpktโ average bytes per packet; see the description for thepacketskeyword. 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: anacceptverdict in a chain of theforwardhook still leaves room for someone to drop the packet in anotherforwardhook base chain (or a chain called from it) that has a higher priority number, or in a chain attached to thepostroutinghook. ๐ญ 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 implicitreturnverdict 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โ literallyjumpexcept 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 viagotoverdicts โ 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 stringlevelโ syslog level of logging โ type: string:emerg,alert,crit,err,warn[default],notice,info,debug,auditgroupโ 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 headerip optionsโ log options from the IP/IPv6 packet headerskuidโ log the userid of the process which generated the packetetherโ 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โ0host-unreachableโ1prot-unreachableโ2port-unreachableโ3frag-neededโ4net-prohibitedโ9host-prohibitedโ10admin-prohibitedโ13
Table 64. Keywords you can use to reject when specifying the ICMPv6 code ๐ฆ
no-routeโ0admin-prohibitedโ1addr-unreachableโ3port-unreachableโ4policy-failโ5reject-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โ0port-unreachableโ1host-unreachableโ2admin-prohibitedโ3
The common default ICMP code to reject is port-unreachable. That's the vibe, that's the default ๐
Also lowkey important: in thebridgefamily, therejectstatement is only allowed in base chains that hook intoinputorprerouting. 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 stringmarkโ Connection tracking mark โ value:marklabelโ Connection tracking label โ value:labelzoneโ 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 thepreroutingoroutputhook, 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_handlemarkโ Packet mark โ value:markpkttypeโ packet type โ value:pkt_typenftraceโ ruleset packet tracing on/off. Usemonitor tracecommand to watch traces โ value:0,1brouteโ 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
snatandmasqueradestatements say: hey, the source address/port of the packet should be modified.snatis only valid in thepostroutingandinputchains, whilemasquerademakes sense only inpostrouting. - the
dnatandredirectstatements are only valid in thepreroutingandoutputchains โ 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,natstatements require bothpreroutingandpostroutingbase 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 fordnatis 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 to1. 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 asfully-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 withIP_TRANSPARENToption is bound to.portโ Port the listening socket withIP_TRANSPARENToption 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 is0. 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 thelibnetfilter_queuedocumentation 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
setnamemust already exist in the given table. - it must have been created with one or both of the
dynamicand thetimeoutflags. - the
dynamicflag is required if the set statement expression includes a stateful object. - the
timeoutflag 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 optionCONFIG_NETFILTER_NETLINK_HOOKenabled, either as a module or builtin. The module is namednfnetlink_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,nftexits with a status of0โจ1โ unspecified errors cause it to exit with a status of12โ memory allocation errors, status2๐ญ3โ unable to open Netlink socket, status3
๐ฆ 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
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
- alpine 3.24: nftables-doc 1.1.6-r1 ยท GPL-2.0-or-later
- nixos 26.05: nftables 1.1.6
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms