Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

selftests/bpf: Test bpf_iter buffer access with negative offset

Commit afbf21dce668 ("bpf: Support readonly/readwrite buffers
in verifier") added readonly/readwrite buffer support which
is currently used by bpf_iter tracing programs. It has
a bug with incorrect parameter ordering which later fixed
by Commit f6dfbe31e8fa ("bpf: Fix swapped arguments in calls
to check_buffer_access").

This patch added a test case with a negative offset access
which will trigger the error path.

Without Commit f6dfbe31e8fa, running the test case in the patch,
the error message looks like:
R1_w=rdwr_buf(id=0,off=0,imm=0) R10=fp0
; value_sum += *(__u32 *)(value - 4);
2: (61) r1 = *(u32 *)(r1 -4)
R1 invalid (null) buffer access: off=-4, size=4

With the above commit, the error message looks like:
R1_w=rdwr_buf(id=0,off=0,imm=0) R10=fp0
; value_sum += *(__u32 *)(value - 4);
2: (61) r1 = *(u32 *)(r1 -4)
R1 invalid rdwr buffer access: off=-4, size=4

Signed-off-by: Yonghong Song <yhs@fb.com>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Acked-by: Song Liu <songliubraving@fb.com>
Link: https://lore.kernel.org/bpf/20200728221801.1090406-1-yhs@fb.com

authored by

Yonghong Song and committed by
Daniel Borkmann
12e6196f 4fc00b79

+34
+13
tools/testing/selftests/bpf/prog_tests/bpf_iter.c
··· 21 21 #include "bpf_iter_bpf_percpu_array_map.skel.h" 22 22 #include "bpf_iter_bpf_sk_storage_map.skel.h" 23 23 #include "bpf_iter_test_kern5.skel.h" 24 + #include "bpf_iter_test_kern6.skel.h" 24 25 25 26 static int duration; 26 27 ··· 886 885 bpf_iter_test_kern5__destroy(skel); 887 886 } 888 887 888 + static void test_buf_neg_offset(void) 889 + { 890 + struct bpf_iter_test_kern6 *skel; 891 + 892 + skel = bpf_iter_test_kern6__open_and_load(); 893 + if (CHECK(skel, "bpf_iter_test_kern6__open_and_load", 894 + "skeleton open_and_load unexpected success\n")) 895 + bpf_iter_test_kern6__destroy(skel); 896 + } 897 + 889 898 void test_bpf_iter(void) 890 899 { 891 900 if (test__start_subtest("btf_id_or_null")) ··· 944 933 test_bpf_sk_storage_map(); 945 934 if (test__start_subtest("rdonly-buf-out-of-bound")) 946 935 test_rdonly_buf_out_of_bound(); 936 + if (test__start_subtest("buf-neg-offset")) 937 + test_buf_neg_offset(); 947 938 }
+21
tools/testing/selftests/bpf/progs/bpf_iter_test_kern6.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* Copyright (c) 2020 Facebook */ 3 + #include "bpf_iter.h" 4 + #include <bpf/bpf_helpers.h> 5 + 6 + char _license[] SEC("license") = "GPL"; 7 + 8 + __u32 value_sum = 0; 9 + 10 + SEC("iter/bpf_map_elem") 11 + int dump_bpf_hash_map(struct bpf_iter__bpf_map_elem *ctx) 12 + { 13 + void *value = ctx->value; 14 + 15 + if (value == (void *)0) 16 + return 0; 17 + 18 + /* negative offset, verifier failure. */ 19 + value_sum += *(__u32 *)(value - 4); 20 + return 0; 21 + }