Debian Codegraph @

src/nsresourced/userns-registry.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/magic.h>
4 #include <linux/nsfs.h>
5 #include <sys/ioctl.h>
6 #include <unistd.h>
7
8 #include "sd-daemon.h"
9 #include "sd-json.h"
10 #include "sd-netlink.h"
11
12 #include "alloc-util.h"
13 #include "chase.h"
14 #include "errno-util.h"
15 #include "fd-util.h"
16 #include "fileio.h"
17 #include "format-util.h"
18 #include "fs-util.h"
19 #include "json-util.h"
20 #include "namespace-util.h"
21 #include "path-util.h"
22 #include "recurse-dir.h"
23 #include "rm-rf.h"
24 #include "stat-util.h"
25 #include "string-util.h"
26 #include "strv.h"
27 #include "uid-classification.h"
28 #include "user-util.h"
29 #include "userns-registry.h"
30 #include "userns-restrict.h"
31
32 int userns_registry_open_fd(void) {
33 int fd;
34
35 fd = chase_and_open(
36 "/run/systemd/nsresource/registry",
37 /* root= */ NULL,
38 CHASE_MKDIR_0755,
39 O_CLOEXEC|O_DIRECTORY|O_CREAT,
40 /* ret_path= */ NULL);
41 if (fd < 0)
42 return log_debug_errno(fd, "Failed to open registry dir: %m");
43
44 return fd;
45 }
46
47 int userns_registry_lock(int dir_fd) {
48 _cleanup_close_ int registry_fd = -EBADF, lock_fd = -EBADF;
49
50 if (dir_fd < 0) {
51 registry_fd = userns_registry_open_fd();
52 if (registry_fd < 0)
53 return registry_fd;
54
55 dir_fd = registry_fd;
56 }
57
58 lock_fd = xopenat_lock_full(dir_fd, "lock", O_CREAT|O_RDWR|O_CLOEXEC, /* xopen_flags= */ 0, 0600, LOCK_BSD, LOCK_EX);
59 if (lock_fd < 0)
60 return log_debug_errno(lock_fd, "Failed to open nsresource registry lock file: %m");
61
62 return TAKE_FD(lock_fd);
63 }
64
65 void delegated_userns_info_done(DelegatedUserNamespaceInfo *info) {
66 if (!info)
67 return;
68
69 info->ancestor_userns = mfree(info->ancestor_userns);
70 info->n_ancestor_userns = 0;
71 }
72
73 static DEFINE_ARRAY_FREE_FUNC(delegated_userns_info_free_array, DelegatedUserNamespaceInfo, delegated_userns_info_done);
74
75 UserNamespaceInfo* userns_info_new(void) {
76 UserNamespaceInfo *info = new(UserNamespaceInfo, 1);
77 if (!info)
78 return NULL;
79
80 *info = (UserNamespaceInfo) {
81 .owner = UID_INVALID,
82 .start_uid = UID_INVALID,
83 .target_uid = UID_INVALID,
84 .start_gid = GID_INVALID,
85 .target_gid = GID_INVALID,
86 };
87
88 return info;
89 }
90
91 UserNamespaceInfo *userns_info_free(UserNamespaceInfo *userns) {
92 if (!userns)
93 return NULL;
94
95 free(userns->cgroups);
96 free(userns->name);
97
98 delegated_userns_info_free_array(userns->delegates, userns->n_delegates);
99
100 strv_free(userns->netifs);
101
102 return mfree(userns);
103 }
104
105 static int dispatch_cgroups_array(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
106 UserNamespaceInfo *info = ASSERT_PTR(userdata);
107 _cleanup_free_ uint64_t *cgroups = NULL;
108 size_t n_cgroups = 0;
109
110 if (sd_json_variant_is_null(variant)) {
111 info->cgroups = mfree(info->cgroups);
112 info->n_cgroups = 0;
113 return 0;
114 }
115
116 if (!sd_json_variant_is_array(variant))
117 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an array.", strna(name));
118
119 cgroups = new(uint64_t, sd_json_variant_elements(variant));
120 if (!cgroups)
121 return json_log_oom(variant, flags);
122
123 sd_json_variant *e;
124 JSON_VARIANT_ARRAY_FOREACH(e, variant) {
125 bool found = false;
126
127 if (!sd_json_variant_is_unsigned(e))
128 return json_log(e, flags, SYNTHETIC_ERRNO(EINVAL), "JSON array element is not a number.");
129
130 FOREACH_ARRAY(cg, cgroups, n_cgroups)
131 if (*cg == sd_json_variant_unsigned(e)) {
132 found = true;
133 break;
134 }
135 if (found) /* suppress duplicate */
136 continue;
137
138 cgroups[n_cgroups++] = sd_json_variant_unsigned(e);
139 }
140
141 assert(n_cgroups <= sd_json_variant_elements(variant));
142
143 free_and_replace(info->cgroups, cgroups);
144 info->n_cgroups = n_cgroups;
145
146 return 0;
147 }
148
149 static int dispatch_delegates_array(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
150 UserNamespaceInfo *info = ASSERT_PTR(userdata);
151 DelegatedUserNamespaceInfo *delegates = NULL;
152 size_t n = 0;
153 int r;
154
155 CLEANUP_ARRAY(delegates, n, delegated_userns_info_free_array);
156
157 if (sd_json_variant_is_null(variant)) {
158 CLEANUP_ARRAY(info->delegates, info->n_delegates, delegated_userns_info_free_array);
159 return 0;
160 }
161
162 if (!sd_json_variant_is_array(variant))
163 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an array.", strna(name));
164
165 size_t elements = sd_json_variant_elements(variant);
166 if (elements > USER_NAMESPACE_DELEGATIONS_MAX)
167 return json_log(variant, flags, SYNTHETIC_ERRNO(E2BIG), "Too many delegations.");
168
169 delegates = new(DelegatedUserNamespaceInfo, elements);
170 if (!delegates)
171 return json_log_oom(variant, flags);
172
173 sd_json_variant *e;
174 JSON_VARIANT_ARRAY_FOREACH(e, variant) {
175 static const sd_json_dispatch_field delegate_dispatch_table[] = {
176 { "userns", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint64, offsetof(DelegatedUserNamespaceInfo, userns_inode), 0 },
177 { "start", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uid_gid, offsetof(DelegatedUserNamespaceInfo, start_uid), SD_JSON_MANDATORY },
178 { "startGid", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uid_gid, offsetof(DelegatedUserNamespaceInfo, start_gid), SD_JSON_MANDATORY },
179 { "size", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint32, offsetof(DelegatedUserNamespaceInfo, size), SD_JSON_MANDATORY },
180 {}
181 };
182
183 delegates[n] = DELEGATED_USER_NAMESPACE_INFO_NULL;
184
185 r = sd_json_dispatch(e, delegate_dispatch_table, flags, &delegates[n]);
186 if (r < 0)
187 return r;
188
189 if (!uid_is_valid(delegates[n].start_uid) || !gid_is_valid(delegates[n].start_gid))
190 return json_log(e, flags, SYNTHETIC_ERRNO(EINVAL), "Invalid delegate UID/GID.");
191
192 if (delegates[n].size == 0)
193 return json_log(e, flags, SYNTHETIC_ERRNO(EINVAL), "Invalid delegate size.");
194
195 n++;
196 }
197
198 delegated_userns_info_free_array(info->delegates, info->n_delegates);
199 info->delegates = TAKE_PTR(delegates);
200 info->n_delegates = n;
201
202 return 0;
203 }
204
205 static int dispatch_ancestor_userns_array(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
206 DelegatedUserNamespaceInfo *info = ASSERT_PTR(userdata);
207 _cleanup_free_ uint64_t *ancestor_userns = NULL;
208 size_t n = 0;
209
210 if (sd_json_variant_is_null(variant)) {
211 info->ancestor_userns = mfree(info->ancestor_userns);
212 info->n_ancestor_userns = 0;
213 return 0;
214 }
215
216 if (!sd_json_variant_is_array(variant))
217 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "JSON field '%s' is not an array.", strna(name));
218
219 ancestor_userns = new(uint64_t, sd_json_variant_elements(variant));
220 if (!ancestor_userns)
221 return json_log_oom(variant, flags);
222
223 sd_json_variant *e;
224 JSON_VARIANT_ARRAY_FOREACH(e, variant) {
225 if (!sd_json_variant_is_unsigned(e))
226 return json_log(e, flags, SYNTHETIC_ERRNO(EINVAL), "JSON array element is not an unsigned integer.");
227
228 uint64_t v = sd_json_variant_unsigned(e);
229 if (v == 0)
230 return json_log(e, flags, SYNTHETIC_ERRNO(EINVAL), "Invalid ancestor userns inode 0.");
231
232 ancestor_userns[n++] = v;
233 }
234
235 free_and_replace(info->ancestor_userns, ancestor_userns);
236 info->n_ancestor_userns = n;
237
238 return 0;
239 }
240
241 static int userns_registry_load(int dir_fd, const char *fn, UserNamespaceInfo **ret) {
242
243 static const sd_json_dispatch_field dispatch_table[] = {
244 { "owner", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uid_gid, offsetof(UserNamespaceInfo, owner), SD_JSON_MANDATORY },
245 { "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(UserNamespaceInfo, name), SD_JSON_MANDATORY },
246 { "userns", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint64, offsetof(UserNamespaceInfo, userns_inode), SD_JSON_MANDATORY },
247 { "usernsId", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint64, offsetof(UserNamespaceInfo, userns_id), 0 },
248 { "size", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint32, offsetof(UserNamespaceInfo, size), 0 },
249 { "start", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uid_gid, offsetof(UserNamespaceInfo, start_uid), 0 },
250 { "target", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uid_gid, offsetof(UserNamespaceInfo, target_uid), 0 },
251 { "startGid", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uid_gid, offsetof(UserNamespaceInfo, start_gid), 0 },
252 { "targetGid", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uid_gid, offsetof(UserNamespaceInfo, target_gid), 0 },
253 { "cgroups", SD_JSON_VARIANT_ARRAY, dispatch_cgroups_array, 0, 0 },
254 { "netifs", SD_JSON_VARIANT_ARRAY, sd_json_dispatch_strv, offsetof(UserNamespaceInfo, netifs), 0 },
255 { "delegates", SD_JSON_VARIANT_ARRAY, dispatch_delegates_array, 0, 0 },
256 {}
257 };
258
259 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
260 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
261 _cleanup_close_ int registry_fd = -EBADF;
262 int r;
263
264 if (dir_fd < 0) {
265 registry_fd = userns_registry_open_fd();
266 if (registry_fd < 0)
267 return registry_fd;
268
269 dir_fd = registry_fd;
270 }
271
272 r = sd_json_parse_file_at(NULL, dir_fd, fn, 0, &v, NULL, NULL);
273 if (r < 0)
274 return r;
275
276 userns_info = userns_info_new();
277 if (!userns_info)
278 return -ENOMEM;
279
280 r = sd_json_dispatch(v, dispatch_table, 0, userns_info);
281 if (r < 0)
282 return r;
283
284 if (userns_info->userns_inode == 0)
285 return -EBADMSG;
286
287 if (userns_info->size == 0) {
288 if (uid_is_valid(userns_info->start_uid) || uid_is_valid(userns_info->target_uid))
289 return -EBADMSG;
290
291 if (gid_is_valid(userns_info->start_gid) || gid_is_valid(userns_info->target_gid))
292 return -EBADMSG;
293 } else {
294 if (!uid_is_valid(userns_info->start_uid) || !uid_is_valid(userns_info->target_uid))
295 return -EBADMSG;
296
297 if (userns_info->size > UINT32_MAX - userns_info->start_uid ||
298 userns_info->size > UINT32_MAX - userns_info->target_uid)
299 return -EBADMSG;
300
301 /* Older versions of the registry didn't maintain UID/GID separately, hence copy over if not
302 * set */
303 if (!gid_is_valid(userns_info->start_gid))
304 userns_info->start_gid = userns_info->start_uid;
305 if (!gid_is_valid(userns_info->target_gid))
306 userns_info->target_gid = userns_info->target_uid;
307
308 if (userns_info->size > UINT32_MAX - userns_info->start_gid ||
309 userns_info->size > UINT32_MAX - userns_info->target_gid)
310 return -EBADMSG;
311 }
312
313 if (ret)
314 *ret = TAKE_PTR(userns_info);
315 return 0;
316 }
317
318 int userns_registry_uid_exists(int dir_fd, uid_t start) {
319 _cleanup_free_ char *fn = NULL;
320
321 assert(dir_fd >= 0);
322
323 if (!uid_is_valid(start))
324 return -ENOENT;
325
326 if (start == 0)
327 return true;
328
329 if (asprintf(&fn, "u" UID_FMT ".userns", start) < 0)
330 return -ENOMEM;
331
332 if (faccessat(dir_fd, fn, F_OK, AT_SYMLINK_NOFOLLOW) < 0)
333 return errno == ENOENT ? false : -errno;
334
335 return true;
336 }
337
338 int userns_registry_gid_exists(int dir_fd, gid_t start) {
339 _cleanup_free_ char *fn = NULL;
340
341 assert(dir_fd >= 0);
342
343 if (!gid_is_valid(start))
344 return -ENOENT;
345
346 if (start == 0)
347 return true;
348
349 if (asprintf(&fn, "g" GID_FMT ".userns", start) < 0)
350 return -ENOMEM;
351
352 if (faccessat(dir_fd, fn, F_OK, AT_SYMLINK_NOFOLLOW) < 0)
353 return errno == ENOENT ? false : -errno;
354
355 return true;
356 }
357
358 int userns_registry_name_exists(int dir_fd, const char *name) {
359 _cleanup_free_ char *fn = NULL;
360
361 assert(dir_fd >= 0);
362
363 if (!userns_name_is_valid(name))
364 return -EINVAL;
365
366 fn = strjoin("n", name, ".userns");
367 if (!fn)
368 return -ENOMEM;
369
370 if (faccessat(dir_fd, fn, F_OK, AT_SYMLINK_NOFOLLOW) < 0)
371 return errno == ENOENT ? false : -errno;
372
373 return true;
374 }
375
376 int userns_registry_load_by_start_uid(int dir_fd, uid_t start, UserNamespaceInfo **ret) {
377 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
378 _cleanup_close_ int registry_fd = -EBADF;
379 _cleanup_free_ char *fn = NULL;
380 int r;
381
382 if (!uid_is_valid(start))
383 return -ENOENT;
384
385 if (dir_fd < 0) {
386 registry_fd = userns_registry_open_fd();
387 if (registry_fd < 0)
388 return registry_fd;
389
390 dir_fd = registry_fd;
391 }
392
393 if (asprintf(&fn, "u" UID_FMT ".userns", start) < 0)
394 return -ENOMEM;
395
396 r = userns_registry_load(dir_fd, fn, &userns_info);
397 if (r < 0)
398 return r;
399
400 if (userns_info->start_uid != start)
401 return -EBADMSG;
402
403 if (ret)
404 *ret = TAKE_PTR(userns_info);
405
406 return 0;
407 }
408
409 int userns_registry_load_by_start_gid(int dir_fd, gid_t start, UserNamespaceInfo **ret) {
410 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
411 _cleanup_close_ int registry_fd = -EBADF;
412 _cleanup_free_ char *fn = NULL;
413 int r;
414
415 if (!gid_is_valid(start))
416 return -ENOENT;
417
418 if (dir_fd < 0) {
419 registry_fd = userns_registry_open_fd();
420 if (registry_fd < 0)
421 return registry_fd;
422
423 dir_fd = registry_fd;
424 }
425
426 if (asprintf(&fn, "g" GID_FMT ".userns", start) < 0)
427 return -ENOMEM;
428
429 r = userns_registry_load(dir_fd, fn, &userns_info);
430 if (r < 0)
431 return r;
432
433 if (userns_info->start_gid != start)
434 return -EBADMSG;
435
436 if (ret)
437 *ret = TAKE_PTR(userns_info);
438
439 return 0;
440 }
441
442 int userns_registry_load_by_userns_inode(int dir_fd, uint64_t inode, UserNamespaceInfo **ret) {
443 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
444 _cleanup_close_ int registry_fd = -EBADF;
445 _cleanup_free_ char *fn = NULL;
446 int r;
447
448 if (inode == 0)
449 return -ENOENT;
450
451 if (dir_fd < 0) {
452 registry_fd = userns_registry_open_fd();
453 if (registry_fd < 0)
454 return registry_fd;
455
456 dir_fd = registry_fd;
457 }
458
459 if (asprintf(&fn, "i%" PRIu64 ".userns", inode) < 0)
460 return -ENOMEM;
461
462 r = userns_registry_load(dir_fd, fn, &userns_info);
463 if (r < 0)
464 return r;
465
466 if (userns_info->userns_inode != inode)
467 return -EBADMSG;
468
469 if (ret)
470 *ret = TAKE_PTR(userns_info);
471
472 return 0;
473 }
474
475 static void release_userns_inode_resources(struct userns_restrict_bpf *bpf, uint64_t inode) {
476 int r;
477
478 assert(inode != 0);
479
480 if (bpf) {
481 r = userns_restrict_reset_by_inode(bpf, inode);
482 if (r < 0)
483 log_warning_errno(r, "Failed to remove namespace inode from BPF map, ignoring: %m");
484 }
485
486 r = sd_notifyf(/* unset_environment= */ false,
487 "FDSTOREREMOVE=1\n"
488 "FDNAME=userns-%" PRIu64 "\n", inode);
489 if (r < 0)
490 log_warning_errno(r, "Failed to send fd store removal message, ignoring: %m");
491 }
492
493 void userns_registry_release_by_info(struct userns_restrict_bpf *bpf, int dir_fd, UserNamespaceInfo *info) {
494 int r;
495
496 assert(dir_fd >= 0);
497 assert(info);
498 assert(info->userns_inode != 0);
499
500 if (DEBUG_LOGGING) {
501 if (uid_is_valid(info->start_uid))
502 log_debug("Removing user namespace mapping %" PRIu64 " for UID " UID_FMT ".", info->userns_inode, info->start_uid);
503 else
504 log_debug("Removing user namespace mapping %" PRIu64 ".", info->userns_inode);
505 }
506
507 release_userns_inode_resources(bpf, info->userns_inode);
508
509 r = userns_info_remove_cgroups(info);
510 if (r < 0)
511 log_warning_errno(r, "Failed to remove cgroups of user namespace, ignoring: %m");
512
513 r = userns_info_remove_netifs(info);
514 if (r < 0)
515 log_warning_errno(r, "Failed to remove netifs of user namespace, ignoring: %m");
516
517 r = userns_registry_remove(dir_fd, info);
518 if (r < 0)
519 log_warning_errno(r, "Failed to remove user namespace '%s', ignoring.", info->name);
520 }
521
522 void userns_registry_release_by_userns_inode(struct userns_restrict_bpf *bpf, int dir_fd, uint64_t inode) {
523 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
524 int r;
525
526 assert(dir_fd >= 0);
527 assert(inode != 0);
528
529 r = userns_registry_load_by_userns_inode(dir_fd, inode, &userns_info);
530 if (r >= 0)
531 return userns_registry_release_by_info(bpf, dir_fd, userns_info);
532
533 log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
534 "Failed to find userns for inode %" PRIu64 ", ignoring: %m", inode);
535 log_debug("Removing user namespace mapping %" PRIu64 ".", inode);
536
537 /* No registry entry — still clean up the inode-keyed kernel resources (BPF map allowlist and
538 * fdstore fd), which can outlive a missing registry record. */
539 release_userns_inode_resources(bpf, inode);
540 }
541
542 int userns_registry_reap_if_dead(struct userns_restrict_bpf *bpf, int dir_fd, uint64_t inode) {
543 _cleanup_(userns_info_freep) UserNamespaceInfo *info = NULL;
544 int r;
545
546 assert(dir_fd >= 0);
547 assert(inode != 0);
548
549 /* This is the shared engine behind both the runtime allocation hot path and the startup
550 * registry sweep: it reclaims ranges blocked by a dead namespace that no BPF death event
551 * cleaned up, without waiting for the manager to restart. */
552
553 r = userns_registry_load_by_userns_inode(dir_fd, inode, &info);
554 if (r == -ENOENT)
555 /* No entry is registered for this inode any more (already gone) — e.g. a dead ancestor
556 * still referenced by a delegation chain. Nothing to reap. */
557 return USERNS_REAP_INDETERMINATE;
558 if (r < 0)
559 return r;
560
561 if (info->userns_id == 0)
562 return USERNS_REAP_INDETERMINATE; /* Entry predates ns id tracking, can't probe authoritatively. */
563
564 _cleanup_close_ int probe_fd = namespace_open_by_id(info->userns_id);
565 if (probe_fd >= 0)
566 return USERNS_REAP_ALIVE; /* Still alive (or the inode was recycled for a live namespace). */
567 if (ERRNO_IS_NEG_PRIVILEGE(probe_fd) || ERRNO_IS_NEG_NOT_SUPPORTED(probe_fd) || probe_fd == -EINVAL)
568 /* EPERM/EACCES (not in the initial user namespace, missing CAP_SYS_ADMIN), or
569 * ENOTSUP/ENOSYS/EINVAL (kernel new enough for NS_GET_ID but too old for
570 * open_by_handle_at() lookup by id on nsfs) — we can't confirm death for this or any
571 * other entry. The userns_id == 0 case is already handled above, so -EINVAL here means
572 * the lookup is unsupported rather than a bad id. */
573 return USERNS_REAP_UNSUPPORTED;
574 if (probe_fd != -ESTALE)
575 return probe_fd; /* Unexpected probe error. */
576
577 log_debug("User namespace %" PRIu64 " (id %" PRIu64 ") refers to a dead namespace, reclaiming its resources.",
578 inode, info->userns_id);
579
580 userns_registry_release_by_info(bpf, dir_fd, info);
581 return USERNS_REAP_RELEASED;
582 }
583
584 int userns_info_verify_fd(int userns_fd, const UserNamespaceInfo *info) {
585 uint64_t live_id;
586
587 assert(userns_fd >= 0);
588 assert(info);
589
590 /* Verifies that userns_fd refers to the same user namespace described by info, distinguishing a
591 * live namespace from a different one that happens to have inherited the same inode after the
592 * original was destroyed. Returns 0 on match (also when the check cannot be performed because
593 * the stored or live id is unavailable on older kernels), -ESTALE on mismatch, or another
594 * negative errno on unexpected failure. */
595
596 if (info->userns_id == 0)
597 return 0;
598
599 if (ioctl(userns_fd, NS_GET_ID, &live_id) < 0) {
600 if (ERRNO_IS_IOCTL_NOT_SUPPORTED(errno))
601 return 0;
602 return -errno;
603 }
604
605 return live_id == info->userns_id ? 0 : -ESTALE;
606 }
607
608 int userns_registry_load_by_name(int dir_fd, const char *name, UserNamespaceInfo **ret) {
609 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
610 _cleanup_close_ int registry_fd = -EBADF;
611 _cleanup_free_ char *fn = NULL;
612 int r;
613
614 assert(name);
615
616 if (!userns_name_is_valid(name)) /* Invalid names never exist */
617 return -ENOENT;
618
619 if (dir_fd < 0) {
620 registry_fd = userns_registry_open_fd();
621 if (registry_fd < 0)
622 return registry_fd;
623
624 dir_fd = registry_fd;
625 }
626
627 fn = strjoin("n", name, ".userns");
628 if (!fn)
629 return -ENOMEM;
630
631 r = userns_registry_load(dir_fd, fn, &userns_info);
632 if (r < 0)
633 return r;
634
635 if (!streq_ptr(userns_info->name, name))
636 return -EBADMSG;
637
638 if (ret)
639 *ret = TAKE_PTR(userns_info);
640
641 return 0;
642 }
643
644 int userns_registry_store(int dir_fd, UserNamespaceInfo *info) {
645 _cleanup_close_ int registry_fd = -EBADF;
646 int r;
647
648 assert(info);
649
650 if (!uid_is_valid(info->owner) ||
651 !info->name ||
652 info->userns_inode == 0)
653 return -EINVAL;
654
655 if (dir_fd < 0) {
656 registry_fd = userns_registry_open_fd();
657 if (registry_fd < 0)
658 return registry_fd;
659
660 dir_fd = registry_fd;
661 }
662
663 _cleanup_(sd_json_variant_unrefp) sd_json_variant *cgroup_array = NULL;
664 FOREACH_ARRAY(cg, info->cgroups, info->n_cgroups) {
665 r = sd_json_variant_append_arrayb(
666 &cgroup_array,
667 SD_JSON_BUILD_UNSIGNED(*cg));
668 if (r < 0)
669 return r;
670 }
671
672 _cleanup_(sd_json_variant_unrefp) sd_json_variant *delegates_array = NULL;
673 FOREACH_ARRAY(delegate, info->delegates, info->n_delegates) {
674 r = sd_json_variant_append_arraybo(
675 &delegates_array,
676 SD_JSON_BUILD_PAIR_UNSIGNED("userns", delegate->userns_inode),
677 SD_JSON_BUILD_PAIR_UNSIGNED("start", delegate->start_uid),
678 SD_JSON_BUILD_PAIR_UNSIGNED("startGid", delegate->start_gid),
679 SD_JSON_BUILD_PAIR_UNSIGNED("size", delegate->size));
680 if (r < 0)
681 return r;
682 }
683
684 _cleanup_(sd_json_variant_unrefp) sd_json_variant *def = NULL;
685 r = sd_json_buildo(
686 &def,
687 SD_JSON_BUILD_PAIR_UNSIGNED("owner", info->owner),
688 SD_JSON_BUILD_PAIR_STRING("name", info->name),
689 SD_JSON_BUILD_PAIR_UNSIGNED("userns", info->userns_inode),
690 SD_JSON_BUILD_PAIR_CONDITION(info->userns_id != 0, "usernsId", SD_JSON_BUILD_UNSIGNED(info->userns_id)),
691 SD_JSON_BUILD_PAIR_CONDITION(info->size > 0, "size", SD_JSON_BUILD_UNSIGNED(info->size)),
692 SD_JSON_BUILD_PAIR_CONDITION(uid_is_valid(info->start_uid), "start", SD_JSON_BUILD_UNSIGNED(info->start_uid)),
693 SD_JSON_BUILD_PAIR_CONDITION(uid_is_valid(info->target_uid), "target", SD_JSON_BUILD_UNSIGNED(info->target_uid)),
694 SD_JSON_BUILD_PAIR_CONDITION(gid_is_valid(info->start_gid), "startGid", SD_JSON_BUILD_UNSIGNED(info->start_gid)),
695 SD_JSON_BUILD_PAIR_CONDITION(gid_is_valid(info->target_gid), "targetGid", SD_JSON_BUILD_UNSIGNED(info->target_gid)),
696 SD_JSON_BUILD_PAIR_CONDITION(!!cgroup_array, "cgroups", SD_JSON_BUILD_VARIANT(cgroup_array)),
697 JSON_BUILD_PAIR_STRV_NON_EMPTY("netifs", info->netifs),
698 SD_JSON_BUILD_PAIR_CONDITION(!!delegates_array, "delegates", SD_JSON_BUILD_VARIANT(delegates_array)));
699 if (r < 0)
700 return r;
701
702 _cleanup_free_ char *def_buf = NULL;
703 r = sd_json_variant_format(def, 0, &def_buf);
704 if (r < 0)
705 return log_debug_errno(r, "Failed to format userns JSON object: %m");
706
707 _cleanup_free_ char *reg_fn = NULL, *link1_fn = NULL, *link2_fn = NULL, *link3_fn = NULL, *owner_fn = NULL, *uid_fn = NULL;
708 if (asprintf(&reg_fn, "i%" PRIu64 ".userns", info->userns_inode) < 0)
709 return log_oom_debug();
710
711 r = write_string_file_at(dir_fd, reg_fn, def_buf, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
712 if (r < 0)
713 return log_debug_errno(r, "Failed to write userns data to '%s' in registry: %m", reg_fn);
714
715 link1_fn = strjoin("n", info->name, ".userns");
716 if (!link1_fn) {
717 r = log_oom_debug();
718 goto fail;
719 }
720
721 r = linkat_replace(dir_fd, reg_fn, dir_fd, link1_fn);
722 if (r < 0) {
723 log_debug_errno(r, "Failed to link userns data to '%s' in registry: %m", link1_fn);
724 goto fail;
725 }
726
727 if (uid_is_transient(info->start_uid)) {
728 if (asprintf(&link2_fn, "u" UID_FMT ".userns", info->start_uid) < 0) {
729 r = log_oom_debug();
730 goto fail;
731 }
732
733 r = linkat_replace(dir_fd, reg_fn, dir_fd, link2_fn);
734 if (r < 0) {
735 log_debug_errno(r, "Failed to link userns data to '%s' in registry: %m", link2_fn);
736 goto fail;
737 }
738 }
739
740 if (gid_is_transient(info->start_gid)) {
741 if (asprintf(&link3_fn, "g" GID_FMT ".userns", info->start_gid) < 0) {
742 r = log_oom_debug();
743 goto fail;
744 }
745
746 r = linkat_replace(dir_fd, reg_fn, dir_fd, link3_fn);
747 if (r < 0) {
748 log_debug_errno(r, "Failed to link userns data to '%s' in registry: %m", link3_fn);
749 goto fail;
750 }
751 }
752
753 if (asprintf(&uid_fn, "o" UID_FMT ".owns", info->owner) < 0) {
754 r = log_oom_debug();
755 goto fail;
756 }
757
758 if (mkdirat(dir_fd, uid_fn, 0755) < 0 && errno != EEXIST) {
759 r = log_debug_errno(errno, "Failed to create per-UID subdir '%s' of registry: %m", uid_fn);
760 goto fail;
761 }
762
763 if (asprintf(&owner_fn, "%s/i%" PRIu64 ".userns", uid_fn, info->userns_inode) < 0) {
764 r = log_oom_debug();
765 goto fail;
766 }
767
768 r = linkat_replace(dir_fd, reg_fn, dir_fd, owner_fn);
769 if (r < 0) {
770 log_debug_errno(r, "Failed to link userns data to '%s' in registry: %m", owner_fn);
771 goto fail;
772 }
773
774 /* Store delegation files */
775 FOREACH_ARRAY(delegate, info->delegates, info->n_delegates) {
776 _cleanup_(sd_json_variant_unrefp) sd_json_variant *delegate_def = NULL, *ancestor_array = NULL;
777 _cleanup_free_ char *delegate_buf = NULL, *delegate_uid_fn = NULL, *delegate_gid_fn = NULL;
778
779 if (asprintf(&delegate_uid_fn, "u" UID_FMT ".delegate", delegate->start_uid) < 0) {
780 r = log_oom_debug();
781 goto fail;
782 }
783
784 /* Check if this delegation already exists. If so, this is a recursive
785 * subdelegation: we need to preserve the chain of previous owners so that
786 * ownership can be restored when the current owner goes away. */
787 _cleanup_(delegated_userns_info_done) DelegatedUserNamespaceInfo existing = DELEGATED_USER_NAMESPACE_INFO_NULL;
788
789 r = userns_registry_load_delegation_by_uid(dir_fd, delegate->start_uid, &existing);
790 if (r >= 0) {
791 /* Delegation file exists — append old owner to ancestor chain */
792 FOREACH_ARRAY(ancestor_userns, existing.ancestor_userns, existing.n_ancestor_userns) {
793 r = sd_json_variant_append_arrayb(
794 &ancestor_array,
795 SD_JSON_BUILD_UNSIGNED(*ancestor_userns));
796 if (r < 0)
797 goto fail;
798 }
799
800 /* userns_registry_store() is also called to update existing entries in the registry
801 * in which case we don't need to update the ownership of the delegated UID ranges. */
802 if (delegate->userns_inode != existing.userns_inode) {
803 r = sd_json_variant_append_arrayb(
804 &ancestor_array,
805 SD_JSON_BUILD_UNSIGNED(existing.userns_inode));
806 if (r < 0)
807 goto fail;
808 }
809
810 } else if (r != -ENOENT) {
811 log_debug_errno(r, "Failed to load existing delegation for UID " UID_FMT ": %m", delegate->start_uid);
812 goto fail;
813 }
814
815 r = sd_json_buildo(
816 &delegate_def,
817 SD_JSON_BUILD_PAIR_UNSIGNED("userns", delegate->userns_inode),
818 SD_JSON_BUILD_PAIR_UNSIGNED("start", delegate->start_uid),
819 SD_JSON_BUILD_PAIR_UNSIGNED("startGid", delegate->start_gid),
820 SD_JSON_BUILD_PAIR_UNSIGNED("size", delegate->size),
821 SD_JSON_BUILD_PAIR_CONDITION(!!ancestor_array, "ancestorUserns", SD_JSON_BUILD_VARIANT(ancestor_array)));
822 if (r < 0)
823 goto fail;
824
825 r = sd_json_variant_format(delegate_def, /* flags= */ 0, &delegate_buf);
826 if (r < 0) {
827 log_debug_errno(r, "Failed to format delegation JSON object: %m");
828 goto fail;
829 }
830
831 r = write_string_file_at(dir_fd, delegate_uid_fn, delegate_buf, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
832 if (r < 0) {
833 log_debug_errno(r, "Failed to write delegation data to '%s' in registry: %m", delegate_uid_fn);
834 goto fail;
835 }
836
837 /* Create GID symlink pointing to the UID file */
838 if (asprintf(&delegate_gid_fn, "g" GID_FMT ".delegate", delegate->start_gid) < 0) {
839 r = log_oom_debug();
840 goto fail;
841 }
842
843 r = linkat_replace(dir_fd, delegate_uid_fn, dir_fd, delegate_gid_fn);
844 if (r < 0) {
845 log_debug_errno(r, "Failed to link delegation data to '%s' in registry: %m", delegate_gid_fn);
846 goto fail;
847 }
848 }
849
850 return 0;
851
852 fail:
853 if (reg_fn)
854 (void) unlinkat(dir_fd, reg_fn, /* flags= */ 0);
855 if (link1_fn)
856 (void) unlinkat(dir_fd, link1_fn, /* flags= */ 0);
857 if (link2_fn)
858 (void) unlinkat(dir_fd, link2_fn, /* flags= */ 0);
859 if (link3_fn)
860 (void) unlinkat(dir_fd, link3_fn, /* flags= */ 0);
861 if (owner_fn)
862 (void) unlinkat(dir_fd, owner_fn, /* flags= */ 0);
863 if (uid_fn)
864 (void) unlinkat(dir_fd, uid_fn, AT_REMOVEDIR);
865
866 /* Clean up any delegation files we created */
867 FOREACH_ARRAY(delegate, info->delegates, info->n_delegates) {
868 _cleanup_free_ char *delegate_uid_fn = NULL, *delegate_gid_fn = NULL;
869
870 if (asprintf(&delegate_uid_fn, "u" UID_FMT ".delegate", delegate->start_uid) >= 0)
871 (void) unlinkat(dir_fd, delegate_uid_fn, /* flags= */ 0);
872
873 if (asprintf(&delegate_gid_fn, "g" GID_FMT ".delegate", delegate->start_gid) >= 0)
874 (void) unlinkat(dir_fd, delegate_gid_fn, /* flags= */ 0);
875 }
876
877 return r;
878 }
879
880 int userns_registry_remove(int dir_fd, UserNamespaceInfo *info) {
881 _cleanup_close_ int registry_fd = -EBADF;
882 int ret = 0, r;
883
884 assert(info);
885
886 if (dir_fd < 0) {
887 registry_fd = userns_registry_open_fd();
888 if (registry_fd < 0)
889 return registry_fd;
890
891 dir_fd = registry_fd;
892 }
893
894 _cleanup_free_ char *reg_fn = NULL;
895 if (asprintf(&reg_fn, "i%" PRIu64 ".userns", info->userns_inode) < 0)
896 return log_oom_debug();
897
898 r = RET_NERRNO(unlinkat(dir_fd, reg_fn, 0));
899 if (r < 0)
900 RET_GATHER(ret, log_debug_errno(r, "Failed to remove %s: %m", reg_fn));
901
902 _cleanup_free_ char *link1_fn = NULL;
903 link1_fn = strjoin("n", info->name, ".userns");
904 if (!link1_fn)
905 return log_oom_debug();
906
907 r = RET_NERRNO(unlinkat(dir_fd, link1_fn, 0));
908 if (r < 0)
909 RET_GATHER(ret, log_debug_errno(r, "Failed to remove %s: %m", link1_fn));
910
911 if (uid_is_transient(info->start_uid)) {
912 _cleanup_free_ char *link2_fn = NULL;
913
914 if (asprintf(&link2_fn, "u" UID_FMT ".userns", info->start_uid) < 0)
915 return log_oom_debug();
916
917 r = RET_NERRNO(unlinkat(dir_fd, link2_fn, 0));
918 if (r < 0)
919 RET_GATHER(ret, log_debug_errno(r, "Failed to remove %s: %m", link2_fn));
920 }
921
922 if (gid_is_transient(info->start_gid)) {
923 _cleanup_free_ char *link3_fn = NULL;
924
925 if (asprintf(&link3_fn, "g" GID_FMT ".userns", info->start_gid) < 0)
926 return log_oom_debug();
927
928 r = RET_NERRNO(unlinkat(dir_fd, link3_fn, 0));
929 if (r < 0)
930 RET_GATHER(ret, log_debug_errno(r, "Failed to remove %s: %m", link3_fn));
931 }
932
933 _cleanup_free_ char *uid_fn = NULL;
934 if (asprintf(&uid_fn, "o" UID_FMT ".owns", info->owner) < 0)
935 return log_oom_debug();
936
937 _cleanup_free_ char *owner_fn = NULL;
938 if (asprintf(&owner_fn, "%s/i%" PRIu64 ".userns", uid_fn, info->userns_inode) < 0)
939 return log_oom_debug();
940
941 r = RET_NERRNO(unlinkat(dir_fd, owner_fn, 0));
942 if (r < 0)
943 RET_GATHER(ret, log_debug_errno(r, "Failed to remove %s: %m", owner_fn));
944
945 r = RET_NERRNO(unlinkat(dir_fd, uid_fn, AT_REMOVEDIR));
946 if (r < 0 && r != -ENOTEMPTY)
947 RET_GATHER(ret, log_debug_errno(r, "Failed to remove %s: %m", uid_fn));
948
949 /* Remove or restore delegation files */
950 FOREACH_ARRAY(delegate, info->delegates, info->n_delegates) {
951 /* Check if this delegation has ancestor user namespaces. If so, restore ownership to
952 * the last ancestor instead of removing the delegation file entirely. */
953 _cleanup_(delegated_userns_info_done) DelegatedUserNamespaceInfo existing = DELEGATED_USER_NAMESPACE_INFO_NULL;
954
955 r = userns_registry_load_delegation_by_uid(dir_fd, delegate->start_uid, &existing);
956 if (r < 0) {
957 log_debug_errno(r,
958 "Failed to load delegated UID range starting at "UID_FMT":"GID_FMT" for userns %"PRIu64": %m",
959 delegate->start_uid, delegate->start_gid, delegate->userns_inode);
960 RET_GATHER(ret, r);
961 continue;
962 }
963
964 _cleanup_free_ char *delegate_uid_fn = NULL, *delegate_gid_fn = NULL;
965 if (asprintf(&delegate_uid_fn, "u" UID_FMT ".delegate", delegate->start_uid) < 0)
966 return log_oom_debug();
967 if (asprintf(&delegate_gid_fn, "g" GID_FMT ".delegate", delegate->start_gid) < 0)
968 return log_oom_debug();
969
970 if (existing.n_ancestor_userns > 0) {
971 _cleanup_(sd_json_variant_unrefp) sd_json_variant *delegate_def = NULL, *ancestor_array = NULL;
972 _cleanup_free_ char *delegate_buf = NULL;
973
974 /* Pop the last ancestor userns inode to become the new owner */
975 uint64_t new_owner = existing.ancestor_userns[existing.n_ancestor_userns - 1];
976
977 log_debug("Moving ownership of delegated UID range from %"PRIu64" to %"PRIu64".",
978 delegate->userns_inode, new_owner);
979
980 /* Rebuild ancestor array without the last entry */
981 for (size_t j = 0; j + 1 < existing.n_ancestor_userns; j++) {
982 r = sd_json_variant_append_arrayb(
983 &ancestor_array,
984 SD_JSON_BUILD_UNSIGNED(existing.ancestor_userns[j]));
985 if (r < 0)
986 return log_debug_errno(r, "Failed to append to JSON array: %m");
987 }
988
989 r = sd_json_buildo(
990 &delegate_def,
991 SD_JSON_BUILD_PAIR_UNSIGNED("userns", new_owner),
992 SD_JSON_BUILD_PAIR_UNSIGNED("start", existing.start_uid),
993 SD_JSON_BUILD_PAIR_UNSIGNED("startGid", existing.start_gid),
994 SD_JSON_BUILD_PAIR_UNSIGNED("size", existing.size),
995 SD_JSON_BUILD_PAIR_CONDITION(!!ancestor_array, "ancestorUserns", SD_JSON_BUILD_VARIANT(ancestor_array)));
996 if (r < 0)
997 return log_debug_errno(r, "Failed to build delegate JSON object: %m");
998
999 r = sd_json_variant_format(delegate_def, /* flags= */ 0, &delegate_buf);
1000 if (r < 0)
1001 return log_debug_errno(r, "Failed to format delegation JSON object: %m");
1002
1003 r = write_string_file_at(dir_fd, delegate_uid_fn, delegate_buf, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1004 if (r < 0) {
1005 RET_GATHER(ret, log_debug_errno(r, "Failed to write restored delegation data to '%s' in registry: %m", delegate_uid_fn));
1006 continue;
1007 }
1008
1009 /* The atomic write above replaced the UID file with a new inode, so the
1010 * hardlink to the GID file is now broken. Re-create it to keep the two in
1011 * sync. */
1012 r = linkat_replace(dir_fd, delegate_uid_fn, dir_fd, delegate_gid_fn);
1013 if (r < 0)
1014 RET_GATHER(ret, log_debug_errno(r, "Failed to re-link '%s' to '%s' in registry: %m", delegate_uid_fn, delegate_gid_fn));
1015
1016 continue;
1017 }
1018
1019 log_debug("Removing delegated UID range starting at "UID_FMT":"GID_FMT" for userns %"PRIu64 ".",
1020 delegate->start_uid, delegate->start_gid, delegate->userns_inode);
1021
1022 /* No ancestor chain — just remove the delegation files */
1023 r = RET_NERRNO(unlinkat(dir_fd, delegate_uid_fn, 0));
1024 if (r < 0)
1025 RET_GATHER(ret, log_debug_errno(r, "Failed to remove %s: %m", delegate_uid_fn));
1026
1027 r = RET_NERRNO(unlinkat(dir_fd, delegate_gid_fn, 0));
1028 if (r < 0)
1029 RET_GATHER(ret, log_debug_errno(r, "Failed to remove %s: %m", delegate_gid_fn));
1030 }
1031
1032 return ret;
1033 }
1034
1035 bool userns_info_has_cgroup(UserNamespaceInfo *userns, uint64_t cgroup_id) {
1036 assert(userns);
1037
1038 FOREACH_ARRAY(i, userns->cgroups, userns->n_cgroups)
1039 if (*i == cgroup_id)
1040 return true;
1041
1042 return false;
1043 }
1044
1045 int userns_info_add_cgroup(UserNamespaceInfo *userns, uint64_t cgroup_id) {
1046 assert(userns);
1047
1048 if (userns_info_has_cgroup(userns, cgroup_id))
1049 return 0;
1050
1051 if (!GREEDY_REALLOC(userns->cgroups, userns->n_cgroups+1))
1052 return -ENOMEM;
1053
1054 userns->cgroups[userns->n_cgroups++] = cgroup_id;
1055 return 1;
1056 }
1057
1058 static int userns_destroy_cgroup(uint64_t cgroup_id) {
1059 _cleanup_close_ int cgroup_fd = -EBADF, parent_fd = -EBADF;
1060 int r;
1061
1062 cgroup_fd = cg_cgroupid_open(/* cgroupfs_fd= */ -EBADF, cgroup_id);
1063 if (cgroup_fd == -ESTALE) {
1064 log_debug_errno(cgroup_fd, "Control group %" PRIu64 " already gone, ignoring.", cgroup_id);
1065 return 0;
1066 }
1067 if (cgroup_fd < 0)
1068 return log_debug_errno(cgroup_fd, "Failed to open cgroup %" PRIu64 ", ignoring: %m", cgroup_id);
1069
1070 _cleanup_free_ char *path = NULL;
1071 r = fd_get_path(cgroup_fd, &path);
1072 if (r < 0)
1073 return log_debug_errno(r, "Failed to get path of cgroup %" PRIu64 ", ignoring: %m", cgroup_id);
1074
1075 const char *e = path_startswith(path, "/sys/fs/cgroup/");
1076 if (!e)
1077 return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "Got cgroup path that doesn't start with /sys/fs/cgroup/, refusing: %s", path);
1078 if (isempty(e))
1079 return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "Got root cgroup path, which can't be right, refusing.");
1080
1081 log_debug("Destroying cgroup %" PRIu64 " (%s)", cgroup_id, path);
1082
1083 _cleanup_free_ char *fname = NULL;
1084 r = path_extract_filename(path, &fname);
1085 if (r < 0)
1086 return log_debug_errno(r, "Failed to extract name of cgroup %" PRIu64 ", ignoring: %m", cgroup_id);
1087
1088 parent_fd = openat(cgroup_fd, "..", O_CLOEXEC|O_DIRECTORY);
1089 if (parent_fd < 0)
1090 return log_debug_errno(errno, "Failed to open parent cgroup of %" PRIu64 ", ignoring: %m", cgroup_id);
1091
1092 /* Safety check, never leave cgroupfs */
1093 r = fd_is_fs_type(parent_fd, CGROUP2_SUPER_MAGIC);
1094 if (r < 0)
1095 return log_debug_errno(r, "Failed to determine if parent directory of cgroup %" PRIu64 " is still a cgroup, ignoring: %m", cgroup_id);
1096 if (!r)
1097 return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "Parent directory of cgroup %" PRIu64 " is not a cgroup, refusing.", cgroup_id);
1098
1099 cgroup_fd = safe_close(cgroup_fd);
1100
1101 r = rm_rf_child(parent_fd, fname, REMOVE_ONLY_DIRECTORIES|REMOVE_CHMOD);
1102 if (r < 0)
1103 log_debug_errno(r, "Failed to remove delegated cgroup %" PRIu64 ", ignoring: %m", cgroup_id);
1104
1105 return 0;
1106 }
1107
1108 int userns_info_remove_cgroups(UserNamespaceInfo *userns) {
1109 int ret = 0;
1110
1111 assert(userns);
1112
1113 FOREACH_ARRAY(c, userns->cgroups, userns->n_cgroups)
1114 RET_GATHER(ret, userns_destroy_cgroup(*c));
1115
1116 userns->cgroups = mfree(userns->cgroups);
1117 userns->n_cgroups = 0;
1118
1119 return ret;
1120 }
1121
1122 int userns_info_add_netif(UserNamespaceInfo *userns, const char *netif) {
1123 int r;
1124
1125 assert(userns);
1126 assert(netif);
1127
1128 if (strv_contains(userns->netifs, netif))
1129 return 0;
1130
1131 r = strv_extend(&userns->netifs, netif);
1132 if (r < 0)
1133 return r;
1134
1135 return 1;
1136 }
1137
1138 static int userns_destroy_netif(sd_netlink **rtnl, const char *name) {
1139 int r;
1140
1141 assert(rtnl);
1142 assert(name);
1143
1144 log_debug("Removing delegated network interface '%s'", name);
1145
1146 if (!*rtnl) {
1147 r = sd_netlink_open(rtnl);
1148 if (r < 0)
1149 return log_debug_errno(r, "Failed to connect to netlink: %m");
1150 }
1151
1152 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
1153 r = sd_rtnl_message_new_link(*rtnl, &m, RTM_DELLINK, /* ifindex= */ 0);
1154 if (r < 0)
1155 return r;
1156
1157 r = sd_netlink_message_append_string(m, IFLA_IFNAME, name);
1158 if (r < 0)
1159 return r;
1160
1161 r = sd_netlink_call(*rtnl, m, /* timeout= */ 0, /* ret= */ NULL);
1162 if (ERRNO_IS_NEG_DEVICE_ABSENT(r)) /* Already gone? */
1163 return 0;
1164 if (r < 0)
1165 return log_debug_errno(r, "Failed to remove interface %s: %m", name);
1166
1167 return 1;
1168 }
1169
1170 int userns_info_remove_netifs(UserNamespaceInfo *userns) {
1171 _cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL;
1172 int ret = 0;
1173
1174 assert(userns);
1175
1176 STRV_FOREACH(c, userns->netifs)
1177 RET_GATHER(ret, userns_destroy_netif(&rtnl, *c));
1178
1179 userns->netifs = strv_free(userns->netifs);
1180 return ret;
1181 }
1182
1183 bool userns_name_is_valid(const char *name) {
1184
1185 /* Checks if the specified string is suitable as user namespace name. */
1186
1187 if (isempty(name))
1188 return false;
1189
1190 if (strlen(name) > NAME_MAX) /* before we use alloca(), let's check for size */
1191 return false;
1192
1193 const char *f = strjoina("n", name, ".userns"); /* Make sure we can name our lookup symlink with this name */
1194 if (!filename_is_valid(f))
1195 return false;
1196
1197 const char *u = strjoina("ns-", name, "-65535"); /* Make sure we can turn this into valid user names */
1198 if (!valid_user_group_name(u, 0))
1199 return false;
1200
1201 return true;
1202 }
1203
1204 int userns_registry_per_uid(int dir_fd, uid_t owner) {
1205 _cleanup_close_ int registry_fd = -EBADF;
1206 int n = 0, r;
1207
1208 if (dir_fd < 0) {
1209 registry_fd = userns_registry_open_fd();
1210 if (registry_fd < 0)
1211 return registry_fd;
1212
1213 dir_fd = registry_fd;
1214 }
1215
1216 _cleanup_free_ char *uid_fn = NULL;
1217 if (asprintf(&uid_fn, "o" UID_FMT ".owns", owner) < 0)
1218 return log_oom_debug();
1219
1220 _cleanup_free_ DirectoryEntries *de = NULL;
1221
1222 r = readdir_all_at(dir_fd, uid_fn, RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE, &de);
1223 if (r == -ENOENT)
1224 return 0;
1225 if (r < 0)
1226 return log_debug_errno(r, "Failed to enumerate contents of '%s' sub-directory: %m", uid_fn);
1227
1228 FOREACH_ARRAY(i, de->entries, de->n_entries) {
1229 struct dirent *e = *i;
1230
1231 if (e->d_type != DT_REG)
1232 continue;
1233
1234 if (!startswith(e->d_name, "i") || !endswith(e->d_name, ".userns"))
1235 continue;
1236
1237 n++;
1238
1239 if (n == INT_MAX) /* overflow safety check, just in case */
1240 break;
1241 }
1242
1243 return n;
1244 }
1245
1246 int userns_registry_delegation_uid_exists(int dir_fd, uid_t start) {
1247 _cleanup_free_ char *fn = NULL;
1248
1249 assert(dir_fd >= 0);
1250
1251 if (!uid_is_valid(start))
1252 return -ENOENT;
1253
1254 if (start == 0)
1255 return true;
1256
1257 if (asprintf(&fn, "u" UID_FMT ".delegate", start) < 0)
1258 return -ENOMEM;
1259
1260 if (faccessat(dir_fd, fn, F_OK, AT_SYMLINK_NOFOLLOW) < 0)
1261 return errno == ENOENT ? false : -errno;
1262
1263 return true;
1264 }
1265
1266 int userns_registry_delegation_gid_exists(int dir_fd, gid_t start) {
1267 _cleanup_free_ char *fn = NULL;
1268
1269 assert(dir_fd >= 0);
1270
1271 if (!gid_is_valid(start))
1272 return -ENOENT;
1273
1274 if (start == 0)
1275 return true;
1276
1277 if (asprintf(&fn, "g" GID_FMT ".delegate", start) < 0)
1278 return -ENOMEM;
1279
1280 if (faccessat(dir_fd, fn, F_OK, AT_SYMLINK_NOFOLLOW) < 0)
1281 return errno == ENOENT ? false : -errno;
1282
1283 return true;
1284 }
1285
1286 static int userns_registry_load_delegation(int dir_fd, const char *filename, DelegatedUserNamespaceInfo *ret) {
1287
1288 static const sd_json_dispatch_field dispatch_table[] = {
1289 { "userns", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint64, offsetof(DelegatedUserNamespaceInfo, userns_inode), SD_JSON_MANDATORY },
1290 { "start", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uid_gid, offsetof(DelegatedUserNamespaceInfo, start_uid), SD_JSON_MANDATORY },
1291 { "startGid", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uid_gid, offsetof(DelegatedUserNamespaceInfo, start_gid), 0 },
1292 { "size", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint32, offsetof(DelegatedUserNamespaceInfo, size), SD_JSON_MANDATORY },
1293 { "ancestorUserns", SD_JSON_VARIANT_ARRAY, dispatch_ancestor_userns_array, 0, 0 },
1294 {}
1295 };
1296
1297 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
1298 _cleanup_close_ int registry_fd = -EBADF;
1299 int r;
1300
1301 if (dir_fd < 0) {
1302 registry_fd = userns_registry_open_fd();
1303 if (registry_fd < 0)
1304 return registry_fd;
1305
1306 dir_fd = registry_fd;
1307 }
1308
1309 r = sd_json_parse_file_at(/* f= */ NULL, dir_fd, filename, /* flags= */ 0, &v, /* reterr_line= */ NULL, /* reterr_column= */ NULL);
1310 if (r < 0)
1311 return r;
1312
1313 _cleanup_(delegated_userns_info_done) DelegatedUserNamespaceInfo data = DELEGATED_USER_NAMESPACE_INFO_NULL;
1314
1315 r = sd_json_dispatch(v, dispatch_table, /* flags= */ 0, &data);
1316 if (r < 0)
1317 return r;
1318
1319 if (data.userns_inode == 0)
1320 return -EBADMSG;
1321 if (data.size == 0)
1322 return -EBADMSG;
1323
1324 if (ret)
1325 *ret = TAKE_GENERIC(data, DelegatedUserNamespaceInfo, DELEGATED_USER_NAMESPACE_INFO_NULL);
1326
1327 return 0;
1328 }
1329
1330 int userns_registry_load_delegation_by_uid(int dir_fd, uid_t start, DelegatedUserNamespaceInfo *ret) {
1331 _cleanup_free_ char *fn = NULL;
1332 int r;
1333
1334 if (!uid_is_valid(start))
1335 return -ENOENT;
1336
1337 if (asprintf(&fn, "u" UID_FMT ".delegate", start) < 0)
1338 return -ENOMEM;
1339
1340 _cleanup_(delegated_userns_info_done) DelegatedUserNamespaceInfo data = DELEGATED_USER_NAMESPACE_INFO_NULL;
1341 r = userns_registry_load_delegation(dir_fd, fn, &data);
1342 if (r < 0)
1343 return r;
1344
1345 if (data.start_uid != start)
1346 return -EBADMSG;
1347
1348 if (ret)
1349 *ret = TAKE_GENERIC(data, DelegatedUserNamespaceInfo, DELEGATED_USER_NAMESPACE_INFO_NULL);
1350
1351 return 0;
1352 }
1353
1354 int userns_registry_load_delegation_by_gid(int dir_fd, gid_t start, DelegatedUserNamespaceInfo *ret) {
1355 _cleanup_free_ char *fn = NULL;
1356 int r;
1357
1358 if (!gid_is_valid(start))
1359 return -ENOENT;
1360
1361 if (asprintf(&fn, "g" UID_FMT ".delegate", start) < 0)
1362 return -ENOMEM;
1363
1364 _cleanup_(delegated_userns_info_done) DelegatedUserNamespaceInfo data = DELEGATED_USER_NAMESPACE_INFO_NULL;
1365 r = userns_registry_load_delegation(dir_fd, fn, &data);
1366 if (r < 0)
1367 return r;
1368
1369 if (data.start_gid != start)
1370 return -EBADMSG;
1371
1372 if (ret)
1373 *ret = TAKE_GENERIC(data, DelegatedUserNamespaceInfo, DELEGATED_USER_NAMESPACE_INFO_NULL);
1374
1375 return 0;
1376 }