Skip to contentSkip to conversation

Netfilter fixes for net

PATCH In review Pablo Neira Ayuso 2 participants 17 messages Nov 29

Subsystems (5)
lore
Share & tools
lore

Pablo Neira Ayuso

author maintainer
#0 lore raw

cover Netfilter fixes for net

The following patchset contains Netfilter fixes for net, mostly LLM findings are usual these days, unless stated otherwise:

1) Allocate all ct extensions if ct helper extension is used, this is needed because ct extension reallocation is possible while expectations are already sitting in the expectation list. From Jaeyeong Lee.

2) Restrict xt_IDLETIMER to init_netns. This xtables extensions exposes a global sysfs interface. Follow ups are possible to restore this feature if someone proves to be using this extension from netns. From Zhiling Zou.

3) Prevent an unbound recursion in the synproxy transmit path. This is similar to a recent fix to address a similar recursion in the reject transmit path. Patch from Fernando F. Mancera.

4) On conntrack module removal, wait for RCU quiescent state to address possible use-after-free. From Chengfeng Ye.

5) Set IP_CT_ESTABLISHED state to TCP reject skbuffs to address a warning splat in the NAT infrastructure. From xujiahao.

6) Restrict maximum number of chain of master conntracks to 8 when allocating a new expectation. This is to address a recursion in the conntrack destroy path leading to stack overflow. From Florian Westphal.

7) Skip recycled unconfirmed conntracks seen from /proc/net/nf_conntrack due to TYPESAFE_RCU, otherwise access to ct extension of this new unconfirmed conntrack results in a crash. from Yiran Qiu.

8) Detach ct template in conntrack bridge when packet is invalid, otherwise ct template is exposed to follow up hooks in the pipeline. From Luxiao Xu.

9) In synproxy, fix incorrect handshake ACK sent to the backend carries a TSecr uncovered since commit 3ba075278c11 ("tcp: be less liberal in TSEcr received while in SYN_RECV state"). This bug has been reported in production. Patch from Florian Westphal.

10) Disable hook for dormant table only if transition to dormant state took place in this transaction. From Ma Xinmen.

11) Add unregister flag for hooks as a dependency to fix a regression in the follow up patch in this series.

12) Unbind flowtable flow_block when hook are released, otherwise, flowtable entries in hardware are not released when the flowtable is destroyed. This regression has been observed in production.

13) Flush pending nf_tables destroy work before handling the flowtable event to address a race between flowtable events and the destroy worker.

14) Update conntrack defrag to stop at the legacy AH protocol header, just like 568af6de058c ("netfilter: nf_tables: set pktinfo->thoff at AH header if found"). Fragment header before AH is still possible. This addresses a hypothetical policy bypass. The AH protocol is deprecated since 2017, noone should be using it.

Please, pull these changes from:

git://git.kernel.org/pub/scm/linux/kernel/git/netfilter/nf.git nf-26-11-29

Thanks.

----------------------------------------------------------------

The following changes since commit e1055cbfd6eb578417f3ce983cf44462e8465267:

Merge tag 'linux-can-fixes-for-7.4-20261124' of git://git.kernel.org/pub/scm/linux/kernel/git/mkl/linux-can (2026-11-26 15:47:14 +0100)

are available in the Git repository at:

git://git.kernel.org/pub/scm/linux/kernel/git/netfilter/nf.git nf-26-11-29

for you to fetch changes up to 88fe9e22aa1f37150e2057d8d9dd4c979196be11:

netfilter: ipv6: stop the conntrack fragment search at AH (2026-11-29 00:40:27 +0100)

----------------------------------------------------------------
netfilter pull request 26-11-29

----------------------------------------------------------------
Chengfeng Ye (1):
netfilter: conntrack: wait for RCU readers before freeing the hash

Fernando Fernandez Mancera (1):
netfilter: synproxy: prevent unbounded recursion in transmit path

Florian Westphal (2):
netfilter: nf_conntrack: limit expectation master chain depth
netfilter: synproxy: fix double tsoff application in server ACK TSecr

Jaeyeong Lee (1):
netfilter: conntrack: prevent helper extension relocation

Luxiao Xu (1):
netfilter: bridge: detach conntrack template on invalid IP frames

Ma Xinmeng (1):
netfilter: nf_tables: only disable tables on a dormant transition

Pablo Neira Ayuso (3):
netfilter: nf_tables: add NFT_HOOK_UNREGISTERED and use it
netfilter: nf_tables: unbind flowtable on hook release
netfilter: nf_tables: flush destroy work from flowtable netdev event handler

Ryosuke Iwahashi (1):
netfilter: ipv6: stop the conntrack fragment search at AH

Yiran Qiu (1):
netfilter: conntrack: skip unconfirmed entries in /proc/net/nf_conntrack

Zhiling Zou (1):
netfilter: xt_IDLETIMER: restrict to init_net

xujiahao (1):
netfilter: conntrack: attach generated TCP resets as ESTABLISHED

 include/linux/netfilter.h                   |   8 +-
 include/net/netfilter/nf_conntrack_helper.h |  15 ++++
 include/net/netfilter/nf_tables.h           |   3 +-
 net/bridge/netfilter/nf_conntrack_bridge.c  |  16 ++--
 net/ipv4/icmp.c                             |   2 +-
 net/ipv4/netfilter/nf_reject_ipv4.c         |   2 +-
 net/ipv6/icmp.c                             |   2 +-
 net/ipv6/netfilter/nf_conntrack_reasm.c     |   9 +--
 net/ipv6/netfilter/nf_reject_ipv6.c         |   2 +-
 net/netfilter/core.c                        |   4 +-
 net/netfilter/nf_conntrack_core.c           |  28 +++++--
 net/netfilter/nf_conntrack_expect.c         |  15 +++-
 net/netfilter/nf_conntrack_extend.c         |  31 +++++---
 net/netfilter/nf_conntrack_netlink.c        |  36 ++++++---
 net/netfilter/nf_conntrack_standalone.c     |   3 +
 net/netfilter/nf_synproxy_core.c            |  39 +++++++++-
 net/netfilter/nf_tables_api.c               | 114 +++++++++++++++++-----------
 net/netfilter/nft_chain_filter.c            |   6 +-
 net/netfilter/xt_IDLETIMER.c                |   7 ++
 19 files changed, 242 insertions(+), 100 deletions(-)
author maintainer
#1 lore raw

PATCH 1/14 netfilter: conntrack: prevent helper extension relocation

From: Jaeyeong Lee <[email protected]>

nf_ct_ext_add() may relocate an unconfirmed conntrack's extension blob when the current allocation is too small. struct nf_conn_help embeds the hlist head for the master's expectations. The first expectation's lnode.pprev therefore points into that extension blob.

An nftables CT expectation object can link an expectation before a later NAT expression adds extensions to the same unconfirmed conntrack. If an addition relocates the blob, the copied hlist head still points to the expectation, but the expectation's pprev continues to point into the freed old blob. Removing the expectation later executes hlist_del_rcu() and writes through this stale pointer.

Reserve enough storage for every extension whenever the helper extension is added. Account for the alignment padding that may be required between extensions so the reservation is independent of their addition order. No expectation can be linked before its master has a helper extension, so subsequent additions fit in the existing allocation and cannot invalidate expectation list pointers. Conntracks without helpers are unaffected.

Fixes 857b46027d6f ("netfilter: nft_ct: add ct expectations support")
---
 net/netfilter/nf_conntrack_extend.c | 31 +++++++++++++++++++----------
 1 file changed, 21 insertions(+), 10 deletions(-)
net/netfilter/nf_conntrack_extend.c +21 -10
index 0da105e1ded9..e5e04e0ec40a 100644
@@ -54,35 +54,38 @@ static const u8 nf_ct_ext_type_len[NF_CT_EXT_NUM] = {
 #endif
 };
 
+#define NF_CT_EXT_TYPE_SIZE(type) \
+	ALIGN(sizeof(type), __alignof__(struct nf_ct_ext))
+
 static __always_inline unsigned int total_extension_size(void)
 {
 	/* remember to add new extensions below */
 	BUILD_BUG_ON(NF_CT_EXT_NUM > 10);
 
 	return sizeof(struct nf_ct_ext) +
-	       sizeof(struct nf_conn_help)
+	       NF_CT_EXT_TYPE_SIZE(struct nf_conn_help)
 #if IS_ENABLED(CONFIG_NF_NAT)
-		+ sizeof(struct nf_conn_nat)
+		+ NF_CT_EXT_TYPE_SIZE(struct nf_conn_nat)
 #endif
-		+ sizeof(struct nf_conn_seqadj)
-		+ sizeof(struct nf_conn_acct)
+		+ NF_CT_EXT_TYPE_SIZE(struct nf_conn_seqadj)
+		+ NF_CT_EXT_TYPE_SIZE(struct nf_conn_acct)
 #ifdef CONFIG_NF_CONNTRACK_EVENTS
-		+ sizeof(struct nf_conntrack_ecache)
+		+ NF_CT_EXT_TYPE_SIZE(struct nf_conntrack_ecache)
 #endif
 #ifdef CONFIG_NF_CONNTRACK_TIMESTAMP
-		+ sizeof(struct nf_conn_tstamp)
+		+ NF_CT_EXT_TYPE_SIZE(struct nf_conn_tstamp)
 #endif
 #ifdef CONFIG_NF_CONNTRACK_TIMEOUT
-		+ sizeof(struct nf_conn_timeout)
+		+ NF_CT_EXT_TYPE_SIZE(struct nf_conn_timeout)
 #endif
 #ifdef CONFIG_NF_CONNTRACK_LABELS
-		+ sizeof(struct nf_conn_labels)
+		+ NF_CT_EXT_TYPE_SIZE(struct nf_conn_labels)
 #endif
 #if IS_ENABLED(CONFIG_NETFILTER_SYNPROXY)
-		+ sizeof(struct nf_conn_synproxy)
+		+ NF_CT_EXT_TYPE_SIZE(struct nf_conn_synproxy)
 #endif
 #if IS_ENABLED(CONFIG_NET_ACT_CT)
-		+ sizeof(struct nf_conn_act_ct_ext)
+		+ NF_CT_EXT_TYPE_SIZE(struct nf_conn_act_ct_ext)
 #endif
 	;
 }
@@ -112,6 +115,14 @@ void *nf_ct_ext_add(struct nf_conn *ct, enum nf_ct_ext_id id, gfp_t gfp)
 	newlen = newoff + nf_ct_ext_type_len[id];
 
 	alloc = max(newlen, NF_CT_EXT_PREALLOC);
+	/*
+	 * nf_conn_help contains the expectation list head.  Once an
+	 * expectation is linked, its lnode.pprev points into this allocation,
+	 * so later extension additions must not be allowed to relocate it.
+	 */
+	if (id == NF_CT_EXT_HELPER)
+		alloc = max(alloc, total_extension_size());
+
 	new = krealloc(ct->ext, alloc, gfp);
 	if (!new)
 		return NULL;
Signature · 1 line
2.47.3
#2 lore raw

Re: [PATCH net 01/14] netfilter: conntrack: prevent helper extension relocation

This is an automated message. This series looks like a fix, but its commit messages seem to be missing some information:

Hi!

This is an automated message. This series looks like a fix, but its commit messages seem to be missing some information:

- How the issue was discovered, e.g. hit in production, hit during development, syzbot report, manual code inspection, LLM or static analysis tool scan.

- Whether the issue was actually triggered, or is only theoretical (e.g. found by LLM and not proven at runtime). If it was triggered please include the symptoms, like the stack trace or kernel messages.

Please do not repost the series just to address the above. Instead, reply to this email with the missing information, so that reviewers can take it into account.

*IMPORTANT*: If you do repost (for other reasons) - please include the relevant info in the cover letter or commit messages.

Signature · 2 lines
The evaluation is done by an LLM so it may be wrong, if you think
that is the case please reply and explain.
author maintainer
#3 lore raw

Re: [PATCH net 01/14] netfilter: conntrack: prevent helper extension relocation

Hi,

Quoted 5 lines · On Sun, Nov 29, 2026 at 12:14:24AM +0000, [email protected] wrote:

Hi!

This is an automated message. This series looks like a fix, but its commit messages seem to be missing some information:

Quoted 7 lines

- How the issue was discovered, e.g. hit in production, hit during development, syzbot report, manual code inspection, LLM or static analysis tool scan.

- Whether the issue was actually triggered, or is only theoretical (e.g. found by LLM and not proven at runtime). If it was triggered please include the symptoms, like the stack trace or kernel messages.

This is PR containing netfilter fixes.

These are mostly LLM finding, unless stated otherwise as described in the cover letter.

Quoted 9 lines

Please do not repost the series just to address the above. Instead, reply to this email with the missing information, so that reviewers can take it into account.

*IMPORTANT*: If you do repost (for other reasons) - please include the relevant info in the cover letter or commit messages.

Signature · 2 lines
The evaluation is done by an LLM so it may be wrong, if you think
that is the case please reply and explain.
author maintainer
#4 lore raw

PATCH 2/14 netfilter: xt_IDLETIMER: restrict to init_net

In reply to Pablo Neira Ayuso

From: Zhiling Zou <[email protected]>

IDLETIMER keeps its timer registry, reference counts, and sysfs files in module-global state, while Xtables invokes checkentry and destroy for rules in individual network namespaces. A matching label from another namespace can therefore reuse and control an existing timer.

The sysfs interface is global and cannot represent per-namespace labels with the current target design. Reject IDLETIMER rules outside init_net so that global state stays in the namespace it was built for.

Fixes 0902b469bd25 ("netfilter: xtables: idletimer target implementation")
---
 net/netfilter/xt_IDLETIMER.c | 7 +++++++
 1 file changed, 7 insertions(+)
net/netfilter/xt_IDLETIMER.c +7 -0
index 71b78b5da698..2449c091cdf6 100644
@@ -28,6 +28,7 @@
 #include <linux/kobject.h>
 #include <linux/workqueue.h>
 #include <linux/sysfs.h>
+#include <net/net_namespace.h>
 
 struct idletimer_tg {
 	struct list_head entry;
@@ -308,6 +309,9 @@ static int idletimer_tg_checkentry(const struct xt_tgchk_param *par)
 	struct idletimer_tg_info *info = par->targinfo;
 	int ret;
 
+	if (!net_eq(par->net, &init_net))
+		return -EOPNOTSUPP;
+
 	ret = idletimer_tg_helper(info);
 	if(ret < 0)
 		return -EINVAL;
@@ -341,6 +345,9 @@ static int idletimer_tg_checkentry_v1(const struct xt_tgchk_param *par)
 	struct idletimer_tg_info_v1 *info = par->targinfo;
 	int ret;
 
+	if (!net_eq(par->net, &init_net))
+		return -EOPNOTSUPP;
+
 	if (info->send_nl_msg)
 		return -EOPNOTSUPP;
 
Signature · 1 line
2.47.3
author maintainer
#5 lore raw

PATCH 3/14 netfilter: synproxy: prevent unbounded recursion in transmit path

In reply to Pablo Neira Ayuso

From: Fernando Fernandez Mancera <[email protected]>

Packets generated at synproxy_send_tcp() and synproxy_send_tcp_ipv6() are handled by ip_local_out() and ip6_local_out) which traverse LOCAL_OUT and POST_ROUTING. As SYNPROXY hooks are registered on POST_ROUTING, a payload mangling rule at OUTPUT with priority raw can rewrite the generated ACK to SYN|ACK before conntrack sees it.

This leaves the conntrack state in SYN_RECV state and synproxy sends two more ACKs repeating the cycle until the IRQ stack guard page is hit:

  BUG: IRQ stack guard page was hit
  Oops: stack guard page: 0000 [#1] SMP NOPTI
   synproxy_send_tcp
   ipv4_synproxy_hook
   nf_hook_slow
   ip_output
   ipv4_synproxy_hook
   ...

Fix this by applying the per-CPU xmit recursion limit. Note that this cannot be triggered with iptables as it is not possible to modify the TCP flags from raw priority.

Fixes ad49d86e07a4 ("netfilter: nf_tables: Add synproxy support")
---
 net/netfilter/nf_synproxy_core.c | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
net/netfilter/nf_synproxy_core.c +19 -0
index 401ce5a13f3f..9dd681596c70 100644
@@ -21,6 +21,7 @@
 #include <net/netfilter/nf_conntrack_synproxy.h>
 #include <net/netfilter/nf_conntrack_zones.h>
 #include <net/netfilter/nf_synproxy.h>
+#include <net/netfilter/nf_recursion.h>
 
 static DEFINE_MUTEX(synproxy_mutex);
 
@@ -439,7 +440,16 @@ synproxy_send_tcp(struct net *net,
 		nf_conntrack_get(nfct);
 	}
 
+	local_bh_disable();
+	if (nf_dev_xmit_recursion()) {
+		local_bh_enable();
+		goto free_nskb;
+	}
+
+	nf_dev_xmit_recursion_inc();
 	ip_local_out(net, nskb->sk, nskb);
+	nf_dev_xmit_recursion_dec();
+	local_bh_enable();
 	return;
 
 free_nskb:
@@ -858,7 +868,16 @@ synproxy_send_tcp_ipv6(struct net *net,
 		nf_conntrack_get(nfct);
 	}
 
+	local_bh_disable();
+	if (nf_dev_xmit_recursion()) {
+		local_bh_enable();
+		goto free_nskb;
+	}
+
+	nf_dev_xmit_recursion_inc();
 	ip6_local_out(net, nskb->sk, nskb);
+	nf_dev_xmit_recursion_dec();
+	local_bh_enable();
 	return;
 
 free_nskb:
Signature · 1 line
2.47.3
author maintainer
#6 lore raw

PATCH 4/14 netfilter: conntrack: wait for RCU readers before freeing the hash

In reply to Pablo Neira Ayuso

From: Chengfeng Ye <[email protected]>

nf_ct_get_tuple_skb() calls into conntrack under rcu_read_lock() without holding a module reference. CAKE can use this hook to look up a packet without an attached conntrack, even during nf_conntrack module teardown.

nf_conntrack_cleanup_end() clears nf_ct_hook but frees nf_conntrack_hash without waiting for existing readers. The grace period in per-net cleanup runs while the hook is still published, so a later reader can race as follows:

CPU 0 (packet path) CPU 1 (module teardown)
rcu_read_lock()
ct_hook = rcu_dereference(nf_ct_hook)
RCU_INIT_POINTER(nf_ct_hook, NULL) kvfree(nf_conntrack_hash)
ct_hook->get_tuple_skb()
nf_conntrack_find_get()
access freed hash bucket
rcu_read_unlock()

The same missing grace period affects initialization failure after nf_conntrack_init_end() publishes the hook. During module teardown, KASAN reported:

  BUG: KASAN: vmalloc-out-of-bounds in __nf_conntrack_find_get.isra.0
  Read of size 8 at addr ffffc900012e2ae0 by task poc/90
  Call Trace:
   __nf_conntrack_find_get.isra.0+0xf87/0x10c0 [nf_conntrack]
   nf_conntrack_get_tuple_skb+0x255/0x400 [nf_conntrack]
   nf_ct_get_tuple_skb+0x75/0xb0
   cake_hash+0xfdb/0x1e10
   cake_enqueue+0x5cd/0x36e0
   dev_qdisc_enqueue+0x40/0x170
   __dev_queue_xmit+0x1e90/0x3110

Wait for an RCU grace period after clearing nf_ct_hook, before releasing the hash table and the remaining conntrack resources.

Fixes b60a60405fb9 ("netfilter: Add nf_ct_get_tuple_skb global lookup function")
---
 net/netfilter/nf_conntrack_core.c | 1 +
 1 file changed, 1 insertion(+)
net/netfilter/nf_conntrack_core.c +1 -0
index 931b76aacd93..0cb5320883bd 100644
@@ -2454,6 +2454,7 @@ void nf_conntrack_cleanup_start(void)
 void nf_conntrack_cleanup_end(void)
 {
 	RCU_INIT_POINTER(nf_ct_hook, NULL);
+	synchronize_rcu();
 	cancel_delayed_work_sync(&conntrack_gc_work.dwork);
 	kvfree(nf_conntrack_hash);
 
Signature · 1 line
2.47.3
author maintainer
#7 lore raw

PATCH 5/14 netfilter: conntrack: attach generated TCP resets as ESTABLISHED

In reply to Pablo Neira Ayuso

From: xujiahao <[email protected]>

nf_conntrack_attach() marks every packet it attaches as related to the conntrack entry of the packet which caused it: IP_CT_RELATED_REPLY when that packet was in the original direction, IP_CT_RELATED otherwise.

That is right for the ICMP errors built by icmp.c and icmpv6.c, but not for the TCP resets built by nf_send_reset(): a reset is a packet of the connection itself and carries the state of the connection, just like the equivalent reset the TCP stack emits.

A locally generated reset therefore currently leaves through the LOCAL_OUT nat hook as IP_CT_RELATED_REPLY. As no nat mapping is initialized for it, nf_nat_inet_fn() evaluates the nat OUTPUT chain, so a DNAT target reachable from that chain rewrites the reset and warns:

  WARNING: net/netfilter/xt_nat.c:154 at xt_dnat_target_v2+0x97/0xc0

Pass the protocol of the generated packet to nf_ct_attach() and mark TCP resets as ESTABLISHED/ESTABLISHED_REPLY. They then take the default branch of nf_nat_inet_fn(), which only applies the mapping already installed on the connection. ICMP errors keep IP_CT_RELATED/_REPLY.

Passing u8 l4proto rather than a boolean keeps the call sites readable, as nf_ct_attach(new, skb, IPPROTO_TCP) says which packet is built.

---
 include/linux/netfilter.h           |  8 +++++---
 net/ipv4/icmp.c                     |  2 +-
 net/ipv4/netfilter/nf_reject_ipv4.c |  2 +-
 net/ipv6/icmp.c                     |  2 +-
 net/ipv6/netfilter/nf_reject_ipv6.c |  2 +-
 net/netfilter/core.c                |  4 ++--
 net/netfilter/nf_conntrack_core.c   | 27 +++++++++++++++++++++------
 7 files changed, 32 insertions(+), 15 deletions(-)
include/linux/netfilter.h +5 -3
index e99afc1414cd..c9771578f18d 100644
@@ -454,13 +454,14 @@ nf_nat_decode_session(struct sk_buff *skb, struct flowi *fl, u_int8_t family)
 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
 #include <linux/netfilter/nf_conntrack_zones_common.h>
 
-void nf_ct_attach(struct sk_buff *, const struct sk_buff *);
+void nf_ct_attach(struct sk_buff *, const struct sk_buff *, u8 l4proto);
 void nf_ct_set_closing(struct nf_conntrack *nfct);
 struct nf_conntrack_tuple;
 bool nf_ct_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
 			 const struct sk_buff *skb);
 #else
-static inline void nf_ct_attach(struct sk_buff *new, struct sk_buff *skb) {}
+static inline void nf_ct_attach(struct sk_buff *new, struct sk_buff *skb,
+				u8 l4proto) {}
 static inline void nf_ct_set_closing(struct nf_conntrack *nfct) {}
 struct nf_conntrack_tuple;
 static inline bool nf_ct_get_tuple_skb(struct nf_conntrack_tuple *dst_tuple,
@@ -478,7 +479,8 @@ struct nf_ct_hook {
 	void (*destroy)(struct nf_conntrack *);
 	bool (*get_tuple_skb)(struct nf_conntrack_tuple *,
 			      const struct sk_buff *);
-	void (*attach)(struct sk_buff *nskb, const struct sk_buff *skb);
+	void (*attach)(struct sk_buff *nskb, const struct sk_buff *skb,
+		       u8 l4proto);
 	void (*set_closing)(struct nf_conntrack *nfct);
 	int (*confirm)(struct sk_buff *skb);
 	u32 (*get_id)(const struct nf_conntrack *nfct);
net/ipv4/icmp.c +1 -1
index 90c0e22c29be..e01e3294132f 100644
@@ -375,7 +375,7 @@ static int icmp_glue_bits(void *from, char *to, int offset, int len, int odd,
 	if (icmp_param->data.icmph.type <= NR_ICMP_TYPES &&
 	    icmp_pointers[array_index_nospec(icmp_param->data.icmph.type,
 					     NR_ICMP_TYPES + 1)].error)
-		nf_ct_attach(skb, icmp_param->skb);
+		nf_ct_attach(skb, icmp_param->skb, IPPROTO_ICMP);
 	return 0;
 }
 
net/ipv4/netfilter/nf_reject_ipv4.c +1 -1
index 4082fa184af8..47baf3b8e41d 100644
@@ -309,7 +309,7 @@ void nf_send_reset(struct net *net, struct sock *sk, struct sk_buff *oldskb,
 	if (nskb->len > dst4_mtu(skb_dst(nskb)))
 		goto free_nskb;
 
-	nf_ct_attach(nskb, oldskb);
+	nf_ct_attach(nskb, oldskb, IPPROTO_TCP);
 	nf_ct_set_closing(skb_nfct(oldskb));
 
 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
net/ipv6/icmp.c +1 -1
index d8203ebad882..8494a5b98a49 100644
@@ -327,7 +327,7 @@ static int icmpv6_getfrag(void *from, char *to, int offset, int len, int odd, st
 				      to, len);
 	skb->csum = csum_block_add(skb->csum, csum, odd);
 	if (!(msg->type & ICMPV6_INFOMSG_MASK))
-		nf_ct_attach(skb, org_skb);
+		nf_ct_attach(skb, org_skb, IPPROTO_ICMP);
 	return 0;
 }
 
net/ipv6/netfilter/nf_reject_ipv6.c +1 -1
index 7c9464184517..98350cde587f 100644
@@ -378,7 +378,7 @@ void nf_send_reset6(struct net *net, struct sock *sk, struct sk_buff *oldskb,
 	nf_reject_ip6hdr_put(nskb, oldskb, IPPROTO_TCP, ip6_dst_hoplimit(dst));
 	nf_reject_ip6_tcphdr_put(nskb, oldskb, otcph, otcplen);
 
-	nf_ct_attach(nskb, oldskb);
+	nf_ct_attach(nskb, oldskb, IPPROTO_TCP);
 	nf_ct_set_closing(skb_nfct(oldskb));
 
 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
net/netfilter/core.c +2 -2
index 44c856c1e621..a6ac172379af 100644
@@ -702,7 +702,7 @@ EXPORT_SYMBOL_GPL(nf_nat_hook);
  * tracking in use: without this, connection may not be in hash table, and hence
  * manufactured ICMP or RST packets will not be associated with it.
  */
-void nf_ct_attach(struct sk_buff *new, const struct sk_buff *skb)
+void nf_ct_attach(struct sk_buff *new, const struct sk_buff *skb, u8 l4proto)
 {
 	const struct nf_ct_hook *ct_hook;
 
@@ -710,7 +710,7 @@ void nf_ct_attach(struct sk_buff *new, const struct sk_buff *skb)
 		rcu_read_lock();
 		ct_hook = rcu_dereference(nf_ct_hook);
 		if (ct_hook)
-			ct_hook->attach(new, skb);
+			ct_hook->attach(new, skb, l4proto);
 		rcu_read_unlock();
 	}
 }
net/netfilter/nf_conntrack_core.c +21 -6
index 0cb5320883bd..7f113e221330 100644
@@ -2178,17 +2178,32 @@ EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
 #endif
 
 /* Used by ipt_REJECT and ip6t_REJECT. */
-static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
+static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb,
+				u8 l4proto)
 {
 	struct nf_conn *ct;
 	enum ip_conntrack_info ctinfo;
 
-	/* This ICMP is in reverse direction to the packet which caused it */
 	ct = nf_ct_get(skb, &ctinfo);
-	if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
-		ctinfo = IP_CT_RELATED_REPLY;
-	else
-		ctinfo = IP_CT_RELATED;
+	if (l4proto == IPPROTO_TCP) {
+		/*
+		 * A reset we generate for an existing TCP connection belongs
+		 * to that connection, it is not an error related to it, so it
+		 * carries the state of the connection.  Attaching it as
+		 * related would let it take a fresh NAT mapping on its way
+		 * out, i.e. rewrite the reset.
+		 */
+		if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
+			ctinfo = IP_CT_ESTABLISHED_REPLY;
+		else
+			ctinfo = IP_CT_ESTABLISHED;
+	} else {
+		/* Errors are in reverse direction to the packet that caused them. */
+		if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
+			ctinfo = IP_CT_RELATED_REPLY;
+		else
+			ctinfo = IP_CT_RELATED;
+	}
 
 	/* Attach to new skbuff, and increment count */
 	nf_ct_set(nskb, ct, ctinfo);
Signature · 1 line
2.47.3
author maintainer
#8 lore raw

PATCH 6/14 netfilter: nf_conntrack: limit expectation master chain depth

In reply to Pablo Neira Ayuso

From: Florian Westphal <[email protected]>

A conntrack can point to a master conntrack, which itself may point to another master, and so on. There is currently no bound on how deep this chain can grow.

Force a max depth in nf_ct_expect_alloc(): walk the master chain and reject allocation if it would exceed 8 levels of nesting.

Also add ctnetlink_find_get_master and use it so that ctnetlink create paths return -EMLINK instead of falling through to nf_ct_expect_alloc() and returning a misleading -ENOMEM.

This prevents unbounded ct->master->master->... chains.

This also restricts the number of call forward/redirects that h323 and sip helpers will follow.

---
 include/net/netfilter/nf_conntrack_helper.h | 15 +++++++++
 net/netfilter/nf_conntrack_expect.c         | 15 +++++++--
 net/netfilter/nf_conntrack_netlink.c        | 36 +++++++++++++++------
 3 files changed, 53 insertions(+), 13 deletions(-)
include/net/netfilter/nf_conntrack_helper.h +15 -0
index 335b8c43694f..53a8eda848dc 100644
@@ -29,6 +29,8 @@ enum nf_ct_helper_flags {
 
 #define NF_CT_HELPER_NAME_LEN	16
 
+#define NF_CT_MAX_EXPECT_CHAIN_LEN	8
+
 /* Must be kept in sync with the classes defined by helpers */
 #define NF_CT_MAX_EXPECT_CLASSES	4
 
@@ -159,6 +161,19 @@ static inline void nf_ct_help_put(const struct nf_conn *ct)
 		kfree_rcu(helper, rcu);
 }
 
+static inline bool nf_ct_master_acceptable(const struct nf_conn *m)
+{
+	unsigned int depth = 0;
+
+	while (m->master) {
+		if (++depth >= NF_CT_MAX_EXPECT_CHAIN_LEN)
+			return false;
+		m = m->master;
+	}
+
+	return true;
+}
+
 int nf_conntrack_helper_init(void);
 void nf_conntrack_helper_fini(void);
 
net/netfilter/nf_conntrack_expect.c +12 -3
index 06242c86e1dc..62e434cd57c9 100644
@@ -299,13 +299,22 @@ void nf_ct_unexpect_related(struct nf_conntrack_expect *exp)
 }
 EXPORT_SYMBOL_GPL(nf_ct_unexpect_related);
 
-/* We don't increase the master conntrack refcount for non-fulfilled
- * conntracks. During the conntrack destruction, the expectations are
- * always killed before the conntrack itself */
+/**
+ * nf_ct_expect_alloc - allocate a new conntrack expectation
+ * @me: The conntrack to be used as master.
+ *
+ * The master conntrack refcount is not incremented; expectations
+ * are always killed before the master conntrack is destroyed.
+ *
+ * Return: a new expectation on success or NULL on failure.
+ */
 struct nf_conntrack_expect *nf_ct_expect_alloc(struct nf_conn *me)
 {
 	struct nf_conntrack_expect *new;
 
+	if (!nf_ct_master_acceptable(me))
+		return NULL;
+
 	new = kmem_cache_zalloc(nf_ct_expect_cachep, GFP_ATOMIC);
 	if (!new)
 		return NULL;
net/netfilter/nf_conntrack_netlink.c +26 -10
index 1f8d94a05240..30428d520e43 100644
@@ -2231,6 +2231,26 @@ ctnetlink_change_conntrack(struct nf_conn *ct,
 	return 0;
 }
 
+static struct nf_conn *
+ctnetlink_find_get_master(struct net *net, const struct nf_conntrack_zone *zone,
+			  const struct nf_conntrack_tuple *tuple)
+{
+	struct nf_conntrack_tuple_hash *master_h;
+	struct nf_conn *master_ct;
+
+	master_h = nf_conntrack_find_get(net, zone, tuple);
+	if (!master_h)
+		return ERR_PTR(-ENOENT);
+
+	master_ct = nf_ct_tuplehash_to_ctrack(master_h);
+	if (!nf_ct_master_acceptable(master_ct)) {
+		nf_ct_put(master_ct);
+		return ERR_PTR(-EMLINK);
+	}
+
+	return master_ct;
+}
+
 static struct nf_conn *
 ctnetlink_create_conntrack(struct net *net,
 			   const struct nf_conntrack_zone *zone,
@@ -2356,7 +2376,6 @@ ctnetlink_create_conntrack(struct net *net,
 	/* setup master conntrack: this is a confirmed expectation */
 	if (cda[CTA_TUPLE_MASTER]) {
 		struct nf_conntrack_tuple master;
-		struct nf_conntrack_tuple_hash *master_h;
 		struct nf_conn *master_ct;
 
 		err = ctnetlink_parse_tuple(cda, &master, CTA_TUPLE_MASTER,
@@ -2364,12 +2383,11 @@ ctnetlink_create_conntrack(struct net *net,
 		if (err < 0)
 			goto err2;
 
-		master_h = nf_conntrack_find_get(net, zone, &master);
-		if (master_h == NULL) {
-			err = -ENOENT;
+		master_ct = ctnetlink_find_get_master(net, zone, &master);
+		if (IS_ERR(master_ct)) {
+			err = PTR_ERR(master_ct);
 			goto err2;
 		}
-		master_ct = nf_ct_tuplehash_to_ctrack(master_h);
 		__set_bit(IPS_EXPECTED_BIT, &ct->status);
 		ct->master = master_ct;
 	}
@@ -3613,7 +3631,6 @@ ctnetlink_create_expect(struct net *net,
 			u_int8_t u3, u32 portid, int report)
 {
 	struct nf_conntrack_tuple tuple, mask, master_tuple;
-	struct nf_conntrack_tuple_hash *h = NULL;
 	struct nf_conntrack_expect *exp;
 	struct nf_conn *ct;
 	int err;
@@ -3633,10 +3650,9 @@ ctnetlink_create_expect(struct net *net,
 		return err;
 
 	/* Look for master conntrack of this expectation */
-	h = nf_conntrack_find_get(net, zone, &master_tuple);
-	if (!h)
-		return -ENOENT;
-	ct = nf_ct_tuplehash_to_ctrack(h);
+	ct = ctnetlink_find_get_master(net, zone, &master_tuple);
+	if (IS_ERR(ct))
+		return PTR_ERR(ct);
 
 	rcu_read_lock();
 	exp = ctnetlink_alloc_expect(cda, ct, NULL, &tuple, &mask);
Signature · 1 line
2.47.3
author maintainer
#9 lore raw

PATCH 7/14 netfilter: conntrack: skip unconfirmed entries in /proc/net/nf_conntrack

In reply to Pablo Neira Ayuso

From: Yiran Qiu <[email protected]>

ct_seq_show() takes a reference on a conntrack it found by a lockless walk of the hash table, but never checks that the conntrack is confirmed. nf_conntrack is SLAB_TYPESAFE_BY_RCU, so between ct_get_next() and refcount_inc_not_zero() the entry can be freed and its slot reused by init_conntrack() for a new, unconfirmed conntrack. The increment then succeeds and the dump prints a conntrack that is not in any table. nf_ct_key_equal(), gc_worker_skip_ct() and early_drop() reject unconfirmed entries for this reason.

Since commit 2ad9d7747c10 ("netfilter: conntrack: free extension area immediately") this is also a use-after-free. An unconfirmed conntrack can still grow its extension area, for example when an nft ct helper object attaches a helper, and nf_ct_ext_add() then frees the old ct->ext through krealloc(). seq_print_acct() and ct_show_delta_time() read ct->ext without a lock, so the dump can read the freed buffer and print what it finds there as counters or a time delta.

Skip entries that are not confirmed.

Found with afb-afl, an LLM-driven kernel audit/repro pipeline; the fix and this changelog were also drafted with LLM assistance. Reproduced on a KASAN build of mainline (v7.4-rc3+) that carried timing counters in ct_seq_show() (two ktime_get() per entry) but no added delay: an unprivileged user in its own user and network namespace churns UDP flows through an nft ct helper object while reading /proc/net/nf_conntrack, and KASAN reported a slab-use-after-free in ct_seq_show() after 9 and 41 minutes in two runs. The same build with this patch ran the reproducer for 60 minutes with no report. With only this patch applied to a KASAN build, the conntrack_resize.sh selftest, which compares /proc/net/nf_conntrack with ctnetlink dumps, passed in three runs.

Fixes ea781f197d6a ("netfilter: nf_conntrack: use SLAB_DESTROY_BY_RCU and get rid of call_rcu()")
---
 net/netfilter/nf_conntrack_standalone.c | 3 +++
 1 file changed, 3 insertions(+)
net/netfilter/nf_conntrack_standalone.c +3 -0
index d88a10230862..299691d7ac1e 100644
@@ -314,6 +314,9 @@ static int ct_seq_show(struct seq_file *s, void *v)
 	/* load ->status after refcount increase */
 	smp_acquire__after_ctrl_dep();
 
+	if (!nf_ct_is_confirmed(ct))
+		goto release;
+
 	if (nf_ct_should_gc(ct)) {
 		struct ct_iter_state *st = s->private;
 
Signature · 1 line
2.47.3
author maintainer
#10 lore raw

PATCH 8/14 netfilter: bridge: detach conntrack template on invalid IP frames

In reply to Pablo Neira Ayuso

From: Luxiao Xu <[email protected]>

A bridge rule such as nftables ct zone set can attach a conntrack template with IP_CT_NEW to an skb before nf_ct_bridge_pre() runs. When a frame has an ETH_P_IP or ETH_P_IPV6 protocol, nf_ct_bridge_pre() performs header pull, length trimming, and nf_ct_br_ip_check() / nf_ct_br_ipv6_check() validation before invoking defragmentation and nf_conntrack_in().

If any of those six checks fails, nf_ct_bridge_pre() returns NF_ACCEPT immediately without passing the skb to nf_conntrack_in(), which would normally clear skb->_nfct and drop the template reference on parse failure. Because nft_ct_get_eval() evaluates NFT_CT_STATE from ct and ctinfo before rejecting template objects, the retained template causes malformed, truncated, or wrong-version IP frames to match ct state new instead of ct state invalid.

Jump to a shared error path that calls nf_reset_ct(skb) before returning NF_ACCEPT on all IPv4 and IPv6 header/length rejection paths so the template reference is released and the frame is treated as invalid, even on kernels without downstream template filtering in ct readers.

---
 net/bridge/netfilter/nf_conntrack_bridge.c | 16 ++++++++++------
 1 file changed, 10 insertions(+), 6 deletions(-)
net/bridge/netfilter/nf_conntrack_bridge.c +10 -6
index 8c83dc05114b..11d6183fb11d 100644
@@ -257,28 +257,28 @@ static unsigned int nf_ct_bridge_pre(void *priv, struct sk_buff *skb,
 	switch (skb->protocol) {
 	case htons(ETH_P_IP):
 		if (!pskb_may_pull(skb, sizeof(struct iphdr)))
-			return NF_ACCEPT;
+			goto invalid;
 
 		len = skb_ip_totlen(skb);
 		if (pskb_trim_rcsum(skb, len))
-			return NF_ACCEPT;
+			goto invalid;
 
 		if (nf_ct_br_ip_check(skb))
-			return NF_ACCEPT;
+			goto invalid;
 
 		bridge_state.pf = NFPROTO_IPV4;
 		ret = nf_ct_br_defrag4(skb, &bridge_state);
 		break;
 	case htons(ETH_P_IPV6):
 		if (!pskb_may_pull(skb, sizeof(struct ipv6hdr)))
-			return NF_ACCEPT;
+			goto invalid;
 
 		len = sizeof(struct ipv6hdr) + skb_ipv6_payload_len(skb);
 		if (pskb_trim_rcsum(skb, len))
-			return NF_ACCEPT;
+			goto invalid;
 
 		if (nf_ct_br_ipv6_check(skb))
-			return NF_ACCEPT;
+			goto invalid;
 
 		bridge_state.pf = NFPROTO_IPV6;
 		ret = nf_ct_br_defrag6(skb, &bridge_state);
@@ -293,6 +293,10 @@ static unsigned int nf_ct_bridge_pre(void *priv, struct sk_buff *skb,
 		return ret;
 
 	return nf_conntrack_in(skb, &bridge_state);
+
+invalid:
+	nf_reset_ct(skb);
+	return NF_ACCEPT;
 }
 
 static unsigned int nf_ct_bridge_in(void *priv, struct sk_buff *skb,
Signature · 1 line
2.47.3
author maintainer
#11 lore raw

PATCH 9/14 netfilter: synproxy: fix double tsoff application in server ACK TSecr

In reply to Pablo Neira Ayuso

From: Florian Westphal <[email protected]>

When SYNPROXY is active with timestamp options enabled, the handshake ACK sent to the backend carries a TSecr that is off by synproxy->tsoff.

The code swaps tsval and tsecr before calling synproxy_send_server_ack(). The ACK is built with the correct TSecr (the server's TSval), but it re-enters ipv4_synproxy_hook() on its way out, where synproxy_tstamp_adjust() adds tsoff to TSecr a second time.

Since commit 3ba075278c11 ("tcp: be less liberal in TSEcr received while in SYN_RECV state") Linux TCP performs stricter validation and such backends will drops the ACK. This will delay connection establishment until the server SYN-ACK retransmit, which may take a few seconds.

Replace the swap() by explicit initialisation of tsval/tsecr for both the server and client ACKs. Build the server ACK with TSecr pre-compensated (server TSval - tsoff), so that the adjustment on re-entry yields the server's actual TSval.

---
 net/netfilter/nf_synproxy_core.c | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)
net/netfilter/nf_synproxy_core.c +16 -4
index 9dd681596c70..559db2c972f8 100644
@@ -661,6 +661,7 @@ ipv4_synproxy_hook(void *priv, struct sk_buff *skb,
 	const struct ip_ct_tcp *state;
 	struct tcphdr *th, _th;
 	unsigned int thoff;
+	u32 tsval, tsecr;
 
 	ct = nf_ct_get(skb, &ctinfo);
 	if (!ct)
@@ -742,13 +743,18 @@ ipv4_synproxy_hook(void *priv, struct sk_buff *skb,
 				  NF_SYNPROXY_OPT_WSCALE |
 				  NF_SYNPROXY_OPT_SACK_PERM);
 
-		swap(opts.tsval, opts.tsecr);
+		tsval = opts.tsval;
+		tsecr = opts.tsecr;
+
+		opts.tsval = tsecr;
+		opts.tsecr = tsval - synproxy->tsoff;
 		synproxy_send_server_ack(net, state, skb, th, &opts);
 
 		nf_ct_seqadj_init(ct, ctinfo, synproxy->isn - ntohl(th->seq));
 		nf_conntrack_event_cache(IPCT_SEQADJ, ct);
 
-		swap(opts.tsval, opts.tsecr);
+		opts.tsecr = tsecr;
+		opts.tsval = tsval;
 		synproxy_send_client_ack(net, skb, th, &opts);
 
 		consume_skb(skb);
@@ -1093,6 +1099,7 @@ ipv6_synproxy_hook(void *priv, struct sk_buff *skb,
 	struct synproxy_options opts = {};
 	const struct ip_ct_tcp *state;
 	struct tcphdr *th, _th;
+	u32 tsval, tsecr;
 	__be16 frag_off;
 	u8 nexthdr;
 	int thoff;
@@ -1181,13 +1188,18 @@ ipv6_synproxy_hook(void *priv, struct sk_buff *skb,
 				  NF_SYNPROXY_OPT_WSCALE |
 				  NF_SYNPROXY_OPT_SACK_PERM);
 
-		swap(opts.tsval, opts.tsecr);
+		tsval = opts.tsval;
+		tsecr = opts.tsecr;
+
+		opts.tsval = tsecr;
+		opts.tsecr = tsval - synproxy->tsoff;
 		synproxy_send_server_ack_ipv6(net, state, skb, th, &opts);
 
 		nf_ct_seqadj_init(ct, ctinfo, synproxy->isn - ntohl(th->seq));
 		nf_conntrack_event_cache(IPCT_SEQADJ, ct);
 
-		swap(opts.tsval, opts.tsecr);
+		opts.tsecr = tsecr;
+		opts.tsval = tsval;
 		synproxy_send_client_ack_ipv6(net, skb, th, &opts);
 
 		consume_skb(skb);
Signature · 1 line
2.47.3
author maintainer
#12 lore raw

PATCH 10/14 netfilter: nf_tables: only disable tables on a dormant transition

In reply to Pablo Neira Ayuso

From: Ma Xinmeng <[email protected]>

nf_tables_commit() calls nf_tables_table_disable() for every NEWTABLE transaction that has NFT_TABLE_F_DORMANT set and __NFT_TABLE_F_UPDATE. Since table adoption introduced __NFT_TABLE_F_WAS_ORPHAN, UPDATE no longer implies a dormant state change: re-owning an already dormant PERSIST orphan sets UPDATE because of the adoption, even though the table never left the dormant state. The commit then clears DORMANT, walks the basechains, and unregisters a hook that was never registered, which triggers WARN_ONCE("hook not found") in __nf_unregister_net_hook().

Use __NFT_TABLE_F_WAS_AWAKEN, which records an awake-to-dormant transition, instead of the current DORMANT flag. This skips the disable for an already dormant adopted table while preserving the genuine awake-to-dormant path.

Fixes 31bf508be656 ("netfilter: nf_tables: Implement table adoption support")
---
 net/netfilter/nf_tables_api.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/netfilter/nf_tables_api.c +1 -1
index 8b94b5e7dbdb..b184c739cb67 100644
@@ -11078,7 +11078,7 @@ static int nf_tables_commit(struct net *net, struct sk_buff *skb)
 					nft_trans_destroy(trans);
 					break;
 				}
-				if (table->flags & NFT_TABLE_F_DORMANT)
+				if (table->flags & __NFT_TABLE_F_WAS_AWAKEN)
 					nf_tables_table_disable(net, table);
 
 				table->flags &= ~__NFT_TABLE_F_UPDATE;
Signature · 1 line
2.47.3
author maintainer
#13 lore raw

PATCH 11/14 netfilter: nf_tables: add NFT_HOOK_UNREGISTERED and use it

In reply to Pablo Neira Ayuso

Commit f9a43007d3f7 ("netfilter: nf_tables: double hook unregistration in netns path") fixes a race in the netns exit path with netdev device event handler. The netns pre_exit handler unregisters the hooks, then exit release them. In between this two calls, the netdev event might show up and try to unregister the hooks again. This patch revisit this fix by adding a new NFT_HOOK_UNREGISTERED flag which allows us to skip the hook from the netdevice and flowtable event handlers.

This patch is a prerequisit for another follow up fix for the flowtable hardware offload which allows to unregister the flow_block once the entries in hardware have been removed.

---
 include/net/netfilter/nf_tables.h |  3 +-
 net/netfilter/nf_tables_api.c     | 53 +++++++++++++++----------------
 net/netfilter/nft_chain_filter.c  |  6 ++--
 3 files changed, 31 insertions(+), 31 deletions(-)
include/net/netfilter/nf_tables.h +2 -1
index 9d597482363d..5edff5d7dacd 100644
@@ -1209,7 +1209,8 @@ struct nft_stats {
 	struct u64_stats_sync	syncp;
 };
 
-#define NFT_HOOK_REMOVE	(1 << 0)
+#define NFT_HOOK_REMOVE		(1 << 0)
+#define NFT_HOOK_UNREGISTERED	(1 << 1)
 
 struct nft_hook {
 	struct list_head	list;
net/netfilter/nf_tables_api.c +25 -28

142 lines not on this page · raw message

net/netfilter/nft_chain_filter.c +4 -2
index e04e689f2228..ffbf5dad3139 100644
@@ -337,7 +337,8 @@ static int nft_netdev_event(unsigned long event, struct net_device *dev,
 			if (!ops || (changename && match))
 				continue;
 
-			if (!(table->flags & NFT_TABLE_F_DORMANT))
+			if (!(table->flags & NFT_TABLE_F_DORMANT) &&
+			    !(hook->flags & NFT_HOOK_UNREGISTERED))
 				nf_unregister_net_hook(dev_net(dev), ops);
 
 			list_del_rcu(&ops->list);
@@ -356,7 +357,8 @@ static int nft_netdev_event(unsigned long event, struct net_device *dev,
 
 			ops->dev = dev;
 
-			if (!(table->flags & NFT_TABLE_F_DORMANT) &&
+			if ((!(table->flags & NFT_TABLE_F_DORMANT) &&
+			     !(hook->flags & NFT_HOOK_UNREGISTERED)) &&
 			    nf_register_net_hook(dev_net(dev), ops)) {
 				kfree(ops);
 				return 1;
Signature · 1 line
2.47.3
author maintainer
#14 lore raw

PATCH 12/14 netfilter: nf_tables: unbind flowtable on hook release

In reply to Pablo Neira Ayuso

Commit 13210fc63f35 ("netfilter: nf_tables: imbalance in flowtable binding") breaks hardware offload by unbinding the flow_block too early, this results in leaving entries in the hardware. Any pending offload work will be ignored because there is no flow_block anymore in place.

This patch restores the strategy followed by commit 5acab91458ce ("netfilter: nf_tables: unbind callbacks from flowtable destroy path") by unregistering the hook first, then unbind the flow_block from the error and destroy paths, right before the hook is released.

Fixes 13210fc63f35 ("netfilter: nf_tables: imbalance in flowtable binding")
---
 net/netfilter/nf_tables_api.c | 65 +++++++++++++++++++++++++----------
 1 file changed, 47 insertions(+), 18 deletions(-)
net/netfilter/nf_tables_api.c +47 -18
index c19cf6d8cd0b..0189375e4063 100644
@@ -380,6 +380,22 @@ static void nft_netdev_hook_unlink_free_rcu(struct nft_hook *hook)
 	nft_netdev_hook_free_rcu(hook);
 }
 
+static void nft_flowtable_hook_unlink_free_rcu(struct nft_flowtable *flowtable,
+					       struct nft_hook *hook)
+{
+	struct nf_hook_ops *ops;
+
+	/* This unbind command needs to come this late, otherwise offload
+	 * worker finds no flow_block and entries are not cleaned up from
+	 * hardware.
+	 */
+	list_for_each_entry(ops, &hook->ops_list, list) {
+		flowtable->data.type->setup(&flowtable->data, ops->dev,
+					    FLOW_BLOCK_UNBIND);
+	}
+	nft_netdev_hook_unlink_free_rcu(hook);
+}
+
 static void nft_trans_hook_destroy(struct nft_trans_hook *trans_hook)
 {
 	list_del(&trans_hook->list);
@@ -9026,12 +9042,9 @@ nft_flowtable_type_get(struct net *net, u8 family)
 
 /* Only called from error and netdev event paths. */
 static void nft_unregister_flowtable_ops(struct net *net,
-					 struct nft_flowtable *flowtable,
 					 struct nf_hook_ops *ops)
 {
 	nf_unregister_net_hook(net, ops);
-	flowtable->data.type->setup(&flowtable->data, ops->dev,
-				    FLOW_BLOCK_UNBIND);
 }
 
 static void __nft_unregister_flowtable_net_hooks(struct net *net,
@@ -9043,7 +9056,7 @@ static void __nft_unregister_flowtable_net_hooks(struct net *net,
 
 	list_for_each_entry_safe(hook, next, hook_list, list) {
 		list_for_each_entry(ops, &hook->ops_list, list)
-			nft_unregister_flowtable_ops(net, flowtable, ops);
+			nft_unregister_flowtable_ops(net, ops);
 
 		hook->flags |= NFT_HOOK_UNREGISTERED;
 	}
@@ -9114,7 +9127,9 @@ static int nft_register_flowtable_net_hooks(struct net *net,
 			if (i-- <= 0)
 				break;
 
-			nft_unregister_flowtable_ops(net, flowtable, ops);
+			nft_unregister_flowtable_ops(net, ops);
+			flowtable->data.type->setup(&flowtable->data, ops->dev,
+						    FLOW_BLOCK_UNBIND);
 		}
 		nft_netdev_hook_unlink_free_rcu(hook);
 	}
@@ -9141,9 +9156,9 @@ static void nft_flowtable_unregister_trans_hook(struct net *net,
 	list_for_each_entry_safe(trans_hook, next, hook_list, list) {
 		hook = trans_hook->hook;
 		list_for_each_entry(ops, &hook->ops_list, list)
-			nft_unregister_flowtable_ops(net, flowtable, ops);
+			nft_unregister_flowtable_ops(net, ops);
 
-		nft_netdev_hook_unlink_free_rcu(hook);
+		nft_flowtable_hook_unlink_free_rcu(flowtable, trans_hook->hook);
 		nft_trans_hook_destroy(trans_hook);
 	}
 }
@@ -9229,9 +9244,11 @@ static int nft_flowtable_update(struct nft_ctx *ctx, const struct nlmsghdr *nlh,
 err_flowtable_update_hook:
 	list_for_each_entry_safe(hook, next, &flowtable_hook.list, list) {
 		if (unregister) {
-			list_for_each_entry(ops, &hook->ops_list, list)
-				nft_unregister_flowtable_ops(ctx->net,
-							     flowtable, ops);
+			list_for_each_entry(ops, &hook->ops_list, list) {
+				nft_unregister_flowtable_ops(ctx->net, ops);
+				flowtable->data.type->setup(&flowtable->data, ops->dev,
+							    FLOW_BLOCK_UNBIND);
+			}
 		}
 		nft_netdev_hook_unlink_free_rcu(hook);
 	}
@@ -9752,10 +9769,19 @@ static void nf_tables_flowtable_notify(struct nft_ctx *ctx,
 	nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
 }
 
+static void nft_flowtable_hooks_destroy(struct nft_flowtable *flowtable,
+					struct list_head *hook_list)
+{
+	struct nft_hook *hook, *next;
+
+	list_for_each_entry_safe(hook, next, hook_list, list)
+		nft_flowtable_hook_unlink_free_rcu(flowtable, hook);
+}
+
 static void nf_tables_flowtable_destroy(struct nft_flowtable *flowtable)
 {
 	flowtable->data.type->free(&flowtable->data);
-	nft_hooks_destroy(&flowtable->hook_list);
+	nft_flowtable_hooks_destroy(flowtable, &flowtable->hook_list);
 	kfree(flowtable->name);
 	module_put(flowtable->data.type->owner);
 	kfree(flowtable);
@@ -9830,10 +9856,11 @@ static int nft_flowtable_event(unsigned long event, struct net_device *dev,
 				continue;
 
 			/* flow_offload_netdev_event() cleans up entries for us. */
-			if (!(hook->flags & NFT_HOOK_UNREGISTERED)) {
-				nft_unregister_flowtable_ops(dev_net(dev),
-							     flowtable, ops);
-			}
+			if (!(hook->flags & NFT_HOOK_UNREGISTERED))
+				nft_unregister_flowtable_ops(dev_net(dev), ops);
+
+			flowtable->data.type->setup(&flowtable->data, ops->dev,
+						    FLOW_BLOCK_UNBIND);
 			list_del_rcu(&ops->list);
 			kfree_rcu(ops, rcu);
 			break;
@@ -11311,10 +11338,12 @@ static void nf_tables_abort_release(struct nft_trans *trans)
 		nft_obj_destroy(&ctx, nft_trans_obj(trans));
 		break;
 	case NFT_MSG_NEWFLOWTABLE:
-		if (nft_trans_flowtable_update(trans))
-			nft_hooks_destroy(&nft_trans_flowtable_hooks(trans));
-		else
+		if (nft_trans_flowtable_update(trans)) {
+			nft_flowtable_hooks_destroy(nft_trans_flowtable(trans),
+						    &nft_trans_flowtable_hooks(trans));
+		} else {
 			nf_tables_flowtable_destroy(nft_trans_flowtable(trans));
+		}
 		break;
 	}
 	kfree(trans);
Signature · 1 line
2.47.3
author maintainer
#15 lore raw

PATCH 13/14 netfilter: nf_tables: flush destroy work from flowtable netdev event handler

In reply to Pablo Neira Ayuso

Sashiko reports that the following race is possible while dismantling the flowtable with hardware offload:

CPU0 CPU1 (kworker)
nf_tables_commit()
list_del_rcu(&flowtable->list)
nft_unregister_flowtable_net_hooks()
nf_tables_commit_release()
schedule_work(&destroy_work)
mutex_unlock(&commit_mutex)

                                      nf_tables_trans_destroy_work()
                                        synchronize_rcu()
                                        ...

unregister_netdevice()
nf_tables_flowtable_event()
/* flowtable not in
* table->flowtables, ops->dev
* stays on flowtable->hook_list
*/
free_netdev(dev)

                                        nf_tables_flowtable_destroy()
                                          nft_flowtable_hooks_destroy()
                                            ...
                                            flowtable->data.type->setup(
                                              ..., ops->dev,
                                              FLOW_BLOCK_UNBIND)
                                              <-- use-after-free

A netdevice event could happen in between the commit and commit_release. After commit, the flowtable has been removed from the table list, therefore, it is not reachable by the flowtable netdevice handler so the hook cannot be unregistered and a stale reference to the netdevice remains in place, leading to possible UaF from the commit_release path when accessing the netdevice.

Fix this by flushing the pending destroy work before handling netdevice events.

---
 net/netfilter/nf_tables_api.c | 2 ++
 1 file changed, 2 insertions(+)
net/netfilter/nf_tables_api.c +2 -0
index 0189375e4063..9ea8789f5664 100644
@@ -9929,6 +9929,8 @@ static int nf_tables_flowtable_event(struct notifier_block *this,
 	nft_net = nft_pernet(net);
 	mutex_lock(&nft_net->commit_mutex);
 
+	nf_tables_trans_destroy_flush_work(net);
+
 	if (event == NETDEV_CHANGENAME) {
 		if (__nf_tables_flowtable_event(NETDEV_REGISTER, dev, true)) {
 			ret = NOTIFY_BAD;
Signature · 1 line
2.47.3
author maintainer
#16 lore raw

PATCH 14/14 netfilter: ipv6: stop the conntrack fragment search at AH

In reply to Pablo Neira Ayuso

From: Ryosuke Iwahashi <[email protected]>

find_prev_fhdr() looks beyond an IPv6 Authentication Header (AH) for a Fragment header. Reassembly there can change data covered by AH before IPv6 input processes AH.

Stop the search at AH. Conntrack still reassembles fragments when the Fragment header precedes AH.

Fixes 6aafeef03b9d ("netfilter: push reasm skb through instead of original frag skbs")
---
 net/ipv6/netfilter/nf_conntrack_reasm.c | 9 +++------
 1 file changed, 3 insertions(+), 6 deletions(-)
net/ipv6/netfilter/nf_conntrack_reasm.c +3 -6
index f25ff2a12a82..893b250b99f9 100644
@@ -410,9 +410,9 @@ find_prev_fhdr(struct sk_buff *skb, u8 *prevhdrp, int *prevhoff, int *fhoff)
 		struct ipv6_opt_hdr hdr;
 		int hdrlen;
 
-		if (!ipv6_ext_hdr(nexthdr)) {
+		/* Leave headers beyond AH for the authenticated input path. */
+		if (!ipv6_ext_hdr(nexthdr) || nexthdr == NEXTHDR_AUTH)
 			return -1;
-		}
 		if (nexthdr == NEXTHDR_NONE) {
 			pr_debug("next header is none\n");
 			return -1;
@@ -423,10 +423,7 @@ find_prev_fhdr(struct sk_buff *skb, u8 *prevhdrp, int *prevhoff, int *fhoff)
 		}
 		if (skb_copy_bits(skb, start, &hdr, sizeof(hdr)))
 			return -1;
-		if (nexthdr == NEXTHDR_AUTH)
-			hdrlen = ipv6_authlen(&hdr);
-		else
-			hdrlen = ipv6_optlen(&hdr);
+		hdrlen = ipv6_optlen(&hdr);
 
 		prevhdr = nexthdr;
 		prev_nhoff = start;
Signature · 1 line
2.47.3