1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/bpf.h>
3 #include <bpf/bpf_helpers.h>
4 #include <bpf/bpf_tracing.h>
5 #include <errno.h>
6 #include <linux/capability.h>
7 
8 struct kernel_cap_struct {
9 	__u32 cap[_LINUX_CAPABILITY_U32S_3];
10 } __attribute__((preserve_access_index));
11 
12 struct cred {
13 	struct kernel_cap_struct cap_effective;
14 } __attribute__((preserve_access_index));
15 
16 char _license[] SEC("license") = "GPL";
17 
18 SEC("lsm.s/userns_create")
19 int BPF_PROG(test_userns_create, const struct cred *cred, int ret)
20 {
21 	struct kernel_cap_struct caps = cred->cap_effective;
22 	int cap_index = CAP_TO_INDEX(CAP_SYS_ADMIN);
23 	__u32 cap_mask = CAP_TO_MASK(CAP_SYS_ADMIN);
24 
25 	if (ret)
26 		return 0;
27 
28 	ret = -EPERM;
29 	if (caps.cap[cap_index] & cap_mask)
30 		return 0;
31 
32 	return -EPERM;
33 }
34