]> git.ipfire.org Git - thirdparty/nftables.git/log
thirdparty/nftables.git
5 years agosrc: allow variables in the chain priority specification
Fernando Fernandez Mancera [Fri, 2 Aug 2019 10:12:08 +0000 (12:12 +0200)] 
src: allow variables in the chain priority specification

This patch allows you to use variables in chain priority definitions,
e.g.

define prio = filter
define prionum = 10
define prioffset = "filter - 150"

add table ip foo
add chain ip foo bar { type filter hook input priority $prio; }
add chain ip foo ber { type filter hook input priority $prionum; }
add chain ip foo bor { type filter hook input priority $prioffset; }

Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
5 years agosrc: remove global symbol_table
Pablo Neira Ayuso [Wed, 7 Aug 2019 22:30:28 +0000 (00:30 +0200)] 
src: remove global symbol_table

Store symbol tables in context object instead. Use the nft_ctx object to
store the dynamic symbol table. Pass it on to the parse_ctx object so
this can be accessed from the parse routines. This dynamic symbol table
is also accesible from the output_ctx object for print routines.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
5 years agosrc: add parse_ctx object
Pablo Neira Ayuso [Wed, 7 Aug 2019 21:51:18 +0000 (23:51 +0200)] 
src: add parse_ctx object

This object stores the dynamic symbol tables that are loaded from files.
Pass this object to datatype parse functions, although this new
parameter is not used yet, this is just a preparation patch.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agocache: incorrect flush flag for table/chain
Laura Garcia Liebana [Wed, 31 Jul 2019 11:27:46 +0000 (13:27 +0200)] 
cache: incorrect flush flag for table/chain

After the new cache system, nft raises a table error flushing a chain in
a transaction.

 # nft "flush chain ip nftlb filter-newfarm ; \
    add rule ip nftlb filter-newfarm update \
    @persist-newfarm {  ip saddr : ct mark } ; \
    flush chain ip nftlb nat-newfarm"
 Error: No such file or directory
 flush chain ip nftlb filter-newfarm ; add rule ip nftlb (...)
                                                   ^^^^^

This patch sets the cache flag properly to save this case.

Fixes: 01e5c6f0ed031 ("src: add cache level flags")
Signed-off-by: Laura Garcia Liebana <nevola@gmail.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: Fix dumping vlan rules
M. Braun [Mon, 15 Jul 2019 16:59:01 +0000 (18:59 +0200)] 
src: Fix dumping vlan rules

Given the following bridge rules:
1. ip protocol icmp accept
2. ether type vlan vlan type ip ip protocol icmp accept

The are currently both dumped by "nft list ruleset" as
1. ip protocol icmp accept
2. ip protocol icmp accept

Though, the netlink code actually is different

bridge filter FORWARD 4
  [ payload load 2b @ link header + 12 => reg 1 ]
  [ cmp eq reg 1 0x00000008 ]
  [ payload load 1b @ network header + 9 => reg 1 ]
  [ cmp eq reg 1 0x00000001 ]
  [ immediate reg 0 accept ]

bridge filter FORWARD 5 4
  [ payload load 2b @ link header + 12 => reg 1 ]
  [ cmp eq reg 1 0x00000081 ]
  [ payload load 2b @ link header + 16 => reg 1 ]
  [ cmp eq reg 1 0x00000008 ]
  [ payload load 1b @ network header + 9 => reg 1 ]
  [ cmp eq reg 1 0x00000001 ]
  [ immediate reg 0 accept ]

What happens here is that:

1. vlan type ip kills ether type vlan
2. ip protocol icmp kills vlan type ip

Fix this by avoiding the removal of all vlan statements
in the given example.

Signed-off-by: Michael Braun <michael-dev@fami-braun.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: Call bison with -Wno-yacc to silence warnings
Phil Sutter [Tue, 23 Jul 2019 12:30:39 +0000 (14:30 +0200)] 
src: Call bison with -Wno-yacc to silence warnings

Bison-3.3 significantly increased warnings for POSIX incompatibilities,
it now complains about missing support for %name-prefix, %define,
%destructor and string literals. The latter applies to parameter of
%name-prefix and all relevant %token statements.

Signed-off-by: Phil Sutter <phil@nwl.cc>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoparser_bison: Fix for deprecated statements
Phil Sutter [Tue, 23 Jul 2019 09:53:39 +0000 (11:53 +0200)] 
parser_bison: Fix for deprecated statements

Bison-3.3 started to warn about:

/home/n0-1/git/nftables/src/parser_bison.y:117.1-19: warning: deprecated directive, use ‘%define api.prefix {nft_}’ [-Wdeprecated]
    117 | %name-prefix "nft_"
        | ^~~~~~~~~~~~~~~~~~~
/home/n0-1/git/nftables/src/parser_bison.y:119.1-12: warning: deprecated directive, use ‘%define api.pure’ [-Wdeprecated]
  119 | %pure-parser
      | ^~~~~~~~~~~~
/home/n0-1/git/nftables/src/parser_bison.y:124.1-14: warning: deprecated directive, use ‘%define parse.error verbose’ [-Wdeprecated]
  124 | %error-verbose
      | ^~~~~~~~~~~~~~

Replace the last two as suggested but leave the first one in place as
that causes compilation errors in scanner.l - flex seems not to pick up
the changed internal symbol names.

Signed-off-by: Phil Sutter <phil@nwl.cc>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoscanner: don't rely on fseek for input stream repositioning
Florian Westphal [Sun, 21 Jul 2019 10:18:31 +0000 (12:18 +0200)] 
scanner: don't rely on fseek for input stream repositioning

It doesn't work when reading from a pipe, leading to parser
errors in case of 'cat foo | nft -f -', whereas 'nft -f < foo'
works fine.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1354
Signed-off-by: Florian Westphal <fw@strlen.de>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agodoc: fib: explain example in more detail
Florian Westphal [Sun, 21 Jul 2019 10:43:05 +0000 (12:43 +0200)] 
doc: fib: explain example in more detail

As noted by Felix Dreissig, fib documentation is quite terse, so explain
the 'saddr . iif' example with a few more words.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1220
Signed-off-by: Florian Westphal <fw@strlen.de>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: Sync comments with current expr definition
Brett Mastbergen [Tue, 23 Jul 2019 17:36:49 +0000 (13:36 -0400)] 
src: Sync comments with current expr definition

ops has been removed, and etype has been added

Signed-off-by: Brett Mastbergen <bmastbergen@untangle.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests: shell: check for table re-definition usecase
Florian Westphal [Sun, 21 Jul 2019 00:14:07 +0000 (02:14 +0200)] 
tests: shell: check for table re-definition usecase

Make sure nft behaves like 0.9.0 -- the ruleset

flush ruleset
table inet filter {
}
table inet filter {
      chain test {
        counter
    }
}

loads again without crashing/generating an error message.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1351
Fixes: e5382c0d08e3c ("src: Support intra-transaction rule references")
Signed-off-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agocache: add NFT_CACHE_UPDATE and NFT_CACHE_FLUSHED flags
Pablo Neira Ayuso [Tue, 23 Jul 2019 13:03:23 +0000 (15:03 +0200)] 
cache: add NFT_CACHE_UPDATE and NFT_CACHE_FLUSHED flags

NFT_CACHE_FLUSHED tells cache_update() to skip the netlink dump to
populate the cache, since the existing ruleset is going to flushed by
this batch.

NFT_CACHE_UPDATE tells rule_evaluate() to perform incremental updates to
the cache based on the existing batch, this is required by the rule
commands that use the index and the position selectors.

This patch removes cache_flush() which is not required anymore. This
cache removal is coming too late, in the evaluation phase, after the
initial cache_update() invocation.

Be careful with NFT_CACHE_UPDATE, this flag needs to be left in place if
NFT_CACHE_FLUSHED is set on.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agorule: removed duplicate member initializer.
Jeremy Sowden [Fri, 19 Jul 2019 11:10:10 +0000 (12:10 +0100)] 
rule: removed duplicate member initializer.

Initialization of a netlink_ctx included two initializers for .nft.
Removed one of them.

Fixes: 2dc07bcd7eaa ("src: pass struct nft_ctx through struct netlink_ctx")
Signed-off-by: Jeremy Sowden <jeremy@azazel.net>
Acked-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agolibnftables: get rid of repeated initialization of netlink_ctx
Jeremy Sowden [Fri, 19 Jul 2019 11:10:09 +0000 (12:10 +0100)] 
libnftables: get rid of repeated initialization of netlink_ctx

Most members in the context don't change, so there is no need to memset
it and reassign them on every iteration.  Moved that code out of the
loop.

Fixes: a72315d2bad4 ("src: add rule batching support")
Reported-by: Pablo Neira Ayuso <pablo@netfilter.org>
Signed-off-by: Jeremy Sowden <jeremy@azazel.net>
Acked-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: osf: fix snprintf -Wformat-truncation warning
Fernando Fernandez Mancera [Mon, 22 Jul 2019 16:34:08 +0000 (18:34 +0200)] 
src: osf: fix snprintf -Wformat-truncation warning

Fedora 30 uses very recent gcc (version 9.1.1 20190503 (Red Hat 9.1.1-1)),
osf produces following warnings:

-Wformat-truncation warning have been introduced in the version 7.1 of gcc.
Also, remove a unneeded address check of "tmp + 1" in nf_osf_strchr().

nfnl_osf.c: In function ‘nfnl_osf_load_fingerprints’:
nfnl_osf.c:292:39: warning: ‘%s’ directive output may be truncated writing
up to 1023 bytes into a region of size 128 [-Wformat-truncation=]
  292 |   cnt = snprintf(obuf, sizeof(obuf), "%s,", pbeg);
      |                                       ^~
nfnl_osf.c:292:9: note: ‘snprintf’ output between 2 and 1025 bytes into a
destination of size 128
  292 |   cnt = snprintf(obuf, sizeof(obuf), "%s,", pbeg);
      |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
nfnl_osf.c:302:46: warning: ‘%s’ directive output may be truncated writing
up to 1023 bytes into a region of size 32 [-Wformat-truncation=]
  302 |    cnt = snprintf(f.genre, sizeof(f.genre), "%s", pbeg);
      |                                              ^~
nfnl_osf.c:302:10: note: ‘snprintf’ output between 1 and 1024 bytes into a
destination of size 32
  302 |    cnt = snprintf(f.genre, sizeof(f.genre), "%s", pbeg);
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
nfnl_osf.c:309:49: warning: ‘%s’ directive output may be truncated writing
up to 1023 bytes into a region of size 32 [-Wformat-truncation=]
  309 |   cnt = snprintf(f.version, sizeof(f.version), "%s", pbeg);
      |                                                 ^~
nfnl_osf.c:309:9: note: ‘snprintf’ output between 1 and 1024 bytes into a
destination of size 32
  309 |   cnt = snprintf(f.version, sizeof(f.version), "%s", pbeg);
      |         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
nfnl_osf.c:317:47: warning: ‘%s’ directive output may be truncated writing
up to 1023 bytes into a region of size 32 [-Wformat-truncation=]
  317 |       snprintf(f.subtype, sizeof(f.subtype), "%s", pbeg);
      |                                               ^~
nfnl_osf.c:317:7: note: ‘snprintf’ output between 1 and 1024 bytes into a
destination of size 32
  317 |       snprintf(f.subtype, sizeof(f.subtype), "%s", pbeg);
      |       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Reported-by: Florian Westphal <fw@strlen.de>
Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Florian Westphal <fw@strlen.de>
6 years agoevaluate: missing location for chain nested in table definition
Pablo Neira Ayuso [Mon, 22 Jul 2019 11:55:22 +0000 (13:55 +0200)] 
evaluate: missing location for chain nested in table definition

error reporting may crash because location is unset.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: evaluate: support prefix expression in statements
Florian Westphal [Mon, 22 Jul 2019 09:37:40 +0000 (11:37 +0200)] 
src: evaluate: support prefix expression in statements

Currently nft dumps core when it encounters a prefix expression as
part of a statement, e.g.
iifname ens3 snat to 10.0.0.0/28

yields:
BUG: unknown expression type prefix
nft: netlink_linearize.c:688: netlink_gen_expr: Assertion `0' failed.

This assertion is correct -- we can't linearize a prefix because
kernel doesn't know what that is.

For LHS prefixes, they get converted to a binary 'and' such as
'10.0.0.0 & 255.255.255.240'.  For RHS, we can do something similar
and convert them into a range.

snat to 10.0.0.0/28 will be converted into:
iifname "ens3" snat to 10.0.0.0-10.0.0.15

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1187
Signed-off-by: Florian Westphal <fw@strlen.de>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agodoc: fib: explain example in more detail
Florian Westphal [Sun, 21 Jul 2019 10:43:05 +0000 (12:43 +0200)] 
doc: fib: explain example in more detail

As noted by Felix Dreissig, fib documentation is quite terse, so explain
the 'saddr . iif' example with a few more words.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1220
Signed-off-by: Florian Westphal <fw@strlen.de>
6 years agoevaluate: bogus error when refering to existing non-base chain
Pablo Neira Ayuso [Tue, 16 Jul 2019 17:49:42 +0000 (19:49 +0200)] 
evaluate: bogus error when refering to existing non-base chain

 add rule ip testNEW test6 jump test8
                                ^^^^^
 Error: invalid verdict chain expression value

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agojson: Fix memleak in timeout_policy_json()
Phil Sutter [Thu, 18 Jul 2019 15:16:56 +0000 (17:16 +0200)] 
json: Fix memleak in timeout_policy_json()

Use the correct function when populating policy property value,
otherwise the temporary objects' refcounts are incremented.

Fixes: c82a26ebf7e9f ("json: Add ct timeout support")
Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoinclude: json: add missing synproxy stmt print stub
Fernando Fernandez Mancera [Thu, 18 Jul 2019 09:41:14 +0000 (11:41 +0200)] 
include: json: add missing synproxy stmt print stub

statement.c:930:11: error: ‘synproxy_stmt_json’ undeclared here (not in a function); did you mean ‘tproxy_stmt_json’?
  .json  = synproxy_stmt_json,
           ^~~~~~~~~~~~~~~~~~
           tproxy_stmt_json

Fixes: 1188a69604c3 ("src: introduce SYNPROXY matching")
Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests: py: add missing json outputs
Fernando Fernandez Mancera [Wed, 17 Jul 2019 10:46:46 +0000 (12:46 +0200)] 
tests: py: add missing json outputs

Fixes: 1188a69604c3 ("src: introduce SYNPROXY matching")
Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agojson: fix synproxy flag parser typo
Fernando Fernandez Mancera [Wed, 17 Jul 2019 10:46:45 +0000 (12:46 +0200)] 
json: fix synproxy flag parser typo

Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: introduce SYNPROXY matching
Fernando Fernandez Mancera [Sat, 22 Jun 2019 17:12:08 +0000 (19:12 +0200)] 
src: introduce SYNPROXY matching

Add support for "synproxy" statement. For example (for TCP port 8888):

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

chain z {
type filter hook input priority filter; policy accept;
tcp dport 8888 ct state invalid,untracked synproxy mss 1460 wscale 7 timestamp sack-perm
ct state invalid drop
}
}

Signed-off-by: Fernando Fernandez Mancera <ffmancera@riseup.net>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests: fix up two broken json test cases
Florian Westphal [Tue, 16 Jul 2019 19:40:27 +0000 (21:40 +0200)] 
tests: fix up two broken json test cases

Forgot to add a json test case for the recently added ct ip addr in map case.
Fix up rawpayload.t for json, it needs to expect new "th dport" when
listing.

Reported-by: Pablo Neira Ayuso <pablo@netfilter.org>
Signed-off-by: Florian Westphal <fw@strlen.de>
6 years agoevaluate: missing basic evaluation of expectations
Pablo Neira Ayuso [Tue, 16 Jul 2019 19:16:18 +0000 (21:16 +0200)] 
evaluate: missing basic evaluation of expectations

Basic ct expectation object evaluation. This fixes tests/py errors.

Error reporting is very sparse at this stage. I'm intentionally leaving
this as future work to store location objects for each field, so user
gets better indication on what is missing when configuring expectations.

Fixes: 1dd08fcfa07a ("src: add ct expectations support")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: add ct expectations support
Stéphane Veyret [Tue, 9 Jul 2019 13:02:09 +0000 (15:02 +0200)] 
src: add ct expectations support

This modification allow to directly add/list/delete expectations.

Signed-off-by: Stéphane Veyret <sveyret@gmail.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agocache: incorrect flags for create commands
Pablo Neira Ayuso [Tue, 16 Jul 2019 09:48:33 +0000 (11:48 +0200)] 
cache: incorrect flags for create commands

 # nft create table testD
 # nft create chain testD test6
 Error: No such file or directory
 create chain testD test6
              ^^^^^

Handle 'create' command just like 'add' and 'insert'. Check for object
types to dump the tables for more fine grain listing, instead of dumping
the whole ruleset.

Fixes: 7df42800cf89 ("src: single cache_update() call to build cache before evaluation")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoevaluate: honor NFT_SET_OBJECT flag
Pablo Neira Ayuso [Thu, 11 Jul 2019 13:50:13 +0000 (15:50 +0200)] 
evaluate: honor NFT_SET_OBJECT flag

This is noticeable when displaying mispelling errors, however, there are
also few spots not checking for the object map flag.

Before:

 # nft flush set inet filter countermxx
 Error: No such file or directory; did you mean set ‘countermap’ in table inet ‘filter’?
 flush set inet filter countermxx
                       ^^^^^^^^^^
After:

 # nft flush set inet filter countermxx
 Error: No such file or directory; did you mean map ‘countermap’ in table inet ‘filter’?
 flush set inet filter countermxx
                       ^^^^^^^^^^

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: use set_is_anonymous()
Pablo Neira Ayuso [Mon, 15 Jul 2019 17:42:07 +0000 (19:42 +0200)] 
src: use set_is_anonymous()

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoevaluate: missing object maps handling in list and flush commands
Pablo Neira Ayuso [Thu, 11 Jul 2019 13:49:09 +0000 (15:49 +0200)] 
evaluate: missing object maps handling in list and flush commands

NFT_SET_OBJECT tells there is an object map.

 # nft list ruleset
 table inet filter {
        map countermap {
                type ipv4_addr : counter
        }
 }

The following command fails:

 # nft flush set inet filter countermap

This patch checks for NFT_SET_OBJECT from new set_is_literal() and
map_is_literal() functions. This patch also adds tests for this.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: add set_is_datamap(), set_is_objmap() and set_is_map() helpers
Pablo Neira Ayuso [Mon, 15 Jul 2019 06:26:43 +0000 (08:26 +0200)] 
src: add set_is_datamap(), set_is_objmap() and set_is_map() helpers

Two map types are currently possible:

* data maps, ie. set_is_datamap().
* object maps, ie. set_is_objmap().

This patch adds helper functions to check for the map type.

set_is_map() allows you to check for either map type.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests: shell: make sure we test nft binary from working tree, not host
Florian Westphal [Mon, 15 Jul 2019 10:29:48 +0000 (12:29 +0200)] 
tests: shell: make sure we test nft binary from working tree, not host

This tests the installed host nft binary, which fails on my test vm.
Using the one from the working tree makes this test pass.

Signed-off-by: Florian Westphal <fw@strlen.de>
6 years agoproto: add pseudo th protocol to match d/sport in generic way
Florian Westphal [Sat, 13 Jul 2019 17:23:27 +0000 (19:23 +0200)] 
proto: add pseudo th protocol to match d/sport in generic way

Problem: Its not possible to easily match both udp and tcp in a single
rule.

... input ip protocol { tcp,udp } dport 53

will not work, as bison expects "tcp dport" or "sctp dport", or any
other transport protocol name.

Its possible to match the sport and dport via raw payload expressions,
e.g.:
... input ip protocol { tcp,udp } @th,16,16 53

but its not very readable.
Furthermore, its not possible to use this for set definitions:

table inet filter {
        set myset {
                type ipv4_addr . inet_proto . inet_service
        }

        chain forward {
                type filter hook forward priority filter; policy accept;
                ip daddr . ip protocol . @th,0,16 @myset
        }
}
 # nft -f test
 test:7:26-35: Error: can not use variable sized data types (integer) in concat expressions

During the netfilter workshop Pablo suggested to add an alias to do raw
sport/dport matching more readable, and make it use the inet_service
type automatically.

So, this change makes @th,0,16 work for the set definition case by
setting the data type to inet_service.

A new "th s|dport" syntax is provided as readable alternative:

ip protocol { tcp, udp } th dport 53

As "th" is an alias for the raw expression, no dependency is
generated -- its the users responsibility to add a suitable test to
select the l4 header types that should be matched.

Suggested-by: Pablo Neira Ayuso <pablo@netfilter.org>
Signed-off-by: Florian Westphal <fw@strlen.de>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc/ct: provide fixed data lengh sizes for ip/ip6 keys
Florian Westphal [Fri, 12 Jul 2019 10:29:31 +0000 (12:29 +0200)] 
src/ct: provide fixed data lengh sizes for ip/ip6 keys

nft can load but not list this:

table inet filter {
 chain input {
  ct original ip daddr {1.2.3.4} accept
 }
}

Problem is that the ct template length is 0, so we believe the right hand
side is a concatenation because left->len < set->key->len is true.
nft then calls abort() during concatenation parsing.

Closes: https://bugzilla.netfilter.org/show_bug.cgi?id=1222
Signed-off-by: Florian Westphal <fw@strlen.de>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agocli: remove useless #include headers
Pablo Neira Ayuso [Thu, 4 Jul 2019 22:45:42 +0000 (00:45 +0200)] 
cli: remove useless #include headers

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agomain: replace NFT_EXIT_NOMEM by EXIT_FAILURE
Pablo Neira Ayuso [Thu, 4 Jul 2019 22:39:17 +0000 (00:39 +0200)] 
main: replace NFT_EXIT_NOMEM by EXIT_FAILURE

The main.c file always uses either EXIT_FAILURE or EXIT_SUCCESS, replace
this.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: use malloc() and free() from cli and main
Pablo Neira Ayuso [Thu, 4 Jul 2019 12:38:37 +0000 (14:38 +0200)] 
src: use malloc() and free() from cli and main

xmalloc() and xfree() are internal symbols of the library, do not use
them.

Fixes: 16543a0136c0 ("libnftables: export public symbols only")
Reported-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoipopt: missing ipopt.h and ipopt.c files
Pablo Neira Ayuso [Thu, 4 Jul 2019 18:01:02 +0000 (20:01 +0200)] 
ipopt: missing ipopt.h and ipopt.c files

Fixes: 226a0e072d5c ("exthdr: add support for matching IPv4 options")
Reported-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agofiles: Add inet family nat config
Phil Sutter [Thu, 4 Jul 2019 10:22:45 +0000 (12:22 +0200)] 
files: Add inet family nat config

Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoexthdr: add support for matching IPv4 options
Stephen Suryaputra [Thu, 4 Jul 2019 00:30:52 +0000 (20:30 -0400)] 
exthdr: add support for matching IPv4 options

Add capability to have rules matching IPv4 options. This is developed
mainly to support dropping of IP packets with loose and/or strict source
route route options.

Signed-off-by: Stephen Suryaputra <ssuryaextr@gmail.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests: shell: update test to include reset command
Pablo Neira Ayuso [Wed, 3 Jul 2019 11:11:52 +0000 (13:11 +0200)] 
tests: shell: update test to include reset command

Update tests to invoke the reset command.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agomnl: remove unnecessary NLM_F_ACK flags
Pablo Neira Ayuso [Tue, 2 Jul 2019 17:03:40 +0000 (19:03 +0200)] 
mnl: remove unnecessary NLM_F_ACK flags

On error, the kernel already sends to userspace an acknowledgement for
the table and chain deletion case.

In case of NLM_F_DUMP, the NLM_F_ACK is not required as the kernel
always sends a NLMSG_DONE at the end of the dumping, even if the list of
objects is empty.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agofiles: Move netdev-ingress.nft to /etc/nftables as well
Phil Sutter [Mon, 24 Jun 2019 15:12:38 +0000 (17:12 +0200)] 
files: Move netdev-ingress.nft to /etc/nftables as well

Commit 13535a3b40b62 ("files: restore base table skeletons") moved
config skeletons back from examples/ to /etc/nftables/ directory, but
ignored the fact that commit 6c9230e79339c ("nftables: rearrange files
and examples") added a new file 'netdev-ingress.nft' which is referenced
from 'all-in-one.nft' as well.

Fixes: 13535a3b40b62 ("files: restore base table skeletons")
Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests: py: fix python3
Shekhar Sharma [Fri, 28 Jun 2019 20:02:29 +0000 (01:32 +0530)] 
tests: py: fix python3

This converts the nft-test.py file to run on both py2 and py3.

Signed-off-by: Shekhar Sharma <shekhar250198@gmail.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agolibnftables: export public symbols only
Arturo Borrero Gonzalez [Mon, 1 Jul 2019 10:53:28 +0000 (12:53 +0200)] 
libnftables: export public symbols only

Export public symbols (the library API functions) instead of all symbols in
the library.

This patch introduces the required macros to manage the visibility attributes
(mostly copied from libnftnl.git) and also marks each symbol as exported when
they need to be public. Also, introduce a .map file for proper symbol
versioning.

Previous to this patch, libnftables public symbols were:

% dpkg-gensymbols -q -plibnftables -v0.9.1 -O -esrc/.libs/libnftables.so.1 | wc -l
527

With this patch, libnftables symbols are:

% dpkg-gensymbols -q -plibnftables -v0.9.1 -O -esrc/.libs/libnftables.so.1
libnftables.so.1 libnftables #MINVER#
 nft_ctx_add_include_path@Base 0.9.1
 nft_ctx_buffer_error@Base 0.9.1
 nft_ctx_buffer_output@Base 0.9.1
 nft_ctx_clear_include_paths@Base 0.9.1
 nft_ctx_free@Base 0.9.1
 nft_ctx_get_dry_run@Base 0.9.1
 nft_ctx_get_error_buffer@Base 0.9.1
 nft_ctx_get_output_buffer@Base 0.9.1
 nft_ctx_new@Base 0.9.1
 nft_ctx_output_get_debug@Base 0.9.1
 nft_ctx_output_get_flags@Base 0.9.1
 nft_ctx_output_set_debug@Base 0.9.1
 nft_ctx_output_set_flags@Base 0.9.1
 nft_ctx_set_dry_run@Base 0.9.1
 nft_ctx_set_error@Base 0.9.1
 nft_ctx_set_output@Base 0.9.1
 nft_ctx_unbuffer_error@Base 0.9.1
 nft_ctx_unbuffer_output@Base 0.9.1
 nft_run_cmd_from_buffer@Base 0.9.1
 nft_run_cmd_from_filename@Base 0.9.1

Signed-off-by: Arturo Borrero Gonzalez <arturo@netfilter.org>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agolibnftables: reallocate definition of nft_print() and nft_gmp_print()
Arturo Borrero Gonzalez [Mon, 1 Jul 2019 10:53:10 +0000 (12:53 +0200)] 
libnftables: reallocate definition of nft_print() and nft_gmp_print()

They are not part of the libnftables library API, they are not public symbols,
so it doesn't not make sense to have them there. Move the two functions to a
different source file so libnftables.c only has the API functions.

I think copyright belongs to Phil Sutter since he introduced this code back in
commit 2535ba7006f22a6470f4c88ea7d30c343a1d8799 (src: get rid of printf).

Signed-off-by: Arturo Borrero Gonzalez <arturo@netfilter.org>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agonft: don't use xzalloc()
Arturo Borrero Gonzalez [Mon, 1 Jul 2019 10:52:48 +0000 (12:52 +0200)] 
nft: don't use xzalloc()

In the current setup, nft (the frontend object) is using the xzalloc() function
from libnftables, which does not makes sense, as this is typically an internal
helper function.

In order to don't use this public libnftables symbol (a later patch just
removes it), let's use calloc() directly in the nft frontend.

Signed-off-by: Arturo Borrero Gonzalez <arturo@netfilter.org>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agorule: print space between policy and timeout
Pablo Neira Ayuso [Mon, 1 Jul 2019 17:56:08 +0000 (19:56 +0200)] 
rule: print space between policy and timeout

 table ip filter {
        ct timeout agressive-tcp {
...
                policy = { established : 100, close_wait : 4, close : 4 }
                                      ^ ^               ^ ^        ^ ^

for consistency with map syntax.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agorule: do not print semicolon in ct timeout
Pablo Neira Ayuso [Mon, 1 Jul 2019 17:54:00 +0000 (19:54 +0200)] 
rule: do not print semicolon in ct timeout

table ip filter {
        ct timeout agressive-tcp {
                protocol tcp;
                            ^--- remove this semicolon

Not needed, remove it.

Fixes: c7c94802679c ("src: add ct timeout support")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoparser_bison: do not enforce semicolon from ct helper block
Pablo Neira Ayuso [Mon, 1 Jul 2019 17:49:06 +0000 (19:49 +0200)] 
parser_bison: do not enforce semicolon from ct helper block

Use the statement separator rule, since newline is also valid.

Fixes: c7c94802679c ("src: add ct timeout support")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests: shell: restore element expiration
Pablo Neira Ayuso [Mon, 1 Jul 2019 16:34:42 +0000 (18:34 +0200)] 
tests: shell: restore element expiration

This patch adds a test for 24f33c710e8c ("src: enable set expiration
date for set elements").

This is also implicitly testing for a cache corruption bug that is fixed
by 9b032cd6477b ("monitor: fix double cache update with --echo").

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agomonitor: fix double cache update with --echo
Pablo Neira Ayuso [Mon, 1 Jul 2019 16:10:30 +0000 (18:10 +0200)] 
monitor: fix double cache update with --echo

The evaluation step already updates the cache for each command in this
batch. There is no need to update the cache again from the echo path,
otherwise the cache is populated twice with the same object.

Fixes: b99c4d072d99 ("Implement --echo option")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: enable set expiration date for set elements
Laura Garcia Liebana [Mon, 17 Jun 2019 16:15:41 +0000 (18:15 +0200)] 
src: enable set expiration date for set elements

Currently, the expiration of every element in a set or map
is a read-only parameter generated at kernel side.

This change will permit to set a certain expiration date
per element that will be required, for example, during
stateful replication among several nodes.

This patch will enable the _expires_ input parameter in
the parser and propagate NFTNL_SET_ELEM_EXPIRATION in
order to send the configured value.

Signed-off-by: Laura Garcia Liebana <nevola@gmail.com>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agobuild: avoid unnecessary call to xargs
Jan Engelhardt [Tue, 25 Jun 2019 06:58:35 +0000 (08:58 +0200)] 
build: avoid unnecessary call to xargs

Signed-off-by: Jan Engelhardt <jengelh@inai.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agobuild: avoid recursion into py/ if not selected
Jan Engelhardt [Tue, 25 Jun 2019 06:58:34 +0000 (08:58 +0200)] 
build: avoid recursion into py/ if not selected

Signed-off-by: Jan Engelhardt <jengelh@inai.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agobuild: unbreak non-functionality of --disable-python
Jan Engelhardt [Tue, 25 Jun 2019 06:58:33 +0000 (08:58 +0200)] 
build: unbreak non-functionality of --disable-python

Signed-off-by: Jan Engelhardt <jengelh@inai.de>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agomain: Bail if non-available JSON was requested
Phil Sutter [Mon, 24 Jun 2019 17:10:38 +0000 (19:10 +0200)] 
main: Bail if non-available JSON was requested

If user passes '-j' flag, falling back to standard syntax output
probably causes more harm than good so instead print an error message
and exit(1).

Suggested-by: Pablo Neira Ayuso <pablo@netfilter.org>
Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agojson: Print newline at end of list output
Phil Sutter [Mon, 24 Jun 2019 17:10:37 +0000 (19:10 +0200)] 
json: Print newline at end of list output

If listing ruleset elements with '-j' flag, print a final newline to not
upset shell prompts.

Suggested-by: Pablo Neira Ayuso <pablo@netfilter.org>
Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agobuild: Bump version to v0.9.1 v0.9.1
Pablo Neira Ayuso [Mon, 24 Jun 2019 10:14:22 +0000 (12:14 +0200)] 
build: Bump version to v0.9.1

Update dependency on libnftnl.

Update release name too: https://www.youtube.com/watch?v=CTV1To1e5w8

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoct: support for NFT_CT_{SRC,DST}_{IP,IP6}
Pablo Neira Ayuso [Fri, 21 Jun 2019 08:28:37 +0000 (10:28 +0200)] 
ct: support for NFT_CT_{SRC,DST}_{IP,IP6}

These keys are available since kernel >= 4.17.

You can still use NFT_CT_{SRC,DST}, however, you need to specify 'meta
protocol' in first place to provide layer 3 context.

Note that NFT_CT_{SRC,DST} are broken with set, maps and concatenations.
This patch is implicitly fixing these cases.

If your kernel is < 4.17, you can still use address matching via
explicit meta nfproto:

meta nfproto ipv4 ct original saddr 1.2.3.4

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: prefer meta protocol as bridge l3 dependency
Florian Westphal [Tue, 18 Jun 2019 18:43:59 +0000 (20:43 +0200)] 
src: prefer meta protocol as bridge l3 dependency

On families other than 'ip', the rule

ip protocol icmp

needs a dependency on the ip protocol so we do not treat e.g. an ipv6
header as ip.

Bridge currently uses eth_hdr.type for this, but that will cause the
rule above to not match in case the ip packet is within a VLAN tagged
frame -- ether.type will appear as ETH_P_8021Q.

Due to vlan tag stripping, skb->protocol will be ETH_P_IP -- so prefer
to use this instead.

Signed-off-by: Florian Westphal <fw@strlen.de>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: statement: disable reject statement type omission for bridge
Florian Westphal [Tue, 18 Jun 2019 18:43:58 +0000 (20:43 +0200)] 
src: statement: disable reject statement type omission for bridge

add rule bridge test-bridge input reject with icmp type port-unreachable

... will be printed as 'reject', which is fine on ip family, but not on
bridge -- 'with icmp type' adds an ipv4 dependency, but simple reject
does not (it will use icmpx to also reject ipv6 packets with an icmpv6 error).

Add a toggle to supress short-hand versions in this case.

Signed-off-by: Florian Westphal <fw@strlen.de>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agonetlink_delinerize: remove network header dep for reject statement also in bridge...
Florian Westphal [Tue, 18 Jun 2019 18:43:57 +0000 (20:43 +0200)] 
netlink_delinerize: remove network header dep for reject statement also in bridge family

add rule bridge test-bridge input reject with icmp type ...

is shown as

ether type ip reject type ...

i.e., the dependency is not removed.

Allow dependency removal -- this adds a problem where some icmp types
will be shortened to 'reject', losing the icmp ipv4 dependency.

Next patch resolves this problem by disabling short-hand abbreviations
for bridge reject statements.

Signed-off-by: Florian Westphal <fw@strlen.de>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agorule: do not suggest anonymous sets on mispelling errors
Pablo Neira Ayuso [Tue, 18 Jun 2019 16:49:51 +0000 (18:49 +0200)] 
rule: do not suggest anonymous sets on mispelling errors

 # nft list set x __set000
 Error: No such file or directory; did you mean set ‘__set0’ in table ip ‘x’?
 list set x __set000
            ^^^^^^^^

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoevaluate: do not allow to list/flush anonymous sets via list command
Pablo Neira Ayuso [Tue, 18 Jun 2019 14:19:28 +0000 (16:19 +0200)] 
evaluate: do not allow to list/flush anonymous sets via list command

Don't allow this:

 # nft list set x __set0
 table ip x {
        set __set0 {
                type ipv4_addr
                flags constant
                elements = { 1.1.1.1 }
        }
 }

Constant sets never change and they are attached to a rule (anonymous
flag is set on), do not list their content through this command. Do not
allow flush operation either.

After this patch:

 # nft list set x __set0
 Error: No such file or directory
 list set x __set0
            ^^^^^^

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoevaluate: allow get/list/flush dynamic sets and maps via list command
Pablo Neira Ayuso [Tue, 18 Jun 2019 13:08:54 +0000 (15:08 +0200)] 
evaluate: allow get/list/flush dynamic sets and maps via list command

Before:

 # nft list set ip filter untracked_unknown
 Error: No such file or directory; did you mean set ‘untracked_unknown’ in table ip ‘filter’?
 list set ip filter untracked_unknown
                    ^^^^^^^^^^^^^^^^^

After:

 # nft list set ip filter untracked_unknown
 table ip filter {
        set untracked_unknown {
                type ipv4_addr . inet_service . ipv4_addr . inet_service . inet_proto
                size 100000
                flags dynamic,timeout
        }
 }

Add a testcase for this too.

Reported-by: Václav Zindulka <vaclav.zindulka@tlapnet.cz>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests: add missing json arp operation output
Florian Westphal [Tue, 18 Jun 2019 18:13:58 +0000 (20:13 +0200)] 
tests: add missing json arp operation output

Signed-off-by: Florian Westphal <fw@strlen.de>
6 years agosrc: add cache level flags
Pablo Neira Ayuso [Mon, 17 Jun 2019 10:03:08 +0000 (12:03 +0200)] 
src: add cache level flags

The score approach based on command type is confusing.

This patch introduces cache level flags, each flag specifies what kind
of object type is needed. These flags are set on/off depending on the
list of commands coming in this batch.

cache_is_complete() now checks if the cache contains the objects that
are needed through these new flags.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agonetlink: remove netlink_list_table()
Pablo Neira Ayuso [Mon, 17 Jun 2019 12:01:56 +0000 (14:01 +0200)] 
netlink: remove netlink_list_table()

Remove this wrapper, call netlink_list_rules() instead.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agorule: skip cache population from do_command_monitor()
Pablo Neira Ayuso [Mon, 17 Jun 2019 11:54:46 +0000 (13:54 +0200)] 
rule: skip cache population from do_command_monitor()

nft_evaluate() already populates the cache before running the monitor
command. Remove this code.

Fixes: 7df42800cf89 ("src: single cache_update() call to build cache before evaluation")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests: shell: cannot use handle for non-existing rule in kernel
Pablo Neira Ayuso [Mon, 17 Jun 2019 11:28:49 +0000 (13:28 +0200)] 
tests: shell: cannot use handle for non-existing rule in kernel

Do not guess handle for an unexisting rule in the kernel.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: remove useless parameter from cache_flush()
Pablo Neira Ayuso [Mon, 17 Jun 2019 10:22:10 +0000 (12:22 +0200)] 
src: remove useless parameter from cache_flush()

Command type is never used in cache_flush().

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agodatatype: fix print of raw numerical symbol values
Florian Westphal [Mon, 17 Jun 2019 09:55:42 +0000 (11:55 +0200)] 
datatype: fix print of raw numerical symbol values

The two rules:
arp operation 1-2 accept
arp operation 256-512 accept

are both shown as 256-512:

        chain in_public {
                arp operation 256-512 accept
                arp operation 256-512 accept
                meta mark "1"
                tcp flags 2,4
        }

This is because range expression enforces numeric output,
yet nft_print doesn't respect byte order.

Behave as if we had no symbol in the first place and call
the base type print function instead.

This means we now respect format specifier as well:
chain in_public {
                arp operation 1-2 accept
                arp operation 256-512 accept
                meta mark 0x00000001
                tcp flags 0x2,0x4
}

Without fix, added test case will fail:
'add rule arp test-arp input arp operation 1-2': 'arp operation 1-2' mismatches 'arp operation 256-512'

v2: in case of -n, also elide quotation marks, just as if we would not
have found a symbolic name.

Signed-off-by: Florian Westphal <fw@strlen.de>
Acked-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agocache: do not populate the cache in case of flush ruleset command
Pablo Neira Ayuso [Fri, 14 Jun 2019 12:16:59 +0000 (14:16 +0200)] 
cache: do not populate the cache in case of flush ruleset command

__CMD_FLUSH_RULESET is a dummy definition that used to skip the netlink
dump to populate the cache. This patch is a workaround until we have a
better infrastructure to track the state of the cache objects.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoevaluate: double datatype_free() with dynamic integer datatypes
Pablo Neira Ayuso [Fri, 14 Jun 2019 09:55:08 +0000 (11:55 +0200)] 
evaluate: double datatype_free() with dynamic integer datatypes

datatype_set() already deals with this case, remove this.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoevaluate: update byteorder only for implicit maps
Pablo Neira Ayuso [Fri, 14 Jun 2019 09:50:42 +0000 (11:50 +0200)] 
evaluate: update byteorder only for implicit maps

The byteorder adjustment for the integer datatype is only required by
implicit maps.

Fixes: b9b6092304ae ("evaluate: store byteorder for set keys")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoevaluate: use-after-free in meter
Pablo Neira Ayuso [Thu, 13 Jun 2019 15:03:35 +0000 (17:03 +0200)] 
evaluate: use-after-free in meter

Similar to bbe139fdf5a5 ("evaluate: use-after-free in implicit set").

==12727== Invalid read of size 4
==12727==    at 0x72DB515: expr_free (expression.c:86)
==12727==    by 0x72D3092: set_free (rule.c:367)
==12727==    by 0x72DB555: expr_destroy (expression.c:79)
==12727==    by 0x72DB555: expr_free (expression.c:95)
==12727==    by 0x72D7A35: meter_stmt_destroy (statement.c:137)
==12727==    by 0x72D7A07: stmt_free (statement.c:50)
==12727==    by 0x72D7AD7: stmt_list_free (statement.c:60)
==12727==    by 0x72D32EF: rule_free (rule.c:610)
==12727==    by 0x72D3834: chain_free (rule.c:827)
==12727==    by 0x72D45D4: table_free (rule.c:1184)
==12727==    by 0x72D46A7: __cache_flush (rule.c:293)
==12727==    by 0x72D472C: cache_release (rule.c:313)
==12727==    by 0x72D4A79: cache_update (rule.c:264)
==12727==  Address 0x64f14c8 is 56 bytes inside a block of size 128 free'd
==12727==    at 0x4C2CDDB: free (vg_replace_malloc.c:530)
==12727==    by 0x72D7A2C: meter_stmt_destroy (statement.c:136)
==12727==    by 0x72D7A07: stmt_free (statement.c:50)
==12727==    by 0x72D7AD7: stmt_list_free (statement.c:60)
==12727==    by 0x72D32EF: rule_free (rule.c:610)
==12727==    by 0x72D3834: chain_free (rule.c:827)
==12727==    by 0x72D45D4: table_free (rule.c:1184)
==12727==    by 0x72D46A7: __cache_flush (rule.c:293)
==12727==    by 0x72D472C: cache_release (rule.c:313)
==12727==    by 0x72D4A79: cache_update (rule.c:264)
==12727==    by 0x72F82CE: nft_evaluate (libnftables.c:388)
==12727==    by 0x72F8A8B: nft_run_cmd_from_buffer (libnftables.c:428)

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agomonitor: Accept -j flag
Phil Sutter [Wed, 12 Jun 2019 17:27:37 +0000 (19:27 +0200)] 
monitor: Accept -j flag

Make 'nft -j monitor' equal to 'nft monitor json' and change
documentation to use only the first variant since that is more intuitive
and also consistent with other commands.

While being at it, drop references to XML from monitor section - it was
never supported.

Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agonetlink_delinearize: use-after-free in expr_postprocess_string()
Pablo Neira Ayuso [Thu, 13 Jun 2019 09:26:36 +0000 (11:26 +0200)] 
netlink_delinearize: use-after-free in expr_postprocess_string()

escaped_string_wildcard_expr_alloc() may reallocate the expression.
valgrind reports errors like this one:

==29945== Invalid write of size 4
==29945==    at 0x72EE944: __expr_postprocess_string (netlink_delinearize.c:2006)
==29945==    by 0x72EE944: expr_postprocess_string (netlink_delinearize.c:2016)
==29945==    by 0x72EE944: expr_postprocess (netlink_delinearize.c:2120)
==29945==    by 0x72EE5A7: expr_postprocess (netlink_delinearize.c:2094)
==29945==    by 0x72EF23B: stmt_expr_postprocess (netlink_delinearize.c:2289)
==29945==    by 0x72EF23B: rule_parse_postprocess (netlink_delinearize.c:2510)
==29945==    by 0x72EF23B: netlink_delinearize_rule (netlink_delinearize.c:2650)
==29945==    by 0x72E6F63: list_rule_cb (netlink.c:330)
==29945==    by 0x7770BD3: nftnl_rule_list_foreach (rule.c:810)
==29945==    by 0x72E739E: netlink_list_rules (netlink.c:349)
==29945==    by 0x72E739E: netlink_list_table (netlink.c:490)
==29945==    by 0x72D4A89: cache_init_objects (rule.c:194)
==29945==    by 0x72D4A89: cache_init (rule.c:216)
==29945==    by 0x72D4A89: cache_update (rule.c:266)
==29945==    by 0x72F829E: nft_evaluate (libnftables.c:388)
==29945==    by 0x72F8A5B: nft_run_cmd_from_buffer (libnftables.c:428)

Remove expr->len, not needed and it triggers use-after-free errors.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agodatatype: dtype_clone() should clone flags too
Pablo Neira Ayuso [Wed, 12 Jun 2019 11:58:22 +0000 (13:58 +0200)] 
datatype: dtype_clone() should clone flags too

Clone original flags too.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: add reference counter for dynamic datatypes
Pablo Neira Ayuso [Tue, 11 Jun 2019 15:16:50 +0000 (17:16 +0200)] 
src: add reference counter for dynamic datatypes

There are two datatypes are using runtime datatype allocation:

* Concatenations.
* Integer, that require byteorder adjustment.

From the evaluation / postprocess step, transformations are common,
hence expressions may end up fetching (infering) datatypes from an
existing one.

This patch adds a reference counter to release the dynamic datatype
object when it is shared.

The API includes the following helper functions:

* datatype_set(expr, datatype), to assign a datatype to an expression.
  This helper already deals with reference counting for dynamic
  datatypes. This also drops the reference counter of any previous
  datatype (to deal with the datatype replacement case).

* datatype_get(datatype) bumps the reference counter. This function also
  deals with nul-pointers, that occurs when the datatype is unset.

* datatype_free() drops the reference counter, and it also releases the
  datatype if there are not more clients of it.

Rule of thumb is: The reference counter of any newly allocated datatype
is set to zero.

This patch also updates every spot to use datatype_set() for non-dynamic
datatypes, for consistency. In this case, the helper just makes an
simple assignment.

Note that expr_alloc() has been updated to call datatype_get() on the
datatype that is assigned to this new expression. Moreover, expr_free()
calls datatype_free().

This fixes valgrind reports like this one:

==28352== 1,350 (440 direct, 910 indirect) bytes in 5 blocks are definitely lost in loss recor 3 of 3
==28352==    at 0x4C2BBAF: malloc (vg_replace_malloc.c:299)
==28352==    by 0x4E79558: xmalloc (utils.c:36)
==28352==    by 0x4E7963D: xzalloc (utils.c:65)
==28352==    by 0x4E6029B: dtype_alloc (datatype.c:1073)
==28352==    by 0x4E6029B: concat_type_alloc (datatype.c:1127)
==28352==    by 0x4E6D3B3: netlink_delinearize_set (netlink.c:578)
==28352==    by 0x4E6D68E: list_set_cb (netlink.c:648)
==28352==    by 0x5D74023: nftnl_set_list_foreach (set.c:780)
==28352==    by 0x4E6D6F3: netlink_list_sets (netlink.c:669)
==28352==    by 0x4E5A7A3: cache_init_objects (rule.c:159)
==28352==    by 0x4E5A7A3: cache_init (rule.c:216)
==28352==    by 0x4E5A7A3: cache_update (rule.c:266)
==28352==    by 0x4E7E0EE: nft_evaluate (libnftables.c:388)
==28352==    by 0x4E7EADD: nft_run_cmd_from_filename (libnftables.c:479)
==28352==    by 0x109A53: main (main.c:310)

This patch also removes the DTYPE_F_CLONE flag which is broken and not
needed anymore since proper reference counting is in place.

Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoparser_bison: free chain name after creating constant expression
Pablo Neira Ayuso [Mon, 10 Jun 2019 17:23:40 +0000 (19:23 +0200)] 
parser_bison: free chain name after creating constant expression

==2330== 2 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2330==    at 0x4C2BBAF: malloc (vg_replace_malloc.c:299)
==2330==    by 0x583D3B9: strdup (strdup.c:42)
==2330==    by 0x4E7966D: xstrdup (utils.c:75)
==2330==    by 0x4E9C283: nft_lex (scanner.l:626)
==2330==    by 0x4E8E3C2: nft_parse (parser_bison.c:5297)
==2330==    by 0x4E7EAB2: nft_parse_bison_filename (libnftables.c:374)
==2330==    by 0x4E7EAB2: nft_run_cmd_from_filename (libnftables.c:475)
==2330==    by 0x109A53: main (main.c:310)

Fixes: f1e8a129ee42 ("src: Introduce chain_expr in jump and goto statements")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agonetlink_delinearize: release expression before calling netlink_parse_concat_expr()
Pablo Neira Ayuso [Mon, 10 Jun 2019 15:26:41 +0000 (17:26 +0200)] 
netlink_delinearize: release expression before calling netlink_parse_concat_expr()

netlink_get_register() clones the expression in the register. Release
this expression before calling netlink_parse_concat_expr() to
deconstruct the concatenation.

==15069==    at 0x4C2BBAF: malloc (vg_replace_malloc.c:299)
==15069==    by 0x4E79508: xmalloc (utils.c:36)
==15069==    by 0x4E795ED: xzalloc (utils.c:65)
==15069==    by 0x4E6029B: dtype_alloc (datatype.c:1073)
==15069==    by 0x4E6029B: concat_type_alloc (datatype.c:1127)
==15069==    by 0x4E6D3B3: netlink_delinearize_set (netlink.c:578)
==15069==    by 0x4E6D68E: list_set_cb (netlink.c:648)
==15069==    by 0x5F34023: nftnl_set_list_foreach (set.c:780)
==15069==    by 0x4E6D6F3: netlink_list_sets (netlink.c:669)
==15069==    by 0x4E5A7A3: cache_init_objects (rule.c:159)
==15069==    by 0x4E5A7A3: cache_init (rule.c:216)
==15069==    by 0x4E5A7A3: cache_update (rule.c:266)
==15069==    by 0x4E7E09E: nft_evaluate (libnftables.c:388)
==15069==    by 0x4E7E85B: nft_run_cmd_from_buffer (libnftables.c:428)

Reported-by: Václav Zindulka <vaclav.zindulka@tlapnet.cz>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agonetlink_delinearize: release expressions in context registers
Pablo Neira Ayuso [Mon, 10 Jun 2019 15:19:49 +0000 (17:19 +0200)] 
netlink_delinearize: release expressions in context registers

netlink_release_registers() needs to go a bit further to release the
expressions in the register array. This should be safe since
netlink_get_register() clones expressions in the context registers.

Reported-by: Václav Zindulka <vaclav.zindulka@tlapnet.cz>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agoexpression: use expr_clone() from verdict_expr_clone()
Pablo Neira Ayuso [Mon, 10 Jun 2019 11:51:20 +0000 (13:51 +0200)] 
expression: use expr_clone() from verdict_expr_clone()

Chains are now expressions, do not assume a constant value is used.

==26302== Process terminating with default action of signal 11 (SIGSEGV)
==26302==  Access not within mapped region at address 0x50
==26302==    at 0x67D7EE7: __gmpz_init_set (in /usr/lib/x86_64-linux-gnu/libgmp.so.10.3.2)
==26302==    by 0x4E61224: expr_clone (expression.c:65)
==26302==    by 0x4E7898B: interval_map_decompose (segtree.c:943)
==26302==    by 0x4E6DDA0: netlink_list_setelems (netlink.c:882)
==26302==    by 0x4E5A806: cache_init_objects (rule.c:166)
==26302==    by 0x4E5A806: cache_init (rule.c:216)
==26302==    by 0x4E5A806: cache_update (rule.c:266)
==26302==    by 0x4E7E0EE: nft_evaluate (libnftables.c:388)
==26302==    by 0x4E7E8AB: nft_run_cmd_from_buffer (libnftables.c:428)

Fixes: f1e8a129ee42 ("src: Introduce chain_expr in jump and goto statements")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: invalid read when importing chain name (trace and json)
Pablo Neira Ayuso [Mon, 10 Jun 2019 11:32:47 +0000 (13:32 +0200)] 
src: invalid read when importing chain name (trace and json)

Update trace and json too.

Fixes: 142350f154c7 ("src: invalid read when importing chain name")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: invalid read when importing chain name
Pablo Neira Ayuso [Mon, 10 Jun 2019 11:12:20 +0000 (13:12 +0200)] 
src: invalid read when importing chain name

Use strlen(), otherwise mpz_import_data() reads too much beyond the real
chain string. Valgrind reports the following error:

==2759== Invalid read of size 1
==2759==    at 0x67D68D6: __gmpz_import (in /usr/lib/x86_64-linux-gnu/libgmp.so.10.3.2)
==2759==    by 0x4E79467: mpz_import_data (gmputil.c:133)
==2759==    by 0x4E60A12: constant_expr_alloc (expression.c:375)
==2759==    by 0x4E8ED65: nft_parse (parser_bison.y:3825)
==2759==    by 0x4E7E850: nft_parse_bison_buffer (libnftables.c:357)
==2759==    by 0x4E7E850: nft_run_cmd_from_buffer (libnftables.c:424)
==2759==    by 0x1095D4: main (in /tmp/a.out)
==2759==  Address 0x6ee1b4a is 0 bytes after a block of size 10 alloc'd
==2759==    at 0x4C2BBAF: malloc (vg_replace_malloc.c:299)
==2759==    by 0x59FD3B9: strdup (strdup.c:42)
==2759==    by 0x4E7963D: xstrdup (utils.c:75)
==2759==    by 0x4E9C233: nft_lex (scanner.l:626)
==2759==    by 0x4E8E382: nft_parse (parser_bison.c:5297)
==2759==    by 0x4E7E850: nft_parse_bison_buffer (libnftables.c:357)
==2759==    by 0x4E7E850: nft_run_cmd_from_buffer (libnftables.c:424)

Fixes: f1e8a129ee42 ("src: Introduce chain_expr in jump and goto statements")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests/shell: Print unified diffs in dump errors
Phil Sutter [Fri, 7 Jun 2019 17:25:27 +0000 (19:25 +0200)] 
tests/shell: Print unified diffs in dump errors

Non-unified format is useful only if the expected output is printed as
well, which is not the case.

Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests/shell: Fix warning from awk call
Phil Sutter [Fri, 7 Jun 2019 17:25:26 +0000 (19:25 +0200)] 
tests/shell: Fix warning from awk call

Syntax passed to awk in that one testcase caused a warning, fix the
syntax.

Fixes: e0a9aad024809 ("tests: shell: fix tests for deletion via handle attribute")
Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests/py: Add missing arp.t JSON equivalents
Phil Sutter [Fri, 7 Jun 2019 17:25:25 +0000 (19:25 +0200)] 
tests/py: Add missing arp.t JSON equivalents

Fixes: 4b0f2a712b579 ("src: support for arp sender and target ethernet and IPv4 addresses")
Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests/py: Fix JSON equivalents
Phil Sutter [Fri, 7 Jun 2019 17:25:24 +0000 (19:25 +0200)] 
tests/py: Fix JSON equivalents

Recent patch removing single element set use missed to adjust JSON
equivalents accordingly.

Fixes: 27f6a4c68b4fd ("tests: replace single element sets")
Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: Support intra-transaction rule references
Phil Sutter [Fri, 7 Jun 2019 17:21:21 +0000 (19:21 +0200)] 
src: Support intra-transaction rule references

A rule may be added before or after another one using index keyword. To
support for the other rule being added within the same batch, one has to
make use of NFTNL_RULE_ID and NFTNL_RULE_POSITION_ID attributes. This
patch does just that among a few more crucial things:

* If cache is complete enough to contain rules, update cache when
  evaluating rule commands so later index references resolve correctly.

* Reduce rule_translate_index() to its core code which is the actual
  linking of rules and consequently rename the function. The removed
  bits are pulled into the calling rule_evaluate() to reduce code
  duplication in between cache updates with and without rule reference.

* Pass the current command op to rule_evaluate() as indicator whether to
  insert before or after a referenced rule or at beginning or end of
  chain in cache. Exploit this from chain_evaluate() to avoid adding
  the chain's rules a second time.

Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agosrc: Make cache_is_complete() public
Phil Sutter [Fri, 7 Jun 2019 17:21:20 +0000 (19:21 +0200)] 
src: Make cache_is_complete() public

Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agorule: Introduce rule_lookup_by_index()
Phil Sutter [Fri, 7 Jun 2019 17:21:19 +0000 (19:21 +0200)] 
rule: Introduce rule_lookup_by_index()

In contrast to rule_lookup(), this function returns a chain's rule at a
given index instead of by handle.

Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agotests/json_echo: Drop needless workaround
Phil Sutter [Fri, 7 Jun 2019 17:21:18 +0000 (19:21 +0200)] 
tests/json_echo: Drop needless workaround

With cache issues now resolved, there is no need for the multi add test
workaround anymore.

Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agocache: Fix evaluation for rules with index reference
Phil Sutter [Fri, 7 Jun 2019 17:21:17 +0000 (19:21 +0200)] 
cache: Fix evaluation for rules with index reference

After parsing input, rule location data (index or handle) is contained
in cmd->handle, not yet in cmd->rule->handle.

Fixes: 7df42800cf89e ("src: single cache_update() call to build cache before evaluation")
Signed-off-by: Phil Sutter <phil@nwl.cc>
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agolibnftables: check for errors after evaluations
Pablo Neira Ayuso [Fri, 7 Jun 2019 12:20:48 +0000 (14:20 +0200)] 
libnftables: check for errors after evaluations

Check for state->nerrs after evaluation to restore error reporting when
evaluation fails.

Fixes: df2f746fb4cf ("libnftables: keep evaluating until parser_max_errors")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agomnl: bogus error when running monitor mode
Pablo Neira Ayuso [Wed, 5 Jun 2019 17:34:51 +0000 (19:34 +0200)] 
mnl: bogus error when running monitor mode

Fix bogus error message:

 # nft monitor
 Cannot set up netlink socket buffer size to 16777216 bytes, falling back to 16777216 bytes

Fixes: bcf60fb819bf ("mnl: add mnl_set_rcvbuffer() and use it")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
6 years agolibnftables: keep evaluating until parser_max_errors
Pablo Neira Ayuso [Fri, 7 Jun 2019 11:37:22 +0000 (13:37 +0200)] 
libnftables: keep evaluating until parser_max_errors

Bail out after parser_max_errors has been reached, eg.

 # nft -f /tmp/errors.nft
 /tmp/errors.nft:1:23-23: Error: syntax error, unexpected newline
 filter input tcp dport
                       ^
 /tmp/errors.nft:2:24-26: Error: datatype mismatch, expected internet network service, expression has type Internet protocol
 filter input tcp dport tcp
              ~~~~~~~~~ ^^^
 /tmp/errors.nft:3:24-26: Error: datatype mismatch, expected internet network service, expression has type Internet protocol
 filter input tcp sport udp
              ~~~~~~~~~ ^^^

Fixes: f211921e25e6 ("src: perform evaluation after parsing")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>