Debian Codegraph @

src/bpf/restrict-fs.bpf.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 /* The SPDX header above is actually correct in claiming this was
4 * LGPL-2.1-or-later, because it is. Since the kernel doesn't consider that
5 * compatible with GPL we will claim this to be GPL however, which should be
6 * fine given that LGPL-2.1-or-later downgrades to GPL if needed.
7 */
8
9 #include <errno.h>
10 #include <linux/bpf.h>
11 #include <linux/types.h>
12 #include <stddef.h>
13 #include <stdint.h>
14 #include <bpf/bpf_core_read.h>
15 #include <bpf/bpf_helpers.h>
16 #include <bpf/bpf_tracing.h>
17
18 struct super_block {
19 unsigned long s_magic;
20 } __attribute__((preserve_access_index));
21
22 struct inode {
23 struct super_block *i_sb;
24 } __attribute__((preserve_access_index));
25
26 struct file {
27 struct inode *f_inode;
28 } __attribute__((preserve_access_index));
29
30 /*
31 * max_entries is set from user space with the bpf_map__set_max_entries helper.
32 * */
33 struct {
34 __uint(type, BPF_MAP_TYPE_HASH_OF_MAPS);
35 __type(key, uint64_t); /* cgroup ID */
36 __type(value, uint32_t); /* fs magic set */
37 } cgroup_hash SEC(".maps");
38
39 SEC("lsm/file_open")
40 int BPF_PROG(restrict_filesystems, struct file *file, int ret)
41 {
42 unsigned long raw_magic_number;
43 uint64_t cgroup_id;
44 uint32_t *value, *magic_map, magic_number, zero = 0, *is_allow;
45
46 /* ret is the return value from the previous BPF program or 0 if it's
47 * the first hook */
48 if (ret != 0)
49 return ret;
50
51 BPF_CORE_READ_INTO(&raw_magic_number, file, f_inode, i_sb, s_magic);
52 /* super_block.s_magic is unsigned long, but magic_map keys are
53 * uint32_t. Using s_magic as-is would fail on big-endian systems,
54 * which have 64-bit unsigned long. So cast it. */
55 magic_number = (uint32_t)raw_magic_number;
56
57 cgroup_id = bpf_get_current_cgroup_id();
58
59 magic_map = bpf_map_lookup_elem(&cgroup_hash, &cgroup_id);
60 if (!magic_map)
61 return 0;
62
63 is_allow = bpf_map_lookup_elem(magic_map, &zero);
64 if (!is_allow)
65 /* Malformed map, it doesn't include whether it's an allow list
66 * or a deny list. Allow. */
67 return 0;
68
69 if (*is_allow) {
70 /* Allow-list: Allow access only if magic_number present in inner map */
71 if (!bpf_map_lookup_elem(magic_map, &magic_number))
72 return -EPERM;
73 } else {
74 /* Deny-list: Allow access only if magic_number is not present in inner map */
75 if (bpf_map_lookup_elem(magic_map, &magic_number))
76 return -EPERM;
77 }
78
79 return 0;
80 }
81
82 static const char _license[] SEC("license") = "GPL";