nft man page

nft — Administration tool of the nftables framework for packet filtering and classification

Examples (TL;DR)

Synopsis

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

Description

nft is the command line tool used to set up, maintain and inspect packet filtering and classification rules in the Linux kernel, in the nftables framework. The Linux kernel subsystem is known as nf_tables, and ‘nf’ stands for Netfilter.

Options

For a full summary of options, run nft --help.

-h, --help

Show help message and all options.

-v, --version

Show version.

-n, --numeric

Print fully numerical output.

-s, --stateless

Omit stateful information of rules and stateful objects.

-N, --reversedns

Translate IP address to names via reverse DNS lookup. This may slow down your listing since it generates network traffic.

-S, --service

Translate ports to service names as defined by /etc/services.

-u, --guid

Translate numeric UID/GID to names as defined by /etc/passwd and /etc/group.

-p, --numeric-protocol

Display layer 4 protocol numerically.

-y, --numeric-priority

Display base chain priority numerically.

-c, --check

Check commands validity without actually applying the changes.

-a, --handle

Show object handles in output.

-e, --echo

When inserting items into the ruleset using add, insert or replace commands, print notifications just like nft monitor.

-j, --json

Format output in JSON. See libnftables-json(5) for a schema description.

-I, --includepath directory

Add the directory directory to the list of directories to be searched for included files. This option may be specified multiple times.

-f, --file filename

Read input from filename. If filename is -, read from stdin.

nft scripts must start #!/usr/sbin/nft -f

-i, --interactive

Read input from an interactive readline CLI. You can use quit to exit, or use the EOF marker, normally this is CTRL-D.

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.

Identifiers begin with an alphabetic character (a-z,A-Z), followed 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 -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 alphabetical order. Files beginning with dot (.) are not matched by include statements.

Symbolic Variables

define variable = expr
$variable

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

Using symbolic variables.

define int_if1 = eth0
define int_if2 = eth1
define int_ifs = { $int_if1, $int_if2 }

filter input iif $int_ifs accept

Address Families

Address families determine the type of packets which are processed. For each address family, the kernel contains so called hooks at specific stages of the packet processing paths, which invoke nftables if rules for these hooks exist.

ipIPv4 address family.
ip6IPv6 address family.
inetInternet (IPv4/IPv6) address family.
arpARP address family, handling IPv4 ARP packets.
bridgeBridge address family, handling packets which traverse a bridge device.
netdevNetdev address family, handling packets from ingress.

All nftables objects exist in address family specific namespaces, therefore all identifiers include an address family. If an identifier is specified without an address family, the ip family is used by default.

IPv4/IPv6/Inet Address Families

The IPv4/IPv6/Inet address families handle IPv4, IPv6 or both types of packets. They contain five hooks at different packet processing stages in the network stack.

Table 1. IPv4/IPv6/Inet address family hooks

HookDescription
preroutingAll packets entering the system are processed by the prerouting hook. It is invoked before the routing process and is used for early filtering or changing packet attributes that affect routing.
inputPackets delivered to the local system are processed by the input hook.
forwardPackets forwarded to a different host are processed by the forward hook.
outputPackets sent by local processes are processed by the output hook.
postroutingAll packets leaving the system are processed by the postrouting hook.

ARP Address Family

The ARP address family handles ARP packets received and sent by the system. It is commonly used to mangle ARP packets for clustering.

Table 2. ARP address family hooks

HookDescription
inputPackets delivered to the local system are processed by the input hook.
outputPackets send by the local system are processed by the output hook.

Bridge Address Family

The bridge address family handles Ethernet packets traversing bridge devices.

The list of supported hooks is identical to IPv4/IPv6/Inet address families above.

Netdev Address Family

The Netdev address family handles packets from ingress.

Table 3. Netdev address family hooks

HookDescription
ingressAll packets entering the system are processed by this hook. It is invoked before layer 3 protocol handlers and it can be used for early filtering and policing.

Ruleset

{list | flush} ruleset [family]

The ruleset keyword is used to identify the whole set of tables, chains, etc. currently in place in kernel. The following ruleset commands exist:

listPrint the ruleset in human-readable format.
flushClear the whole ruleset. Note that, unlike iptables, this will remove all tables and whatever they contain, effectively leading to an empty ruleset - no packet filtering will happen anymore, so the kernel accepts any valid packet it receives.

It is 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.

By design, list ruleset command output may be used as input to nft -f. Effectively, this is the nft-equivalent of iptables-save and iptables-restore.

Tables

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

Tables are containers for chains, sets and stateful objects. They are identified by their address family and their name. The address family must be one of ip, ip6, inet, arp, bridge, netdev. The inet address family is a dummy family which is used to create hybrid IPv4/IPv6 tables. 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 the former will not return an error if the specified table already exists while create will return an error.

Table 4. Table flags

FlagDescription
dormanttable is not evaluated any more (base chains are unregistered).

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 0; }

# 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
addAdd a new table for the given family with the given name.
deleteDelete the specified table.
listList all chains and rules of the specified table.
flushFlush all chains and rules of the specified table.

Chains

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

Chains are containers for rules. They exist 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 jump target and is used for better rule organization.

addAdd 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.
createSimilar to the add command, but returns an error if the chain already exists.
deleteDelete the specified chain. The chain must not contain any rules or be used as jump target.
renameRename the specified chain.
listList all rules of the specified chain.
flushFlush all rules of the specified chain.

For base chains, type, hook and priority parameters are mandatory.

Table 5. Supported chain types

TypeFamiliesHooksDescription
filterallallStandard chain type to use in doubt.
natip, ip6, inetprerouting, input, output, postroutingChains 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).
routeip, ip6outputIf 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 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 two further quirks worth noticing:

The priority parameter accepts a signed integer value or a standard priority name which specifies the order in which chains with same hook value are traversed. The ordering is ascending, i.e. lower priority values have precedence over higher ones.

Standard priority values can be replaced with easily memorizable names. Not all names make sense in every family with every hook (see the compatibility matrices below) but their numerical value can still be used for prioritizing chains.

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. See the following tables that describe the values and compatibility.

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

NameValueFamiliesHooks
raw-300ip, ip6, inetall
mangle-150ip, ip6, inetall
dstnat-100ip, ip6, inetprerouting
filter0ip, ip6, inet, arp, netdevall
security50ip, ip6, inetall
srcnat100ip, ip6, inetpostrouting

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

NameValueHooks
dstnat-300prerouting
filter-200all
out100output
srcnat300postrouting

Basic arithmetic expressions (addition and subtraction) can also be achieved with these standard names to ease relative prioritizing, e.g. mangle - 5 stands for -155. Values will also be printed like this until the value is not further than 10 form the standard value.

Base chains also allow to set the chain’s policy, i.e. what happens to packets not explicitly accepted or refused in 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 rule [family] table chain handle handle

Rules are added to chains in the given table. If the family is not specified, the ip family is used. Rules are constructed from two kinds of components according to a set of grammatical rules: expressions and statements.

The add and insert commands support an optional location specifier, which is either a handle or the index (starting at zero) of an existing rule. Internally, rule locations are always identified by handle and the translation from index happens in userspace. This has two potential implications in case a concurrent ruleset change happens after the translation was done: The effective rule index might change if a rule was inserted or deleted before the referred one. If the referred rule was deleted, the command is rejected by the kernel just as if an invalid handle was given.

A comment is a single word or a double-quoted (") multi-word string which can be used to make notes regarding the actual rule. Note: If you use bash for adding rules, you have to escape the quotation marks, e.g. \"enable ssh for servers\".

addAdd 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.
insertSame as add except the rule is inserted at the beginning of the chain or before the specified rule.
replaceSimilar to add, but the rule replaces the specified rule.
deleteDelete the specified rule.

add a rule to ip table input 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

delete rule from inet table.

# nft -a list ruleset
table inet filter {
        chain input {
                type filter hook input priority 0; 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

Sets

nftables offers two kinds of set concepts. Anonymous sets are sets that have no specific name. The set members are enclosed in curly braces, with commas to separate elements when creating the rule the set is used in. Once that rule is removed, the set is removed as well. They cannot be updated, i.e. once an anonymous set is declared it cannot be changed anymore except by removing/altering the rule that uses the anonymous set.

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 sets that need to be defined first before they can be referenced in rules. 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 sets 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. The next section describes nft set syntax in more detail.

add set [family] table set { type type ; [flags flags ;] [timeout timeout ;] [gc-interval gc-interval ;] [elements = { element[, ...] } ;] [size size ;] [policy policy ;] [auto-merge ;] }
{delete | list | flush} set [family] table set
list sets
delete set [family] table handle handle
{add | delete} 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.

addAdd a new set in the specified table. See the Set specification table below for more information about how to specify a sets properties.
deleteDelete the specified set.
listDisplay the elements in the specified set.
flushRemove all elements from the specified set.
add elementComma-separated list of elements to add into the specified set.
delete elementComma-separated list of elements to delete from the specified set.

Table 8. Set specifications

KeywordDescriptionType
typedata type of set elementsstring: ipv4_addr, ipv6_addr, ether_addr, inet_proto, inet_service, mark
flagsset flagsstring: constant, dynamic, interval, timeout
timeouttime an element stays in the set, mandatory if set is added to from the packet path (ruleset).string, decimal followed by unit. Units are: d, h, m, s
gc-intervalgarbage collection interval, only available when timeout or flag timeout are activestring, decimal followed by unit. Units are: d, h, m, s
elementselements contained by the setset data type
sizemaximum number of elements in the set, mandatory if set is added to from the packet path (ruleset).unsigned integer (64 bit)
policyset policystring: performance [default], memory
auto-mergeautomatic merge of adjacent/overlapping set elements (only for interval sets)

Maps

add map [family] table map { type type [flags flags ;] [elements = { element[, ...] } ;] [size size ;] [policy policy ;] }
{delete | list | flush} map [family] table map
list maps
{add | delete} element [family] table map { elements = { element[, ...] } ; }

Maps store data based on some specific key used as input. They are uniquely identified by a user-defined name and attached to tables.

addAdd a new map in the specified table.
deleteDelete the specified map.
listDisplay the elements in the specified map.
flushRemove all elements from the specified map.
add elementComma-separated list of elements to add into the specified map.
delete elementComma-separated list of element keys to delete from the specified map.

Table 9. Map specifications

KeywordDescriptionType
typedata type of map elementsstring ‘:’ string: ipv4_addr, ipv6_addr, ether_addr, inet_proto, inet_service, mark, counter, quota. Counter and quota can’t be used as keys
flagsmap flagsstring: constant, interval
elementselements contained by the mapmap data type
sizemaximum number of elements in the mapunsigned integer (64 bit)
policymap policystring: performance [default], memory

Flowtables

{add | create} flowtable [family] table flowtable { hook hook priority priority ; devices = { device[, ...] } ; }
{delete | list} flowtable [family] table flowtable

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.

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.

addAdd a new flowtable for the given family with the given name.
deleteDelete the specified flowtable.
listList all flowtables.

Stateful Objects

{add | delete | list | reset} type [family] table object
delete type [family] table handle handle
list counters
list quotas

Stateful objects are attached to tables and are identified by an unique name. They group stateful information from rules, to reference them in rules the keywords "type name" are used e.g. "counter name".

addAdd a new stateful object in the specified table.
deleteDelete the specified object.
listDisplay stateful information the object holds.
resetList-and-reset stateful object.

CT Helper

ct helper helper { type type protocol protocol ; [l3proto family ;] }

Ct helper is used to define connection tracking helpers that can then be used in combination with the ct helper set statement. type and protocol are mandatory, l3proto is derived from the table family by default, i.e. in the inet table the kernel will try to load both the ipv4 and ipv6 helper backends, if they are supported by the kernel.

Table 10. conntrack helper specifications

KeywordDescriptionType
typename of helper typequoted string (e.g. "ftp")
protocollayer 4 protocol of the helperstring (e.g. ip)
l3protolayer 3 protocol of the helperaddress family (e.g. ip)

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 0;
      tcp dport 21 ct helper set "ftp-standard"
  }
}

CT Timeout

ct timeout name { protocol protocol ; policy = { state: value [, ...] } ; [l3proto family ;] }

Ct timeout is used to update connection tracking timeout values.Timeout policies are assigned with the ct timeout set statement. protocol and policy are mandatory, l3proto is derived from the table family by default.

Table 11. conntrack timeout specifications

KeywordDescriptionType
protocollayer 4 protocol of the timeout objectstring (e.g. ip)
stateconnection state namestring (e.g. "established")
valuetimeout value for connection stateunsigned integer
l3protolayer 3 protocol of the timeout objectaddress family (e.g. ip)

defining and assigning ct timeout policy.

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

        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

ct expectation name { protocol protocol ; dport dport ; timeout timeout ; size size ; [*l3proto family ;] }

Ct expectation is used to create connection expectations. Expectations are assigned with the ct expectation set statement. protocol, dport, timeout and size are mandatory, l3proto is derived from the table family by default.

Table 12. conntrack expectation specifications

KeywordDescriptionType
protocollayer 4 protocol of the expectation objectstring (e.g. ip)
dportdestination port of expected connectionunsigned integer
timeouttimeout value for expectationunsigned integer
sizesize value for expectationunsigned integer
l3protolayer 3 protocol of the expectation objectaddress family (e.g. ip)

defining and assigning ct expectation policy.

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

counter [packets bytes]

Table 13. Counter specifications

KeywordDescriptionType
packetsinitial count of packetsunsigned integer (64 bit)
bytesinitial count of bytesunsigned integer (64 bit)

Quota

quota [over | until] [used]

Table 14. Quota specifications

KeywordDescriptionType
quotaquota limit, used as the quota nameTwo arguments, unsigned integer (64 bit) and string: bytes, kbytes, mbytes. "over" and "until" go before these arguments
usedinitial value of used quotaTwo arguments, unsigned integer (64 bit) and string: bytes, kbytes, mbytes

Expressions

Expressions represent values, either constants like network addresses, port numbers, etc., or data gathered from the packet during ruleset evaluation. Expressions can be combined using binary, logical, relational and other types of expressions to form complex or relational (match) expressions. They are also used as arguments to certain types of operations, like NAT, packet marking etc.

Each expression has a data type, which determines the size, parsing and representation of symbolic values and type compatibility with other expressions.

Describe Command

describe expression

The describe command shows information about the type of an expression and its data type.

The describe command.

$ 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 type compatibility of expressions. A number of global data types exist, in addition some expression types define further data types specific to the expression type. Most data types have a fixed size, some however may have a dynamic size, f.i. the string type.

Types may be derived from lower order types, f.i. the IPv4 address type is derived from the integer type, meaning an IPv4 address can also be specified as an integer value.

In certain contexts (set and map definitions), it is necessary to explicitly specify a data type. Each type has a name which is used for this.

Integer Type

NameKeywordSizeBase type
Integerintegervariable-

The integer type is used for numeric values. It may be specified as a decimal, hexadecimal or octal number. The integer type does not have a fixed size, its size is determined by the expression for which it is used.

Bitmask Type

NameKeywordSizeBase type
Bitmaskbitmaskvariableinteger

The bitmask type (bitmask) is used for bitmasks.

String Type

NameKeywordSizeBase type
Stringstringvariable-

The string type is used for character strings. A string begins with an alphabetic character (a-zA-Z) followed by zero or more alphanumeric characters or the characters /, -, _ and .. In addition, anything enclosed in double quotes (") is recognized as a string.

String specification.

# Interface name
filter input iifname eth0

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

IPv4 Address Type

NameKeywordSizeBase type
IPV4 addressipv4_addr32 bitinteger

The IPv4 address type is used 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.

IPv4 address specification.

# dotted decimal notation
filter output ip daddr 127.0.0.1

# host name
filter output ip daddr localhost

IPv6 Address Type

NameKeywordSizeBase type
IPv6 addressipv6_addr128 bitinteger

The IPv6 address type is used for IPv6 addresses. Addresses are specified as a host name or as hexadecimal halfwords separated by colons. Addresses might be enclosed in square brackets ("[]") to differentiate them from port numbers.

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

Boolean Type

NameKeywordSizeBase type
Booleanboolean1 bitinteger

The boolean type is a syntactical helper type in userspace. Its use is in the right-hand side of a (typically implicit) relational expression to change the expression on the left-hand side into a boolean check (usually for existence).

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

KeywordValue
exists1
missing0

Table 16. expressions support a boolean comparison

ExpressionBehaviour
fibCheck route existence.
exthdrCheck IPv6 extension header existence.
tcp optionCheck TCP option header existence.

Boolean specification.

# match if route exists
filter input fib daddr . iif oif 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

ICMP Type Type

NameKeywordSizeBase type
ICMP Typeicmp_type8 bitinteger

The ICMP Type type is used to conveniently specify the ICMP header’s type field.

Table 17. Keywords may be used when specifying the ICMP type

KeywordValue
echo-reply0
destination-unreachable3
source-quench4
redirect5
echo-request8
router-advertisement9
router-solicitation10
time-exceeded11
parameter-problem12
timestamp-request13
timestamp-reply14
info-request15
info-reply16
address-mask-request17
address-mask-reply18

ICMP Type specification.

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

ICMP Code Type

NameKeywordSizeBase type
ICMP Codeicmp_code8 bitinteger

The ICMP Code type is used to conveniently specify the ICMP header’s code field.

Table 18. Keywords may be used when specifying the ICMP code

KeywordValue
net-unreachable0
host-unreachable1
prot-unreachable2
port-unreachable3
net-prohibited9
host-prohibited10
admin-prohibited13

ICMPv6 Type Type

NameKeywordSizeBase type
ICMPv6 Typeicmpx_code8 bitinteger

The ICMPv6 Type type is used to conveniently specify the ICMPv6 header’s type field.

Table 19. keywords may be used when specifying the ICMPv6 type:

KeywordValue
destination-unreachable1
packet-too-big2
time-exceeded3
parameter-problem4
echo-request128
echo-reply129
mld-listener-query130
mld-listener-report131
mld-listener-done132
mld-listener-reduction132
nd-router-solicit133
nd-router-advert134
nd-neighbor-solicit135
nd-neighbor-advert136
nd-redirect137
router-renumbering138
ind-neighbor-solicit141
ind-neighbor-advert142
mld2-listener-report143

ICMPv6 Type specification.

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

ICMPv6 Code Type

NameKeywordSizeBase type
ICMPv6 Codeicmpv6_code8 bitinteger

The ICMPv6 Code type is used to conveniently specify the ICMPv6 header’s code field.

Table 20. keywords may be used when specifying the ICMPv6 code

KeywordValue
no-route0
admin-prohibited1
addr-unreachable3
port-unreachable4
policy-fail5
reject-route6

Icmpvx Code Type

NameKeywordSizeBase type
ICMPvX Codeicmpv6_type8 bitinteger

The ICMPvX Code type abstraction is a set of values which overlap between ICMP and ICMPv6 Code types to be used from the inet family.

Table 21. keywords may be used when specifying the ICMPvX code

KeywordValue
no-route0
port-unreachable1
host-unreachable2
admin-prohibited3

Conntrack Types

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

NameKeywordSizeBase type
conntrack statect_state4 bytebitmask
conntrack directionct_dir8 bitinteger
conntrack statusct_status4 bytebitmask
conntrack event bitsct_event4 bytebitmask
conntrack labelct_label128 bitbitmask

For each of the types above, keywords are available for convenience:

Table 23. conntrack state (ct_state)

KeywordValue
invalid1
established2
related4
new8
untracked64

Table 24. conntrack direction (ct_dir)

KeywordValue
original0
reply1

Table 25. conntrack status (ct_status)

KeywordValue
expected1
seen-reply2
assured4
confirmed8
snat16
dnat32
dying512

Table 26. conntrack event bits (ct_event)

KeywordValue
new1
related2
destroy4
reply8
assured16
protoinfo32
helper64
mark128
seqadj256
secmark512
label1024

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

Primary Expressions

The lowest order expression is a primary expression, representing either a constant or a single datum from a packet’s payload, meta data or a stateful module.

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}

A meta expression refers to meta data associated with a packet.

There are two types of meta expressions: unqualified and qualified meta expressions. Qualified meta expressions require the meta keyword before the meta key, unqualified meta expressions can be specified by using the meta key directly or as qualified meta expressions. 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.

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

iif and oif are used to match on the interface index, whereas iifname and oifname are used to match on the interface name. This is not the same — 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".

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.

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 interface gets deleted and later a new interface with the same name is created.

Table 27. Meta expression types

KeywordDescriptionType
lengthLength of the packet in bytesinteger (32-bit)
nfprotoreal hook protocol family, useful only in inet tableinteger (32 bit)
l4protolayer 4 protocol, skips ipv6 extension headersinteger (8 bit)
protocolEtherType protocol valueether_type
priorityTC packet prioritytc_handle
markPacket markmark
iifInput interface indexiface_index
iifnameInput interface nameifname
iiftypeInput interface typeiface_type
oifOutput interface indexiface_index
oifnameOutput interface nameifname
oiftypeOutput interface hardware typeiface_type
skuidUID associated with originating socketuid
skgidGID associated with originating socketgid
rtclassidRouting realmrealm
ibrnameInput bridge interface nameifname
obrnameOutput bridge interface nameifname
pkttypepacket typepkt_type
cpucpu number processing the packetinteger (32 bit)
iifgroupincoming device groupdevgroup
oifgroupoutgoing device groupdevgroup
cgroupcontrol group idinteger (32 bit)
randompseudo-random numberinteger (32 bit)
ipsecbooleanboolean (1 bit)
iifkindInput interface kind

Table 28. Meta expression specific types

TypeDescription
iface_indexInterface index (32 bit number). Can be specified numerically or as name of an existing interface.
ifnameInterface name (16 byte string). Does not have to exist.
iface_typeInterface type (16 bit number).
uidUser ID (32 bit number). Can be specified numerically or as user name.
gidGroup ID (32 bit number). Can be specified numerically or as group name.
realmRouting Realm (32 bit number). Can be specified numerically or as symbolic name defined in /etc/iproute2/rt_realms.
devgroup_typeDevice group (32 bit number). Can be specified numerically or as symbolic name defined in /etc/iproute2/group.
pkt_typePacket type: host (addressed to local host), broadcast (to all), multicast (to group), other (addressed to another host).
ifkindInterface kind (16 byte string). Does not have to exist.

Using meta expressions.

# qualified meta expression
filter output meta oif eth0

# unqualified meta expression
filter output oif eth0

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

Socket Expression

socket {transparent | mark}

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 looks for an established or non-zero bound listening socket (possibly with a non-local address).

Table 29. Available socket attributes

NameDescriptionType
transparentValue of the IP_TRANSPARENT socket option in the found socket. It can be 0 or 1.boolean (1 bit)
markValue of the socket mark (SOL_SOCKET, SO_MARK).mark

Using socket expression.

# Mark packets that correspond to a transparent socket
table inet x {
    chain y {
        type filter hook prerouting priority -150; policy accept;
        socket transparent 1 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 -150; policy accept;
        socket mark 0x0000000f nftrace set 1
    }
}

# Set packet mark to socket mark
table inet x {
    chain y {
        type filter hook prerouting priority -150; policy accept;
        tcp dport 8080 mark set socket mark
    }
}

Osf Expression

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

The osf expression does passive operating system fingerprinting. This expression compares some data (Window Size, MSS, options and their order, DF, and others) from packets with the SYN bit set.

Table 30. Available osf attributes

NameDescriptionType
ttlDo TTL checks on the packet to determine the operating system.string
versionDo OS version checks on the packet.
nameName of the OS signature to match. All signatures can be found at pf.os file. Use "unknown" for OS signatures that the expression could not detect.string

Available ttl values.

If no TTL attribute is passed, make a true IP header and 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.

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 0; policy accept;
        osf ttl skip name "Linux"
    }
}

Fib Expressions

fib {saddr | daddr | mark | iif | oif} [. ...] {oif | oifname | type}

A fib expression queries the fib (forwarding information base) to obtain information such as the output interface index a particular address would use. The input is a tuple of elements that is used as input to the fib lookup functions.

Table 31. fib expression specific types

KeywordDescriptionType
oifOutput interface indexinteger (32 bit)
oifnameOutput interface namestring
typeAddress typefib_addrtype

Using fib expressions.

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

In this example, 'saddr . iif' looks up routing information based on the source address and the input interface.
oif picks the output interface index from the routing information.
If no route was found for the source address/input interface combination, the output interface index is zero.
In case the input interface is specified as part of the input key, the output interface index is always the same as the input interface index or zero.
If only 'saddr oif' is given, then oif can be any interface index or zero.

In this example, 'saddr . iif' lookups up routing information based on the source address and the input interface.
oif picks the output interface index from the routing information.
If no route was found for the source address/input interface combination, the output interface index is zero.
In case the input interface is specified as part of the input key, the output interface index is always the same as the input interface index or zero.
If only 'saddr oif' is given, then oif can be any interface index or zero.

# drop packets to address not configured on ininterface
filter prerouting fib daddr . iif type != { local, broadcast, multicast } drop

# 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.

Table 32. Routing expression types

KeywordDescriptionType
classidRouting realmrealm
nexthopRouting nexthopipv4_addr/ipv6_addr
mtuTCP maximum segment size of routeinteger (16 bit)
ipsecroute via ipsec tunnel or transportboolean

Table 33. Routing expression specific types

TypeDescription
realmRouting 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
filter output rt ipsec missing

# 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

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 34. Ipsec expression types

KeywordDescriptionType
reqidRequest IDinteger (32 bit)
spiSecurity Parameter Indexinteger (32 bit)
saddrSource address of the tunnelipv4_addr/ipv6_addr
daddrDestination address of the tunnelipv4_addr/ipv6_addr

Payload Expressions

Payload expressions refer to data from the packet’s payload.

Ethernet Header Expression

ether {daddr | saddr | type}

Table 35. Ethernet header expression types

KeywordDescriptionType
daddrDestination MAC addressether_addr
saddrSource MAC addressether_addr
typeEtherTypeether_type

Vlan Header Expression

vlan {id | cfi | pcp | type}

Table 36. VLAN header expression

KeywordDescriptionType
idVLAN ID (VID)integer (12 bit)
cfiCanonical Format Indicatorinteger (1 bit)
pcpPriority code pointinteger (3 bit)
typeEtherTypeether_type

ARP Header Expression

arp {htype | ptype | hlen | plen | operation | saddr { ip | ether } | daddr { ip | ether }

Table 37. ARP header expression

KeywordDescriptionType
htypeARP hardware typeinteger (16 bit)
ptypeEtherTypeether_type
hlenHardware address leninteger (8 bit)
plenProtocol address leninteger (8 bit)
operationOperationarp_op
saddr etherEthernet sender addressether_addr
daddr etherEthernet target addressether_addr
saddr ipIPv4 sender addressipv4_addr
daddr ipIPv4 target addressipv4_addr

IPv4 Header Expression

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

Table 38. IPv4 header expression

KeywordDescriptionType
versionIP header version (4)integer (4 bit)
hdrlengthIP header length including optionsinteger (4 bit) FIXME scaling
dscpDifferentiated Services Code Pointdscp
ecnExplicit Congestion Notificationecn
lengthTotal packet lengthinteger (16 bit)
idIP IDinteger (16 bit)
frag-offFragment offsetinteger (16 bit)
ttlTime to liveinteger (8 bit)
protocolUpper layer protocolinet_proto
checksumIP header checksuminteger (16 bit)
saddrSource addressipv4_addr
daddrDestination addressipv4_addr

ICMP Header Expression

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

This expression refers to ICMP header fields. When using it in inet, bridge or netdev families, it will cause an implicit dependency on IPv4 to be created. To match on unusual cases like ICMP over IPv6, one has to add an explicit meta protocol ip6 match to the rule.

Table 39. ICMP header expression

KeywordDescriptionType
typeICMP type fieldicmp_type
codeICMP code fieldinteger (8 bit)
checksumICMP checksum fieldinteger (16 bit)
idID of echo request/responseinteger (16 bit)
sequencesequence number of echo request/responseinteger (16 bit)
gatewaygateway of redirectsinteger (32 bit)
mtuMTU of path MTU discoveryinteger (16 bit)

IGMP Header Expression

igmp {type | mrt | checksum | group}

This expression refers to IGMP header fields. When using it in inet, bridge or netdev families, it will cause an implicit dependency on IPv4 to be created. To match on unusual cases like IGMP over IPv6, one has to add an explicit meta protocol ip6 match to the rule.

Table 40. IGMP header expression

KeywordDescriptionType
typeIGMP type fieldigmp_type
mrtIGMP maximum response time fieldinteger (8 bit)
checksumICMP checksum fieldinteger (16 bit)
groupGroup addressinteger (32 bit)

IPv6 Header Expression

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

This expression refers to the ipv6 header fields. Caution when using ip6 nexthdr, the value only refers to the next header, i.e. ip6 nexthdr tcp will only match if the ipv6 packet does not contain any extension headers. Packets that are fragmented or e.g. contain a routing extension headers will not be matched. Please use meta l4proto if you wish to match the real transport header and ignore any additional extension headers instead.

Table 41. IPv6 header expression

KeywordDescriptionType
versionIP header version (6)integer (4 bit)
dscpDifferentiated Services Code Pointdscp
ecnExplicit Congestion Notificationecn
flowlabelFlow labelinteger (20 bit)
lengthPayload lengthinteger (16 bit)
nexthdrNexthdr protocolinet_proto
hoplimitHop limitinteger (8 bit)
saddrSource addressipv6_addr
daddrDestination addressipv6_addr

Using ip6 header expressions.

# 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}

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.

Table 42. ICMPv6 header expression

KeywordDescriptionType
typeICMPv6 type fieldicmpv6_type
codeICMPv6 code fieldinteger (8 bit)
checksumICMPv6 checksum fieldinteger (16 bit)
parameter-problempointer to probleminteger (32 bit)
packet-too-bigoversized MTUinteger (32 bit)
idID of echo request/responseinteger (16 bit)
sequencesequence number of echo request/responseinteger (16 bit)
max-delaymaximum response delay of MLD queriesinteger (16 bit)

TCP Header Expression

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

Table 43. TCP header expression

KeywordDescriptionType
sportSource portinet_service
dportDestination portinet_service
sequenceSequence numberinteger (32 bit)
ackseqAcknowledgement numberinteger (32 bit)
doffData offsetinteger (4 bit) FIXME scaling
reservedReserved areainteger (4 bit)
flagsTCP flagstcp_flag
windowWindowinteger (16 bit)
checksumChecksuminteger (16 bit)
urgptrUrgent pointerinteger (16 bit)

UDP Header Expression

udp {sport | dport | length | checksum}

Table 44. UDP header expression

KeywordDescriptionType
sportSource portinet_service
dportDestination portinet_service
lengthTotal packet lengthinteger (16 bit)
checksumChecksuminteger (16 bit)

UDP-Lite Header Expression

udplite {sport | dport | checksum}

Table 45. UDP-Lite header expression

KeywordDescriptionType
sportSource portinet_service
dportDestination portinet_service
checksumChecksuminteger (16 bit)

SCTP Header Expression

sctp {sport | dport | vtag | checksum}

Table 46. SCTP header expression

KeywordDescriptionType
sportSource portinet_service
dportDestination portinet_service
vtagVerification Taginteger (32 bit)
checksumChecksuminteger (32 bit)

DCCP Header Expression

dccp {sport | dport}

Table 47. DCCP header expression

KeywordDescriptionType
sportSource portinet_service
dportDestination portinet_service

Authentication Header Expression

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

Table 48. AH header expression

KeywordDescriptionType
nexthdrNext header protocolinet_proto
hdrlengthAH Header lengthinteger (8 bit)
reservedReserved areainteger (16 bit)
spiSecurity Parameter Indexinteger (32 bit)
sequenceSequence numberinteger (32 bit)

Encrypted Security Payload Header Expression

esp {spi | sequence}

Table 49. ESP header expression

KeywordDescriptionType
spiSecurity Parameter Indexinteger (32 bit)
sequenceSequence numberinteger (32 bit)

Ipcomp Header Expression

comp {nexthdr | flags | cpi}

Table 50. IPComp header expression

KeywordDescriptionType
nexthdrNext header protocolinet_proto
flagsFlagsbitmask
cpicompression Parameter Indexinteger (16 bit)

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.

Table 51. Supported payload protocol bases

BaseDescription
llLink layer, for example the Ethernet header
nhNetwork header, for example IPv4 or IPv6
thTransport Header, for example TCP

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.

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 | noop | maxseg | window | sack-permitted | sack | sack0 | sack1 | sack2 | sack3 | timestamp} 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 | noop | maxseg | window | sack-permitted | sack | sack0 | sack1 | sack2 | sack3 | timestamp}
ip option { lsrr | ra | rr | ssrr }

Table 52. IPv6 extension headers

KeywordDescription
hbhHop by Hop
rtRouting Header
fragFragmentation header
dstdst options
mhMobility Header
srhSegment Routing Header

Table 53. TCP Options

KeywordDescriptionTCP option fields
eolEnd if option listkind
noop1 Byte TCP No-op optionskind
maxsegTCP Maximum Segment Sizekind, length, size
windowTCP Window Scalingkind, length, count
sack-permittedTCP SACK permittedkind, length
sackTCP Selective Acknowledgement (alias of block 0)kind, length, left, right
sack0TCP Selective Acknowledgement (block 0)kind, length, left, right
sack1TCP Selective Acknowledgement (block 1)kind, length, left, right
sack2TCP Selective Acknowledgement (block 2)kind, length, left, right
sack3TCP Selective Acknowledgement (block 3)kind, length, left, right
timestampTCP Timestampskind, length, tsval, tsecr

Table 54. IP Options

KeywordDescriptionIP option fields
lsrrLoose Source Routetype, length, ptr, addr
raRouter Alerttype, length, value
rrRecord Routetype, length, ptr, addr
ssrrStrict Source Routetype, length, ptr, addr

finding TCP options.

filter input tcp option sack-permitted kind 1 counter

matching IPv6 exthdr.

ip6 filter input frag more-fragments 1 counter

finding IP option.

filter input ip option lsrr exists counter

Conntrack Expressions

Conntrack expressions refer to meta data of the connection tracking entry associated with a packet.

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. The same is true for the zone, if a direction is given, the zone is only matched if the zone id is tied to the given direction.

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

Table 55. Conntrack expressions

KeywordDescriptionType
stateState of the connectionct_state
directionDirection of the packet relative to the connectionct_dir
statusStatus of the connectionct_status
markConnection markmark
expirationConnection expiration timetime
helperHelper associated with the connectionstring
labelConnection tracking label bit or symbolic name defined in connlabel.conf in the nftables include pathct_label
l3protoLayer 3 protocol of the connectionnf_proto
saddrSource address of the connection for the given directionipv4_addr/ipv6_addr
daddrDestination address of the connection for the given directionipv4_addr/ipv6_addr
protocolLayer 4 protocol of the connection for the given directioninet_proto
proto-srcLayer 4 protocol source for the given directioninteger (16 bit)
proto-dstLayer 4 protocol destination for the given directioninteger (16 bit)
packetspacket count seen in the given direction or sum of original and replyinteger (64 bit)
bytesbyte count seen, see description for packets keywordinteger (64 bit)
avgpktaverage bytes per packet, see description for packets keywordinteger (64 bit)
zoneconntrack zoneinteger (16 bit)

A description of conntrack-specific types listed above can be found sub-section Conntrack Types above.

restrict the number of parallel connections to a server.

filter input tcp dport 22 meter test { ip saddr ct count over 2 } reject

Statements

Statements represent actions to be performed. They can alter control flow (return, jump to a different chain, accept or drop the packet) or can perform actions, such as logging, rejecting a packet, etc.

Statements exist in two kinds. Terminal statements unconditionally terminate evaluation of the current rule, non-terminal statements either only conditionally or never terminate evaluation of the current rule, in other words, they are passive from the ruleset evaluation perspective. There can be an arbitrary amount of non-terminal statements in a rule, but only a single terminal statement as the final statement.

Verdict Statement

The verdict statement alters control flow in the ruleset and issues policy decisions for packets.

{accept | drop | queue | continue | return}
{jump | goto} chain

accept and drop are absolute verdicts — they terminate ruleset evaluation immediately.

acceptTerminate ruleset evaluation and accept the packet. The packet can still be dropped later by another hook, for instance accept in the forward hook still allows to drop the packet later in the postrouting hook, or another forward base chain that has a higher priority number and is evaluated afterwards in the processing pipeline.
dropTerminate ruleset evaluation and drop the packet. The drop occurs instantly, no further chains or hooks are evaluated. It is not possible to accept the packet in a later chain again, as those are not evaluated anymore for the packet.
queueTerminate ruleset evaluation and queue the packet to userspace. Userspace must provide a drop or accept verdict. In case of accept, processing resumes with the next base chain hook, not the rule following the queue verdict.
continueContinue ruleset evaluation with the next rule. This is the default behaviour in case a rule issues no verdict.
returnReturn from the current chain and continue evaluation at the next rule in the last chain. If issued in a base chain, it is equivalent to the base chain policy.
jump chainContinue evaluation at the first rule in chain. The current position in the ruleset is pushed to a call stack and evaluation will continue there when the new chain is entirely evaluated or a return verdict is issued. In case an absolute verdict is issued by a rule in the chain, ruleset evaluation terminates immediately and the specific action is taken.
goto chainSimilar to jump, but the current position is not pushed to the call stack, meaning that after the new chain evaluation will continue at the last chain instead of the one containing the goto statement.

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

Payload Statement

payload_expression set value

The payload statement alters packet content. It can be used for example to set 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 unicast 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. This can currently be used to alter the TCP Maximum segment size of packets, similar to TCPMSS.

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

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, such as header fields, 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 multicast the packet through a netlink socket to the specified multicast group. One or more userspace processes may subscribe to the group to receive the packets, see libnetfilter_queue documentation for details.

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 the rule evaluation continues after the packet is logged.

Table 56. log statement options

KeywordDescriptionType
prefixLog message prefixquoted string
levelSyslog level of loggingstring: emerg, alert, crit, err, warn [default], notice, info, debug, audit
groupNFLOG group to send messages tounsigned integer (16 bit)
snaplenLength of packet payload to include in netlink messageunsigned integer (32 bit)
queue-thresholdNumber of packets to queue inside the kernel before sending them to userspaceunsigned integer (32 bit)

Table 57. log-flags

FlagDescription
tcp sequenceLog TCP sequence numbers.
tcp optionsLog options from the TCP packet header.
ip optionsLog options from the IP/IPv6 packet header.
skuidLog the userid of the process which generated the packet.
etherDecode MAC addresses and protocol.
allEnable 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 type icmp_code |
                 icmpv6 type icmpv6_code |
                 icmpx type icmpx_code |
                 tcp reset

A reject statement is used to send back an error packet in response to the matched packet otherwise it is equivalent to drop so it is a terminating statement, ending rule traversal. This statement is only valid in the input, forward and output chains, and user-defined chains which are only called from those chains.

Table 58. different ICMP reject variants are meant for use in different table families

VariantFamilyType
icmpipicmp_code
icmpv6ip6icmpv6_code
icmpxineticmpx_code

For a description of the different types and a list of supported keywords refer to Data Types section above. The common default reject value is port-unreachable.

Note that in bridge family, reject statement is only allowed in base chains which hook into input or prerouting.

Counter Statement

A counter statement sets the hit count of packets along with the number of bytes.

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

Conntrack Statement

The conntrack statement can be used to set the conntrack mark and conntrack labels.

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

The ct statement sets meta data associated with a connection. The zone id has to be assigned before a conntrack lookup takes place, i.e. this has to be done in prerouting and possibly output (if locally generated packets need to be placed in a distinct zone), with a hook priority of -300.

Table 59. Conntrack statement types

KeywordDescriptionValue
eventconntrack event bitsbitmask, integer (32 bit)
helpername of ct helper object to assign to the connectionquoted string
markConnection tracking markmark
labelConnection tracking labellabel
zoneconntrack zoneinteger (16 bit)

save packet nfmark in conntrack.

ct mark set meta mark

set zone mapped via interface.

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

restrict events reported by ctnetlink.

ct event set new,related,destroy

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} set value

A meta statement sets meta data associated with a packet.

Table 60. Meta statement types

KeywordDescriptionValue
priorityTC packet prioritytc_handle
markPacket markmark
pkttypepacket typepkt_type
nftraceruleset packet tracing on/off. Use monitor trace command to watch traces0, 1

Limit Statement

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

A limit statement matches at a limited rate using a token bucket filter. A rule using this statement will match until this limit is reached. It can be used in combination with the log statement to give limited logging. The optional over keyword makes it match over the specified rate.

Table 61. limit statement values

ValueDescriptionType
packet_numberNumber of packetsunsigned integer (32 bit)
byte_numberNumber of bytesunsigned integer (32 bit)

Nat Statements

snat to address [:port] [PRF_FLAGS]
snat to address - address [:port - port] [PRF_FLAGS]
snat to { ip | ip6 } address - address [:port - port] [PR_FLAGS]
dnat to address [:port] [PRF_FLAGS]
dnat to address [:port - port] [PR_FLAGS]
dnat to { ip | ip6 } address [:port - port] [PR_FLAGS]
masquerade to [:port] [PRF_FLAGS]
masquerade to [:port - port] [PRF_FLAGS]
redirect to [:port] [PRF_FLAGS]
redirect to [:port - port] [PRF_FLAGS]

PRF_FLAGS := PRF_FLAG [, PRF_FLAGS]
PR_FLAGS  := PR_FLAG [, PR_FLAGS]
PRF_FLAG  := PR_FLAG | fully-random
PR_FLAG   := persistent | random

The nat statements are only valid from nat chain types.

The snat and masquerade statements specify that the source address of the packet should be modified. While snat is only valid in the postrouting and input chains, masquerade makes sense only in postrouting. The dnat and redirect statements are only valid in the prerouting and output chains, they specify that the destination address of the packet should be modified. You can use non-base chains which are called from base chains of nat chain type too. All future packets in this connection will also be mangled, and rules should cease being examined.

The masquerade statement is a special form of snat which always uses the outgoing interface’s IP address to translate to. It is particularly useful on gateways with dynamic (public) IP addresses.

The redirect statement is a special form of dnat which always translates the destination address to the local host’s one. It comes in handy if one only wants to alter the destination port of incoming traffic on different interfaces.

When used in the inet family (available with kernel 5.2), the dnat and snat statements require the use of the ip and ip6 keyword in case an address is provided, see the examples below.

Before kernel 4.18 nat statements require both prerouting and postrouting base chains to be present since otherwise packets on the return path won’t be seen by netfilter and therefore no reverse translation will take place.

Table 62. NAT statement values

ExpressionDescriptionType
addressSpecifies 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.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 }
portSpecifies that the source/destination address of the packet should be modified.port number (16 bit)

Table 63. NAT statement flags

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

Using NAT statements.

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

# 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

Tproxy Statement

Tproxy redirects the packet to a local socket without changing the packet header in any way. If any of the arguments is missing the data of the incoming packet is used as parameter. Tproxy matching requires another rule that ensures the presence of transport protocol header is specified.

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

This syntax can be used in ip/ip6 tables where network layer protocol is obvious. Either IP address or port can be specified, but at least one of them is necessary.

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

This syntax can be used in inet tables. The ip/ip6 parameter defines the family the rule will match. The address parameter must be of this family. When only port is defined, the address family should not be specified. In this case the rule will match for both families.

Table 64. tproxy attributes

NameDescription
addressIP address the listening socket with IP_TRANSPARENT option is bound to.
portPort the listening socket with IP_TRANSPARENT option is bound to.

Example ruleset for tproxy statement.

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

Synproxy Statement

This statement will process TCP three-way-handshake parallel in netfilter context to protect either local or backend system. This statement requires connection tracking because sequence numbers need to be translated.

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

Table 65. synproxy statement attributes

NameDescription
mssMaximum segment size announced to clients. This must match the backend.
wscaleWindow scale announced to clients. This must match the backend.

Table 66. synproxy statement flags

FlagDescription
sack-permPass client selective acknowledgement option to backend (will be disabled if not present).
timestampPass client timestamp option to backend (will be disabled if not present, also needed for selective acknowledgement and window scaling).

Example ruleset for synproxy statement.

Determine tcp options used by 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

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

Make SYN packets untracked.

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

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 valid client response (3WHS ACK packets) and
drop incorrect cookies. Flags combinations not expected during  3WHS will not
match and continue (e.g. SYN+FIN, SYN+ACK). Finally, drop invalid packets, this
will be out-of-flow packets that were not matched by SYNPROXY.

    table ip foo {
            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
            }
    }

The outcome ruleset of the steps above should be similar to the one below.

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

                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 allows us to select what flows you want to accelerate forwarding through layer 3 network stack bypass. You have to specify the flowtable name where you want to offload this flow.

flow add @flowtable

Queue Statement

This statement passes the packet to userspace using the nfnetlink_queue handler. The packet is put into the queue identified by its 16-bit queue number. Userspace can inspect and modify the packet if desired. Userspace must then drop or re-inject the packet into the kernel. See libnetfilter_queue documentation for details.

queue [num queue_number] [bypass]
queue [num queue_number_from - queue_number_to] [QUEUE_FLAGS]

QUEUE_FLAGS := QUEUE_FLAG [, QUEUE_FLAGS]
QUEUE_FLAG  := bypass | fanout

Table 67. queue statement values

ValueDescriptionType
queue_numberSets queue number, default is 0.unsigned integer (16 bit)
queue_number_fromSets initial queue in the range, if fanout is used.unsigned integer (16 bit)
queue_number_toSets closing queue in the range, if fanout is used.unsigned integer (16 bit)

Table 68. queue statement flags

FlagDescription
bypassLet packets go through if userspace application cannot back off. Before using this flag, read libnetfilter_queue documentation for performance tuning recommendations.
fanoutDistribute packets between several queues.

Dup Statement

The dup statement is used to duplicate a packet and send the copy to a different destination.

dup to device
dup to address device device

Table 69. Dup statement values

ExpressionDescriptionType
addressSpecifies that the copy of the packet should be sent to a new gateway.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 }
deviceSpecifies that the copy should be transmitted via device.string

Using the dup statement.

# 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
netdetv 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 is used to redirect a raw packet to another interface. It is only available in the netdev family ingress hook. It is similar to the dup statement except that no copy is made.

fwd to device

Set Statement

The set statement is used to dynamically add or update elements in a set from the packet path. The set setname must already exist in the given table and must have been created with the dynamic flag. Furthermore, these sets must specify both a maximum set size (to prevent memory exhaustion) and a timeout (so that number of entries in set will not grow indefinitely). The set statement can be used to e.g. create dynamic blacklists.

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

Example for 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.
nft add set ip filter blackhole "{ type ipv4_addr; flags timeout; size 65536; }"

# 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.
# entries will timeout after one minute, after which they might be re-added if limit condition persists.
nft add rule ip filter input tcp flags syn tcp dport ssh meter flood size 128000 { ip saddr timeout 10s limit rate over 10/second} add @blackhole { ip saddr timeout 1m } drop

# inspect state of the rate limit meter:
nft list meter ip filter flood

# inspect content of blackhole:
nft list set ip filter blackhole

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

Map Statement

The map statement is used to lookup data based on some specific input key.

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, but contains verdicts as values.

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 }

Additional Commands

These are some additional commands included in nft.

Monitor

The monitor command allows you to listen to Netlink events produced by the nf_tables subsystem, related to creation and deletion of objects. When they occur, nft will print to stdout the monitored events in either JSON or native nft format.

To filter events related to a concrete object, use one of the keywords tables, chains, sets, rules, elements, ruleset.

To filter events related to a concrete action, use keyword new or destroy.

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

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 and the entire command is marked.

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

On success, nft exits with a status of 0. Unspecified errors cause it to exit with a status of 1, memory allocation errors with a status of 2, unable to open Netlink socket with 3.

See Also

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

There is an official wiki at: https://wiki.nftables.org

Authors

nftables was written by Patrick McHardy and Pablo Neira Ayuso, among many other contributors from the Netfilter community.

Referenced By

conntrackd(8), libnftables(3), xtables-monitor(8), xtables-nft(8), xtables-translate(8).

08/23/2019