PatrickMcHardykaber@trash.net2008-2014Patrick McHardyPablo NeiraNeira Ayusopablo@netfilter.org2013-2016Pablo Neira Ayusonft8nft
Administration tool of the nftables framework for packet filtering and classification
nft -I
directory -f
filename -i
cmdnft -hnft -vDescription
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.
Show help message and all options.
Show version.
Show data numerically. When used once (the default behaviour), skip
lookup of addresses to symbolic names. Use twice to also show Internet
services (port numbers) numerically. Use three times to also show
protocols and UIDs/GIDs numerically.
Translate IP addresses to names. Usually requires network traffic for DNS lookup.
Omit stateful information of rules and stateful objects.
Check commands validity without actually applying the changes.
Show object handles in output.
When inserting items into the ruleset using add,
insert or replace commands,
print notifications just like nft monitor.
Add the directory directory to the list of directories to be searched for included files. This option may be specified multiple times.
Read input from filename. If filename is -, read from stdin.
nft scripts must start #!/usr/sbin/nft -f
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 formatLexical 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 filesinclude "filename"
Other files can be included by using the include statement.
The directories to be searched for include files can be specified using
the 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 variablesdefinevariable = 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.
IPv4 address family.
IPv6 address family.
Internet (IPv4/IPv6) address family.
ARP address family, handling IPv4 ARP packets.
Bridge address family, handling packets which traverse a bridge device.
Netdev 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.
IPv4/IPv6/Inet address family hooksHookDescriptionprerouting
All 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.
input
Packets delivered to the local system are processed by the input hook.
forward
Packets forwarded to a different host are processed by the forward hook.
output
Packets sent by local processes are processed by the output hook.
postrouting
All 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.
ARP address family hooksHookDescriptioninput
Packets delivered to the local system are processed by the input hook.
output
Packets 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.
Netdev address family hooksHookDescriptioningress
All 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.
Rulesetlistflushrulesetfamilyexportrulesetformat
The ruleset keyword is used to identify the whole
set of tables, chains, etc. currently in place in kernel. The
following ruleset commands exist:
Print the ruleset in human-readable format.
Clear the whole ruleset. Note that unlike iptables, this
will remove all tables and whatever they contain,
effectively leading to an empty ruleset - no packet
filtering will happen anymore, so the kernel accepts any
valid packet it receives.
Print the ruleset in machine readable format. The
mandatory format parameter
may be either xml or
json.
It is possible to limit list and
flush to a specific address family only. For a
list of valid family names, see ADDRESS FAMILIES above.
Note that contrary to what one might assume, the output generated
by export is not parseable by
nft -f. Instead, the output of
list command serves well for that purpose.
Tablesaddcreatetablefamilytable
flags flagsdeletelistflushtablefamilytabledeletetablefamily 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
ipip6inetarpbridgenetdev.
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 flagsFlagDescriptiondormanttable 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
Add a new table for the given family with the given name.
Delete the specified table.
List all chains and rules of the specified table.
Flush all chains and rules of the specified table.
Chainsaddcreatechainfamilytablechain
type type
hook hookdevice device
priority priority ;
policy policy ;deletelistflushchainfamilytablechaindeletechainfamilytable handle handlerenamechainfamilytablechainnewname
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.
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.
Similar to the add command, but returns an error if the
chain already exists.
Delete the specified chain. The chain must not contain any rules or be
used as jump target.
Rename the specified chain.
List all rules of the specified chain.
Flush all rules of the specified chain.
For base chains, type, hook and priority parameters are mandatory.
Supported chain typesTypeFamiliesHooksDescriptionfilterallallStandard chain type to use in doubt.natip, ip6prerouting, input, output, postroutingChains of this type perform Network 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:
netdev family supports merely a single
combination, namely filter type and
ingress hook. Base chains in this family also require the device parameter to be present since they exist per incoming interface only.
arp family supports only
input and output
hooks, both in chains of type
filter.
The priority parameter accepts a signed integer value 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.
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.
Rulesaddinsertrulefamilytablechainhandlepositionhandleindexindexstatement...
replace rulefamilytablechain handle handlestatement...
deleterulefamilytablechain handle handle
Rules are added to chain 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 of an existing
rule or an index (starting at zero). 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.
Add a new rule described by the list of statements. The rule is appended to the
given chain unless a handle is specified, in which case the
rule is appended to the rule given by the handle.
The alternative name position is deprecated and should not be
used anymore.
Similar to the add command, but the rule is prepended to the
beginning of the chain or before the rule with the given
handle.
Similar to the add command, but the rule replaces the specified rule.
Delete 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 setfamilytableset
{ type
type ;
flags flags ;timeout timeout ;gc-interval gc-interval ;elements = { element[,...] } ;size size ;policy policy ;auto-merge auto-merge ;
}
deletelistflush setfamilytablesetdelete setfamilytable handle handleadddelete elementfamilytableset
{
element[,...] }
Sets are elements containers of an user-defined data type, they are uniquely identified by an user-defined name and attached to tables.
Add a new set in the specified table.
Delete the specified set.
Display the elements in the specified set.
Remove all elements from the specified set.
Comma-separated list of elements to add into the specified set.
Comma-separated list of elements to delete from the specified set.
Set specificationsKeywordDescriptionTypetypedata type of set elementsstring: ipv4_addr, ipv6_addr, ether_addr, inet_proto, inet_service, markflagsset flagsstring: constant, interval, timeouttimeouttime 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, sgc-intervalgarbage collection interval, only available when timeout or flag timeout are activestring, decimal followed by unit. Units are: d, h, m, selementselements contained by the setset data typesizemaximum 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], memoryauto-mergeautomatic merge of adjacent/overlapping set elements (only for interval sets)
Mapsadd mapfamilytablemap
{ type
typeflags flags ;elements = { element[,...] } ;size size ;policy policy ;
}
deletelistflush mapfamilytablemapadddelete elementfamilytablemap
{
elements = { element[,...] } ;
}
Maps store data based on some specific key used as input, they are uniquely identified by an user-defined name and attached to tables.
Add a new map in the specified table.
Delete the specified map.
Display the elements in the specified map.
Remove all elements from the specified map.
Comma-separated list of elements to add into the specified map.
Comma-separated list of element keys to delete from the specified map.
Map specificationsKeywordDescriptionTypetypedata 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 keysflagsmap flagsstring: constant, intervalelementselements contained by the mapmap data typesizemaximum number of elements in the mapunsigned integer (64 bit)policymap policystring: performance [default], memory
Flowtablesaddcreateflowtablefamilytableflowtable
hook hook
priority priority ;
devices = { device[,...] } ;
deletelistflowtablefamilytableflowtable
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
what flows you want to offload through the flow offload
expression from the forward chain. Flowtables are
identified by their address family and their name. The address family
must be one of
ipip6inet.
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.
Add a new flowtable for the given family with the given name.
Delete the specified flowtable.
List all flowtables.
Stateful objectsadddeletelistreset typefamilytableobjectdelete typefamilytable handle handle
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".
Add a new stateful object in the specified table.
Delete the specified object.
Display stateful information the object holds.
List-and-reset stateful object.
Ctcthelperhelper { 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.
conntrack helper specificationsKeywordDescriptionTypetypename of helper typequoted string (e.g. "ftp")protocollayer 4 protocol of the helperstring (e.g. tcp)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"
}
}
Countercounterpackets bytes
Counter specificationsKeywordDescriptionTypepacketsinitial count of packetsunsigned integer (64 bit)bytesinitial count of bytesunsigned integer (64 bit)
Quotaquotaoveruntilused
Quota specificationsKeywordDescriptionTypequotaquota limit, used as the quota nameTwo arguments, unsigned integer (64 bit) and string: bytes, kbytes, mbytes. "over" and "until" go before these argumentsusedinitial 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 commanddescribeexpression
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 typeIntegerintegervariable-
The integer type is used for numeric values. It may be specified as decimal, hexadecimal
or octal number. The integer type doesn't have a fixed size, its size is determined by the
expression for which it is used.
Bitmask type
The bitmask type (bitmask) is used for bitmasks.
String type
NameKeywordSizeBase typeStringstringvariable-
The string type is used to 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)"
Link layer address type
The link layer address type is used for link layer addresses. Link layer addresses are specified
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
IPv4 address type
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
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 ipv6 address
ip6 nat prerouting tcp dport 2222 dnat to [1ce::d0]:22
Boolean type
The boolean type is a syntactical helper type in user space.
It's 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).
The following keywords will automatically resolve into a boolean
type with given value:
KeywordValueexists1missing0
Boolean specification
The following expressions support a boolean comparison:
# 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
The ICMPv6 Type type is used to conveniently specify the ICMPv6 header's type field.
The following keywords may be used when specifying the ICMPv6 type:
The ICMPv6 Code type is used to conveniently specify the ICMPv6 header's code field.
The following keywords may be used when specifying the ICMPv6 code:
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.
The following keywords may be used when specifying the ICMPvX code:
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 expressionsmetalengthnfprotol4protoprotocolprioritymetamarkiifiifnameiiftypeoifoifnameoiftypeskuidskgidnftracertclassidibrnameobrnamepkttypecpuiifgroupoifgroupcgrouprandomsecpath
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 expression typesKeywordDescriptionTypelengthLength 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_typepriorityTC packet prioritytc_handlemarkPacket markmarkiifInput interface indexiface_indexiifnameInput interface nameifnameiiftypeInput interface typeiface_typeoifOutput interface indexiface_indexoifnameOutput interface nameifnameoiftypeOutput interface hardware typeiface_typeskuidUID associated with originating socketuidskgidGID associated with originating socketgidrtclassidRouting realmrealmibrnameInput bridge interface nameifnameobrnameOutput bridge interface nameifnamepkttypepacket typepkt_typecpucpu number processing the packetinteger (32 bits)iifgroupincoming device groupdevgroupoifgroupoutgoing device groupdevgroupcgroupcontrol group idinteger (32 bits)randompseudo-random numberinteger (32 bits)secpathbooleanboolean (1 bit)
Meta expression specific typesTypeDescriptioniface_index
Interface index (32 bit number). Can be specified numerically
or as name of an existing interface.
ifname
Interface name (16 byte string). Does not have to exist.
iface_type
Interface type (16 bit number).
uid
User ID (32 bit number). Can be specified numerically or as
user name.
gid
Group ID (32 bit number). Can be specified numerically or as
group name.
realm
Routing Realm (32 bit number). Can be specified numerically
or as symbolic name defined in /etc/iproute2/rt_realms.
devgroup_type
Device group (32 bit number). Can be specified numerically
or as symbolic name defined in /etc/iproute2/group.
pkt_type
Packet type: Unicast (addressed to local host),
Broadcast (to all), Multicast (to group).
Using meta expressions
# qualified meta expression
filter output meta oif eth0
# unqualified meta expression
filter output oif eth0
# packed was subject to ipsec processing
raw prerouting meta secpath exists accept
fib expressionsfibsaddrdaddrmarkiifoifoifoifnametype
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.
Using fib expressions
# drop packets without a reverse path
filter prerouting fib saddr . iif oif missing drop
# 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 expressionsrtclassidnexthop
A routing expression refers to routing data associated with a packet.
Routing expression typesKeywordDescriptionTypeclassidRouting realmrealmnexthopRouting nexthopipv4_addr/ipv6_addrmtuTCP maximum segment size of routeinteger (16 bit)
Routing expression specific typesTypeDescriptionrealm
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
Payload expressions
Payload expressions refer to data from the packet's payload.
Ethernet header expressionetherEthernet header field
Ethernet header expression typesKeywordDescriptionTypedaddrDestination MAC addressether_addrsaddrSource MAC addressether_addrtypeEtherTypeether_type
VLAN header expressionvlanVLAN header field
VLAN header expressionKeywordDescriptionTypeidVLAN ID (VID)integer (12 bit)cfiCanonical Format Indicatorinteger (1 bit)pcpPriority code pointinteger (3 bit)typeEtherTypeether_type
ICMP header expressionKeywordDescriptionTypetypeICMP type fieldicmp_typecodeICMP 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)
IPv6 header expressionip6IPv6 header field
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.
Raw payload expression@base,offset,length
The raw payload expression instructs to load lengthbits starting at offsetbits.
Bit 0 refers the 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 my using meta l4proto 5 before
the raw expression.
Supported payload protocol basesBaseDescriptionllLink layer, for example the Ethernet headernhNetwork header, for example IPv4 or IPv6thTransport Header, for example TCP
Matching destination port of both UDP and TCP
inet filter input meta l4proto {tcp, udp} @th,16,16 { dns, http }
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 and
TCP options.
nftables currently supports matching (finding) a given ipv6 extension header or TCP option.
hbhnexthdrhdrlengthfragnexthdrfrag-offmore-fragmentsidrtnexthdrhdrlengthtypeseg-leftdstnexthdrhdrlengthmhnexthdrhdrlengthchecksumtypesrhflagstagsidseg-lefttcp optioneolnoopmaxsegwindowsack-permittedsacksack0sack1sack2sack3timestamptcp_option_field
The following syntaxes are valid only in a relational expression
with boolean type on right-hand side for checking header existence only:
exthdrhbhfragrtdstmhtcp optioneolnoopmaxsegwindowsack-permittedsacksack0sack1sack2sack3timestamp
finding TCP options
filter input tcp option sack-permitted kind 1 counter
matching IPv6 exthdr
ip6 filter input frag more-fragments 1 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.
ctstatedirectionstatusmarkexpirationhelperlabell3protoprotocolbytespacketsavgpktzonectoriginalreplyl3protoprotocolproto-srcproto-dstbytespacketsavgpktzonectoriginalreplyipip6saddrdaddr
Conntrack expressionsKeywordDescriptionTypestateState of the connectionct_statedirectionDirection of the packet relative to the connectionct_dirstatusStatus of the connectionct_statusmarkConnection markmarkexpirationConnection expiration timetimehelperHelper associated with the connectionstringlabelConnection tracking label bit or symbolic name defined in connlabel.conf in the nftables include pathct_labell3protoLayer 3 protocol of the connectionnf_protosaddrSource address of the connection for the given directionipv4_addr/ipv6_addrdaddrDestination address of the connection for the given directionipv4_addr/ipv6_addrprotocolLayer 4 protocol of the connection for the given directioninet_protoproto-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.
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.
acceptdropqueuecontinuereturnjumpgotochain
Terminate ruleset evaluation and accept the packet.
Terminate ruleset evaluation and drop the packet.
Terminate ruleset evaluation and queue the packet to userspace.
Continue ruleset evaluation with the next rule. FIXME
Return 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 accept.
Continue 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 of a
return verdict is issued.
Similar 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.
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
The payload statement alters packet content.
It can be used for example to set ip DSCP (differv) 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
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 statementlogprefix
quoted_stringlevel
syslog-levelflags
log-flagsloggroup
nflog_groupprefix
quoted_stringqueue-threshold
valuesnaplen
size
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). If the group number 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. This is a non-terminating statement, so the rule evaluation continues after the packet is logged.
log statement optionsKeywordDescriptionTypeprefixLog message prefixquoted stringlevelSyslog level of loggingstring: emerg, alert, crit, err, warn [default], notice, info, debuggroupNFLOG 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)
log-flagsFlagDescriptiontcp 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 statementrejectwithicmpicmp6icmpxtypeicmp_typeicmp6_typeicmpx_typereject with 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.
The different ICMP reject variants are meant for use in different table families:
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.
counterpacketsnumberbytesnumberConntrack statement
The conntrack statement can be used to set the conntrack mark and conntrack labels.
ctmarkeventlabelzonesetvalue
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.
Conntrack statement typesKeywordDescriptionValueeventconntrack event bitsbitmask, integer (32 bit)helpername of ct helper object to assign to the connectionquoted stringmarkConnection tracking markmarklabelConnection tracking labellabelzoneconntrack 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.
metamarkprioritypkttypenftracesetvalue
A meta statement sets meta data associated with a packet.
Meta statement typesKeywordDescriptionValuepriorityTC packet prioritytc_handlemarkPacket markmarkpkttypepacket typepkt_typenftraceruleset packet tracing on/off. Use monitor trace command to watch traces0, 1
Limit statementlimitrateoverpacket_number/secondminutehourdayburst packet_number packetslimitrateoverbyte_numberbyteskbytesmbytes/secondminutehourdayweekburst byte_number bytes
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 over keyword, that is optional, makes it match over the specified rate.
limit statement valuesValueDescriptionTypepacket_numberNumber of packetsunsigned integer (32 bit)byte_numberNumber of bytesunsigned integer (32 bit)
NAT statementssnatto
address:portpersistent, random, fully-randomsnatto
address - address:port - portpersistent, random, fully-randomdnatto
address:portpersistent, random, fully-randomdnatto
address:port - portpersistent, random, fully-randommasqueradeto
:portpersistent, random, fully-randommasqueradeto
:port - portpersistent, random, fully-randomredirectto
:portpersistent, random, fully-randomredirectto
:port - portpersistent, random, fully-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.
Note that all 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.
NAT statement valuesExpressionDescriptionTypeaddressSpecifies 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 bits)
NAT statement flagsFlagDescriptionpersistentGives a client the same source-/destination-address for each connection.randomIf used then port mapping will be randomized using a random 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
Flow offload statement
A flow offload 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 offload@flowtableQueue 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.
queuenum
queue_numberbypassqueuenum
queue_number_from - queue_number_tobypass,fanout
queue statement valuesValueDescriptionTypequeue_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)
queue statement flagsFlagDescriptionbypassLet 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.
dupto
devicedupto
addressdevicedevice
Dup statement valuesExpressionDescriptionTypeaddressSpecifies 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