Debian Codegraph @

src/nsresourced/nsresourcework.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <linux/if_tun.h>
5 #include <linux/magic.h>
6 #include <linux/nsfs.h>
7 #include <linux/veth.h>
8 #include <net/if.h>
9 #include <poll.h>
10 #include <sched.h>
11 #include <sys/eventfd.h>
12 #include <sys/ioctl.h>
13 #include <sys/stat.h>
14 #include <unistd.h>
15 #include <utmpx.h>
16
17 #include "sd-daemon.h"
18 #include "sd-event.h"
19 #include "sd-netlink.h"
20 #include "sd-varlink.h"
21
22 #include "argv-util.h"
23 #include "bus-polkit.h"
24 #include "env-util.h"
25 #include "errno-util.h"
26 #include "ether-addr-util.h"
27 #include "fd-util.h"
28 #include "fileio.h"
29 #include "format-util.h"
30 #include "hashmap.h"
31 #include "io-util.h"
32 #include "json-util.h"
33 #include "main-func.h"
34 #include "mountpoint-util.h"
35 #include "namespace-util.h"
36 #include "netlink-util.h"
37 #include "nsresource.h"
38 #include "pidref.h"
39 #include "process-util.h"
40 #include "random-util.h"
41 #include "siphash24.h"
42 #include "socket-util.h"
43 #include "stat-util.h"
44 #include "string-table.h"
45 #include "string-util.h"
46 #include "strv.h"
47 #include "time-util.h"
48 #include "uid-classification.h"
49 #include "uid-range.h"
50 #include "user-record.h"
51 #include "user-util.h"
52 #include "userdb.h"
53 #include "userns-registry.h"
54 #include "userns-restrict.h"
55 #include "varlink-io.systemd.NamespaceResource.h"
56 #include "varlink-io.systemd.UserDatabase.h"
57 #include "varlink-util.h"
58
59 #define ITERATIONS_MAX 64U
60 #define RUNTIME_MAX_USEC (5 * USEC_PER_MINUTE)
61 #define PRESSURE_SLEEP_TIME_USEC (50 * USEC_PER_MSEC)
62 #define LISTEN_IDLE_USEC (90 * USEC_PER_SEC)
63 #define USERNS_PER_UID 256
64
65 typedef struct Context {
66 Hashmap *polkit_registry;
67 struct userns_restrict_bpf *bpf;
68 } Context;
69
70 typedef struct LookupParameters {
71 const char *user_name;
72 const char *group_name;
73 union {
74 uid_t uid;
75 gid_t gid;
76 };
77 const char *service;
78 } LookupParameters;
79
80 typedef enum AllocateUserRangeType {
81 ALLOCATE_USER_RANGE_MANAGED,
82 ALLOCATE_USER_RANGE_SELF,
83 _ALLOCATE_USER_RANGE_TYPE_MAX,
84 _ALLOCATE_USER_RANGE_TYPE_INVALID = -EINVAL,
85 } AllocateUserRangeType;
86
87 static const char *const allocate_user_range_type_table[_ALLOCATE_USER_RANGE_TYPE_MAX] = {
88 [ALLOCATE_USER_RANGE_MANAGED] = "managed",
89 [ALLOCATE_USER_RANGE_SELF] = "self",
90 };
91
92 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(allocate_user_range_type, AllocateUserRangeType);
93 static JSON_DISPATCH_ENUM_DEFINE(dispatch_allocate_user_range_type, AllocateUserRangeType, allocate_user_range_type_from_string);
94
95 static int build_user_json(UserNamespaceInfo *userns_info, uid_t offset, sd_json_variant **ret) {
96 _cleanup_free_ char *name = NULL, *realname = NULL;
97 UserDisposition disposition;
98 int r;
99
100 assert(userns_info);
101 assert(offset < userns_info->size);
102
103 if (asprintf(&name, "ns-%s-" UID_FMT, userns_info->name, offset) < 0)
104 return -ENOMEM;
105
106 if (userns_info->size > 1) {
107 disposition = USER_CONTAINER;
108 r = asprintf(&realname, "User " UID_FMT " of Allocated Namespace %s", offset, userns_info->name);
109 } else {
110 disposition = USER_DYNAMIC;
111 r = asprintf(&realname, "Allocated Namespace %s", userns_info->name);
112 }
113 if (r < 0)
114 return -ENOMEM;
115
116 return sd_json_buildo(
117 ret,
118 SD_JSON_BUILD_PAIR_STRING("userName", name),
119 SD_JSON_BUILD_PAIR_UNSIGNED("uid", userns_info->start_uid + offset),
120 SD_JSON_BUILD_PAIR_UNSIGNED("gid", GID_NOBODY),
121 SD_JSON_BUILD_PAIR_STRING("realName", realname),
122 SD_JSON_BUILD_PAIR("homeDirectory", JSON_BUILD_CONST_STRING("/")),
123 SD_JSON_BUILD_PAIR_STRING("shell", NOLOGIN),
124 SD_JSON_BUILD_PAIR_BOOLEAN("locked", true),
125 SD_JSON_BUILD_PAIR("service", JSON_BUILD_CONST_STRING("io.systemd.NamespaceResource")),
126 SD_JSON_BUILD_PAIR_STRING("disposition", user_disposition_to_string(disposition)));
127 }
128
129 static int vl_method_get_user_record(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
130
131 static const sd_json_dispatch_field dispatch_table[] = {
132 { "uid", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid, offsetof(LookupParameters, uid), 0 },
133 { "userName", SD_JSON_VARIANT_STRING, json_dispatch_const_user_group_name, offsetof(LookupParameters, user_name), SD_JSON_RELAX },
134 { "service", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(LookupParameters, service), 0 },
135 {}
136 };
137
138 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
139 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
140 LookupParameters p = {
141 .uid = UID_INVALID,
142 };
143 uid_t offset;
144 int r;
145
146 assert(parameters);
147
148 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
149 if (r != 0)
150 return r;
151
152 if (!streq_ptr(p.service, "io.systemd.NamespaceResource"))
153 return sd_varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
154
155 if (p.user_name) {
156 _cleanup_free_ char *n = NULL;
157 const char *e, *f;
158
159 e = startswith(p.user_name, "ns-");
160 if (!e)
161 goto not_found;
162
163 f = strrchr(e, '-');
164 if (!f)
165 goto not_found;
166
167 if (parse_uid(f+1, &offset) < 0)
168 goto not_found;
169
170 n = strndup(e, f - e);
171 if (!n)
172 return log_oom();
173
174 r = userns_registry_load_by_name(
175 /* dir_fd= */ -EBADF,
176 n,
177 &userns_info);
178 if (r == -ENOENT)
179 goto not_found;
180 if (r < 0)
181 return r;
182
183 if (offset >= userns_info->size) /* Outside of range? */
184 goto not_found;
185
186 if (uid_is_valid(p.uid) && p.uid != userns_info->start_uid + offset)
187 return sd_varlink_error(link, "io.systemd.UserDatabase.ConflictingRecordFound", NULL);
188
189 } else if (uid_is_valid(p.uid)) {
190 uid_t start, uidmask;
191
192 if (uid_is_container(p.uid))
193 uidmask = (uid_t) UINT32_C(0xFFFF0000);
194 else if (uid_is_dynamic(p.uid))
195 uidmask = (uid_t) UINT32_C(0xFFFFFFFF);
196 else
197 goto not_found;
198
199 start = p.uid & uidmask;
200 offset = p.uid - start;
201
202 r = userns_registry_load_by_start_uid(
203 /* dir_fd= */ -EBADF,
204 start,
205 &userns_info);
206 if (r == -ENOENT)
207 goto not_found;
208 if (r < 0)
209 return r;
210
211 if (offset >= userns_info->size) /* Outside of range? */
212 goto not_found;
213 } else
214 return sd_varlink_error(link, "io.systemd.UserDatabase.EnumerationNotSupported", NULL);
215
216 r = build_user_json(userns_info, offset, &v);
217 if (r < 0)
218 return r;
219
220 return sd_varlink_replybo(link, SD_JSON_BUILD_PAIR_VARIANT("record", v));
221
222 not_found:
223 return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
224 }
225
226 static int build_group_json(UserNamespaceInfo *userns_info, gid_t offset, sd_json_variant **ret) {
227 _cleanup_free_ char *name = NULL, *description = NULL;
228 UserDisposition disposition;
229 int r;
230
231 assert(userns_info);
232 assert(offset < userns_info->size);
233
234 if (asprintf(&name, "ns-%s-" GID_FMT, userns_info->name, offset) < 0)
235 return -ENOMEM;
236
237 if (userns_info->size > 1) {
238 disposition = USER_CONTAINER;
239 r = asprintf(&description, "Group " GID_FMT " of Allocated Namespace %s", offset, userns_info->name);
240 } else {
241 disposition = USER_DYNAMIC;
242 r = asprintf(&description, "Allocated Namespace %s", userns_info->name);
243 }
244 if (r < 0)
245 return -ENOMEM;
246
247 return sd_json_buildo(
248 ret,
249 SD_JSON_BUILD_PAIR_STRING("groupName", name),
250 SD_JSON_BUILD_PAIR_UNSIGNED("gid", userns_info->start_gid + offset),
251 SD_JSON_BUILD_PAIR_STRING("description", description),
252 SD_JSON_BUILD_PAIR("service", JSON_BUILD_CONST_STRING("io.systemd.NamespaceResource")),
253 SD_JSON_BUILD_PAIR_STRING("disposition", user_disposition_to_string(disposition)));
254 }
255
256 static int vl_method_get_group_record(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
257
258 static const sd_json_dispatch_field dispatch_table[] = {
259 { "gid", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid, offsetof(LookupParameters, gid), 0 },
260 { "groupName", SD_JSON_VARIANT_STRING, json_dispatch_const_user_group_name, offsetof(LookupParameters, group_name), SD_JSON_RELAX },
261 { "service", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(LookupParameters, service), 0 },
262 {}
263 };
264
265 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
266 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
267 LookupParameters p = {
268 .gid = GID_INVALID,
269 };
270 gid_t offset;
271 int r;
272
273 assert(parameters);
274
275 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
276 if (r != 0)
277 return r;
278
279 if (!streq_ptr(p.service, "io.systemd.NamespaceResource"))
280 return sd_varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
281
282 if (p.group_name) {
283 _cleanup_free_ char *n = NULL;
284 const char *e, *f;
285
286 e = startswith(p.group_name, "ns-");
287 if (!e)
288 goto not_found;
289
290 f = strrchr(e, '-');
291 if (!f)
292 goto not_found;
293
294 if (parse_gid(f+1, &offset) < 0)
295 goto not_found;
296
297 n = strndup(e, f - e);
298 if (!n)
299 return log_oom();
300
301 r = userns_registry_load_by_name(
302 /* dir_fd= */ -EBADF,
303 n,
304 &userns_info);
305 if (r == -ENOENT)
306 goto not_found;
307 if (r < 0)
308 return r;
309
310 if (offset >= userns_info->size) /* Outside of range? */
311 goto not_found;
312
313 if (gid_is_valid(p.gid) && p.gid != userns_info->start_gid + offset)
314 return sd_varlink_error(link, "io.systemd.UserDatabase.ConflictingRecordFound", NULL);
315
316 } else if (gid_is_valid(p.gid)) {
317 gid_t start, gidmask;
318
319 if (gid_is_container(p.gid))
320 gidmask = (gid_t) UINT32_C(0xFFFF0000);
321 else if (gid_is_dynamic(p.gid))
322 gidmask = (gid_t) UINT32_C(0xFFFFFFFF);
323 else
324 goto not_found;
325
326 start = p.gid & gidmask;
327 offset = p.gid - start;
328
329 r = userns_registry_load_by_start_gid(
330 /* dir_fd= */ -EBADF,
331 start,
332 &userns_info);
333 if (r == -ENOENT)
334 goto not_found;
335 if (r < 0)
336 return r;
337
338 if (offset >= userns_info->size) /* Outside of range? */
339 goto not_found;
340 } else
341 return sd_varlink_error(link, "io.systemd.UserDatabase.EnumerationNotSupported", NULL);
342
343 r = build_group_json(userns_info, offset, &v);
344 if (r < 0)
345 return r;
346
347 return sd_varlink_replybo(link, SD_JSON_BUILD_PAIR_VARIANT("record", v));
348
349 not_found:
350 return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
351 }
352
353 static int vl_method_get_memberships(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
354 static const sd_json_dispatch_field dispatch_table[] = {
355 { "userName", SD_JSON_VARIANT_STRING, json_dispatch_const_user_group_name, offsetof(LookupParameters, user_name), SD_JSON_RELAX },
356 { "groupName", SD_JSON_VARIANT_STRING, json_dispatch_const_user_group_name, offsetof(LookupParameters, group_name), SD_JSON_RELAX },
357 { "service", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(LookupParameters, service), 0 },
358 {}
359 };
360
361 LookupParameters p = {};
362 int r;
363
364 assert(parameters);
365
366 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
367 if (r != 0)
368 return r;
369
370 if (!streq_ptr(p.service, "io.systemd.NamespaceResource"))
371 return sd_varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
372
373 /* We don't support auxiliary groups for namespace allocations */
374 return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
375 }
376
377 static int registry_range_is_available(
378 struct userns_restrict_bpf *bpf,
379 int registry_dir_fd,
380 uid_t candidate,
381 bool gid) {
382
383 _cleanup_(userns_info_freep) UserNamespaceInfo *owner = NULL;
384 int r;
385
386 assert(registry_dir_fd >= 0);
387
388 /* Checks whether the (UID or GID) range starting at candidate is free to allocate as a fresh
389 * transient range. If an existing registry entry claims it but its owning namespace has since
390 * died — without a BPF death event reaping it yet — we reclaim it on the spot and treat the range
391 * as available. Unlike delegations, transient registrations have no ancestor chain, so a single
392 * reap suffices. */
393
394 r = gid ? userns_registry_gid_exists(registry_dir_fd, (gid_t) candidate)
395 : userns_registry_uid_exists(registry_dir_fd, candidate);
396 if (r < 0)
397 return r;
398 if (r == 0)
399 return true; /* No registry entry for this range → available. */
400
401 r = gid ? userns_registry_load_by_start_gid(registry_dir_fd, (gid_t) candidate, &owner)
402 : userns_registry_load_by_start_uid(registry_dir_fd, candidate, &owner);
403 if (r == -ENOENT)
404 return true; /* Raced away between the existence check and the load → available. */
405 if (r < 0)
406 return r;
407
408 r = userns_registry_reap_if_dead(bpf, registry_dir_fd, owner->userns_inode);
409 if (r < 0)
410 return r;
411 if (r == USERNS_REAP_RELEASED)
412 return true; /* Owner was dead and reaped → range is now free. */
413
414 /* Owner is alive or its liveness couldn't be determined → we can't reclaim it, so the range
415 * is taken. */
416 log_debug("%s" UID_FMT " unavailable: already registered in userns registry.",
417 gid ? "GID " : "UID ", candidate);
418 return false;
419 }
420
421 static int delegation_range_is_available(
422 struct userns_restrict_bpf *bpf,
423 int registry_dir_fd,
424 uid_t candidate,
425 uint64_t parent_userns_inode,
426 bool gid) {
427
428 int r;
429
430 assert(registry_dir_fd >= 0);
431
432 /* Checks whether the (UID or GID) range starting at candidate is free to allocate as far as
433 * the delegation registry is concerned. A delegated range is available only if it's owned by
434 * the requesting parent user namespace (which may then sub-allocate within it). If it's owned
435 * by another namespace that has since died — without a BPF death event reaping it yet — we reclaim
436 * it on the spot, which restores the range to its ancestor (possibly the parent), and
437 * re-evaluate. This walks a chain of dead ancestors until it reaches a live owner, the
438 * requesting parent, or a fully freed range. */
439
440 r = gid ? userns_registry_delegation_gid_exists(registry_dir_fd, (gid_t) candidate)
441 : userns_registry_delegation_uid_exists(registry_dir_fd, candidate);
442 if (r < 0)
443 return r;
444 if (r == 0)
445 return true; /* No delegation for this range → available. */
446
447 for (;;) {
448 _cleanup_(delegated_userns_info_done) DelegatedUserNamespaceInfo delegation = DELEGATED_USER_NAMESPACE_INFO_NULL;
449
450 r = gid ? userns_registry_load_delegation_by_gid(registry_dir_fd, (gid_t) candidate, &delegation)
451 : userns_registry_load_delegation_by_uid(registry_dir_fd, candidate, &delegation);
452 if (r == -ENOENT)
453 return true; /* Delegation removed while reaping (no ancestor left) → fully free. */
454 if (r < 0)
455 return r;
456
457 if (delegation.userns_inode == parent_userns_inode) {
458 /* The parent userns owns this delegation, so the range is available for nested
459 * allocation. */
460 log_debug("%s" UID_FMT " is delegated by parent userns inode %" PRIu64 ", available for nested allocation.",
461 gid ? "GID " : "UID ", candidate, parent_userns_inode);
462 return true;
463 }
464
465 /* Owned by some other namespace. If that namespace is dead, reclaim it (restoring the
466 * range to its ancestor) and loop to re-evaluate; otherwise the range is genuinely
467 * taken. */
468 r = userns_registry_reap_if_dead(bpf, registry_dir_fd, delegation.userns_inode);
469 if (r < 0)
470 return r;
471 if (r == USERNS_REAP_RELEASED)
472 continue; /* Reaped a dead owner; re-evaluate the now-restored delegation. */
473
474 /* Owner is alive, or its liveness couldn't be determined (no recorded id, or a dead
475 * ancestor that an earlier reap popped into ownership but left no registry entry to
476 * drive a further restore). We can't reclaim the range here — and mustn't loop, since
477 * re-reaping would not make progress — so treat it as taken. */
478 log_debug("%s" UID_FMT " unavailable: delegated to userns inode %" PRIu64 " that can't be reclaimed (parent is %" PRIu64 ").",
479 gid ? "GID " : "UID ", candidate, delegation.userns_inode, parent_userns_inode);
480 return false;
481 }
482 }
483
484 static int uid_is_available(
485 struct userns_restrict_bpf *bpf,
486 int registry_dir_fd,
487 uid_t candidate,
488 int parent_userns_fd) {
489
490 int r;
491
492 assert(registry_dir_fd >= 0);
493
494 log_debug("Checking if UID " UID_FMT " is available.", candidate);
495
496 uint64_t parent_userns_inode = 0;
497 struct stat parent_st;
498 if (fstat(parent_userns_fd, &parent_st) < 0)
499 return log_debug_errno(errno, "Failed to fstat parent user namespace: %m");
500 parent_userns_inode = parent_st.st_ino;
501
502 /* Check whether an existing transient registration claims this range; a dead owner is reclaimed
503 * inline so its range doesn't stay blocked. The UID and GID are checked separately as either
504 * can exist independently. */
505 r = registry_range_is_available(bpf, registry_dir_fd, candidate, /* gid= */ false);
506 if (r < 0)
507 return r;
508 if (r == 0)
509 return false;
510
511 r = registry_range_is_available(bpf, registry_dir_fd, candidate, /* gid= */ true);
512 if (r < 0)
513 return r;
514 if (r == 0)
515 return false;
516
517 /* Also check delegation files. A delegated range is only available for nested allocation when
518 * the requesting parent owns it; dead owners are reclaimed inline so their ranges don't stay
519 * blocked. We check the UID and GID delegations separately as either can exist independently. */
520 r = delegation_range_is_available(bpf, registry_dir_fd, candidate, parent_userns_inode, /* gid= */ false);
521 if (r < 0)
522 return r;
523 if (r == 0)
524 return false;
525
526 r = delegation_range_is_available(bpf, registry_dir_fd, candidate, parent_userns_inode, /* gid= */ true);
527 if (r < 0)
528 return r;
529 if (r == 0)
530 return false;
531
532 r = is_our_namespace(parent_userns_fd, NAMESPACE_USER);
533 if (r < 0)
534 return log_debug_errno(r, "Failed to check if parent user namespace is our user namespace: %m");
535
536 if (r > 0) {
537 /* Only check userdb if we're allocating from our current user namespace. userdb won't be
538 * to tell us anything on whether UIDs/GIDs in another user namespace are in use or not. On
539 * top of that, for nspawn containers registered with machined's userdb implementation, it
540 * would tell us that any ranges delegated to the container are in use (which is true in the
541 * nsresourced user namespace, but not in the nspawn user namespace). */
542
543 r = userdb_by_uid(candidate, /* match= */ NULL, USERDB_AVOID_MULTIPLEXER, /* ret= */ NULL);
544 if (r >= 0) {
545 log_debug("UID " UID_FMT " unavailable: known to userdb.", candidate);
546 return false;
547 }
548 if (r != -ESRCH)
549 return r;
550
551 r = groupdb_by_gid(candidate, /* match= */ NULL, USERDB_AVOID_MULTIPLEXER, /* ret= */ NULL);
552 if (r >= 0) {
553 log_debug("UID " UID_FMT " unavailable: GID known to groupdb.", candidate);
554 return false;
555 }
556 if (r != -ESRCH)
557 return r;
558 }
559
560 log_debug("UID " UID_FMT " is available.", candidate);
561
562 return true;
563 }
564
565 static int name_is_available(
566 int registry_dir_fd,
567 const char *name) {
568
569 _cleanup_free_ char *user_name = NULL;
570 int r;
571
572 assert(registry_dir_fd >= 0);
573 assert(name);
574
575 r = userns_registry_name_exists(registry_dir_fd, name);
576 if (r < 0)
577 return r;
578 if (r > 0)
579 return false;
580
581 user_name = strjoin("ns-", name, "-0");
582 if (!user_name)
583 return -ENOMEM;
584
585 r = userdb_by_name(user_name, /* match= */ NULL, USERDB_AVOID_MULTIPLEXER, /* ret= */ NULL);
586 if (r >= 0)
587 return false;
588 if (r != -ESRCH)
589 return r;
590
591 r = groupdb_by_name(user_name, /* match= */ NULL, USERDB_AVOID_MULTIPLEXER, /* ret= */ NULL);
592 if (r >= 0)
593 return false;
594 if (r != -ESRCH)
595 return r;
596
597 log_debug("Namespace name '%s' is available.", name);
598
599 return true;
600 }
601
602 static int inode_slot_is_available(
603 int registry_dir_fd,
604 int userns_fd,
605 struct userns_restrict_bpf *bpf,
606 uint64_t inode) {
607
608 _cleanup_(userns_info_freep) UserNamespaceInfo *existing = NULL;
609 int r;
610
611 assert(registry_dir_fd >= 0);
612 assert(userns_fd >= 0);
613 assert(inode != 0);
614
615 /* Returns true if the registry has no entry for this inode (after cleaning up any stale
616 * leftover from a previously-registered namespace whose inode was recycled by the kernel),
617 * false if a live registration already occupies the slot, negative on error. */
618
619 r = userns_registry_load_by_userns_inode(registry_dir_fd, inode, &existing);
620 if (r == -ENOENT)
621 return true;
622 if (r < 0)
623 return log_debug_errno(r, "Failed to load existing registry entry: %m");
624
625 r = userns_info_verify_fd(userns_fd, existing);
626 if (r >= 0)
627 return false;
628 if (r != -ESTALE)
629 return log_debug_errno(r, "Failed to verify user namespace identity: %m");
630
631 log_debug("Inode %" PRIu64 " was reused by the kernel; cleaning up stale registry entry for namespace id %" PRIu64 ".",
632 inode, existing->userns_id);
633 userns_registry_release_by_info(bpf, registry_dir_fd, existing);
634 return true;
635 }
636
637 static int allocate_one(
638 struct userns_restrict_bpf *bpf,
639 int registry_dir_fd,
640 const char *name,
641 uint32_t size,
642 int parent_userns_fd,
643 UIDRange *candidates,
644 uid_t *ret_candidate) {
645
646 static const uint8_t hash_key[16] = {
647 0xd4, 0xd7, 0x33, 0xa7, 0x4d, 0xd3, 0x42, 0xcd,
648 0xaa, 0xe9, 0x45, 0xd0, 0xfb, 0xec, 0x79, 0xee,
649 };
650 _cleanup_(uid_range_freep) UIDRange *copy = NULL;
651 uid_t candidate, uidmin, uidmax;
652 unsigned n_tries = 100;
653 size_t idx;
654 int r;
655
656 assert(registry_dir_fd >= 0);
657 assert(candidates);
658 assert(ret_candidate);
659
660 switch (size) {
661
662 case NSRESOURCE_UIDS_64K:
663 uidmin = CONTAINER_UID_BASE_MIN;
664 uidmax = CONTAINER_UID_BASE_MAX;
665 break;
666
667 case NSRESOURCE_UIDS_1:
668 uidmin = DYNAMIC_UID_MIN;
669 uidmax = DYNAMIC_UID_MAX;
670 break;
671
672 default:
673 assert_not_reached();
674 }
675
676 /* Make a copy of candidates that we can modify for the selection algorithm */
677 r = uid_range_copy(candidates, &copy);
678 if (r < 0)
679 return log_debug_errno(r, "Failed to copy UID range: %m");
680
681 /* Clip the copy with the valid UID range for this allocation size */
682 r = uid_range_clip(copy, uidmin, uidmax);
683 if (r < 0)
684 return log_debug_errno(r, "Failed to intersect UID range: %m");
685
686 /* Partition entries into entries of exactly the right size */
687 r = uid_range_partition(copy, size);
688 if (r < 0)
689 return log_debug_errno(r, "Failed to partition UID ranges: %m");
690
691 if (uid_range_is_empty(copy))
692 return log_debug_errno(SYNTHETIC_ERRNO(EHOSTDOWN), "Relevant UID range not delegated, can't allocate.");
693
694 log_debug("Partitioned UID range into %zu entries of size %" PRIu32, copy->n_entries, size);
695
696 /* Start from a hash of the input name if we have one, use random values afterwards. */
697 idx = name ? siphash24_string(name, hash_key) : random_u32();
698 for (;; idx = random_u32()) {
699 if (uid_range_is_empty(copy))
700 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "All candidate UIDs already taken.");
701
702 if (--n_tries <= 0)
703 return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "Try limit hit, no UIDs available.");
704
705 idx %= copy->n_entries;
706
707 candidate = copy->entries[idx].start;
708
709 /* We only check the base UID for each range. Pass the parent userns inode so that
710 * allocating from a delegated range owned by the parent is allowed. */
711 r = uid_is_available(bpf, registry_dir_fd, candidate, parent_userns_fd);
712 if (r < 0)
713 return log_debug_errno(r, "Can't determine if UID range " UID_FMT " is available: %m", candidate);
714 if (r > 0)
715 break;
716
717 log_debug("UID range " UID_FMT " already taken.", candidate);
718
719 /* Remove this unavailable range from candidates so we don't try it again */
720 r = uid_range_remove(copy, candidate, size);
721 if (r < 0)
722 return log_debug_errno(r, "Failed to remove unavailable range from candidates: %m");
723 }
724
725 /* Remove the allocated range from the original candidates */
726 r = uid_range_remove(candidates, candidate, size);
727 if (r < 0)
728 return log_debug_errno(r, "Failed to remove allocated range from candidates: %m");
729
730 *ret_candidate = candidate;
731
732 log_debug("Allocating UID range " UID_FMT "…" UID_FMT, candidate, candidate + size - 1);
733
734 return 0;
735 }
736
737 static int allocate_now(
738 int registry_dir_fd,
739 int userns_fd,
740 int parent_userns_fd,
741 struct userns_restrict_bpf *bpf,
742 UserNamespaceInfo *info,
743 int *ret_lock_fd) {
744
745 _cleanup_(uid_range_freep) UIDRange *candidates = NULL;
746 uid_t candidate;
747 int r;
748
749 /* Returns the following error codes:
750 *
751 * EBUSY → all UID candidates we checked are already taken
752 * EEXIST → the name for the userns already exists
753 * EDEADLK → the userns is already registered in the registry
754 */
755
756 assert(registry_dir_fd >= 0);
757 assert(userns_fd >= 0);
758 assert(info);
759
760 r = uid_range_load_userns_by_fd(parent_userns_fd, UID_RANGE_USERNS_INSIDE, &candidates);
761 if (r < 0)
762 return log_debug_errno(r, "Failed to read userns UID range: %m");
763
764 log_debug("Parent user namespace exposes %zu UID range(s) inside:", uid_range_entries(candidates));
765 if (DEBUG_LOGGING)
766 FOREACH_ARRAY(e, candidates->entries, candidates->n_entries)
767 log_debug(" " UID_FMT "…" UID_FMT " (size " UID_FMT ")",
768 e->start, e->start + e->nr - 1, e->nr);
769
770 _cleanup_close_ int lock_fd = -EBADF;
771 lock_fd = userns_registry_lock(registry_dir_fd);
772 if (lock_fd < 0)
773 return log_debug_errno(lock_fd, "Failed to open nsresource registry lock file: %m");
774
775 /* Enforce limit on user namespaces per UID */
776 r = userns_registry_per_uid(registry_dir_fd, info->owner);
777 if (r < 0)
778 return log_debug_errno(r, "Failed to determine number of currently registered user namespaces per UID " UID_FMT ": %m", info->owner);
779 if (r >= USERNS_PER_UID)
780 return log_debug_errno(SYNTHETIC_ERRNO(EUSERS), "User already registered %i user namespaces, refusing.", r);
781
782 r = inode_slot_is_available(registry_dir_fd, userns_fd, bpf, info->userns_inode);
783 if (r < 0)
784 return r;
785 if (r == 0)
786 return -EDEADLK;
787
788 r = name_is_available(registry_dir_fd, info->name);
789 if (r < 0)
790 return r;
791 if (r == 0)
792 return -EEXIST;
793
794 /* If the source UID/GID are already set we're doing a "self" user namespace and don't need to
795 * allocate a transient range. */
796 if (!uid_is_valid(info->start_uid) && !gid_is_valid(info->start_gid)) {
797 r = allocate_one(
798 bpf,
799 registry_dir_fd,
800 info->name, info->size,
801 parent_userns_fd,
802 candidates,
803 &candidate);
804 if (r < 0)
805 return r;
806
807 info->start_uid = candidate;
808 info->start_gid = (gid_t) candidate;
809 }
810
811 /* Now allocate delegated ranges if requested */
812 if (info->n_delegates > 0) {
813 assert(info->delegates);
814
815 FOREACH_ARRAY(delegate, info->delegates, info->n_delegates) {
816 r = allocate_one(
817 bpf,
818 registry_dir_fd,
819 /* name= */ NULL,
820 delegate->size,
821 parent_userns_fd,
822 candidates,
823 &candidate);
824 if (r < 0)
825 return r;
826
827 delegate->userns_inode = info->userns_inode;
828 delegate->start_uid = candidate;
829 delegate->start_gid = (gid_t) candidate;
830 }
831 }
832
833 if (ret_lock_fd)
834 *ret_lock_fd = TAKE_FD(lock_fd);
835
836 return 0;
837 }
838
839 static int write_userns_mappings(PidRef *pidref, const char *uidmap, const char *gidmap) {
840 const char *pmap;
841 int r;
842
843 assert(pidref);
844 assert(uidmap);
845 assert(gidmap);
846
847 pmap = procfs_file_alloca(pidref->pid, "uid_map");
848 r = write_string_file(pmap, uidmap, /* flags= */ 0);
849 if (r < 0)
850 return log_error_errno(r, "Failed to write 'uid_map' file of user namespace: %m");
851
852 pmap = procfs_file_alloca(pidref->pid, "gid_map");
853 r = write_string_file(pmap, gidmap, /* flags= */ 0);
854 if (r < 0)
855 return log_error_errno(r, "Failed to write 'gid_map' file of user namespace: %m");
856
857 return 0;
858 }
859
860 static int write_userns(
861 int userns_fd,
862 int parent_userns_fd,
863 const UserNamespaceInfo *userns_info,
864 bool map_foreign) {
865
866 _cleanup_(pidref_done_sigkill_wait) PidRef pidref = PIDREF_NULL;
867 _cleanup_close_ int efd = -EBADF;
868 uint64_t u;
869 int r;
870
871 assert(userns_fd >= 0);
872 assert(parent_userns_fd >= 0);
873 assert(userns_info);
874 assert(uid_is_valid(userns_info->target_uid));
875 assert(uid_is_valid(userns_info->start_uid));
876 assert(gid_is_valid(userns_info->target_gid));
877 assert(gid_is_valid(userns_info->start_gid));
878 assert(userns_info->size > 0);
879 assert(userns_info->size <= UINT32_MAX - userns_info->start_uid);
880 assert(userns_info->size <= UINT32_MAX - userns_info->start_gid);
881
882 efd = eventfd(0, EFD_CLOEXEC);
883 if (efd < 0)
884 return log_error_errno(errno, "Failed to allocate eventfd(): %m");
885
886 r = pidref_safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_LOG, &pidref);
887 if (r < 0)
888 return r;
889 if (r == 0) {
890 /* child */
891
892 if (setns(userns_fd, CLONE_NEWUSER) < 0) {
893 log_error_errno(errno, "Failed to join user namespace: %m");
894 goto child_fail;
895 }
896
897 if (eventfd_write(efd, 1) < 0) {
898 log_error_errno(errno, "Failed to ping event fd: %m");
899 goto child_fail;
900 }
901
902 freeze();
903
904 child_fail:
905 _exit(EXIT_FAILURE);
906 }
907
908 /* Wait until child joined the user namespace */
909 if (eventfd_read(efd, &u) < 0)
910 return log_error_errno(errno, "Failed to wait for event fd: %m");
911
912 /* Now write mapping */
913
914 _cleanup_(uid_range_freep) UIDRange *outside_range = NULL;
915 r = uid_range_load_userns_by_fd_full(parent_userns_fd, UID_RANGE_USERNS_OUTSIDE, /* coalesce= */ false, &outside_range);
916 if (r < 0)
917 return log_debug_errno(r, "Failed to read userns UID range: %m");
918
919 _cleanup_(uid_range_freep) UIDRange *inside_range = NULL;
920 r = uid_range_load_userns_by_fd_full(parent_userns_fd, UID_RANGE_USERNS_INSIDE, /* coalesce= */ false, &inside_range);
921 if (r < 0)
922 return log_debug_errno(r, "Failed to read userns UID range: %m");
923
924 uid_t start_uid;
925 r = uid_range_translate(outside_range, inside_range, userns_info->start_uid, &start_uid);
926 if (r < 0)
927 return log_debug_errno(r, "Failed to translate UID "UID_FMT" to parent userns: %m", userns_info->start_uid);
928
929 /* Let's enforce that the transient UID/GID ranges are mapped 1:1 in the parent user namespace, to
930 * avoid any weird mapping shenanigans that might happen otherwise. */
931
932 if (uid_is_transient(userns_info->start_uid) && start_uid != userns_info->start_uid)
933 return log_debug_errno(
934 SYNTHETIC_ERRNO(ERANGE),
935 "Transient UID range not mapped 1:1 in parent userns ("UID_FMT" -> "UID_FMT")",
936 userns_info->start_uid, start_uid);
937
938 /* Build uid_map content: primary mapping + delegated mappings (1:1) */
939 _cleanup_free_ char *uidmap = NULL;
940 if (asprintf(&uidmap, UID_FMT " " UID_FMT " %" PRIu32 "\n",
941 userns_info->target_uid, start_uid, userns_info->size) < 0)
942 return log_oom();
943
944 log_debug("UID mapping: " UID_FMT " " UID_FMT " %" PRIu32,
945 userns_info->target_uid, userns_info->start_uid, userns_info->size);
946
947 FOREACH_ARRAY(delegate, userns_info->delegates, userns_info->n_delegates) {
948 r = uid_range_translate(outside_range, inside_range, delegate->start_uid, &start_uid);
949 if (r < 0)
950 return log_debug_errno(r, "Failed to translate UID "UID_FMT" to parent userns: %m", userns_info->start_uid);
951
952 if (start_uid != delegate->start_uid)
953 return log_debug_errno(
954 SYNTHETIC_ERRNO(ERANGE),
955 "Delegated transient UID range not mapped 1:1 in parent userns ("UID_FMT" -> "UID_FMT")",
956 delegate->start_uid, start_uid);
957
958 if (strextendf(&uidmap,
959 UID_FMT " " UID_FMT " %" PRIu32 "\n",
960 delegate->start_uid,
961 start_uid,
962 delegate->size) < 0)
963 return log_oom();
964
965 log_debug("UID mapping: " UID_FMT " " UID_FMT " %" PRIu32,
966 delegate->start_uid, start_uid, delegate->size);
967 }
968
969 if (map_foreign) {
970 r = uid_range_translate(outside_range, inside_range, FOREIGN_UID_MIN, &start_uid);
971 if (r < 0)
972 return log_debug_errno(r, "Failed to translate UID "UID_FMT" to parent userns: %m", FOREIGN_UID_MIN);
973
974 if (start_uid != FOREIGN_UID_MIN)
975 return log_debug_errno(
976 SYNTHETIC_ERRNO(ERANGE),
977 "Foreign UID range not mapped 1:1 in parent userns ("UID_FMT" -> "UID_FMT")",
978 FOREIGN_UID_MIN, start_uid);
979
980 if (strextendf(&uidmap, UID_FMT " " UID_FMT " %" PRIu32 "\n",
981 FOREIGN_UID_MIN, start_uid, NSRESOURCE_UIDS_64K) < 0)
982 return log_oom();
983 }
984
985 outside_range = uid_range_free(outside_range);
986 inside_range = uid_range_free(inside_range);
987
988 r = uid_range_load_userns_by_fd_full(parent_userns_fd, GID_RANGE_USERNS_OUTSIDE, /* coalesce= */ false, &outside_range);
989 if (r < 0)
990 return log_debug_errno(r, "Failed to read userns GID range: %m");
991
992 r = uid_range_load_userns_by_fd_full(parent_userns_fd, GID_RANGE_USERNS_INSIDE, /* coalesce= */ false, &inside_range);
993 if (r < 0)
994 return log_debug_errno(r, "Failed to read userns GID range: %m");
995
996 gid_t start_gid;
997 r = uid_range_translate(outside_range, inside_range, userns_info->start_gid, &start_gid);
998 if (r < 0)
999 return log_debug_errno(r, "Failed to translate GID "GID_FMT" to parent userns: %m", userns_info->start_gid);
1000
1001 if (gid_is_transient(userns_info->start_gid) && start_gid != userns_info->start_gid)
1002 return log_debug_errno(
1003 SYNTHETIC_ERRNO(ERANGE),
1004 "Transient GID range not mapped 1:1 in parent userns ("GID_FMT" -> "GID_FMT")",
1005 userns_info->start_gid, start_gid);
1006
1007 _cleanup_free_ char *gidmap = NULL;
1008 if (asprintf(&gidmap, GID_FMT " " GID_FMT " %" PRIu32 "\n",
1009 userns_info->target_gid, start_gid, userns_info->size) < 0)
1010 return log_oom();
1011
1012 log_debug("GID mapping: " GID_FMT " " GID_FMT " %" PRIu32,
1013 userns_info->target_gid, userns_info->start_gid, userns_info->size);
1014
1015 FOREACH_ARRAY(delegate, userns_info->delegates, userns_info->n_delegates) {
1016 r = uid_range_translate(outside_range, inside_range, delegate->start_gid, &start_gid);
1017 if (r < 0)
1018 return log_debug_errno(r, "Failed to translate GID "GID_FMT" to parent userns: %m", userns_info->start_gid);
1019
1020 if (start_gid != delegate->start_gid)
1021 return log_debug_errno(
1022 SYNTHETIC_ERRNO(ERANGE),
1023 "Delegated transient GID range not mapped 1:1 in parent userns ("GID_FMT" -> "GID_FMT")",
1024 delegate->start_gid, start_gid);
1025
1026 /* Delegated ranges are mapped 1:1 (inside GID == outside GID) */
1027 if (strextendf(&gidmap, GID_FMT " " GID_FMT " %" PRIu32 "\n",
1028 delegate->start_gid,
1029 start_gid,
1030 delegate->size) < 0)
1031 return log_oom();
1032
1033 log_debug("GID mapping: " GID_FMT " " GID_FMT " %" PRIu32,
1034 delegate->start_gid, start_gid, delegate->size);
1035 }
1036
1037 if (map_foreign) {
1038 r = uid_range_translate(outside_range, inside_range, FOREIGN_UID_MIN, &start_gid);
1039 if (r < 0)
1040 return log_debug_errno(r, "Failed to translate GID "GID_FMT" to parent userns: %m", FOREIGN_UID_MIN);
1041
1042 if (start_gid != FOREIGN_UID_MIN)
1043 return log_debug_errno(
1044 SYNTHETIC_ERRNO(ERANGE),
1045 "Foreign GID range not mapped 1:1 in parent userns ("GID_FMT" -> "GID_FMT")",
1046 FOREIGN_UID_MIN, start_gid);
1047
1048 if (strextendf(&gidmap, GID_FMT " " GID_FMT " %" PRIu32 "\n",
1049 FOREIGN_UID_MIN, start_gid, NSRESOURCE_UIDS_64K) < 0)
1050 return log_oom();
1051 }
1052
1053 r = is_our_namespace(parent_userns_fd, NAMESPACE_USER);
1054 if (r < 0)
1055 return log_debug_errno(r, "Failed to check if parent user namespace refers to our own user namespace: %m");
1056 if (r > 0)
1057 return write_userns_mappings(&pidref, uidmap, gidmap);
1058
1059 /* The kernel is paranoid that the uid_map and gid_map files are written either from the user
1060 * namespace itself or its parent user namespace, so we have to join the parent user namespace to
1061 * write the files. */
1062
1063 r = pidref_safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_LOG|FORK_WAIT, /* ret= */ NULL);
1064 if (r < 0)
1065 return r;
1066 if (r == 0) {
1067 if (setns(parent_userns_fd, CLONE_NEWUSER) < 0) {
1068 log_error_errno(errno, "Failed to join parent user namespace: %m");
1069 _exit(EXIT_FAILURE);
1070 }
1071
1072 r = write_userns_mappings(&pidref, uidmap, gidmap);
1073 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
1074 }
1075
1076 /* We are done! */
1077
1078 log_debug("Successfully configured user namespace.");
1079 return 0;
1080 }
1081
1082 static int test_userns_api_support(sd_varlink *link) {
1083 int r;
1084
1085 assert(link);
1086
1087 /* We only expose the userns API if our manager daemon told us this OK to do. It will set this
1088 * boolean only if it managed to set up BPF correctly for itself (i.e. watches for userns going away
1089 * via BPF APIs). This should make very sure we don't accidentally allow any of the userns stuff to
1090 * go through without the BPF LSM in effect. */
1091
1092 r = getenv_bool("NSRESOURCE_API");
1093 if (r < 0)
1094 return log_error_errno(r, "Failed to parse $NSRESOURCE_API: %m");
1095 if (r == 0)
1096 return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceInterfaceNotSupported", NULL);
1097
1098 return 0;
1099 }
1100
1101 static char* hash_name(sd_varlink *link, const char *name) {
1102 int r;
1103
1104 assert(link);
1105 assert(name);
1106
1107 /* Make up a hashed name for this userns. We take the passed name, and hash it together with the
1108 * connection cookie. This should make collisions unlikely but generation still deterministic (this
1109 * matters because on polkit requests we might be called twice, and should generate the same string
1110 * each time, to ensure the Polkit query looks the same) */
1111
1112 uint64_t cookie = 0;
1113 r = socket_get_cookie(sd_varlink_get_fd(link), &cookie);
1114 if (r < 0)
1115 log_debug_errno(r, "Failed to determine connection cookie, ignoring: %m");
1116
1117 struct siphash h;
1118 static sd_id128_t key = SD_ID128_MAKE(ed,3a,bb,01,3a,14,4b,b3,8a,63,a4,ad,ba,2d,c9,0a);
1119 siphash24_init(&h, key.bytes);
1120 siphash24_compress_typesafe(cookie, &h);
1121 siphash24_compress_string(name, &h);
1122
1123 /* Make sure the hashed name fits into utmpx even if prefixed with "ns-", the peer's UID, "-", and
1124 * suffixed by "-65535". */
1125
1126 assert_cc(STRLEN("ns-65535-") + 16 + STRLEN("-65535") < sizeof_field(struct utmpx, ut_user));
1127
1128 char *s = NULL;
1129 if (asprintf(&s, "%016" PRIx64, siphash24_finalize(&h)) < 0)
1130 return NULL;
1131
1132 return s;
1133 }
1134
1135 static char *shorten_name(const char *name) {
1136
1137 /* Shorten the specified name, so that it works as a userns name */
1138
1139 char *n = strdup(name);
1140 if (!n)
1141 return NULL;
1142
1143 /* make sure the truncated name fits into utmpx even if prefixed with "ns-" and suffixed by "-65535" */
1144 strshorten(n, sizeof_field(struct utmpx, ut_user) - STRLEN("ns-") - STRLEN("-65536") - 1);
1145
1146 return n;
1147 }
1148
1149 static int validate_name(sd_varlink *link, const char *name, bool mangle, char **ret) {
1150 int r;
1151
1152 assert(link);
1153 assert(name);
1154 assert(ret);
1155
1156 uid_t peer_uid;
1157 r = sd_varlink_get_peer_uid(link, &peer_uid);
1158 if (r < 0)
1159 return r;
1160
1161 _cleanup_free_ char *un = NULL;
1162 if (peer_uid == 0) {
1163 /* If the client is root, we'll not prefix it, but we will make sure it's suitable for
1164 * inclusion in a user name */
1165 if (userns_name_is_valid(name)) {
1166 un = strdup(name);
1167 if (!un)
1168 return -ENOMEM;
1169 } else {
1170 if (!mangle)
1171 return sd_varlink_error_invalid_parameter_name(link, "name");
1172
1173 un = shorten_name(name);
1174 if (!un)
1175 return -ENOMEM;
1176
1177 /* Let's see if shortening was enough? (It might not be, for example because an empty
1178 * string was provided – which no truncation would make valid.) */
1179 if (!userns_name_is_valid(un)) {
1180 free(un);
1181
1182 /* if not, make up a hashed name */
1183 un = hash_name(link, name);
1184 if (!un)
1185 return -ENOMEM;
1186 }
1187 }
1188 } else {
1189 /* If the client is not root then prefix the name with the UID of the peer, so that they live
1190 * in separate namespaces and cannot interfere with each other's names. */
1191
1192 if (asprintf(&un, UID_FMT "-%s", peer_uid, name) < 0)
1193 return -ENOMEM;
1194
1195 if (!userns_name_is_valid(un)) {
1196 if (!mangle)
1197 return sd_varlink_error_invalid_parameter_name(link, "name");
1198
1199 _cleanup_free_ char *c = shorten_name(un);
1200 if (!c)
1201 return -ENOMEM;
1202
1203 /* Let's see if shortening was enough? */
1204 if (userns_name_is_valid(c))
1205 free_and_replace(un, c);
1206 else {
1207 free(c);
1208 c = hash_name(link, name);
1209 if (!c)
1210 return -ENOMEM;
1211
1212 un = mfree(un);
1213 if (asprintf(&un, UID_FMT "-%s", peer_uid, c) < 0)
1214 return -ENOMEM;
1215
1216 if (!userns_name_is_valid(un))
1217 return sd_varlink_error_invalid_parameter_name(link, "name");
1218 }
1219 }
1220 }
1221
1222 *ret = TAKE_PTR(un);
1223 return 0;
1224 }
1225
1226 static int validate_target_and_size(sd_varlink *link, uid_t target, uint32_t size, AllocateUserRangeType type) {
1227 assert(link);
1228
1229 if (type == ALLOCATE_USER_RANGE_SELF) {
1230 /* Self userns must have size 1 and target must be 0 or unset */
1231 if (size != 1)
1232 return sd_varlink_error_invalid_parameter_name(link, "size");
1233
1234 if (!IN_SET(target, UID_INVALID, 0))
1235 return sd_varlink_error_invalid_parameter_name(link, "target");
1236 } else {
1237 if (!IN_SET(size, 1U, 0x10000))
1238 return sd_varlink_error_invalid_parameter_name(link, "size");
1239
1240 if (!uid_is_valid(target) || target > UINT32_MAX - size)
1241 return sd_varlink_error_invalid_parameter_name(link, "target");
1242 }
1243
1244 return 0;
1245 }
1246
1247 static int validate_userns(sd_varlink *link, int userns_fd) {
1248 int r;
1249
1250 assert(link);
1251 assert(userns_fd >= 0);
1252
1253 r = fd_verify_safe_flags(userns_fd);
1254 if (r < 0)
1255 return log_debug_errno(r, "User namespace file descriptor has unsafe flags set: %m");
1256
1257 /* Validate this is actually a valid user namespace fd */
1258 r = fd_is_namespace(userns_fd, NAMESPACE_USER);
1259 if (r < 0)
1260 return log_debug_errno(r, "Failed to check if user namespace fd is actually a user namespace: %m");
1261 if (r == 0)
1262 return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
1263
1264 /* And refuse the thing if it is our own */
1265 r = is_our_namespace(userns_fd, NAMESPACE_USER);
1266 if (r < 0)
1267 return log_debug_errno(r, "Failed to check if user namespace fd refers to our own user namespace: %m");
1268 if (r > 0)
1269 return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
1270
1271 uid_t peer_uid;
1272 r = sd_varlink_get_peer_uid(link, &peer_uid);
1273 if (r < 0)
1274 return log_debug_errno(r, "Failed to acquire peer UID: %m");
1275
1276 if (peer_uid != 0) {
1277 /* Refuse if the userns is not actually owned by our client. */
1278 uid_t owner_uid;
1279 if (ioctl(userns_fd, NS_GET_OWNER_UID, &owner_uid) < 0)
1280 return log_debug_errno(errno, "Failed to get owner UID of user namespace: %m");
1281
1282 if (owner_uid != peer_uid)
1283 return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
1284 }
1285
1286 return 0;
1287 }
1288
1289 static int validate_userns_is_empty(sd_varlink *link, int userns_fd) {
1290 int r;
1291
1292 assert(link);
1293 assert(userns_fd >= 0);
1294
1295 _cleanup_(uid_range_freep) UIDRange *range = NULL;
1296 r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_OUTSIDE, &range);
1297 if (r < 0)
1298 return log_debug_errno(r, "Failed to read userns UID range: %m");
1299
1300 if (!uid_range_is_empty(range))
1301 return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
1302
1303 range = uid_range_free(range);
1304 r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_OUTSIDE, &range);
1305 if (r < 0)
1306 return log_debug_errno(r, "Failed to read userns GID range: %m");
1307
1308 if (!uid_range_is_empty(range))
1309 return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
1310
1311 return 0;
1312 }
1313
1314 typedef struct AllocateParameters {
1315 const char *name;
1316 AllocateUserRangeType type;
1317 uint32_t size;
1318 uid_t target;
1319 unsigned userns_fd_idx;
1320 bool mangle_name;
1321 uint32_t delegate_container_ranges;
1322 bool map_foreign;
1323 } AllocateParameters;
1324
1325 static int vl_method_allocate_user_range(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
1326
1327 static const sd_json_dispatch_field dispatch_table[] = {
1328 { "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(AllocateParameters, name), SD_JSON_MANDATORY },
1329 { "size", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint32, offsetof(AllocateParameters, size), SD_JSON_MANDATORY },
1330 { "target", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid, offsetof(AllocateParameters, target), 0 },
1331 { "userNamespaceFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AllocateParameters, userns_fd_idx), SD_JSON_MANDATORY },
1332 { "mangleName", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(AllocateParameters, mangle_name), 0 },
1333 { "type", SD_JSON_VARIANT_STRING, dispatch_allocate_user_range_type, offsetof(AllocateParameters, type), 0 },
1334 { "delegateContainerRanges", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint32, offsetof(AllocateParameters, delegate_container_ranges), 0 },
1335 { "mapForeign", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_stdbool, offsetof(AllocateParameters, map_foreign), 0 },
1336 {}
1337 };
1338
1339 _cleanup_close_ int userns_fd = -EBADF, registry_dir_fd = -EBADF, lock_fd = -EBADF;
1340 _cleanup_free_ char *userns_name = NULL;
1341 Context *c = ASSERT_PTR(userdata);
1342 uid_t peer_uid;
1343 gid_t peer_gid;
1344 struct stat userns_st;
1345 AllocateParameters p = {
1346 .type = ALLOCATE_USER_RANGE_MANAGED,
1347 .size = UINT32_MAX,
1348 .target = UID_INVALID,
1349 .userns_fd_idx = UINT_MAX,
1350 };
1351 int r;
1352
1353 assert(link);
1354 assert(parameters);
1355
1356 r = test_userns_api_support(link);
1357 if (r != 0)
1358 return r;
1359
1360 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
1361 if (r != 0)
1362 return r;
1363
1364 if (p.type != ALLOCATE_USER_RANGE_SELF && p.target == UID_INVALID)
1365 p.target = 0;
1366
1367 r = validate_name(link, p.name, p.mangle_name, &userns_name);
1368 if (r != 0)
1369 return r;
1370
1371 r = validate_target_and_size(link, p.target, p.size, p.type);
1372 if (r != 0)
1373 return r;
1374
1375 if (p.delegate_container_ranges > USER_NAMESPACE_DELEGATIONS_MAX)
1376 return sd_varlink_error(link, "io.systemd.NamespaceResource.TooManyDelegations", NULL);
1377
1378 userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
1379 if (userns_fd < 0)
1380 return log_debug_errno(userns_fd, "Failed to take user namespace fd from Varlink connection: %m");
1381
1382 r = validate_userns(link, userns_fd);
1383 if (r != 0)
1384 return r;
1385
1386 r = validate_userns_is_empty(link, userns_fd);
1387 if (r != 0)
1388 return r;
1389
1390 if (fstat(userns_fd, &userns_st) < 0)
1391 return log_debug_errno(errno, "Failed to fstat() user namespace fd: %m");
1392
1393 _cleanup_close_ int parent_userns_fd = ioctl(userns_fd, NS_GET_PARENT);
1394 if (parent_userns_fd < 0)
1395 return log_debug_errno(errno, "Failed to get parent user namespace: %m");
1396
1397 struct stat parent_st = {};
1398 if (DEBUG_LOGGING && fstat(parent_userns_fd, &parent_st) < 0)
1399 return log_debug_errno(errno, "Failed to fstat() parent user namespace fd: %m");
1400
1401 r = sd_varlink_get_peer_uid(link, &peer_uid);
1402 if (r < 0)
1403 return r;
1404
1405 r = sd_varlink_get_peer_gid(link, &peer_gid);
1406 if (r < 0)
1407 return r;
1408
1409 log_debug("Processing AllocateUserRange request: name='%s' type=%s peer=" UID_FMT ":" GID_FMT
1410 " userns=" INO_FMT " parent_userns=" INO_FMT
1411 " size=%" PRIu32 " delegates=%" PRIu32 " mapForeign=%s",
1412 userns_name,
1413 p.type == ALLOCATE_USER_RANGE_SELF ? "self" : "managed",
1414 peer_uid, peer_gid,
1415 userns_st.st_ino, parent_st.st_ino,
1416 p.size, p.delegate_container_ranges, yes_no(p.map_foreign));
1417
1418 const char *polkit_details[] = {
1419 "name", userns_name,
1420 NULL,
1421 };
1422
1423 r = varlink_verify_polkit_async_full(
1424 link,
1425 /* bus= */ NULL,
1426 "io.systemd.namespace-resource.allocate-user-namespace",
1427 polkit_details,
1428 /* good_user= */ UID_INVALID,
1429 POLKIT_DEFAULT_ALLOW, /* If no polkit is installed, allow unpriv userns namespace allocation */
1430 &c->polkit_registry);
1431 if (r <= 0)
1432 return r;
1433
1434 if (!c->bpf) {
1435 r = userns_restrict_install(/* pin= */ true, &c->bpf);
1436 if (r < 0)
1437 return r;
1438 }
1439
1440 registry_dir_fd = userns_registry_open_fd();
1441 if (registry_dir_fd < 0)
1442 return registry_dir_fd;
1443
1444 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = userns_info_new();
1445 if (!userns_info)
1446 return -ENOMEM;
1447
1448 userns_info->name = TAKE_PTR(userns_name);
1449 if (!userns_info->name)
1450 return -ENOMEM;
1451
1452 userns_info->owner = peer_uid;
1453 userns_info->userns_inode = userns_st.st_ino;
1454 if (ioctl(userns_fd, NS_GET_ID, &userns_info->userns_id) < 0)
1455 log_debug_errno(errno, "Failed to query userns ID, ignoring: %m");
1456 userns_info->size = p.size;
1457 userns_info->target_uid = p.target;
1458 userns_info->target_gid = (gid_t) p.target;
1459
1460 if (p.type == ALLOCATE_USER_RANGE_SELF) {
1461 /* The start UID/GID will be mapped to the parent userns in write_userns(). If a self
1462 * mapping to the peer UID/GID is requested, we have to map the target UID/GID ourselves here
1463 * as write_userns() doesn't take care of that. */
1464
1465 userns_info->start_uid = peer_uid;
1466 userns_info->start_gid = peer_gid;
1467
1468 if (p.target == UID_INVALID) {
1469 r = uid_range_translate_userns_fd(
1470 parent_userns_fd,
1471 UID_RANGE_USERNS_OUTSIDE,
1472 peer_uid,
1473 &userns_info->target_uid);
1474 if (r < 0)
1475 return log_debug_errno(r, "Failed to translate UID "UID_FMT" to parent user namespace: %m", peer_uid);
1476
1477 r = uid_range_translate_userns_fd(
1478 parent_userns_fd,
1479 GID_RANGE_USERNS_OUTSIDE,
1480 peer_gid,
1481 &userns_info->target_gid);
1482 if (r < 0)
1483 return log_debug_errno(r, "Failed to translate GID "GID_FMT" to parent user namespace: %m", peer_gid);
1484 }
1485 }
1486
1487 /* Set up delegation arrays if requested */
1488 if (p.delegate_container_ranges > 0) {
1489 userns_info->delegates = new0(DelegatedUserNamespaceInfo, p.delegate_container_ranges);
1490 if (!userns_info->delegates)
1491 return -ENOMEM;
1492
1493 FOREACH_ARRAY(delegate, userns_info->delegates, p.delegate_container_ranges) {
1494 *delegate = DELEGATED_USER_NAMESPACE_INFO_NULL;
1495 delegate->size = NSRESOURCE_UIDS_64K;
1496 }
1497
1498 userns_info->n_delegates = p.delegate_container_ranges;
1499 }
1500
1501 r = allocate_now(registry_dir_fd, userns_fd, parent_userns_fd, c->bpf, userns_info, &lock_fd);
1502 if (r == -EHOSTDOWN) /* The needed UID range is not delegated to us */
1503 return sd_varlink_error(link, "io.systemd.NamespaceResource.DynamicRangeUnavailable", NULL);
1504 if (r == -EBUSY) /* All used up */
1505 return sd_varlink_error(link, "io.systemd.NamespaceResource.NoDynamicRange", NULL);
1506 if (r == -EDEADLK)
1507 return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceExists", NULL);
1508 if (r == -EEXIST)
1509 return sd_varlink_error(link, "io.systemd.NamespaceResource.NameExists", NULL);
1510 if (r < 0)
1511 return r;
1512
1513 r = userns_registry_store(registry_dir_fd, userns_info);
1514 if (r < 0)
1515 return r;
1516
1517 /* Register the userns in the BPF map with an empty allowlist */
1518 r = userns_restrict_put_by_fd(
1519 c->bpf,
1520 userns_fd,
1521 /* replace= */ true,
1522 /* mount_fds= */ NULL,
1523 /* n_mount_fds= */ 0);
1524 if (r < 0)
1525 goto fail;
1526
1527 if (p.type == ALLOCATE_USER_RANGE_SELF) {
1528 /* For "self" allocations we deny setgroups() via the BPF LSM. We can't use
1529 * /proc/self/setgroups for this as that is transitive and also applies to child user
1530 * namespaces. The BPF LSM hook only applies to the specific user namespace. */
1531 r = userns_restrict_setgroups_deny_by_fd(c->bpf, userns_fd);
1532 if (r < 0)
1533 goto fail;
1534 }
1535
1536 r = write_userns(userns_fd, parent_userns_fd, userns_info, p.map_foreign);
1537 if (r < 0)
1538 goto fail;
1539
1540 lock_fd = safe_close(lock_fd);
1541
1542 /* Send user namespace and process fd to our manager process, which will watch the process and user namespace */
1543 r = sd_pid_notifyf_with_fds(
1544 /* pid= */ 0,
1545 /* unset_environment= */ false,
1546 &userns_fd, 1,
1547 "FDSTORE=1\n"
1548 "FDNAME=userns-" INO_FMT "\n", userns_info->userns_inode);
1549 if (r < 0)
1550 goto fail;
1551
1552 /* Note, we'll not return UID values from the host, since the child might not run in the same
1553 * user namespace as us. If they want to know the ranges they should read them off the userns fd, so
1554 * that they are translated into their PoV */
1555 return sd_varlink_replybo(link, SD_JSON_BUILD_PAIR_STRING("name", userns_name));
1556
1557 fail:
1558 /* Note: we don't have to clean-up the BPF maps in the error path: the bpf map type used will
1559 * automatically do that once the userns inode goes away */
1560 userns_registry_remove(registry_dir_fd, userns_info);
1561 return r;
1562 }
1563
1564 static int validate_userns_is_safe(sd_varlink *link, int userns_fd) {
1565 int r;
1566
1567 assert(link);
1568 assert(userns_fd >= 0);
1569
1570 /* Read the outside UID range and verify it isn't empty */
1571 _cleanup_(uid_range_freep) UIDRange *outside_range = NULL;
1572 r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_OUTSIDE, &outside_range);
1573 if (r < 0)
1574 return log_debug_errno(r, "Failed to read userns UID range: %m");
1575 if (uid_range_is_empty(outside_range))
1576 return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
1577
1578 /* Read the outside GID range and check it is the same as the UID range */
1579 _cleanup_(uid_range_freep) UIDRange *outside_range_gid = NULL;
1580 r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_OUTSIDE, &outside_range_gid);
1581 if (r < 0)
1582 return log_debug_errno(r, "Failed to read userns GID range: %m");
1583 if (!uid_range_equal(outside_range, outside_range_gid))
1584 return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
1585
1586 /* Read the inside UID range, and verify it matches the size of the outside UID range */
1587 _cleanup_(uid_range_freep) UIDRange *inside_range = NULL;
1588 r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_INSIDE, &inside_range);
1589 if (r < 0)
1590 return log_debug_errno(r, "Failed to read userns contents: %m");
1591 if (uid_range_size(outside_range) != uid_range_size(inside_range))
1592 return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Uh, inside and outside UID range sizes don't match.");
1593
1594 /* Read the inside GID range, and verify it matches the inside UID range */
1595 _cleanup_(uid_range_freep) UIDRange *inside_range_gid = NULL;
1596 r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_INSIDE, &inside_range_gid);
1597 if (r < 0)
1598 return log_debug_errno(r, "Failed to read userns contents: %m");
1599 if (!uid_range_equal(inside_range, inside_range_gid))
1600 return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
1601
1602 uid_t peer_uid;
1603 r = sd_varlink_get_peer_uid(link, &peer_uid);
1604 if (r < 0)
1605 return r;
1606
1607 uid_t peer_gid;
1608 r = sd_varlink_get_peer_gid(link, &peer_gid);
1609 if (r < 0)
1610 return r;
1611
1612 /* Insist that the first UID/GID in the range matches the client's UID/GID */
1613 if (outside_range->entries[0].start != peer_uid ||
1614 outside_range_gid->entries[0].start != peer_gid)
1615 return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
1616
1617 /* If there are more than one UID in the range, then also insist that the first UID maps to root inside the userns */
1618 if (uid_range_size(outside_range) > 1 && inside_range->entries[0].start != 0)
1619 return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
1620
1621 return 0;
1622 }
1623
1624 typedef struct RegisterParameters {
1625 const char *name;
1626 unsigned userns_fd_idx;
1627 bool mangle_name;
1628 } RegisterParameters;
1629
1630 static int vl_method_register_user_namespace(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
1631
1632 static const sd_json_dispatch_field dispatch_table[] = {
1633 { "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(RegisterParameters, name), SD_JSON_MANDATORY },
1634 { "userNamespaceFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(RegisterParameters, userns_fd_idx), SD_JSON_MANDATORY },
1635 { "mangleName", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(RegisterParameters, mangle_name), 0 },
1636 {}
1637 };
1638
1639 _cleanup_close_ int userns_fd = -EBADF, registry_dir_fd = -EBADF;
1640 _cleanup_free_ char *userns_name = NULL;
1641 Context *c = ASSERT_PTR(userdata);
1642 uid_t peer_uid;
1643 struct stat userns_st;
1644 RegisterParameters p = {
1645 .userns_fd_idx = UINT_MAX,
1646 };
1647 int r;
1648
1649 assert(link);
1650 assert(parameters);
1651
1652 r = test_userns_api_support(link);
1653 if (r != 0)
1654 return r;
1655
1656 r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
1657 if (r != 0)
1658 return r;
1659
1660 r = validate_name(link, p.name, p.mangle_name, &userns_name);
1661 if (r != 0)
1662 return r;
1663
1664 userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
1665 if (userns_fd < 0)
1666 return userns_fd;
1667
1668 r = validate_userns(link, userns_fd);
1669 if (r != 0)
1670 return r;
1671
1672 r = validate_userns_is_safe(link, userns_fd);
1673 if (r != 0)
1674 return r;
1675
1676 if (fstat(userns_fd, &userns_st) < 0)
1677 return log_debug_errno(errno, "Failed to fstat() user namespace fd: %m");
1678
1679 r = sd_varlink_get_peer_uid(link, &peer_uid);
1680 if (r < 0)
1681 return r;
1682
1683 const char *polkit_details[] = {
1684 "name", userns_name,
1685 NULL,
1686 };
1687
1688 r = varlink_verify_polkit_async_full(
1689 link,
1690 /* bus= */ NULL,
1691 "io.systemd.namespace-resource.register-user-namespace",
1692 polkit_details,
1693 /* good_user= */ UID_INVALID,
1694 POLKIT_DEFAULT_ALLOW, /* If no polkit is installed, allow unpriv userns namespace registration */
1695 &c->polkit_registry);
1696 if (r <= 0)
1697 return r;
1698
1699 if (!c->bpf) {
1700 r = userns_restrict_install(/* pin= */ true, &c->bpf);
1701 if (r < 0)
1702 return r;
1703 }
1704
1705 registry_dir_fd = userns_registry_open_fd();
1706 if (registry_dir_fd < 0)
1707 return registry_dir_fd;
1708
1709 _cleanup_close_ int lock_fd = -EBADF;
1710 lock_fd = userns_registry_lock(registry_dir_fd);
1711 if (lock_fd < 0)
1712 return log_debug_errno(lock_fd, "Failed to open nsresource registry lock file: %m");
1713
1714 r = inode_slot_is_available(registry_dir_fd, userns_fd, c->bpf, userns_st.st_ino);
1715 if (r < 0)
1716 return r;
1717 if (r == 0)
1718 return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceExists", NULL);
1719
1720 r = name_is_available(registry_dir_fd, userns_name);
1721 if (r < 0)
1722 return r;
1723 if (r == 0)
1724 return sd_varlink_error(link, "io.systemd.NamespaceResource.NameExists", NULL);
1725
1726 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = userns_info_new();
1727 if (!userns_info)
1728 return -ENOMEM;
1729
1730 userns_info->name = TAKE_PTR(userns_name);
1731 if (!userns_info->name)
1732 return -ENOMEM;
1733
1734 userns_info->owner = peer_uid;
1735 userns_info->userns_inode = userns_st.st_ino;
1736 if (ioctl(userns_fd, NS_GET_ID, &userns_info->userns_id) < 0)
1737 log_debug_errno(errno, "Failed to query userns ID, ignoring: %m");
1738
1739 r = userns_registry_store(registry_dir_fd, userns_info);
1740 if (r < 0)
1741 return log_debug_errno(r, "Failed to update userns registry: %m");
1742
1743 /* Register the userns in the BPF map with an empty allowlist */
1744 r = userns_restrict_put_by_fd(
1745 c->bpf,
1746 userns_fd,
1747 /* replace= */ true,
1748 /* mount_fds= */ NULL,
1749 /* n_mount_fds= */ 0);
1750 if (r < 0)
1751 goto fail;
1752
1753 /* Send user namespace and process fd to our manager process, which will watch the process and user namespace */
1754 r = sd_pid_notifyf_with_fds(
1755 /* pid= */ 0,
1756 /* unset_environment= */ false,
1757 &userns_fd, 1,
1758 "FDSTORE=1\n"
1759 "FDNAME=userns-" INO_FMT "\n", userns_info->userns_inode);
1760 if (r < 0)
1761 goto fail;
1762
1763 return sd_varlink_replybo(link, SD_JSON_BUILD_PAIR_STRING("name", userns_name));
1764
1765 fail:
1766 userns_registry_remove(registry_dir_fd, userns_info);
1767 return r;
1768 }
1769
1770 typedef struct AddMountParameters {
1771 unsigned userns_fd_idx;
1772 unsigned mount_fd_idx;
1773 } AddMountParameters;
1774
1775 static int vl_method_add_mount_to_user_namespace(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
1776
1777 static const sd_json_dispatch_field parameter_dispatch_table[] = {
1778 { "userNamespaceFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AddMountParameters, userns_fd_idx), SD_JSON_MANDATORY },
1779 { "mountFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AddMountParameters, mount_fd_idx), SD_JSON_MANDATORY },
1780 {}
1781 };
1782
1783 _cleanup_close_ int userns_fd = -EBADF, mount_fd = -EBADF, registry_dir_fd = -EBADF;
1784 Context *c = ASSERT_PTR(userdata);
1785 AddMountParameters p = {
1786 .userns_fd_idx = UINT_MAX,
1787 .mount_fd_idx = UINT_MAX,
1788 };
1789 int r, mnt_id = 0;
1790 struct stat userns_st;
1791
1792 assert(link);
1793 assert(parameters);
1794
1795 r = test_userns_api_support(link);
1796 if (r != 0)
1797 return r;
1798
1799 /* Allowlisting arbitrary mounts is a privileged operation */
1800 r = varlink_check_privileged_peer(link);
1801 if (r < 0)
1802 return r;
1803
1804 r = sd_varlink_dispatch(link, parameters, parameter_dispatch_table, &p);
1805 if (r != 0)
1806 return r;
1807
1808 userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
1809 if (userns_fd < 0)
1810 return userns_fd;
1811
1812 r = validate_userns(link, userns_fd);
1813 if (r != 0)
1814 return r;
1815
1816 if (fstat(userns_fd, &userns_st) < 0)
1817 return -errno;
1818
1819 mount_fd = sd_varlink_peek_dup_fd(link, p.mount_fd_idx);
1820 if (mount_fd < 0)
1821 return mount_fd;
1822
1823 r = fd_verify_safe_flags_full(mount_fd, O_PATH|O_DIRECTORY);
1824 if (r < 0)
1825 return log_debug_errno(r, "Mount file descriptor has unsafe flags set: %m");
1826
1827 r = fd_verify_directory(mount_fd);
1828 if (r < 0)
1829 return r;
1830
1831 r = path_get_mnt_id_at(mount_fd, NULL, &mnt_id);
1832 if (r < 0)
1833 return r;
1834
1835 r = varlink_verify_polkit_async_full(
1836 link,
1837 /* bus= */ NULL,
1838 "io.systemd.namespace-resource.delegate-mount",
1839 /* details= */ NULL,
1840 /* good_user= */ UID_INVALID,
1841 POLKIT_DEFAULT_ALLOW, /* If no polkit is installed, allow delegation of mounts to registered userns */
1842 &c->polkit_registry);
1843 if (r <= 0)
1844 return r;
1845
1846 registry_dir_fd = userns_registry_open_fd();
1847 if (registry_dir_fd < 0)
1848 return registry_dir_fd;
1849
1850 _cleanup_close_ int lock_fd = -EBADF;
1851 lock_fd = userns_registry_lock(registry_dir_fd);
1852 if (lock_fd < 0)
1853 return log_debug_errno(lock_fd, "Failed to open nsresource registry lock file: %m");
1854
1855 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
1856 r = userns_registry_load_by_userns_inode(
1857 registry_dir_fd,
1858 userns_st.st_ino,
1859 &userns_info);
1860 if (r == -ENOENT)
1861 return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceNotRegistered", NULL);
1862 if (r < 0)
1863 return r;
1864
1865 r = userns_info_verify_fd(userns_fd, userns_info);
1866 if (r == -ESTALE)
1867 return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceNotRegistered", NULL);
1868 if (r < 0)
1869 return log_debug_errno(r, "Failed to verify user namespace identity: %m");
1870
1871 if (!c->bpf) {
1872 r = userns_restrict_install(/* pin= */ true, &c->bpf);
1873 if (r < 0)
1874 return r;
1875 }
1876
1877 /* Pin the mount fd */
1878 r = sd_pid_notifyf_with_fds(
1879 /* pid= */ 0,
1880 /* unset_environment= */ false,
1881 &mount_fd, 1,
1882 "FDSTORE=1\n"
1883 "FDNAME=userns-" INO_FMT "\n", userns_st.st_ino);
1884 if (r < 0)
1885 return r;
1886
1887 /* Add this mount to the user namespace's BPF map allowlist entry. */
1888 r = userns_restrict_put_by_fd(
1889 c->bpf,
1890 userns_fd,
1891 /* replace= */ false,
1892 &mount_fd,
1893 1);
1894 if (r < 0)
1895 return r;
1896
1897 if (DEBUG_LOGGING) {
1898 if (userns_info->size > 0)
1899 log_debug("Granting access to mount %i to user namespace " INO_FMT " ('%s' @ UID " UID_FMT ")",
1900 mnt_id, userns_st.st_ino, userns_info->name, userns_info->start_uid);
1901 else
1902 log_debug("Granting access to mount %i to user namespace " INO_FMT " ('%s')",
1903 mnt_id, userns_st.st_ino, userns_info->name);
1904 }
1905
1906 return sd_varlink_replyb(link, SD_JSON_BUILD_EMPTY_OBJECT);
1907 }
1908
1909 static int validate_cgroup(sd_varlink *link, int fd, uint64_t *ret_cgroup_id) {
1910 int r;
1911
1912 assert(link);
1913 assert(fd >= 0);
1914 assert(ret_cgroup_id);
1915
1916 r = fd_verify_safe_flags_full(fd, O_DIRECTORY);
1917 if (r < 0)
1918 return log_debug_errno(r, "Control group file descriptor has unsafe flags set: %m");
1919
1920 r = fd_verify_directory(fd);
1921 if (r < 0)
1922 return log_debug_errno(r, "Verification that cgroup fd refers to directory failed: %m");
1923
1924 r = fd_is_fs_type(fd, CGROUP2_SUPER_MAGIC);
1925 if (r < 0)
1926 return log_debug_errno(r, "Failed to check if cgroup fd actually refers to cgroupfs: %m");
1927 if (r == 0)
1928 return sd_varlink_error_invalid_parameter_name(link, "controlGroupFileDescriptor");
1929
1930 r = fd_to_handle_u64(fd, ret_cgroup_id);
1931 if (r < 0)
1932 return log_debug_errno(r, "Failed to read cgroup ID from cgroupfs: %m");
1933
1934 return 0;
1935 }
1936
1937 typedef struct AddCGroupParameters {
1938 unsigned userns_fd_idx;
1939 unsigned cgroup_fd_idx;
1940 } AddCGroupParameters;
1941
1942 static int vl_method_add_cgroup_to_user_namespace(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
1943 static const sd_json_dispatch_field parameter_dispatch_table[] = {
1944 { "userNamespaceFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AddCGroupParameters, userns_fd_idx), SD_JSON_MANDATORY },
1945 { "controlGroupFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AddCGroupParameters, cgroup_fd_idx), SD_JSON_MANDATORY },
1946 {}
1947 };
1948
1949 _cleanup_close_ int userns_fd = -EBADF, cgroup_fd = -EBADF, registry_dir_fd = -EBADF;
1950 AddCGroupParameters p = {
1951 .userns_fd_idx = UINT_MAX,
1952 .cgroup_fd_idx = UINT_MAX,
1953 };
1954 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
1955 Context *c = ASSERT_PTR(userdata);
1956 struct stat userns_st, cgroup_st;
1957 uid_t peer_uid;
1958 int r;
1959
1960 assert(link);
1961 assert(parameters);
1962
1963 r = test_userns_api_support(link);
1964 if (r != 0)
1965 return r;
1966
1967 r = sd_varlink_dispatch(link, parameters, parameter_dispatch_table, &p);
1968 if (r != 0)
1969 return r;
1970
1971 userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
1972 if (userns_fd < 0)
1973 return log_debug_errno(userns_fd, "Failed to take user namespace fd from Varlink connection: %m");
1974
1975 r = validate_userns(link, userns_fd);
1976 if (r != 0)
1977 return r;
1978
1979 if (fstat(userns_fd, &userns_st) < 0)
1980 return log_debug_errno(errno, "Failed to fstat() user namespace fd: %m");
1981
1982 cgroup_fd = sd_varlink_peek_dup_fd(link, p.cgroup_fd_idx);
1983 if (cgroup_fd < 0)
1984 return log_debug_errno(cgroup_fd, "Failed to take cgroup fd from Varlink connection: %m");
1985
1986 uint64_t cgroup_id;
1987 r = validate_cgroup(link, cgroup_fd, &cgroup_id);
1988 if (r != 0)
1989 return r;
1990
1991 if (fstat(cgroup_fd, &cgroup_st) < 0)
1992 return log_debug_errno(errno, "Failed to fstat() cgroup fd: %m");
1993
1994 r = varlink_verify_polkit_async_full(
1995 link,
1996 /* bus= */ NULL,
1997 "io.systemd.namespace-resource.delegate-cgroup",
1998 /* details= */ NULL,
1999 /* good_user= */ UID_INVALID,
2000 POLKIT_DEFAULT_ALLOW, /* If no polkit is installed, allow delegation of cgroups to registered userns */
2001 &c->polkit_registry);
2002 if (r <= 0)
2003 return r;
2004
2005 registry_dir_fd = userns_registry_open_fd();
2006 if (registry_dir_fd < 0)
2007 return registry_dir_fd;
2008
2009 _cleanup_close_ int lock_fd = -EBADF;
2010 lock_fd = userns_registry_lock(registry_dir_fd);
2011 if (lock_fd < 0)
2012 return lock_fd;
2013
2014 r = userns_registry_load_by_userns_inode(
2015 registry_dir_fd,
2016 userns_st.st_ino,
2017 &userns_info);
2018 if (r == -ENOENT)
2019 return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceNotRegistered", NULL);
2020 if (r < 0)
2021 return r;
2022
2023 r = userns_info_verify_fd(userns_fd, userns_info);
2024 if (r == -ESTALE)
2025 return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceNotRegistered", NULL);
2026 if (r < 0)
2027 return log_debug_errno(r, "Failed to verify user namespace identity: %m");
2028
2029 /* The user namespace must have a user assigned */
2030 if (userns_info->size == 0)
2031 return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceWithoutUserRange", NULL);
2032 if (userns_info_has_cgroup(userns_info, cgroup_id))
2033 return sd_varlink_error(link, "io.systemd.NamespaceResource.ControlGroupAlreadyAdded", NULL);
2034 if (userns_info->n_cgroups > USER_NAMESPACE_CGROUPS_DELEGATE_MAX)
2035 return sd_varlink_error(link, "io.systemd.NamespaceResource.TooManyControlGroups", NULL);
2036
2037 /* Registering a cgroup for this client is only allowed for the root or the owner of a userns */
2038 r = sd_varlink_get_peer_uid(link, &peer_uid);
2039 if (r < 0)
2040 return log_debug_errno(r, "Failed to get connection peer: %m");
2041 if (peer_uid != 0) {
2042 if (peer_uid != userns_info->owner)
2043 return sd_varlink_error(link, SD_VARLINK_ERROR_PERMISSION_DENIED, NULL);
2044
2045 /* The cgroup must be owned by the owner of the userns */
2046 if (cgroup_st.st_uid != userns_info->owner)
2047 return sd_varlink_error(link, SD_VARLINK_ERROR_PERMISSION_DENIED, NULL);
2048 }
2049
2050 r = userns_info_add_cgroup(userns_info, cgroup_id);
2051 if (r < 0)
2052 return r;
2053
2054 r = userns_registry_store(registry_dir_fd, userns_info);
2055 if (r < 0)
2056 return r;
2057
2058 if (fchown(cgroup_fd, userns_info->start_uid, userns_info->start_gid) < 0)
2059 return log_debug_errno(errno, "Failed to change ownership of cgroup: %m");
2060
2061 if (fchmod(cgroup_fd, 0755) < 0)
2062 return log_debug_errno(errno, "Failed to change access mode of cgroup: %m");
2063
2064 FOREACH_STRING(attr, "cgroup.procs", "cgroup.subtree_control", "cgroup.threads") {
2065 (void) fchmodat(cgroup_fd, attr, 0644, AT_SYMLINK_NOFOLLOW);
2066 (void) fchownat(cgroup_fd, attr, userns_info->start_uid, userns_info->start_gid, AT_SYMLINK_NOFOLLOW);
2067 }
2068
2069 log_debug("Granting ownership to cgroup %" PRIu64 " to userns " INO_FMT " ('%s' @ UID " UID_FMT ")",
2070 cgroup_id, userns_st.st_ino, userns_info->name, userns_info->start_uid);
2071
2072 return sd_varlink_replyb(link, SD_JSON_BUILD_EMPTY_OBJECT);
2073 }
2074
2075 static uint64_t hash_ifname_id(UserNamespaceInfo *userns_info, const char *ifname) {
2076 struct siphash state;
2077
2078 assert(userns_info);
2079
2080 siphash24_init(&state, (const uint8_t[]) { 0xc4, 0x6c, 0x96, 0xe8, 0xad, 0x37, 0x4d, 0x5f, 0xa1, 0xae, 0xfe, 0x70, 0x40, 0xed, 0x41, 0x5f });
2081 siphash24_compress_string(userns_info->name, &state);
2082 siphash24_compress_byte(0, &state); /* separator */
2083 siphash24_compress_string(strempty(ifname), &state);
2084
2085 return siphash24_finalize(&state);
2086 }
2087
2088 static void hash_ether_addr(UserNamespaceInfo *userns_info, const char *ifname, uint64_t n, struct ether_addr *ret) {
2089 struct siphash state;
2090 uint64_t h;
2091
2092 assert(userns_info);
2093 assert(ret);
2094
2095 siphash24_init(&state, (const uint8_t[]) { 0x36, 0xaa, 0xd1, 0x69, 0xc7, 0xe5, 0x4c, 0xaa, 0x1e, 0xb2, 0x9e, 0xb3, 0x3a, 0x6b, 0xd4, 0x71 });
2096 siphash24_compress_string(userns_info->name, &state);
2097 siphash24_compress_byte(0, &state); /* separator */
2098 siphash24_compress_string(strempty(ifname), &state);
2099 siphash24_compress_byte(0, &state); /* separator */
2100 n = htole64(n); /* add the 'index' to the mix in an endianness-independent fashion */
2101 siphash24_compress_typesafe(n, &state);
2102
2103 h = htole64(siphash24_finalize(&state));
2104
2105 assert(sizeof(h) >= sizeof_field(struct ether_addr, ether_addr_octet));
2106
2107 memcpy(ret->ether_addr_octet, &h, sizeof_field(struct ether_addr, ether_addr_octet));
2108 ether_addr_mark_random(ret);
2109 }
2110
2111 static int create_veth(
2112 int netns_fd,
2113 const char *ifname_host,
2114 const char *altifname_host,
2115 struct ether_addr *mac_host,
2116 const char *ifname_namespace,
2117 struct ether_addr *mac_namespace) {
2118
2119 int r;
2120
2121 assert(netns_fd >= 0);
2122 assert(ifname_host);
2123 assert(mac_host);
2124 assert(ifname_namespace);
2125 assert(mac_namespace);
2126
2127 log_debug("Creating veth link on host %s (%s) with address %s to container as %s with address %s",
2128 ifname_host, strna(altifname_host), ETHER_ADDR_TO_STR(mac_host),
2129 ifname_namespace, ETHER_ADDR_TO_STR(mac_namespace));
2130
2131 _cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL;
2132 r = sd_netlink_open(&rtnl);
2133 if (r < 0)
2134 return log_error_errno(r, "Failed to allocation netlink connection: %m");
2135
2136 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
2137 r = sd_rtnl_message_new_link(rtnl, &m, RTM_NEWLINK, 0);
2138 if (r < 0)
2139 return log_error_errno(r, "Failed to allocate netlink message: %m");
2140
2141 r = sd_netlink_message_append_string(m, IFLA_IFNAME, ifname_host);
2142 if (r < 0)
2143 return log_error_errno(r, "Failed to add netlink interface name: %m");
2144
2145 r = sd_netlink_message_append_ether_addr(m, IFLA_ADDRESS, mac_host);
2146 if (r < 0)
2147 return log_error_errno(r, "Failed to add netlink MAC address: %m");
2148
2149 r = sd_netlink_message_open_container(m, IFLA_LINKINFO);
2150 if (r < 0)
2151 return log_error_errno(r, "Failed to open netlink container: %m");
2152
2153 r = sd_netlink_message_open_container_union(m, IFLA_INFO_DATA, "veth");
2154 if (r < 0)
2155 return log_error_errno(r, "Failed to open netlink container: %m");
2156
2157 r = sd_netlink_message_open_container(m, VETH_INFO_PEER);
2158 if (r < 0)
2159 return log_error_errno(r, "Failed to open netlink container: %m");
2160
2161 r = sd_netlink_message_append_string(m, IFLA_IFNAME, ifname_namespace);
2162 if (r < 0)
2163 return log_error_errno(r, "Failed to add netlink interface name: %m");
2164
2165 r = sd_netlink_message_append_ether_addr(m, IFLA_ADDRESS, mac_namespace);
2166 if (r < 0)
2167 return log_error_errno(r, "Failed to add netlink MAC address: %m");
2168
2169 r = sd_netlink_message_append_u32(m, IFLA_NET_NS_FD, netns_fd);
2170 if (r < 0)
2171 return log_error_errno(r, "Failed to add netlink namespace field: %m");
2172
2173 r = sd_netlink_message_close_container(m);
2174 if (r < 0)
2175 return log_error_errno(r, "Failed to close netlink container: %m");
2176
2177 r = sd_netlink_message_close_container(m);
2178 if (r < 0)
2179 return log_error_errno(r, "Failed to close netlink container: %m");
2180
2181 r = sd_netlink_message_close_container(m);
2182 if (r < 0)
2183 return log_error_errno(r, "Failed to close netlink container: %m");
2184
2185 r = sd_netlink_call(rtnl, m, 0, NULL);
2186 if (r < 0)
2187 return log_error_errno(r, "Failed to add new veth interfaces (%s:%s): %m", ifname_host, ifname_namespace);
2188
2189 r = rtnl_set_link_alternative_names_by_ifname(&rtnl, ifname_host, STRV_MAKE(altifname_host));
2190 if (r < 0)
2191 log_warning_errno(r, "Failed to set alternative interface name to '%s', ignoring: %m", altifname_host);
2192
2193 return 0;
2194 }
2195
2196 static int create_tap(
2197 int userns_fd,
2198 const char *ifname_host,
2199 char *const *altifname_host,
2200 struct ether_addr *mac_host) {
2201
2202 int r;
2203
2204 assert(ifname_host);
2205 assert(mac_host);
2206
2207 if (!ifname_valid(ifname_host))
2208 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid interface name: %s", ifname_host);
2209
2210 log_debug("Creating tap link on host %s (%s) with address %s",
2211 ifname_host, strna(altifname_host ? altifname_host[0] : NULL), ETHER_ADDR_TO_STR(mac_host));
2212
2213 _cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL;
2214 if (altifname_host) {
2215 r = sd_netlink_open(&rtnl);
2216 if (r < 0)
2217 return log_error_errno(r, "Failed to allocate netlink connection: %m");
2218 }
2219
2220 uid_t uid;
2221 r = userns_get_base_uid(userns_fd, &uid, /* ret_gid= */ NULL);
2222 if (r < 0)
2223 return log_error_errno(r, "Failed to get namespace base UID/GID: %m");
2224
2225 struct ifreq ifr = {
2226 .ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR,
2227 };
2228
2229 assert(strlen(ifname_host) < sizeof(ifr.ifr_name));
2230 strcpy(ifr.ifr_name, ifname_host);
2231
2232 _cleanup_close_ int fd = open("/dev/net/tun", O_RDWR|O_CLOEXEC);
2233 if (fd < 0) {
2234 if (errno == ENOENT) /* Turn ENOENT → EOPNOTSUPP */
2235 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Network tap device node /dev/net/tun not found, cannot create network interface.");
2236
2237 return log_error_errno(errno, "Failed to open %s: %m", "/dev/net/tun");
2238 }
2239
2240 if (ioctl(fd, TUNSETIFF, &ifr) < 0)
2241 return log_error_errno(errno, "TUNSETIFF failed: %m");
2242
2243 if (ioctl(fd, TUNSETOWNER, uid) < 0)
2244 return log_error_errno(errno, "TUNSETOWNER failed: %m");
2245
2246 if (!strv_isempty(altifname_host)) {
2247 r = rtnl_set_link_alternative_names_by_ifname(&rtnl, ifname_host, altifname_host);
2248 if (r < 0)
2249 log_warning_errno(r, "Failed to set alternative interface names, ignoring: %m");
2250 }
2251
2252 return TAKE_FD(fd);
2253 }
2254
2255 static int validate_netns(sd_varlink *link, int userns_fd, int netns_fd) {
2256 int r;
2257
2258 assert(link);
2259 assert(userns_fd >= 0);
2260 assert(netns_fd >= 0);
2261
2262 r = fd_verify_safe_flags(netns_fd);
2263 if (r < 0)
2264 return log_debug_errno(r, "Network namespace file descriptor has unsafe flags set: %m");
2265
2266 /* Validate this is actually a valid network namespace fd */
2267 r = fd_is_namespace(netns_fd, NAMESPACE_NET);
2268 if (r < 0)
2269 return r;
2270 if (r == 0)
2271 return sd_varlink_error_invalid_parameter_name(link, "networkNamespaceFileDescriptor");
2272
2273 /* And refuse the thing if it is our own */
2274 r = is_our_namespace(netns_fd, NAMESPACE_NET);
2275 if (r < 0)
2276 return r;
2277 if (r > 0)
2278 return sd_varlink_error_invalid_parameter_name(link, "networkNamespaceFileDescriptor");
2279
2280 /* Check if the netns actually belongs to the userns */
2281 _cleanup_close_ int owner_userns_fd = -EBADF;
2282 owner_userns_fd = ioctl(netns_fd, NS_GET_USERNS);
2283 if (owner_userns_fd < 0)
2284 return -errno;
2285
2286 r = inode_same_at(owner_userns_fd, /* filea= */ NULL, userns_fd, /* fileb= */ NULL, AT_EMPTY_PATH);
2287 if (r < 0)
2288 return r;
2289 if (r == 0)
2290 return sd_varlink_error_invalid_parameter_name(link, "networkNamespaceFileDescriptor");
2291
2292 uid_t peer_uid;
2293 r = sd_varlink_get_peer_uid(link, &peer_uid);
2294 if (r < 0)
2295 return r;
2296
2297 if (peer_uid != 0) {
2298 /* Refuse if the netns is not actually owned by our client. */
2299
2300 uid_t owner_uid;
2301 if (ioctl(owner_userns_fd, NS_GET_OWNER_UID, &owner_uid) < 0)
2302 return -errno;
2303
2304 if (owner_uid != peer_uid)
2305 return sd_varlink_error_invalid_parameter_name(link, "networkNamespaceFileDescriptor");
2306 }
2307
2308 return 0;
2309 }
2310
2311 typedef struct AddNetworkParameters {
2312 unsigned userns_fd_idx;
2313 unsigned netns_fd_idx;
2314 const char *ifname;
2315 const char *mode;
2316 } AddNetworkParameters;
2317
2318 static int vl_method_add_netif_to_user_namespace(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
2319 static const sd_json_dispatch_field parameter_dispatch_table[] = {
2320 { "userNamespaceFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AddNetworkParameters, userns_fd_idx), SD_JSON_MANDATORY },
2321 { "networkNamespaceFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AddNetworkParameters, netns_fd_idx), 0 },
2322 { "namespaceInterfaceName", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(AddNetworkParameters, ifname), 0 },
2323 { "mode", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(AddNetworkParameters, mode), SD_JSON_MANDATORY },
2324 {}
2325 };
2326
2327 _cleanup_close_ int userns_fd = -EBADF, netns_fd = -EBADF, registry_dir_fd = -EBADF;
2328 Context *c = ASSERT_PTR(userdata);
2329 AddNetworkParameters p = {
2330 .userns_fd_idx = UINT_MAX,
2331 .netns_fd_idx = UINT_MAX,
2332 };
2333 int r;
2334
2335 assert(link);
2336 assert(parameters);
2337
2338 r = test_userns_api_support(link);
2339 if (r != 0)
2340 return r;
2341
2342 r = sd_varlink_dispatch(link, parameters, parameter_dispatch_table, &p);
2343 if (r != 0)
2344 return r;
2345
2346 userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
2347 if (userns_fd < 0)
2348 return userns_fd;
2349
2350 r = validate_userns(link, userns_fd);
2351 if (r != 0)
2352 return r;
2353
2354 struct stat userns_st;
2355 if (fstat(userns_fd, &userns_st) < 0)
2356 return -errno;
2357
2358 if (p.netns_fd_idx != UINT_MAX) {
2359 netns_fd = sd_varlink_peek_dup_fd(link, p.netns_fd_idx);
2360 if (netns_fd < 0)
2361 return netns_fd;
2362
2363 r = validate_netns(link, userns_fd, netns_fd);
2364 if (r != 0)
2365 return r;
2366 }
2367
2368 if (p.ifname && !ifname_valid(p.ifname))
2369 return sd_varlink_error_invalid_parameter_name(link, "interfaceName");
2370
2371 if (streq(p.mode, "veth")) {
2372 /* In veth mode we need a netns */
2373
2374 if (netns_fd < 0)
2375 return sd_varlink_error_invalid_parameter_name(link, "networkNamespaceFileDescriptor");
2376
2377 } else if (streq(p.mode, "tap")) {
2378 /* In tap mode we do want a netns, nor an interface name for it */
2379
2380 if (p.ifname)
2381 return sd_varlink_error_invalid_parameter_name(link, "namespaceInterfaceName");
2382
2383 if (netns_fd >= 0)
2384 return sd_varlink_error_invalid_parameter_name(link, "networkNamespaceFileDescriptor");
2385 } else
2386 return sd_varlink_error_invalid_parameter_name(link, "mode");
2387
2388 const char *polkit_details[] = {
2389 "type", p.mode,
2390 NULL,
2391 };
2392
2393 r = varlink_verify_polkit_async_full(
2394 link,
2395 /* bus= */ NULL,
2396 "io.systemd.namespace-resource.delegate-network-interface",
2397 polkit_details,
2398 /* good_user= */ UID_INVALID,
2399 POLKIT_DEFAULT_ALLOW, /* If no polkit is installed, allow delegation of network interfaces to registered userns */
2400 &c->polkit_registry);
2401 if (r <= 0)
2402 return r;
2403
2404 registry_dir_fd = userns_registry_open_fd();
2405 if (registry_dir_fd < 0)
2406 return registry_dir_fd;
2407
2408 _cleanup_close_ int lock_fd = userns_registry_lock(registry_dir_fd);
2409 if (lock_fd < 0)
2410 return log_debug_errno(lock_fd, "Failed to open nsresource registry lock file: %m");
2411
2412 _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
2413 r = userns_registry_load_by_userns_inode(
2414 registry_dir_fd,
2415 userns_st.st_ino,
2416 &userns_info);
2417 if (r == -ENOENT)
2418 return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceNotRegistered", NULL);
2419 if (r < 0)
2420 return r;
2421
2422 r = userns_info_verify_fd(userns_fd, userns_info);
2423 if (r == -ESTALE)
2424 return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceNotRegistered", NULL);
2425 if (r < 0)
2426 return log_debug_errno(r, "Failed to verify user namespace identity: %m");
2427
2428 if (strv_length(userns_info->netifs) > USER_NAMESPACE_NETIFS_DELEGATE_MAX)
2429 return sd_varlink_error(link, "io.systemd.NamespaceResource.TooManyNetworkInterfaces", NULL);
2430
2431 /* Registering a network interface for this client is only allowed for the root or the owner of a userns */
2432 uid_t peer_uid;
2433 r = sd_varlink_get_peer_uid(link, &peer_uid);
2434 if (r < 0)
2435 return r;
2436 if (peer_uid != 0 && peer_uid != userns_info->owner)
2437 return sd_varlink_error(link, SD_VARLINK_ERROR_PERMISSION_DENIED, NULL);
2438
2439 _cleanup_free_ char *ifname_host = NULL, *altifname_host = NULL;
2440 const char *ifname_namespace = p.ifname ?: "host0";
2441
2442 /* The short ifname is just too short to generate readable and unique names where unprivileged users
2443 * can't take each others names. Hence just hash it. The alternative name however contains more useful
2444 * information. */
2445 if (asprintf(&ifname_host, "ns-%08" PRIx64, hash_ifname_id(userns_info, p.ifname)) < 0)
2446 return -ENOMEM;
2447 strshorten(ifname_host, IFNAMSIZ-1);
2448
2449 /* Register the interface in the userns store first, so that we can be sure it's properly 'owned' at
2450 * any time, in case setup fails for some reason. Given we the interface name is hashed accidental
2451 * collisions should be unlikely. */
2452 r = userns_info_add_netif(userns_info, ifname_host);
2453 if (r < 0)
2454 return r;
2455
2456 r = userns_registry_store(registry_dir_fd, userns_info);
2457 if (r < 0)
2458 return r;
2459
2460 if (p.ifname)
2461 r = asprintf(&altifname_host, "ns-" UID_FMT "-%s-%s", userns_info->owner, userns_info->name, p.ifname);
2462 else
2463 r = asprintf(&altifname_host, "ns-" UID_FMT "-%s", userns_info->owner, userns_info->name);
2464 if (r < 0)
2465 return -ENOMEM;
2466
2467 if (!ifname_valid_full(altifname_host, IFNAME_VALID_ALTERNATIVE))
2468 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Generated alternative interface name not valid: %s", altifname_host);
2469
2470 struct ether_addr ether_addr_host;
2471 hash_ether_addr(userns_info, p.ifname, 0, &ether_addr_host);
2472
2473 if (streq(p.mode, "veth")) {
2474 struct ether_addr ether_addr_namespace;
2475 hash_ether_addr(userns_info, p.ifname, 1, &ether_addr_namespace);
2476
2477 r = create_veth(netns_fd,
2478 ifname_host, altifname_host, &ether_addr_host,
2479 ifname_namespace, &ether_addr_namespace);
2480 if (r < 0)
2481 return r;
2482
2483 log_debug("Added veth tunnel %s from host to userns " INO_FMT " ('%s' @ UID " UID_FMT ", interface %s).",
2484 ifname_host, userns_st.st_ino, userns_info->name, userns_info->start_uid, ifname_namespace);
2485
2486 return sd_varlink_replybo(
2487 link,
2488 SD_JSON_BUILD_PAIR_STRING("hostInterfaceName", ifname_host),
2489 SD_JSON_BUILD_PAIR_STRING("namespaceInterfaceName", ifname_namespace));
2490
2491 } else if (streq(p.mode, "tap")) {
2492 /* NB: when we do the "tap" stuff we do not actually do any namespace operation here, neither
2493 * netns nor userns. We use the userns only as conduit for user identity information and
2494 * indication that the calling user has some control over the UID they want to assign the tap
2495 * device to. */
2496
2497 _cleanup_close_ int tap_fd = create_tap(userns_fd, ifname_host, STRV_MAKE(altifname_host), &ether_addr_host);
2498 if (tap_fd < 0)
2499 return tap_fd;
2500
2501 log_debug("Added tap device %s from host to userns " INO_FMT " ('%s' @ UID " UID_FMT ").",
2502 ifname_host, userns_st.st_ino, userns_info->name, userns_info->start_uid);
2503
2504 int fd_index = sd_varlink_push_fd(link, tap_fd);
2505 if (fd_index < 0)
2506 return log_error_errno(fd_index, "Failed to push tap fd into varlink socket: %m");
2507
2508 TAKE_FD(tap_fd);
2509
2510 return sd_varlink_replybo(
2511 link,
2512 SD_JSON_BUILD_PAIR_STRING("hostInterfaceName", ifname_host),
2513 SD_JSON_BUILD_PAIR_INTEGER("interfaceFileDescriptor", fd_index));
2514 } else
2515 assert_not_reached();
2516 }
2517
2518 static int process_connection(sd_varlink_server *server, int _fd) {
2519 _cleanup_close_ int fd = TAKE_FD(_fd); /* always take possession */
2520 _cleanup_(sd_varlink_close_unrefp) sd_varlink *vl = NULL;
2521 _cleanup_(sd_event_unrefp) sd_event *event = NULL;
2522 int r;
2523
2524 assert(server);
2525 assert(fd >= 0);
2526
2527 r = sd_event_new(&event);
2528 if (r < 0)
2529 return r;
2530
2531 r = sd_varlink_server_attach_event(server, event, /* priority= */ 0);
2532 if (r < 0)
2533 return log_error_errno(r, "Failed to attach Varlink server to event loop: %m");
2534
2535 r = sd_varlink_server_add_connection(server, fd, &vl);
2536 if (r < 0)
2537 return log_error_errno(r, "Failed to add connection: %m");
2538
2539 TAKE_FD(fd);
2540 vl = sd_varlink_ref(vl);
2541
2542 r = sd_event_loop(event);
2543 if (r < 0)
2544 return log_error_errno(r, "Failed to run event loop: %m");
2545
2546 r = sd_varlink_server_detach_event(server);
2547 if (r < 0)
2548 return log_error_errno(r, "Failed to detach Varlink server from event loop: %m");
2549
2550 return 0;
2551 }
2552
2553 static void context_free(Context *c) {
2554 assert(c);
2555
2556 c->polkit_registry = hashmap_free(c->polkit_registry);
2557 c->bpf = userns_restrict_bpf_free(c->bpf);
2558 }
2559
2560 static int run(int argc, char *argv[]) {
2561 usec_t start_time, listen_idle_usec, last_busy_usec = USEC_INFINITY;
2562 _cleanup_(sd_varlink_server_unrefp) sd_varlink_server *server = NULL;
2563 _cleanup_(context_free) Context c = {};
2564 _cleanup_(pidref_done) PidRef parent = PIDREF_NULL;
2565 unsigned n_iterations = 0;
2566 int m, listen_fd, r;
2567
2568 log_setup();
2569
2570 m = sd_listen_fds(false);
2571 if (m < 0)
2572 return log_error_errno(m, "Failed to determine number of listening fds: %m");
2573 if (m == 0)
2574 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No socket to listen on received.");
2575 if (m > 1)
2576 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Worker can only listen on a single socket at a time.");
2577
2578 listen_fd = SD_LISTEN_FDS_START;
2579
2580 r = fd_nonblock(listen_fd, false);
2581 if (r < 0)
2582 return log_error_errno(r, "Failed to turn off non-blocking mode for listening socket: %m");
2583
2584 r = varlink_server_new(
2585 &server,
2586 SD_VARLINK_SERVER_INHERIT_USERDATA|
2587 SD_VARLINK_SERVER_ALLOW_FD_PASSING_INPUT|SD_VARLINK_SERVER_ALLOW_FD_PASSING_OUTPUT,
2588 &c);
2589 if (r < 0)
2590 return log_error_errno(r, "Failed to allocate varlink server: %m");
2591
2592 r = sd_varlink_server_add_interface_many(
2593 server,
2594 &vl_interface_io_systemd_NamespaceResource,
2595 &vl_interface_io_systemd_UserDatabase);
2596 if (r < 0)
2597 return log_error_errno(r, "Failed to add UserDatabase and NamespaceResource interface to varlink server: %m");
2598
2599 r = sd_varlink_server_bind_method_many(
2600 server,
2601 "io.systemd.NamespaceResource.AllocateUserRange", vl_method_allocate_user_range,
2602 "io.systemd.NamespaceResource.RegisterUserNamespace", vl_method_register_user_namespace,
2603 "io.systemd.NamespaceResource.AddMountToUserNamespace", vl_method_add_mount_to_user_namespace,
2604 "io.systemd.NamespaceResource.AddControlGroupToUserNamespace", vl_method_add_cgroup_to_user_namespace,
2605 "io.systemd.NamespaceResource.AddNetworkToUserNamespace", vl_method_add_netif_to_user_namespace,
2606 "io.systemd.UserDatabase.GetUserRecord", vl_method_get_user_record,
2607 "io.systemd.UserDatabase.GetGroupRecord", vl_method_get_group_record,
2608 "io.systemd.UserDatabase.GetMemberships", vl_method_get_memberships);
2609 if (r < 0)
2610 return log_error_errno(r, "Failed to bind methods: %m");
2611
2612 r = sd_varlink_server_set_exit_on_idle(server, true);
2613 if (r < 0)
2614 return log_error_errno(r, "Failed to enable exit-on-idle mode: %m");
2615
2616 r = getenv_bool("NSRESOURCE_FIXED_WORKER");
2617 if (r < 0)
2618 return log_error_errno(r, "Failed to parse NSRESOURCE_FIXED_WORKER: %m");
2619 listen_idle_usec = r ? USEC_INFINITY : LISTEN_IDLE_USEC;
2620
2621 r = pidref_set_parent(&parent);
2622 if (r < 0)
2623 return log_error_errno(r, "Failed to acquire pidfd of parent process: %m");
2624
2625 start_time = now(CLOCK_MONOTONIC);
2626
2627 for (;;) {
2628 _cleanup_close_ int fd = -EBADF;
2629 usec_t n;
2630
2631 /* Exit the worker in regular intervals, to flush out all memory use */
2632 if (n_iterations++ > ITERATIONS_MAX) {
2633 log_debug("Exiting worker, processed %u iterations, that's enough.", n_iterations);
2634 break;
2635 }
2636
2637 n = now(CLOCK_MONOTONIC);
2638 if (n >= usec_add(start_time, RUNTIME_MAX_USEC)) {
2639 log_debug("Exiting worker, ran for %s, that's enough.",
2640 FORMAT_TIMESPAN(usec_sub_unsigned(n, start_time), 0));
2641 break;
2642 }
2643
2644 if (last_busy_usec == USEC_INFINITY)
2645 last_busy_usec = n;
2646 else if (listen_idle_usec != USEC_INFINITY && n >= usec_add(last_busy_usec, listen_idle_usec)) {
2647 log_debug("Exiting worker, been idle for %s.",
2648 FORMAT_TIMESPAN(usec_sub_unsigned(n, last_busy_usec), 0));
2649 break;
2650 }
2651
2652 (void) rename_process("systemd-nsresourcework: waiting...");
2653 fd = RET_NERRNO(accept4(listen_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC));
2654 (void) rename_process("systemd-nsresourcework: processing...");
2655
2656 if (fd == -EAGAIN)
2657 continue; /* The listening socket has SO_RECVTIMEO set, hence a timeout is expected
2658 * after a while, let's check if it's time to exit though. */
2659 if (fd == -EINTR)
2660 continue; /* Might be that somebody attached via strace, let's just continue in that
2661 * case */
2662 if (fd < 0)
2663 return log_error_errno(fd, "Failed to accept() from listening socket: %m");
2664
2665 if (now(CLOCK_MONOTONIC) <= usec_add(n, PRESSURE_SLEEP_TIME_USEC)) {
2666 /* We only slept a very short time? If so, let's see if there are more sockets
2667 * pending, and if so, let's ask our parent for more workers */
2668
2669 r = fd_wait_for_event(listen_fd, POLLIN, 0);
2670 if (r < 0)
2671 return log_error_errno(r, "Failed to test for POLLIN on listening socket: %m");
2672
2673 if (FLAGS_SET(r, POLLIN)) {
2674 r = pidref_kill(&parent, SIGUSR2);
2675 if (r == -ESRCH)
2676 return log_error_errno(r, "Parent already died?");
2677 if (r < 0)
2678 return log_error_errno(r, "Failed to send SIGUSR2 signal to parent: %m");
2679 }
2680 }
2681
2682 (void) process_connection(server, TAKE_FD(fd));
2683 last_busy_usec = USEC_INFINITY;
2684 }
2685
2686 return 0;
2687 }
2688
2689 DEFINE_MAIN_FUNCTION(run);