]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/nspawn/nspawn-cgroup.c
Merge pull request #15794 from poettering/pam-sudo-fixes-part2
[thirdparty/systemd.git] / src / nspawn / nspawn-cgroup.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <sys/mount.h>
4
5 #include "alloc-util.h"
6 #include "cgroup-setup.h"
7 #include "fd-util.h"
8 #include "fileio.h"
9 #include "format-util.h"
10 #include "fs-util.h"
11 #include "mkdir.h"
12 #include "mount-util.h"
13 #include "mountpoint-util.h"
14 #include "nspawn-cgroup.h"
15 #include "nspawn-mount.h"
16 #include "path-util.h"
17 #include "rm-rf.h"
18 #include "string-util.h"
19 #include "strv.h"
20 #include "user-util.h"
21 #include "util.h"
22
23 static int chown_cgroup_path(const char *path, uid_t uid_shift) {
24 _cleanup_close_ int fd = -1;
25 const char *fn;
26
27 fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
28 if (fd < 0)
29 return -errno;
30
31 FOREACH_STRING(fn,
32 ".",
33 "cgroup.clone_children",
34 "cgroup.controllers",
35 "cgroup.events",
36 "cgroup.procs",
37 "cgroup.stat",
38 "cgroup.subtree_control",
39 "cgroup.threads",
40 "notify_on_release",
41 "tasks")
42 if (fchownat(fd, fn, uid_shift, uid_shift, 0) < 0)
43 log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
44 "Failed to chown \"%s/%s\", ignoring: %m", path, fn);
45
46 return 0;
47 }
48
49 int chown_cgroup(pid_t pid, CGroupUnified unified_requested, uid_t uid_shift) {
50 _cleanup_free_ char *path = NULL, *fs = NULL;
51 int r;
52
53 r = cg_pid_get_path(NULL, pid, &path);
54 if (r < 0)
55 return log_error_errno(r, "Failed to get container cgroup path: %m");
56
57 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, path, NULL, &fs);
58 if (r < 0)
59 return log_error_errno(r, "Failed to get file system path for container cgroup: %m");
60
61 r = chown_cgroup_path(fs, uid_shift);
62 if (r < 0)
63 return log_error_errno(r, "Failed to chown() cgroup %s: %m", fs);
64
65 if (unified_requested == CGROUP_UNIFIED_SYSTEMD || (unified_requested == CGROUP_UNIFIED_NONE && cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) > 0)) {
66 _cleanup_free_ char *lfs = NULL;
67 /* Always propagate access rights from unified to legacy controller */
68
69 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, NULL, &lfs);
70 if (r < 0)
71 return log_error_errno(r, "Failed to get file system path for container cgroup: %m");
72
73 r = chown_cgroup_path(lfs, uid_shift);
74 if (r < 0)
75 return log_error_errno(r, "Failed to chown() cgroup %s: %m", lfs);
76 }
77
78 return 0;
79 }
80
81 int sync_cgroup(pid_t pid, CGroupUnified unified_requested, uid_t uid_shift) {
82 _cleanup_free_ char *cgroup = NULL;
83 char tree[] = "/tmp/unifiedXXXXXX", pid_string[DECIMAL_STR_MAX(pid) + 1];
84 bool undo_mount = false;
85 const char *fn;
86 int r, unified_controller;
87
88 unified_controller = cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER);
89 if (unified_controller < 0)
90 return log_error_errno(unified_controller, "Failed to determine whether the systemd hierarchy is unified: %m");
91 if ((unified_controller > 0) == (unified_requested >= CGROUP_UNIFIED_SYSTEMD))
92 return 0;
93
94 /* When the host uses the legacy cgroup setup, but the
95 * container shall use the unified hierarchy, let's make sure
96 * we copy the path from the name=systemd hierarchy into the
97 * unified hierarchy. Similar for the reverse situation. */
98
99 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
100 if (r < 0)
101 return log_error_errno(r, "Failed to get control group of " PID_FMT ": %m", pid);
102
103 /* In order to access the unified hierarchy we need to mount it */
104 if (!mkdtemp(tree))
105 return log_error_errno(errno, "Failed to generate temporary mount point for unified hierarchy: %m");
106
107 if (unified_controller > 0)
108 r = mount_verbose(LOG_ERR, "cgroup", tree, "cgroup",
109 MS_NOSUID|MS_NOEXEC|MS_NODEV, "none,name=systemd,xattr");
110 else
111 r = mount_verbose(LOG_ERR, "cgroup", tree, "cgroup2",
112 MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
113 if (r < 0)
114 goto finish;
115
116 undo_mount = true;
117
118 /* If nspawn dies abruptly the cgroup hierarchy created below
119 * its unit isn't cleaned up. So, let's remove it
120 * https://github.com/systemd/systemd/pull/4223#issuecomment-252519810 */
121 fn = strjoina(tree, cgroup);
122 (void) rm_rf(fn, REMOVE_ROOT|REMOVE_ONLY_DIRECTORIES);
123
124 fn = strjoina(tree, cgroup, "/cgroup.procs");
125
126 sprintf(pid_string, PID_FMT, pid);
127 r = write_string_file(fn, pid_string, WRITE_STRING_FILE_DISABLE_BUFFER|WRITE_STRING_FILE_MKDIR_0755);
128 if (r < 0) {
129 log_error_errno(r, "Failed to move process: %m");
130 goto finish;
131 }
132
133 fn = strjoina(tree, cgroup);
134 r = chown_cgroup_path(fn, uid_shift);
135 if (r < 0)
136 log_error_errno(r, "Failed to chown() cgroup %s: %m", fn);
137 finish:
138 if (undo_mount)
139 (void) umount_verbose(tree);
140
141 (void) rmdir(tree);
142 return r;
143 }
144
145 int create_subcgroup(pid_t pid, bool keep_unit, CGroupUnified unified_requested) {
146 _cleanup_free_ char *cgroup = NULL;
147 CGroupMask supported;
148 const char *payload;
149 int r;
150
151 assert(pid > 1);
152
153 /* In the unified hierarchy inner nodes may only contain subgroups, but not processes. Hence, if we running in
154 * the unified hierarchy and the container does the same, and we did not create a scope unit for the container
155 * move us and the container into two separate subcgroups.
156 *
157 * Moreover, container payloads such as systemd try to manage the cgroup they run in in full (i.e. including
158 * its attributes), while the host systemd will only delegate cgroups for children of the cgroup created for a
159 * delegation unit, instead of the cgroup itself. This means, if we'd pass on the cgroup allocated from the
160 * host systemd directly to the payload, the host and payload systemd might fight for the cgroup
161 * attributes. Hence, let's insert an intermediary cgroup to cover that case too.
162 *
163 * Note that we only bother with the main hierarchy here, not with any secondary ones. On the unified setup
164 * that's fine because there's only one hierarchy anyway and controllers are enabled directly on it. On the
165 * legacy setup, this is fine too, since delegation of controllers is generally not safe there, hence we won't
166 * do it. */
167
168 r = cg_mask_supported(&supported);
169 if (r < 0)
170 return log_error_errno(r, "Failed to determine supported controllers: %m");
171
172 if (keep_unit)
173 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 0, &cgroup);
174 else
175 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
176 if (r < 0)
177 return log_error_errno(r, "Failed to get our control group: %m");
178
179 payload = strjoina(cgroup, "/payload");
180 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, payload, pid);
181 if (r < 0)
182 return log_error_errno(r, "Failed to create %s subcgroup: %m", payload);
183
184 if (keep_unit) {
185 const char *supervisor;
186
187 supervisor = strjoina(cgroup, "/supervisor");
188 r = cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER, supervisor, 0);
189 if (r < 0)
190 return log_error_errno(r, "Failed to create %s subcgroup: %m", supervisor);
191 }
192
193 /* Try to enable as many controllers as possible for the new payload. */
194 (void) cg_enable_everywhere(supported, supported, cgroup, NULL);
195 return 0;
196 }
197
198 /* Retrieve existing subsystems. This function is called in a new cgroup
199 * namespace.
200 */
201 static int get_process_controllers(Set **ret) {
202 _cleanup_set_free_ Set *controllers = NULL;
203 _cleanup_fclose_ FILE *f = NULL;
204 int r;
205
206 assert(ret);
207
208 f = fopen("/proc/self/cgroup", "re");
209 if (!f)
210 return errno == ENOENT ? -ESRCH : -errno;
211
212 for (;;) {
213 _cleanup_free_ char *line = NULL;
214 char *e, *l;
215
216 r = read_line(f, LONG_LINE_MAX, &line);
217 if (r < 0)
218 return r;
219 if (r == 0)
220 break;
221
222 l = strchr(line, ':');
223 if (!l)
224 continue;
225
226 l++;
227 e = strchr(l, ':');
228 if (!e)
229 continue;
230
231 *e = 0;
232
233 if (STR_IN_SET(l, "", "name=systemd", "name=unified"))
234 continue;
235
236 r = set_put_strdup(&controllers, l);
237 if (r < 0)
238 return r;
239 }
240
241 *ret = TAKE_PTR(controllers);
242
243 return 0;
244 }
245
246 static int mount_legacy_cgroup_hierarchy(
247 const char *dest,
248 const char *controller,
249 const char *hierarchy,
250 bool read_only) {
251
252 const char *to, *fstype, *opts;
253 int r;
254
255 to = strjoina(strempty(dest), "/sys/fs/cgroup/", hierarchy);
256
257 r = path_is_mount_point(to, dest, 0);
258 if (r < 0 && r != -ENOENT)
259 return log_error_errno(r, "Failed to determine if %s is mounted already: %m", to);
260 if (r > 0)
261 return 0;
262
263 (void) mkdir_p(to, 0755);
264
265 /* The superblock mount options of the mount point need to be
266 * identical to the hosts', and hence writable... */
267 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER_HYBRID)) {
268 fstype = "cgroup2";
269 opts = NULL;
270 } else if (streq(controller, SYSTEMD_CGROUP_CONTROLLER_LEGACY)) {
271 fstype = "cgroup";
272 opts = "none,name=systemd,xattr";
273 } else {
274 fstype = "cgroup";
275 opts = controller;
276 }
277
278 r = mount_verbose(LOG_ERR, "cgroup", to, fstype, MS_NOSUID|MS_NOEXEC|MS_NODEV, opts);
279 if (r < 0)
280 return r;
281
282 /* ... hence let's only make the bind mount read-only, not the superblock. */
283 if (read_only) {
284 r = mount_verbose(LOG_ERR, NULL, to, NULL,
285 MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, NULL);
286 if (r < 0)
287 return r;
288 }
289
290 return 1;
291 }
292
293 /* Mount a legacy cgroup hierarchy when cgroup namespaces are supported. */
294 static int mount_legacy_cgns_supported(
295 const char *dest,
296 CGroupUnified unified_requested,
297 bool userns,
298 uid_t uid_shift,
299 uid_t uid_range,
300 const char *selinux_apifs_context) {
301
302 _cleanup_set_free_ Set *controllers = NULL;
303 const char *cgroup_root = "/sys/fs/cgroup", *c;
304 int r;
305
306 (void) mkdir_p(cgroup_root, 0755);
307
308 /* Mount a tmpfs to /sys/fs/cgroup if it's not mounted there yet. */
309 r = path_is_mount_point(cgroup_root, dest, AT_SYMLINK_FOLLOW);
310 if (r < 0)
311 return log_error_errno(r, "Failed to determine if /sys/fs/cgroup is already mounted: %m");
312 if (r == 0) {
313 _cleanup_free_ char *options = NULL;
314
315 /* When cgroup namespaces are enabled and user namespaces are
316 * used then the mount of the cgroupfs is done *inside* the new
317 * user namespace. We're root in the new user namespace and the
318 * kernel will happily translate our uid/gid to the correct
319 * uid/gid as seen from e.g. /proc/1/mountinfo. So we simply
320 * pass uid 0 and not uid_shift to tmpfs_patch_options().
321 */
322 r = tmpfs_patch_options("mode=755" TMPFS_LIMITS_SYS_FS_CGROUP, 0, selinux_apifs_context, &options);
323 if (r < 0)
324 return log_oom();
325
326 r = mount_verbose(LOG_ERR, "tmpfs", cgroup_root, "tmpfs",
327 MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME, options);
328 if (r < 0)
329 return r;
330 }
331
332 r = cg_all_unified();
333 if (r < 0)
334 return r;
335 if (r > 0)
336 goto skip_controllers;
337
338 r = get_process_controllers(&controllers);
339 if (r < 0)
340 return log_error_errno(r, "Failed to determine cgroup controllers: %m");
341
342 for (;;) {
343 _cleanup_free_ const char *controller = NULL;
344
345 controller = set_steal_first(controllers);
346 if (!controller)
347 break;
348
349 r = mount_legacy_cgroup_hierarchy("", controller, controller, !userns);
350 if (r < 0)
351 return r;
352
353 /* When multiple hierarchies are co-mounted, make their
354 * constituting individual hierarchies a symlink to the
355 * co-mount.
356 */
357 c = controller;
358 for (;;) {
359 _cleanup_free_ char *target = NULL, *tok = NULL;
360
361 r = extract_first_word(&c, &tok, ",", 0);
362 if (r < 0)
363 return log_error_errno(r, "Failed to extract co-mounted cgroup controller: %m");
364 if (r == 0)
365 break;
366
367 if (streq(controller, tok))
368 break;
369
370 target = path_join("/sys/fs/cgroup/", tok);
371 if (!target)
372 return log_oom();
373
374 r = symlink_idempotent(controller, target, false);
375 if (r == -EINVAL)
376 return log_error_errno(r, "Invalid existing symlink for combined hierarchy: %m");
377 if (r < 0)
378 return log_error_errno(r, "Failed to create symlink for combined hierarchy: %m");
379 }
380 }
381
382 skip_controllers:
383 if (unified_requested >= CGROUP_UNIFIED_SYSTEMD) {
384 r = mount_legacy_cgroup_hierarchy("", SYSTEMD_CGROUP_CONTROLLER_HYBRID, "unified", false);
385 if (r < 0)
386 return r;
387 }
388
389 r = mount_legacy_cgroup_hierarchy("", SYSTEMD_CGROUP_CONTROLLER_LEGACY, "systemd", false);
390 if (r < 0)
391 return r;
392
393 if (!userns)
394 return mount_verbose(LOG_ERR, NULL, cgroup_root, NULL,
395 MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME|MS_RDONLY, "mode=755");
396
397 return 0;
398 }
399
400 /* Mount legacy cgroup hierarchy when cgroup namespaces are unsupported. */
401 static int mount_legacy_cgns_unsupported(
402 const char *dest,
403 CGroupUnified unified_requested,
404 bool userns,
405 uid_t uid_shift,
406 uid_t uid_range,
407 const char *selinux_apifs_context) {
408
409 _cleanup_set_free_free_ Set *controllers = NULL;
410 const char *cgroup_root;
411 int r;
412
413 cgroup_root = prefix_roota(dest, "/sys/fs/cgroup");
414
415 (void) mkdir_p(cgroup_root, 0755);
416
417 /* Mount a tmpfs to /sys/fs/cgroup if it's not mounted there yet. */
418 r = path_is_mount_point(cgroup_root, dest, AT_SYMLINK_FOLLOW);
419 if (r < 0)
420 return log_error_errno(r, "Failed to determine if /sys/fs/cgroup is already mounted: %m");
421 if (r == 0) {
422 _cleanup_free_ char *options = NULL;
423
424 r = tmpfs_patch_options("mode=755" TMPFS_LIMITS_SYS_FS_CGROUP, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &options);
425 if (r < 0)
426 return log_oom();
427
428 r = mount_verbose(LOG_ERR, "tmpfs", cgroup_root, "tmpfs",
429 MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME, options);
430 if (r < 0)
431 return r;
432 }
433
434 r = cg_all_unified();
435 if (r < 0)
436 return r;
437 if (r > 0)
438 goto skip_controllers;
439
440 r = cg_kernel_controllers(&controllers);
441 if (r < 0)
442 return log_error_errno(r, "Failed to determine cgroup controllers: %m");
443
444 for (;;) {
445 _cleanup_free_ char *controller = NULL, *origin = NULL, *combined = NULL;
446
447 controller = set_steal_first(controllers);
448 if (!controller)
449 break;
450
451 origin = path_join("/sys/fs/cgroup/", controller);
452 if (!origin)
453 return log_oom();
454
455 r = readlink_malloc(origin, &combined);
456 if (r == -EINVAL) {
457 /* Not a symbolic link, but directly a single cgroup hierarchy */
458
459 r = mount_legacy_cgroup_hierarchy(dest, controller, controller, true);
460 if (r < 0)
461 return r;
462
463 } else if (r < 0)
464 return log_error_errno(r, "Failed to read link %s: %m", origin);
465 else {
466 _cleanup_free_ char *target = NULL;
467
468 target = path_join(dest, origin);
469 if (!target)
470 return log_oom();
471
472 /* A symbolic link, a combination of controllers in one hierarchy */
473
474 if (!filename_is_valid(combined)) {
475 log_warning("Ignoring invalid combined hierarchy %s.", combined);
476 continue;
477 }
478
479 r = mount_legacy_cgroup_hierarchy(dest, combined, combined, true);
480 if (r < 0)
481 return r;
482
483 r = symlink_idempotent(combined, target, false);
484 if (r == -EINVAL)
485 return log_error_errno(r, "Invalid existing symlink for combined hierarchy: %m");
486 if (r < 0)
487 return log_error_errno(r, "Failed to create symlink for combined hierarchy: %m");
488 }
489 }
490
491 skip_controllers:
492 if (unified_requested >= CGROUP_UNIFIED_SYSTEMD) {
493 r = mount_legacy_cgroup_hierarchy(dest, SYSTEMD_CGROUP_CONTROLLER_HYBRID, "unified", false);
494 if (r < 0)
495 return r;
496 }
497
498 r = mount_legacy_cgroup_hierarchy(dest, SYSTEMD_CGROUP_CONTROLLER_LEGACY, "systemd", false);
499 if (r < 0)
500 return r;
501
502 return mount_verbose(LOG_ERR, NULL, cgroup_root, NULL,
503 MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME|MS_RDONLY, "mode=755");
504 }
505
506 static int mount_unified_cgroups(const char *dest) {
507 const char *p;
508 int r;
509
510 assert(dest);
511
512 p = prefix_roota(dest, "/sys/fs/cgroup");
513
514 (void) mkdir_p(p, 0755);
515
516 r = path_is_mount_point(p, dest, AT_SYMLINK_FOLLOW);
517 if (r < 0)
518 return log_error_errno(r, "Failed to determine if %s is mounted already: %m", p);
519 if (r > 0) {
520 p = prefix_roota(dest, "/sys/fs/cgroup/cgroup.procs");
521 if (access(p, F_OK) >= 0)
522 return 0;
523 if (errno != ENOENT)
524 return log_error_errno(errno, "Failed to determine if mount point %s contains the unified cgroup hierarchy: %m", p);
525
526 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
527 "%s is already mounted but not a unified cgroup hierarchy. Refusing.", p);
528 }
529
530 return mount_verbose(LOG_ERR, "cgroup", p, "cgroup2", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
531 }
532
533 int mount_cgroups(
534 const char *dest,
535 CGroupUnified unified_requested,
536 bool userns,
537 uid_t uid_shift,
538 uid_t uid_range,
539 const char *selinux_apifs_context,
540 bool use_cgns) {
541
542 if (unified_requested >= CGROUP_UNIFIED_ALL)
543 return mount_unified_cgroups(dest);
544 if (use_cgns)
545 return mount_legacy_cgns_supported(dest, unified_requested, userns, uid_shift, uid_range, selinux_apifs_context);
546
547 return mount_legacy_cgns_unsupported(dest, unified_requested, userns, uid_shift, uid_range, selinux_apifs_context);
548 }
549
550 static int mount_systemd_cgroup_writable_one(const char *root, const char *own) {
551 int r;
552
553 assert(root);
554 assert(own);
555
556 /* Make our own cgroup a (writable) bind mount */
557 r = mount_verbose(LOG_ERR, own, own, NULL, MS_BIND, NULL);
558 if (r < 0)
559 return r;
560
561 /* And then remount the systemd cgroup root read-only */
562 return mount_verbose(LOG_ERR, NULL, root, NULL,
563 MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, NULL);
564 }
565
566 int mount_systemd_cgroup_writable(
567 const char *dest,
568 CGroupUnified unified_requested) {
569
570 _cleanup_free_ char *own_cgroup_path = NULL;
571 const char *root, *own;
572 int r;
573
574 assert(dest);
575
576 r = cg_pid_get_path(NULL, 0, &own_cgroup_path);
577 if (r < 0)
578 return log_error_errno(r, "Failed to determine our own cgroup path: %m");
579
580 /* If we are living in the top-level, then there's nothing to do... */
581 if (path_equal(own_cgroup_path, "/"))
582 return 0;
583
584 if (unified_requested >= CGROUP_UNIFIED_ALL) {
585
586 root = prefix_roota(dest, "/sys/fs/cgroup");
587 own = strjoina(root, own_cgroup_path);
588
589 } else {
590
591 if (unified_requested >= CGROUP_UNIFIED_SYSTEMD) {
592 root = prefix_roota(dest, "/sys/fs/cgroup/unified");
593 own = strjoina(root, own_cgroup_path);
594
595 r = mount_systemd_cgroup_writable_one(root, own);
596 if (r < 0)
597 return r;
598 }
599
600 root = prefix_roota(dest, "/sys/fs/cgroup/systemd");
601 own = strjoina(root, own_cgroup_path);
602 }
603
604 return mount_systemd_cgroup_writable_one(root, own);
605 }