public inbox for bpf@vger.kernel.org
 help / color / mirror / Atom feed
* [PATCH] bpf: btf: reject division by zero in btf_struct_walk for zero-size flex array elements
@ 2026-04-13  8:50 Dudu Lu
  2026-04-13  9:26 ` bot+bpf-ci
  2026-04-13 21:43 ` Eduard Zingerman
  0 siblings, 2 replies; 5+ messages in thread
From: Dudu Lu @ 2026-04-13  8:50 UTC (permalink / raw)
  To: bpf; +Cc: martin.lau, ast, daniel, andrii, Dudu Lu

btf_struct_walk() computes `off = (off - moff) % t->size` when handling
access to a flexible array member. If the element type is a zero-size
struct (e.g., `struct B {}`), t->size is 0 and this causes a division-
by-zero exception. On x86 this triggers a #DE fault resulting in a
kernel panic.

The BTF validator does not reject zero-size structs: btf_struct_check_meta()
passes trivially for vlen=0 structs, and btf_array_resolve() skips the
overflow check for flex arrays (nelems=0). This allows a user to load
crafted BTF containing `struct B {}; struct A { int x; struct B flex[]; }`
and then trigger the crash when the verifier calls btf_struct_walk()
during program load.

Fix this by adding a check for t->size == 0 before the modulo operation.
When a zero-size element type is encountered in a flex array, return
-EINVAL to reject the access.

Note: ARM64 is not affected because its `udiv` instruction returns 0
for division by zero (no exception). However, the resulting incorrect
offset computation would still be a logic bug.

Fixes: 1dc92851849c ("bpf: kernel side support for BTF Var and DataSec")
Signed-off-by: Dudu Lu <phx0fer@gmail.com>
---
 kernel/bpf/btf.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 71f9143fe90f..f25009ea0d89 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -7103,6 +7103,13 @@ static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
 		if (!btf_type_is_struct(t))
 			goto error;
 
+		/* Zero-size element type (e.g., empty struct) would cause
+		 * division by zero below. Reject the access.
+		 */
+		if (t->size == 0) {
+			bpf_log(log, "zero-size type in flex array\n");
+			goto error;
+		}
 		off = (off - moff) % t->size;
 		goto again;
 
-- 
2.39.3 (Apple Git-145)


^ permalink raw reply related	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2026-04-13 21:43 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-04-13  8:50 [PATCH] bpf: btf: reject division by zero in btf_struct_walk for zero-size flex array elements Dudu Lu
2026-04-13  9:26 ` bot+bpf-ci
2026-04-13 10:23   ` Leon Hwang
2026-04-13 10:31     ` Leon Hwang
2026-04-13 21:43 ` Eduard Zingerman

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox