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

selftests/bpf: Add sockopt case to verify prog_type

Make sure only sockopt programs can be attached to the setsockopt
and getsockopt hooks.

Signed-off-by: Stanislav Fomichev <sdf@google.com>
Acked-by: Eduard Zingerman <eddyz87@gmail.com>
Link: https://lore.kernel.org/r/20240426231621.2716876-4-sdf@google.com
Signed-off-by: Martin KaFai Lau <martin.lau@kernel.org>

authored by

Stanislav Fomichev and committed by
Martin KaFai Lau
095ddb50 d70b2660

+38 -2
+38 -2
tools/testing/selftests/bpf/prog_tests/sockopt.c
··· 24 24 static struct sockopt_test { 25 25 const char *descr; 26 26 const struct bpf_insn insns[64]; 27 + enum bpf_prog_type prog_type; 27 28 enum bpf_attach_type attach_type; 28 29 enum bpf_attach_type expected_attach_type; 29 30 ··· 929 928 930 929 .error = EPERM_SETSOCKOPT, 931 930 }, 931 + 932 + /* ==================== prog_type ==================== */ 933 + 934 + { 935 + .descr = "can attach only BPF_CGROUP_SETSOCKOP", 936 + .insns = { 937 + /* return 1 */ 938 + BPF_MOV64_IMM(BPF_REG_0, 1), 939 + BPF_EXIT_INSN(), 940 + 941 + }, 942 + .prog_type = BPF_PROG_TYPE_CGROUP_SKB, 943 + .attach_type = BPF_CGROUP_SETSOCKOPT, 944 + .expected_attach_type = 0, 945 + .error = DENY_ATTACH, 946 + }, 947 + 948 + { 949 + .descr = "can attach only BPF_CGROUP_GETSOCKOP", 950 + .insns = { 951 + /* return 1 */ 952 + BPF_MOV64_IMM(BPF_REG_0, 1), 953 + BPF_EXIT_INSN(), 954 + 955 + }, 956 + .prog_type = BPF_PROG_TYPE_CGROUP_SKB, 957 + .attach_type = BPF_CGROUP_GETSOCKOPT, 958 + .expected_attach_type = 0, 959 + .error = DENY_ATTACH, 960 + }, 932 961 }; 933 962 934 963 static int load_prog(const struct bpf_insn *insns, 964 + enum bpf_prog_type prog_type, 935 965 enum bpf_attach_type expected_attach_type) 936 966 { 937 967 LIBBPF_OPTS(bpf_prog_load_opts, opts, ··· 979 947 } 980 948 insns_cnt++; 981 949 982 - fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCKOPT, NULL, "GPL", insns, insns_cnt, &opts); 950 + fd = bpf_prog_load(prog_type, NULL, "GPL", insns, insns_cnt, &opts); 983 951 if (verbose && fd < 0) 984 952 fprintf(stderr, "%s\n", bpf_log_buf); 985 953 ··· 1071 1039 static int run_test(int cgroup_fd, struct sockopt_test *test, bool use_io_uring, 1072 1040 bool use_link) 1073 1041 { 1042 + int prog_type = BPF_PROG_TYPE_CGROUP_SOCKOPT; 1074 1043 int sock_fd, err, prog_fd, link_fd = -1; 1075 1044 void *optval = NULL; 1076 1045 int ret = 0; 1077 1046 1078 - prog_fd = load_prog(test->insns, test->expected_attach_type); 1047 + if (test->prog_type) 1048 + prog_type = test->prog_type; 1049 + 1050 + prog_fd = load_prog(test->insns, prog_type, test->expected_attach_type); 1079 1051 if (prog_fd < 0) { 1080 1052 if (test->error == DENY_LOAD) 1081 1053 return 0;