Skip to contentSkip to conversation

bpf: Add bpf_memmem and bpf_dynptr_memmem kfuncs

RFC PATCH Superseded Abhishek Khade 3 participants 6 messages Nov 22

Subsystems (3)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

cover bpf: Add bpf_memmem and bpf_dynptr_memmem kfuncs

This patch series introduces two new BPF kfuncs for binary-safe substring searching in raw memory and dynamic pointers:
- bpf_memmem(): Searches for a binary needle within a flat memory buffer.
- bpf_dynptr_memmem(): Searches for a binary needle within a BPF dynptr.

Both kfuncs utilize a two-tier search strategy (memchr() for initial byte matching followed by memcmp()) and enforce maximum buffer length boundaries (BPF_MEMMEM_MAX_LEN). Selftests covering boundary conditions, embedded null bytes, and dynptr integration are included.

Abhishek Khade (2):
bpf: Add bpf_memmem and bpf_dynptr_memmem kfuncs selftests/bpf: Add selftests for bpf_memmem and bpf_dynptr_memmem
kfuncs

 kernel/bpf/helpers.c                          | 115 ++++++++
 .../selftests/bpf/prog_tests/memmem_kfunc.c   |   9 +
 .../selftests/bpf/progs/memmem_kfunc.c        | 259 ++++++++++++++++++
 3 files changed, 383 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/memmem_kfunc.c
 create mode 100644 tools/testing/selftests/bpf/progs/memmem_kfunc.c
Signature · 1 line
2.53.0
#1 lore raw

RFC PATCH 1/2 bpf: Add bpf_memmem and bpf_dynptr_memmem kfuncs

With the introduction of bpf_strstr, bpf_strnstr, bpf_strcasestr, and bpf_strcasecmp in Linux 6.17–6.19, BPF programs gained solid support for floating-offset substring search in null-terminated C-strings.

However, in network packet inspection (TC/XDP, TLS SNI tagging, binary protocol delimiters) and security monitoring (e.g. BPF LSM hooks inspecting raw memory or binary execution buffers), data buffers are frequently not null-terminated and often contain embedded '\0' bytes. For these use cases, existing string kfuncs terminate prematurely at the first null byte.

Currently, developers attempting to search variable-length binary payloads must choose between:
1. Writing a loop using bpf_loop() or open-coded iterators: Even with verifier inlining, this executes 1 subprogram call per byte and cannot leverage 64-bit word-at-a-time SIMD scanning, making it significantly slower than kernel-internal scanning.
2. Streaming raw buffers to user space via BPF ring buffers: This induces heavy memory copying and context-switch latency, often leading to ring buffer drops under high-throughput workloads.

To address this gap, this RFC proposes two complementary kfuncs in kernel/bpf/helpers.c:
- bpf_memmem(): Searches for a byte sequence within a flat memory slice.
- bpf_dynptr_memmem(): Searches for a byte sequence within a dynamic pointer (struct bpf_dynptr).

Both functions wrap an internal allocation-free scanning routine based on the kernel's optimized memchr() (leveraging word-at-a-time 64-bit detection) followed by memcmp(), returning the matched byte offset or -ENOENT. Buffer sizes are capped at BPF_MEMMEM_MAX_LEN (2 MB) to prevent RCU stall/soft-lockup risks. Verifier bounds safety is enforced via the standard __sz naming convention and dynptr type tracking.

---
 kernel/bpf/helpers.c | 115 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 115 insertions(+)
kernel/bpf/helpers.c +115 -0
index 6788489a2..4b99bf050 100644
@@ -2991,6 +2991,119 @@ __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task,
 	return ret;
 }
 
+#define BPF_MEMMEM_MAX_LEN (2 * 1024 * 1024) /* 2 MB max search buffer */
+
+/*
+ * In-kernel binary byte sequence search.
+ * Scans haystack for the first byte using optimized memchr(),
+ * then validates the remaining needle with memcmp().
+ */
+static void *__bpf_memmem(const void *haystack, size_t haystack_sz,
+			  const void *needle, size_t needle_sz)
+{
+	const char *h = haystack;
+	const char *n = needle;
+	const char *end;
+
+	if (needle_sz == 0)
+		return (void *)haystack;
+	if (needle_sz > haystack_sz)
+		return NULL;
+	if (needle_sz == 1)
+		return memchr(haystack, n[0], haystack_sz);
+
+	end = h + haystack_sz - needle_sz + 1;
+	while ((h = memchr(h, n[0], end - h)) != NULL) {
+		if (memcmp(h, n, needle_sz) == 0)
+			return (void *)h;
+		h++;
+	}
+
+	return NULL;
+}
+
+/**
+ * bpf_memmem - search for needle byte pattern in a flat memory buffer
+ * @haystack: pointer to haystack memory buffer
+ * @haystack__sz: size of haystack buffer in bytes
+ * @needle: pointer to byte pattern to search for
+ * @needle__sz: size of pattern in bytes
+ * @flags: reserved for future options (must be 0)
+ *
+ * Return:
+ * * >=0      - 0-based byte offset of match in haystack
+ * * %-ENOENT - needle was not found in haystack
+ * * %-EINVAL - invalid flags or parameters (empty needle or needle > haystack)
+ * * %-E2BIG  - haystack exceeds maximum allowed search size (2 MB)
+ */
+__bpf_kfunc long bpf_memmem(const void *haystack, u32 haystack__sz,
+			    const void *needle, u32 needle__sz,
+			    u64 flags)
+{
+	const void *match;
+
+	if (flags)
+		return -EINVAL;
+	if (!haystack || !needle || needle__sz == 0 || needle__sz > haystack__sz)
+		return -EINVAL;
+	if (haystack__sz > BPF_MEMMEM_MAX_LEN)
+		return -E2BIG;
+
+	match = __bpf_memmem(haystack, haystack__sz, needle, needle__sz);
+	if (!match)
+		return -ENOENT;
+
+	return (long)((const char *)match - (const char *)haystack);
+}
+
+/**
+ * bpf_dynptr_memmem - search for needle within a dynamic pointer
+ * @haystack: pointer to dynptr representing the search buffer
+ * @needle: pointer to pattern to search for
+ * @needle__sz: size of pattern in bytes
+ * @flags: reserved for future options (must be 0)
+ *
+ * Note:
+ * For skb dynptrs, the inspected buffer range must be contiguous/linear
+ * (e.g. via bpf_skb_pull_data()); fragmented buffers will return %-EINVAL.
+ *
+ * Return:
+ * * >=0      - 0-based byte offset of match in dynptr buffer
+ * * %-ENOENT - needle was not found
+ * * %-EINVAL - invalid flags, non-linear buffer, or parameters
+ * * %-E2BIG  - dynptr buffer exceeds maximum allowed search size (2 MB)
+ */
+__bpf_kfunc long bpf_dynptr_memmem(const struct bpf_dynptr *haystack,
+				   const void *needle, u32 needle__sz,
+				   u64 flags)
+{
+	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)haystack;
+	const void *data;
+	const void *match;
+	u32 size;
+
+	if (flags)
+		return -EINVAL;
+	if (!ptr || !ptr->data || !needle || needle__sz == 0)
+		return -EINVAL;
+
+	size = __bpf_dynptr_size(ptr);
+	if (needle__sz > size)
+		return -EINVAL;
+	if (size > BPF_MEMMEM_MAX_LEN)
+		return -E2BIG;
+
+	data = __bpf_dynptr_data(ptr, size);
+	if (!data)
+		return -EINVAL;
+
+	match = __bpf_memmem(data, size, needle, needle__sz);
+	if (!match)
+		return -ENOENT;
+
+	return (long)((const char *)match - (const char *)data);
+}
+
 BPF_CALL_2(bpf_current_task_under_cgroup, struct bpf_map *, map, u32, idx)
 {
 	struct bpf_array *array = container_of(map, struct bpf_array, map);
@@ -5168,6 +5281,8 @@ BTF_ID_FLAGS(func, bpf_verify_pkcs7_signature, KF_SLEEPABLE)
 #ifdef CONFIG_S390
 BTF_ID_FLAGS(func, bpf_get_lowcore)
 #endif
+BTF_ID_FLAGS(func, bpf_memmem)
+BTF_ID_FLAGS(func, bpf_dynptr_memmem)
 BTF_KFUNCS_END(generic_btf_ids)
 
 static const struct btf_kfunc_id_set generic_kfunc_set = {
Signature · 1 line
2.53.0
#2 lore raw
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [High] bpf: bpf_memmem() and bpf_dynptr_memmem() defined inside CONFIG_CGROUPS - [High] bpf: quadratic…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [High] bpf: bpf_memmem() and bpf_dynptr_memmem() defined inside CONFIG_CGROUPS
- [High] bpf: quadratic O(N*M) complexity in __bpf_memmem() with 2 MB buffer cap
- [Medium] bpf: u64 size truncated to u32 in bpf_dynptr_memmem() before bounds check
- [Medium] bpf: bpf_memmem() and bpf_dynptr_memmem() placed in generic_btf_ids
--

commit 8544ed400181be07e2f78fbba3ee242f2ebcc135
Author: Abhishek Khade <[email protected]>

bpf: Add bpf_memmem and bpf_dynptr_memmem kfuncs

This commit adds the bpf_memmem() and bpf_dynptr_memmem() kfuncs to search for binary byte sequences in flat memory buffers and BPF dynptrs.

Quoted 28 lines
kernel/bpf/helpers.c +20 -0
index 937a0d7d68390..2f3e349955466 100644
@@ -2994,6 +2994,119 @@ __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task,
 	return ret;
 }
 
+#define BPF_MEMMEM_MAX_LEN (2 * 1024 * 1024) /* 2 MB max search buffer */
+
+/*
+ * In-kernel binary byte sequence search.
+ * Scans haystack for the first byte using optimized memchr(),
+ * then validates the remaining needle with memcmp().
+ */
+static void *__bpf_memmem(const void *haystack, size_t haystack_sz,
+			  const void *needle, size_t needle_sz)
+{
+	const char *h = haystack;
+	const char *n = needle;
+	const char *end;
+
+	if (needle_sz == 0)
+		return (void *)haystack;
+	if (needle_sz > haystack_sz)
+		return NULL;
+	if (needle_sz == 1)
+		return memchr(haystack, n[0], haystack_sz);

kernel/bpf/helpers.c __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task, · line 3026

Quoted 10 lines
kernel/bpf/helpers.c +10 -0
+
+	end = h + haystack_sz - needle_sz + 1;
+	while ((h = memchr(h, n[0], end - h)) != NULL) {
+		if (memcmp(h, n, needle_sz) == 0)
+			return (void *)h;
+		h++;
+	}
+
+	return NULL;
+}

[Severity: High]
Can __bpf_memmem() trigger RCU CPU stalls and soft lockups on repetitive inputs?

Both bpf_memmem() and bpf_dynptr_memmem() allow haystack_sz and needle_sz up to BPF_MEMMEM_MAX_LEN (2 MB), and __bpf_memmem() advances h by one byte whenever memcmp() fails. A 2 MB haystack of repeated zero bytes searched for a 1 MB needle of zeroes ending in a non-zero byte runs the loop over 10^6 times and compares 1 MB on each step (~1.1 * 10^12 byte comparisons) in a non-preemptible BPF context.

Also, the commit message notes that memchr() uses 64-bit word-at-a-time detection, but the generic memchr() in lib/string.c (used on x86_64 and other architectures without __HAVE_ARCH_MEMCHR) scans byte-by-byte.

[ ... ]

kernel/bpf/helpers.c __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task, · line 3042

Quoted 4 lines
kernel/bpf/helpers.c +4 -0
+__bpf_kfunc long bpf_memmem(const void *haystack, u32 haystack__sz,
+			    const void *needle, u32 needle__sz,
+			    u64 flags)
+{

[Severity: High]
Are __bpf_memmem(), bpf_memmem(), and bpf_dynptr_memmem() unintentionally placed inside the #ifdef CONFIG_CGROUPS block?

They are inserted between bpf_task_under_cgroup() and bpf_current_task_under_cgroup(), inside the #ifdef CONFIG_CGROUPS guard that opens before bpf_cgroup_acquire() and closes after bpf_task_get_cgroup1(), while their BTF_ID_FLAGS entries in generic_btf_ids are emitted outside #ifdef CONFIG_CGROUPS. When CONFIG_CGROUPS is disabled and CONFIG_DEBUG_INFO_BTF is enabled, resolve_btfids fails the build on the missing symbols (under CONFIG_WERROR=y) or leaves zeroed BTF IDs that cause kfunc_init() to fail registering generic_kfunc_set at boot. Moving the definitions after the #endif /* CONFIG_CGROUPS */ line avoids this.

[ ... ]

Quoted 9 lines
kernel/bpf/helpers.c +9 -0
+__bpf_kfunc long bpf_dynptr_memmem(const struct bpf_dynptr *haystack,
+				   const void *needle, u32 needle__sz,
+				   u64 flags)
+{
+	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)haystack;
+	const void *data;
+	const void *match;
+	u32 size;
+

kernel/bpf/helpers.c __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task, · line 3094

Quoted 10 lines
kernel/bpf/helpers.c +10 -0
+	if (flags)
+		return -EINVAL;
+	if (!ptr || !ptr->data || !needle || needle__sz == 0)
+		return -EINVAL;
+
+	size = __bpf_dynptr_size(ptr);
+	if (needle__sz > size)
+		return -EINVAL;
+	if (size > BPF_MEMMEM_MAX_LEN)
+		return -E2BIG;

[Severity: Medium]
Does storing __bpf_dynptr_size(ptr) into u32 size truncate 64-bit dynptr sizes before the bounds checks?

__bpf_dynptr_size() returns u64 because BPF_DYNPTR_TYPE_FILE stores a 64-bit size. If a dynptr has a 64-bit size whose upper 32 bits are non-zero and lower 32 bits are at most BPF_MEMMEM_MAX_LEN (for example, a file dynptr adjusted to 4 GiB), truncating size to u32 bypasses the size > BPF_MEMMEM_MAX_LEN (-E2BIG) check. Declaring size as u64 avoids the truncation.

[ ... ]

kernel/bpf/helpers.c BTF_ID_FLAGS(func, bpf_verify_pkcs7_signature, KF_SLEEPABLE) · line 5371

Quoted 7 lines
kernel/bpf/helpers.c +2 -0
@@ -5253,6 +5366,8 @@ BTF_ID_FLAGS(func, bpf_verify_pkcs7_signature, KF_SLEEPABLE)
 #ifdef CONFIG_S390
 BTF_ID_FLAGS(func, bpf_get_lowcore)
 #endif
+BTF_ID_FLAGS(func, bpf_memmem)
+BTF_ID_FLAGS(func, bpf_dynptr_memmem)
 BTF_KFUNCS_END(generic_btf_ids)

[Severity: Medium]
Should bpf_memmem and bpf_dynptr_memmem be registered in common_btf_ids instead of generic_btf_ids?

kfunc_init() only registers generic_kfunc_set for TRACING, SCHED_CLS, XDP, STRUCT_OPS, SYSCALL, and CGROUP_SKB, which prevents KPROBE, SOCKET_FILTER, SK_SKB, SCHED_ACT, NETFILTER, and LWT programs from calling these kfuncs. The other generic dynptr and string search kfuncs in kernel/bpf/helpers.c are placed in common_btf_ids so they are registered for BPF_PROG_TYPE_UNSPEC.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw
In reply to Abhishek Khade
TL;DR: Nits only: possibly unreachable needle_sz and !ptr checks in the memmem kfuncs; the empty-needle branch returns offset 0, contradicting the documentation.
Quoted 1 line

bpf: Add bpf_memmem and bpf_dynptr_memmem kfuncs

TL;DR: Nits only: possibly unreachable needle_sz and !ptr checks in the memmem kfuncs; the empty-needle branch returns offset 0, contradicting the documentation.

Quoted 3 lines
kernel/bpf/helpers.c +0 -0

[ ... ]

kernel/bpf/helpers.c __bpf_kfunc long bpf_task_under_cgroup(struct task_struct *task, · line 3011

Quoted 11 lines
kernel/bpf/helpers.c +11 -0
+static void *__bpf_memmem(const void *haystack, size_t haystack_sz,
+			  const void *needle, size_t needle_sz)
+{
+	const char *h = haystack;
+	const char *n = needle;
+	const char *end;
+
+	if (needle_sz == 0)
+		return (void *)haystack;
+	if (needle_sz > haystack_sz)
+		return NULL;

this isn't a bug, but are these two needle_sz checks in __bpf_memmem() reachable?

Both bpf_memmem() and bpf_dynptr_memmem() already reject needle__sz == 0 and needle__sz > haystack size with -EINVAL before calling it. The empty-needle branch here also returns a match at offset 0, which is the opposite of what the kfunc documentation says.

[ ... ]

kernel/bpf/helpers.c

Quoted 2 lines
kernel/bpf/helpers.c +2 -0
+	if (!ptr || !ptr->data || !needle || needle__sz == 0)
+		return -EINVAL;

Similarly, can !ptr be true in bpf_dynptr_memmem(), given that the verifier requires an initialized dynptr argument? The neighbouring dynptr kfuncs such as bpf_dynptr_slice() only test ptr->data.

---
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/45015018001

#4 lore raw

RFC PATCH 2/2 selftests/bpf: Add selftests for bpf_memmem and bpf_dynptr_memmem kfuncs

In reply to Abhishek Khade

Add automated BPF selftests validating in-kernel binary byte sequence matching for bpf_memmem() and bpf_dynptr_memmem().

Covered test cases:
1. Binary pattern match across embedded null bytes (0x00).
2. Match at buffer start (offset 0).
3. Match at buffer end (haystack_sz - needle_sz).
4. Single-byte needle fastpath.
5. Non-matching pattern returning -ENOENT.
6. Multiple candidate occurrences returning the first match.
7. Overlapping candidate prefixes returning the correct match.
8. Exact match where needle equals haystack.
9. Needles larger than haystack returning -EINVAL.
10. Empty needle returning -EINVAL.
11. Invalid flags returning -EINVAL.
12. Oversized haystack (> 2 MB) returning -E2BIG.
13. Exact 2 MB boundary full scan.
14. Zero-length haystack returning -EINVAL.
15. Dynamic pointer (bpf_dynptr) searching across embedded nulls, start, end, not found, size boundary, and error cases.

---
 .../selftests/bpf/prog_tests/memmem_kfunc.c   |   9 +
 .../selftests/bpf/progs/memmem_kfunc.c        | 259 ++++++++++++++++++
 2 files changed, 268 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/memmem_kfunc.c
 create mode 100644 tools/testing/selftests/bpf/progs/memmem_kfunc.c
tools/testing/selftests/bpf/prog_tests/memmem_kfunc.c new file +9 -0
new file mode 100644
index 000000000..d27c9a2a2
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Abhishek Khade */
+#include <test_progs.h>
+#include "memmem_kfunc.skel.h"
+
+void test_memmem_kfunc(void)
+{
+	RUN_TESTS(memmem_kfunc);
+}
tools/testing/selftests/bpf/progs/memmem_kfunc.c new file +259 -0

259 lines not on this page · raw message

Signature · 1 line
2.53.0
#5 lore raw

Re: [RFC PATCH bpf-next 2/2] selftests/bpf: Add selftests for bpf_memmem and bpf_dynptr_memmem kfuncs

TL;DR: Nit only, in the memmem selftests: the (void *) casts in the bpf_dynptr_from_mem() calls may be unnecessary, since the arrays aren't const and other callers omit them.
Quoted 1 line

selftests/bpf: Add selftests for bpf_memmem and bpf_dynptr_memmem kfuncs

TL;DR: Nit only, in the memmem selftests: the (void *) casts in the bpf_dynptr_from_mem() calls may be unnecessary, since the arrays aren't const and other callers omit them.

Quoted 5 lines
tools/testing/selftests/bpf/progs/memmem_kfunc.c new file +0 -0
new file mode 100644
index 000000000000..8abd06e9758d

[ ... ]

tools/testing/selftests/bpf/progs/memmem_kfunc.c line 159

Quoted 9 lines
tools/testing/selftests/bpf/progs/memmem_kfunc.c new file +9 -0
+SEC("syscall")
+__success __retval(7)
+int test_dynptr_memmem_embedded_null(void *ctx)
+{
+	struct bpf_dynptr ptr;
+
+	bpf_dynptr_from_mem((void *)bin_data, sizeof(bin_data), 0, &ptr);
+	return bpf_dynptr_memmem(&ptr, needle_null, sizeof(needle_null), 0);
+}

this isn't a bug, but are the (void *) casts needed in the bpf_dynptr_from_mem() calls?

bin_data, needle_start and oversized_buf are not const, so they convert to void * implicitly. The bpf_memmem() calls earlier in this file pass the same arrays without a cast, and dynptr_success.c passes map_val directly.

Dropping the casts would match those callers.

---
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/45015018001