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

systemd / systemd / 14554080340

19 Apr 2025 11:46AM UTC coverage: 72.101% (-0.03%) from 72.13%
14554080340

push

github

web-flow
Add two new paragraphs to coding style about header files (#37188)

296880 of 411754 relevant lines covered (72.1%)

687547.52 hits per line

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

78.11
/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 "log.h"
11
#include "missing_fs.h"
12
#include "missing_magic.h"
13
#include "missing_namespace.h"
14
#include "missing_sched.h"
15
#include "missing_syscall.h"
16
#include "mountpoint-util.h"
17
#include "namespace-util.h"
18
#include "parse-util.h"
19
#include "pidfd-util.h"
20
#include "process-util.h"
21
#include "stat-util.h"
22
#include "stdio-util.h"
23
#include "uid-range.h"
24
#include "user-util.h"
25

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

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

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

48
        return _NAMESPACE_TYPE_INVALID;
49
}
50

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

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

57
        if (pidref_is_remote(pidref))
8,159✔
58
                return -EREMOTE;
8,159✔
59

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

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

69
        _cleanup_close_ int nsfd = -EBADF;
8,159✔
70
        const char *p;
1,945✔
71

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

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

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

93
        return TAKE_FD(nsfd);
94
}
95

96
int pidref_namespace_open_by_type(const PidRef *pidref, NamespaceType type) {
97
        return pidref_namespace_open_by_type_internal(pidref, type, NULL);
7,937✔
98
}
99

100
int namespace_open_by_type(NamespaceType type) {
101
        _cleanup_(pidref_done) PidRef self = PIDREF_NULL;
3,942✔
102
        int r;
3,942✔
103

104
        assert(type >= 0 && type < _NAMESPACE_TYPE_MAX);
3,942✔
105

106
        r = pidref_set_self(&self);
3,942✔
107
        if (r < 0)
3,942✔
108
                return r;
109

110
        return pidref_namespace_open_by_type(&self, type);
3,942✔
111
}
112

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

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

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

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

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

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

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

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

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

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

165
                need_verify = true;
52✔
166
        }
167

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

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

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

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

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

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

189
        return 0;
190
}
191

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

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

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

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

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

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

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

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

228
        if (mntns_fd >= 0)
355✔
229
                if (setns(mntns_fd, CLONE_NEWNS) < 0)
233✔
230
                        return -errno;
×
231

232
        if (netns_fd >= 0)
355✔
233
                if (setns(netns_fd, CLONE_NEWNET) < 0)
122✔
234
                        return -errno;
×
235

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

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

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

248
        if (userns_fd >= 0)
355✔
249
                return reset_uid_gid();
×
250

251
        return 0;
252
}
253

254
int fd_is_namespace(int fd, NamespaceType type) {
255
        int r;
94✔
256

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

259
        assert(fd >= 0);
94✔
260
        assert(type < _NAMESPACE_TYPE_MAX);
94✔
261

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

266
        if (type < 0)
85✔
267
                return true;
268

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

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

277
        return found_type == type;
85✔
278
}
279

280
int is_our_namespace(int fd, NamespaceType type) {
281
        int r;
22✔
282

283
        assert(fd >= 0);
22✔
284
        assert(type < _NAMESPACE_TYPE_MAX);
22✔
285

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

292
        _cleanup_close_ int our_ns = namespace_open_by_type(type);
44✔
293
        if (our_ns < 0)
22✔
294
                return our_ns;
295

296
        return fd_inode_same(fd, our_ns);
22✔
297
}
298

299
int namespace_is_init(NamespaceType type) {
300
        int r;
4,801✔
301

302
        assert(type >= 0);
4,801✔
303
        assert(type < _NAMESPACE_TYPE_MAX);
4,801✔
304

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

308
        const char *p = pid_namespace_path(0, type);
4,795✔
309

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

318
                return r ? true : -ENOSYS;
12✔
319
        }
320
        if (r < 0)
4,783✔
321
                return r;
322

323
        return st.st_ino == namespace_info[type].root_inode;
4,783✔
324
}
325

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

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

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

335
        if (pidref_equal(pid1, pid2))
137✔
336
                return true;
337

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

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

352
        return fd_inode_same(ns1, ns2);
137✔
353
}
354

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

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

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

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

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

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

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

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

389
                        return 0;
5✔
390
                }
391

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

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

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

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

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

412
        return 0;
413
}
414

415
int detach_mount_namespace_harder(uid_t target_uid, gid_t target_gid) {
416
        uid_t from_uid;
53✔
417
        gid_t from_gid;
53✔
418
        int r;
53✔
419

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

436
        if (!uid_is_valid(target_uid))
53✔
437
                return -EINVAL;
438
        if (!gid_is_valid(target_gid))
53✔
439
                return -EINVAL;
440

441
        r = detach_mount_namespace();
53✔
442
        if (r != -EPERM)
53✔
443
                return r;
444

445
        from_uid = getuid();
×
446
        from_gid = getgid();
×
447

448
        if (unshare(CLONE_NEWUSER) < 0)
×
449
                return log_debug_errno(errno, "Failed to acquire user namespace: %m");
×
450

451
        r = write_string_filef("/proc/self/uid_map", 0,
×
452
                               UID_FMT " " UID_FMT " 1\n", target_uid, from_uid);
453
        if (r < 0)
×
454
                return log_debug_errno(r, "Failed to write uid map: %m");
×
455

456
        r = write_string_file("/proc/self/setgroups", "deny", 0);
×
457
        if (r < 0)
×
458
                return log_debug_errno(r, "Failed to write setgroups file: %m");
×
459

460
        r = write_string_filef("/proc/self/gid_map", 0,
×
461
                               GID_FMT " " GID_FMT " 1\n", target_gid, from_gid);
462
        if (r < 0)
×
463
                return log_debug_errno(r, "Failed to write gid map: %m");
×
464

465
        return detach_mount_namespace();
×
466
}
467

468
int detach_mount_namespace_userns(int userns_fd) {
469
        int r;
2✔
470

471
        assert(userns_fd >= 0);
2✔
472

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

476
        r = reset_uid_gid();
2✔
477
        if (r < 0)
2✔
478
                return log_debug_errno(r, "Failed to become root in user namespace: %m");
×
479

480
        return detach_mount_namespace();
2✔
481
}
482

483
int parse_userns_uid_range(const char *s, uid_t *ret_uid_shift, uid_t *ret_uid_range) {
484
        _cleanup_free_ char *buffer = NULL;
2✔
485
        const char *range, *shift;
2✔
486
        int r;
2✔
487
        uid_t uid_shift, uid_range = 65536;
2✔
488

489
        assert(s);
2✔
490

491
        range = strchr(s, ':');
2✔
492
        if (range) {
2✔
493
                buffer = strndup(s, range - s);
×
494
                if (!buffer)
×
495
                        return log_oom();
×
496
                shift = buffer;
×
497

498
                range++;
×
499
                r = safe_atou32(range, &uid_range);
×
500
                if (r < 0)
×
501
                        return log_error_errno(r, "Failed to parse UID range \"%s\": %m", range);
×
502
        } else
503
                shift = s;
504

505
        r = parse_uid(shift, &uid_shift);
2✔
506
        if (r < 0)
2✔
507
                return log_error_errno(r, "Failed to parse UID \"%s\": %m", s);
2✔
508

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

512
        if (ret_uid_shift)
×
513
                *ret_uid_shift = uid_shift;
×
514

515
        if (ret_uid_range)
×
516
                *ret_uid_range = uid_range;
×
517

518
        return 0;
519
}
520

521
int userns_acquire_empty(void) {
522
        _cleanup_(pidref_done_sigkill_wait) PidRef pid = PIDREF_NULL;
22✔
523
        int r;
22✔
524

525
        r = pidref_safe_fork("(sd-mkuserns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_NEW_USERNS|FORK_FREEZE, &pid);
22✔
526
        if (r < 0)
22✔
527
                return r;
528
        assert(r > 0);
22✔
529

530
        return pidref_namespace_open_by_type(&pid, NAMESPACE_USER);
22✔
531
}
532

533
int userns_acquire(const char *uid_map, const char *gid_map, bool setgroups_deny) {
534
        char path[STRLEN("/proc//setgroups") + DECIMAL_STR_MAX(pid_t) + 1];
3,801✔
535
        _cleanup_(pidref_done_sigkill_wait) PidRef pid = PIDREF_NULL;
3,801✔
536
        int r;
3,801✔
537

538
        assert(uid_map);
3,801✔
539
        assert(gid_map);
3,801✔
540

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

545
        r = pidref_safe_fork("(sd-mkuserns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_NEW_USERNS|FORK_FREEZE, &pid);
3,801✔
546
        if (r < 0)
3,801✔
547
                return r;
548
        assert(r > 0);
3,801✔
549

550
        xsprintf(path, "/proc/" PID_FMT "/uid_map", pid.pid);
3,801✔
551
        r = write_string_file(path, uid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
3,801✔
552
        if (r < 0)
3,801✔
553
                return log_debug_errno(r, "Failed to write UID map: %m");
×
554

555
        if (setgroups_deny) {
3,801✔
556
                xsprintf(path, "/proc/" PID_FMT "/setgroups", pid.pid);
3,801✔
557
                r = write_string_file(path, "deny", WRITE_STRING_FILE_DISABLE_BUFFER);
3,801✔
558
                if (r < 0)
3,801✔
559
                        return log_debug_errno(r, "Failed to write setgroups file: %m");
×
560
        }
561

562
        xsprintf(path, "/proc/" PID_FMT "/gid_map", pid.pid);
3,801✔
563
        r = write_string_file(path, gid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
3,801✔
564
        if (r < 0)
3,801✔
565
                return log_debug_errno(r, "Failed to write GID map: %m");
×
566

567
        return pidref_namespace_open_by_type(&pid, NAMESPACE_USER);
3,801✔
568
}
569

570
int userns_acquire_self_root(void) {
571

572
        /* Returns a user namespace with only our own uid/gid mapped to root, and everything else unmapped.
573
         *
574
         * Note: this can be acquired unprivileged! */
575

576
        _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
3,672✔
577
        if (asprintf(&uid_map, "0 " UID_FMT " 1", getuid()) < 0)
3,672✔
578
                return -ENOMEM;
579
        if (asprintf(&gid_map, "0 " GID_FMT " 1", getgid()) < 0)
3,672✔
580
                return -ENOMEM;
581

582
        return userns_acquire(uid_map, gid_map, /* setgroups_deny= */ true);
3,672✔
583
}
584

585
int userns_enter_and_pin(int userns_fd, pid_t *ret_pid) {
586
        _cleanup_close_pair_ int pfd[2] = EBADF_PAIR;
40✔
587
        _cleanup_(sigkill_waitp) pid_t pid = 0;
40✔
588
        ssize_t n;
40✔
589
        char x;
40✔
590
        int r;
40✔
591

592
        assert(userns_fd >= 0);
40✔
593
        assert(ret_pid);
40✔
594

595
        if (pipe2(pfd, O_CLOEXEC) < 0)
40✔
596
                return -errno;
×
597

598
        r = safe_fork_full(
80✔
599
                        "(sd-pinuserns)",
600
                        /* stdio_fds= */ NULL,
601
                        (int[]) { pfd[1], userns_fd }, 2,
40✔
602
                        FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL,
603
                        &pid);
604
        if (r < 0)
40✔
605
                return r;
606
        if (r == 0) {
40✔
607
                /* Child. */
608

609
                if (setns(userns_fd, CLONE_NEWUSER) < 0) {
×
610
                        log_debug_errno(errno, "Failed to join userns: %m");
×
611
                        _exit(EXIT_FAILURE);
×
612
                }
613

614
                userns_fd = safe_close(userns_fd);
×
615

616
                n = write(pfd[1], &(const char) { 'x' }, 1);
×
617
                if (n < 0) {
×
618
                        log_debug_errno(errno, "Failed to write to pipe: %m");
×
619
                        _exit(EXIT_FAILURE);
×
620
                }
621
                assert(n == 1);
×
622

623
                freeze();
×
624
        }
625

626
        pfd[1] = safe_close(pfd[1]);
40✔
627

628
        n = read(pfd[0], &x, 1);
40✔
629
        if (n < 0)
40✔
630
                return -errno;
×
631
        if (n == 0)
40✔
632
                return -EPROTO;
633
        assert(n == 1);
40✔
634
        assert(x == 'x');
40✔
635

636
        *ret_pid = TAKE_PID(pid);
40✔
637
        return 0;
40✔
638
}
639

640
int userns_get_base_uid(int userns_fd, uid_t *ret_uid, gid_t *ret_gid) {
641
        _cleanup_(sigkill_waitp) pid_t pid = 0;
24✔
642
        int r;
24✔
643

644
        assert(userns_fd >= 0);
24✔
645

646
        r = userns_enter_and_pin(userns_fd, &pid);
24✔
647
        if (r < 0)
24✔
648
                return r;
649

650
        uid_t uid;
24✔
651
        r = uid_map_search_root(pid, UID_RANGE_USERNS_OUTSIDE, &uid);
24✔
652
        if (r < 0)
24✔
653
                return r;
654

655
        gid_t gid;
21✔
656
        r = uid_map_search_root(pid, GID_RANGE_USERNS_OUTSIDE, &gid);
21✔
657
        if (r < 0)
21✔
658
                return r;
659

660
        if (!ret_gid && uid != gid)
21✔
661
                return -EUCLEAN;
662

663
        if (ret_uid)
18✔
664
                *ret_uid = uid;
18✔
665
        if (ret_gid)
18✔
666
                *ret_gid = gid;
3✔
667

668
        return 0;
669
}
670

671
int process_is_owned_by_uid(const PidRef *pidref, uid_t uid) {
672
        int r;
9✔
673

674
        /* Checks if the specified process either is owned directly by the specified user, or if it is inside
675
         * a user namespace owned by it. */
676

677
        assert(uid_is_valid(uid));
9✔
678

679
        uid_t process_uid;
9✔
680
        r = pidref_get_uid(pidref, &process_uid);
9✔
681
        if (r < 0)
9✔
682
                return r;
9✔
683
        if (process_uid == uid)
9✔
684
                return true;
685

686
        _cleanup_close_ int userns_fd = -EBADF;
9✔
687
        userns_fd = pidref_namespace_open_by_type(pidref, NAMESPACE_USER);
6✔
688
        if (userns_fd == -ENOPKG) /* If userns is not supported, then they don't matter for ownership */
6✔
689
                return false;
690
        if (userns_fd < 0)
6✔
691
                return userns_fd;
692

693
        for (unsigned iteration = 0;; iteration++) {
×
694
                uid_t ns_uid;
6✔
695

696
                /* This process is in our own userns? Then we are done, in our own userns only the UIDs
697
                 * themselves matter. */
698
                r = is_our_namespace(userns_fd, NAMESPACE_USER);
6✔
699
                if (r < 0)
6✔
700
                        return r;
6✔
701
                if (r > 0)
6✔
702
                        return false;
703

704
                if (ioctl(userns_fd, NS_GET_OWNER_UID, &ns_uid) < 0)
3✔
705
                        return -errno;
×
706
                if (ns_uid == uid)
3✔
707
                        return true;
708

709
                /* Paranoia check */
710
                if (iteration > 16)
×
711
                        return log_debug_errno(SYNTHETIC_ERRNO(ELOOP), "Giving up while tracing parents of user namespaces after %u steps.", iteration);
×
712

713
                /* Go up the tree */
714
                _cleanup_close_ int parent_fd = ioctl(userns_fd, NS_GET_USERNS);
6✔
715
                if (parent_fd < 0) {
×
716
                        if (errno == EPERM) /* EPERM means we left our own userns */
×
717
                                return false;
718

719
                        return -errno;
×
720
                }
721

722
                close_and_replace(userns_fd, parent_fd);
×
723
        }
724
}
725

726
int is_idmapping_supported(const char *path) {
727
        _cleanup_close_ int mount_fd = -EBADF, userns_fd = -EBADF, dir_fd = -EBADF;
7,342✔
728
        int r;
3,671✔
729

730
        assert(path);
3,671✔
731

732
        if (!mount_new_api_supported())
3,671✔
733
                return false;
734

735
        userns_fd = r = userns_acquire_self_root();
3,671✔
736
        if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || ERRNO_IS_NEG_PRIVILEGE(r) || r == -EINVAL)
3,671✔
737
                return false;
738
        if (r == -ENOSPC) {
3,671✔
739
                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");
×
740
                return false;
×
741
        }
742
        if (r < 0)
3,671✔
743
                return log_debug_errno(r, "Failed to acquire new user namespace for checking if '%s' supports ID-mapping: %m", path);
×
744

745
        dir_fd = r = RET_NERRNO(open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
3,671✔
746
        if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
7,342✔
747
                return false;
748
        if (r < 0)
3,671✔
749
                return log_debug_errno(r, "Failed to open '%s', cannot determine if ID-mapping is supported: %m", path);
×
750

751
        mount_fd = r = RET_NERRNO(open_tree(dir_fd, "", AT_EMPTY_PATH | OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC));
3,671✔
752
        if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || ERRNO_IS_NEG_PRIVILEGE(r) || r == -EINVAL)
3,671✔
753
                return false;
×
754
        if (r < 0)
3,671✔
755
                return log_debug_errno(r, "Failed to open mount tree '%s', cannot determine if ID-mapping is supported: %m", path);
×
756

757
        r = RET_NERRNO(mount_setattr(mount_fd, "", AT_EMPTY_PATH,
3,671✔
758
                       &(struct mount_attr) {
3,671✔
759
                                .attr_set = MOUNT_ATTR_IDMAP | MOUNT_ATTR_NOSUID | MOUNT_ATTR_NOEXEC | MOUNT_ATTR_RDONLY | MOUNT_ATTR_NODEV,
760
                                .userns_fd = userns_fd,
761
                        }, sizeof(struct mount_attr)));
762
        if (ERRNO_IS_NEG_NOT_SUPPORTED(r) || ERRNO_IS_NEG_PRIVILEGE(r) || r == -EINVAL)
3,671✔
763
                return false;
6✔
764
        if (r < 0)
3,665✔
765
                return log_debug_errno(r, "Failed to set mount attribute to '%s', cannot determine if ID-mapping is supported: %m", path);
×
766

767
        return true;
768
}
769

770
int netns_acquire(void) {
771
        _cleanup_(pidref_done_sigkill_wait) PidRef pid = PIDREF_NULL;
7✔
772
        int r;
7✔
773

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

777
        r = pidref_safe_fork("(sd-mknetns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG_SIGKILL|FORK_NEW_NETNS|FORK_FREEZE, &pid);
7✔
778
        if (r < 0)
7✔
779
                return log_debug_errno(r, "Failed to fork process into new netns: %m");
×
780
        assert(r > 0);
7✔
781

782
        return pidref_namespace_open_by_type(&pid, NAMESPACE_NET);
7✔
783
}
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