Debian Codegraph @

src/basic/namespace-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <linux/magic.h>
5 #include <linux/nsfs.h>
6 #include <sched.h>
7 #include <sys/ioctl.h>
8 #include <sys/mount.h>
9 #include <unistd.h>
10
11 #include "capability-util.h"
12 #include "dlfcn-util.h"
13 #include "errno-util.h"
14 #include "fd-util.h"
15 #include "fileio.h"
16 #include "log.h"
17 #include "mountpoint-util.h"
18 #include "namespace-util.h"
19 #include "parse-util.h"
20 #include "pidfd-util.h"
21 #include "pidref.h"
22 #include "process-util.h"
23 #include "stat-util.h"
24 #include "stdio-util.h"
25 #include "uid-range.h"
26 #include "unaligned.h"
27 #include "user-util.h"
28
29 const struct namespace_info namespace_info[_NAMESPACE_TYPE_MAX + 1] = {
30 [NAMESPACE_CGROUP] = { "cgroup", "ns/cgroup", CLONE_NEWCGROUP, PIDFD_GET_CGROUP_NAMESPACE, PROC_CGROUP_INIT_INO },
31 [NAMESPACE_IPC] = { "ipc", "ns/ipc", CLONE_NEWIPC, PIDFD_GET_IPC_NAMESPACE, PROC_IPC_INIT_INO },
32 [NAMESPACE_NET] = { "net", "ns/net", CLONE_NEWNET, PIDFD_GET_NET_NAMESPACE, 0 },
33 /* So, the mount namespace flag is called CLONE_NEWNS for historical
34 * reasons. Let's expose it here under a more explanatory name: "mnt".
35 * This is in-line with how the kernel exposes namespaces in /proc/$PID/ns. */
36 [NAMESPACE_MOUNT] = { "mnt", "ns/mnt", CLONE_NEWNS, PIDFD_GET_MNT_NAMESPACE, 0 },
37 [NAMESPACE_PID] = { "pid", "ns/pid", CLONE_NEWPID, PIDFD_GET_PID_NAMESPACE, PROC_PID_INIT_INO },
38 [NAMESPACE_USER] = { "user", "ns/user", CLONE_NEWUSER, PIDFD_GET_USER_NAMESPACE, PROC_USER_INIT_INO },
39 [NAMESPACE_UTS] = { "uts", "ns/uts", CLONE_NEWUTS, PIDFD_GET_UTS_NAMESPACE, PROC_UTS_INIT_INO },
40 [NAMESPACE_TIME] = { "time", "ns/time", CLONE_NEWTIME, PIDFD_GET_TIME_NAMESPACE, PROC_TIME_INIT_INO },
41 {}, /* Allow callers to iterate over the array without using _NAMESPACE_TYPE_MAX. */
42 };
43
44 #define pid_namespace_path(pid, type) procfs_file_alloca(pid, namespace_info[type].proc_path)
45
46 NamespaceType clone_flag_to_namespace_type(unsigned long clone_flag) {
47 for (NamespaceType t = 0; t < _NAMESPACE_TYPE_MAX; t++)
48 if (((namespace_info[t].clone_flag ^ clone_flag) & (CLONE_NEWCGROUP|CLONE_NEWIPC|CLONE_NEWNET|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUSER|CLONE_NEWUTS|CLONE_NEWTIME)) == 0)
49 return t;
50
51 return _NAMESPACE_TYPE_INVALID;
52 }
53
54 bool namespace_type_supported(NamespaceType type) {
55 assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
56
57 const char *p = pid_namespace_path(0, type);
58 return access(p, F_OK) >= 0;
59 }
60
61 static int pidref_namespace_open_by_type_internal(const PidRef *pidref, NamespaceType type, bool *need_verify) {
62 int r;
63
64 assert(pidref_is_set(pidref));
65 assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
66
67 if (pidref_is_remote(pidref))
68 return -EREMOTE;
69
70 if (pidref->fd >= 0) {
71 r = pidfd_get_namespace(pidref->fd, namespace_info[type].pidfd_get_ns_ioctl_cmd);
72 if (r == -ENOPKG)
73 return log_debug_errno(
74 r,
75 "Cannot open %s namespace for PID "PID_FMT" as the namespace type is not supported by the kernel",
76 namespace_info[type].proc_name, pidref->pid);
77 if (!ERRNO_IS_NEG_NOT_SUPPORTED(r))
78 return r;
79 }
80
81 if (need_verify) /* The caller shall call pidref_verify() later */
82 *need_verify = true;
83
84 _cleanup_close_ int nsfd = -EBADF;
85 const char *p;
86
87 p = pid_namespace_path(pidref->pid, type);
88 nsfd = RET_NERRNO(open(p, O_RDONLY|O_NOCTTY|O_CLOEXEC));
89 if (nsfd == -ENOENT) {
90 r = proc_mounted();
91 if (r == 0)
92 /* /proc/ is not available or not set up properly, we're most likely in some chroot environment. */
93 return log_debug_errno(
94 SYNTHETIC_ERRNO(ENOSYS),
95 "Cannot open %s namespace for PID "PID_FMT" as /proc is not mounted",
96 namespace_info[type].proc_name, pidref->pid);
97 if (r > 0)
98 /* If /proc/ is definitely around then this means the namespace type is not supported */
99 return log_debug_errno(
100 SYNTHETIC_ERRNO(ENOPKG),
101 "Cannot open %s namespace for PID "PID_FMT" via /proc as the namespace type is not supported by the kernel",
102 namespace_info[type].proc_name, pidref->pid);
103
104 /* can't determine? then propagate original error */
105 }
106 if (nsfd < 0)
107 return nsfd;
108
109 if (!need_verify) { /* Otherwise we verify on our own */
110 r = pidref_verify(pidref);
111 if (r < 0)
112 return r;
113 }
114
115 return TAKE_FD(nsfd);
116 }
117
118 int pidref_namespace_open_by_type(const PidRef *pidref, NamespaceType type) {
119 return pidref_namespace_open_by_type_internal(pidref, type, NULL);
120 }
121
122 int namespace_open_by_type(NamespaceType type) {
123 _cleanup_(pidref_done) PidRef self = PIDREF_NULL;
124 int r;
125
126 assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
127
128 r = pidref_set_self(&self);
129 if (r < 0)
130 return r;
131
132 return pidref_namespace_open_by_type(&self, type);
133 }
134
135 int pidref_namespace_open(
136 const PidRef *pidref,
137 int *ret_pidns_fd,
138 int *ret_mntns_fd,
139 int *ret_netns_fd,
140 int *ret_userns_fd,
141 int *ret_root_fd) {
142
143 _cleanup_close_ int pidns_fd = -EBADF, mntns_fd = -EBADF, netns_fd = -EBADF,
144 userns_fd = -EBADF, root_fd = -EBADF;
145 bool need_verify = false;
146 int r;
147
148 assert(pidref_is_set(pidref));
149
150 if (pidref_is_remote(pidref))
151 return -EREMOTE;
152
153 if (ret_pidns_fd) {
154 pidns_fd = pidref_namespace_open_by_type_internal(pidref, NAMESPACE_PID, &need_verify);
155 if (pidns_fd < 0)
156 return pidns_fd;
157 }
158
159 if (ret_mntns_fd) {
160 mntns_fd = pidref_namespace_open_by_type_internal(pidref, NAMESPACE_MOUNT, &need_verify);
161 if (mntns_fd < 0)
162 return mntns_fd;
163 }
164
165 if (ret_netns_fd) {
166 netns_fd = pidref_namespace_open_by_type_internal(pidref, NAMESPACE_NET, &need_verify);
167 if (netns_fd < 0)
168 return netns_fd;
169 }
170
171 if (ret_userns_fd) {
172 userns_fd = pidref_namespace_open_by_type_internal(pidref, NAMESPACE_USER, &need_verify);
173 if (userns_fd < 0 && userns_fd != -ENOPKG)
174 return userns_fd;
175 }
176
177 if (ret_root_fd) {
178 const char *root;
179
180 root = procfs_file_alloca(pidref->pid, "root");
181 root_fd = RET_NERRNO(open(root, O_CLOEXEC|O_DIRECTORY));
182 if (root_fd == -ENOENT && proc_mounted() == 0)
183 return -ENOSYS;
184 if (root_fd < 0)
185 return root_fd;
186
187 need_verify = true;
188 }
189
190 if (need_verify) {
191 r = pidref_verify(pidref);
192 if (r < 0)
193 return r;
194 }
195
196 if (ret_pidns_fd)
197 *ret_pidns_fd = TAKE_FD(pidns_fd);
198
199 if (ret_mntns_fd)
200 *ret_mntns_fd = TAKE_FD(mntns_fd);
201
202 if (ret_netns_fd)
203 *ret_netns_fd = TAKE_FD(netns_fd);
204
205 if (ret_userns_fd)
206 *ret_userns_fd = TAKE_FD(userns_fd);
207
208 if (ret_root_fd)
209 *ret_root_fd = TAKE_FD(root_fd);
210
211 return 0;
212 }
213
214 int namespace_open(
215 pid_t pid,
216 int *ret_pidns_fd,
217 int *ret_mntns_fd,
218 int *ret_netns_fd,
219 int *ret_userns_fd,
220 int *ret_root_fd) {
221
222 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
223 int r;
224
225 r = pidref_set_pid(&pidref, pid);
226 if (r < 0)
227 return r;
228
229 return pidref_namespace_open(&pidref, ret_pidns_fd, ret_mntns_fd, ret_netns_fd, ret_userns_fd, ret_root_fd);
230 }
231
232 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int userns_fd, int root_fd) {
233 int r;
234
235 /* Block dlopen() now, to avoid us inadvertently loading shared library from another namespace */
236 block_dlopen();
237
238 /* Join namespaces, but only if we're not part of them already. This is important if we don't
239 * necessarily own the namespace in question, as kernel would unconditionally return EPERM otherwise. */
240
241 if (pidns_fd >= 0) {
242 r = is_our_namespace(pidns_fd, NAMESPACE_PID);
243 if (r < 0)
244 return r;
245 if (r > 0)
246 pidns_fd = -EBADF;
247 }
248
249 if (mntns_fd >= 0) {
250 r = is_our_namespace(mntns_fd, NAMESPACE_MOUNT);
251 if (r < 0)
252 return r;
253 if (r > 0)
254 mntns_fd = -EBADF;
255 }
256
257 if (netns_fd >= 0) {
258 r = is_our_namespace(netns_fd, NAMESPACE_NET);
259 if (r < 0)
260 return r;
261 if (r > 0)
262 netns_fd = -EBADF;
263 }
264
265 if (userns_fd >= 0) {
266 /* Can't setns to your own userns, since then you could escalate from non-root to root in
267 * your own namespace, so check if namespaces are equal before attempting to enter. */
268
269 r = is_our_namespace(userns_fd, NAMESPACE_USER);
270 if (r < 0)
271 return r;
272 if (r > 0)
273 userns_fd = -EBADF;
274 }
275
276 r = have_effective_cap(CAP_SYS_ADMIN);
277 if (r < 0)
278 return r;
279
280 bool have_cap_sys_admin = r > 0;
281
282 if (!have_cap_sys_admin) {
283 /* If we don't have CAP_SYS_ADMIN in our own user namespace, our best bet is to enter the
284 * user namespace first (if we got one) to get CAP_SYS_ADMIN within the child user namespace,
285 * and then hope the other namespaces are owned by the child user namespace. If they aren't,
286 * we'll just get an EPERM later on when trying to setns() to them. */
287
288 if (userns_fd < 0)
289 return log_debug_errno(
290 SYNTHETIC_ERRNO(EPERM),
291 "Need CAP_SYS_ADMIN or a child user namespace to enter namespaces.");
292
293 if (setns(userns_fd, CLONE_NEWUSER) < 0)
294 return -errno;
295 }
296
297 if (pidns_fd >= 0)
298 if (setns(pidns_fd, CLONE_NEWPID) < 0)
299 return -errno;
300
301 if (mntns_fd >= 0)
302 if (setns(mntns_fd, CLONE_NEWNS) < 0)
303 return -errno;
304
305 if (netns_fd >= 0)
306 if (setns(netns_fd, CLONE_NEWNET) < 0)
307 return -errno;
308
309 if (userns_fd >= 0 && have_cap_sys_admin)
310 if (setns(userns_fd, CLONE_NEWUSER) < 0)
311 return -errno;
312
313 if (root_fd >= 0) {
314 if (fchdir(root_fd) < 0)
315 return -errno;
316
317 if (chroot(".") < 0)
318 return -errno;
319 }
320
321 if (userns_fd >= 0) {
322 /* Try to become root in the user namespace but don't error out if we can't, since it's not
323 * uncommon to have user namespaces without a root user in them. */
324 r = reset_uid_gid();
325 if (r < 0)
326 log_debug_errno(r, "Unable to drop auxiliary groups or reset UID/GID, ignoring: %m");
327 }
328
329 return 0;
330 }
331
332 int fd_is_namespace(int fd, NamespaceType type) {
333 int r;
334
335 /* Checks whether the specified file descriptor refers to a namespace (of type if type != _NAMESPACE_INVALID). */
336
337 assert(fd >= 0);
338 assert(type < _NAMESPACE_TYPE_MAX);
339
340 r = fd_is_fs_type(fd, NSFS_MAGIC);
341 if (r <= 0)
342 return r;
343
344 if (type < 0)
345 return true;
346
347 int clone_flag = ioctl(fd, NS_GET_NSTYPE);
348 if (clone_flag < 0)
349 return -errno;
350
351 NamespaceType found_type = clone_flag_to_namespace_type(clone_flag);
352 if (found_type < 0)
353 return -EBADF; /* Uh? Unknown namespace type? */
354
355 return found_type == type;
356 }
357
358 int is_our_namespace(int fd, NamespaceType type) {
359 int r;
360
361 assert(fd >= 0);
362 assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
363
364 r = fd_is_namespace(fd, type);
365 if (r < 0)
366 return r;
367 if (r == 0) /* Not a namespace or not of the right type? */
368 return -EUCLEAN;
369
370 _cleanup_close_ int our_ns = namespace_open_by_type(type);
371 if (our_ns < 0)
372 return our_ns;
373
374 return fd_inode_same(fd, our_ns);
375 }
376
377 int are_our_namespaces(int pidns_fd, int mntns_fd, int netns_fd, int userns_fd, int root_fd) {
378 int r;
379
380 if (pidns_fd >= 0) {
381 r = is_our_namespace(pidns_fd, NAMESPACE_PID);
382 if (r <= 0)
383 return r;
384 }
385
386 if (mntns_fd >= 0) {
387 r = is_our_namespace(mntns_fd, NAMESPACE_MOUNT);
388 if (r <= 0)
389 return r;
390 }
391
392 if (netns_fd >= 0) {
393 r = is_our_namespace(netns_fd, NAMESPACE_NET);
394 if (r <= 0)
395 return r;
396 }
397
398 if (userns_fd >= 0) {
399 r = is_our_namespace(userns_fd, NAMESPACE_USER);
400 if (r <= 0)
401 return r;
402 }
403
404 if (root_fd >= 0) {
405 r = dir_fd_is_root(root_fd);
406 if (r <= 0)
407 return r;
408 }
409
410 return true;
411 }
412
413 int namespace_is_init(NamespaceType type) {
414 int r;
415
416 assert(type >= 0);
417 assert(type < _NAMESPACE_TYPE_MAX);
418
419 if (namespace_info[type].root_inode == 0)
420 return -EBADR; /* Cannot answer this question */
421
422 const char *p = pid_namespace_path(0, type);
423
424 struct stat st;
425 r = RET_NERRNO(stat(p, &st));
426 if (r == -ENOENT) {
427 /* If the /proc/ns/<type> API is not around in /proc/ then ns is off in the kernel and we are in the init ns */
428 r = proc_mounted();
429 if (r < 0)
430 return -ENOENT; /* If we can't determine if /proc/ is mounted propagate original error */
431
432 return r ? true : -ENOSYS;
433 }
434 if (r < 0)
435 return r;
436
437 return st.st_ino == namespace_info[type].root_inode;
438 }
439
440 int pidref_in_same_namespace(PidRef *pid1, PidRef *pid2, NamespaceType type) {
441 _cleanup_close_ int ns1 = -EBADF, ns2 = -EBADF;
442
443 /* Accepts NULL to indicate our own process */
444
445 assert(!pid1 || pidref_is_set(pid1));
446 assert(!pid2 || pidref_is_set(pid2));
447 assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
448
449 if (pidref_equal(pid1, pid2))
450 return true;
451
452 if (!pid1)
453 ns1 = namespace_open_by_type(type);
454 else
455 ns1 = pidref_namespace_open_by_type(pid1, type);
456 if (ns1 < 0)
457 return ns1;
458
459 if (!pid2)
460 ns2 = namespace_open_by_type(type);
461 else
462 ns2 = pidref_namespace_open_by_type(pid2, type);
463 if (ns2 < 0)
464 return ns2;
465
466 return fd_inode_same(ns1, ns2);
467 }
468
469 int in_same_namespace(pid_t pid1, pid_t pid2, NamespaceType type) {
470 assert(pid1 >= 0);
471 assert(pid2 >= 0);
472 return pidref_in_same_namespace(pid1 == 0 ? NULL : &PIDREF_MAKE_FROM_PID(pid1),
473 pid2 == 0 ? NULL : &PIDREF_MAKE_FROM_PID(pid2),
474 type);
475 }
476
477 int namespace_get_leader(PidRef *pidref, NamespaceType type, PidRef *ret) {
478 int r;
479
480 /* Note: we don't bother with pidref_is_set()/pidref_is_remote() here, as the first call we do,
481 * pidref_get_ppid_as_pidref() calls those anyway */
482
483 assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
484 assert(ret);
485
486 _cleanup_(pidref_done) PidRef current = PIDREF_NULL;
487 PidRef *c = pidref;
488
489 for (;;) {
490 _cleanup_(pidref_done) PidRef parent = PIDREF_NULL;
491
492 r = pidref_get_ppid_as_pidref(c, &parent);
493 if (r < 0)
494 return r;
495
496 r = pidref_in_same_namespace(c, &parent, type);
497 if (r < 0)
498 return r;
499 if (r == 0) {
500 /* If the parent and the child are not in the same namespace, then the child is
501 * the leader we are looking for. */
502
503 if (pidref_is_set(&current))
504 *ret = TAKE_PIDREF(current);
505 else {
506 r = pidref_copy(c, ret);
507 if (r < 0)
508 return r;
509 }
510
511 return 0;
512 }
513
514 pidref_done(&current);
515 current = TAKE_PIDREF(parent);
516 c = &current;
517 }
518 }
519
520 int detach_mount_namespace(void) {
521 /* Detaches the mount namespace, disabling propagation from our namespace to the host. Sets
522 * propagation first to MS_SLAVE for all mounts (disabling propagation), and then back to MS_SHARED
523 * (so that we create a new peer group). */
524
525 if (unshare(CLONE_NEWNS) < 0)
526 return log_debug_errno(errno, "Failed to acquire mount namespace: %m");
527
528 if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0)
529 return log_debug_errno(errno, "Failed to set mount propagation to MS_SLAVE for all mounts: %m");
530
531 if (mount(NULL, "/", NULL, MS_SHARED | MS_REC, NULL) < 0)
532 return log_debug_errno(errno, "Failed to set mount propagation back to MS_SHARED for all mounts: %m");
533
534 return 0;
535 }
536
537 int detach_mount_namespace_harder(uid_t target_uid, gid_t target_gid) {
538 uid_t from_uid;
539 gid_t from_gid;
540 int r;
541
542 /* Tried detach_mount_namespace() first. If that doesn't work due to permissions, opens up an
543 * unprivileged user namespace with a mapping of the originating UID/GID to the specified target
544 * UID/GID. Then, tries detach_mount_namespace() again.
545 *
546 * Or in other words: tries much harder to get a mount namespace, making use of unprivileged user
547 * namespaces if need be.
548 *
549 * Note that after this function completed:
550 *
551 * → if we had privs, afterwards uids/gids on files and processes are as before
552 *
553 * → if we had no privs, our own id and all our files will show up owned by target_uid/target_gid,
554 * and everything else owned by nobody.
555 *
556 * Yes, that's quite a difference. */
557
558 if (!uid_is_valid(target_uid))
559 return -EINVAL;
560 if (!gid_is_valid(target_gid))
561 return -EINVAL;
562
563 r = detach_mount_namespace();
564 if (r != -EPERM)
565 return r;
566
567 from_uid = getuid();
568 from_gid = getgid();
569
570 if (unshare(CLONE_NEWUSER) < 0)
571 return log_debug_errno(errno, "Failed to acquire user namespace: %m");
572
573 r = write_string_filef("/proc/self/uid_map", 0,
574 UID_FMT " " UID_FMT " 1\n", target_uid, from_uid);
575 if (r < 0)
576 return log_debug_errno(r, "Failed to write uid map: %m");
577
578 r = write_string_file("/proc/self/setgroups", "deny", 0);
579 if (r < 0)
580 return log_debug_errno(r, "Failed to write setgroups file: %m");
581
582 r = write_string_filef("/proc/self/gid_map", 0,
583 GID_FMT " " GID_FMT " 1\n", target_gid, from_gid);
584 if (r < 0)
585 return log_debug_errno(r, "Failed to write gid map: %m");
586
587 return detach_mount_namespace();
588 }
589
590 int detach_mount_namespace_userns(int userns_fd) {
591 int r;
592
593 assert(userns_fd >= 0);
594
595 if (setns(userns_fd, CLONE_NEWUSER) < 0)
596 return log_debug_errno(errno, "Failed to join user namespace: %m");
597
598 r = reset_uid_gid();
599 if (r < 0)
600 return log_debug_errno(r, "Failed to become root in user namespace: %m");
601
602 return detach_mount_namespace();
603 }
604
605 int parse_userns_uid_range(const char *s, uid_t *ret_uid_shift, uid_t *ret_uid_range) {
606 _cleanup_free_ char *buffer = NULL;
607 const char *range, *shift;
608 int r;
609 uid_t uid_shift, uid_range = 65536;
610
611 assert(s);
612
613 range = strchr(s, ':');
614 if (range) {
615 buffer = strndup(s, range - s);
616 if (!buffer)
617 return log_oom();
618 shift = buffer;
619
620 range++;
621 r = safe_atou32(range, &uid_range);
622 if (r < 0)
623 return log_error_errno(r, "Failed to parse UID range \"%s\": %m", range);
624 } else
625 shift = s;
626
627 r = parse_uid(shift, &uid_shift);
628 if (r < 0)
629 return log_error_errno(r, "Failed to parse UID \"%s\": %m", s);
630
631 if (!userns_shift_range_valid(uid_shift, uid_range))
632 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "UID range cannot be empty or go beyond " UID_FMT ".", UID_INVALID);
633
634 if (ret_uid_shift)
635 *ret_uid_shift = uid_shift;
636
637 if (ret_uid_range)
638 *ret_uid_range = uid_range;
639
640 return 0;
641 }
642
643 int userns_acquire_empty(void) {
644 _cleanup_(pidref_done_sigkill_wait) PidRef pid = PIDREF_NULL;
645 int r;
646
647 r = pidref_safe_fork("(sd-mkuserns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_NEW_USERNS|FORK_FREEZE, &pid);
648 if (r < 0)
649 return r;
650 assert(r > 0);
651
652 return pidref_namespace_open_by_type(&pid, NAMESPACE_USER);
653 }
654
655 int userns_acquire(const char *uid_map, const char *gid_map, bool setgroups_deny) {
656 char path[STRLEN("/proc//setgroups") + DECIMAL_STR_MAX(pid_t) + 1];
657 _cleanup_(pidref_done_sigkill_wait) PidRef pid = PIDREF_NULL;
658 int r;
659
660 assert(uid_map);
661 assert(gid_map);
662
663 /* Forks off a process in a new userns, configures the specified uidmap/gidmap, acquires an fd to it,
664 * and then kills the process again. This way we have a userns fd that is not bound to any
665 * process. We can use that for file system mounts and similar. */
666
667 r = pidref_safe_fork("(sd-mkuserns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_NEW_USERNS|FORK_FREEZE, &pid);
668 if (r < 0)
669 return r;
670 assert(r > 0);
671
672 xsprintf(path, "/proc/" PID_FMT "/uid_map", pid.pid);
673 r = write_string_file(path, uid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
674 if (r < 0)
675 return log_debug_errno(r, "Failed to write UID map: %m");
676
677 if (setgroups_deny) {
678 xsprintf(path, "/proc/" PID_FMT "/setgroups", pid.pid);
679 r = write_string_file(path, "deny", WRITE_STRING_FILE_DISABLE_BUFFER);
680 if (r < 0)
681 return log_debug_errno(r, "Failed to write setgroups file: %m");
682 }
683
684 xsprintf(path, "/proc/" PID_FMT "/gid_map", pid.pid);
685 r = write_string_file(path, gid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
686 if (r < 0)
687 return log_debug_errno(r, "Failed to write GID map: %m");
688
689 return pidref_namespace_open_by_type(&pid, NAMESPACE_USER);
690 }
691
692 int userns_acquire_self_root(void) {
693
694 /* Returns a user namespace with only our own uid/gid mapped to root, and everything else unmapped.
695 *
696 * Note: this can be acquired unprivileged! */
697
698 _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
699 if (asprintf(&uid_map, "0 " UID_FMT " 1", getuid()) < 0)
700 return -ENOMEM;
701 if (asprintf(&gid_map, "0 " GID_FMT " 1", getgid()) < 0)
702 return -ENOMEM;
703
704 return userns_acquire(uid_map, gid_map, /* setgroups_deny= */ true);
705 }
706
707 int userns_enter_and_pin(int userns_fd, PidRef *ret) {
708 _cleanup_close_pair_ int pfd[2] = EBADF_PAIR;
709 _cleanup_(pidref_done_sigkill_wait) PidRef pidref = PIDREF_NULL;
710 ssize_t n;
711 char x;
712 int r;
713
714 assert(userns_fd >= 0);
715 assert(ret);
716
717 if (pipe2(pfd, O_CLOEXEC) < 0)
718 return -errno;
719
720 r = pidref_safe_fork_full(
721 "(sd-pinuserns)",
722 /* stdio_fds= */ NULL,
723 (int[]) { pfd[1], userns_fd }, 2,
724 FORK_CLOSE_ALL_FDS|FORK_REOPEN_LOG|FORK_DEATHSIG_SIGKILL,
725 &pidref);
726 if (r < 0)
727 return r;
728 if (r == 0) {
729 /* Child. */
730
731 if (setns(userns_fd, CLONE_NEWUSER) < 0) {
732 log_debug_errno(errno, "Failed to join userns: %m");
733 _exit(EXIT_FAILURE);
734 }
735
736 userns_fd = safe_close(userns_fd);
737
738 n = write(pfd[1], &(const char) { 'x' }, 1);
739 if (n < 0) {
740 log_debug_errno(errno, "Failed to write to pipe: %m");
741 _exit(EXIT_FAILURE);
742 }
743 assert(n == 1);
744
745 freeze();
746 }
747
748 pfd[1] = safe_close(pfd[1]);
749
750 n = read(pfd[0], &x, 1);
751 if (n < 0)
752 return -errno;
753 if (n == 0)
754 return -EPROTO;
755 assert(n == 1);
756 assert(x == 'x');
757
758 *ret = TAKE_PIDREF(pidref);
759 return 0;
760 }
761
762 bool userns_supported(void) {
763 return access("/proc/self/uid_map", F_OK) >= 0;
764 }
765
766 int userns_get_base_uid(int userns_fd, uid_t *ret_uid, gid_t *ret_gid) {
767 _cleanup_(pidref_done_sigkill_wait) PidRef pidref = PIDREF_NULL;
768 int r;
769
770 assert(userns_fd >= 0);
771
772 r = userns_enter_and_pin(userns_fd, &pidref);
773 if (r < 0)
774 return r;
775
776 uid_t uid;
777 r = uid_map_search_root(pidref.pid, UID_RANGE_USERNS_OUTSIDE, &uid);
778 if (r < 0)
779 return r;
780
781 gid_t gid;
782 r = uid_map_search_root(pidref.pid, GID_RANGE_USERNS_OUTSIDE, &gid);
783 if (r < 0)
784 return r;
785
786 if (!ret_gid && uid != gid)
787 return -EUCLEAN;
788
789 if (ret_uid)
790 *ret_uid = uid;
791 if (ret_gid)
792 *ret_gid = gid;
793
794 return 0;
795 }
796
797 int process_is_owned_by_uid(const PidRef *pidref, uid_t uid) {
798 int r;
799
800 /* Checks if the specified process either is owned directly by the specified user, or if it is inside
801 * a user namespace owned by it. */
802
803 assert(uid_is_valid(uid));
804
805 uid_t process_uid;
806 r = pidref_get_uid(pidref, &process_uid);
807 if (r < 0)
808 return log_debug_errno(r, "Failed to get UID of process " PID_FMT ": %m", pidref->pid);
809 if (process_uid == uid)
810 return true;
811
812 log_debug("Process " PID_FMT " has UID " UID_FMT ", which doesn't match expected UID " UID_FMT ", checking user namespace ownership.",
813 pidref->pid, process_uid, uid);
814
815 _cleanup_close_ int userns_fd = -EBADF;
816 userns_fd = pidref_namespace_open_by_type(pidref, NAMESPACE_USER);
817 if (userns_fd == -ENOPKG) /* If userns is not supported, then they don't matter for ownership */
818 return false;
819 if (userns_fd < 0)
820 return log_debug_errno(userns_fd, "Failed to open user namespace of process " PID_FMT ": %m", pidref->pid);
821
822 for (unsigned iteration = 0;; iteration++) {
823 uid_t ns_uid;
824
825 /* This process is in our own userns? Then we are done, in our own userns only the UIDs
826 * themselves matter. */
827 r = is_our_namespace(userns_fd, NAMESPACE_USER);
828 if (r < 0)
829 return log_debug_errno(r, "Failed to check if user namespace of process " PID_FMT " is our own (iteration %u): %m", pidref->pid, iteration);
830 if (r > 0) {
831 log_debug("User namespace of process " PID_FMT " is our own namespace (iteration %u), not owned by expected UID.", pidref->pid, iteration);
832 return false;
833 }
834
835 if (ioctl(userns_fd, NS_GET_OWNER_UID, &ns_uid) < 0)
836 return log_debug_errno(errno, "Failed to get owner UID of user namespace of process " PID_FMT " (iteration %u): %m", pidref->pid, iteration);
837 if (ns_uid == uid) {
838 log_debug("User namespace of process " PID_FMT " is owned by UID " UID_FMT " (iteration %u), ownership check passed.", pidref->pid, uid, iteration);
839 return true;
840 }
841
842 log_debug("User namespace of process " PID_FMT " is owned by UID " UID_FMT ", expected UID " UID_FMT " (iteration %u), going up the tree.",
843 pidref->pid, ns_uid, uid, iteration);
844
845 /* Paranoia check */
846 if (iteration > 16)
847 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP), "Giving up while tracing parents of user namespaces after %u steps.", iteration);
848
849 /* Go up the tree */
850 _cleanup_close_ int parent_fd = ioctl(userns_fd, NS_GET_USERNS);
851 if (parent_fd < 0) {
852 if (errno == EPERM) { /* EPERM means we left our own userns */
853 log_debug("NS_GET_USERNS ioctl returned EPERM for process " PID_FMT " (iteration %u), left our own userns.", pidref->pid, iteration);
854 return false;
855 }
856
857 return log_debug_errno(errno, "NS_GET_USERNS ioctl failed for process " PID_FMT " (iteration %u): %m", pidref->pid, iteration);
858 }
859
860 close_and_replace(userns_fd, parent_fd);
861 }
862 }
863
864 int namespace_open_by_id(uint64_t ns_id) {
865 int r;
866
867 /* Looks up a namespace by its unique boot-stable identifier and returns an O_PATH fd to it.
868 * Requires kernel ≥ 6.13.
869 *
870 * Returns -ESTALE if the namespace no longer exists, or if the kernel refuses the lookup
871 * for permission reasons. The latter happens outside the initial user namespace: the
872 * kernel only permits open_by_handle_at() on nsfs when the caller is in the initial user
873 * and pid namespaces with CAP_SYS_ADMIN, with a narrow exception for lookups of the
874 * caller's own user namespace and its ancestors. To avoid conflating "namespace is dead"
875 * with "kernel refused us", we refuse early with -EPERM when we aren't in the initial
876 * user/pid namespace or missing CAP_SYS_ADMIN and let the caller skip the check. */
877
878 if (ns_id == 0)
879 return -EINVAL;
880
881 r = namespace_is_init(NAMESPACE_USER);
882 if (r < 0)
883 return r;
884 if (r == 0)
885 return -EPERM;
886
887 r = namespace_is_init(NAMESPACE_PID);
888 if (r < 0)
889 return r;
890 if (r == 0)
891 return -EPERM;
892
893 r = have_effective_cap(CAP_SYS_ADMIN);
894 if (r < 0)
895 return r;
896 if (r == 0)
897 return -EPERM;
898
899 /* The natural way to write this would be a compound designated initializer:
900 *
901 * union { ... } fh = {
902 * .file_handle.handle_bytes = sizeof(struct nsfs_file_handle),
903 * .file_handle.handle_type = FILEID_NSFS,
904 * };
905 *
906 * but that only zero-initializes the named struct members of struct file_handle.
907 * struct file_handle ends with a flexible array (`unsigned char f_handle[]`), whose
908 * storage comes from the overlapping `space[]` member of the union. Bytes in that storage
909 * are not covered by the partial struct initializer and end up as stack garbage. Zero the
910 * entire union first, then fill in the fields explicitly. */
911
912 union {
913 struct file_handle file_handle;
914 uint8_t space[offsetof(struct file_handle, f_handle) + sizeof(struct nsfs_file_handle)];
915 } fh = {};
916 fh.file_handle.handle_bytes = sizeof(struct nsfs_file_handle);
917 fh.file_handle.handle_type = FILEID_NSFS;
918
919 /* The first 8 bytes of struct nsfs_file_handle (see <linux/nsfs.h>, uapi since kernel v6.18)
920 * are __u64 ns_id; the remaining ns_type/ns_inum fields stay zero so the kernel looks up by
921 * id alone. The kernel made lookup-by-id-only an explicit ABI guarantee in v6.19 via commit
922 * 04173501a69e ("nstree: allow lookup solely based on inode"). */
923 unaligned_write_ne64(fh.file_handle.f_handle, ns_id);
924
925 return RET_NERRNO(open_by_handle_at(FD_NSFS_ROOT, &fh.file_handle, O_PATH|O_CLOEXEC));
926 }
927
928 int is_idmapping_supported(const char *path) {
929 _cleanup_close_ int mount_fd = -EBADF, userns_fd = -EBADF, dir_fd = -EBADF;
930 int r;
931
932 assert(path);
933
934 if (!mount_new_api_supported())
935 return false;
936
937 userns_fd = r = userns_acquire_self_root();
938 if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || ERRNO_IS_NEG_PRIVILEGE(r) || r == -EINVAL)
939 return false;
940 if (r == -ENOSPC) {
941 log_debug_errno(r, "Failed to acquire new user namespace, user.max_user_namespaces seems to be exhausted or maybe even zero, assuming ID-mapping is not supported: %m");
942 return false;
943 }
944 if (r < 0)
945 return log_debug_errno(r, "Failed to acquire new user namespace for checking if '%s' supports ID-mapping: %m", path);
946
947 dir_fd = r = RET_NERRNO(open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
948 if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
949 return false;
950 if (r < 0)
951 return log_debug_errno(r, "Failed to open '%s', cannot determine if ID-mapping is supported: %m", path);
952
953 mount_fd = r = RET_NERRNO(open_tree(dir_fd, "", AT_EMPTY_PATH | OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC));
954 if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || ERRNO_IS_NEG_PRIVILEGE(r) || r == -EINVAL)
955 return false;
956 if (r < 0)
957 return log_debug_errno(r, "Failed to open mount tree '%s', cannot determine if ID-mapping is supported: %m", path);
958
959 r = RET_NERRNO(mount_setattr(mount_fd, "", AT_EMPTY_PATH,
960 &(struct mount_attr) {
961 .attr_set = MOUNT_ATTR_IDMAP | MOUNT_ATTR_NOSUID | MOUNT_ATTR_NOEXEC | MOUNT_ATTR_RDONLY | MOUNT_ATTR_NODEV,
962 .userns_fd = userns_fd,
963 }, sizeof(struct mount_attr)));
964 if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || ERRNO_IS_NEG_PRIVILEGE(r) || r == -EINVAL)
965 return false;
966 if (r < 0)
967 return log_debug_errno(r, "Failed to set mount attribute to '%s', cannot determine if ID-mapping is supported: %m", path);
968
969 return true;
970 }
971
972 int netns_acquire(void) {
973 _cleanup_(pidref_done_sigkill_wait) PidRef pid = PIDREF_NULL;
974 int r;
975
976 /* Forks off a process in a new network namespace, acquires a network namespace fd, and then kills
977 * the process again. This way we have a netns fd that is not bound to any process. */
978
979 r = pidref_safe_fork("(sd-mknetns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_NEW_NETNS|FORK_FREEZE, &pid);
980 if (r < 0)
981 return log_debug_errno(r, "Failed to fork process into new netns: %m");
982 assert(r > 0);
983
984 return pidref_namespace_open_by_type(&pid, NAMESPACE_NET);
985 }