]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/nspawn/nspawn-mount.c
nspawn: don't require chown() if userns is not on
[thirdparty/systemd.git] / src / nspawn / nspawn-mount.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2015 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <sys/mount.h>
21 #include <linux/magic.h>
22
23 #include "alloc-util.h"
24 #include "escape.h"
25 #include "fd-util.h"
26 #include "fileio.h"
27 #include "fs-util.h"
28 #include "label.h"
29 #include "mkdir.h"
30 #include "mount-util.h"
31 #include "nspawn-mount.h"
32 #include "parse-util.h"
33 #include "path-util.h"
34 #include "rm-rf.h"
35 #include "set.h"
36 #include "stat-util.h"
37 #include "string-util.h"
38 #include "strv.h"
39 #include "user-util.h"
40 #include "util.h"
41
42 CustomMount* custom_mount_add(CustomMount **l, unsigned *n, CustomMountType t) {
43 CustomMount *c, *ret;
44
45 assert(l);
46 assert(n);
47 assert(t >= 0);
48 assert(t < _CUSTOM_MOUNT_TYPE_MAX);
49
50 c = realloc(*l, (*n + 1) * sizeof(CustomMount));
51 if (!c)
52 return NULL;
53
54 *l = c;
55 ret = *l + *n;
56 (*n)++;
57
58 *ret = (CustomMount) { .type = t };
59
60 return ret;
61 }
62
63 void custom_mount_free_all(CustomMount *l, unsigned n) {
64 unsigned i;
65
66 for (i = 0; i < n; i++) {
67 CustomMount *m = l + i;
68
69 free(m->source);
70 free(m->destination);
71 free(m->options);
72
73 if (m->work_dir) {
74 (void) rm_rf(m->work_dir, REMOVE_ROOT|REMOVE_PHYSICAL);
75 free(m->work_dir);
76 }
77
78 strv_free(m->lower);
79 }
80
81 free(l);
82 }
83
84 int custom_mount_compare(const void *a, const void *b) {
85 const CustomMount *x = a, *y = b;
86 int r;
87
88 r = path_compare(x->destination, y->destination);
89 if (r != 0)
90 return r;
91
92 if (x->type < y->type)
93 return -1;
94 if (x->type > y->type)
95 return 1;
96
97 return 0;
98 }
99
100 int bind_mount_parse(CustomMount **l, unsigned *n, const char *s, bool read_only) {
101 _cleanup_free_ char *source = NULL, *destination = NULL, *opts = NULL;
102 const char *p = s;
103 CustomMount *m;
104 int r;
105
106 assert(l);
107 assert(n);
108
109 r = extract_many_words(&p, ":", EXTRACT_DONT_COALESCE_SEPARATORS, &source, &destination, NULL);
110 if (r < 0)
111 return r;
112 if (r == 0)
113 return -EINVAL;
114
115 if (r == 1) {
116 destination = strdup(source);
117 if (!destination)
118 return -ENOMEM;
119 }
120
121 if (r == 2 && !isempty(p)) {
122 opts = strdup(p);
123 if (!opts)
124 return -ENOMEM;
125 }
126
127 if (!path_is_absolute(source))
128 return -EINVAL;
129
130 if (!path_is_absolute(destination))
131 return -EINVAL;
132
133 m = custom_mount_add(l, n, CUSTOM_MOUNT_BIND);
134 if (!m)
135 return log_oom();
136
137 m->source = source;
138 m->destination = destination;
139 m->read_only = read_only;
140 m->options = opts;
141
142 source = destination = opts = NULL;
143 return 0;
144 }
145
146 int tmpfs_mount_parse(CustomMount **l, unsigned *n, const char *s) {
147 _cleanup_free_ char *path = NULL, *opts = NULL;
148 const char *p = s;
149 CustomMount *m;
150 int r;
151
152 assert(l);
153 assert(n);
154 assert(s);
155
156 r = extract_first_word(&p, &path, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
157 if (r < 0)
158 return r;
159 if (r == 0)
160 return -EINVAL;
161
162 if (isempty(p))
163 opts = strdup("mode=0755");
164 else
165 opts = strdup(p);
166 if (!opts)
167 return -ENOMEM;
168
169 if (!path_is_absolute(path))
170 return -EINVAL;
171
172 m = custom_mount_add(l, n, CUSTOM_MOUNT_TMPFS);
173 if (!m)
174 return -ENOMEM;
175
176 m->destination = path;
177 m->options = opts;
178
179 path = opts = NULL;
180 return 0;
181 }
182
183 static int tmpfs_patch_options(
184 const char *options,
185 bool userns,
186 uid_t uid_shift, uid_t uid_range,
187 bool patch_ids,
188 const char *selinux_apifs_context,
189 char **ret) {
190
191 char *buf = NULL;
192
193 if ((userns && uid_shift != 0) || patch_ids) {
194 assert(uid_shift != UID_INVALID);
195
196 if (asprintf(&buf, "%s%suid=" UID_FMT ",gid=" UID_FMT,
197 options ?: "", options ? "," : "",
198 uid_shift, uid_shift) < 0)
199 return -ENOMEM;
200
201 options = buf;
202 }
203
204 #ifdef HAVE_SELINUX
205 if (selinux_apifs_context) {
206 char *t;
207
208 t = strjoin(options ?: "", options ? "," : "",
209 "context=\"", selinux_apifs_context, "\"");
210 free(buf);
211 if (!t)
212 return -ENOMEM;
213
214 buf = t;
215 }
216 #endif
217
218 if (!buf && options) {
219 buf = strdup(options);
220 if (!buf)
221 return -ENOMEM;
222 }
223 *ret = buf;
224
225 return !!buf;
226 }
227
228 int mount_sysfs(const char *dest, MountSettingsMask mount_settings) {
229 const char *full, *top, *x;
230 int r;
231 unsigned long extra_flags = 0;
232
233 top = prefix_roota(dest, "/sys");
234 r = path_check_fstype(top, SYSFS_MAGIC);
235 if (r < 0)
236 return log_error_errno(r, "Failed to determine filesystem type of %s: %m", top);
237 /* /sys might already be mounted as sysfs by the outer child in the
238 * !netns case. In this case, it's all good. Don't touch it because we
239 * don't have the right to do so, see https://github.com/systemd/systemd/issues/1555.
240 */
241 if (r > 0)
242 return 0;
243
244 full = prefix_roota(top, "/full");
245
246 (void) mkdir(full, 0755);
247
248 if (mount_settings & MOUNT_APPLY_APIVFS_RO)
249 extra_flags |= MS_RDONLY;
250
251 r = mount_verbose(LOG_ERR, "sysfs", full, "sysfs",
252 MS_NOSUID|MS_NOEXEC|MS_NODEV|extra_flags, NULL);
253 if (r < 0)
254 return r;
255
256 FOREACH_STRING(x, "block", "bus", "class", "dev", "devices", "kernel") {
257 _cleanup_free_ char *from = NULL, *to = NULL;
258
259 from = prefix_root(full, x);
260 if (!from)
261 return log_oom();
262
263 to = prefix_root(top, x);
264 if (!to)
265 return log_oom();
266
267 (void) mkdir(to, 0755);
268
269 r = mount_verbose(LOG_ERR, from, to, NULL, MS_BIND, NULL);
270 if (r < 0)
271 return r;
272
273 r = mount_verbose(LOG_ERR, NULL, to, NULL,
274 MS_BIND|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT|extra_flags, NULL);
275 if (r < 0)
276 return r;
277 }
278
279 r = umount_verbose(full);
280 if (r < 0)
281 return r;
282
283 if (rmdir(full) < 0)
284 return log_error_errno(errno, "Failed to remove %s: %m", full);
285
286 x = prefix_roota(top, "/fs/kdbus");
287 (void) mkdir_p(x, 0755);
288
289 /* Create mountpoint for cgroups. Otherwise we are not allowed since we
290 * remount /sys read-only.
291 */
292 if (cg_ns_supported()) {
293 x = prefix_roota(top, "/fs/cgroup");
294 (void) mkdir_p(x, 0755);
295 }
296
297 return mount_verbose(LOG_ERR, NULL, top, NULL,
298 MS_BIND|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT|extra_flags, NULL);
299 }
300
301 static int mkdir_userns(const char *path, mode_t mode, MountSettingsMask mask, uid_t uid_shift) {
302 int r;
303
304 assert(path);
305
306 r = mkdir(path, mode);
307 if (r < 0 && errno != EEXIST)
308 return -errno;
309
310 if ((mask & MOUNT_USE_USERNS) == 0)
311 return 0;
312
313 if (mask & MOUNT_IN_USERNS)
314 return 0;
315
316 r = lchown(path, uid_shift, uid_shift);
317 if (r < 0)
318 return -errno;
319
320 return 0;
321 }
322
323 static int mkdir_userns_p(const char *prefix, const char *path, mode_t mode, MountSettingsMask mask, uid_t uid_shift) {
324 const char *p, *e;
325 int r;
326
327 assert(path);
328
329 if (prefix && !path_startswith(path, prefix))
330 return -ENOTDIR;
331
332 /* create every parent directory in the path, except the last component */
333 p = path + strspn(path, "/");
334 for (;;) {
335 char t[strlen(path) + 1];
336
337 e = p + strcspn(p, "/");
338 p = e + strspn(e, "/");
339
340 /* Is this the last component? If so, then we're done */
341 if (*p == 0)
342 break;
343
344 memcpy(t, path, e - path);
345 t[e-path] = 0;
346
347 if (prefix && path_startswith(prefix, t))
348 continue;
349
350 r = mkdir_userns(t, mode, mask, uid_shift);
351 if (r < 0)
352 return r;
353 }
354
355 return mkdir_userns(path, mode, mask, uid_shift);
356 }
357
358 int mount_all(const char *dest,
359 MountSettingsMask mount_settings,
360 uid_t uid_shift, uid_t uid_range,
361 const char *selinux_apifs_context) {
362
363 typedef struct MountPoint {
364 const char *what;
365 const char *where;
366 const char *type;
367 const char *options;
368 unsigned long flags;
369 MountSettingsMask mount_settings;
370 } MountPoint;
371
372 static const MountPoint mount_table[] = {
373 /* inner child mounts */
374 { "proc", "/proc", "proc", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV, MOUNT_FATAL|MOUNT_IN_USERNS },
375 { "/proc/sys", "/proc/sys", NULL, NULL, MS_BIND, MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* Bind mount first ...*/
376 { "/proc/sys/net", "/proc/sys/net", NULL, NULL, MS_BIND, MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO|MOUNT_APPLY_APIVFS_NETNS }, /* (except for this) */
377 { NULL, "/proc/sys", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* ... then, make it r/o */
378 { "/proc/sysrq-trigger", "/proc/sysrq-trigger", NULL, NULL, MS_BIND, MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* Bind mount first ...*/
379 { NULL, "/proc/sysrq-trigger", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* ... then, make it r/o */
380 { "tmpfs", "/tmp", "tmpfs", "mode=1777", MS_STRICTATIME, MOUNT_FATAL|MOUNT_IN_USERNS },
381
382 /* outer child mounts */
383 { "tmpfs", "/sys", "tmpfs", "mode=755", MS_NOSUID|MS_NOEXEC|MS_NODEV, MOUNT_FATAL|MOUNT_APPLY_APIVFS_NETNS },
384 { "sysfs", "/sys", "sysfs", NULL, MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV, MOUNT_FATAL|MOUNT_APPLY_APIVFS_RO }, /* skipped if above was mounted */
385 { "sysfs", "/sys", "sysfs", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV, MOUNT_FATAL }, /* skipped if above was mounted */
386
387 { "tmpfs", "/dev", "tmpfs", "mode=755", MS_NOSUID|MS_STRICTATIME, MOUNT_FATAL },
388 { "tmpfs", "/dev/shm", "tmpfs", "mode=1777", MS_NOSUID|MS_NODEV|MS_STRICTATIME, MOUNT_FATAL },
389 { "tmpfs", "/run", "tmpfs", "mode=755", MS_NOSUID|MS_NODEV|MS_STRICTATIME, MOUNT_FATAL },
390 #ifdef HAVE_SELINUX
391 { "/sys/fs/selinux", "/sys/fs/selinux", NULL, NULL, MS_BIND, 0 }, /* Bind mount first */
392 { NULL, "/sys/fs/selinux", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, 0 }, /* Then, make it r/o */
393 #endif
394 };
395
396 unsigned k;
397 int r;
398 bool use_userns = (mount_settings & MOUNT_USE_USERNS);
399 bool netns = (mount_settings & MOUNT_APPLY_APIVFS_NETNS);
400 bool ro = (mount_settings & MOUNT_APPLY_APIVFS_RO);
401 bool in_userns = (mount_settings & MOUNT_IN_USERNS);
402
403 for (k = 0; k < ELEMENTSOF(mount_table); k++) {
404 _cleanup_free_ char *where = NULL, *options = NULL;
405 const char *o;
406 bool fatal = (mount_table[k].mount_settings & MOUNT_FATAL);
407
408 if (in_userns != (bool)(mount_table[k].mount_settings & MOUNT_IN_USERNS))
409 continue;
410
411 if (!netns && (bool)(mount_table[k].mount_settings & MOUNT_APPLY_APIVFS_NETNS))
412 continue;
413
414 if (!ro && (bool)(mount_table[k].mount_settings & MOUNT_APPLY_APIVFS_RO))
415 continue;
416
417 where = prefix_root(dest, mount_table[k].where);
418 if (!where)
419 return log_oom();
420
421 r = path_is_mount_point(where, AT_SYMLINK_FOLLOW);
422 if (r < 0 && r != -ENOENT)
423 return log_error_errno(r, "Failed to detect whether %s is a mount point: %m", where);
424
425 /* Skip this entry if it is not a remount. */
426 if (mount_table[k].what && r > 0)
427 continue;
428
429 r = mkdir_userns_p(dest, where, 0755, mount_settings, uid_shift);
430 if (r < 0 && r != -EEXIST) {
431 if (fatal)
432 return log_error_errno(r, "Failed to create directory %s: %m", where);
433
434 log_debug_errno(r, "Failed to create directory %s: %m", where);
435 continue;
436 }
437
438 o = mount_table[k].options;
439 if (streq_ptr(mount_table[k].type, "tmpfs")) {
440 if (in_userns)
441 r = tmpfs_patch_options(o, use_userns, 0, uid_range, true, selinux_apifs_context, &options);
442 else
443 r = tmpfs_patch_options(o, use_userns, uid_shift, uid_range, false, selinux_apifs_context, &options);
444 if (r < 0)
445 return log_oom();
446 if (r > 0)
447 o = options;
448 }
449
450 r = mount_verbose(fatal ? LOG_ERR : LOG_DEBUG,
451 mount_table[k].what,
452 where,
453 mount_table[k].type,
454 mount_table[k].flags,
455 o);
456 if (r < 0 && fatal)
457 return r;
458 }
459
460 return 0;
461 }
462
463 static int parse_mount_bind_options(const char *options, unsigned long *mount_flags, char **mount_opts) {
464 const char *p = options;
465 unsigned long flags = *mount_flags;
466 char *opts = NULL;
467
468 assert(options);
469
470 for (;;) {
471 _cleanup_free_ char *word = NULL;
472 int r = extract_first_word(&p, &word, ",", 0);
473 if (r < 0)
474 return log_error_errno(r, "Failed to extract mount option: %m");
475 if (r == 0)
476 break;
477
478 if (streq(word, "rbind"))
479 flags |= MS_REC;
480 else if (streq(word, "norbind"))
481 flags &= ~MS_REC;
482 else {
483 log_error("Invalid bind mount option: %s", word);
484 return -EINVAL;
485 }
486 }
487
488 *mount_flags = flags;
489 /* in the future mount_opts will hold string options for mount(2) */
490 *mount_opts = opts;
491
492 return 0;
493 }
494
495 static int mount_bind(const char *dest, CustomMount *m) {
496 struct stat source_st, dest_st;
497 const char *where;
498 unsigned long mount_flags = MS_BIND | MS_REC;
499 _cleanup_free_ char *mount_opts = NULL;
500 int r;
501
502 assert(m);
503
504 if (m->options) {
505 r = parse_mount_bind_options(m->options, &mount_flags, &mount_opts);
506 if (r < 0)
507 return r;
508 }
509
510 if (stat(m->source, &source_st) < 0)
511 return log_error_errno(errno, "Failed to stat %s: %m", m->source);
512
513 where = prefix_roota(dest, m->destination);
514
515 if (stat(where, &dest_st) >= 0) {
516 if (S_ISDIR(source_st.st_mode) && !S_ISDIR(dest_st.st_mode)) {
517 log_error("Cannot bind mount directory %s on file %s.", m->source, where);
518 return -EINVAL;
519 }
520
521 if (!S_ISDIR(source_st.st_mode) && S_ISDIR(dest_st.st_mode)) {
522 log_error("Cannot bind mount file %s on directory %s.", m->source, where);
523 return -EINVAL;
524 }
525
526 } else if (errno == ENOENT) {
527 r = mkdir_parents_label(where, 0755);
528 if (r < 0)
529 return log_error_errno(r, "Failed to make parents of %s: %m", where);
530
531 /* Create the mount point. Any non-directory file can be
532 * mounted on any non-directory file (regular, fifo, socket,
533 * char, block).
534 */
535 if (S_ISDIR(source_st.st_mode))
536 r = mkdir_label(where, 0755);
537 else
538 r = touch(where);
539 if (r < 0)
540 return log_error_errno(r, "Failed to create mount point %s: %m", where);
541
542 } else
543 return log_error_errno(errno, "Failed to stat %s: %m", where);
544
545 r = mount_verbose(LOG_ERR, m->source, where, NULL, mount_flags, mount_opts);
546 if (r < 0)
547 return r;
548
549 if (m->read_only) {
550 r = bind_remount_recursive(where, true, NULL);
551 if (r < 0)
552 return log_error_errno(r, "Read-only bind mount failed: %m");
553 }
554
555 return 0;
556 }
557
558 static int mount_tmpfs(
559 const char *dest,
560 CustomMount *m,
561 bool userns, uid_t uid_shift, uid_t uid_range,
562 const char *selinux_apifs_context) {
563
564 const char *where, *options;
565 _cleanup_free_ char *buf = NULL;
566 int r;
567
568 assert(dest);
569 assert(m);
570
571 where = prefix_roota(dest, m->destination);
572
573 r = mkdir_p_label(where, 0755);
574 if (r < 0 && r != -EEXIST)
575 return log_error_errno(r, "Creating mount point for tmpfs %s failed: %m", where);
576
577 r = tmpfs_patch_options(m->options, userns, uid_shift, uid_range, false, selinux_apifs_context, &buf);
578 if (r < 0)
579 return log_oom();
580 options = r > 0 ? buf : m->options;
581
582 return mount_verbose(LOG_ERR, "tmpfs", where, "tmpfs", MS_NODEV|MS_STRICTATIME, options);
583 }
584
585 static char *joined_and_escaped_lower_dirs(char * const *lower) {
586 _cleanup_strv_free_ char **sv = NULL;
587
588 sv = strv_copy(lower);
589 if (!sv)
590 return NULL;
591
592 strv_reverse(sv);
593
594 if (!strv_shell_escape(sv, ",:"))
595 return NULL;
596
597 return strv_join(sv, ":");
598 }
599
600 static int mount_overlay(const char *dest, CustomMount *m) {
601 _cleanup_free_ char *lower = NULL;
602 const char *where, *options;
603 int r;
604
605 assert(dest);
606 assert(m);
607
608 where = prefix_roota(dest, m->destination);
609
610 r = mkdir_label(where, 0755);
611 if (r < 0 && r != -EEXIST)
612 return log_error_errno(r, "Creating mount point for overlay %s failed: %m", where);
613
614 (void) mkdir_p_label(m->source, 0755);
615
616 lower = joined_and_escaped_lower_dirs(m->lower);
617 if (!lower)
618 return log_oom();
619
620 if (m->read_only) {
621 _cleanup_free_ char *escaped_source = NULL;
622
623 escaped_source = shell_escape(m->source, ",:");
624 if (!escaped_source)
625 return log_oom();
626
627 options = strjoina("lowerdir=", escaped_source, ":", lower);
628 } else {
629 _cleanup_free_ char *escaped_source = NULL, *escaped_work_dir = NULL;
630
631 assert(m->work_dir);
632 (void) mkdir_label(m->work_dir, 0700);
633
634 escaped_source = shell_escape(m->source, ",:");
635 if (!escaped_source)
636 return log_oom();
637 escaped_work_dir = shell_escape(m->work_dir, ",:");
638 if (!escaped_work_dir)
639 return log_oom();
640
641 options = strjoina("lowerdir=", lower, ",upperdir=", escaped_source, ",workdir=", escaped_work_dir);
642 }
643
644 return mount_verbose(LOG_ERR, "overlay", where, "overlay", m->read_only ? MS_RDONLY : 0, options);
645 }
646
647 int mount_custom(
648 const char *dest,
649 CustomMount *mounts, unsigned n,
650 bool userns, uid_t uid_shift, uid_t uid_range,
651 const char *selinux_apifs_context) {
652
653 unsigned i;
654 int r;
655
656 assert(dest);
657
658 for (i = 0; i < n; i++) {
659 CustomMount *m = mounts + i;
660
661 switch (m->type) {
662
663 case CUSTOM_MOUNT_BIND:
664 r = mount_bind(dest, m);
665 break;
666
667 case CUSTOM_MOUNT_TMPFS:
668 r = mount_tmpfs(dest, m, userns, uid_shift, uid_range, selinux_apifs_context);
669 break;
670
671 case CUSTOM_MOUNT_OVERLAY:
672 r = mount_overlay(dest, m);
673 break;
674
675 default:
676 assert_not_reached("Unknown custom mount type");
677 }
678
679 if (r < 0)
680 return r;
681 }
682
683 return 0;
684 }
685
686 /* Retrieve existing subsystems. This function is called in a new cgroup
687 * namespace.
688 */
689 static int get_controllers(Set *subsystems) {
690 _cleanup_fclose_ FILE *f = NULL;
691 char line[LINE_MAX];
692
693 assert(subsystems);
694
695 f = fopen("/proc/self/cgroup", "re");
696 if (!f)
697 return errno == ENOENT ? -ESRCH : -errno;
698
699 FOREACH_LINE(line, f, return -errno) {
700 int r;
701 char *e, *l, *p;
702
703 l = strchr(line, ':');
704 if (!l)
705 continue;
706
707 l++;
708 e = strchr(l, ':');
709 if (!e)
710 continue;
711
712 *e = 0;
713
714 if (STR_IN_SET(l, "", "name=systemd"))
715 continue;
716
717 p = strdup(l);
718 if (!p)
719 return -ENOMEM;
720
721 r = set_consume(subsystems, p);
722 if (r < 0)
723 return r;
724 }
725
726 return 0;
727 }
728
729 static int mount_legacy_cgroup_hierarchy(const char *dest, const char *controller, const char *hierarchy,
730 CGroupUnified unified_requested, bool read_only) {
731 const char *to, *fstype, *opts;
732 int r;
733
734 to = strjoina(strempty(dest), "/sys/fs/cgroup/", hierarchy);
735
736 r = path_is_mount_point(to, 0);
737 if (r < 0 && r != -ENOENT)
738 return log_error_errno(r, "Failed to determine if %s is mounted already: %m", to);
739 if (r > 0)
740 return 0;
741
742 mkdir_p(to, 0755);
743
744 /* The superblock mount options of the mount point need to be
745 * identical to the hosts', and hence writable... */
746 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
747 if (unified_requested >= CGROUP_UNIFIED_SYSTEMD) {
748 fstype = "cgroup2";
749 opts = NULL;
750 } else {
751 fstype = "cgroup";
752 opts = "none,name=systemd,xattr";
753 }
754 } else {
755 fstype = "cgroup";
756 opts = controller;
757 }
758
759 r = mount_verbose(LOG_ERR, "cgroup", to, fstype, MS_NOSUID|MS_NOEXEC|MS_NODEV, opts);
760 if (r < 0)
761 return r;
762
763 /* ... hence let's only make the bind mount read-only, not the superblock. */
764 if (read_only) {
765 r = mount_verbose(LOG_ERR, NULL, to, NULL,
766 MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, NULL);
767 if (r < 0)
768 return r;
769 }
770
771 return 1;
772 }
773
774 /* Mount a legacy cgroup hierarchy when cgroup namespaces are supported. */
775 static int mount_legacy_cgns_supported(
776 CGroupUnified unified_requested, bool userns, uid_t uid_shift,
777 uid_t uid_range, const char *selinux_apifs_context) {
778 _cleanup_set_free_free_ Set *controllers = NULL;
779 const char *cgroup_root = "/sys/fs/cgroup", *c;
780 int r;
781
782 (void) mkdir_p(cgroup_root, 0755);
783
784 /* Mount a tmpfs to /sys/fs/cgroup if it's not mounted there yet. */
785 r = path_is_mount_point(cgroup_root, AT_SYMLINK_FOLLOW);
786 if (r < 0)
787 return log_error_errno(r, "Failed to determine if /sys/fs/cgroup is already mounted: %m");
788 if (r == 0) {
789 _cleanup_free_ char *options = NULL;
790
791 /* When cgroup namespaces are enabled and user namespaces are
792 * used then the mount of the cgroupfs is done *inside* the new
793 * user namespace. We're root in the new user namespace and the
794 * kernel will happily translate our uid/gid to the correct
795 * uid/gid as seen from e.g. /proc/1/mountinfo. So we simply
796 * pass uid 0 and not uid_shift to tmpfs_patch_options().
797 */
798 r = tmpfs_patch_options("mode=755", userns, 0, uid_range, true, selinux_apifs_context, &options);
799 if (r < 0)
800 return log_oom();
801
802 r = mount_verbose(LOG_ERR, "tmpfs", cgroup_root, "tmpfs",
803 MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME, options);
804 if (r < 0)
805 return r;
806 }
807
808 if (cg_all_unified() > 0)
809 goto skip_controllers;
810
811 controllers = set_new(&string_hash_ops);
812 if (!controllers)
813 return log_oom();
814
815 r = get_controllers(controllers);
816 if (r < 0)
817 return log_error_errno(r, "Failed to determine cgroup controllers: %m");
818
819 for (;;) {
820 _cleanup_free_ const char *controller = NULL;
821
822 controller = set_steal_first(controllers);
823 if (!controller)
824 break;
825
826 r = mount_legacy_cgroup_hierarchy("", controller, controller, unified_requested, !userns);
827 if (r < 0)
828 return r;
829
830 /* When multiple hierarchies are co-mounted, make their
831 * constituting individual hierarchies a symlink to the
832 * co-mount.
833 */
834 c = controller;
835 for (;;) {
836 _cleanup_free_ char *target = NULL, *tok = NULL;
837
838 r = extract_first_word(&c, &tok, ",", 0);
839 if (r < 0)
840 return log_error_errno(r, "Failed to extract co-mounted cgroup controller: %m");
841 if (r == 0)
842 break;
843
844 target = prefix_root("/sys/fs/cgroup", tok);
845 if (!target)
846 return log_oom();
847
848 if (streq(controller, tok))
849 break;
850
851 r = symlink_idempotent(controller, target);
852 if (r == -EINVAL)
853 return log_error_errno(r, "Invalid existing symlink for combined hierarchy: %m");
854 if (r < 0)
855 return log_error_errno(r, "Failed to create symlink for combined hierarchy: %m");
856 }
857 }
858
859 skip_controllers:
860 r = mount_legacy_cgroup_hierarchy("", SYSTEMD_CGROUP_CONTROLLER, "systemd", unified_requested, false);
861 if (r < 0)
862 return r;
863
864 if (!userns)
865 return mount_verbose(LOG_ERR, NULL, cgroup_root, NULL,
866 MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME|MS_RDONLY, "mode=755");
867
868 return 0;
869 }
870
871 /* Mount legacy cgroup hierarchy when cgroup namespaces are unsupported. */
872 static int mount_legacy_cgns_unsupported(
873 const char *dest,
874 CGroupUnified unified_requested, bool userns, uid_t uid_shift, uid_t uid_range,
875 const char *selinux_apifs_context) {
876 _cleanup_set_free_free_ Set *controllers = NULL;
877 const char *cgroup_root;
878 int r;
879
880 cgroup_root = prefix_roota(dest, "/sys/fs/cgroup");
881
882 (void) mkdir_p(cgroup_root, 0755);
883
884 /* Mount a tmpfs to /sys/fs/cgroup if it's not mounted there yet. */
885 r = path_is_mount_point(cgroup_root, AT_SYMLINK_FOLLOW);
886 if (r < 0)
887 return log_error_errno(r, "Failed to determine if /sys/fs/cgroup is already mounted: %m");
888 if (r == 0) {
889 _cleanup_free_ char *options = NULL;
890
891 r = tmpfs_patch_options("mode=755", userns, uid_shift, uid_range, false, selinux_apifs_context, &options);
892 if (r < 0)
893 return log_oom();
894
895 r = mount_verbose(LOG_ERR, "tmpfs", cgroup_root, "tmpfs",
896 MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME, options);
897 if (r < 0)
898 return r;
899 }
900
901 if (cg_all_unified() > 0)
902 goto skip_controllers;
903
904 controllers = set_new(&string_hash_ops);
905 if (!controllers)
906 return log_oom();
907
908 r = cg_kernel_controllers(controllers);
909 if (r < 0)
910 return log_error_errno(r, "Failed to determine cgroup controllers: %m");
911
912 for (;;) {
913 _cleanup_free_ char *controller = NULL, *origin = NULL, *combined = NULL;
914
915 controller = set_steal_first(controllers);
916 if (!controller)
917 break;
918
919 origin = prefix_root("/sys/fs/cgroup/", controller);
920 if (!origin)
921 return log_oom();
922
923 r = readlink_malloc(origin, &combined);
924 if (r == -EINVAL) {
925 /* Not a symbolic link, but directly a single cgroup hierarchy */
926
927 r = mount_legacy_cgroup_hierarchy(dest, controller, controller, unified_requested, true);
928 if (r < 0)
929 return r;
930
931 } else if (r < 0)
932 return log_error_errno(r, "Failed to read link %s: %m", origin);
933 else {
934 _cleanup_free_ char *target = NULL;
935
936 target = prefix_root(dest, origin);
937 if (!target)
938 return log_oom();
939
940 /* A symbolic link, a combination of controllers in one hierarchy */
941
942 if (!filename_is_valid(combined)) {
943 log_warning("Ignoring invalid combined hierarchy %s.", combined);
944 continue;
945 }
946
947 r = mount_legacy_cgroup_hierarchy(dest, combined, combined, unified_requested, true);
948 if (r < 0)
949 return r;
950
951 r = symlink_idempotent(combined, target);
952 if (r == -EINVAL)
953 return log_error_errno(r, "Invalid existing symlink for combined hierarchy: %m");
954 if (r < 0)
955 return log_error_errno(r, "Failed to create symlink for combined hierarchy: %m");
956 }
957 }
958
959 skip_controllers:
960 r = mount_legacy_cgroup_hierarchy(dest, SYSTEMD_CGROUP_CONTROLLER, "systemd", unified_requested, false);
961 if (r < 0)
962 return r;
963
964 return mount_verbose(LOG_ERR, NULL, cgroup_root, NULL,
965 MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME|MS_RDONLY, "mode=755");
966 }
967
968 static int mount_unified_cgroups(const char *dest) {
969 const char *p;
970 int r;
971
972 assert(dest);
973
974 p = prefix_roota(dest, "/sys/fs/cgroup");
975
976 (void) mkdir_p(p, 0755);
977
978 r = path_is_mount_point(p, AT_SYMLINK_FOLLOW);
979 if (r < 0)
980 return log_error_errno(r, "Failed to determine if %s is mounted already: %m", p);
981 if (r > 0) {
982 p = prefix_roota(dest, "/sys/fs/cgroup/cgroup.procs");
983 if (access(p, F_OK) >= 0)
984 return 0;
985 if (errno != ENOENT)
986 return log_error_errno(errno, "Failed to determine if mount point %s contains the unified cgroup hierarchy: %m", p);
987
988 log_error("%s is already mounted but not a unified cgroup hierarchy. Refusing.", p);
989 return -EINVAL;
990 }
991
992 return mount_verbose(LOG_ERR, "cgroup", p, "cgroup2", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
993 }
994
995 int mount_cgroups(
996 const char *dest,
997 CGroupUnified unified_requested,
998 bool userns, uid_t uid_shift, uid_t uid_range,
999 const char *selinux_apifs_context,
1000 bool use_cgns) {
1001
1002 if (unified_requested >= CGROUP_UNIFIED_ALL)
1003 return mount_unified_cgroups(dest);
1004 else if (use_cgns)
1005 return mount_legacy_cgns_supported(unified_requested, userns, uid_shift, uid_range, selinux_apifs_context);
1006
1007 return mount_legacy_cgns_unsupported(dest, unified_requested, userns, uid_shift, uid_range, selinux_apifs_context);
1008 }
1009
1010 int mount_systemd_cgroup_writable(
1011 const char *dest,
1012 CGroupUnified unified_requested) {
1013
1014 _cleanup_free_ char *own_cgroup_path = NULL;
1015 const char *systemd_root, *systemd_own;
1016 int r;
1017
1018 assert(dest);
1019
1020 r = cg_pid_get_path(NULL, 0, &own_cgroup_path);
1021 if (r < 0)
1022 return log_error_errno(r, "Failed to determine our own cgroup path: %m");
1023
1024 /* If we are living in the top-level, then there's nothing to do... */
1025 if (path_equal(own_cgroup_path, "/"))
1026 return 0;
1027
1028 if (unified_requested >= CGROUP_UNIFIED_ALL) {
1029 systemd_own = strjoina(dest, "/sys/fs/cgroup", own_cgroup_path);
1030 systemd_root = prefix_roota(dest, "/sys/fs/cgroup");
1031 } else {
1032 systemd_own = strjoina(dest, "/sys/fs/cgroup/systemd", own_cgroup_path);
1033 systemd_root = prefix_roota(dest, "/sys/fs/cgroup/systemd");
1034 }
1035
1036 /* Make our own cgroup a (writable) bind mount */
1037 r = mount_verbose(LOG_ERR, systemd_own, systemd_own, NULL, MS_BIND, NULL);
1038 if (r < 0)
1039 return r;
1040
1041 /* And then remount the systemd cgroup root read-only */
1042 return mount_verbose(LOG_ERR, NULL, systemd_root, NULL,
1043 MS_BIND|MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_RDONLY, NULL);
1044 }
1045
1046 int setup_volatile_state(
1047 const char *directory,
1048 VolatileMode mode,
1049 bool userns, uid_t uid_shift, uid_t uid_range,
1050 const char *selinux_apifs_context) {
1051
1052 _cleanup_free_ char *buf = NULL;
1053 const char *p, *options;
1054 int r;
1055
1056 assert(directory);
1057
1058 if (mode != VOLATILE_STATE)
1059 return 0;
1060
1061 /* --volatile=state means we simply overmount /var
1062 with a tmpfs, and the rest read-only. */
1063
1064 r = bind_remount_recursive(directory, true, NULL);
1065 if (r < 0)
1066 return log_error_errno(r, "Failed to remount %s read-only: %m", directory);
1067
1068 p = prefix_roota(directory, "/var");
1069 r = mkdir(p, 0755);
1070 if (r < 0 && errno != EEXIST)
1071 return log_error_errno(errno, "Failed to create %s: %m", directory);
1072
1073 options = "mode=755";
1074 r = tmpfs_patch_options(options, userns, uid_shift, uid_range, false, selinux_apifs_context, &buf);
1075 if (r < 0)
1076 return log_oom();
1077 if (r > 0)
1078 options = buf;
1079
1080 return mount_verbose(LOG_ERR, "tmpfs", p, "tmpfs", MS_STRICTATIME, options);
1081 }
1082
1083 int setup_volatile(
1084 const char *directory,
1085 VolatileMode mode,
1086 bool userns, uid_t uid_shift, uid_t uid_range,
1087 const char *selinux_apifs_context) {
1088
1089 bool tmpfs_mounted = false, bind_mounted = false;
1090 char template[] = "/tmp/nspawn-volatile-XXXXXX";
1091 _cleanup_free_ char *buf = NULL;
1092 const char *f, *t, *options;
1093 int r;
1094
1095 assert(directory);
1096
1097 if (mode != VOLATILE_YES)
1098 return 0;
1099
1100 /* --volatile=yes means we mount a tmpfs to the root dir, and
1101 the original /usr to use inside it, and that read-only. */
1102
1103 if (!mkdtemp(template))
1104 return log_error_errno(errno, "Failed to create temporary directory: %m");
1105
1106 options = "mode=755";
1107 r = tmpfs_patch_options(options, userns, uid_shift, uid_range, false, selinux_apifs_context, &buf);
1108 if (r < 0)
1109 return log_oom();
1110 if (r > 0)
1111 options = buf;
1112
1113 r = mount_verbose(LOG_ERR, "tmpfs", template, "tmpfs", MS_STRICTATIME, options);
1114 if (r < 0)
1115 goto fail;
1116
1117 tmpfs_mounted = true;
1118
1119 f = prefix_roota(directory, "/usr");
1120 t = prefix_roota(template, "/usr");
1121
1122 r = mkdir(t, 0755);
1123 if (r < 0 && errno != EEXIST) {
1124 r = log_error_errno(errno, "Failed to create %s: %m", t);
1125 goto fail;
1126 }
1127
1128 r = mount_verbose(LOG_ERR, f, t, NULL, MS_BIND|MS_REC, NULL);
1129 if (r < 0)
1130 goto fail;
1131
1132 bind_mounted = true;
1133
1134 r = bind_remount_recursive(t, true, NULL);
1135 if (r < 0) {
1136 log_error_errno(r, "Failed to remount %s read-only: %m", t);
1137 goto fail;
1138 }
1139
1140 r = mount_verbose(LOG_ERR, template, directory, NULL, MS_MOVE, NULL);
1141 if (r < 0)
1142 goto fail;
1143
1144 (void) rmdir(template);
1145
1146 return 0;
1147
1148 fail:
1149 if (bind_mounted)
1150 (void) umount_verbose(t);
1151
1152 if (tmpfs_mounted)
1153 (void) umount_verbose(template);
1154 (void) rmdir(template);
1155 return r;
1156 }
1157
1158 VolatileMode volatile_mode_from_string(const char *s) {
1159 int b;
1160
1161 if (isempty(s))
1162 return _VOLATILE_MODE_INVALID;
1163
1164 b = parse_boolean(s);
1165 if (b > 0)
1166 return VOLATILE_YES;
1167 if (b == 0)
1168 return VOLATILE_NO;
1169
1170 if (streq(s, "state"))
1171 return VOLATILE_STATE;
1172
1173 return _VOLATILE_MODE_INVALID;
1174 }