]> git.ipfire.org Git - thirdparty/nftables.git/log
thirdparty/nftables.git
3 years agotests: monitor: update insert and replace commands
Pablo Neira Ayuso [Fri, 24 Sep 2021 23:34:36 +0000 (01:34 +0200)] 
tests: monitor: update insert and replace commands

Adjust test after these two kernel fixes:

("netfilter: nf_tables: reverse order in rule replacement expansion")
("netfilter: nf_tables: add position handle in event notification")

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agomonitor: honor NLM_F_APPEND flag for rules
Pablo Neira Ayuso [Mon, 20 Sep 2021 21:39:17 +0000 (23:39 +0200)] 
monitor: honor NLM_F_APPEND flag for rules

Print 'add' or 'insert' according to this netlink flag.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agomonitor: display rule position handle
Pablo Neira Ayuso [Mon, 20 Sep 2021 16:52:18 +0000 (18:52 +0200)] 
monitor: display rule position handle

This allow to locate the incremental update in the ruleset.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agonetlink: dynset: set compound expr dtype based on set key definition
Florian Westphal [Tue, 28 Sep 2021 19:34:30 +0000 (21:34 +0200)] 
netlink: dynset: set compound expr dtype based on set key definition

"nft add rule ... add @t { ip saddr . 22 ..." will be listed as
'ip saddr . 0x16  [ invalid type]".

This is a display bug, the compound expression created during netlink
deserialization lacks correct datatypes for the value expression.

Avoid this by setting the individual expressions' datatype.
The set key has the needed information, so walk over the types and set
them in the dynset statment.

Also add a test case.

Reported-by: Paulo Ricardo Bruck <paulobruck1@gmail.com>
Signed-off-by: Florian Westphal <fw@strlen.de>
3 years agopayload: don't adjust offsets of autogenerated dependency expressions
Florian Westphal [Tue, 28 Sep 2021 12:16:48 +0000 (14:16 +0200)] 
payload: don't adjust offsets of autogenerated dependency expressions

Pablo says:
  user reports that this is broken:
  nft --debug=netlink add rule bridge filter forward vlan id 100 vlan id set 200
[..]
    [ payload load 2b @ link header + 14 => reg 1 ]
[..]
    [ payload load 2b @ link header + 28 => reg 1 ]
    [ bitwise reg 1 = ( reg 1 & 0x000000f0 ) ^ 0x0000c800 ]
    [ payload write reg 1 => 2b @ link header + 14 csum_type 0 csum_off 0 csum_flags 0x0 ]

    offset says 28, it is assuming q-in-q, in this case it is mangling the
    existing header.

The problem here is that 'vlan id set 200' needs a read-modify-write
cycle because 'vlan id set' has to preserve bits located in the same byte area
as the vlan id.

The first 'payload load' at offset 14 is generated via 'vlan id 100',
this part is ok.

The second 'payload load' at offset 28 is the bogus one.
Its added as a dependency, but then adjusted because nft evaluation
considers this identical to 'vlan id 1 vlan id '2, where nft assumes
q-in-q.

To fix this, skip offset adjustments for raw expressions and mark the
dependency-generated payload instruction as such.

This is fine because raw payload operations assume that user specifies
base/offset/length manually.

Also add a test case for this.

Reported-by: Pablo Neira Ayuso <pablo@netfilter.org>
Signed-off-by: Florian Westphal <fw@strlen.de>
3 years agonetlink: reset temporary set element stmt list after list splice
Pablo Neira Ayuso [Thu, 16 Sep 2021 11:51:23 +0000 (13:51 +0200)] 
netlink: reset temporary set element stmt list after list splice

Reset temporary stmt list to deal with the key_end case which might
result in a jump backward to handle the rhs of the interval.

Reported-by: Martin Zatloukal <slezi2@pvfree.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agodoc: fix synopsis of named counter, quota and ct {helper,timeout,expect}
Pablo Neira Ayuso [Thu, 16 Sep 2021 09:59:13 +0000 (11:59 +0200)] 
doc: fix synopsis of named counter, quota and ct {helper,timeout,expect}

Synopsis is not complete. Add examples for counters and quotas.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agotests: py: update ct expiration
Pablo Neira Ayuso [Wed, 15 Sep 2021 00:05:22 +0000 (02:05 +0200)] 
tests: py: update ct expiration

Since 309785674b25 ("datatype: time_print() ignores -T"), time_type
honors -T option. Given tests/py run in numeric format, this patch
fixes a warning since the ct expiration is now expressed in seconds.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agosrc: revert hashtable for expression handlers
Pablo Neira Ayuso [Tue, 14 Sep 2021 23:05:52 +0000 (01:05 +0200)] 
src: revert hashtable for expression handlers

Partially revert 913979f882d1 ("src: add expression handler hashtable")
which is causing a crash with two instances of the nftables handler.

$ sudo python
[sudo] password for echerkashin:
Python 3.9.7 (default, Sep  3 2021, 06:18:44)
[GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from nftables import Nftables
>>> n1=Nftables()
>>> n2=Nftables()
>>> <Ctrl-D>
double free or corruption (top)
Aborted

Reported-by: Eugene Crosser <crosser@average.org>
Suggested-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agodoc: nfnetlink_log allows one single process through unicast
Pablo Neira Ayuso [Mon, 6 Sep 2021 20:34:50 +0000 (22:34 +0200)] 
doc: nfnetlink_log allows one single process through unicast

nfnetlink_log uses netlink unicast to send logs to one single process in
userspace.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agonetlink: rework range_expr_to_prefix()
Pablo Neira Ayuso [Mon, 6 Sep 2021 20:04:51 +0000 (22:04 +0200)] 
netlink: rework range_expr_to_prefix()

Consolidate prefix calculation in range_expr_is_prefix().

Add tests/py for 9208fb30dc49 ("src: Check range bounds before converting to
prefix").

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agometa: skip -T for hour and date format
Pablo Neira Ayuso [Mon, 6 Sep 2021 08:31:19 +0000 (10:31 +0200)] 
meta: skip -T for hour and date format

If -T is used:

- meta hour displays the hours in seconds based on your timezone.
- meta time displays the UNIX time since 1970 in nanoseconds.

Better, skip -T for these two datatypes and use the formatted output
instead, ie.

- meta hour "00:00:20"
- meta time "1970-01-01 01:00:01"

Fixes: f8f32deda31d ("meta: Introduce new conditions 'time', 'day' and 'hour'")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agosrc: Check range bounds before converting to prefix
Xiao Liang [Mon, 6 Sep 2021 03:06:41 +0000 (11:06 +0800)] 
src: Check range bounds before converting to prefix

The lower bound must be the first value of the prefix to be coverted.
For example, range "10.0.0.15-10.0.0.240" can not be converted to
"10.0.0.15/24". Validate it by checking if the lower bound value has
enough trailing zeros.

Signed-off-by: Xiao Liang <shaw.leon@gmail.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agodoc: refer to ulogd manpage
Pablo Neira Ayuso [Mon, 6 Sep 2021 11:18:34 +0000 (13:18 +0200)] 
doc: refer to ulogd manpage

Refer to the ulogd daemon in the log statement section.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agodoc: libnflog handles `log group`, not libnfq
Duncan Roe [Mon, 6 Sep 2021 03:40:09 +0000 (13:40 +1000)] 
doc: libnflog handles `log group`, not libnfq

Signed-off-by: Duncan Roe <duncan_roe@optusnet.com.au>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agodoc: Missing NFT_CTX_OUTPUT_NUMERIC_SYMBOL in libnftables documentation
Pablo Neira Ayuso [Mon, 6 Sep 2021 08:39:58 +0000 (10:39 +0200)] 
doc: Missing NFT_CTX_OUTPUT_NUMERIC_SYMBOL in libnftables documentation

Add NFT_CTX_OUTPUT_NUMERIC_SYMBOL to libnftables.adoc to keep it in sync
with the nftables/libnftables.h header.

Fixes: 685a06447ee4 ("doc: libnftables.adoc misc cleanups")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agoinclude: add NFT_CTX_OUTPUT_NUMERIC_TIME to NFT_CTX_OUTPUT_NUMERIC_ALL
Pablo Neira Ayuso [Fri, 3 Sep 2021 08:29:16 +0000 (10:29 +0200)] 
include: add NFT_CTX_OUTPUT_NUMERIC_TIME to NFT_CTX_OUTPUT_NUMERIC_ALL

Therefore, -n honors numeric time in seconds.

Fixes: f8f32deda31d ("meta: Introduce new conditions 'time', 'day' and 'hour'")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agodatatype: time_print() ignores -T
Pablo Neira Ayuso [Fri, 3 Sep 2021 08:12:11 +0000 (10:12 +0200)] 
datatype: time_print() ignores -T

Honor NFT_CTX_OUTPUT_NUMERIC_TIME.

 # nft list ruleset
 table ip x {
        set y {
                type ipv4_addr
                flags timeout
                elements = { 1.1.1.1 timeout 5m expires 1m49s40ms }
        }
 }
 # sudo nft -T list ruleset
 table ip x {
        set y {
                type ipv4_addr
                flags timeout
                elements = { 1.1.1.1 timeout 300s expires 108s }
        }
 }

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1561
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agorule: remove redundant meta protocol from the evaluation step
Pablo Neira Ayuso [Mon, 30 Aug 2021 19:37:50 +0000 (21:37 +0200)] 
rule: remove redundant meta protocol from the evaluation step

567ea4774e13 ("netlink_delinearize: incorrect meta protocol dependency kill")
does not document two cases that are handled in this patch:

- 'meta protocol ip' is removed if used in the ip family.
- 'meta protocol ip6' is removed if used in the ip6 family.

This patch removes this redundancy earlier, from the evaluation step
before netlink bytecode generation.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agonetlink_delinearize: incorrect meta protocol dependency kill again
Pablo Neira Ayuso [Mon, 30 Aug 2021 21:31:59 +0000 (23:31 +0200)] 
netlink_delinearize: incorrect meta protocol dependency kill again

This patch adds __meta_dependency_may_kill() to consolidate inspection
of the meta protocol, nfproto and ether type expression to validate
dependency removal on listings.

Phil reports that 567ea4774e13 includes an update on the ip and ip6
families that is not described in the patch, moreover, it flips the
default verdict from true to false.

Fixes: 567ea4774e13 ("netlink_delinearize: incorrect meta protocol dependency kill")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agoparser_json: Fix error reporting for invalid syntax
Phil Sutter [Wed, 1 Sep 2021 14:41:44 +0000 (16:41 +0200)] 
parser_json: Fix error reporting for invalid syntax

Errors emitted by the JSON parser caused BUG() in erec_print() due to
input descriptor values being bogus.

Due to lack of 'include' support, JSON parser uses a single input
descriptor only and it lived inside the json_ctx object on stack of
nft_parse_json_*() functions.

By the time errors are printed though, that scope is not valid anymore.
Move the static input descriptor object to avoid this.

Fixes: 586ad210368b7 ("libnftables: Implement JSON parser")
Signed-off-by: Phil Sutter <phil@nwl.cc>
3 years agonetlink_delinearize: incorrect meta protocol dependency kill
Pablo Neira Ayuso [Thu, 26 Aug 2021 10:24:37 +0000 (12:24 +0200)] 
netlink_delinearize: incorrect meta protocol dependency kill

meta protocol is meaningful in bridge, netdev and inet families, do
not remove this.

Fixes: 056aaa3e6dc6 ("netlink_delinearize: Refactor meta_may_dependency_kill()")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agocache: provide a empty list for flowtables and objects when request fails
Pablo Neira Ayuso [Wed, 25 Aug 2021 13:46:20 +0000 (15:46 +0200)] 
cache: provide a empty list for flowtables and objects when request fails

Old kernels do not support for dumping the flowtable and object lists,
provide an empty list instead to unbreak the cache initialization.

Fixes: 560963c4d41e ("cache: add hashtable cache for flowtable")
Fixes: 45a84088ecbd ("cache: add hashtable cache for object")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agocache: skip set element netlink dump for add/delete element command
Pablo Neira Ayuso [Tue, 24 Aug 2021 09:52:36 +0000 (11:52 +0200)] 
cache: skip set element netlink dump for add/delete element command

Add NFT_CACHE_SETELEM_MAYBE to dump the set elements conditionally,
only in case that the set interval flag is set on.

Reported-by: Cristian Constantin <const.crist@googlemail.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agotests: monitor: Continue on error
Phil Sutter [Wed, 11 Aug 2021 20:11:46 +0000 (22:11 +0200)] 
tests: monitor: Continue on error

Just make sure return code reflects the overall result.

Signed-off-by: Phil Sutter <phil@nwl.cc>
3 years agotests: monitor: Print errors to stderr
Phil Sutter [Wed, 11 Aug 2021 18:08:14 +0000 (20:08 +0200)] 
tests: monitor: Print errors to stderr

While being at it, introduce die() to error and exit. But don't use it
everywhere to prepare for continuing on errors.

Signed-off-by: Phil Sutter <phil@nwl.cc>
3 years agotests: json_echo: Print errors to stderr
Phil Sutter [Wed, 11 Aug 2021 16:14:06 +0000 (18:14 +0200)] 
tests: json_echo: Print errors to stderr

Apart from the obvious, this fixes exit_dump() which tried to dump the
wrong variable ('out' instead of 'obj') and missed that json.dumps()
doesn't print but just returns a string. Make it call exit_err() to
share some code, which changes the prefix from 'FAIL' to 'Error' as a
side-effect.

While being at it, fix for a syntax warning with newer Python in
unrelated code.

Fixes: bb32d8db9a125 ("JSON: Add support for echo option")
Signed-off-by: Phil Sutter <phil@nwl.cc>
3 years agosrc: Optimize prefix match only if is big-endian
Xiao Liang [Fri, 20 Aug 2021 16:12:37 +0000 (00:12 +0800)] 
src: Optimize prefix match only if is big-endian

A prefix of integer type is big-endian in nature. Prefix match can be
optimized to truncated 'cmp' only if it is big-endian.

[ Add one tests/py for this use-case --pablo ]

Fixes: 25338cdb6c77 ("src: Optimize prefix matches on byte-boundaries")
Signed-off-by: Xiao Liang <shaw.leon@gmail.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agotests: shell: add nft-f/0022variables_0 dump file
Pablo Neira Ayuso [Fri, 20 Aug 2021 11:05:15 +0000 (13:05 +0200)] 
tests: shell: add nft-f/0022variables_0 dump file

Dump file was missing.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agosrc: queue: consolidate queue statement syntax
Pablo Neira Ayuso [Fri, 20 Aug 2021 10:43:50 +0000 (12:43 +0200)] 
src: queue: consolidate queue statement syntax

Print queue statement using the 'queue ... to' syntax to consolidate the
syntax around Florian's proposal introduced in 6cf0f2c17bfb ("src:
queue: allow use of arbitrary queue expressions").

Retain backward compatibility, 'queue num' syntax is still allowed.

Update and add new tests.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agoparser: permit symbolic define for 'queue num' again
Florian Westphal [Fri, 20 Aug 2021 09:52:35 +0000 (11:52 +0200)] 
parser: permit symbolic define for 'queue num' again

WHen I simplified the parser to restrict 'queue num' I forgot that
instead of range and immediate value its also allowed to pass in
a variable expression, e.g.

define myq = 0
add rule ... 'queue num $myq bypass'

Allow those as well and add a test case for this.

Fixes: 767f0af82a389 ("parser: restrict queue num expressiveness")
Reported-by: Amish <anon.amish@gmail.com>
Signed-off-by: Florian Westphal <fw@strlen.de>
3 years agobuild: Bump version to v1.0.0 v1.0.0
Pablo Neira Ayuso [Tue, 17 Aug 2021 17:25:46 +0000 (19:25 +0200)] 
build: Bump version to v1.0.0

Update libversion since new API has been added in 9edaa6a51eab ("src:
add --define key=value").

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agonetlink_delinearize: skip flags / mask notation for singleton bitmask again
Pablo Neira Ayuso [Sun, 15 Aug 2021 12:46:53 +0000 (14:46 +0200)] 
netlink_delinearize: skip flags / mask notation for singleton bitmask again

!= operation should also be covered too.

Fixes: 347a4aa16e64 ("netlink_delinearize: skip flags / mask notation for singleton bitmask")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agoevaluate: expand variable containing set into multiple mappings
Pablo Neira Ayuso [Wed, 11 Aug 2021 10:08:41 +0000 (12:08 +0200)] 
evaluate: expand variable containing set into multiple mappings

 # cat x.nft
 define interfaces = { eth0, eth1 }

 table ip x {
        chain y {
type filter hook input priority 0; policy accept;
                iifname vmap { lo : accept, $interfaces : drop }
        }
 }
 # nft -f x.nft
 # nft list ruleset
 table ip x {
        chain y {
type filter hook input priority 0; policy accept;
                iifname vmap { "lo" : accept, "eth0" : drop, "eth1" : drop }
        }
 }

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agotests/py: Make netns spawning more robust
Phil Sutter [Tue, 10 Aug 2021 13:40:06 +0000 (15:40 +0200)] 
tests/py: Make netns spawning more robust

On systems without unshare Python module, try to call unshare binary
with oneself as parameters.

Signed-off-by: Phil Sutter <phil@nwl.cc>
3 years agotcpopt: bogus assertion on undefined options
Pablo Neira Ayuso [Wed, 11 Aug 2021 03:24:48 +0000 (05:24 +0200)] 
tcpopt: bogus assertion on undefined options

 # nft add rule x y tcp option 6 exists
 # nft list ruleset
 nft: tcpopt.c:208: tcpopt_init_raw: Assertion `expr->exthdr.desc != NULL' failed.
 Aborted

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1557
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
3 years agomnl: revisit hook listing
Pablo Neira Ayuso [Mon, 2 Aug 2021 10:32:52 +0000 (12:32 +0200)] 
mnl: revisit hook listing

Update this command to display the hook datapath for a packet depending
on its family.

This patch also includes:

- Group of existing hooks based on the hook location.
- Order hooks by priority, from INT_MIN to INT_MAX.
- Do not add sign to priority zero.
- Refresh include/linux/netfilter/nfnetlink_hook.h cache copy.
- Use NFNLA_CHAIN_* attributes to print the chain family, table and name.
  If NFNLA_CHAIN_* attributes are not available, display the hookfn name.
- Update syntax: remove optional hook parameter, promote the 'device'
  argument.

The following example shows the hook datapath for IPv4 packets coming in
from netdevice 'eth0':

 # nft list hooks ip device eth0
 family ip {
        hook ingress {
                +0000000010 chain netdev x y [nf_tables]
                +0000000300 chain inet m w  [nf_tables]
        }
        hook input {
                -0000000100 chain ip a b [nf_tables]
                +0000000300 chain inet m z [nf_tables]
        }
        hook forward {
                -0000000225 selinux_ipv4_forward
                 0000000000 chain ip a c [nf_tables]
        }
        hook output {
                -0000000225 selinux_ipv4_output
        }
        hook postrouting {
                +0000000225 selinux_ipv4_postroute
        }
 }

Note that the listing above includes the existing netdev and inet
hooks/chains which *might* interfer in the travel of an incoming IPv4
packet. This allows users to debug the pipeline, basically, to
understand in what order the hooks/chains are evaluated for the IPv4
packets.

If the netdevice is not specified, then the ingress hooks are not
shown.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agotests: py: check more flag match transformations to compact syntax
Pablo Neira Ayuso [Wed, 28 Jul 2021 09:04:50 +0000 (11:04 +0200)] 
tests: py: check more flag match transformations to compact syntax

Add a few more tests to extend coverage.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agotests: py: tcp flags & (fin | syn | rst | ack) == syn
Pablo Neira Ayuso [Tue, 27 Jul 2021 21:18:16 +0000 (23:18 +0200)] 
tests: py: tcp flags & (fin | syn | rst | ack) == syn

Add a test case to cover translation to tcp flags syn / fin,syn,rst,ack.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agonetlink_delinearize: skip flags / mask notation for singleton bitmask
Pablo Neira Ayuso [Tue, 27 Jul 2021 20:26:52 +0000 (22:26 +0200)] 
netlink_delinearize: skip flags / mask notation for singleton bitmask

Do not transform 'tcp flags & flag == flag' to 'flag / flag'.
The parser does not accept this notation yet.

Fixes: c3d57114f119 ("parser_bison: add shortcut syntax for matching flags without binary operations")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agotests: py: idempotent tcp flags & syn != 0 to tcp flag syn
Pablo Neira Ayuso [Tue, 27 Jul 2021 20:21:48 +0000 (22:21 +0200)] 
tests: py: idempotent tcp flags & syn != 0 to tcp flag syn

Add a test to cover this case.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoevaluate: disallow negation with binary operation
Pablo Neira Ayuso [Tue, 27 Jul 2021 15:23:34 +0000 (17:23 +0200)] 
evaluate: disallow negation with binary operation

The negation was introduced to provide a simple shortcut. Extend
e6c32b2fa0b8 ("src: add negation match on singleton bitmask value") to
disallow negation with binary operations too.

 # nft add rule meh tcp_flags 'tcp flags & (fin | syn | rst | ack) ! syn'
 Error: cannot combine negation with binary expression
 add rule meh tcp_flags tcp flags & (fin | syn | rst | ack) ! syn
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^   ~~~

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agonetlink_linearize: incorrect netlink bytecode with binary operation and flags
Pablo Neira Ayuso [Tue, 27 Jul 2021 15:23:30 +0000 (17:23 +0200)] 
netlink_linearize: incorrect netlink bytecode with binary operation and flags

nft generates incorrect bytecode when combining flag datatype and binary
operations:

  # nft --debug=netlink add rule meh tcp_flags 'tcp flags & (fin | syn | rst | ack) syn'
ip
  [ meta load l4proto => reg 1 ]
  [ cmp eq reg 1 0x00000006 ]
  [ payload load 1b @ transport header + 13 => reg 1 ]
  [ bitwise reg 1 = ( reg 1 & 0x00000017 ) ^ 0x00000000 ]
  [ bitwise reg 1 = ( reg 1 & 0x00000002 ) ^ 0x00000000 ]
  [ cmp neq reg 1 0x00000000 ]

Note the double bitwise expression. The last two expressions are not
correct either since it should match on the syn flag, ie. 0x2.

After this patch, netlink bytecode generation looks correct:

 # nft --debug=netlink add rule meh tcp_flags 'tcp flags & (fin | syn | rst | ack) syn'
ip
  [ meta load l4proto => reg 1 ]
  [ cmp eq reg 1 0x00000006 ]
  [ payload load 1b @ transport header + 13 => reg 1 ]
  [ bitwise reg 1 = ( reg 1 & 0x00000017 ) ^ 0x00000000 ]
  [ cmp eq reg 1 0x00000002 ]

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoexpression: missing != in flagcmp expression print function
Pablo Neira Ayuso [Tue, 27 Jul 2021 15:23:27 +0000 (17:23 +0200)] 
expression: missing != in flagcmp expression print function

Missing != when printing the expression.

Fixes: c3d57114f119 ("parser_bison: add shortcut syntax for matching flags without binary operations")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agotests: py: missing json update for numeric reject with icmp numeric
Pablo Neira Ayuso [Mon, 26 Jul 2021 22:32:04 +0000 (00:32 +0200)] 
tests: py: missing json update for numeric reject with icmp numeric

Add missing tests to cover json support for reject with icmp numeric.

Fixes: 1ab1fcbc19a8 ("parser_bison: parse number as reject icmp code")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agotests: py: update new reject with icmp code syntax leftover
Pablo Neira Ayuso [Mon, 26 Jul 2021 22:26:43 +0000 (00:26 +0200)] 
tests: py: update new reject with icmp code syntax leftover

I forgot to update a few more spots in the json files.

Fixes: 08d2f0493671 ("src: promote 'reject with icmp CODE' syntax")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoevaluate: error reporting for missing statements in set/map declaration
Pablo Neira Ayuso [Mon, 26 Jul 2021 16:00:09 +0000 (18:00 +0200)] 
evaluate: error reporting for missing statements in set/map declaration

Assuming this map:

        map y {
                type ipv4_addr : verdict
        }

This patch slightly improves error reporting to refer to the missing
'counter' statement in the map declaration.

 # nft 'add element x y { 1.2.3.4 counter packets 1 bytes 1 : accept, * counter : drop }'
 Error: missing statement in map declaration
 add element x y { 1.2.3.4 counter packets 10 bytes 640 : accept, * counter : drop }
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agosrc: promote 'reject with icmp CODE' syntax
Pablo Neira Ayuso [Mon, 26 Jul 2021 15:22:32 +0000 (17:22 +0200)] 
src: promote 'reject with icmp CODE' syntax

The kernel already assumes that that ICMP type to reject a packet is
destination-unreachable, hence the user specifies the *ICMP code*.

Simplify the syntax to:

... reject with icmp port-unreachable

this removes the 'type' keyword before the ICMP code to reject the
packet with.

IIRC, the original intention is to leave room for future extensions that
allow to specify both the ICMP type and the ICMP code, this is however
not possible with the current inconsistent syntax.

Update manpages which also refer to ICMP type.

Adjust tests/py to the new syntax.

Fixes: 5fdd0b6a0600 ("nft: complete reject support")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoparser_bison: parse number as reject icmp code
Pablo Neira Ayuso [Mon, 26 Jul 2021 14:29:58 +0000 (16:29 +0200)] 
parser_bison: parse number as reject icmp code

Extend parser to accept a numeric icmp code, instead of bailing out:

 # nft add rule inet filter input reject with icmpx type 3
 Error: syntax error, unexpected number, expecting string
 add rule inet filter input reject with icmpx type 3
                                                   ^

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1555
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoparser_bison: stateful statement support in map
Pablo Neira Ayuso [Mon, 26 Jul 2021 10:00:07 +0000 (12:00 +0200)] 
parser_bison: stateful statement support in map

Missing parser extension to support for stateful statements in map.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agotests: shell: Fix bogus testsuite failure with 100Hz
Phil Sutter [Mon, 26 Jul 2021 13:27:32 +0000 (15:27 +0200)] 
tests: shell: Fix bogus testsuite failure with 100Hz

On kernels with CONFIG_HZ=100, clock granularity does not allow tracking
timeouts in single digit ms range. Change sets/0031set_timeout_size_0 to
not expose this detail.

Signed-off-by: Phil Sutter <phil@nwl.cc>
Acked-by: Florian Westphal <fw@strlen.de>
4 years agosrc: expose nft_ctx_clear_vars as API
Pablo Neira Ayuso [Sat, 24 Jul 2021 10:07:27 +0000 (12:07 +0200)] 
src: expose nft_ctx_clear_vars as API

This function might be useful to recycle the existing nft_ctx to use it
with different external variable definitions.

Moreover, reset ctx->num_vars to zero.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agosrc: fix nft_ctx_clear_include_paths in libnftables.map
Pablo Neira Ayuso [Sat, 24 Jul 2021 10:04:57 +0000 (12:04 +0200)] 
src: fix nft_ctx_clear_include_paths in libnftables.map

There a typo that prevents exposing the function as API.

Fixes: 16543a0136c0 ("libnftables: export public symbols only")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoparser_json: inconditionally initialize ct timeout list
Pablo Neira Ayuso [Thu, 22 Jul 2021 16:28:14 +0000 (18:28 +0200)] 
parser_json: inconditionally initialize ct timeout list

The policy is optional, make sure this timeout list is initialized.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoparser_bison: missing initialization of ct timeout policy list
Pablo Neira Ayuso [Thu, 22 Jul 2021 16:14:28 +0000 (18:14 +0200)] 
parser_bison: missing initialization of ct timeout policy list

rule.c:1715:3: runtime error: member access within null pointer of type 'struct timeout_state'
AddressSanitizer:DEADLYSIGNAL
=================================================================
==29500==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x7f5bfd43c2a4 bp 0x7ffcb82f13b0 sp 0x7ffcb82f1360 T0)
==29500==The signal is caused by a READ memory access.
==29500==Hint: address points to the zero page.
    #0 0x7f5bfd43c2a3 in obj_free /home/test/nftables/src/rule.c:1715
    #1 0x7f5bfd43875d in cmd_free /home/test/nftables/src/rule.c:1447
    #2 0x7f5bfd58e6f2 in nft_run_cmd_from_filename /home/test/nftables/src/libnftables.c:628
    #3 0x5645c48762b1 in main /home/test/nftables/src/main.c:512
    #4 0x7f5bfc0eb09a in __libc_start_main ../csu/libc-start.c:308
    #5 0x5645c4873459 in _start (/home/test/nftables/src/.libs/nft+0x9459)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /home/test/nftables/src/rule.c:1715 in obj_free
==29500==ABORTING

Fixes: 7a0e26723496 ("rule: memleak of list of timeout policies")
Signed-off-by: Pablo Neira Ayuso <test@netfilter.org>
4 years agotests: py: add dnat to port without defining destination address
Pablo Neira Ayuso [Thu, 22 Jul 2021 15:43:56 +0000 (17:43 +0200)] 
tests: py: add dnat to port without defining destination address

Add a test to cover dnat to port without destination address.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1428
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agolibnftables: missing nft_ctx_add_var() symbol map update
Pablo Neira Ayuso [Wed, 21 Jul 2021 07:48:02 +0000 (09:48 +0200)] 
libnftables: missing nft_ctx_add_var() symbol map update

Add nft_ctx_add_var() to libnftables.map symbol map.

Fixes: 9edaa6a51eab ("src: add --define key=value")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoevaluate: fix inet nat with no layer 3 info
Pablo Neira Ayuso [Tue, 20 Jul 2021 16:59:44 +0000 (18:59 +0200)] 
evaluate: fix inet nat with no layer 3 info

nft currently reports:

 Error: Could not process rule: Protocol error
 add rule inet x y meta l4proto tcp dnat to :80
                                    ^^^^

default to NFPROTO_INET family, otherwise kernel bails out EPROTO when
trying to load the conntrack helper.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1428
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agosrc: add --define key=value
Pablo Neira Ayuso [Tue, 20 Jul 2021 10:17:33 +0000 (12:17 +0200)] 
src: add --define key=value

This patch adds a new option to define variables from the command line.

 # cat test.nft
 table netdev x {
        chain y {
                type filter hook ingress devices = $dev priority 0;
                counter accept
        }
 }
 # nft --define dev="{ eth0, eth1 }" -f test.nft

You can only combine it with -f/--filename.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agotests: py: extend coverage for dnat with classic range representation
Pablo Neira Ayuso [Wed, 14 Jul 2021 10:05:24 +0000 (12:05 +0200)] 
tests: py: extend coverage for dnat with classic range representation

Add a few more tests for the classic dnat range representation.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agosrc: support for nat with interval concatenation
Pablo Neira Ayuso [Tue, 13 Jul 2021 18:21:01 +0000 (20:21 +0200)] 
src: support for nat with interval concatenation

This patch allows you to combine concatenation and interval in NAT
mappings, e.g.

 add rule x y dnat to ip saddr . tcp dport map { 192.168.1.2 . 80 : 10.141.10.2-10.141.10.5 . 8888-8999 }

This generates the following NAT expression:

 [ nat dnat ip addr_min reg 1 addr_max reg 10 proto_min reg 9 proto_max reg 11 ]

which expects to obtain the following tuple:

 IP address (min), source port (min), IP address (max), source port (max)

to be obtained from the map. This representation simplifies the
delinearize path, since the datatype is specified as:

 ipv4_addr . inet_service.

A few more notes on this update:

- alloc_nftnl_setelem() needs a variant netlink_gen_data() to deal with
  the representation of the range on the rhs of the mapping. In contrast
  to interval concatenation in the key side, where the range is expressed
  as two netlink attributes, the data side of the set element mapping
  stores the interval concatenation in a contiguos memory area, see
  __netlink_gen_concat_expand() for reference.

- add range_expr_postprocess() to postprocess the data mapping range.
  If either one single IP address or port is used, then the minimum and
  maximum value in the range is the same value, e.g. to avoid listing
  80-80, this round simplify the range. This also invokes the range
  to prefix conversion routine.

- add concat_elem_expr() helper function to consolidate code to build
  the concatenation expression on the rhs element data side.

This patch also adds tests/py and tests/shell.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agosrc: infer NAT mapping with concatenation from set
Pablo Neira Ayuso [Tue, 13 Jul 2021 18:18:27 +0000 (20:18 +0200)] 
src: infer NAT mapping with concatenation from set

If the map is anonymous, infer it from the set elements. Otherwise, the
set definition already have an explicit concatenation definition in the
data side of the mapping.

This update simplifies the NAT mapping syntax with concatenations, e.g.

 snat ip to ip saddr map { 10.141.11.4 : 192.168.2.3 . 80 }

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agosrc: remove STMT_NAT_F_INTERVAL flags and interval keyword
Pablo Neira Ayuso [Tue, 13 Jul 2021 18:18:15 +0000 (20:18 +0200)] 
src: remove STMT_NAT_F_INTERVAL flags and interval keyword

STMT_NAT_F_INTERVAL is not useful, the keyword interval can be removed
to simplify the syntax, e.g.

 snat to ip saddr map { 10.141.11.4 : 192.168.2.2-192.168.2.4 }

This patch reworks 9599d9d25a6b ("src: NAT support for intervals in
maps").

Do not remove STMT_NAT_F_INTERVAL yet since this flag is needed for
interval concatenations coming in a follow up patch.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agonetlink_delinearize: stmt and expr error path memleaks
Pablo Neira Ayuso [Mon, 12 Jul 2021 16:10:57 +0000 (18:10 +0200)] 
netlink_delinearize: stmt and expr error path memleaks

Use stmt_free() and expr_free() to release these objects.

Fixes: 671851617c8d ("netlink_delinearize: Fix resource leaks")
Fixes: 3a8640672978 ("src: hash: support of symmetric hash")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agobuild: get `make distcheck` to pass again
Duncan Roe [Sun, 4 Jul 2021 06:33:57 +0000 (16:33 +1000)] 
build: get `make distcheck` to pass again

Commit 4694f7230195 introduced nfnetlink_hook.h but didn't update the
automake system to take account of the new file.

Signed-off-by: Duncan Roe <duncan_roe@optusnet.com.au>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agonetlink_delinarize: don't check for set element if set is not populated
Florian Westphal [Wed, 30 Jun 2021 15:45:18 +0000 (17:45 +0200)] 
netlink_delinarize: don't check for set element if set is not populated

0065_icmp_postprocessing: line 13: Segmentation fault $NFT insert rule ip x foo index 1 accept

Since no listing is done, cache isn't populated and 'nft insert' will trip over
set->init == NULL during postprocessing of the existing 'icmp id 42' expression.

Fixes: 9a5574e2d4e9 ("netlink_delinearize: add missing icmp id/sequence support")
Reported-by: Eric Garver <eric@garver.life>
Reported-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agocmd: incorrect error reporting when table declaration exists
Pablo Neira Ayuso [Tue, 29 Jun 2021 12:36:18 +0000 (14:36 +0200)] 
cmd: incorrect error reporting when table declaration exists

This example ruleset is missing the chain declaration:

 add table x
 add set x y { typeof ip saddr ; }
 add rule x y counter

After this patch, error reporting provides suggestions for the missing
chain:

 # nft -f ruleset.nft
 ruleset.nft:3:12-12: Error: No such file or directory; did you mean chain â€˜INPUT’ in table ip â€˜filter’?
 add rule x y counter
            ^

Before this patch, it incorrectly refers to the table:

 ruleset.nft:3:10-10: Error: No such file or directory; did you mean table â€˜filter’ in family ip?
 add rule x y counter
          ^

This patch invalidates the table that is found via fuzzy lookup if it
exists in the cache.

Fixes: 0276c2fee939 ("cmd: check for table mismatch first in error reporting")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agocmd: incorrect table location in error reporting
Pablo Neira Ayuso [Tue, 29 Jun 2021 12:23:10 +0000 (14:23 +0200)] 
cmd: incorrect table location in error reporting

If the command refers to an inexisting table, then use the table location.

ruleset.nft:3:12-12: Error: No such file or directory; did you mean table â€˜filter’ in family ip?
add rule x x ip saddr @x log prefix "Anti SSH-Bruteforce: " drop
         ^

before this patch location is not correct:

ruleset.nft:3:12-12: Error: No such file or directory; did you mean table â€˜filter’ in family ip?
add rule x x ip saddr @x log prefix "Anti SSH-Bruteforce: " drop
           ^

Fixes: 0276c2fee939 ("cmd: check for table mismatch first in error reporting")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agorule: obj_free() releases timeout state string
Pablo Neira Ayuso [Wed, 23 Jun 2021 12:44:12 +0000 (14:44 +0200)] 
rule: obj_free() releases timeout state string

Missing free() on the timeout state string on object release.

Fixes: 7a0e26723496 ("rule: memleak of list of timeout policies"
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoparser_bison: memleak in rate limit parser
Pablo Neira Ayuso [Wed, 23 Jun 2021 11:40:49 +0000 (13:40 +0200)] 
parser_bison: memleak in rate limit parser

Direct leak of 13 byte(s) in 1 object(s) allocated from:
    #0 0x7fb49ad79810 in strdup (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x3a810)
    #1 0x7fb496b8f63a in xstrdup /home/pablo/nftables/src/utils.c:85
    #2 0x7fb496c9a79d in nft_lex /home/pablo/nftables/src/scanner.l:740
    [...]

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoparser_bison: string memleak in YYERROR path
Pablo Neira Ayuso [Wed, 23 Jun 2021 11:09:53 +0000 (13:09 +0200)] 
parser_bison: string memleak in YYERROR path

Release dynamically allocated string by lex from the YYERROR path, e.g.

 # cat test.nft
 table x {
        map test {
                type ipv4_addr . foo . inet_service : ipv4_addr . inet_service
        }
 }

 # nft -f test.nft
test.nft:3:20-22: Error: unknown datatype foo
                type ipv4_addr . foo . inet_service : ipv4_addr . inet_service
                                 ^^^
test.nft:6-9: Error: set definition does not specify key
        map test {
            ^^^^
 ==29692==ERROR: LeakSanitizer: detected memory leaks

 Direct leak of 5 byte(s) in 1 object(s) allocated from:
    #0 0x7f6c869e8810 in strdup (/usr/lib/x86_64-linux-gnu/libasan.so.5+0x3a810)
    #1 0x7f6c8637f63a in xstrdup /home/test/nftables/src/utils.c:85
    #2 0x7f6c8648a4d3 in nft_lex /home/test/nftables/src/scanner.l:740

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agolibnftables: fix memleak when first message in batch is used to report error
Pablo Neira Ayuso [Fri, 18 Jun 2021 23:42:20 +0000 (01:42 +0200)] 
libnftables: fix memleak when first message in batch is used to report error

The err->seqnum == batch_seqnum case results in a memleak of mnl_err
objects under some scenarios such as nf_tables kernel support is not
available or user runs the nft executable as non-root.

Fixes: f930cc500318 ("nftables: fix supression of "permission denied" errors")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoevaluate: fix maps with key and data concatenations
Pablo Neira Ayuso [Tue, 22 Jun 2021 19:38:18 +0000 (21:38 +0200)] 
evaluate: fix maps with key and data concatenations

expr_evaluate_concat() is overloaded, it deals with two cases:

 #1 set key and data definitions, this case uses the special
    dynamically created concatenation datatype which is taken
    from the context.
 #2 set elements, this case iterates over the set key and data
    expressions that are components of the concatenation tuple,
    to fetch the corresponding datatype.

Add a new function to deal with case #1 specifically.

This patch is implicitly fixing up map that include arbitrary
concatenations. This is failing with a spurious error report such as:

 # cat bug.nft
 table x {
        map test {
                type ipv4_addr . inet_proto . inet_service : ipv4_addr . inet_service
        }
 }

 # nft -f bug.nft
 bug.nft:3:48-71: Error: datatype mismatch, expected concatenation of (IPv4 address, Internet protocol, internet network service), expression has type concatenation of (IPv4 address, internet network service)
                type ipv4_addr . inet_proto . inet_service : ipv4_addr . inet_service
                                                             ^^^^^^^^^^^^^^^^^^^^^^^^

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agosrc: queue: allow use of MAP statement for queue number retrieval
Florian Westphal [Wed, 16 Jun 2021 16:45:56 +0000 (18:45 +0200)] 
src: queue: allow use of MAP statement for queue number retrieval

This allows to chose a queue number at run time using map statements,
e.g.:

queue flags bypass to ip saddr map { 192.168.7/24 : 0, 192.168.0/24 : 1 }

Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agotests: extend queue testcases for new sreg support
Florian Westphal [Tue, 15 Jun 2021 21:03:57 +0000 (23:03 +0200)] 
tests: extend queue testcases for new sreg support

Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agosrc: queue: allow use of arbitrary queue expressions
Florian Westphal [Tue, 15 Jun 2021 12:57:08 +0000 (14:57 +0200)] 
src: queue: allow use of arbitrary queue expressions

back in 2016 Liping Zhang added support to kernel and libnftnl to
specify a source register containing the queue number to use.

This was never added to nft itself, so allow this.
On linearization side, check if attached expression is a range.
If its not, allocate a new register and set NFTNL_EXPR_QUEUE_SREG_QNUM
attribute after generating the lowlevel expressions for the kernel.

On delinarization we need to check for presence of
NFTNL_EXPR_QUEUE_SREG_QNUM and decode the expression(s) when present.

Also need to do postprocessing for STMT_QUEUE so that the protocol
context is set correctly, without this only raw payload expressions
will be shown (@nh,32,...) instead of 'ip ...'.

Next patch adds test cases.

Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agoparser: new queue flag input format
Florian Westphal [Wed, 16 Jun 2021 16:25:28 +0000 (18:25 +0200)] 
parser: new queue flag input format

Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agoparser: add queue_stmt_compat
Florian Westphal [Wed, 16 Jun 2021 00:01:36 +0000 (02:01 +0200)] 
parser: add queue_stmt_compat

Rename existing rules to _compat to make sure old rules using 'queue'
statement will work.

Next patch adds distinct input format where flags are explicitly
provided:

 queue flags name,<nextflag> num 1

Without this, extension of queue expression to handle arbitrary
expression instead of queue number or range results in parser errors.

Example:
   queue num jhash ip saddr mod 4 and 1 bypass

will fail because scanner is still in 'ip' state, not 'queue', when
"bypass" is read.

Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agosrc: add queue expr and flags to queue_stmt_alloc
Florian Westphal [Tue, 15 Jun 2021 23:45:29 +0000 (01:45 +0200)] 
src: add queue expr and flags to queue_stmt_alloc

Preparation patch to avoid too much $<stmt>$ references in the parser.

Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agoparser: restrict queue num expressiveness
Florian Westphal [Tue, 15 Jun 2021 22:43:46 +0000 (00:43 +0200)] 
parser: restrict queue num expressiveness

Else we run into trouble once we allow
queue num symhash mod 4 and 1

and so on.  Example problem:

queue num jhash ip saddr mod 4 and 1 bypass

This will fail to parse because the scanner is in the wrong state
(ip, not queue), so 'bypass' is parsed as a string.

Currently, while nft will eat the above just fine (minus 'bypass'),
nft rejects this from the evaluation phase with
   Error: queue number is not constant

So seems we are lucky and can restrict the supported expressions
to integer and range.

Furthermore, the line looks wrong because this statement:

   queue num jhash ip saddr mod 4 and 1 bypass

doesn't specifiy a number, "queue num 4" does, or "queue num 1-2" do.

For arbitrary expr support it seems sensible to enforce stricter
ordering to avoid any problems with the flags, for example:

queue bypass,futurekeyword to jhash ip saddr mod 42

Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agoevaluate: fix hash expression maxval
Florian Westphal [Wed, 16 Jun 2021 21:16:45 +0000 (23:16 +0200)] 
evaluate: fix hash expression maxval

It needs to account for the offset too.

Fixes: 9bee0c86f179 ("src: add offset attribute for hash expression")
Fixes: d4f9a8fb9e9a ("src: add offset attribute for numgen expression")
Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agorule: memleak of list of timeout policies
Pablo Neira Ayuso [Thu, 17 Jun 2021 15:29:11 +0000 (17:29 +0200)] 
rule: memleak of list of timeout policies

Release list of ct timeout policy when object is freed.

Direct leak of 160 byte(s) in 2 object(s) allocated from:
    #0 0x7fc0273ad330 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xe9330)
    #1 0x7fc0231377c4 in xmalloc /home/.../devel/nftables/src/utils.c:36
    #2 0x7fc023137983 in xzalloc /home/.../devel/nftables/src/utils.c:75
    #3 0x7fc0231f64d6 in nft_parse /home/.../devel/nftables/src/parser_bison.y:4448

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoparser_bison: memleak in osf flags
Pablo Neira Ayuso [Thu, 17 Jun 2021 15:24:59 +0000 (17:24 +0200)] 
parser_bison: memleak in osf flags

Release osf string flag after processing.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agonetlink_delinearize: memleak when listing ct event rule
Pablo Neira Ayuso [Thu, 17 Jun 2021 15:01:54 +0000 (17:01 +0200)] 
netlink_delinearize: memleak when listing ct event rule

listing a ruleset containing:

ct event set new,related,destroy,label

results in memleak:

 Direct leak of 3672 byte(s) in 27 object(s) allocated from:
    #0 0x7fa5465c0330 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xe9330)
    #1 0x7fa54233772c in xmalloc /home/.../devel/nftables/src/utils.c:36
    #2 0x7fa5423378eb in xzalloc /home/.../devel/nftables/src/utils.c:75
    #3 0x7fa5422488c6 in expr_alloc /home/.../devel/nftables/src/expression.c:45
    #4 0x7fa54224fb91 in binop_expr_alloc /home/.../devel/nftables/src/expression.c:698
    #5 0x7fa54224ddf8 in bitmask_expr_to_binops /home/.../devel/nftables/src/expression.c:512
    #6 0x7fa5423102ca in expr_postprocess /home/.../devel/nftables/src/netlink_delinearize.c:2448

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agosegtree: memleak in error path of the set to segtree conversion
Pablo Neira Ayuso [Thu, 17 Jun 2021 10:31:11 +0000 (12:31 +0200)] 
segtree: memleak in error path of the set to segtree conversion

Release the array of intervals and the segtree in case of error,
otherwise these structures and objects are never released:

SUMMARY: AddressSanitizer: 2864 byte(s) leaked in 37 allocation(s).

Moreover, improve existing a test coverage of this error path.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agonetlink_delinearize: memleak in string netlink postprocessing
Pablo Neira Ayuso [Thu, 17 Jun 2021 00:58:09 +0000 (02:58 +0200)] 
netlink_delinearize: memleak in string netlink postprocessing

Listing a matching wilcard string results in a memleak: ifname "dummy*"

Direct leak of 136 byte(s) in 1 object(s) allocated from:
    #0 0x7f27ba52e330 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xe9330)
    #1 0x7f27b9e1d434 in xmalloc /home/.../devel/nftables/src/utils.c:36
    #2 0x7f27b9e1d5f3 in xzalloc /home/.../devel/nftables/src/utils.c:75
    #3 0x7f27b9d2e8c6 in expr_alloc /home/.../devel/nftables/src/expression.c:45
    #4 0x7f27b9d326e9 in constant_expr_alloc /home/.../devel/nftables/src/expression.c:419
    #5 0x7f27b9db9318 in netlink_alloc_value /home/.../devel/nftables/src/netlink.c:390
    #6 0x7f27b9de0433 in netlink_parse_cmp /home/.../devel/nftables/src/netlink_delinearize.c:321
    #7 0x7f27b9deb025 in netlink_parse_expr /home/.../devel/nftables/src/netlink_delinearize.c:1764
    #8 0x7f27b9deb0de in netlink_parse_rule_expr /home/.../devel/nftables/src/netlink_delinearize.c:1776
    #9 0x7f27b860af7b in nftnl_expr_foreach /home/.../devel/libnftnl/src/rule.c:690

Direct leak of 8 byte(s) in 1 object(s) allocated from:
    #0 0x7f27ba52e330 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xe9330)
    #1 0x7f27b9e1d434 in xmalloc /home/.../devel/nftables/src/utils.c:36
    #2 0x7f27b96975c5 in __gmpz_init2 (/usr/lib/x86_64-linux-gnu/libgmp.so.10+0x1c5c5)

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoevaluate: memleak in binary operation transfer to RHS
Pablo Neira Ayuso [Wed, 16 Jun 2021 23:33:13 +0000 (01:33 +0200)] 
evaluate: memleak in binary operation transfer to RHS

Remove useless reference count grabbing on constant expression that
results in a memleak.

Direct leak of 136 byte(s) in 1 object(s) allocated from:
    #0 0x7f4cd54af330 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xe9330)
    #1 0x7f4cd4d9e489 in xmalloc /home/.../devel/nftables/src/utils.c:36
    #2 0x7f4cd4d9e648 in xzalloc /home/.../devel/nftables/src/utils.c:75
    #3 0x7f4cd4caf8c6 in expr_alloc /home/.../devel/nftables/src/expression.c:45
    #4 0x7f4cd4cb36e9 in constant_expr_alloc /home/.../devel/nftables/src/expression.c:419
    #5 0x7f4cd4ca714c in integer_type_parse /home/.../devel/nftables/src/datatype.c:397
    #6 0x7f4cd4ca4bee in symbolic_constant_parse /home/.../devel/nftables/src/datatype.c:165
    #7 0x7f4cd4ca4572 in symbol_parse /home/.../devel/nftables/src/datatype.c:135
    #8 0x7f4cd4cc333f in expr_evaluate_symbol /home/.../devel/nftables/src/evaluate.c:251
[...]
Indirect leak of 8 byte(s) in 1 object(s) allocated from:
    #0 0x7f4cd54af330 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xe9330)
    #1 0x7f4cd4d9e489 in xmalloc /home/.../devel/nftables/src/utils.c:36
    #2 0x7f4cd46185c5 in __gmpz_init2 (/usr/lib/x86_64-linux-gnu/libgmp.so.10+0x1c5c5)

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoevaluate: unbreak verdict maps with implicit map with interval concatenations
Pablo Neira Ayuso [Wed, 16 Jun 2021 11:49:08 +0000 (13:49 +0200)] 
evaluate: unbreak verdict maps with implicit map with interval concatenations

Verdict maps in combination with interval concatenations are broken, e.g.

 # nft add rule x y tcp dport . ip saddr vmap { 1025-65535 . 192.168.10.2 : accept }

Retrieve the concatenation field length and count from the map->map
expressions that represents the key of the implicit map.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoevaluate: do not skip mapping elements
Pablo Neira Ayuso [Wed, 16 Jun 2021 17:00:50 +0000 (19:00 +0200)] 
evaluate: do not skip mapping elements

Set element keys are of EXPR_SET_ELEM expression type, however, mappings
use the EXPR_MAPPING expression to wrap the EXPR_SET_ELEM key
(mapping->left) and the corresponding data (mapping->right).

This patch adds a wrapper function to fetch the EXPR_SET_ELEM expression
from the key in case of mappings and use it.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agotests: add a icmp-reply only and icmpv6 id test cases
Florian Westphal [Tue, 15 Jun 2021 16:01:51 +0000 (18:01 +0200)] 
tests: add a icmp-reply only and icmpv6 id test cases

Check that nft doesn't remove the dependency in these cases:
icmp type echo-reply icmp id 1
("icmp id" matches both echo request and reply).

Add icmpv6 test cases.  These fail without the previous patches:

add rule ip6 test-ip6 input icmpv6 id 1:
 'icmpv6 id 1' mismatches
 'icmpv6 type { echo-request, echo-reply} icmpv6 parameter-problem 65536/16'

add rule ip6 test-ip6 input icmpv6 type echo-reply icmpv6 id 65534':
  'icmpv6 type echo-reply icmpv6 id 65534' mismatches
  'icmpv6 type echo-reply @th,32,16 65534'

Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agopayload: do not remove icmp echo dependency
Florian Westphal [Tue, 15 Jun 2021 16:01:50 +0000 (18:01 +0200)] 
payload: do not remove icmp echo dependency

"icmp type echo-request icmp id 2" and "icmp id 2" are not the same,
the latter gains an implicit dependency on both echo-request and
echo-reply.

Change payload dependency tracking to not store dependency in case
the value type is ICMP(6)_ECHO(REPLY).

Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agonetlink_delinearize: add missing icmp id/sequence support
Florian Westphal [Tue, 15 Jun 2021 16:01:49 +0000 (18:01 +0200)] 
netlink_delinearize: add missing icmp id/sequence support

Pablo reports following input and output:
in: icmpv6 id 1
out: icmpv6 type { echo-request, echo-reply } icmpv6 parameter-problem 65536/16

Reason is that icmp fields overlap, decoding of the correct name requires
check of the icmpv6 type.  This only works for equality tests, for
instance

in: icmpv6 type echo-request icmpv6 id 1
will be listed as "icmpv6 id 1" (which is not correct either, since the
input only matches on echo-request).

with this patch, output of 'icmpv6 id 1' is
icmpv6 type { echo-request, echo-reply } icmpv6 id 1

The second problem, the removal of a single check (request OR reply),
is resolved in the followup patch.

Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agotests: shell: cover split chain reference across tables
Pablo Neira Ayuso [Mon, 14 Jun 2021 18:51:11 +0000 (20:51 +0200)] 
tests: shell: cover split chain reference across tables

Add a test to cover table T1 containing the definition of chain C1, and
table T1' (actually the same definition as T1) that contains a (jump)
reference to chain C1.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agotests: shell: extend connlimit test
Pablo Neira Ayuso [Fri, 4 Jun 2021 01:10:06 +0000 (03:10 +0200)] 
tests: shell: extend connlimit test

Extend existing test to add a ct count expression in the set definition.

This test cover the upstream kernel fix ad9f151e560b ("netfilter:
nf_tables: initialize set before expression setup").

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agosrc: replace opencoded NFT_SET_ANONYMOUS set flag check by set_is_anonymous()
Pablo Neira Ayuso [Mon, 14 Jun 2021 12:57:25 +0000 (14:57 +0200)] 
src: replace opencoded NFT_SET_ANONYMOUS set flag check by set_is_anonymous()

Use set_is_anonymous() to check for the NFT_SET_ANONYMOUS set flag
instead.

Reported-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agosrc: add xzalloc_array() and use it to allocate the expression hashtable
Pablo Neira Ayuso [Mon, 14 Jun 2021 12:47:47 +0000 (14:47 +0200)] 
src: add xzalloc_array() and use it to allocate the expression hashtable

Otherwise, assertion to ensure that no colission occur is hit due to
uninitialized hashtable memory area:

nft: netlink_delinearize.c:1741: expr_handler_init: Assertion `expr_handle_ht[hash] == NULL' failed.

Fixes: c4058f96c6a5 ("netlink_delinearize: Fix suspicious calloc() call")
Acked-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agoevaluate: add set to cache once
Pablo Neira Ayuso [Mon, 14 Jun 2021 12:05:09 +0000 (14:05 +0200)] 
evaluate: add set to cache once

67d3969a7244 ("evaluate: add set to the cache") re-adds the set into the
cache again.

This bug was hidden behind 5ec5c706d993 ("cache: add hashtable cache for
table") which broke set_evaluate() for anonymous sets.

Phil reported a gcc compilation warning which uncovered this problem.

Reported-by: Phil Sutter <phil@nwl.cc>
Fixes: 67d3969a7244 ("evaluate: add set to the cache")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
4 years agojson: tests: add missing concat test case
Florian Westphal [Mon, 14 Jun 2021 13:01:41 +0000 (15:01 +0200)] 
json: tests: add missing concat test case

Fix
ERROR: did not find JSON equivalent for rule 'ip saddr . ip daddr { 192.0.2.1 . 10.0.0.1-10.0.0.2 }'

when running nft-test.py -j

Fixes: bbcc5eda7e58 ("evaluate: restore interval + concatenation in anonymous set")
Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agojson: tests: fix vlan.t cfi test case
Florian Westphal [Mon, 14 Jun 2021 12:57:57 +0000 (14:57 +0200)] 
json: tests: fix vlan.t cfi test case

The test case exists twice, once with new dei, once with old 'cfi',
so we need to retain the cfi one in the json file too.

Else we get:
 WARNING: line 2: Wrote JSON equivalent for rule vlan id 4094 vlan dei 1

Fixes: d2fba515ff94 ("src: add vlan dei")
Signed-off-by: Florian Westphal <fw@strlen.de>
4 years agorule: Fix for potential off-by-one in cmd_add_loc()
Phil Sutter [Fri, 11 Jun 2021 15:08:34 +0000 (17:08 +0200)] 
rule: Fix for potential off-by-one in cmd_add_loc()

Using num_attrs as index means it must be at max one less than the
array's size at function start.

Fixes: 27362a5bfa433 ("rule: larger number of error locations")
Signed-off-by: Phil Sutter <phil@nwl.cc>