Skip to content

Commit 7edfc02

Browse files
RtoaxAlexei Starovoitov
authored andcommitted
bpf: Fix bpf_strnstr() to handle suffix match cases better
bpf_strnstr() should not treat the ending '\0' of s2 as a matching character if the parameter 'len' equal to s2 string length, for example: 1. bpf_strnstr("openat", "open", 4) = -ENOENT 2. bpf_strnstr("openat", "open", 5) = 0 This patch makes (1) return 0, fix just the `len == strlen(s2)` case. And fix a more general case when s2 is a suffix of the first len characters of s1. Fixes: e913705 ("bpf: Add kfuncs for read-only string operations") Signed-off-by: Rong Tao <rongtao@cestc.cn> Signed-off-by: Andrii Nakryiko <andrii@kernel.org> Link: https://lore.kernel.org/bpf/tencent_17DC57B9D16BC443837021BEACE84B7C1507@qq.com Signed-off-by: Alexei Starovoitov <ast@kernel.org>
1 parent 387be23 commit 7edfc02

1 file changed

Lines changed: 8 additions & 1 deletion

File tree

kernel/bpf/helpers.c

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3664,10 +3664,17 @@ __bpf_kfunc int bpf_strnstr(const char *s1__ign, const char *s2__ign, size_t len
36643664

36653665
guard(pagefault)();
36663666
for (i = 0; i < XATTR_SIZE_MAX; i++) {
3667-
for (j = 0; i + j < len && j < XATTR_SIZE_MAX; j++) {
3667+
for (j = 0; i + j <= len && j < XATTR_SIZE_MAX; j++) {
36683668
__get_kernel_nofault(&c2, s2__ign + j, char, err_out);
36693669
if (c2 == '\0')
36703670
return i;
3671+
/*
3672+
* We allow reading an extra byte from s2 (note the
3673+
* `i + j <= len` above) to cover the case when s2 is
3674+
* a suffix of the first len chars of s1.
3675+
*/
3676+
if (i + j == len)
3677+
break;
36713678
__get_kernel_nofault(&c1, s1__ign + j, char, err_out);
36723679
if (c1 == '\0')
36733680
return -ENOENT;

0 commit comments

Comments
 (0)