Skip to contentSkip to conversation

bpf: Guard conntrack opts error writes

PATCH Superseded Yiyang Chen 6 participants 13 messages Jun 16 – Jun 22

Subsystems (6)
lore
Share & tools
lore
#0 lore raw

cover bpf: Guard conntrack opts error writes

The conntrack lookup/allocation kfuncs expose an opts/opts__sz pair. The verifier checks the caller-provided opts__sz range, but the wrappers currently write opts->error after internal errors even when opts__sz is too small to include that field.

Patch 1 writes opts->error only when opts__sz includes it. Patch 2 adds a bpf_nf regression check that keeps a guard in opts->error while passing opts__sz covering only netns_id.

The regression check follows the existing bpf_nf test shape. Before the fix, the guard is overwritten with -EINVAL even though opts__sz covers only the first four bytes of the options object. After the fix, the kfunc still returns NULL for the invalid size, but the guard remains intact.

Validation, rebased and tested on bpf-next master e4287bf34f97 ("selftests/bpf: Work around llvm stack overflow in crypto progs"):

  git diff --check origin/master..HEAD: OK
  scripts/checkpatch.pl --strict on 1/2 and 2/2: OK
  make O=/root/ebpf-verifier-bug-detection/kernel-build/bpf-next \
    net/netfilter/nf_conntrack_bpf.o: OK
  git am of exported 1/2 and 2/2 on a fresh worktree at base: OK
  range-diff between branch commits and git-am result: equivalent

The local direct clang build of test_bpf_nf.c is blocked by the local kernel BTF/config: this environment's generated vmlinux.h lacks struct nf_conn.mark, which is used by pre-existing test_bpf_nf.c code. The changed kernel object and generated patch application were validated.

Yiyang Chen (2):
bpf: Guard conntrack opts error writes selftests/bpf: Cover small conntrack opts error writes

 net/netfilter/nf_conntrack_bpf.c              | 17 +++++++++---
 .../testing/selftests/bpf/prog_tests/bpf_nf.c |  6 +++++
 .../testing/selftests/bpf/progs/test_bpf_nf.c | 26 +++++++++++++++++++
 3 files changed, 45 insertions(+), 4 deletions(-)

base-commit: e4287bf34f97a88c7d9322f5bde828724c073a6b

Signature · 1 line
2.34.1
#1 lore raw

PATCH 1/2 bpf: Guard conntrack opts error writes

The conntrack lookup and allocation kfuncs take an opts pointer together with an opts__sz argument. The verifier checks only the memory range described by opts__sz, but the wrappers unconditionally write opts->error whenever the internal lookup or allocation helper returns an error.

For an invalid size smaller than the end of opts->error, that write can land outside the verifier-checked range. Keep returning NULL for invalid arguments, but only report the error through opts->error when the supplied size includes the field.

This preserves error reporting for the supported 12-byte and 16-byte layouts, and for other invalid sizes that still include opts->error.

Fixes b4c2b9593a1c ("net/netfilter: Add unstable CT lookup helpers for XDP and TC-BPF")
Fixes d7e79c97c00c ("net: netfilter: Add kfuncs to allocate and insert CT")
---
 net/netfilter/nf_conntrack_bpf.c | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)
net/netfilter/nf_conntrack_bpf.c +13 -4
index 40c261cd0af38..3c182024ec509 100644
@@ -65,6 +65,11 @@ enum {
 	NF_BPF_CT_OPTS_SZ = 16,
 };
 
+static bool bpf_ct_opts_has_error(u32 opts_len)
+{
+	return opts_len >= offsetofend(struct bpf_ct_opts, error);
+}
+
 static int bpf_nf_ct_tuple_parse(struct bpf_sock_tuple *bpf_tuple,
 				 u32 tuple_len, u8 protonum, u8 dir,
 				 struct nf_conntrack_tuple *tuple)
@@ -298,7 +303,8 @@ bpf_xdp_ct_alloc(struct xdp_md *xdp_ctx, struct bpf_sock_tuple *bpf_tuple,
 	nfct = __bpf_nf_ct_alloc_entry(dev_net(ctx->rxq->dev), bpf_tuple, tuple__sz,
 				       opts, opts__sz, 10);
 	if (IS_ERR(nfct)) {
-		opts->error = PTR_ERR(nfct);
+		if (bpf_ct_opts_has_error(opts__sz))
+			opts->error = PTR_ERR(nfct);
 		return NULL;
 	}
 
@@ -332,7 +338,8 @@ bpf_xdp_ct_lookup(struct xdp_md *xdp_ctx, struct bpf_sock_tuple *bpf_tuple,
 	caller_net = dev_net(ctx->rxq->dev);
 	nfct = __bpf_nf_ct_lookup(caller_net, bpf_tuple, tuple__sz, opts, opts__sz);
 	if (IS_ERR(nfct)) {
-		opts->error = PTR_ERR(nfct);
+		if (bpf_ct_opts_has_error(opts__sz))
+			opts->error = PTR_ERR(nfct);
 		return NULL;
 	}
 	return nfct;
@@ -364,7 +371,8 @@ bpf_skb_ct_alloc(struct __sk_buff *skb_ctx, struct bpf_sock_tuple *bpf_tuple,
 	net = skb->dev ? dev_net(skb->dev) : sock_net(skb->sk);
 	nfct = __bpf_nf_ct_alloc_entry(net, bpf_tuple, tuple__sz, opts, opts__sz, 10);
 	if (IS_ERR(nfct)) {
-		opts->error = PTR_ERR(nfct);
+		if (bpf_ct_opts_has_error(opts__sz))
+			opts->error = PTR_ERR(nfct);
 		return NULL;
 	}
 
@@ -398,7 +406,8 @@ bpf_skb_ct_lookup(struct __sk_buff *skb_ctx, struct bpf_sock_tuple *bpf_tuple,
 	caller_net = skb->dev ? dev_net(skb->dev) : sock_net(skb->sk);
 	nfct = __bpf_nf_ct_lookup(caller_net, bpf_tuple, tuple__sz, opts, opts__sz);
 	if (IS_ERR(nfct)) {
-		opts->error = PTR_ERR(nfct);
+		if (bpf_ct_opts_has_error(opts__sz))
+			opts->error = PTR_ERR(nfct);
 		return NULL;
 	}
 	return nfct;
Signature · 1 line
2.34.1
#2 lore raw
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] TOCTOU Vulnerability / Use-After-Free due to multiple reads of BPF-provided opts->netns_id --

commit 8efa13ac7f8992d846ab4af35e05c540c530390f
Author: Yiyang Chen <[email protected]>

bpf: Guard conntrack opts error writes

This commit updates the BPF conntrack lookup and allocation wrappers to conditionally write to opts->error. It ensures the write only occurs if the provided opts__sz is large enough to include the error field.

Quoted 4 lines
net/netfilter/nf_conntrack_bpf.c +0 -0
index 40c261cd0af38..3c182024ec509 100644

[ ... ]

net/netfilter/nf_conntrack_bpf.c bpf_xdp_ct_alloc(struct xdp_md *xdp_ctx, struct bpf_sock_tuple *bpf_tuple, · line 304

Quoted 3 lines
net/netfilter/nf_conntrack_bpf.c +0 -0
@@ -298,7 +303,8 @@ bpf_xdp_ct_alloc(struct xdp_md *xdp_ctx, struct bpf_sock_tuple *bpf_tuple,
 	nfct = __bpf_nf_ct_alloc_entry(dev_net(ctx->rxq->dev), bpf_tuple, tuple__sz,
 				       opts, opts__sz, 10);

[Severity: High]
This is a pre-existing issue, but does __bpf_nf_ct_alloc_entry() (and similarly __bpf_nf_ct_lookup()) have a time-of-check to time-of-use (TOCTOU) vulnerability regarding opts->netns_id?

The BPF verifier allows the opts argument to point to memory that can be concurrently modified by a BPF program. Inside __bpf_nf_ct_alloc_entry(), opts->netns_id is read multiple times:

net/netfilter/nf_conntrack_bpf.c:__bpf_nf_ct_alloc_entry() {
    ...
    if (opts->netns_id >= 0) {
        net = get_net_ns_by_id(net, opts->netns_id);
    ...
out:
    if (opts->netns_id >= 0)
        put_net(net);
}

Since function calls like get_net_ns_by_id() act as compiler barriers, the value will be reloaded from memory. If a concurrent thread modifies opts->netns_id from a negative value to a valid ID between the initial check and the final put_net() check, could the function drop a reference it never acquired, leading to a refcount underflow and use-after-free?

Similarly, changing it from a valid ID to a negative value could cause a reference leak. Could we cache the value of opts->netns_id in a local variable to ensure the same value is used for both checks?

Quoted 7 lines
net/netfilter/nf_conntrack_bpf.c +2 -1
 	if (IS_ERR(nfct)) {
-		opts->error = PTR_ERR(nfct);
+		if (bpf_ct_opts_has_error(opts__sz))
+			opts->error = PTR_ERR(nfct);
 		return NULL;
 	}
 
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw
In reply to Yiyang Chen
Quoted 38 lines · Yiyang Chen

The conntrack lookup and allocation kfuncs take an opts pointer together with an opts__sz argument. The verifier checks only the memory range described by opts__sz, but the wrappers unconditionally write opts->error whenever the internal lookup or allocation helper returns an error.

For an invalid size smaller than the end of opts->error, that write can land outside the verifier-checked range. Keep returning NULL for invalid arguments, but only report the error through opts->error when the supplied size includes the field.

This preserves error reporting for the supported 12-byte and 16-byte layouts, and for other invalid sizes that still include opts->error.

Fixes b4c2b9593a1c ("net/netfilter: Add unstable CT lookup helpers for XDP and TC-BPF")
Fixes d7e79c97c00c ("net: netfilter: Add kfuncs to allocate and insert CT")
---
 net/netfilter/nf_conntrack_bpf.c | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)
net/netfilter/nf_conntrack_bpf.c +5 -0
index 40c261cd0af38..3c182024ec509 100644
@@ -65,6 +65,11 @@ enum {
 	NF_BPF_CT_OPTS_SZ = 16,
 };
 
+static bool bpf_ct_opts_has_error(u32 opts_len)
+{
+	return opts_len >= offsetofend(struct bpf_ct_opts, error);
+}
+
 static int bpf_nf_ct_tuple_parse(struct bpf_sock_tuple *bpf_tuple,
 				 u32 tuple_len, u8 protonum, u8 dir,
 				 struct nf_conntrack_tuple *tuple)

net/netfilter/nf_conntrack_bpf.c bpf_xdp_ct_alloc(struct xdp_md *xdp_ctx, struct bpf_sock_tuple *bpf_tuple, · line 307

Quoted 6 lines
net/netfilter/nf_conntrack_bpf.c +2 -1
@@ -298,7 +303,8 @@ bpf_xdp_ct_alloc(struct xdp_md *xdp_ctx, struct bpf_sock_tuple *bpf_tuple,
 	nfct = __bpf_nf_ct_alloc_entry(dev_net(ctx->rxq->dev), bpf_tuple, tuple__sz,
 				       opts, opts__sz, 10);
 	if (IS_ERR(nfct)) {
-		opts->error = PTR_ERR(nfct);
+		if (bpf_ct_opts_has_error(opts__sz))
+			opts->error = PTR_ERR(nfct);

LLMs have no taste.

Above two lines could have been one helper
bpf_ct_opts_set_error(opts, opts__sz, PTR_ERR(nfct));

Or we can do a step further and simplify the code more. Turn this:

   if (IS_ERR(nfct)) {
           opts->error = PTR_ERR(nfct);
           return NULL;

}
return (struct nf_conn___init *)nfct;
into:
return (struct nf_conn___init *)bpf_ct_opts_result(opts, opts__sz, nfct);

static void *bpf_ct_opts_result(struct bpf_ct_opts *opts, u32 opts__sz, void *ret) {
if (!IS_ERR(ret))

    return ret;
  if (opts__sz >= offsetofend(struct bpf_ct_opts, error))
    opts->error = PTR_ERR(ret);

return NULL;
}

This kind of small improvements should be obvious to any human developer. Please do NOT send us patches straight out of LLM.
Review it first and think how to improve it.

pw-bot: cr

#4 lore raw

PATCH 2/2 selftests/bpf: Cover small conntrack opts error writes

In reply to Yiyang Chen

Add a conntrack kfunc regression check for opts__sz values that do not cover opts->error. The BPF program initializes opts->error with a guard value, calls the lookup and allocation kfuncs with opts__sz set to sizeof(opts->netns_id), and verifies that the guard is still intact after the kfunc returns NULL.

Without the conntrack wrapper guard, the kfunc error path overwrites that guard with -EINVAL even though the verifier checked only the first four bytes of the options object.

---
 .../testing/selftests/bpf/prog_tests/bpf_nf.c |  6 +++++
 .../testing/selftests/bpf/progs/test_bpf_nf.c | 26 +++++++++++++++++++
 2 files changed, 32 insertions(+)
tools/testing/selftests/bpf/prog_tests/bpf_nf.c +6 -0
index b33dba4b126e2..14d4c1793aed5 100644
@@ -5,6 +5,8 @@
 #include "test_bpf_nf.skel.h"
 #include "test_bpf_nf_fail.skel.h"
 
+#define CT_OPTS_ERROR_GUARD 0x12345678
+
 static char log_buf[1024 * 1024];
 
 struct {
@@ -119,6 +121,10 @@ static void test_bpf_nf_ct(int mode)
 	ASSERT_EQ(skel->bss->test_einval_reserved_new, -EINVAL, "Test EINVAL for reserved in new struct not set to 0");
 	ASSERT_EQ(skel->bss->test_einval_netns_id, -EINVAL, "Test EINVAL for netns_id < -1");
 	ASSERT_EQ(skel->bss->test_einval_len_opts, -EINVAL, "Test EINVAL for len__opts != NF_BPF_CT_OPTS_SZ");
+	ASSERT_EQ(skel->bss->test_einval_len_opts_small_lookup, CT_OPTS_ERROR_GUARD,
+		  "Test no error write for lookup opts__sz before error field");
+	ASSERT_EQ(skel->bss->test_einval_len_opts_small_alloc, CT_OPTS_ERROR_GUARD,
+		  "Test no error write for alloc opts__sz before error field");
 	ASSERT_EQ(skel->bss->test_eproto_l4proto, -EPROTO, "Test EPROTO for l4proto != TCP or UDP");
 	ASSERT_EQ(skel->bss->test_enonet_netns_id, -ENONET, "Test ENONET for bad but valid netns_id");
 	ASSERT_EQ(skel->bss->test_enoent_lookup, -ENOENT, "Test ENOENT for failed lookup");
tools/testing/selftests/bpf/progs/test_bpf_nf.c +26 -0
index 076fbf03a1268..df43649ecb785 100644
@@ -10,6 +10,8 @@
 #define EINVAL 22
 #define ENOENT 2
 
+#define CT_OPTS_ERROR_GUARD 0x12345678
+
 #define NF_CT_ZONE_DIR_ORIG (1 << IP_CT_DIR_ORIGINAL)
 #define NF_CT_ZONE_DIR_REPL (1 << IP_CT_DIR_REPLY)
 
@@ -19,6 +21,8 @@ int test_einval_reserved = 0;
 int test_einval_reserved_new = 0;
 int test_einval_netns_id = 0;
 int test_einval_len_opts = 0;
+int test_einval_len_opts_small_lookup = 0;
+int test_einval_len_opts_small_alloc = 0;
 int test_eproto_l4proto = 0;
 int test_enonet_netns_id = 0;
 int test_enoent_lookup = 0;
@@ -124,6 +128,28 @@ nf_ct_test(struct nf_conn *(*lookup_fn)(void *, struct bpf_sock_tuple *, u32,
 	else
 		test_einval_len_opts = opts_def.error;
 
+	opts_def.error = CT_OPTS_ERROR_GUARD;
+	ct = lookup_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,
+		       sizeof(opts_def.netns_id));
+	if (ct) {
+		bpf_ct_release(ct);
+		test_einval_len_opts_small_lookup = -EINVAL;
+	} else {
+		test_einval_len_opts_small_lookup = opts_def.error;
+	}
+
+	opts_def.error = CT_OPTS_ERROR_GUARD;
+	ct = alloc_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,
+		      sizeof(opts_def.netns_id));
+	if (ct) {
+		ct = bpf_ct_insert_entry(ct);
+		if (ct)
+			bpf_ct_release(ct);
+		test_einval_len_opts_small_alloc = -EINVAL;
+	} else {
+		test_einval_len_opts_small_alloc = opts_def.error;
+	}
+
 	opts_def.l4proto = IPPROTO_ICMP;
 	ct = lookup_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,
 		       sizeof(opts_def));
Signature · 1 line
2.34.1
#5 lore raw

Re: [PATCH bpf-next 2/2] selftests/bpf: Cover small conntrack opts error writes

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] Missing bounds check for the enum parameter manip in the bpf_ct_set_nat_info kfunc allows a BPF program to pass an arbitrary value, triggering a WARN_ON and corrupting the conntrack state. --

commit a2c96d6b406da0481952334b633ba64cd47d26da
Author: Yiyang Chen <[email protected]>

selftests/bpf: Cover small conntrack opts error writes

This commit adds a conntrack kfunc regression check for opts__sz values that do not cover opts->error. It verifies that the guard value remains intact when the kfunc returns NULL due to an error.

Quoted 4 lines
tools/testing/selftests/bpf/progs/test_bpf_nf.c +0 -0
index 076fbf03a1268..df43649ecb785 100644

[ ... ]

Quoted 16 lines
tools/testing/selftests/bpf/progs/test_bpf_nf.c +12 -0
@@ -124,6 +128,28 @@ nf_ct_test(struct nf_conn *(*lookup_fn)(void *, struct bpf_sock_tuple *, u32,
 	else
 		test_einval_len_opts = opts_def.error;
 
+	opts_def.error = CT_OPTS_ERROR_GUARD;
+	ct = lookup_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,
+		       sizeof(opts_def.netns_id));
+	if (ct) {
+		bpf_ct_release(ct);
+		test_einval_len_opts_small_lookup = -EINVAL;
+	} else {
+		test_einval_len_opts_small_lookup = opts_def.error;
+	}
+
+	opts_def.error = CT_OPTS_ERROR_GUARD;
+	ct = alloc_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,

tools/testing/selftests/bpf/progs/test_bpf_nf.c nf_ct_test(struct nf_conn *(*lookup_fn)(void *, struct bpf_sock_tuple *, u32, · line 152

Quoted 10 lines
tools/testing/selftests/bpf/progs/test_bpf_nf.c +10 -0
+		      sizeof(opts_def.netns_id));
+	if (ct) {
+		ct = bpf_ct_insert_entry(ct);
+		if (ct)
+			bpf_ct_release(ct);
+		test_einval_len_opts_small_alloc = -EINVAL;
+	} else {
+		test_einval_len_opts_small_alloc = opts_def.error;
+	}
+

[Severity: High]
This is a pre-existing issue, but while reviewing these conntrack kfunc tests I noticed that bpf_ct_set_nat_info() lacks a bounds check for the manip enum parameter.

Since the BPF verifier does not check the range of enum values passed to kfuncs unless they are annotated with __const, could a BPF program pass an arbitrary scalar value for the manip parameter?

Looking at net/netfilter/nf_nat_bpf.c:bpf_ct_set_nat_info():

    __bpf_kfunc int bpf_ct_set_nat_info(struct nf_conn___init *nfct,
                                        union nf_inet_addr *addr, int port,
                                        enum nf_nat_manip_type manip)
    {
        ...
        return nf_nat_setup_info(ct, &range, manip) == NF_DROP ? -ENOMEM : 0;
    }

If an invalid value is passed directly to nf_nat_setup_info(), would it trigger the WARN_ON(maniptype != NF_NAT_MANIP_SRC && maniptype != NF_NAT_MANIP_DST) and fall through the default branches?

It seems this could result in the connection status being inconsistently set, potentially corrupting the conntrack state or acting as a local denial of service vector if panic_on_warn is enabled.

Quoted 3 lines
tools/testing/selftests/bpf/progs/test_bpf_nf.c +0 -0
 	opts_def.l4proto = IPPROTO_ICMP;
 	ct = lookup_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,
 		       sizeof(opts_def));
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#6 lore raw

Re: [PATCH bpf-next 2/2] selftests/bpf: Cover small conntrack opts error writes

In reply to Yiyang Chen
This is a regression test for the out-of-bounds opts->error write that is fixed in the prior series commit 86b813c37ee5 ("bpf: Guard conntrack opts error writes"), but it carries no Fixes: tags.
Quoted 8 lines

selftests/bpf: Cover small conntrack opts error writes

Add a conntrack kfunc regression check for opts__sz values that do not cover opts->error. The BPF program initializes opts->error with a guard value, calls the lookup and allocation kfuncs with opts__sz set to sizeof(opts->netns_id), and verifies that the guard is still intact after the kfunc returns NULL.

Quoted 5 lines

Without the conntrack wrapper guard, the kfunc error path overwrites that guard with -EINVAL even though the verifier checked only the first four bytes of the options object.

This is a regression test for the out-of-bounds opts->error write that is fixed in the prior series commit 86b813c37ee5 ("bpf: Guard conntrack opts error writes"), but it carries no Fixes: tags.

A regression test usually carries the same Fixes: tags as the fix it covers, so it gets backported to stable alongside that fix. The two new test cases map onto the two commits that introduced the kfuncs: the small-opts lookup case covers the lookup kfunc and the small-opts alloc case covers the alloc kfunc.

Should this include:

Fixes b4c2b9593a1c ("net/netfilter: Add unstable CT lookup helpers for XDP and TC-BPF")
Fixes d7e79c97c00c ("net: netfilter: Add kfuncs to allocate and insert CT")

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/27597459087

reviewer Reviewed-by on v1 2/2
#7 lore raw

Re: [PATCH bpf-next 2/2] selftests/bpf: Cover small conntrack opts error writes

In reply to Yiyang Chen
Quoted 11 lines · Yiyang Chen

Add a conntrack kfunc regression check for opts__sz values that do not cover opts->error. The BPF program initializes opts->error with a guard value, calls the lookup and allocation kfuncs with opts__sz set to sizeof(opts->netns_id), and verifies that the guard is still intact after the kfunc returns NULL.

Without the conntrack wrapper guard, the kfunc error path overwrites that guard with -EINVAL even though the verifier checked only the first four bytes of the options object.

Quoted 80 lines
---
 .../testing/selftests/bpf/prog_tests/bpf_nf.c |  6 +++++
 .../testing/selftests/bpf/progs/test_bpf_nf.c | 26 +++++++++++++++++++
 2 files changed, 32 insertions(+)
tools/testing/selftests/bpf/prog_tests/bpf_nf.c +6 -0
index b33dba4b126e2..14d4c1793aed5 100644
@@ -5,6 +5,8 @@
 #include "test_bpf_nf.skel.h"
 #include "test_bpf_nf_fail.skel.h"
 
+#define CT_OPTS_ERROR_GUARD 0x12345678
+
 static char log_buf[1024 * 1024];
 
 struct {
@@ -119,6 +121,10 @@ static void test_bpf_nf_ct(int mode)
 	ASSERT_EQ(skel->bss->test_einval_reserved_new, -EINVAL, "Test EINVAL for reserved in new struct not set to 0");
 	ASSERT_EQ(skel->bss->test_einval_netns_id, -EINVAL, "Test EINVAL for netns_id < -1");
 	ASSERT_EQ(skel->bss->test_einval_len_opts, -EINVAL, "Test EINVAL for len__opts != NF_BPF_CT_OPTS_SZ");
+	ASSERT_EQ(skel->bss->test_einval_len_opts_small_lookup, CT_OPTS_ERROR_GUARD,
+		  "Test no error write for lookup opts__sz before error field");
+	ASSERT_EQ(skel->bss->test_einval_len_opts_small_alloc, CT_OPTS_ERROR_GUARD,
+		  "Test no error write for alloc opts__sz before error field");
 	ASSERT_EQ(skel->bss->test_eproto_l4proto, -EPROTO, "Test EPROTO for l4proto != TCP or UDP");
 	ASSERT_EQ(skel->bss->test_enonet_netns_id, -ENONET, "Test ENONET for bad but valid netns_id");
 	ASSERT_EQ(skel->bss->test_enoent_lookup, -ENOENT, "Test ENOENT for failed lookup");
tools/testing/selftests/bpf/progs/test_bpf_nf.c +26 -0
index 076fbf03a1268..df43649ecb785 100644
@@ -10,6 +10,8 @@
 #define EINVAL 22
 #define ENOENT 2
 
+#define CT_OPTS_ERROR_GUARD 0x12345678
+
 #define NF_CT_ZONE_DIR_ORIG (1 << IP_CT_DIR_ORIGINAL)
 #define NF_CT_ZONE_DIR_REPL (1 << IP_CT_DIR_REPLY)
 
@@ -19,6 +21,8 @@ int test_einval_reserved = 0;
 int test_einval_reserved_new = 0;
 int test_einval_netns_id = 0;
 int test_einval_len_opts = 0;
+int test_einval_len_opts_small_lookup = 0;
+int test_einval_len_opts_small_alloc = 0;
 int test_eproto_l4proto = 0;
 int test_enonet_netns_id = 0;
 int test_enoent_lookup = 0;
@@ -124,6 +128,28 @@ nf_ct_test(struct nf_conn *(*lookup_fn)(void *, struct bpf_sock_tuple *, u32,
 	else
 		test_einval_len_opts = opts_def.error;
 
+	opts_def.error = CT_OPTS_ERROR_GUARD;
+	ct = lookup_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,
+		       sizeof(opts_def.netns_id));
+	if (ct) {
+		bpf_ct_release(ct);
+		test_einval_len_opts_small_lookup = -EINVAL;
+	} else {
+		test_einval_len_opts_small_lookup = opts_def.error;
+	}
+
+	opts_def.error = CT_OPTS_ERROR_GUARD;
+	ct = alloc_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,
+		      sizeof(opts_def.netns_id));
+	if (ct) {
+		ct = bpf_ct_insert_entry(ct);
+		if (ct)
+			bpf_ct_release(ct);
+		test_einval_len_opts_small_alloc = -EINVAL;
+	} else {
+		test_einval_len_opts_small_alloc = opts_def.error;
+	}
+
 	opts_def.l4proto = IPPROTO_ICMP;
 	ct = lookup_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,
 		       sizeof(opts_def));
#8 lore raw

v2 cover bpf: Guard conntrack opts error writes

In reply to Yiyang Chen

The conntrack lookup/allocation kfuncs expose an opts/opts__sz pair. The verifier checks the caller-provided opts__sz range, but the wrappers currently write opts->error after internal errors even when opts__sz is too small to include that field.

Patch 1 writes opts->error only when opts__sz includes it, and uses a single helper to fold ERR_PTR returns into the kfunc ABI result while keeping the local nfct result variable in each wrapper.
Patch 2 adds a bpf_nf regression check that keeps a guard in opts->error while passing opts__sz covering only netns_id.

The regression check follows the existing bpf_nf test shape. Before the fix, the guard is overwritten with -EINVAL even though opts__sz covers only the first four bytes of the options object. After the fix, the kfunc still returns NULL for the invalid size, but the guard remains intact.

Validation, rebased and tested on bpf-next master e771677c937d
("Merge tag 'for-linus-iommufd' of git://git.kernel.org/pub/scm/linux/kernel/git/jgg/iommufd"):

git diff --check origin/master..HEAD: OK scripts/checkpatch.pl --strict on 1/2 and 2/2: OK
make O=/root/ebpf-verifier-bug-detection/kernel-build/bpf-next \
net/netfilter/nf_conntrack_bpf.o: OK
Focused QEMU direct-runner against XDP and TC lookup/alloc paths:
unpatched bpf-next e771677c937d: guard overwritten with -EINVAL patched v2 007dfd0341cd: guard preserved as 0x12345678
QEMU upstream bpf_nf selftest with CONFIG_NF_CONNTRACK_MARK, CONFIG_NF_CONNTRACK_ZONES, and legacy iptables enabled:
./test_progs -t bpf_nf -vv: OK
git am of exported 1/2 and 2/2 on a fresh worktree at base: OK range-diff between branch commits and git-am result: equivalent

Changes in v2:
- Rebased onto current bpf-next master.
- Reworked patch 1 to use bpf_ct_opts_result() for the ERR_PTR-to-NULL

    conversion and guarded opts->error write, as suggested by Alexei.

- Kept the local nfct result variable in each wrapper before returning through bpf_ct_opts_result().
- Added matching Fixes tags to the selftest patch so the regression test can be backported with the fix.

v1: https://lore.kernel.org/bpf/[email protected]/

Yiyang Chen (2):
bpf: Guard conntrack opts error writes selftests/bpf: Cover small conntrack opts error writes

 net/netfilter/nf_conntrack_bpf.c              | 35 +++++++------------
 .../testing/selftests/bpf/prog_tests/bpf_nf.c |  6 ++++
 .../testing/selftests/bpf/progs/test_bpf_nf.c | 26 ++++++++++++++
 3 files changed, 45 insertions(+), 22 deletions(-)

base-commit: e771677c937da5808f7b6c1f0e4a97ec1a84f8a8

Signature · 1 line
2.34.1
#9 lore raw

PATCH v2 1/2 bpf: Guard conntrack opts error writes

The conntrack lookup and allocation kfuncs take an opts pointer together with an opts__sz argument. The verifier checks only the memory range described by opts__sz, but the wrappers unconditionally write opts->error whenever the internal lookup or allocation helper returns an error.

For an invalid size smaller than the end of opts->error, that write can land outside the verifier-checked range. Keep returning NULL for invalid arguments, but only report the error through opts->error when the supplied size includes the field.

This preserves error reporting for the supported 12-byte and 16-byte layouts, and for other invalid sizes that still include opts->error.

Fixes b4c2b9593a1c ("net/netfilter: Add unstable CT lookup helpers for XDP and TC-BPF")
Fixes d7e79c97c00c ("net: netfilter: Add kfuncs to allocate and insert CT")
---
 net/netfilter/nf_conntrack_bpf.c | 35 ++++++++++++--------------------
 1 file changed, 13 insertions(+), 22 deletions(-)
net/netfilter/nf_conntrack_bpf.c +13 -22
index 40c261cd0af38..f98d1d4b42c3d 100644
@@ -65,6 +65,15 @@ enum {
 	NF_BPF_CT_OPTS_SZ = 16,
 };
 
+static void *bpf_ct_opts_result(struct bpf_ct_opts *opts, u32 opts__sz, void *ret)
+{
+	if (!IS_ERR(ret))
+		return ret;
+	if (opts__sz >= offsetofend(struct bpf_ct_opts, error))
+		opts->error = PTR_ERR(ret);
+	return NULL;
+}
+
 static int bpf_nf_ct_tuple_parse(struct bpf_sock_tuple *bpf_tuple,
 				 u32 tuple_len, u8 protonum, u8 dir,
 				 struct nf_conntrack_tuple *tuple)
@@ -297,12 +306,7 @@ bpf_xdp_ct_alloc(struct xdp_md *xdp_ctx, struct bpf_sock_tuple *bpf_tuple,
 
 	nfct = __bpf_nf_ct_alloc_entry(dev_net(ctx->rxq->dev), bpf_tuple, tuple__sz,
 				       opts, opts__sz, 10);
-	if (IS_ERR(nfct)) {
-		opts->error = PTR_ERR(nfct);
-		return NULL;
-	}
-
-	return (struct nf_conn___init *)nfct;
+	return (struct nf_conn___init *)bpf_ct_opts_result(opts, opts__sz, nfct);
 }
 
 /* bpf_xdp_ct_lookup - Lookup CT entry for the given tuple, and acquire a
@@ -331,11 +335,7 @@ bpf_xdp_ct_lookup(struct xdp_md *xdp_ctx, struct bpf_sock_tuple *bpf_tuple,
 
 	caller_net = dev_net(ctx->rxq->dev);
 	nfct = __bpf_nf_ct_lookup(caller_net, bpf_tuple, tuple__sz, opts, opts__sz);
-	if (IS_ERR(nfct)) {
-		opts->error = PTR_ERR(nfct);
-		return NULL;
-	}
-	return nfct;
+	return bpf_ct_opts_result(opts, opts__sz, nfct);
 }
 
 /* bpf_skb_ct_alloc - Allocate a new CT entry
@@ -363,12 +363,7 @@ bpf_skb_ct_alloc(struct __sk_buff *skb_ctx, struct bpf_sock_tuple *bpf_tuple,
 
 	net = skb->dev ? dev_net(skb->dev) : sock_net(skb->sk);
 	nfct = __bpf_nf_ct_alloc_entry(net, bpf_tuple, tuple__sz, opts, opts__sz, 10);
-	if (IS_ERR(nfct)) {
-		opts->error = PTR_ERR(nfct);
-		return NULL;
-	}
-
-	return (struct nf_conn___init *)nfct;
+	return (struct nf_conn___init *)bpf_ct_opts_result(opts, opts__sz, nfct);
 }
 
 /* bpf_skb_ct_lookup - Lookup CT entry for the given tuple, and acquire a
@@ -397,11 +392,7 @@ bpf_skb_ct_lookup(struct __sk_buff *skb_ctx, struct bpf_sock_tuple *bpf_tuple,
 
 	caller_net = skb->dev ? dev_net(skb->dev) : sock_net(skb->sk);
 	nfct = __bpf_nf_ct_lookup(caller_net, bpf_tuple, tuple__sz, opts, opts__sz);
-	if (IS_ERR(nfct)) {
-		opts->error = PTR_ERR(nfct);
-		return NULL;
-	}
-	return nfct;
+	return bpf_ct_opts_result(opts, opts__sz, nfct);
 }
 
 /* bpf_ct_insert_entry - Add the provided entry into a CT map
Signature · 1 line
2.34.1
#10 lore raw
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] A TOCTOU race condition exists on opts->netns_id which can lead to a struct net reference count underflow. --

commit 6a009d88e07d68168e19d68a21a35e332591db32
Author: Yiyang Chen <[email protected]>

bpf: Guard conntrack opts error writes

This commit updates the BPF conntrack lookup and allocation kfuncs to validate the size of the opts struct before writing to the error field. This prevents out-of-bounds writes when the supplied opts__sz is smaller than the offset of the error field.

Quoted 4 lines
net/netfilter/nf_conntrack_bpf.c +0 -0
index 40c261cd0af38..f98d1d4b42c3d 100644

[ ... ]

net/netfilter/nf_conntrack_bpf.c bpf_xdp_ct_alloc(struct xdp_md *xdp_ctx, struct bpf_sock_tuple *bpf_tuple, · line 308

Quoted 4 lines
net/netfilter/nf_conntrack_bpf.c +0 -0
@@ -297,12 +306,7 @@ bpf_xdp_ct_alloc(struct xdp_md *xdp_ctx, struct bpf_sock_tuple *bpf_tuple,
 
 	nfct = __bpf_nf_ct_alloc_entry(dev_net(ctx->rxq->dev), bpf_tuple, tuple__sz,
 				       opts, opts__sz, 10);

[Severity: High]
This is a pre-existing issue, but since the opts pointer points to memory provided by the BPF program, which can be a shared BPF map value accessible concurrently from user-space, does __bpf_nf_ct_alloc_entry() have a TOCTOU race on opts->netns_id?

Inside net/netfilter/nf_conntrack_bpf.c:__bpf_nf_ct_alloc_entry():

	if (opts->netns_id >= 0) {
		net = get_net_ns_by_id(net, opts->netns_id);
		...
	}
...
out:
	if (opts->netns_id >= 0)
		put_net(net);

If a concurrent process modifies opts->netns_id from < 0 to >= 0 between these checks, put_net() could be called on the unreferenced original net, dropping a reference that was never acquired and leading to a use-after-free of the network namespace. Similarly, changing the value from >= 0 to < 0 would leak a newly acquired net reference.

The exact same pattern is present in __bpf_nf_ct_lookup(). Could we read opts->netns_id once using READ_ONCE() or cache its value locally?

Quoted 8 lines
net/netfilter/nf_conntrack_bpf.c +1 -6
-	if (IS_ERR(nfct)) {
-		opts->error = PTR_ERR(nfct);
-		return NULL;
-	}
-
-	return (struct nf_conn___init *)nfct;
+	return (struct nf_conn___init *)bpf_ct_opts_result(opts, opts__sz, nfct);
 }

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#11 lore raw

PATCH v2 2/2 selftests/bpf: Cover small conntrack opts error writes

In reply to Yiyang Chen

Add a conntrack kfunc regression check for opts__sz values that do not cover opts->error. The BPF program initializes opts->error with a guard value, calls the lookup and allocation kfuncs with opts__sz set to sizeof(opts->netns_id), and verifies that the guard is still intact after the kfunc returns NULL.

Without the conntrack wrapper guard, the kfunc error path overwrites that guard with -EINVAL even though the verifier checked only the first four bytes of the options object.

Fixes b4c2b9593a1c ("net/netfilter: Add unstable CT lookup helpers for XDP and TC-BPF")
Fixes d7e79c97c00c ("net: netfilter: Add kfuncs to allocate and insert CT")
---
 .../testing/selftests/bpf/prog_tests/bpf_nf.c |  6 +++++
 .../testing/selftests/bpf/progs/test_bpf_nf.c | 26 +++++++++++++++++++
 2 files changed, 32 insertions(+)
tools/testing/selftests/bpf/prog_tests/bpf_nf.c +6 -0
index b33dba4b126e2..14d4c1793aed5 100644
@@ -5,6 +5,8 @@
 #include "test_bpf_nf.skel.h"
 #include "test_bpf_nf_fail.skel.h"
 
+#define CT_OPTS_ERROR_GUARD 0x12345678
+
 static char log_buf[1024 * 1024];
 
 struct {
@@ -119,6 +121,10 @@ static void test_bpf_nf_ct(int mode)
 	ASSERT_EQ(skel->bss->test_einval_reserved_new, -EINVAL, "Test EINVAL for reserved in new struct not set to 0");
 	ASSERT_EQ(skel->bss->test_einval_netns_id, -EINVAL, "Test EINVAL for netns_id < -1");
 	ASSERT_EQ(skel->bss->test_einval_len_opts, -EINVAL, "Test EINVAL for len__opts != NF_BPF_CT_OPTS_SZ");
+	ASSERT_EQ(skel->bss->test_einval_len_opts_small_lookup, CT_OPTS_ERROR_GUARD,
+		  "Test no error write for lookup opts__sz before error field");
+	ASSERT_EQ(skel->bss->test_einval_len_opts_small_alloc, CT_OPTS_ERROR_GUARD,
+		  "Test no error write for alloc opts__sz before error field");
 	ASSERT_EQ(skel->bss->test_eproto_l4proto, -EPROTO, "Test EPROTO for l4proto != TCP or UDP");
 	ASSERT_EQ(skel->bss->test_enonet_netns_id, -ENONET, "Test ENONET for bad but valid netns_id");
 	ASSERT_EQ(skel->bss->test_enoent_lookup, -ENOENT, "Test ENOENT for failed lookup");
tools/testing/selftests/bpf/progs/test_bpf_nf.c +26 -0
index 076fbf03a1268..df43649ecb785 100644
@@ -10,6 +10,8 @@
 #define EINVAL 22
 #define ENOENT 2
 
+#define CT_OPTS_ERROR_GUARD 0x12345678
+
 #define NF_CT_ZONE_DIR_ORIG (1 << IP_CT_DIR_ORIGINAL)
 #define NF_CT_ZONE_DIR_REPL (1 << IP_CT_DIR_REPLY)
 
@@ -19,6 +21,8 @@ int test_einval_reserved = 0;
 int test_einval_reserved_new = 0;
 int test_einval_netns_id = 0;
 int test_einval_len_opts = 0;
+int test_einval_len_opts_small_lookup = 0;
+int test_einval_len_opts_small_alloc = 0;
 int test_eproto_l4proto = 0;
 int test_enonet_netns_id = 0;
 int test_enoent_lookup = 0;
@@ -124,6 +128,28 @@ nf_ct_test(struct nf_conn *(*lookup_fn)(void *, struct bpf_sock_tuple *, u32,
 	else
 		test_einval_len_opts = opts_def.error;
 
+	opts_def.error = CT_OPTS_ERROR_GUARD;
+	ct = lookup_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,
+		       sizeof(opts_def.netns_id));
+	if (ct) {
+		bpf_ct_release(ct);
+		test_einval_len_opts_small_lookup = -EINVAL;
+	} else {
+		test_einval_len_opts_small_lookup = opts_def.error;
+	}
+
+	opts_def.error = CT_OPTS_ERROR_GUARD;
+	ct = alloc_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,
+		      sizeof(opts_def.netns_id));
+	if (ct) {
+		ct = bpf_ct_insert_entry(ct);
+		if (ct)
+			bpf_ct_release(ct);
+		test_einval_len_opts_small_alloc = -EINVAL;
+	} else {
+		test_einval_len_opts_small_alloc = opts_def.error;
+	}
+
 	opts_def.l4proto = IPPROTO_ICMP;
 	ct = lookup_fn(ctx, &bpf_tuple, sizeof(bpf_tuple.ipv4), &opts_def,
 		       sizeof(opts_def));
Signature · 1 line
2.34.1
#12 lore raw
In reply to Yiyang Chen
This series was applied to bpf/bpf.git (master) by Alexei Starovoitov <[email protected]>:

Hello:

This series was applied to bpf/bpf.git (master)
by Alexei Starovoitov <[email protected]>:

Quoted 5 lines · On Thu, 18 Jun 2026 10:18:42 +0000 you wrote:

The conntrack lookup/allocation kfuncs expose an opts/opts__sz pair. The verifier checks the caller-provided opts__sz range, but the wrappers currently write opts->error after internal errors even when opts__sz is too small to include that field.

Quoted 7 lines

Patch 1 writes opts->error only when opts__sz includes it, and uses a single helper to fold ERR_PTR returns into the kfunc ABI result while keeping the local nfct result variable in each wrapper.
Patch 2 adds a bpf_nf regression check that keeps a guard in opts->error while passing opts__sz covering only netns_id.

[...]

Here is the summary with links:
- [bpf-next,v2,1/2] bpf: Guard conntrack opts error writes

    https://git.kernel.org/bpf/bpf/c/6f6183a39533
  - [bpf-next,v2,2/2] selftests/bpf: Cover small conntrack opts error writes
    https://git.kernel.org/bpf/bpf/c/38ba6d43af38

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html