bpf/selftests: Test PTR_TO_RDONLY_MEM
authorHao Luo <haoluo@google.com>
Thu, 28 Apr 2022 23:57:50 +0000 (16:57 -0700)
committerGreg Kroah-Hartman <gregkh@linuxfoundation.org>
Sun, 1 May 2022 15:22:26 +0000 (17:22 +0200)
commit 9497c458c10b049438ef6e6ddda898edbc3ec6a8 upstream.

This test verifies that a ksym of non-struct can not be directly
updated.

Signed-off-by: Hao Luo <haoluo@google.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Acked-by: Andrii Nakryiko <andrii@kernel.org>
Link: https://lore.kernel.org/bpf/20211217003152.48334-10-haoluo@google.com
Cc: stable@vger.kernel.org # 5.15.x
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
tools/testing/selftests/bpf/prog_tests/ksyms_btf.c
tools/testing/selftests/bpf/progs/test_ksyms_btf_write_check.c [new file with mode: 0644]

index cf3acfa..69455fe 100644 (file)
@@ -7,6 +7,7 @@
 #include "test_ksyms_btf.skel.h"
 #include "test_ksyms_btf_null_check.skel.h"
 #include "test_ksyms_weak.skel.h"
+#include "test_ksyms_btf_write_check.skel.h"
 
 static int duration;
 
@@ -109,6 +110,16 @@ cleanup:
        test_ksyms_weak__destroy(skel);
 }
 
+static void test_write_check(void)
+{
+       struct test_ksyms_btf_write_check *skel;
+
+       skel = test_ksyms_btf_write_check__open_and_load();
+       ASSERT_ERR_PTR(skel, "unexpected load of a prog writing to ksym memory\n");
+
+       test_ksyms_btf_write_check__destroy(skel);
+}
+
 void test_ksyms_btf(void)
 {
        int percpu_datasec;
@@ -136,4 +147,7 @@ void test_ksyms_btf(void)
 
        if (test__start_subtest("weak_ksyms"))
                test_weak_syms();
+
+       if (test__start_subtest("write_check"))
+               test_write_check();
 }
diff --git a/tools/testing/selftests/bpf/progs/test_ksyms_btf_write_check.c b/tools/testing/selftests/bpf/progs/test_ksyms_btf_write_check.c
new file mode 100644 (file)
index 0000000..2180c41
--- /dev/null
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2021 Google */
+
+#include "vmlinux.h"
+
+#include <bpf/bpf_helpers.h>
+
+extern const int bpf_prog_active __ksym; /* int type global var. */
+
+SEC("raw_tp/sys_enter")
+int handler(const void *ctx)
+{
+       int *active;
+       __u32 cpu;
+
+       cpu = bpf_get_smp_processor_id();
+       active = (int *)bpf_per_cpu_ptr(&bpf_prog_active, cpu);
+       if (active) {
+               /* Kernel memory obtained from bpf_{per,this}_cpu_ptr
+                * is read-only, should _not_ pass verification.
+                */
+               /* WRITE_ONCE */
+               *(volatile int *)active = -1;
+       }
+
+       return 0;
+}
+
+char _license[] SEC("license") = "GPL";