nft man page

nft — Administration tool for packet filtering and classification

Synopsis

nft [ -n | --numeric ] [ [-I | --includepath] directory ] [ [-f | --file] filename | [-i | --interactive] | cmd ...] nft [ -h | --help ] [ -v | --version ]

Description

nft is used to set up, maintain and inspect packet filtering and classification rules in the Linux kernel.

Options

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

-h, --help

Show help message and all options.

-v, --version

Show version.

-n, --numeric

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.

-N

Translate IP addresses to names. Usually requires network traffic for DNS lookup.

-a, --handle

Show rule handles in output.

-I, --includepath directory

Add the directory directory to the list of directories to be searched for included files.

-f, --file filename

Read input from filename.

-i, --interactive

Read input from an interactive readline CLI.

Input File Format

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.

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.

ip

IPv4 address family.

ip6

IPv6 address family.

inet

Internet (IPv4/IPv6) address family.

arp

ARP address family, handling packets vi

bridge

Bridge address family, handling packets which traverse a bridge device.

netdev

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

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.

Netdev Address Family

The Netdev address family handles packets from ingress.

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.

Tables

{add | delete | list | flush} table [family] {table}

Tables are containers for chains and sets. 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. When no address family is specified, ip is used by default.

add

Add a new table for the given family with the given name.

delete

Delete the specified table.

list

List all chains and rules of the specified table.

flush

Flush all chains and rules of the specified table.

Chains

{add} chain [family] {table} {chain} {hook} {priority} {policy} {device} {add | create | delete | list | flush} chain [family] {table} {chain} {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.

add

Add a new chain in the specified table. When a hook and priority value are specified, the chain is created as a base chain and hooked up to the networking stack.

create

Simlar to the add command, but returns an error if the chain already exists.

delete

Delete the specified chain. The chain must not contain any rules or be used as jump target.

rename

Rename the specified chain.

list

List all rules of the specified chain.

flush

Flush all rules of the specified chain.

Rules

[add | insert] rule [family] {table} {chain} [position position] {statement}... {delete} rule [family] {table} {chain} {handle handle}

Rules are constructed from two kinds of components according to a set of grammatical rules: expressions and statements.

add

Add a new rule described by the list of statements. The rule is appended to the given chain unless a position is specified, in which case the rule is appended to the rule given by the position.

insert

Similar to the add command, but the rule is prepended to the beginning of the chain or before the rule at the given position.

delete

Delete the specified rule.

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

pre-defined 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 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

NameKeywordSizeBase type
Bitmaskbitmaskvariableinteger

The bitmask type (bitmask) is used for bitmasks.

String Type

NameKeywordSizeBase type
Stringstringvariable-

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)"

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

IPv6 address specification

# abbreviated loopback address
filter output ip6 daddr ::1

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 | ibriport | obriport | pkttype | cpu | iifgroup | oifgroup | cgroup | random}

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 expression types

KeywordDescriptionType
lengthLength of the packet in bytesinteger (32 bit)
protocolEthertype protocol valueether_type
priorityTC packet prioritytc_handle
markPacket markmark
iifInput interface indexiface_index
iifnameInput interface namestring
iiftypeInput interface typeiface_type
oifOutput interface indexiface_index
oifnameOutput interface namestring
oiftypeOutput interface hardware typeiface_type
skuidUID associated with originating socketuid
skgidGID associated with originating socketgid
rtclassidRouting realmrealm
ibriportInput bridge interface namestring
obriportOutput bridge interface namestring
pkttypepacket typepkt_type
cpucpu number processing the packetinteger (32 bits)
iifgroupincoming device groupdevgroup
oifgroupoutgoing device groupdevgroup
cgroupcontrol group idinteger (32 bits)
randompseudo-random numberinteger (32 bits)

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: 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

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.

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 eq 0 drop

# drop packets to address not configured on ininterface
filter input fib daddr . iif type not { 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 { backhole : drop, prohibit : jump prohibited, unreachable : drop }

Routing Expressions

rt {classid | nexthop}

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

Routing expression types

KeywordDescriptionType
classidRouting realmrealm
nexthopRouting nexthopipv4_addr/ipv6_addr

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

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

Payload Expressions

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

Ethernet Header Expression

ether [ethernet header field]

Ethernet header expression types

KeywordDescriptionType
daddrDestination MAC addressether_addr
saddrSource MAC addressether_addr
typeEtherTypeether_type

Vlan Header Expression

vlan [VLAN header field]

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 [ARP header field]

ARP header expression

KeywordDescriptionType
htypeARP hardware typeinteger (16 bit)
ptypeEtherTypeether_type
hlenHardware address leninteger (8 bit)
plenProtocol address leninteger (8 bit)
operationOperationarp_op

IPv4 Header Expression

ip [IPv4 header field]

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

IPv6 Header Expression

ip6 [IPv6 header field]

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

TCP Header Expression

tcp [TCP header field]

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 [UDP header field]

UDP header expression

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

UDP-Lite Header Expression

udplite [UDP-Lite header field]

UDP-Lite header expression

KeywordDescriptionType
sportSource portinet_service
dportDestination portinet_service
checksumChecksuminteger (16 bit)

SCTP Header Expression

sctp [SCTP header field]

SCTP header expression

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

DCCP Header Expression

dccp [DCCP header field]

DCCP header expression

KeywordDescriptionType
sportSource portinet_service
dportDestination portinet_service

Authentication Header Expression

ah [AH header field]

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 [ESP header field]

ESP header expression

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

Ipcomp Header Expression

comp [IPComp header field]

IPComp header expression

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

Bla

IPv6 Extension Header Expressions

IPv6 extension header expressions refer to data from an IPv6 packet's extension headers.

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 and bytes 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.

ct {state | direction | status | mark | expiration | helper | label | l3proto | protocol | bytes | packets} ct {original | reply} {l3proto | protocol | saddr | daddr | proto-src | proto-dst | bytes | packets}

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)
bytesbytecount seen, see description for packets keywordinteger (64 bit)

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

Terminate ruleset evaluation and accept the packet.

drop

Terminate ruleset evaluation and drop the packet.

queue

Terminate ruleset evaluation and queue the packet to userspace.

continue

Continue ruleset evaluation with the next rule. FIXME

return

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.

jump chain

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.

goto chain

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

Log Statement

log [prefix quoted_string] [level syslog-level] [flags log-flags] log group nflog_group [prefix quoted_string] [queue-threshold value] [snaplen 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 options

KeywordDescriptionType
prefixLog message prefixquoted string
syslog-levelSyslog level of loggingstring: emerg, alert, crit, err, warn [default], notice, info, debug
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)

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 {icmp | icmp6 | icmpx} type {icmp_type | icmp6_type | icmpx_type} reject 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.

reject statement type (ip)

ValueDescriptionType
icmp_typeICMP type response to be sent to the hostnet-unreachable, host-unreachable, prot-unreachable, port-unreachable [default], net-prohibited, host-prohibited, admin-prohibited

reject statement type (ip6)

ValueDescriptionType
icmp6_typeICMPv6 type response to be sent to the hostno-route, admin-prohibited, addr-unreachable, port-unreachable [default], policy-fail, reject-route

reject statement type (inet)

ValueDescriptionType
icmpx_typeICMPvXtype abstraction response to be sent to the host, this is a set of types that overlap in IPv4 and IPv6 to be used from the inet family.port-unreachable [default], admin-prohibited, no-route, host-unreachable

Counter Statement

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

counter {packets number } {bytes number }

Conntrack Statement

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

ct {mark | label} set value

The ct statement sets meta data associated with a connection.

Meta statement types

KeywordDescriptionValue
markConnection tracking markmark
labelConnection tracking labellabel

save packet nfmark in conntrack

ct set mark meta mark

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.

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 / {second | minute | hour | day} [burst packet_number packets] limit rate [over] byte_number {bytes | kbytes | mbytes} / {second | minute | hour | day | week} [burst 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 values

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

Nat Statements

snat to address [:port] [persistent, random, fully-random] snat to address - address [:port - port] [persistent, random, fully-random] dnat to address [:port] [persistent, random, fully-random] dnat to address [:port - port] [persistent, random, fully-random]

The nat statements are only valid from nat chain types.

The snat statement is only valid in the postrouting and input hooks, it specifies that the source address of the packet should be modified. The dnat statement is only valid in the prerouting and output chains, it specifies 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.

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, eg. abcd::1234, or you can use a mapping, eg. 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 flags

FlagDescription
persistentGives 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.

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 reinject the packet into the kernel. See libnetfilter_queue documentation for details.

queue [num queue_number] [bypass] queue [num queue_number_from - queue_number_to] [bypass,fanout]

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)

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 recomendations.
fanoutDistribute packets between several queues.

Additional Commands

These are some additional commands included in nft.

Export

Export your current ruleset in XML or JSON format to stdout.

Examples:

% nft export xml
[...]
% nft export json
[...]

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 ocurr, nft will print to stdout the monitored events in either XML, JSON or native nft format.

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

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 added tables, report in XML format

% nft monitor new tables xml

Listen to deleted rules, report in JSON format

% nft monitor destroy rules json

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

% nft monitor chains

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 carrets (^). 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 can't 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

iptables(8), ip6tables(8), arptables(8), ebtables(8), ip(8), tc(8)

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

Authors

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

Info

11 February 2017