• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 13912360373

17 Mar 2025 10:34PM UTC coverage: 71.946% (+0.03%) from 71.915%
13912360373

push

github

web-flow
nsresourced,vmspawn: allow unpriv "tap" based networking in vmspawn (#36688)

This extends nsresourced to also allow delegation of a network tap
device (in addition to veth) to unpriv clients, with a strictly enforced
naming scheme.

also tightens security on a couple of things:

* enforces polkit on all nsresourced ops too (though by default still
everything is allowed)
* put a limit on delegated network devices
* forcibly clean up delegated network devices when the userns goes away

145 of 375 new or added lines in 14 files covered. (38.67%)

2324 existing lines in 47 files now uncovered.

296268 of 411794 relevant lines covered (71.95%)

711485.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.69
/src/basic/namespace-util.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <fcntl.h>
4
#include <sys/ioctl.h>
5
#include <sys/mount.h>
6

7
#include "errno-util.h"
8
#include "fd-util.h"
9
#include "fileio.h"
10
#include "missing_fs.h"
11
#include "missing_magic.h"
12
#include "missing_namespace.h"
13
#include "missing_sched.h"
14
#include "missing_syscall.h"
15
#include "mountpoint-util.h"
16
#include "namespace-util.h"
17
#include "parse-util.h"
18
#include "pidfd-util.h"
19
#include "process-util.h"
20
#include "stat-util.h"
21
#include "stdio-util.h"
22
#include "uid-range.h"
23
#include "user-util.h"
24

25
const struct namespace_info namespace_info[_NAMESPACE_TYPE_MAX + 1] = {
26
        [NAMESPACE_CGROUP] =  { "cgroup", "ns/cgroup", CLONE_NEWCGROUP, PIDFD_GET_CGROUP_NAMESPACE, PROC_CGROUP_INIT_INO },
27
        [NAMESPACE_IPC]    =  { "ipc",    "ns/ipc",    CLONE_NEWIPC,    PIDFD_GET_IPC_NAMESPACE,    PROC_IPC_INIT_INO    },
28
        [NAMESPACE_NET]    =  { "net",    "ns/net",    CLONE_NEWNET,    PIDFD_GET_NET_NAMESPACE,    0                    },
29
        /* So, the mount namespace flag is called CLONE_NEWNS for historical
30
         * reasons. Let's expose it here under a more explanatory name: "mnt".
31
         * This is in-line with how the kernel exposes namespaces in /proc/$PID/ns. */
32
        [NAMESPACE_MOUNT]  =  { "mnt",    "ns/mnt",    CLONE_NEWNS,     PIDFD_GET_MNT_NAMESPACE,    0                    },
33
        [NAMESPACE_PID]    =  { "pid",    "ns/pid",    CLONE_NEWPID,    PIDFD_GET_PID_NAMESPACE,    PROC_PID_INIT_INO    },
34
        [NAMESPACE_USER]   =  { "user",   "ns/user",   CLONE_NEWUSER,   PIDFD_GET_USER_NAMESPACE,   PROC_USER_INIT_INO   },
35
        [NAMESPACE_UTS]    =  { "uts",    "ns/uts",    CLONE_NEWUTS,    PIDFD_GET_UTS_NAMESPACE,    PROC_UTS_INIT_INO    },
36
        [NAMESPACE_TIME]   =  { "time",   "ns/time",   CLONE_NEWTIME,   PIDFD_GET_TIME_NAMESPACE,   PROC_TIME_INIT_INO   },
37
        {}, /* Allow callers to iterate over the array without using _NAMESPACE_TYPE_MAX. */
38
};
39

40
#define pid_namespace_path(pid, type) procfs_file_alloca(pid, namespace_info[type].proc_path)
41

42
NamespaceType clone_flag_to_namespace_type(unsigned long clone_flag) {
149✔
43
        for (NamespaceType t = 0; t < _NAMESPACE_TYPE_MAX; t++)
630✔
44
                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)
630✔
45
                        return t;
46

47
        return _NAMESPACE_TYPE_INVALID;
48
}
49

50
static int pidref_namespace_open_by_type_internal(const PidRef *pidref, NamespaceType type, bool *need_verify) {
8,586✔
51
        int r;
8,586✔
52

53
        assert(pidref_is_set(pidref));
8,586✔
54
        assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
8,586✔
55

56
        if (pidref_is_remote(pidref))
8,586✔
57
                return -EREMOTE;
8,586✔
58

59
        if (pidref->fd >= 0) {
8,586✔
60
                r = pidfd_get_namespace(pidref->fd, namespace_info[type].pidfd_get_ns_ioctl_cmd);
8,584✔
61
                if (!ERRNO_IS_NEG_NOT_SUPPORTED(r))
8,584✔
62
                        return r;
63
        }
64

65
        if (need_verify) /* The caller shall call pidref_verify() later */
1,923✔
66
                *need_verify = true;
222✔
67

68
        _cleanup_close_ int nsfd = -EBADF;
8,586✔
69
        const char *p;
1,923✔
70

71
        p = pid_namespace_path(pidref->pid, type);
1,923✔
72
        nsfd = RET_NERRNO(open(p, O_RDONLY|O_NOCTTY|O_CLOEXEC));
1,923✔
73
        if (nsfd == -ENOENT) {
×
74
                r = proc_mounted();
×
75
                if (r == 0)
×
76
                        return -ENOSYS;  /* /proc/ is not available or not set up properly, we're most likely
77
                                            in some chroot environment. */
78
                if (r > 0)
×
79
                        return -ENOPKG;  /* If /proc/ is definitely around then this means the namespace type is not supported */
80

81
                /* can't determine? then propagate original error */
82
        }
83
        if (nsfd < 0)
1,923✔
84
                return nsfd;
85

86
        if (!need_verify) { /* Otherwise we verify on our own */
1,923✔
87
                r = pidref_verify(pidref);
1,701✔
88
                if (r < 0)
1,701✔
89
                        return r;
×
90
        }
91

92
        return TAKE_FD(nsfd);
93
}
94

95
int pidref_namespace_open_by_type(const PidRef *pidref, NamespaceType type) {
8,364✔
96
        return pidref_namespace_open_by_type_internal(pidref, type, NULL);
8,364✔
97
}
98

99
int namespace_open_by_type(NamespaceType type) {
4,045✔
100
        _cleanup_(pidref_done) PidRef self = PIDREF_NULL;
4,045✔
101
        int r;
4,045✔
102

103
        assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
4,045✔
104

105
        r = pidref_set_self(&self);
4,045✔
106
        if (r < 0)
4,045✔
107
                return r;
108

109
        return pidref_namespace_open_by_type(&self, type);
4,045✔
110
}
111

112
int pidref_namespace_open(
157✔
113
                const PidRef *pidref,
114
                int *ret_pidns_fd,
115
                int *ret_mntns_fd,
116
                int *ret_netns_fd,
117
                int *ret_userns_fd,
118
                int *ret_root_fd) {
119

120
        _cleanup_close_ int pidns_fd = -EBADF, mntns_fd = -EBADF, netns_fd = -EBADF,
314✔
121
                userns_fd = -EBADF, root_fd = -EBADF;
314✔
122
        bool need_verify = false;
157✔
123
        int r;
157✔
124

125
        assert(pidref_is_set(pidref));
157✔
126

127
        if (pidref_is_remote(pidref))
314✔
128
                return -EREMOTE;
129

130
        if (ret_pidns_fd) {
157✔
131
                pidns_fd = pidref_namespace_open_by_type_internal(pidref, NAMESPACE_PID, &need_verify);
51✔
132
                if (pidns_fd < 0)
51✔
133
                        return pidns_fd;
134
        }
135

136
        if (ret_mntns_fd) {
157✔
137
                mntns_fd = pidref_namespace_open_by_type_internal(pidref, NAMESPACE_MOUNT, &need_verify);
52✔
138
                if (mntns_fd < 0)
52✔
139
                        return mntns_fd;
140
        }
141

142
        if (ret_netns_fd) {
157✔
143
                netns_fd = pidref_namespace_open_by_type_internal(pidref, NAMESPACE_NET, &need_verify);
107✔
144
                if (netns_fd < 0)
107✔
145
                        return netns_fd;
146
        }
147

148
        if (ret_userns_fd) {
157✔
149
                userns_fd = pidref_namespace_open_by_type_internal(pidref, NAMESPACE_USER, &need_verify);
12✔
150
                if (userns_fd < 0 && userns_fd != -ENOPKG)
12✔
151
                        return userns_fd;
152
        }
153

154
        if (ret_root_fd) {
157✔
155
                const char *root;
52✔
156

157
                root = procfs_file_alloca(pidref->pid, "root");
52✔
158
                root_fd = RET_NERRNO(open(root, O_CLOEXEC|O_DIRECTORY));
52✔
159
                if (root_fd == -ENOENT && proc_mounted() == 0)
×
160
                        return -ENOSYS;
161
                if (root_fd < 0)
52✔
162
                        return root_fd;
163

164
                need_verify = true;
52✔
165
        }
166

167
        if (need_verify) {
157✔
168
                r = pidref_verify(pidref);
157✔
169
                if (r < 0)
157✔
170
                        return r;
171
        }
172

173
        if (ret_pidns_fd)
157✔
174
                *ret_pidns_fd = TAKE_FD(pidns_fd);
51✔
175

176
        if (ret_mntns_fd)
157✔
177
                *ret_mntns_fd = TAKE_FD(mntns_fd);
52✔
178

179
        if (ret_netns_fd)
157✔
180
                *ret_netns_fd = TAKE_FD(netns_fd);
107✔
181

182
        if (ret_userns_fd)
157✔
183
                *ret_userns_fd = TAKE_FD(userns_fd);
12✔
184

185
        if (ret_root_fd)
157✔
186
                *ret_root_fd = TAKE_FD(root_fd);
52✔
187

188
        return 0;
189
}
190

191
int namespace_open(
10✔
192
                pid_t pid,
193
                int *ret_pidns_fd,
194
                int *ret_mntns_fd,
195
                int *ret_netns_fd,
196
                int *ret_userns_fd,
197
                int *ret_root_fd) {
198

199
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
10✔
200
        int r;
10✔
201

202
        r = pidref_set_pid(&pidref, pid);
10✔
203
        if (r < 0)
10✔
204
                return r;
205

206
        return pidref_namespace_open(&pidref, ret_pidns_fd, ret_mntns_fd, ret_netns_fd, ret_userns_fd, ret_root_fd);
10✔
207
}
208

209
int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int userns_fd, int root_fd) {
380✔
210
        int r;
380✔
211

212
        if (userns_fd >= 0) {
380✔
213
                /* Can't setns to your own userns, since then you could escalate from non-root to root in
214
                 * your own namespace, so check if namespaces are equal before attempting to enter. */
215

216
                r = is_our_namespace(userns_fd, NAMESPACE_USER);
1✔
217
                if (r < 0)
1✔
218
                        return r;
219
                if (r > 0)
1✔
220
                        userns_fd = -EBADF;
1✔
221
        }
222

223
        if (pidns_fd >= 0)
380✔
224
                if (setns(pidns_fd, CLONE_NEWPID) < 0)
40✔
225
                        return -errno;
×
226

227
        if (mntns_fd >= 0)
380✔
228
                if (setns(mntns_fd, CLONE_NEWNS) < 0)
246✔
229
                        return -errno;
×
230

231
        if (netns_fd >= 0)
380✔
232
                if (setns(netns_fd, CLONE_NEWNET) < 0)
134✔
233
                        return -errno;
×
234

235
        if (userns_fd >= 0)
380✔
236
                if (setns(userns_fd, CLONE_NEWUSER) < 0)
×
237
                        return -errno;
×
238

239
        if (root_fd >= 0) {
380✔
240
                if (fchdir(root_fd) < 0)
41✔
241
                        return -errno;
×
242

243
                if (chroot(".") < 0)
41✔
244
                        return -errno;
×
245
        }
246

247
        if (userns_fd >= 0)
380✔
248
                return reset_uid_gid();
×
249

250
        return 0;
251
}
252

253
int fd_is_namespace(int fd, NamespaceType type) {
158✔
254
        int r;
158✔
255

256
        /* Checks whether the specified file descriptor refers to a namespace (of type if type != _NAMESPACE_INVALID). */
257

258
        assert(fd >= 0);
158✔
259
        assert(type < _NAMESPACE_TYPE_MAX);
158✔
260

261
        r = fd_is_fs_type(fd, NSFS_MAGIC);
158✔
262
        if (r <= 0)
158✔
263
                return r;
264

265
        if (type < 0)
149✔
266
                return true;
267

268
        int clone_flag = ioctl(fd, NS_GET_NSTYPE);
149✔
269
        if (clone_flag < 0)
149✔
270
                return -errno;
×
271

272
        NamespaceType found_type = clone_flag_to_namespace_type(clone_flag);
149✔
273
        if (found_type < 0)
149✔
274
                return -EBADF; /* Uh? Unknown namespace type? */
275

276
        return found_type == type;
149✔
277
}
278

279
int is_our_namespace(int fd, NamespaceType type) {
33✔
280
        int r;
33✔
281

282
        assert(fd >= 0);
33✔
283
        assert(type < _NAMESPACE_TYPE_MAX);
33✔
284

285
        r = fd_is_namespace(fd, type);
33✔
286
        if (r < 0)
33✔
287
                return r;
33✔
288
        if (r == 0) /* Not a namespace or not of the right type? */
33✔
289
                return -EUCLEAN;
290

291
        _cleanup_close_ int our_ns = namespace_open_by_type(type);
66✔
292
        if (our_ns < 0)
33✔
293
                return our_ns;
294

295
        return fd_inode_same(fd, our_ns);
33✔
296
}
297

298
int namespace_is_init(NamespaceType type) {
5,789✔
299
        int r;
5,789✔
300

301
        assert(type >= 0);
5,789✔
302
        assert(type < _NAMESPACE_TYPE_MAX);
5,789✔
303

304
        if (namespace_info[type].root_inode == 0)
5,789✔
305
                return -EBADR; /* Cannot answer this question */
5,789✔
306

307
        const char *p = pid_namespace_path(0, type);
5,783✔
308

309
        struct stat st;
5,783✔
310
        r = RET_NERRNO(stat(p, &st));
5,783✔
311
        if (r == -ENOENT) {
61✔
312
                /* 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 */
313
                r = proc_mounted();
61✔
314
                if (r < 0)
61✔
315
                        return -ENOENT; /* If we can't determine if /proc/ is mounted propagate original error */
316

317
                return r ? true : -ENOSYS;
61✔
318
        }
319
        if (r < 0)
5,722✔
320
                return r;
321

322
        return st.st_ino == namespace_info[type].root_inode;
5,722✔
323
}
324

325
int pidref_in_same_namespace(PidRef *pid1, PidRef *pid2, NamespaceType type) {
134✔
326
        _cleanup_close_ int ns1 = -EBADF, ns2 = -EBADF;
134✔
327

328
        /* Accepts NULL to indicate our own process */
329

330
        assert(!pid1 || pidref_is_set(pid1));
134✔
331
        assert(!pid2 || pidref_is_set(pid2));
134✔
332
        assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
134✔
333

334
        if (pidref_equal(pid1, pid2))
134✔
335
                return true;
336

337
        if (!pid1)
134✔
338
                ns1 = namespace_open_by_type(type);
118✔
339
        else
340
                ns1 = pidref_namespace_open_by_type(pid1, type);
16✔
341
        if (ns1 < 0)
134✔
342
                return ns1;
343

344
        if (!pid2)
134✔
345
                ns2 = namespace_open_by_type(type);
2✔
346
        else
347
                ns2 = pidref_namespace_open_by_type(pid2, type);
132✔
348
        if (ns2 < 0)
134✔
349
                return ns2;
350

351
        return fd_inode_same(ns1, ns2);
134✔
352
}
353

354
int namespace_get_leader(PidRef *pidref, NamespaceType type, PidRef *ret) {
5✔
355
        int r;
5✔
356

357
        /* Note: we don't bother with pidref_is_set()/pidref_is_remote() here, as the first call we do,
358
         * pidref_get_ppid_as_pidref() calls those anyway */
359

360
        assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
5✔
361
        assert(ret);
5✔
362

363
        _cleanup_(pidref_done) PidRef current = PIDREF_NULL;
5✔
364
        PidRef *c = pidref;
5✔
365

366
        for (;;) {
9✔
367
                _cleanup_(pidref_done) PidRef parent = PIDREF_NULL;
5✔
368

369
                r = pidref_get_ppid_as_pidref(c, &parent);
14✔
370
                if (r < 0)
14✔
371
                        return r;
372

373
                r = pidref_in_same_namespace(c, &parent, type);
14✔
374
                if (r < 0)
14✔
375
                        return r;
376
                if (r == 0) {
14✔
377
                        /* If the parent and the child are not in the same namespace, then the child is
378
                         * the leader we are looking for. */
379

380
                        if (pidref_is_set(&current))
5✔
381
                                *ret = TAKE_PIDREF(current);
5✔
382
                        else {
383
                                r = pidref_copy(c, ret);
×
384
                                if (r < 0)
×
385
                                        return r;
386
                        }
387

388
                        return 0;
5✔
389
                }
390

391
                pidref_done(&current);
9✔
392
                current = TAKE_PIDREF(parent);
9✔
393
                c = &current;
9✔
394
        }
395
}
396

397
int detach_mount_namespace(void) {
197✔
398
        /* Detaches the mount namespace, disabling propagation from our namespace to the host. Sets
399
         * propagation first to MS_SLAVE for all mounts (disabling propagation), and then back to MS_SHARED
400
         * (so that we create a new peer group).  */
401

402
        if (unshare(CLONE_NEWNS) < 0)
197✔
403
                return log_debug_errno(errno, "Failed to acquire mount namespace: %m");
×
404

405
        if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0)
197✔
406
                return log_debug_errno(errno, "Failed to set mount propagation to MS_SLAVE for all mounts: %m");
×
407

408
        if (mount(NULL, "/", NULL, MS_SHARED | MS_REC, NULL) < 0)
197✔
409
                return log_debug_errno(errno, "Failed to set mount propagation back to MS_SHARED for all mounts: %m");
×
410

411
        return 0;
412
}
413

414
int detach_mount_namespace_harder(uid_t target_uid, gid_t target_gid) {
53✔
415
        int r;
53✔
416

417
        /* Tried detach_mount_namespace() first. If that doesn't work due to permissions, opens up an
418
         * unprivileged user namespace with a mapping of the originating UID/GID to the specified target
419
         * UID/GID. Then, tries detach_mount_namespace() again.
420
         *
421
         * Or in other words: tries much harder to get a mount namespace, making use of unprivileged user
422
         * namespaces if need be.
423
         *
424
         * Note that after this function completed:
425
         *
426
         *    → if we had privs, afterwards uids/gids on files and processes are as before
427
         *
428
         *    → if we had no privs, our own id and all our files will show up owned by target_uid/target_gid,
429
         *    and everything else owned by nobody.
430
         *
431
         * Yes, that's quite a difference. */
432

433
        if (!uid_is_valid(target_uid))
53✔
434
                return -EINVAL;
435
        if (!gid_is_valid(target_gid))
53✔
436
                return -EINVAL;
437

438
        r = detach_mount_namespace();
53✔
439
        if (r != -EPERM)
53✔
440
                return r;
441

442
        if (unshare(CLONE_NEWUSER) < 0)
×
443
                return log_debug_errno(errno, "Failed to acquire user namespace: %m");
×
444

445
        r = write_string_filef("/proc/self/uid_map", 0,
×
446
                               UID_FMT " " UID_FMT " 1\n", target_uid, getuid());
447
        if (r < 0)
×
448
                return log_debug_errno(r, "Failed to write uid map: %m");
×
449

450
        r = write_string_file("/proc/self/setgroups", "deny", 0);
×
451
        if (r < 0)
×
452
                return log_debug_errno(r, "Failed to write setgroups file: %m");
×
453

454
        r = write_string_filef("/proc/self/gid_map", 0,
×
455
                               GID_FMT " " GID_FMT " 1\n", target_gid, getgid());
456
        if (r < 0)
×
457
                return log_debug_errno(r, "Failed to write gid map: %m");
×
458

459
        return detach_mount_namespace();
×
460
}
461

462
int detach_mount_namespace_userns(int userns_fd) {
2✔
463
        int r;
2✔
464

465
        assert(userns_fd >= 0);
2✔
466

467
        if (setns(userns_fd, CLONE_NEWUSER) < 0)
2✔
468
                return log_debug_errno(errno, "Failed to join user namespace: %m");
×
469

470
        r = reset_uid_gid();
2✔
471
        if (r < 0)
2✔
472
                return log_debug_errno(r, "Failed to become root in user namespace: %m");
×
473

474
        return detach_mount_namespace();
2✔
475
}
476

477
int parse_userns_uid_range(const char *s, uid_t *ret_uid_shift, uid_t *ret_uid_range) {
2✔
478
        _cleanup_free_ char *buffer = NULL;
2✔
479
        const char *range, *shift;
2✔
480
        int r;
2✔
481
        uid_t uid_shift, uid_range = 65536;
2✔
482

483
        assert(s);
2✔
484

485
        range = strchr(s, ':');
2✔
486
        if (range) {
2✔
487
                buffer = strndup(s, range - s);
×
488
                if (!buffer)
×
489
                        return log_oom();
×
490
                shift = buffer;
×
491

492
                range++;
×
493
                r = safe_atou32(range, &uid_range);
×
494
                if (r < 0)
×
495
                        return log_error_errno(r, "Failed to parse UID range \"%s\": %m", range);
×
496
        } else
497
                shift = s;
498

499
        r = parse_uid(shift, &uid_shift);
2✔
500
        if (r < 0)
2✔
501
                return log_error_errno(r, "Failed to parse UID \"%s\": %m", s);
2✔
502

503
        if (!userns_shift_range_valid(uid_shift, uid_range))
×
504
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "UID range cannot be empty or go beyond " UID_FMT ".", UID_INVALID);
×
505

506
        if (ret_uid_shift)
×
507
                *ret_uid_shift = uid_shift;
×
508

509
        if (ret_uid_range)
×
510
                *ret_uid_range = uid_range;
×
511

512
        return 0;
513
}
514

515
int userns_acquire_empty(void) {
22✔
516
        _cleanup_(pidref_done_sigkill_wait) PidRef pid = PIDREF_NULL;
22✔
517
        int r;
22✔
518

519
        r = pidref_safe_fork("(sd-mkuserns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_NEW_USERNS|FORK_FREEZE, &pid);
22✔
520
        if (r < 0)
22✔
521
                return r;
522
        assert(r > 0);
22✔
523

524
        return pidref_namespace_open_by_type(&pid, NAMESPACE_USER);
22✔
525
}
526

527
int userns_acquire(const char *uid_map, const char *gid_map, bool setgroups_deny) {
4,128✔
528
        char path[STRLEN("/proc//setgroups") + DECIMAL_STR_MAX(pid_t) + 1];
4,128✔
529
        _cleanup_(pidref_done_sigkill_wait) PidRef pid = PIDREF_NULL;
4,128✔
530
        int r;
4,128✔
531

532
        assert(uid_map);
4,128✔
533
        assert(gid_map);
4,128✔
534

535
        /* Forks off a process in a new userns, configures the specified uidmap/gidmap, acquires an fd to it,
536
         * and then kills the process again. This way we have a userns fd that is not bound to any
537
         * process. We can use that for file system mounts and similar. */
538

539
        r = pidref_safe_fork("(sd-mkuserns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_NEW_USERNS|FORK_FREEZE, &pid);
4,128✔
540
        if (r < 0)
4,128✔
541
                return r;
542
        assert(r > 0);
4,128✔
543

544
        xsprintf(path, "/proc/" PID_FMT "/uid_map", pid.pid);
4,128✔
545
        r = write_string_file(path, uid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
4,128✔
546
        if (r < 0)
4,128✔
547
                return log_debug_errno(r, "Failed to write UID map: %m");
×
548

549
        if (setgroups_deny) {
4,128✔
550
                xsprintf(path, "/proc/" PID_FMT "/setgroups", pid.pid);
4,128✔
551
                r = write_string_file(path, "deny", WRITE_STRING_FILE_DISABLE_BUFFER);
4,128✔
552
                if (r < 0)
4,128✔
NEW
553
                        return log_debug_errno(r, "Failed to write setgroups file: %m");
×
554
        }
555

556
        xsprintf(path, "/proc/" PID_FMT "/gid_map", pid.pid);
4,128✔
557
        r = write_string_file(path, gid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
4,128✔
558
        if (r < 0)
4,128✔
559
                return log_debug_errno(r, "Failed to write GID map: %m");
×
560

561
        return pidref_namespace_open_by_type(&pid, NAMESPACE_USER);
4,128✔
562
}
563

564
int userns_acquire_self_root(void) {
3,988✔
565

566
        /* Returns a user namespace with only our own uid/gid mapped to root, and everything else unmapped.
567
         *
568
         * Note: this can be acquired unprivileged! */
569

570
        _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
3,988✔
571
        if (asprintf(&uid_map, "0 " UID_FMT " 1", getuid()) < 0)
3,988✔
572
                return -ENOMEM;
573
        if (asprintf(&gid_map, "0 " GID_FMT " 1", getgid()) < 0)
3,988✔
574
                return -ENOMEM;
575

576
        return userns_acquire(uid_map, gid_map, /* setgroups_deny= */ true);
3,988✔
577
}
578

579
int userns_enter_and_pin(int userns_fd, pid_t *ret_pid) {
42✔
580
        _cleanup_close_pair_ int pfd[2] = EBADF_PAIR;
42✔
581
        _cleanup_(sigkill_waitp) pid_t pid = 0;
42✔
582
        ssize_t n;
42✔
583
        char x;
42✔
584
        int r;
42✔
585

586
        assert(userns_fd >= 0);
42✔
587
        assert(ret_pid);
42✔
588

589
        if (pipe2(pfd, O_CLOEXEC) < 0)
42✔
590
                return -errno;
×
591

592
        r = safe_fork_full(
84✔
593
                        "(sd-pinuserns)",
594
                        /* stdio_fds= */ NULL,
595
                        (int[]) { pfd[1], userns_fd }, 2,
42✔
596
                        FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL,
597
                        &pid);
598
        if (r < 0)
42✔
599
                return r;
600
        if (r == 0) {
42✔
601
                /* Child. */
602

603
                if (setns(userns_fd, CLONE_NEWUSER) < 0) {
×
604
                        log_debug_errno(errno, "Failed to join userns: %m");
×
605
                        _exit(EXIT_FAILURE);
×
606
                }
607

608
                userns_fd = safe_close(userns_fd);
×
609

610
                n = write(pfd[1], &(const char) { 'x' }, 1);
×
611
                if (n < 0) {
×
612
                        log_debug_errno(errno, "Failed to write to pipe: %m");
×
613
                        _exit(EXIT_FAILURE);
×
614
                }
615
                assert(n == 1);
×
616

617
                freeze();
×
618
        }
619

620
        pfd[1] = safe_close(pfd[1]);
42✔
621

622
        n = read(pfd[0], &x, 1);
42✔
623
        if (n < 0)
42✔
624
                return -errno;
×
625
        if (n == 0)
42✔
626
                return -EPROTO;
627
        assert(n == 1);
42✔
628
        assert(x == 'x');
42✔
629

630
        *ret_pid = TAKE_PID(pid);
42✔
631
        return 0;
42✔
632
}
633

634
int userns_get_base_uid(int userns_fd, uid_t *ret_uid, gid_t *ret_gid) {
24✔
635
        _cleanup_(sigkill_waitp) pid_t pid = 0;
24✔
636
        int r;
24✔
637

638
        assert(userns_fd >= 0);
24✔
639

640
        r = userns_enter_and_pin(userns_fd, &pid);
24✔
641
        if (r < 0)
24✔
642
                return r;
643

644
        uid_t uid;
24✔
645
        r = uid_map_search_root(pid, UID_RANGE_USERNS_OUTSIDE, &uid);
24✔
646
        if (r < 0)
24✔
647
                return r;
648

649
        gid_t gid;
21✔
650
        r = uid_map_search_root(pid, GID_RANGE_USERNS_OUTSIDE, &gid);
21✔
651
        if (r < 0)
21✔
652
                return r;
653

654
        if (!ret_gid && uid != gid)
21✔
655
                return -EUCLEAN;
656

657
        if (ret_uid)
18✔
658
                *ret_uid = uid;
18✔
659
        if (ret_gid)
18✔
660
                *ret_gid = gid;
3✔
661

662
        return 0;
663
}
664

665
int process_is_owned_by_uid(const PidRef *pidref, uid_t uid) {
9✔
666
        int r;
9✔
667

668
        /* Checks if the specified process either is owned directly by the specified user, or if it is inside
669
         * a user namespace owned by it. */
670

671
        assert(uid_is_valid(uid));
9✔
672

673
        uid_t process_uid;
9✔
674
        r = pidref_get_uid(pidref, &process_uid);
9✔
675
        if (r < 0)
9✔
676
                return r;
9✔
677
        if (process_uid == uid)
9✔
678
                return true;
679

680
        _cleanup_close_ int userns_fd = -EBADF;
9✔
681
        userns_fd = pidref_namespace_open_by_type(pidref, NAMESPACE_USER);
6✔
682
        if (userns_fd == -ENOPKG) /* If userns is not supported, then they don't matter for ownership */
6✔
683
                return false;
684
        if (userns_fd < 0)
6✔
685
                return userns_fd;
686

687
        for (unsigned iteration = 0;; iteration++) {
×
688
                uid_t ns_uid;
6✔
689

690
                /* This process is in our own userns? Then we are done, in our own userns only the UIDs
691
                 * themselves matter. */
692
                r = is_our_namespace(userns_fd, NAMESPACE_USER);
6✔
693
                if (r < 0)
6✔
694
                        return r;
6✔
695
                if (r > 0)
6✔
696
                        return false;
697

698
                if (ioctl(userns_fd, NS_GET_OWNER_UID, &ns_uid) < 0)
3✔
699
                        return -errno;
×
700
                if (ns_uid == uid)
3✔
701
                        return true;
702

703
                /* Paranoia check */
704
                if (iteration > 16)
×
705
                        return log_debug_errno(SYNTHETIC_ERRNO(ELOOP), "Giving up while tracing parents of user namespaces after %u steps.", iteration);
×
706

707
                /* Go up the tree */
708
                _cleanup_close_ int parent_fd = ioctl(userns_fd, NS_GET_USERNS);
6✔
709
                if (parent_fd < 0) {
×
710
                        if (errno == EPERM) /* EPERM means we left our own userns */
×
711
                                return false;
712

713
                        return -errno;
×
714
                }
715

716
                close_and_replace(userns_fd, parent_fd);
×
717
        }
718
}
719

720
int is_idmapping_supported(const char *path) {
3,987✔
721
        _cleanup_close_ int mount_fd = -EBADF, userns_fd = -EBADF, dir_fd = -EBADF;
7,974✔
722
        int r;
3,987✔
723

724
        assert(path);
3,987✔
725

726
        if (!mount_new_api_supported())
3,987✔
727
                return false;
728

729
        userns_fd = r = userns_acquire_self_root();
3,987✔
730
        if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || ERRNO_IS_NEG_PRIVILEGE(r) || r == -EINVAL)
3,987✔
731
                return false;
732
        if (r == -ENOSPC) {
3,987✔
733
                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");
×
734
                return false;
×
735
        }
736
        if (r < 0)
3,987✔
737
                return log_debug_errno(r, "Failed to acquire new user namespace for checking if '%s' supports ID-mapping: %m", path);
×
738

739
        dir_fd = r = RET_NERRNO(open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
3,987✔
740
        if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
7,974✔
741
                return false;
742
        if (r < 0)
3,987✔
743
                return log_debug_errno(r, "Failed to open '%s', cannot determine if ID-mapping is supported: %m", path);
×
744

745
        mount_fd = r = RET_NERRNO(open_tree(dir_fd, "", AT_EMPTY_PATH | OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC));
3,987✔
746
        if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || ERRNO_IS_NEG_PRIVILEGE(r) || r == -EINVAL)
3,987✔
747
                return false;
×
748
        if (r < 0)
3,987✔
749
                return log_debug_errno(r, "Failed to open mount tree '%s', cannot determine if ID-mapping is supported: %m", path);
×
750

751
        r = RET_NERRNO(mount_setattr(mount_fd, "", AT_EMPTY_PATH,
3,987✔
752
                       &(struct mount_attr) {
3,987✔
753
                                .attr_set = MOUNT_ATTR_IDMAP | MOUNT_ATTR_NOSUID | MOUNT_ATTR_NOEXEC | MOUNT_ATTR_RDONLY | MOUNT_ATTR_NODEV,
754
                                .userns_fd = userns_fd,
755
                        }, sizeof(struct mount_attr)));
756
        if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || ERRNO_IS_NEG_PRIVILEGE(r) || r == -EINVAL)
3,987✔
757
                return false;
59✔
758
        if (r < 0)
3,928✔
759
                return log_debug_errno(r, "Failed to set mount attribute to '%s', cannot determine if ID-mapping is supported: %m", path);
×
760

761
        return true;
762
}
763

764
int netns_acquire(void) {
7✔
765
        _cleanup_(pidref_done_sigkill_wait) PidRef pid = PIDREF_NULL;
7✔
766
        int r;
7✔
767

768
        /* Forks off a process in a new network namespace, acquires a network namespace fd, and then kills
769
         * the process again. This way we have a netns fd that is not bound to any process. */
770

771
        r = pidref_safe_fork("(sd-mknetns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_NEW_NETNS|FORK_FREEZE, &pid);
7✔
772
        if (r < 0)
7✔
773
                return log_debug_errno(r, "Failed to fork process into new netns: %m");
×
774
        assert(r > 0);
7✔
775

776
        return pidref_namespace_open_by_type(&pid, NAMESPACE_NET);
7✔
777
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc