Debian Codegraph @

src/bpf/userns-restrict.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 /* If offsetof() is implemented via __builtin_offset() then it doesn't work on current compilers, since the
10 * built-ins do not understand CO-RE. Let's undefine any such macros here, to force bpf_helpers.h to define
11 * its own definitions for this. (In new versions it will do so automatically, but at least in libbpf 1.1.0
12 * it does not.) */
13 #undef offsetof
14 #undef container_of
15
16 #include "vmlinux.h"
17
18 #include <errno.h> /* IWYU pragma: keep */
19 #include <bpf/bpf_core_read.h>
20 #include <bpf/bpf_helpers.h>
21 #include <bpf/bpf_tracing.h>
22
23 #define CONTAINER_UID_MIN ((uid_t) CONTAINER_UID_BASE_MIN)
24 #define CONTAINER_UID_MAX ((uid_t) CONTAINER_UID_BASE_MAX + 0xFFFFU)
25
26 #ifndef bpf_core_cast
27 /* bpf_rdonly_cast() was introduced in libbpf commit 688879f together with
28 * the definition of a bpf_core_cast macro. So use that one to avoid
29 * defining a prototype for bpf_rdonly_cast */
30 void* bpf_rdonly_cast(const void *, __u32) __ksym;
31 #endif
32
33 /* BPF module that implements an allowlist of mounts (identified by mount ID) for user namespaces (identified
34 * by their inode number in nsfs) that restricts creation of inodes (which would inherit the callers UID/GID)
35 * or changing of ownership (similar).
36 *
37 * This hooks into the various path-based LSM entrypoints that control inode creation as well as chown(), and
38 * then looks up the calling process' user namespace in a global map of namespaces, which points us to
39 * another map that is simply a list of allowed mnt_ids. */
40
41 // FIXME: ACL adjustments are currently not blocked. There's no path-based LSM hook available in the kernel
42 // for setting xattrs or ACLs, hence we cannot easily block them, even though we want that. We can get away
43 // with ignoring this for now, as ACLs never define ownership, but purely access: i.e. ACLs never allow
44 // taking possession of an object, but only control access to it. Thus, things like suid access modes should
45 // not be reachable through it. It still sucks though that a user can persistently add an ACL entry to a file
46 // with their transient UIDs/GIDs.
47
48 /* kernel currently enforces a maximum usernamespace nesting depth of 32, see create_user_ns() in the kernel sources */
49 #define USER_NAMESPACE_DEPTH_MAX 32U
50
51 struct mnt_id_map {
52 __uint(type, BPF_MAP_TYPE_HASH);
53 __uint(max_entries, 1); /* placeholder, configured otherwise by nsresourced */
54 __type(key, int);
55 __type(value, int);
56 };
57
58 struct {
59 __uint(type, BPF_MAP_TYPE_HASH_OF_MAPS);
60 __uint(max_entries, 1); /* placeholder, configured otherwise by nsresourced */
61 __type(key, unsigned); /* userns inode */
62 __array(values, struct mnt_id_map);
63 } userns_mnt_id_hash SEC(".maps");
64
65 struct {
66 __uint(type, BPF_MAP_TYPE_HASH);
67 __uint(max_entries, 1); /* placeholder, configured otherwise by nsresourced */
68 __type(key, unsigned); /* userns inode */
69 __type(value, int); /* dummy value */
70 } userns_setgroups_deny SEC(".maps");
71
72 struct {
73 __uint(type, BPF_MAP_TYPE_RINGBUF);
74 __uint(max_entries, 4096);
75 } userns_ringbuf SEC(".maps");
76
77 static inline struct mount *real_mount(struct vfsmount *mnt) {
78 return container_of(mnt, struct mount, mnt);
79 }
80
81 static inline bool uid_is_dynamic(uid_t uid) {
82 return DYNAMIC_UID_MIN <= uid && uid <= DYNAMIC_UID_MAX;
83 }
84
85 static inline bool uid_is_container(uid_t uid) {
86 return CONTAINER_UID_MIN <= uid && uid <= CONTAINER_UID_MAX;
87 }
88
89 static inline bool uid_is_transient(uid_t uid) {
90 return uid_is_dynamic(uid) || uid_is_container(uid);
91 }
92
93 static int userns_owns_mount(struct user_namespace *userns, struct vfsmount *v) {
94 struct user_namespace *mount_userns, *p;
95 struct mount *m;
96
97 /* Get user namespace from vfsmount */
98 m = bpf_rdonly_cast(real_mount(v), bpf_core_type_id_kernel(struct mount));
99 mount_userns = m->mnt_ns->user_ns;
100
101 p = mount_userns;
102 for (unsigned i = 0; i < USER_NAMESPACE_DEPTH_MAX; i++) {
103 if (p == userns)
104 return true;
105
106 p = p->parent;
107 if (!p)
108 break;
109 }
110
111 /* Hmm, something is fishy if there's more than 32 levels of namespaces involved. Let's better be
112 * safe than sorry, and refuse. */
113 if (p)
114 return -EPERM;
115
116 return false;
117 }
118
119 static int validate_mount(struct vfsmount *v, int ret) {
120 struct user_namespace *task_userns;
121 unsigned task_userns_inode;
122 const struct cred *cred;
123 struct task_struct *task;
124 void *mnt_id_map;
125 struct mount *m;
126 int mnt_id, r;
127
128 if (ret != 0) /* propagate earlier error */
129 return ret;
130
131 /* Get user namespace from task */
132 task = (struct task_struct*) bpf_get_current_task_btf();
133 cred = task->cred;
134 if (!cred)
135 return -EPERM;
136 task_userns = cred->user_ns;
137
138 /* fsuid/fsgid are the UID/GID in the initial user namespace, before any idmapped mounts have been
139 * applied. There is no way (yet) to figure out what the UID/GID that will be written to disk will be
140 * after idmapped mounts are taken into account, hence we have to rely on an allowlist of mounts
141 * populated by userspace which tells us if a mount has an appropriate uid mapping in place to
142 * translate the transient UID range to something else. For other UIDs/GIDs, there's no need to do
143 * these checks as we don't insist on idmapped mounts or such for UIDs/GIDs outside the transient
144 * ranges. */
145 if (!uid_is_transient(cred->fsuid.val) && !uid_is_transient((uid_t) cred->fsgid.val))
146 return 0;
147
148 r = userns_owns_mount(task_userns, v);
149 if (r < 0)
150 return r;
151 /* Is the file on a mount that belongs to our own user namespace or a child of it? If so, say
152 * yes immediately. */
153 if (r > 0)
154 return 0;
155
156 /* This is a mount foreign to our task's user namespace, let's consult our allow list */
157 task_userns_inode = task_userns->ns.inum;
158
159 mnt_id_map = bpf_map_lookup_elem(&userns_mnt_id_hash, &task_userns_inode);
160 if (!mnt_id_map) /* No rules installed for this userns? Then say yes, too! */
161 return 0;
162
163 m = bpf_rdonly_cast(real_mount(v), bpf_core_type_id_kernel(struct mount));
164 mnt_id = m->mnt_id;
165
166 /* Otherwise, say yes if the mount ID is allowlisted */
167 if (bpf_map_lookup_elem(mnt_id_map, &mnt_id))
168 return 0;
169
170 return -EPERM;
171 }
172
173 SEC("lsm/path_chown")
174 int BPF_PROG(userns_restrict_path_chown, struct path *path, unsigned long long uid, unsigned long long gid, int ret) {
175 struct user_namespace *task_userns;
176 unsigned task_userns_inode;
177 const struct cred *cred;
178 struct task_struct *task;
179 struct vfsmount *v;
180 void *mnt_id_map;
181 int r;
182
183 if (ret != 0) /* propagate earlier error */
184 return ret;
185
186 /* Get user namespace from task */
187 task = (struct task_struct*) bpf_get_current_task_btf();
188 cred = task->cred;
189 if (!cred)
190 return -EPERM;
191 task_userns = cred->user_ns;
192 v = path->mnt;
193
194 r = userns_owns_mount(task_userns, v);
195 if (r < 0)
196 return r;
197 /* Is the file on a mount that belongs to our own user namespace or a child of it? If so, say
198 * yes immediately. */
199 if (r > 0)
200 return 0;
201
202 /* This is a mount foreign to our task's user namespace, if the user namespace was provisioned by
203 * nsresourced, refuse any UIDs/GIDs in the transient ranges. Note that we can only do this check in
204 * the chown() hook because it receives the UID/GID with idmapped mounts already taken into account,
205 * unlike the other hooks where we cannot (yet) figure out the UID/GID after idmapped mounts are
206 * applied. Hence in the other hooks we have to rely on the mount allowlist to ensure the transient
207 * fsuid/fsgid will be translated to something else when written to disk but in the chown() hook we
208 * can check the provided UID/GID directly to see if it is transient or not. */
209
210 /* User namespaces that were not provisioned by nsresourced can still write to the transient ranges
211 * so that we don't break use cases like systemd-nspawn's --private-users=pick switch. */
212
213 task_userns_inode = task_userns->ns.inum;
214
215 mnt_id_map = bpf_map_lookup_elem(&userns_mnt_id_hash, &task_userns_inode);
216 if (!mnt_id_map) /* No rules installed for this userns? Then say yes, too! */
217 return 0;
218
219 if (uid_is_transient((uid_t) uid) || uid_is_transient((uid_t) gid))
220 return -EPERM;
221
222 return 0;
223 }
224
225 SEC("lsm/path_mkdir")
226 int BPF_PROG(userns_restrict_path_mkdir, struct path *dir, struct dentry *dentry, umode_t mode, int ret) {
227 return validate_mount(dir->mnt, ret);
228 }
229
230 /* The mknod hook covers all file creations, including regular files, in case the reader is looking for a
231 * missing hook for open(). */
232 SEC("lsm/path_mknod")
233 int BPF_PROG(userns_restrict_path_mknod, const struct path *dir, struct dentry *dentry, umode_t mode, unsigned dev, int ret) {
234 return validate_mount(dir->mnt, ret);
235 }
236
237 SEC("lsm/path_symlink")
238 int BPF_PROG(userns_restrict_path_symlink, const struct path *dir, struct dentry *dentry, const char *old_name, int ret) {
239 return validate_mount(dir->mnt, ret);
240 }
241
242 SEC("lsm/path_link")
243 int BPF_PROG(userns_restrict_path_link, struct dentry *old_dentry, const struct path *new_dir, struct dentry *new_dentry, int ret) {
244 return validate_mount(new_dir->mnt, ret);
245 }
246
247 SEC("lsm/task_fix_setgroups")
248 int BPF_PROG(userns_restrict_task_fix_setgroups, struct cred *new_cred, const struct cred *old, int ret) {
249 struct user_namespace *p;
250 unsigned inode;
251
252 if (ret != 0) /* propagate earlier error */
253 return ret;
254
255 /* Walk the task's user namespace and its ancestors to find the first one managed by nsresourced
256 * (i.e. present in either the setgroups deny map or the mount ID hash map). This is necessary
257 * because a task could otherwise trivially bypass the setgroups() restriction by unsharing the user
258 * namespace and mapping the same users and groups. */
259 p = new_cred->user_ns;
260 for (unsigned i = 0; i < USER_NAMESPACE_DEPTH_MAX; i++) {
261 if (!p)
262 break;
263
264 inode = p->ns.inum;
265
266 if (bpf_map_lookup_elem(&userns_setgroups_deny, &inode))
267 return -EPERM;
268
269 if (bpf_map_lookup_elem(&userns_mnt_id_hash, &inode))
270 return 0;
271
272 p = p->parent;
273 }
274
275 /* No nsresourced-managed ancestor found, allow. */
276 return 0;
277 }
278
279 SEC("kprobe/retire_userns_sysctls")
280 int BPF_KPROBE(userns_restrict_retire_userns_sysctls, struct user_namespace *userns) {
281 unsigned inode;
282
283 /* Inform userspace that a user namespace just went away. I wish there was a nicer way to hook into
284 * user namespaces being deleted than using kprobes, but couldn't find any. */
285 userns = bpf_rdonly_cast(userns, bpf_core_type_id_kernel(struct user_namespace));
286 inode = userns->ns.inum;
287
288 /* Check each map separately to avoid the compiler merging the two lookups into a pointer OR
289 * operation, which the BPF verifier rejects. */
290 if (bpf_map_lookup_elem(&userns_mnt_id_hash, &inode))
291 goto notify;
292
293 if (bpf_map_lookup_elem(&userns_setgroups_deny, &inode))
294 goto notify;
295
296 /* No rules installed for this userns? Then send no notification. */
297 return 0;
298
299 notify:
300 bpf_ringbuf_output(&userns_ringbuf, &inode, sizeof(inode), 0);
301 return 0;
302 }
303
304 static const char _license[] SEC("license") = "GPL";