]> git.ipfire.org Git - thirdparty/nftables.git/log
thirdparty/nftables.git
2 years agoevaluate: relax type-checking for integer arguments in mark statements
Jeremy Sowden [Mon, 4 Apr 2022 12:13:52 +0000 (13:13 +0100)] 
evaluate: relax type-checking for integer arguments in mark statements

In order to be able to set ct and meta marks to values derived from
payload expressions, we need to relax the requirement that the type of
the statement argument must match that of the statement key.  Instead,
we require that the base-type of the argument is integer and that the
argument is small enough to fit.

Add one testcase for tests/py.

Signed-off-by: Jeremy Sowden <jeremy@azazel.net>
2 years agonetlink_delinearize: add postprocessing for payload binops
Jeremy Sowden [Mon, 4 Apr 2022 12:13:47 +0000 (13:13 +0100)] 
netlink_delinearize: add postprocessing for payload binops

If a user uses a payload expression as a statement argument:

  nft add rule t c meta mark set ip dscp lshift 2 or 0x10

we may need to undo munging during delinearization.

Signed-off-by: Jeremy Sowden <jeremy@azazel.net>
2 years agooptimize: ignore existing nat mapping
Pablo Neira Ayuso [Tue, 7 Feb 2023 09:53:41 +0000 (10:53 +0100)] 
optimize: ignore existing nat mapping

User might be already using a nat mapping in their ruleset, use the
unsupported statement when collecting statements in this case.

 # nft -c -o -f ruleset.nft
 nft: optimize.c:443: rule_build_stmt_matrix_stmts: Assertion `k >= 0' failed.
 Aborted

The -o/--optimize feature only cares about linear rulesets at this
stage, but do not hit assert() in this case.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1656
Fixes: 0a6dbfce6dc3 ("optimize: merge nat rules with same selectors into map")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agorule: expand standalone chain that contains rules
Pablo Neira Ayuso [Mon, 6 Feb 2023 14:28:41 +0000 (15:28 +0100)] 
rule: expand standalone chain that contains rules

Otherwise rules that this chain contains are ignored when expressed
using the following syntax:

chain inet filter input2 {
       type filter hook input priority filter; policy accept;
       ip saddr 1.2.3.4 tcp dport { 22, 443, 123 } drop
}

When expanding the chain, remove the rule so the new CMD_OBJ_CHAIN
case does not expand it again.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1655
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agorule: add helper function to expand chain rules into commands
Pablo Neira Ayuso [Mon, 6 Feb 2023 14:28:40 +0000 (15:28 +0100)] 
rule: add helper function to expand chain rules into commands

This patch adds a helper function to expand chain rules into commands.
This comes in preparation for the follow up patch.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agooptimize: select merge criteria based on candidates rules
Pablo Neira Ayuso [Mon, 6 Feb 2023 13:18:10 +0000 (14:18 +0100)] 
optimize: select merge criteria based on candidates rules

Select the merge criteria based on the statements that are used
in the candidate rules, instead of using the list of statements
in the given chain.

Update tests to include a rule with a verdict, which triggers
the bug described in the bugzilla ticket.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1657
Fixes: 0a6dbfce6dc3 ("optimize: merge nat rules with same selectors into map")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: add support to command "destroy"
Fernando F. Mancera [Mon, 6 Feb 2023 10:06:42 +0000 (11:06 +0100)] 
src: add support to command "destroy"

"destroy" command performs a deletion as "delete" command but does not fail
if the object does not exist. As there is no NLM_F_* flag for ignoring such
error, it needs to be ignored directly on error handling.

Example of use:

# nft list ruleset
        table ip filter {
                chain output {
                }
        }
        # nft destroy table ip missingtable
# echo $?
0
        # nft list ruleset
        table ip filter {
                chain output {
                }
        }

Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agooptimize: fix incorrect expansion into concatenation with verdict map
Pablo Neira Ayuso [Thu, 2 Feb 2023 20:47:56 +0000 (21:47 +0100)] 
optimize: fix incorrect expansion into concatenation with verdict map

 # nft -c -o -f ruleset.nft
 Merging:
 ruleset.nft:3:3-53:          meta pkttype broadcast udp dport { 67, 547 } accept
 ruleset.nft:4:17-58:         meta pkttype multicast udp dport 1900 drop
 into:
        meta pkttype . udp dport vmap { broadcast . { 67, 547 } : accept, multicast . 1900 : drop }
 ruleset.nft:3:38-39: Error: invalid data type, expected concatenation of (packet type, internet network service)
                meta pkttype broadcast udp dport { 67, 547 } accept
                                                   ^^

Similar to 187c6d01d357 ("optimize: expand implicit set element when
merging into concatenation") but for verdict maps.

Reported-by: Simon G. Trajkovski <neur0armitage@proton.me>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agooptimize: wrap code to build concatenation in helper function
Pablo Neira Ayuso [Thu, 2 Feb 2023 17:15:22 +0000 (18:15 +0100)] 
optimize: wrap code to build concatenation in helper function

Move code to build concatenations into helper function, this routine
includes support for expansion of implicit sets containing singleton
values. This is preparation work to reuse existing code in a follow up
patch.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoevaluate: set eval ctx for add/update statements with integer constants
Florian Westphal [Mon, 23 Jan 2023 18:03:28 +0000 (19:03 +0100)] 
evaluate: set eval ctx for add/update statements with integer constants

Eric reports that nft asserts when using integer basetype constants with
'typeof' sets.  Example:
table netdev t {
set s {
typeof ether saddr . vlan id
flags dynamic,timeout
}

chain c { }
}

loads fine.  But adding a rule with add/update statement fails:
nft 'add rule netdev t c set update ether saddr . 0 @s'
nft: netlink_linearize.c:867: netlink_gen_expr: Assertion `dreg < ctx->reg_low' failed.

When the 'ether saddr . 0' concat expression is processed, there is
no set definition available anymore to deduce the required size of the
integer constant.

nft eval step then derives the required length using the data types.
'0' has integer basetype, so the deduced length is 0.

The assertion triggers because serialization step finds that it
needs one more register.

2 are needed to store the ethernet address, another register is
needed for the vlan id.

Update eval step to make the expression context store the set key
information when processing the preceeding set reference, then
let stmt_evaluate_set() preserve the  existing context instead of
zeroing it again via stmt_evaluate_arg().

This makes concat expression evaluation compute the total size
needed based on the sets key definition.

Reported-by: Eric Garver <eric@garver.life>
Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agotests: shell: extend runtime set element automerge to cover partial deletions
Pablo Neira Ayuso [Sun, 15 Jan 2023 19:17:50 +0000 (20:17 +0100)] 
tests: shell: extend runtime set element automerge to cover partial deletions

Perform partial deletions of an existing interval and check that the
set remains in consistent state.

Before the follow kernel fixes:

 netfilter: nft_set_rbtree: skip elements in transaction from garbage collection
 netfilter: nft_set_rbtree: Switch to node list walk for overlap detection

without these patches, this test fails with bogus overlap reports.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoImplement 'reset rule' and 'reset rules' commands
Phil Sutter [Fri, 14 Oct 2022 21:19:22 +0000 (23:19 +0200)] 
Implement 'reset rule' and 'reset rules' commands

Reset rule counters and quotas in kernel, i.e. without having to reload
them. Requires respective kernel patch to support NFT_MSG_GETRULE_RESET
message type.

Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agointervals: restrict check missing elements fix to sets with no auto-merge
Pablo Neira Ayuso [Thu, 12 Jan 2023 20:46:41 +0000 (21:46 +0100)] 
intervals: restrict check missing elements fix to sets with no auto-merge

If auto-merge is enabled, skip check for element mismatch introduced by
6d1ee9267e7e ("intervals: check for EXPR_F_REMOVE in case of element
mismatch"), which is only relevant to sets with no auto-merge.

The interval adjustment routine for auto-merge already checks for
unexisting intervals in that case.

Uncovered via ASAN:

==11946==ERROR: AddressSanitizer: heap-use-after-free on address
0x60d00000021c at pc 0x559ae160d5b3 bp 0x7ffc37bcb800 sp 0x7ffc37bcb7f8
READ of size 4 at 0x60d00000021c thread T0
    #0 0x559ae160d5b2 in 0? /builddir/build/BUILD/nftables-1.0.6/src/intervals.c:424
    #1 0x559ae15cb05a in interval_set_eval.lto_priv.0 (/usr/lib64/libnftables.so.1+0xaf05a)
    #2 0x559ae15e1c0d in setelem_evaluate.lto_priv.0 (/usr/lib64/libnftables.so.1+0xc5c0d)
    #3 0x559ae166b715 in nft_evaluate (/usr/lib64/libnftables.so.1+0x14f715)
    #4 0x559ae16749b4 in nft_run_cmd_from_buffer (/usr/lib64/libnftables.so.1+0x1589b4)
    #5 0x559ae20c0e7e in main (/usr/bin/nft+0x8e7e)
    #6 0x559ae1341146 in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
    #7 0x559ae1341204 in __libc_start_main_impl ../csu/libc-start.c:381
    #8 0x559ae20c1420 in _start ../sysdeps/x86_64/start.S:115

0x60d00000021c is located 60 bytes inside of 144-byte region [0x60d0000001e0,0x60d000000270) freed by thread T0 here:
    #0 0x559ae18ea618 in __interceptor_free ../../../../gcc-12.2.0/libsanitizer/asan/asan_malloc_linux.cpp:52
    #1 0x559ae160c315 in 4 /builddir/build/BUILD/nftables-1.0.6/src/intervals.c:349
    #2 0x559ae160c315 in 0? /builddir/build/BUILD/nftables-1.0.6/src/intervals.c:420

previously allocated by thread T0 here:
    #0 0x559ae18eb927 in __interceptor_calloc ../../../../gcc-12.2.0/libsanitizer/asan/asan_malloc_linux.cpp:77
    #1 0x559ae15c5076 in set_elem_expr_alloc (/usr/lib64/libnftables.so.1+0xa9076)

Fixes: 6d1ee9267e7e ("intervals: check for EXPR_F_REMOVE in case of element mismatch")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agomnl: dump_nf_hooks() leaks memory in error path
Phil Sutter [Wed, 11 Jan 2023 11:28:15 +0000 (12:28 +0100)] 
mnl: dump_nf_hooks() leaks memory in error path

Have to free the basehook object before returning to caller.

Fixes: 4694f7230195b ("src: add support for base hook dumping")
Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agometa: parse_iso_date() returns boolean
Phil Sutter [Wed, 11 Jan 2023 10:26:41 +0000 (11:26 +0100)] 
meta: parse_iso_date() returns boolean

Returning ts if 'ts == (time_t) -1' signals success to caller despite
failure.

Fixes: 4460b839b945a ("meta: fix compiler warning in date_type_parse()")
Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agonetlink: Fix for potential NULL-pointer deref
Phil Sutter [Tue, 10 Jan 2023 21:36:58 +0000 (22:36 +0100)] 
netlink: Fix for potential NULL-pointer deref

If memory allocation fails, calloc() returns NULL which was not checked
for. The code seems to expect zero array size though, so simply
replacing this call by one of the x*calloc() ones won't work. So guard
the call also by a check for 'len'.

Fixes: db0697ce7f602 ("src: support for flowtable listing")
Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agooptimize: Do not return garbage from stack
Phil Sutter [Fri, 13 Jan 2023 16:09:53 +0000 (17:09 +0100)] 
optimize: Do not return garbage from stack

If input does not contain a single 'add' command (unusual, but
possible), 'ret' value was not initialized by nft_optimize() before
returning its value.

Fixes: fb298877ece27 ("src: add ruleset optimization infrastructure")
Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agooptimize: Clarify chain_optimize() array allocations
Phil Sutter [Tue, 10 Jan 2023 21:13:44 +0000 (22:13 +0100)] 
optimize: Clarify chain_optimize() array allocations

Arguments passed to sizeof() where deemed suspicious by covscan due to
the different type. Consistently specify size of an array 'a' using
'sizeof(*a) * nmemb'.

For the statement arrays in stmt_matrix, even use xzalloc_array() since
the item count is fixed and therefore can't be zero.

Fixes: fb298877ece27 ("src: add ruleset optimization infrastructure")
Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agooptimize: payload expression requires inner_desc comparison
Pablo Neira Ayuso [Wed, 4 Jan 2023 10:25:07 +0000 (11:25 +0100)] 
optimize: payload expression requires inner_desc comparison

Since 772892a018b4 ("src: add vxlan matching support"), payload
expressions have an inner_desc field that provides the description for
the outer tunnel header.

When searching for common mergeable selectors, compare the inner
description too.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agodoc: add gretap matching expression
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:50 +0000 (15:36 +0100)] 
doc: add gretap matching expression

Document new gretap matching expression. This includes support for
matching the encapsulated ethernet frame layer 2, 3 and 4 headers
within the gre header.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agotests: py: add gretap tests
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:46 +0000 (15:36 +0100)] 
tests: py: add gretap tests

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: add gretap support
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:44 +0000 (15:36 +0100)] 
src: add gretap support

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agodoc: add geneve matching expression
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:42 +0000 (15:36 +0100)] 
doc: add geneve matching expression

Document new geneve matching expression. This includes support for
matching the encapsulated ethernet frame layer 2, 3 and 4 headers.

2 years agotests: py: add geneve tests
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:40 +0000 (15:36 +0100)] 
tests: py: add geneve tests

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: add geneve matching support
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:39 +0000 (15:36 +0100)] 
src: add geneve matching support

Add support for GENEVE vni and (ether) type header field.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agodoc: add gre matching expression
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:37 +0000 (15:36 +0100)] 
doc: add gre matching expression

Document new vxlan matching expression. This includes support for
matching the encapsulated ethernet frame layer 3 and 4 headers.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agotests: py: add gre tests
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:35 +0000 (15:36 +0100)] 
tests: py: add gre tests

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: add gre support
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:33 +0000 (15:36 +0100)] 
src: add gre support

GRE has a number of fields that are conditional based on flags,
which requires custom dependency code similar to icmp and icmpv6.
Matching on optional fields is not supported at this stage.

Since this is a layer 3 tunnel protocol, an implicit dependency on
NFT_META_L4PROTO for IPPROTO_GRE is generated. To achieve this, this
patch adds new infrastructure to remove an outer dependency based on
the inner protocol from delinearize path.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: display (inner) tag in --debug=proto-ctx
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:31 +0000 (15:36 +0100)] 
src: display (inner) tag in --debug=proto-ctx

For easier debugging, add decoration on protocol context:

 # nft --debug=proto-ctx add rule netdev x y udp dport 4789 vxlan ip protocol icmp counter
 update link layer protocol context (inner):
  link layer          : netdev <-
  network layer       : none
  transport layer     : none
  payload data        : none

 update network layer protocol context (inner):
  link layer          : netdev
  network layer       : ip <-
  transport layer     : none
  payload data        : none

 update network layer protocol context (inner):
  link layer          : netdev
  network layer       : ip <-
  transport layer     : none
  payload data        : none

 update transport layer protocol context (inner):
  link layer          : netdev
  network layer       : ip
  transport layer     : icmp <-
  payload data        : none

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agodoc: add vxlan matching expression
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:30 +0000 (15:36 +0100)] 
doc: add vxlan matching expression

Document new vxlan matching expression. This includes support for
matching the encapsulated ethernet frame layer 2, 3 and 4 headers.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agotests: shell: add vxlan set tests
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:28 +0000 (15:36 +0100)] 
tests: shell: add vxlan set tests

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agotests: py: add vxlan tests
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:26 +0000 (15:36 +0100)] 
tests: py: add vxlan tests

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: add vxlan matching support
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:25 +0000 (15:36 +0100)] 
src: add vxlan matching support

This patch adds the initial infrastructure to support for inner header
tunnel matching and its first user: vxlan.

A new struct proto_desc field for payload and meta expression to specify
that the expression refers to inner header matching is used.

The existing codebase to generate bytecode is fully reused, allowing for
reusing existing supported layer 2, 3 and 4 protocols.

Syntax requires to specify vxlan before the inner protocol field:

... vxlan ip protocol udp
... vxlan ip saddr 1.2.3.0/24

This also works with concatenations and anonymous sets, eg.

... vxlan ip saddr . vxlan ip daddr { 1.2.3.4 . 4.3.2.1 }

You have to restrict vxlan matching to udp traffic, otherwise it
complains on missing transport protocol dependency, e.g.

... udp dport 4789 vxlan ip daddr 1.2.3.4

The bytecode that is generated uses the new inner expression:

 # nft --debug=netlink add rule netdev x y udp dport 4789 vxlan ip saddr 1.2.3.4
 netdev x y
  [ meta load l4proto => reg 1 ]
  [ cmp eq reg 1 0x00000011 ]
  [ payload load 2b @ transport header + 2 => reg 1 ]
  [ cmp eq reg 1 0x0000b512 ]
  [ inner type 1 hdrsize 8 flags f [ meta load protocol => reg 1 ] ]
  [ cmp eq reg 1 0x00000008 ]
  [ inner type 1 hdrsize 8 flags f [ payload load 4b @ network header + 12 => reg 1 ] ]
  [ cmp eq reg 1 0x04030201 ]

JSON support is not included in this patch.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: add dl_proto_ctx()
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:23 +0000 (15:36 +0100)] 
src: add dl_proto_ctx()

Add dl_proto_ctx() to access protocol context (struct proto_ctx and
struct payload_dep_ctx) from the delinearize path.

This patch comes in preparation for supporting outer and inner
protocol context.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: add eval_proto_ctx()
Pablo Neira Ayuso [Mon, 2 Jan 2023 14:36:20 +0000 (15:36 +0100)] 
src: add eval_proto_ctx()

Add eval_proto_ctx() to access protocol context (struct proto_ctx).
Rename struct proto_ctx field to _pctx to highlight that this field
is internal and the helper function should be used.

This patch comes in preparation for supporting outer and inner
protocol context.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: Add GPLv2+ header to .c files of recent creation
Pablo Neira Ayuso [Wed, 7 Dec 2022 15:08:15 +0000 (16:08 +0100)] 
src: Add GPLv2+ header to .c files of recent creation

This patch comes after a proposal of mine at NFWS 2022 that resulted in
agreement to license recent .c files under GPLv2+ by the attendees at this
meeting:

- Stefano Brivio
- Fernando F. Mancera
- Phil Sutter
- Jozsef Kadlecsik
- Florian Westphal
- Laura Garcia
- Arturo Borrero
- Pablo Neira

It has already happened that one of the external library dependencies
was moved to GPLv3+ (libreadline), resulting in a change to libedit by
default in b4dded0ca78d ("configure: default to libedit for cli").

I have added the GPLv2+ header to the following files:

                        Authors
                        -------
src/cmd.c               Pablo
src/fib.c               Florian
src/hash.c              Pablo
src/iface.c             Pablo
src/json.c              Phil + fixes from occasional contributors
src/libnftables.c       Eric Leblond and Phil
src/mergesort.c         Elise Lenion
src/misspell.c          Pablo
src/mnl.c               Pablo + fixes from occasional contributors
src/monitor.c           Arturo
src/numgen.c            Pablo
src/osf.c               Fernando
src/owner.c             Pablo
src/parser_json.c       Phil + fixes from occasional contributors
src/print.c             Phil
src/xfrm.c              Florian
src/xt.c                Pablo

Eric Leblond and Elise Lennion did not attend NFWS 2022, but they
acknowledged this license update already in the past when I proposed
this to them in private emails.

Update COPYING file too to refer that we are now moving towards GPLv2 or
any later.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: Update copyright header to GPLv2+ in socket.c
Máté Eckl [Fri, 16 Dec 2022 19:06:10 +0000 (20:06 +0100)] 
src: Update copyright header to GPLv2+ in socket.c

Cc: Pablo Neira Ayuso <pablo@netfilter.org>,
Cc: Phil Sutter <phil@nwl.cc>
Signed-off-by: Máté Eckl <ecklm94@gmail.com>
Signed-off-by: Balázs Scheidler <bazsi77@gmail.com>
Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agoct: use inet_service_type for proto-src and proto-dst
Pablo Neira Ayuso [Thu, 22 Dec 2022 11:49:59 +0000 (12:49 +0100)] 
ct: use inet_service_type for proto-src and proto-dst

Instead of using the invalid type.

Problem was uncovered by this ruleset:

 table ip foo {
        map pinned {
                typeof ip daddr . ct original proto-dst : ip daddr . tcp dport
                size 65535
                flags dynamic,timeout
                timeout 6m
        }

        chain pr {
                meta l4proto tcp update @pinned { ip saddr . ct original proto-dst timeout 1m30s : ip daddr . tcp dport }
        }
 }

resulting in the following misleading error:

map-broken.nft:10:51-82: Error: datatype mismatch: expected concatenation of (IPv4 address), expression has type concatenation of (IPv4 address, internet network service)
                meta l4proto tcp update @pinned { ip saddr . ct original proto-dst timeout 1m30s : ip daddr . tcp dport }
                                 ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoevaluate: fix shift exponent underflow in concatenation evaluation
Pablo Neira Ayuso [Thu, 22 Dec 2022 10:23:00 +0000 (11:23 +0100)] 
evaluate: fix shift exponent underflow in concatenation evaluation

There is an underflow of the index that iterates over the concatenation:

../include/datatype.h:292:15: runtime error: shift exponent 4294967290 is too large for 32-bit type 'unsigned int'

set the datatype to invalid which is fine to evaluate a concatenation
in a set/map statement.

Update b8e1940aa190 ("tests: add a test case for map update from packet
path with concat") so it does not need a workaround to work.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoscanner: treat invalid octal strings as strings
Jeremy Sowden [Fri, 16 Dec 2022 20:27:14 +0000 (20:27 +0000)] 
scanner: treat invalid octal strings as strings

The action associated with the `{numberstring}` pattern, passes `yytext`
to `strtoull` with base 0:

errno = 0;
yylval->val = strtoull(yytext, NULL, 0);
if (errno != 0) {
yylval->string = xstrdup(yytext);
return STRING;
}
return NUM;

If `yytext` begins with '0', it will be parsed as octal.  However, this
has unexpected consequences if the token contains non-octal characters.
`09` will be parsed as 0; `0308` will be parsed as 24, because
`strtoull` and its siblings stop parsing as soon as they reach a
character in the input which is not valid for the base.

Replace the `{numberstring}` match with separate `{hexstring}` and
`{decstring}` matches.  For `{decstring}` set the base to 8 if the
leading character is '0', and handle an incompletely parsed token in
the same way as one that causes `strtoull` to set `errno`.

Thus, instead of:

  $ sudo nft -f - <<<'
    table x {
      chain y {
        ip saddr 0308 continue comment "parsed as 0.0.0.24/32"
      }
    }
  '
  $ sudo nft list chain x y
  table ip x {
    chain y {
      ip saddr 0.0.0.24 continue comment "parsed as 0.0.0.24/32"
    }
  }

We get:

  $ sudo ./src/nft -f - <<<'
  > table x {
  >   chain y {
  >     ip saddr 0308 continue comment "error"
  >   }
  > }
  > '
  /dev/stdin:4:14-17: Error: Could not resolve hostname: Name or service not known
      ip saddr 0308 continue comment "error"
               ^^^^

Add a test-case.

Link: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=932880
Link: https://bugzilla.netfilter.org/show_bug.cgi?id=1363
Signed-off-by: Jeremy Sowden <jeremy@azazel.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agobuild: Bump version to 1.0.6 v1.0.6
Pablo Neira Ayuso [Wed, 21 Dec 2022 17:15:32 +0000 (18:15 +0100)] 
build: Bump version to 1.0.6

Update dependency on libnftnl >= 1.2.4 which contains fixes.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoowner: Fix potential array out of bounds access
Pablo Neira Ayuso [Wed, 21 Dec 2022 16:37:46 +0000 (17:37 +0100)] 
owner: Fix potential array out of bounds access

If the link target length exceeds 'sizeof(tmp)' bytes, readlink() will
return 'sizeof(tmp)'. Using this value as index is illegal.

Original update from Phil, for the conntrack-tools tree, which also has
a copy of this function.

Fixes: 6d085b22a8b5 ("table: support for the table owner flag")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agodoc: add/update can be used with maps too
Florian Westphal [Tue, 13 Dec 2022 13:37:22 +0000 (14:37 +0100)] 
doc: add/update can be used with maps too

The man page implies that add/update are only supported with
sets, but this can be used with maps as well.

Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agoxt: Fall back to generic printing from translation
Phil Sutter [Thu, 24 Nov 2022 15:16:41 +0000 (16:16 +0100)] 
xt: Fall back to generic printing from translation

If translation is not available or fails, print the generic format
instead of calling the print callback (which does not respect
output_fp) or silently failing.

Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agoxt: Rewrite unsupported compat expression dumping
Phil Sutter [Thu, 24 Nov 2022 13:17:17 +0000 (14:17 +0100)] 
xt: Rewrite unsupported compat expression dumping

Choose a format which provides more information and is easily parseable.
Then teach parsers about it and make it explicitly reject the ruleset
giving a meaningful explanation. Also update the man pages with some
more details.

Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agoxt: Purify enum nft_xt_type
Phil Sutter [Thu, 24 Nov 2022 15:24:05 +0000 (16:24 +0100)] 
xt: Purify enum nft_xt_type

Remove NFT_XT_MAX from the enum, it is not a valid xt type.

Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agoxt: Delay libxtables access until translation
Phil Sutter [Thu, 10 Nov 2022 17:44:43 +0000 (18:44 +0100)] 
xt: Delay libxtables access until translation

There is no point in spending efforts setting up the xt match/target
when it is not printed afterwards. So just store the statement data from
libnftnl in struct xt_stmt and perform the extension lookup from
xt_stmt_xlate() instead.

This means some data structures are only temporarily allocated for the
sake of passing to libxtables callbacks, no need to drag them around.
Also no need to clone the looked up extension, it is needed only to call
the functions it provides.

While being at it, select numeric output in xt_xlate_*_params -
otherwise there will be reverse DNS lookups which should not happen by
default.

Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agotests: add a test case for map update from packet path with concat
Florian Westphal [Mon, 12 Dec 2022 10:04:36 +0000 (11:04 +0100)] 
tests: add a test case for map update from packet path with concat

add a second test case for map updates, this time with both
a timeout and a data element that consists of a concatenation.

Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agonetlink_linearize: fix timeout with map updates
Florian Westphal [Mon, 12 Dec 2022 10:04:35 +0000 (11:04 +0100)] 
netlink_linearize: fix timeout with map updates

Map updates can use timeouts, just like with sets, but the
linearization step did not pass this info to the kernel.

meta l4proto tcp update @pinned { ip saddr . ct original proto-src timeout 90s : ip daddr . tcp dport

Listing this won't show the "timeout 90s" because kernel never saw it to
begin with.

Also update evaluation step to reject a timeout that was set on
the data part: Timeouts are only allowed for the key-value pair
as a whole.

Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agonetlink_delinearize: fix decoding of concat data element
Florian Westphal [Mon, 12 Dec 2022 10:04:34 +0000 (11:04 +0100)] 
netlink_delinearize: fix decoding of concat data element

Its possible to use update as follows:

 meta l4proto tcp update @pinned { ip saddr . ct original proto-src : ip daddr . ct original proto-dst }

... but when listing, only the first element of the concatenation is
shown.

Check if the element size is too small and parse subsequent registers as
well.

Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agoevaluate: fix compilation warning
Pablo Neira Ayuso [Mon, 12 Dec 2022 09:18:10 +0000 (10:18 +0100)] 
evaluate: fix compilation warning

Set pointer to list of expression to NULL and check that it is set on
before using it.

In function â€˜expr_evaluate_concat’,
    inlined from â€˜expr_evaluate’ at evaluate.c:2488:10:
evaluate.c:1338:20: warning: â€˜expressions’ may be used uninitialized [-Wmaybe-uninitialized]
 1338 |                 if (runaway) {
      |                    ^
evaluate.c: In function â€˜expr_evaluate’:
evaluate.c:1321:33: note: â€˜expressions’ was declared here
 1321 |         const struct list_head *expressions;
      |                                 ^~~~~~~~~~~

Reported-by: Florian Westphal <fw@strlen.de>
Fixes: 508f3a270531 ("netlink: swap byteorder of value component in concatenation of intervals")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoscanner: match full comment line in case of tie
Pablo Neira Ayuso [Sat, 10 Dec 2022 22:36:39 +0000 (23:36 +0100)] 
scanner: match full comment line in case of tie

  add element ip filter public_services {
          # comment 1
          tcp . 80  : jump log_accept,
  # comment 2
          tcp . 443 : jump log_accept,
  }

still fails with the error message:

  # nft -f filter_sets.ip
  In file included from filter_sets.ip:63:1-42:
  filter_sets.ip:4:12-12: Error: syntax error,
  unexpected newline, expecting comma or '}'
  # comment 2
             ^

flex honors the first rule found in case of tie, place comment_line
before comment rule.

Fixes: 931737a17198 ("scanner: munch full comment lines")
Reported-by: Jozsef Kadlecsik <kadlec@netfilter.org>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agonetlink: unfold function to generate concatenations for keys and data
Pablo Neira Ayuso [Thu, 8 Dec 2022 01:32:17 +0000 (02:32 +0100)] 
netlink: unfold function to generate concatenations for keys and data

Add a specific function to generate concatenation with and without
intervals in maps. This restores the original function added by
8ac2f3b2fca3 ("src: Add support for concatenated set ranges") which is
used by 66746e7dedeb ("src: support for nat with interval
concatenation") to generate the data concatenations in maps.

Only the set element key requires the byteswap introduced by 1017d323cafa
("src: support for selectors with different byteorder with interval
concatenations"). Therefore, better not to reuse the same function for
key and data as the future might bring support for more kind of
concatenations in data maps.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agonetlink: add function to generate set element key data
Pablo Neira Ayuso [Fri, 9 Dec 2022 10:55:50 +0000 (11:55 +0100)] 
netlink: add function to generate set element key data

Add netlink_gen_key(), it is just like __netlink_gen_data() with no
EXPR_VERDICT case, which should not ever happen for set element keys.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agonetlink: statify __netlink_gen_data()
Pablo Neira Ayuso [Fri, 9 Dec 2022 10:53:56 +0000 (11:53 +0100)] 
netlink: statify __netlink_gen_data()

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoMakefile: Create LZMA-compressed dist-files
Phil Sutter [Wed, 7 Dec 2022 23:45:28 +0000 (00:45 +0100)] 
Makefile: Create LZMA-compressed dist-files

Use a more modern alternative to bzip2.

Suggested-by: Jan Engelhardt <jengelh@inai.de>
Suggested-by: Pablo Neira Ayuso <pablo@netfilter.org>
Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agoevaluate: do not crash on runaway number of concatenation components
Pablo Neira Ayuso [Thu, 8 Dec 2022 01:25:19 +0000 (02:25 +0100)] 
evaluate: do not crash on runaway number of concatenation components

Display error message in case user specifies more data components than
those defined by the concatenation of selectors.

 # cat example.nft
 table ip x {
        chain y {
                type filter hook prerouting priority 0; policy drop;
                ip saddr . meta mark { 1.2.3.4 . 0x00000100 . 1.2.3.6-1.2.3.8 } accept
        }
 }
 # nft -f example.nft
 example.nft:4:3-22: Error: too many concatenation components
                ip saddr . meta mark { 1.2.3.4 . 0x00000100 . 1.2.3.6-1.2.3.8 } accept
                ~~~~~~~~~~~~~~~~~~~~   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Without this patch, nft crashes:

==464771==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60d000000418 at pc 0x7fbc17513aa5 bp 0x7ffc73d33c90 sp 0x7ffc73d33c88
READ of size 8 at 0x60d000000418 thread T0
    #0 0x7fbc17513aa4 in expr_evaluate_concat /home/pablo/devel/scm/git-netfilter/nftables/src/evaluate.c:1348
    #1 0x7fbc1752a9da in expr_evaluate /home/pablo/devel/scm/git-netfilter/nftables/src/evaluate.c:2476
    #2 0x7fbc175175e2 in expr_evaluate_set_elem /home/pablo/devel/scm/git-netfilter/nftables/src/evaluate.c:1504
    #3 0x7fbc1752aa22 in expr_evaluate /home/pablo/devel/scm/git-netfilter/nftables/src/evaluate.c:2482
    #4 0x7fbc17512cb5 in list_member_evaluate /home/pablo/devel/scm/git-netfilter/nftables/src/evaluate.c:1310
    #5 0x7fbc17518ca0 in expr_evaluate_set /home/pablo/devel/scm/git-netfilter/nftables/src/evaluate.c:1590
    [...]

Fixes: 64bb3f43bb96 ("src: allow to use typeof of raw expressions in set declaration")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agonetlink: swap byteorder of value component in concatenation of intervals
Pablo Neira Ayuso [Thu, 8 Dec 2022 00:35:05 +0000 (01:35 +0100)] 
netlink: swap byteorder of value component in concatenation of intervals

Commit 1017d323cafa ("src: support for selectors with different byteorder with
interval concatenations") was incomplete.

Switch byteorder of singleton values in a set that contains
concatenation of intervals. This singleton value is actually represented
as a range in the kernel.

After this patch, if the set represents a concatenation of intervals:

- EXPR_F_INTERVAL denotes the lhs of the interval.
- EXPR_F_INTERVAL_END denotes the rhs of the interval (this flag was
  already used in this way before this patch).

If none of these flags are set on, then the set contains concatenations
of singleton values (no interval flag is set on), in such case, no
byteorder swap is required.

Update tests/shell and tests/py to cover the use-case breakage reported
by Eric.

Fixes: 1017d323cafa ("src: support for selectors with different byteorder with interval concatenations")
Reported-by: Eric Garver <eric@garver.life>
Tested-by: Eric Garver <eric@garver.life>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agotests: py: missing json for different byteorder selector with interval concatenation
Pablo Neira Ayuso [Wed, 7 Dec 2022 21:15:12 +0000 (22:15 +0100)] 
tests: py: missing json for different byteorder selector with interval concatenation

Add missing json output, otherwise -j reports an error.

Fixes: 1017d323cafa ("src: support for selectors with different byteorder with interval concatenations")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoscanner: munch full comment lines
Pablo Neira Ayuso [Tue, 6 Dec 2022 21:59:55 +0000 (22:59 +0100)] 
scanner: munch full comment lines

Munch lines full comment lines, regular expression matches lines that
start by space or tab, then # follows, finally anything including one
single line break.

Call reset_pos() to ensure error reporting location is not puzzled.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1196
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agodoc: statements: fwd supports for sending packets via neighbouring layer
Pablo Neira Ayuso [Tue, 6 Dec 2022 17:02:25 +0000 (18:02 +0100)] 
doc: statements: fwd supports for sending packets via neighbouring layer

Document ability to forward packets through neighbour layer added in
30d45266bf38 ("expr: extend fwd statement to support address and family").

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agodoc: payload-expression.txt: Mention that 'ih' exists
Harald Welte [Tue, 6 Dec 2022 14:03:33 +0000 (15:03 +0100)] 
doc: payload-expression.txt: Mention that 'ih' exists

Back in commit b67abc51ba6f ("src: raw payload match and mangle on inner
header / payload data") a new payload expression 'ih' was added, but the
documentation wasn't updated accordingly.

Let's at least mention in the man page that it exists at all.

Signed-off-by: Harald Welte <laforge@gnumonks.org>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agojson: fix 'add flowtable' command
Alex Forster [Fri, 2 Dec 2022 03:35:01 +0000 (21:35 -0600)] 
json: fix 'add flowtable' command

In `json_parse_cmd_add_flowtable`, the format arguments passed to `json_unpack` are incorrect: the object key name ("dev") is not provided.

Fixes: da6cb40177da ("parser_json: permit empty device list")
Signed-off-by: Alex Forster <aforster@cloudflare.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: support for selectors with different byteorder with interval concatenations
Pablo Neira Ayuso [Wed, 23 Nov 2022 16:59:21 +0000 (17:59 +0100)] 
src: support for selectors with different byteorder with interval concatenations

Assuming the following interval set with concatenation:

 set test {
typeof ip saddr . meta mark
flags interval
 }

then, the following rule:

 ip saddr . meta mark @test

requires bytecode that swaps the byteorder for the meta mark selector in
case the set contains intervals and concatenations.

 inet x y
   [ meta load nfproto => reg 1 ]
   [ cmp eq reg 1 0x00000002 ]
   [ payload load 4b @ network header + 12 => reg 1 ]
   [ meta load mark => reg 9 ]
   [ byteorder reg 9 = hton(reg 9, 4, 4) ]  <----- this is required !
   [ lookup reg 1 set test dreg 0 ]

This patch updates byteorder_conversion() to add the unary expression
that introduces the byteorder expression.

Moreover, store the meta mark range component of the element tuple in
the set in big endian as it is required for the range comparisons. Undo
the byteorder swap in the netlink delinearize path to listing the meta
mark values accordingly.

Update tests/py to validate that byteorder expression is emitted in the
bytecode. Update tests/shell to validate insertion and listing of a
named map declaration.

A similar commit 806ab081dc9a ("netlink: swap byteorder for
host-endian concat data") already exists in the tree to handle this for
strings with prefix (e.g. eth*).

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoWarn for tables with compat expressions in rules
Phil Sutter [Tue, 11 Oct 2022 16:46:55 +0000 (18:46 +0200)] 
Warn for tables with compat expressions in rules

While being able to "look inside" compat expressions using nft is a nice
feature, it is also (yet another) pitfall for unaware users, deceiving
them into assuming interchangeability (or at least compatibility)
between iptables-nft and nft.

In reality, which involves 'nft list ruleset | nft -f -', any correctly
translated compat expressions will turn into native nftables ones not
understood by (the version of) iptables-nft which created them in the
first place. Other compat expressions will vanish, potentially
compromising the firewall ruleset.

Emit a warning (as comment) to give users a chance to stop and
reconsider before shooting their own foot.

Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agomonitor: missing cache and set handle initialization
Pablo Neira Ayuso [Fri, 11 Nov 2022 10:07:28 +0000 (11:07 +0100)] 
monitor: missing cache and set handle initialization

This leads to a crash when adding stateful expressions to sets:

netlink.c:928:38: runtime error: member access within null pointer of type 'struct nft_ctx'
AddressSanitizer:DEADLYSIGNAL
=================================================================
==13781==ERROR: AddressSanitizer: SEGV on unknown address 0x0000000000d0 (pc 0x7fc96fc2b6b2 bp 0x7ffc0e26b080 sp 0x7ffc0e26b020 T0)
==13781==The signal is caused by a READ memory access.
==13781==Hint: address points to the zero page.
    #0 0x7fc96fc2b6b2 in table_cache_find /home/pablo/devel/scm/git-netfilter/nftables/src/cache.c:456
    #1 0x7fc96fd244d4 in netlink_parse_set_expr /home/pablo/devel/scm/git-netfilter/nftables/src/netlink_delinearize.c:1857
    #2 0x7fc96fcf1b4d in netlink_delinearize_set /home/pablo/devel/scm/git-netfilter/nftables/src/netlink.c:928
    #3 0x7fc96fd41966 in netlink_events_cache_addset /home/pablo/devel/scm/git-netfilter/nftables/src/monitor.c:649

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agodoc: no reset support for limit
Pablo Neira Ayuso [Wed, 9 Nov 2022 14:59:38 +0000 (15:59 +0100)] 
doc: no reset support for limit

Remove reset command, this not supported for ratelimit.

Fixes: eff2d606d20d ("doc: document a few reset commands supported by the parser")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agodoc: document a few reset commands supported by the parser
Pablo Neira Ayuso [Wed, 9 Nov 2022 10:17:34 +0000 (11:17 +0100)] 
doc: document a few reset commands supported by the parser

The following are missing in the manpage:

 *reset counters* ['family']
 *reset quotas* ['family']
 *reset counters* ['family'] *table* 'table'
 *reset quotas* ['family'] *table* 'table'

While at it, expand type to the supported stateful objects.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agooptimize: handle prefix and range when merging into set + concatenation
Pablo Neira Ayuso [Sat, 5 Nov 2022 15:51:10 +0000 (16:51 +0100)] 
optimize: handle prefix and range when merging into set + concatenation

The following ruleset fails to be merged using set + concatenation:

  meta iifname eth1 ip saddr 1.1.1.2 ip daddr 2.2.3.0/24 accept
  meta iifname eth1 ip saddr 1.1.1.2 ip daddr 2.2.4.0-2.2.4.10 accept

hitting the following assertion:

  nft: optimize.c:585: __merge_concat_stmts: Assertion `0' failed.
  Abort

This patch also updates tests/shell.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agopayload: do not kill dependency for proto_unknown
Pablo Neira Ayuso [Mon, 31 Oct 2022 10:35:31 +0000 (11:35 +0100)] 
payload: do not kill dependency for proto_unknown

Unsupported meta match on layer 4 protocol sets on protocol context to
proto_unknown, handle anything coming after it as a raw expression in
payload_expr_expand().

Moreover, payload_dependency_kill() skips dependency removal if protocol
is unknown, so raw payload expression leaves meta layer 4 protocol
remains in place.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1641
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agonetlink_delinearize: complete payload expression in payload statement
Pablo Neira Ayuso [Mon, 31 Oct 2022 10:35:21 +0000 (11:35 +0100)] 
netlink_delinearize: complete payload expression in payload statement

Call payload_expr_complete() to complete payload expression in payload
statement, otherwise expr->payload.desc is set to proto_unknown.

Call stmt_payload_binop_postprocess() introduced by 50ca788ca4d0
("netlink: decode payload statment") if payload_expr_complete() fails to
provide a protocol description (eg. ip dscp).

Follow up patch does not allow to remove redundant payload dependency if
proto_unknown is used to deal with the raw payload expression case.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agotests: shell: deletion from interval concatenation
Pablo Neira Ayuso [Mon, 17 Oct 2022 11:52:43 +0000 (13:52 +0200)] 
tests: shell: deletion from interval concatenation

Deleting item from concatenated set stops working at least in 5.15.64.
Add test to cover this use case.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1638
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agonetlink_delinearize: do not transfer binary operation to non-anonymous sets
Pablo Neira Ayuso [Wed, 12 Oct 2022 10:50:26 +0000 (12:50 +0200)] 
netlink_delinearize: do not transfer binary operation to non-anonymous sets

Michael Braun says:

This results for nft list ruleset in
  nft: netlink_delinearize.c:1945: binop_adjust_one: Assertion `value->len >= binop->right->len' failed.

This is due to binop_adjust_one setting value->len to left->len, which
is shorther than right->len.

Additionally, it does not seem correct to alter set elements from parsing a
rule, so remove that part all together.

Reported-by: Michael Braun <michael-dev@fami-braun.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agorule: do not display handle for implicit chain
Pablo Neira Ayuso [Fri, 7 Oct 2022 08:04:06 +0000 (10:04 +0200)] 
rule: do not display handle for implicit chain

Implicit chains do not allow for incremental updates, do not display rule
handle since kernel refuses to update an implicit chain which is already
bound.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1615
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoparser_bison: display too many levels of nesting error
Pablo Neira Ayuso [Fri, 7 Oct 2022 07:55:59 +0000 (09:55 +0200)] 
parser_bison: display too many levels of nesting error

Instead of hitting this assertion:

 nft: parser_bison.y:70: open_scope: Assertion `state->scope < array_size(state->scopes) - 1' failed.
 Aborted

this is easier to trigger with implicit chains where one level of
nesting from the existing chain scope is supported.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1615
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoevaluate: datatype memleak after binop transfer
Pablo Neira Ayuso [Tue, 4 Oct 2022 23:36:52 +0000 (01:36 +0200)] 
evaluate: datatype memleak after binop transfer

The following ruleset:

ip version vmap { 4 : jump t3, 6 : jump t4 }

results in a memleak.

expr_evaluate_shift() overrides the datatype which results in a datatype
memleak after the binop transfer that triggers a left-shift of the
constant (in the map).

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoevaluate: bogus datatype assertion in binary operation evaluation
Pablo Neira Ayuso [Tue, 4 Oct 2022 23:36:44 +0000 (01:36 +0200)] 
evaluate: bogus datatype assertion in binary operation evaluation

Use datatype_equal(), otherwise dynamically allocated datatype fails
to fulfill the datatype pointer check, triggering the assertion:

 nft: evaluate.c:1249: expr_evaluate_binop: Assertion `expr_basetype(left) == expr_basetype(right)' failed.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1636
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agomonitor: Sanitize startup race condition
Phil Sutter [Wed, 28 Sep 2022 21:26:42 +0000 (23:26 +0200)] 
monitor: Sanitize startup race condition

During startup, 'nft monitor' first fetches the current ruleset and then
keeps this cache up to date based on received events. This is racey, as
any ruleset changes in between the initial fetch and the socket opening
are not recognized.

This script demonstrates the problem:

| #!/bin/bash
|
| while true; do
|  nft flush ruleset
|  iptables-nft -A FORWARD
| done &
| maniploop=$!
|
| trap "kill $maniploop; kill \$!; wait" EXIT
|
| while true; do
|  nft monitor rules >/dev/null &
|  sleep 0.2
|  kill $!
| done

If the table add event is missed, the rule add event callback fails to
deserialize the rule and calls abort().

Avoid the inconvenient program exit by returning NULL from
netlink_delinearize_rule() instead of aborting and make callers check
the return value.

Signed-off-by: Phil Sutter <phil@nwl.cc>
2 years agotests: py: add vlan test case for ip/inet family
Florian Westphal [Tue, 27 Sep 2022 13:41:33 +0000 (15:41 +0200)] 
tests: py: add vlan test case for ip/inet family

before fixup, this failed with:

line 4: 'add rule ip test-ip4 input vlan id 1': '[ payload load 2b @ link header + 12 => reg 1 ]' mismatches '[ payload load 2b @ link header + 0 => reg 1 ]'

... because the auto-dependency did not add the preceeding ethernet
header, so vlan was using the wrong offset.

Note than vlan id match in inet input families will only work if header
removal was disabled, i.e.

... add link vethin1 name vethin1.3 type vlan id 3 reorder_hdr off

otherwise, kernel will strip the vlan tag and interface appears as
a normal ethernet interface.

Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agoevaluate: add ethernet header size offset for implicit vlan dependency
Florian Westphal [Tue, 27 Sep 2022 12:16:15 +0000 (14:16 +0200)] 
evaluate: add ethernet header size offset for implicit vlan dependency

'vlan id 1'

must also add a ethernet header dep, else nft fetches the payload from
header offset 0 instead of 14.

Reported-by: Yi Chen <yiche@redhat.com>
Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agodoc: mention vlan matching in ip/ip6/inet families
Florian Westphal [Tue, 27 Sep 2022 10:28:21 +0000 (12:28 +0200)] 
doc: mention vlan matching in ip/ip6/inet families

It only works if vlan_reorder is turned off to disable the vlan tag
removal.

Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agoevaluate: allow implicit ether -> vlan dep
Florian Westphal [Thu, 11 Aug 2022 07:10:55 +0000 (09:10 +0200)] 
evaluate: allow implicit ether -> vlan dep

nft add rule inet filter input vlan id 2
Error: conflicting protocols specified: ether vs. vlan

Refresh the current dependency after superseding the dummy
dependency to make this work.

Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agodoc, src: make some spelling and grammatical improvements
Jeremy Sowden [Thu, 22 Sep 2022 08:00:42 +0000 (09:00 +0100)] 
doc, src: make some spelling and grammatical improvements

Fix a couple of spelling mistakes:

  'expresion' -> 'expression'

and correct some non-native usages:

  'allows to' -> 'allows one to'

Signed-off-by: Jeremy Sowden <jeremy@azazel.net>
Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agosegtree: fix decomposition of unclosed intervals containing address prefixes
Jeremy Sowden [Sun, 18 Sep 2022 17:22:12 +0000 (18:22 +0100)] 
segtree: fix decomposition of unclosed intervals containing address prefixes

The code which decomposes unclosed intervals doesn't check for prefixes.  This
leads to incorrect output for sets which contain these.  For example,

  # nft -f - <<END
  table ip t {
    chain c {
      ip saddr 192.0.0.0/2 drop
      ip saddr 10.0.0.0/8 drop
      ip saddr { 192.0.0.0/2, 10.0.0.0/8 } drop
    }
  }
  table ip6 t {
    chain c {
      ip6 saddr ff00::/8 drop
      ip6 saddr fe80::/10 drop
      ip6 saddr { ff00::/8, fe80::/10 } drop
    }
  }
  END
  # nft list table ip6 t
  table ip6 t {
    chain c {
      ip6 saddr ff00::/8 drop
      ip6 saddr fe80::/10 drop
      ip6 saddr { fe80::/10, ff00::-ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff } drop
    }
  }
  # nft list table ip t
  table ip t {
    chain c {
      ip saddr 192.0.0.0/2 drop
      ip saddr 10.0.0.0/8 drop
      ip saddr { 10.0.0.0/8, 192.0.0.0-255.255.255.255 } drop
    }
  }

Instead of treating the final unclosed interval as a special case, reuse the
code which correctly handles closed intervals.

Add a shell test-case.

Link: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1018156
Fixes: 86b965bdab8d ("segtree: fix decomposition of unclosed intervals")
Signed-off-by: Jeremy Sowden <jeremy@azazel.net>
Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agosegtree: refactor decomposition of closed intervals
Jeremy Sowden [Sun, 18 Sep 2022 17:22:11 +0000 (18:22 +0100)] 
segtree: refactor decomposition of closed intervals

Move the code in `interval_map_decompose` which adds a new closed
interval to the set into a separate function.  In addition to the moving
of the code, there is one other change: `compound_expr_add` is called
once, after the main conditional, instead of being called in each
branch.

Signed-off-by: Jeremy Sowden <jeremy@azazel.net>
Signed-off-by: Florian Westphal <fw@strlen.de>
2 years agoevaluate: un-break rule insert with intervals
Florian Westphal [Tue, 20 Sep 2022 13:26:07 +0000 (15:26 +0200)] 
evaluate: un-break rule insert with intervals

'rule inet dscpclassify dscp_match  meta l4proto { udp }  th dport { 3478 }  th sport { 3478-3497, 16384-16387 } goto ct_set_ef'
works with 'nft add', but not 'nft insert', the latter yields: "BUG: unhandled op 4".

Fixes: 81e36530fcac ("src: replace interval segment tree overlap and automerge")
Signed-off-by: Florian Westphal <fw@strlen.de>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agodoc: add nft_ctx_add_var() and nft_ctx_clear_vars() docs
Fernando Fernandez Mancera [Mon, 12 Sep 2022 10:52:25 +0000 (12:52 +0200)] 
doc: add nft_ctx_add_var() and nft_ctx_clear_vars() docs

Add missing documentation for nft_ctx_add_var() and nft_ctx_clear_vars()
functions.

Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agopy: support variables management and fix formatting
Fernando Fernandez Mancera [Mon, 12 Sep 2022 10:52:24 +0000 (12:52 +0200)] 
py: support variables management and fix formatting

Add nft_ctx_add_var() and nft_ctx_clear_vars() support through add_var() and
clear_vars(). Also, fix some functions documentation and drop unnecesary
comments.

In addition, modify get_dry_run() to return the previous value set. This is
needed to be consistent with the rest of the python API.

Link: https://bugzilla.netfilter.org/show_bug.cgi?id=1591
Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agopy: extend python API to support libnftables API
Peter Collinson [Mon, 12 Sep 2022 10:52:23 +0000 (12:52 +0200)] 
py: extend python API to support libnftables API

Allows py/nftables.py to support full mapping to the libnftables API. The
changes allow python code to talk in text to the kernel rather than just
using json. The Python API can now also use dry run to test changes.

Link: https://bugzilla.netfilter.org/show_bug.cgi?id=1591
Signed-off-by: Peter Collinson <pc@hillside.co.uk>
Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agojson: add stateful object comment support
Fernando Fernandez Mancera [Sat, 10 Sep 2022 22:11:14 +0000 (00:11 +0200)] 
json: add stateful object comment support

When listing a stateful object with JSON support, the comment was ignored.

Output example:

{
  "counter": {
    "family": "inet",
    "name": "mycounter",
    "table": "t",
    "handle": 1,
    "comment": "my comment in counter",
    "packets": 0,
    "bytes": 0
  }
}

Link: https://bugzilla.netfilter.org/show_bug.cgi?id=1611
Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agojson: add secmark object reference support
Fernando Fernandez Mancera [Sat, 10 Sep 2022 07:59:48 +0000 (09:59 +0200)] 
json: add secmark object reference support

The secmark object reference requires a json parser function and it was
missing. In addition, extends the shell testcases.

Link: https://bugzilla.netfilter.org/show_bug.cgi?id=1630
Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoinclude: resync nf_tables.h cache copy
Pablo Neira Ayuso [Wed, 14 Sep 2022 14:48:12 +0000 (16:48 +0200)] 
include: resync nf_tables.h cache copy

Get this header in sync with nf-next as of 6.0-rc.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agojson: fix empty statement list output in sets and maps
Fernando Fernandez Mancera [Sun, 4 Sep 2022 17:18:26 +0000 (19:18 +0200)] 
json: fix empty statement list output in sets and maps

JSON output of sets and map should not include the statements list if is
empty. The statement output should be stateless also.

In addition, removes duplicated code.

Fixes: 07958ec53830 ("json: add set statement list support")
Fixes: e66f3187d891 ("json: add table map statement support")
Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agojson: fix json schema version verification
Fernando Fernandez Mancera [Fri, 2 Sep 2022 13:35:06 +0000 (15:35 +0200)] 
json: fix json schema version verification

nft should ignore malformed or missing entries of `json_schema_version` but
check the value when it is integer.

Link: https://bugzilla.netfilter.org/show_bug.cgi?id=1490
Fixes: 49e0f1dc6e52 ("JSON: Add metainfo object to all output")
Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agojson: add table map statement support
Fernando Fernandez Mancera [Fri, 2 Sep 2022 10:52:04 +0000 (12:52 +0200)] 
json: add table map statement support

When listing a map with statements with JSON support, the statement list were
ignored.

Output example:

{
  "map": {
    "family": "ip",
    "name": "m",
    "table": "t",
    "type": "ipv4_addr",
    "handle": 1,
    "map": "mark",
    "stmt": [
      {
        "counter": {
          "packets": 0,
          "bytes": 0
        }
      }
    ]
  }
}

Link: https://bugzilla.netfilter.org/show_bug.cgi?id=1588
Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agorule: check address family in set collapse
Derek Hageman [Thu, 1 Sep 2022 16:10:41 +0000 (10:10 -0600)] 
rule: check address family in set collapse

498a5f0c219d added collapsing of set operations in different commands.
However, the logic is currently too relaxed.  It is valid to have a
table and set with identical names on different address families.
For example:

  table ip a {
    set x {
      type inet_service;
    }
  }
  table ip6 a {
      set x {
        type inet_service;
      }
  }
  add element ip a x { 1 }
  add element ip a x { 2 }
  add element ip6 a x { 2 }

The above currently results in nothing being added to the ip6 family
table due to being collapsed into the ip table add. Prior to
498a5f0c219d the set add would work. The fix is simply to check the
family in addition to the table and set names before allowing a
collapse.

[ Add testcase to tests/shell --pablo ]

Fixes: 498a5f0c219d ("rule: collapse set element commands")
Signed-off-by: Derek Hageman <hageman@inthat.cloud>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agojson: add set statement list support
Fernando Fernandez Mancera [Thu, 1 Sep 2022 10:31:43 +0000 (12:31 +0200)] 
json: add set statement list support

When listing a set with statements with JSON support, the statements were
ignored.

Output example:

{
  "set": {
    "op": "add",
    "elem": {
      "payload": {
        "protocol": "ip",
        "field": "saddr"
      }
    },
    "stmt": [
      {
        "limit": {
          "rate": 10,
          "burst": 5,
          "per": "second"
        }
      },
      {
        "counter": {
          "packets": 0,
          "bytes": 0
        }
      }
    ],
    "set": "@my_ssh_meter"
  }
}

Link: https://bugzilla.netfilter.org/show_bug.cgi?id=1495
Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agotests/py: missing userdata in netlink payload
Pablo Neira Ayuso [Wed, 31 Aug 2022 14:56:04 +0000 (16:56 +0200)] 
tests/py: missing userdata in netlink payload

Since libnftnl's 212479ad2c92 ("rule, set_elem: fix printing of user
data"), userdata is missing in netlink payload printing via --debug.
Update tests/py/ip6/srh.t.payload to silence warning.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agosrc: allow burst 0 for byte ratelimit and use it as default
Pablo Neira Ayuso [Tue, 30 Aug 2022 14:51:35 +0000 (16:51 +0200)] 
src: allow burst 0 for byte ratelimit and use it as default

Packet-based limit burst is set to 5, as in iptables. However,
byte-based limit burst adds to the rate to calculate the bucket size,
and this is also sets this to 5 (... bytes in this case). Update it to
use zero byte burst by default instead.

This patch also updates manpage to describe how the burst value
influences the kernel module's token bucket in each of the two modes.
This documentation update is based on original text by Phil Sutter.

Adjust tests/py to silence warnings due to mismatching byte burst.

Fixes: 285baccfea46 ("src: disallow burst 0 in ratelimits")
Acked-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
2 years agoexpr: update EXPR_MAX and add missing comments
Florian Westphal [Tue, 23 Aug 2022 10:51:52 +0000 (12:51 +0200)] 
expr: update EXPR_MAX and add missing comments

WHen flagcmp and catchall expressions got added the EXPR_MAX definition
wasn't changed.

Should have no impact in practice however, this value is only checked to
prevent crash when old nft release is used to list a ruleset generated
by a newer nft release and a unknown 'typeof' expression.

v2: Pablo suggested to add EXPR_MAX into enum so its easier to spot.
Adding __EXPR_MAX + define EXPR_MAX (__EXPR_MAX - 1) causes '__EXPR_MAX
not handled in switch' warnings, hence the 'EXPR_MAX =' solution.

Signed-off-by: Florian Westphal <fw@strlen.de>