1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (C) 2021. Huawei Technologies Co., Ltd */
3 #include <stdbool.h>
4 #include <linux/types.h>
5 #include <linux/bpf.h>
6 #include <bpf/bpf_helpers.h>
7 #include <bpf/bpf_tracing.h>
8 
9 #define STRNCMP_STR_SZ 8
10 
11 const char target[STRNCMP_STR_SZ] = "EEEEEEE";
12 char str[STRNCMP_STR_SZ];
13 int cmp_ret = 0;
14 int target_pid = 0;
15 
16 const char no_str_target[STRNCMP_STR_SZ] = "12345678";
17 char writable_target[STRNCMP_STR_SZ];
18 unsigned int no_const_str_size = STRNCMP_STR_SZ;
19 
20 char _license[] SEC("license") = "GPL";
21 
22 SEC("?tp/syscalls/sys_enter_nanosleep")
23 int do_strncmp(void *ctx)
24 {
25 	if ((bpf_get_current_pid_tgid() >> 32) != target_pid)
26 		return 0;
27 
28 	cmp_ret = bpf_strncmp(str, STRNCMP_STR_SZ, target);
29 	return 0;
30 }
31 
32 SEC("?tp/syscalls/sys_enter_nanosleep")
33 int strncmp_bad_not_const_str_size(void *ctx)
34 {
35 	/* The value of string size is not const, so will fail */
36 	cmp_ret = bpf_strncmp(str, no_const_str_size, target);
37 	return 0;
38 }
39 
40 SEC("?tp/syscalls/sys_enter_nanosleep")
41 int strncmp_bad_writable_target(void *ctx)
42 {
43 	/* Compared target is not read-only, so will fail */
44 	cmp_ret = bpf_strncmp(str, STRNCMP_STR_SZ, writable_target);
45 	return 0;
46 }
47 
48 SEC("?tp/syscalls/sys_enter_nanosleep")
49 int strncmp_bad_not_null_term_target(void *ctx)
50 {
51 	/* Compared target is not null-terminated, so will fail */
52 	cmp_ret = bpf_strncmp(str, STRNCMP_STR_SZ, no_str_target);
53 	return 0;
54 }
55