]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/nspawn/nspawn-mount.c
nspawn: add support for owneridmap bind option
[thirdparty/systemd.git] / src / nspawn / nspawn-mount.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
e83bebef 2
4f5dd394 3#include <sys/mount.h>
07630cea 4#include <linux/magic.h>
e83bebef 5
b5efdb8a 6#include "alloc-util.h"
f461a28d 7#include "chase.h"
4f5dd394 8#include "escape.h"
0996ef00 9#include "fd-util.h"
ca78ad1d 10#include "format-util.h"
f4f15635 11#include "fs-util.h"
0690160e 12#include "label-util.h"
35cd0ba5 13#include "mkdir-label.h"
4349cd7c 14#include "mount-util.h"
049af8ad 15#include "mountpoint-util.h"
b71a0192 16#include "namespace-util.h"
6bedfcbb
LP
17#include "nspawn-mount.h"
18#include "parse-util.h"
4f5dd394
LP
19#include "path-util.h"
20#include "rm-rf.h"
e83bebef 21#include "set.h"
760877e9 22#include "sort-util.h"
8fcde012 23#include "stat-util.h"
07630cea 24#include "string-util.h"
4f5dd394 25#include "strv.h"
e4de7287 26#include "tmpfile-util.h"
ee104e11 27#include "user-util.h"
e83bebef 28
88614c8a 29CustomMount* custom_mount_add(CustomMount **l, size_t *n, CustomMountType t) {
e83bebef
LP
30 CustomMount *c, *ret;
31
32 assert(l);
33 assert(n);
34 assert(t >= 0);
35 assert(t < _CUSTOM_MOUNT_TYPE_MAX);
36
aa484f35 37 c = reallocarray(*l, *n + 1, sizeof(CustomMount));
e83bebef
LP
38 if (!c)
39 return NULL;
40
41 *l = c;
42 ret = *l + *n;
43 (*n)++;
44
511a8cfe
LP
45 *ret = (CustomMount) {
46 .type = t
47 };
e83bebef
LP
48
49 return ret;
50}
51
88614c8a 52void custom_mount_free_all(CustomMount *l, size_t n) {
d2b99ed7 53 for (size_t i = 0; i < n; i++) {
e83bebef
LP
54 CustomMount *m = l + i;
55
56 free(m->source);
57 free(m->destination);
58 free(m->options);
59
60 if (m->work_dir) {
61 (void) rm_rf(m->work_dir, REMOVE_ROOT|REMOVE_PHYSICAL);
62 free(m->work_dir);
63 }
64
c7a4890c
LP
65 if (m->rm_rf_tmpdir) {
66 (void) rm_rf(m->rm_rf_tmpdir, REMOVE_ROOT|REMOVE_PHYSICAL);
67 free(m->rm_rf_tmpdir);
68 }
69
e83bebef 70 strv_free(m->lower);
de40a303 71 free(m->type_argument);
e83bebef
LP
72 }
73
74 free(l);
75}
76
93bab288 77static int custom_mount_compare(const CustomMount *a, const CustomMount *b) {
e83bebef
LP
78 int r;
79
93bab288 80 r = path_compare(a->destination, b->destination);
e83bebef
LP
81 if (r != 0)
82 return r;
83
93bab288 84 return CMP(a->type, b->type);
e83bebef
LP
85}
86
448f7377 87static int source_path_parse(const char *p, char **ret) {
86c0dd4a 88 assert(p);
448f7377 89 assert(ret);
86c0dd4a 90
448f7377
DDM
91 if (isempty(p))
92 return -EINVAL;
93
94 if (*p == '+') {
95 if (!path_is_absolute(p + 1))
96 return -EINVAL;
97
98 char *s = strdup(p);
99 if (!s)
100 return -ENOMEM;
101
102 *ret = TAKE_PTR(s);
103 return 0;
104 }
105
106 return path_make_absolute_cwd(p, ret);
107}
108
109static int source_path_parse_nullable(const char *p, char **ret) {
110 assert(p);
111 assert(ret);
112
113 if (isempty(p)) {
114 *ret = NULL;
115 return 0;
116 }
86c0dd4a 117
448f7377 118 return source_path_parse(p, ret);
86c0dd4a
LP
119}
120
121static char *resolve_source_path(const char *dest, const char *source) {
86c0dd4a
LP
122 if (!source)
123 return NULL;
124
125 if (source[0] == '+')
c6134d3e 126 return path_join(dest, source + 1);
86c0dd4a
LP
127
128 return strdup(source);
129}
130
d0556c55
LP
131static int allocate_temporary_source(CustomMount *m) {
132 assert(m);
133 assert(!m->source);
134 assert(!m->rm_rf_tmpdir);
135
136 m->rm_rf_tmpdir = strdup("/var/tmp/nspawn-temp-XXXXXX");
137 if (!m->rm_rf_tmpdir)
138 return log_oom();
139
140 if (!mkdtemp(m->rm_rf_tmpdir)) {
141 m->rm_rf_tmpdir = mfree(m->rm_rf_tmpdir);
142 return log_error_errno(errno, "Failed to acquire temporary directory: %m");
143 }
144
145 m->source = path_join(m->rm_rf_tmpdir, "src");
146 if (!m->source)
147 return log_oom();
148
149 if (mkdir(m->source, 0755) < 0)
150 return log_error_errno(errno, "Failed to create %s: %m", m->source);
151
152 return 0;
153}
154
88614c8a 155int custom_mount_prepare_all(const char *dest, CustomMount *l, size_t n) {
86c0dd4a
LP
156 int r;
157
158 /* Prepare all custom mounts. This will make source we know all temporary directories. This is called in the
159 * parent process, so that we know the temporary directories to remove on exit before we fork off the
160 * children. */
161
162 assert(l || n == 0);
163
164 /* Order the custom mounts, and make sure we have a working directory */
93bab288 165 typesafe_qsort(l, n, custom_mount_compare);
86c0dd4a 166
d2b99ed7 167 for (size_t i = 0; i < n; i++) {
86c0dd4a
LP
168 CustomMount *m = l + i;
169
de40a303
LP
170 /* /proc we mount in the inner child, i.e. when we acquired CLONE_NEWPID. All other mounts we mount
171 * already in the outer child, so that the mounts are already established before CLONE_NEWPID and in
172 * particular CLONE_NEWUSER. This also means any custom mounts below /proc also need to be mounted in
173 * the inner child, not the outer one. Determine this here. */
174 m->in_userns = path_startswith(m->destination, "/proc");
86c0dd4a 175
de40a303
LP
176 if (m->type == CUSTOM_MOUNT_BIND) {
177 if (m->source) {
178 char *s;
86c0dd4a 179
de40a303
LP
180 s = resolve_source_path(dest, m->source);
181 if (!s)
182 return log_oom();
c7a4890c 183
de40a303
LP
184 free_and_replace(m->source, s);
185 } else {
186 /* No source specified? In that case, use a throw-away temporary directory in /var/tmp */
c7a4890c 187
d0556c55
LP
188 r = allocate_temporary_source(m);
189 if (r < 0)
190 return r;
de40a303 191 }
86c0dd4a
LP
192 }
193
194 if (m->type == CUSTOM_MOUNT_OVERLAY) {
86c0dd4a
LP
195 STRV_FOREACH(j, m->lower) {
196 char *s;
197
198 s = resolve_source_path(dest, *j);
199 if (!s)
200 return log_oom();
201
10af01a5 202 free_and_replace(*j, s);
86c0dd4a
LP
203 }
204
d0556c55
LP
205 if (m->source) {
206 char *s;
207
208 s = resolve_source_path(dest, m->source);
209 if (!s)
210 return log_oom();
211
212 free_and_replace(m->source, s);
213 } else {
214 r = allocate_temporary_source(m);
215 if (r < 0)
216 return r;
217 }
218
86c0dd4a
LP
219 if (m->work_dir) {
220 char *s;
221
222 s = resolve_source_path(dest, m->work_dir);
223 if (!s)
224 return log_oom();
225
10af01a5 226 free_and_replace(m->work_dir, s);
86c0dd4a 227 } else {
86c0dd4a
LP
228 r = tempfn_random(m->source, NULL, &m->work_dir);
229 if (r < 0)
230 return log_error_errno(r, "Failed to acquire working directory: %m");
231 }
232
233 (void) mkdir_label(m->work_dir, 0700);
234 }
235 }
236
237 return 0;
238}
239
88614c8a 240int bind_mount_parse(CustomMount **l, size_t *n, const char *s, bool read_only) {
448f7377 241 _cleanup_free_ char *source = NULL, *destination = NULL, *opts = NULL, *p = NULL;
e83bebef
LP
242 CustomMount *m;
243 int r;
244
245 assert(l);
246 assert(n);
247
a50947c5 248 r = extract_many_words(&s, ":", EXTRACT_DONT_COALESCE_SEPARATORS, &source, &destination, NULL);
e83bebef
LP
249 if (r < 0)
250 return r;
251 if (r == 0)
252 return -EINVAL;
e83bebef 253 if (r == 1) {
86c0dd4a 254 destination = strdup(source[0] == '+' ? source+1 : source);
e83bebef
LP
255 if (!destination)
256 return -ENOMEM;
257 }
a50947c5
DDM
258 if (r == 2 && !isempty(s)) {
259 opts = strdup(s);
e83bebef
LP
260 if (!opts)
261 return -ENOMEM;
262 }
263
448f7377
DDM
264 r = source_path_parse_nullable(source, &p);
265 if (r < 0)
266 return r;
c7a4890c 267
e83bebef
LP
268 if (!path_is_absolute(destination))
269 return -EINVAL;
270
271 m = custom_mount_add(l, n, CUSTOM_MOUNT_BIND);
272 if (!m)
48cbe5f8 273 return -ENOMEM;
e83bebef 274
448f7377 275 m->source = TAKE_PTR(p);
0e636bf5 276 m->destination = TAKE_PTR(destination);
e83bebef 277 m->read_only = read_only;
0e636bf5 278 m->options = TAKE_PTR(opts);
de40a303 279
e83bebef
LP
280 return 0;
281}
282
88614c8a 283int tmpfs_mount_parse(CustomMount **l, size_t *n, const char *s) {
e83bebef 284 _cleanup_free_ char *path = NULL, *opts = NULL;
99534007 285 const char *p = ASSERT_PTR(s);
e83bebef
LP
286 CustomMount *m;
287 int r;
288
289 assert(l);
290 assert(n);
e83bebef
LP
291
292 r = extract_first_word(&p, &path, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
293 if (r < 0)
294 return r;
295 if (r == 0)
296 return -EINVAL;
297
298 if (isempty(p))
299 opts = strdup("mode=0755");
300 else
301 opts = strdup(p);
302 if (!opts)
303 return -ENOMEM;
304
305 if (!path_is_absolute(path))
306 return -EINVAL;
307
308 m = custom_mount_add(l, n, CUSTOM_MOUNT_TMPFS);
309 if (!m)
310 return -ENOMEM;
311
1cc6c93a
YW
312 m->destination = TAKE_PTR(path);
313 m->options = TAKE_PTR(opts);
e83bebef 314
e83bebef
LP
315 return 0;
316}
317
88614c8a 318int overlay_mount_parse(CustomMount **l, size_t *n, const char *s, bool read_only) {
ad85779a
LP
319 _cleanup_free_ char *upper = NULL, *destination = NULL;
320 _cleanup_strv_free_ char **lower = NULL;
321 CustomMount *m;
448f7377 322 int r, k;
ad85779a 323
90e30d76 324 k = strv_split_full(&lower, s, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
86c0dd4a
LP
325 if (k < 0)
326 return k;
ad85779a
LP
327 if (k < 2)
328 return -EADDRNOTAVAIL;
329 if (k == 2) {
448f7377
DDM
330 _cleanup_free_ char *p = NULL;
331
86c0dd4a
LP
332 /* If two parameters are specified, the first one is the lower, the second one the upper directory. And
333 * we'll also define the destination mount point the same as the upper. */
334
448f7377
DDM
335 r = source_path_parse(lower[0], &p);
336 if (r < 0)
337 return r;
338
339 free_and_replace(lower[0], p);
340
341 r = source_path_parse(lower[1], &p);
342 if (r < 0)
343 return r;
344
345 free_and_replace(lower[1], p);
86c0dd4a 346
ae2a15bc 347 upper = TAKE_PTR(lower[1]);
ad85779a 348
86c0dd4a 349 destination = strdup(upper[0] == '+' ? upper+1 : upper); /* take the destination without "+" prefix */
ad85779a
LP
350 if (!destination)
351 return -ENOMEM;
ad85779a 352 } else {
448f7377
DDM
353 _cleanup_free_ char *p = NULL;
354
86c0dd4a
LP
355 /* If more than two parameters are specified, the last one is the destination, the second to last one
356 * the "upper", and all before that the "lower" directories. */
357
ad85779a 358 destination = lower[k - 1];
ae2a15bc 359 upper = TAKE_PTR(lower[k - 2]);
86c0dd4a 360
448f7377
DDM
361 STRV_FOREACH(i, lower) {
362 r = source_path_parse(*i, &p);
363 if (r < 0)
364 return r;
365
366 free_and_replace(*i, p);
367 }
c7a4890c
LP
368
369 /* If the upper directory is unspecified, then let's create it automatically as a throw-away directory
370 * in /var/tmp */
448f7377
DDM
371 r = source_path_parse_nullable(upper, &p);
372 if (r < 0)
373 return r;
374
375 free_and_replace(upper, p);
c7a4890c 376
86c0dd4a
LP
377 if (!path_is_absolute(destination))
378 return -EINVAL;
ad85779a
LP
379 }
380
381 m = custom_mount_add(l, n, CUSTOM_MOUNT_OVERLAY);
382 if (!m)
383 return -ENOMEM;
384
1cc6c93a
YW
385 m->destination = TAKE_PTR(destination);
386 m->source = TAKE_PTR(upper);
387 m->lower = TAKE_PTR(lower);
ad85779a
LP
388 m->read_only = read_only;
389
ad85779a
LP
390 return 0;
391}
392
de40a303
LP
393int inaccessible_mount_parse(CustomMount **l, size_t *n, const char *s) {
394 _cleanup_free_ char *path = NULL;
395 CustomMount *m;
396
397 assert(l);
398 assert(n);
399 assert(s);
400
401 if (!path_is_absolute(s))
402 return -EINVAL;
403
404 path = strdup(s);
405 if (!path)
406 return -ENOMEM;
407
408 m = custom_mount_add(l, n, CUSTOM_MOUNT_INACCESSIBLE);
409 if (!m)
410 return -ENOMEM;
411
412 m->destination = TAKE_PTR(path);
413 return 0;
414}
415
04029482 416int tmpfs_patch_options(
e83bebef 417 const char *options,
2fa017f1 418 uid_t uid_shift,
e83bebef
LP
419 const char *selinux_apifs_context,
420 char **ret) {
421
cfea7618 422 _cleanup_free_ char *buf = NULL;
e83bebef 423
cfea7618 424 assert(ret);
e83bebef 425
cfea7618
YW
426 if (options) {
427 buf = strdup(options);
428 if (!buf)
429 return -ENOMEM;
e83bebef
LP
430 }
431
cfea7618
YW
432 if (uid_shift != UID_INVALID)
433 if (strextendf_with_separator(&buf, ",", "uid=" UID_FMT ",gid=" UID_FMT, uid_shift, uid_shift) < 0)
e83bebef 434 return -ENOMEM;
e83bebef 435
cfea7618
YW
436#if HAVE_SELINUX
437 if (selinux_apifs_context)
d3d15594 438 if (strextendf_with_separator(&buf, ",", "context=\"%s\"", selinux_apifs_context) < 0)
0996ef00 439 return -ENOMEM;
cfea7618 440#endif
0996ef00 441
cfea7618
YW
442 *ret = TAKE_PTR(buf);
443 return !!*ret;
e83bebef
LP
444}
445
4f086aab 446int mount_sysfs(const char *dest, MountSettingsMask mount_settings) {
5980d463 447 const char *full, *top;
d1678248 448 int r;
4f086aab 449 unsigned long extra_flags = 0;
d8fc6a00
LP
450
451 top = prefix_roota(dest, "/sys");
40fd52f2 452 r = path_is_fs_type(top, SYSFS_MAGIC);
d1678248
ILG
453 if (r < 0)
454 return log_error_errno(r, "Failed to determine filesystem type of %s: %m", top);
455 /* /sys might already be mounted as sysfs by the outer child in the
456 * !netns case. In this case, it's all good. Don't touch it because we
457 * don't have the right to do so, see https://github.com/systemd/systemd/issues/1555.
458 */
459 if (r > 0)
460 return 0;
461
d8fc6a00
LP
462 full = prefix_roota(top, "/full");
463
464 (void) mkdir(full, 0755);
465
bd6609eb 466 if (FLAGS_SET(mount_settings, MOUNT_APPLY_APIVFS_RO))
4f086aab
SU
467 extra_flags |= MS_RDONLY;
468
511a8cfe
LP
469 r = mount_nofollow_verbose(LOG_ERR, "sysfs", full, "sysfs",
470 MS_NOSUID|MS_NOEXEC|MS_NODEV|extra_flags, NULL);
60e76d48
ZJS
471 if (r < 0)
472 return r;
d8fc6a00
LP
473
474 FOREACH_STRING(x, "block", "bus", "class", "dev", "devices", "kernel") {
475 _cleanup_free_ char *from = NULL, *to = NULL;
476
c6134d3e 477 from = path_join(full, x);
d8fc6a00
LP
478 if (!from)
479 return log_oom();
480
c6134d3e 481 to = path_join(top, x);
d8fc6a00
LP
482 if (!to)
483 return log_oom();
484
485 (void) mkdir(to, 0755);
486
511a8cfe 487 r = mount_nofollow_verbose(LOG_ERR, from, to, NULL, MS_BIND, NULL);
60e76d48
ZJS
488 if (r < 0)
489 return r;
d8fc6a00 490
511a8cfe
LP
491 r = mount_nofollow_verbose(LOG_ERR, NULL, to, NULL,
492 MS_BIND|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT|extra_flags, NULL);
60e76d48
ZJS
493 if (r < 0)
494 return r;
d8fc6a00
LP
495 }
496
30f5d104 497 r = umount_verbose(LOG_ERR, full, UMOUNT_NOFOLLOW);
60e76d48
ZJS
498 if (r < 0)
499 return r;
d8fc6a00
LP
500
501 if (rmdir(full) < 0)
502 return log_error_errno(errno, "Failed to remove %s: %m", full);
503
0996ef00
CB
504 /* Create mountpoint for cgroups. Otherwise we are not allowed since we
505 * remount /sys read-only.
506 */
5980d463 507 const char *x = prefix_roota(top, "/fs/cgroup");
677a72cd 508 (void) mkdir_p(x, 0755);
d8fc6a00 509
511a8cfe
LP
510 return mount_nofollow_verbose(LOG_ERR, NULL, top, NULL,
511 MS_BIND|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT|extra_flags, NULL);
d8fc6a00
LP
512}
513
b71a0192
CB
514#define PROC_DEFAULT_MOUNT_FLAGS (MS_NOSUID|MS_NOEXEC|MS_NODEV)
515#define SYS_DEFAULT_MOUNT_FLAGS (MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV)
516
e83bebef 517int mount_all(const char *dest,
4f086aab 518 MountSettingsMask mount_settings,
2fa017f1 519 uid_t uid_shift,
e83bebef
LP
520 const char *selinux_apifs_context) {
521
de40a303
LP
522#define PROC_INACCESSIBLE_REG(path) \
523 { "/run/systemd/inaccessible/reg", (path), NULL, NULL, MS_BIND, \
524 MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* Bind mount first ... */ \
d4b653c5
LP
525 { NULL, (path), NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, \
526 MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO } /* Then, make it r/o */
527
528#define PROC_READ_ONLY(path) \
529 { (path), (path), NULL, NULL, MS_BIND, \
530 MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* Bind mount first ... */ \
531 { NULL, (path), NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT, \
532 MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO } /* Then, make it r/o */
533
e83bebef
LP
534 typedef struct MountPoint {
535 const char *what;
536 const char *where;
537 const char *type;
538 const char *options;
539 unsigned long flags;
4f086aab 540 MountSettingsMask mount_settings;
e83bebef
LP
541 } MountPoint;
542
543 static const MountPoint mount_table[] = {
d4b653c5 544 /* First we list inner child mounts (i.e. mounts applied *after* entering user namespacing) */
b71a0192 545 { "proc", "/proc", "proc", NULL, PROC_DEFAULT_MOUNT_FLAGS,
511a8cfe 546 MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_MKDIR|MOUNT_FOLLOW_SYMLINKS }, /* we follow symlinks here since not following them requires /proc/ already being mounted, which we don't have here. */
d4b653c5
LP
547
548 { "/proc/sys", "/proc/sys", NULL, NULL, MS_BIND,
549 MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* Bind mount first ... */
550
551 { "/proc/sys/net", "/proc/sys/net", NULL, NULL, MS_BIND,
552 MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO|MOUNT_APPLY_APIVFS_NETNS }, /* (except for this) */
553
554 { NULL, "/proc/sys", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT,
555 MOUNT_FATAL|MOUNT_IN_USERNS|MOUNT_APPLY_APIVFS_RO }, /* ... then, make it r/o */
556
557 /* Make these files inaccessible to container payloads: they potentially leak information about kernel
558 * internals or the host's execution environment to the container */
de40a303
LP
559 PROC_INACCESSIBLE_REG("/proc/kallsyms"),
560 PROC_INACCESSIBLE_REG("/proc/kcore"),
561 PROC_INACCESSIBLE_REG("/proc/keys"),
562 PROC_INACCESSIBLE_REG("/proc/sysrq-trigger"),
563 PROC_INACCESSIBLE_REG("/proc/timer_list"),
d4b653c5
LP
564
565 /* Make these directories read-only to container payloads: they show hardware information, and in some
566 * cases contain tunables the container really shouldn't have access to. */
567 PROC_READ_ONLY("/proc/acpi"),
568 PROC_READ_ONLY("/proc/apm"),
569 PROC_READ_ONLY("/proc/asound"),
570 PROC_READ_ONLY("/proc/bus"),
571 PROC_READ_ONLY("/proc/fs"),
572 PROC_READ_ONLY("/proc/irq"),
573 PROC_READ_ONLY("/proc/scsi"),
574
e1bb4b0d 575 { "mqueue", "/dev/mqueue", "mqueue", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
dcff2fa5 576 MOUNT_IN_USERNS|MOUNT_MKDIR },
849b9b85 577
d4b653c5 578 /* Then we list outer child mounts (i.e. mounts applied *before* entering user namespacing) */
9f563f27 579 { "tmpfs", "/tmp", "tmpfs", "mode=01777" NESTED_TMPFS_LIMITS, MS_NOSUID|MS_NODEV|MS_STRICTATIME,
dcff2fa5 580 MOUNT_FATAL|MOUNT_APPLY_TMPFS_TMP|MOUNT_MKDIR },
9f563f27 581 { "tmpfs", "/sys", "tmpfs", "mode=0555" TMPFS_LIMITS_SYS, MS_NOSUID|MS_NOEXEC|MS_NODEV,
dcff2fa5 582 MOUNT_FATAL|MOUNT_APPLY_APIVFS_NETNS|MOUNT_MKDIR },
b71a0192 583 { "sysfs", "/sys", "sysfs", NULL, SYS_DEFAULT_MOUNT_FLAGS,
dcff2fa5 584 MOUNT_FATAL|MOUNT_APPLY_APIVFS_RO|MOUNT_MKDIR }, /* skipped if above was mounted */
e1bb4b0d 585 { "sysfs", "/sys", "sysfs", NULL, MS_NOSUID|MS_NOEXEC|MS_NODEV,
dcff2fa5 586 MOUNT_FATAL|MOUNT_MKDIR }, /* skipped if above was mounted */
9f563f27 587 { "tmpfs", "/dev", "tmpfs", "mode=0755" TMPFS_LIMITS_PRIVATE_DEV, MS_NOSUID|MS_STRICTATIME,
dcff2fa5 588 MOUNT_FATAL|MOUNT_MKDIR },
9f563f27 589 { "tmpfs", "/dev/shm", "tmpfs", "mode=01777" NESTED_TMPFS_LIMITS, MS_NOSUID|MS_NODEV|MS_STRICTATIME,
dcff2fa5 590 MOUNT_FATAL|MOUNT_MKDIR },
9f563f27 591 { "tmpfs", "/run", "tmpfs", "mode=0755" TMPFS_LIMITS_RUN, MS_NOSUID|MS_NODEV|MS_STRICTATIME,
dcff2fa5 592 MOUNT_FATAL|MOUNT_MKDIR },
d64e32c2
LP
593 { "/run/host", "/run/host", NULL, NULL, MS_BIND,
594 MOUNT_FATAL|MOUNT_MKDIR|MOUNT_PREFIX_ROOT }, /* Prepare this so that we can make it read-only when we are done */
595 { "/etc/os-release", "/run/host/os-release", NULL, NULL, MS_BIND,
596 MOUNT_TOUCH }, /* As per kernel interface requirements, bind mount first (creating mount points) and make read-only later */
597 { "/usr/lib/os-release", "/run/host/os-release", NULL, NULL, MS_BIND,
598 MOUNT_FATAL }, /* If /etc/os-release doesn't exist use the version in /usr/lib as fallback */
599 { NULL, "/run/host/os-release", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT,
600 MOUNT_FATAL },
56339a10
LP
601 { NULL, "/run/host/os-release", NULL, NULL, MS_PRIVATE,
602 MOUNT_FATAL }, /* Turn off propagation (we only want that for the mount propagation tunnel dir) */
d64e32c2
LP
603 { NULL, "/run/host", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT,
604 MOUNT_FATAL|MOUNT_IN_USERNS },
349cc4a5 605#if HAVE_SELINUX
e1bb4b0d 606 { "/sys/fs/selinux", "/sys/fs/selinux", NULL, NULL, MS_BIND,
6fe01ced 607 MOUNT_MKDIR }, /* Bind mount first (mkdir/chown the mount point in case /sys/ is mounted as minimal skeleton tmpfs) */
e1bb4b0d 608 { NULL, "/sys/fs/selinux", NULL, NULL, MS_BIND|MS_RDONLY|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_REMOUNT,
6fe01ced 609 0 }, /* Then, make it r/o (don't mkdir/chown the mount point here, the previous entry already did that) */
56339a10
LP
610 { NULL, "/sys/fs/selinux", NULL, NULL, MS_PRIVATE,
611 0 }, /* Turn off propagation (we only want that for the mount propagation tunnel dir) */
e83bebef
LP
612#endif
613 };
614
bd6609eb
DDM
615 bool use_userns = FLAGS_SET(mount_settings, MOUNT_USE_USERNS);
616 bool netns = FLAGS_SET(mount_settings, MOUNT_APPLY_APIVFS_NETNS);
617 bool ro = FLAGS_SET(mount_settings, MOUNT_APPLY_APIVFS_RO);
618 bool in_userns = FLAGS_SET(mount_settings, MOUNT_IN_USERNS);
619 bool tmpfs_tmp = FLAGS_SET(mount_settings, MOUNT_APPLY_TMPFS_TMP);
88614c8a 620 int r;
e83bebef 621
d2b99ed7 622 for (size_t k = 0; k < ELEMENTSOF(mount_table); k++) {
d64e32c2 623 _cleanup_free_ char *where = NULL, *options = NULL, *prefixed = NULL;
bd6609eb 624 bool fatal = FLAGS_SET(mount_table[k].mount_settings, MOUNT_FATAL);
d64e32c2 625 const char *o;
4f086aab 626
bd6609eb 627 if (in_userns != FLAGS_SET(mount_table[k].mount_settings, MOUNT_IN_USERNS))
4f086aab 628 continue;
e83bebef 629
bd6609eb 630 if (!netns && FLAGS_SET(mount_table[k].mount_settings, MOUNT_APPLY_APIVFS_NETNS))
d1678248
ILG
631 continue;
632
bd6609eb 633 if (!ro && FLAGS_SET(mount_table[k].mount_settings, MOUNT_APPLY_APIVFS_RO))
e83bebef
LP
634 continue;
635
bd6609eb 636 if (!tmpfs_tmp && FLAGS_SET(mount_table[k].mount_settings, MOUNT_APPLY_TMPFS_TMP))
1099ceeb
LP
637 continue;
638
f461a28d 639 r = chase(mount_table[k].where, dest, CHASE_NONEXISTENT|CHASE_PREFIX_ROOT, &where, NULL);
8ce48cf0 640 if (r < 0)
e85c644e 641 return log_error_errno(r, "Failed to resolve %s%s: %m", strempty(dest), mount_table[k].where);
e83bebef 642
e83bebef 643 /* Skip this entry if it is not a remount. */
de40a303 644 if (mount_table[k].what) {
b409aacb 645 r = path_is_mount_point(where);
de40a303
LP
646 if (r < 0 && r != -ENOENT)
647 return log_error_errno(r, "Failed to detect whether %s is a mount point: %m", where);
648 if (r > 0)
649 continue;
650 }
e83bebef 651
d64e32c2 652 if ((mount_table[k].mount_settings & (MOUNT_MKDIR|MOUNT_TOUCH)) != 0) {
b3b1a08a 653 uid_t u = (use_userns && !in_userns) ? uid_shift : UID_INVALID;
e1bb4b0d
LB
654
655 if (FLAGS_SET(mount_table[k].mount_settings, MOUNT_TOUCH))
656 r = mkdir_parents_safe(dest, where, 0755, u, u, 0);
657 else
658 r = mkdir_p_safe(dest, where, 0755, u, u, 0);
dcff2fa5
LP
659 if (r < 0 && r != -EEXIST) {
660 if (fatal && r != -EROFS)
661 return log_error_errno(r, "Failed to create directory %s: %m", where);
e83bebef 662
dcff2fa5
LP
663 log_debug_errno(r, "Failed to create directory %s: %m", where);
664
665 /* If we failed mkdir() or chown() due to the root directory being read only,
666 * attempt to mount this fs anyway and let mount_verbose log any errors */
667 if (r != -EROFS)
668 continue;
669 }
d64e32c2
LP
670 }
671
672 if (FLAGS_SET(mount_table[k].mount_settings, MOUNT_TOUCH)) {
673 r = touch(where);
674 if (r < 0 && r != -EEXIST) {
675 if (fatal && r != -EROFS)
676 return log_error_errno(r, "Failed to create file %s: %m", where);
677
678 log_debug_errno(r, "Failed to create file %s: %m", where);
679 if (r != -EROFS)
680 continue;
e1bb4b0d 681 }
e83bebef
LP
682 }
683
684 o = mount_table[k].options;
685 if (streq_ptr(mount_table[k].type, "tmpfs")) {
2fa017f1 686 r = tmpfs_patch_options(o, in_userns ? 0 : uid_shift, selinux_apifs_context, &options);
e83bebef
LP
687 if (r < 0)
688 return log_oom();
689 if (r > 0)
690 o = options;
691 }
692
d64e32c2
LP
693 if (FLAGS_SET(mount_table[k].mount_settings, MOUNT_PREFIX_ROOT)) {
694 /* Optionally prefix the mount source with the root dir. This is useful in bind
695 * mounts to be created within the container image before we transition into it. Note
fcdd21ec 696 * that MOUNT_IN_USERNS is run after we transitioned hence prefixing is not necessary
d64e32c2 697 * for those. */
f461a28d 698 r = chase(mount_table[k].what, dest, CHASE_PREFIX_ROOT, &prefixed, NULL);
d64e32c2 699 if (r < 0)
e85c644e 700 return log_error_errno(r, "Failed to resolve %s%s: %m", strempty(dest), mount_table[k].what);
d64e32c2
LP
701 }
702
511a8cfe
LP
703 r = mount_verbose_full(
704 fatal ? LOG_ERR : LOG_DEBUG,
705 prefixed ?: mount_table[k].what,
706 where,
707 mount_table[k].type,
708 mount_table[k].flags,
709 o,
710 FLAGS_SET(mount_table[k].mount_settings, MOUNT_FOLLOW_SYMLINKS));
4f086aab 711 if (r < 0 && fatal)
60e76d48 712 return r;
e83bebef
LP
713 }
714
715 return 0;
716}
717
1aa18710 718static int parse_mount_bind_options(const char *options, unsigned long *mount_flags, char **mount_opts, RemountIdmapping *idmapping) {
a11fd406
ILG
719 unsigned long flags = *mount_flags;
720 char *opts = NULL;
1aa18710 721 RemountIdmapping new_idmapping = *idmapping;
a11fd406
ILG
722 int r;
723
724 assert(options);
725
726 for (;;) {
727 _cleanup_free_ char *word = NULL;
728
d2b99ed7 729 r = extract_first_word(&options, &word, ",", 0);
a11fd406
ILG
730 if (r < 0)
731 return log_error_errno(r, "Failed to extract mount option: %m");
732 if (r == 0)
733 break;
734
735 if (streq(word, "rbind"))
736 flags |= MS_REC;
737 else if (streq(word, "norbind"))
738 flags &= ~MS_REC;
c0c8f718 739 else if (streq(word, "idmap"))
1aa18710 740 new_idmapping = REMOUNT_IDMAPPING_HOST_ROOT;
c0c8f718 741 else if (streq(word, "noidmap"))
1aa18710 742 new_idmapping = REMOUNT_IDMAPPING_NONE;
2b2777ed
QD
743 else if (streq(word, "rootidmap"))
744 new_idmapping = REMOUNT_IDMAPPING_HOST_OWNER;
614d09a3
BF
745 else if (streq(word, "owneridmap"))
746 new_idmapping = REMOUNT_IDMAPPING_HOST_OWNER_TO_TARGET_OWNER;
d2b99ed7 747 else
38288f0b 748 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
d2b99ed7 749 "Invalid bind mount option: %s", word);
a11fd406
ILG
750 }
751
752 *mount_flags = flags;
1aa18710 753 *idmapping = new_idmapping;
a11fd406
ILG
754 /* in the future mount_opts will hold string options for mount(2) */
755 *mount_opts = opts;
756
757 return 0;
758}
759
c0c8f718 760static int mount_bind(const char *dest, CustomMount *m, uid_t uid_shift, uid_t uid_range) {
a11fd406
ILG
761 _cleanup_free_ char *mount_opts = NULL, *where = NULL;
762 unsigned long mount_flags = MS_BIND | MS_REC;
68cf43c3 763 struct stat source_st, dest_st;
614d09a3 764 uid_t dest_uid = UID_INVALID;
e83bebef 765 int r;
1aa18710 766 RemountIdmapping idmapping = REMOUNT_IDMAPPING_NONE;
e83bebef 767
86c0dd4a 768 assert(dest);
e83bebef
LP
769 assert(m);
770
a11fd406 771 if (m->options) {
1aa18710 772 r = parse_mount_bind_options(m->options, &mount_flags, &mount_opts, &idmapping);
a11fd406
ILG
773 if (r < 0)
774 return r;
775 }
776
07bca16f
LP
777 /* If this is a bind mount from a temporary sources change ownership of the source to the container's
778 * root UID. Otherwise it would always show up as "nobody" if user namespacing is used. */
779 if (m->rm_rf_tmpdir && chown(m->source, uid_shift, uid_shift) < 0)
780 return log_error_errno(errno, "Failed to chown %s: %m", m->source);
781
e83bebef
LP
782 if (stat(m->source, &source_st) < 0)
783 return log_error_errno(errno, "Failed to stat %s: %m", m->source);
784
f461a28d 785 r = chase(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where, NULL);
68cf43c3 786 if (r < 0)
ec57bd42 787 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
8ce48cf0
LP
788 if (r > 0) { /* Path exists already? */
789
790 if (stat(where, &dest_st) < 0)
791 return log_error_errno(errno, "Failed to stat %s: %m", where);
e83bebef 792
614d09a3
BF
793 dest_uid = dest_st.st_uid;
794
baaa35ad
ZJS
795 if (S_ISDIR(source_st.st_mode) && !S_ISDIR(dest_st.st_mode))
796 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
797 "Cannot bind mount directory %s on file %s.",
798 m->source, where);
799
800 if (!S_ISDIR(source_st.st_mode) && S_ISDIR(dest_st.st_mode))
801 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
802 "Cannot bind mount file %s on directory %s.",
803 m->source, where);
e83bebef 804
8ce48cf0 805 } else { /* Path doesn't exist yet? */
0a67965f 806 r = mkdir_parents_safe_label(dest, where, 0755, uid_shift, uid_shift, MKDIR_IGNORE_EXISTING);
e83bebef
LP
807 if (r < 0)
808 return log_error_errno(r, "Failed to make parents of %s: %m", where);
b97e83cb
BN
809
810 /* Create the mount point. Any non-directory file can be
811 * mounted on any non-directory file (regular, fifo, socket,
812 * char, block).
813 */
814 if (S_ISDIR(source_st.st_mode))
815 r = mkdir_label(where, 0755);
816 else
817 r = touch(where);
818 if (r < 0)
819 return log_error_errno(r, "Failed to create mount point %s: %m", where);
0a67965f
DDM
820
821 if (chown(where, uid_shift, uid_shift) < 0)
822 return log_error_errno(errno, "Failed to chown %s: %m", where);
614d09a3
BF
823
824 dest_uid = uid_shift;
8ce48cf0 825 }
e83bebef 826
511a8cfe 827 r = mount_nofollow_verbose(LOG_ERR, m->source, where, NULL, mount_flags, mount_opts);
60e76d48
ZJS
828 if (r < 0)
829 return r;
e83bebef
LP
830
831 if (m->read_only) {
64e82c19 832 r = bind_remount_recursive(where, MS_RDONLY, MS_RDONLY, NULL);
e83bebef
LP
833 if (r < 0)
834 return log_error_errno(r, "Read-only bind mount failed: %m");
835 }
836
1aa18710 837 if (idmapping != REMOUNT_IDMAPPING_NONE) {
614d09a3 838 r = remount_idmap(STRV_MAKE(where), uid_shift, uid_range, source_st.st_uid, dest_uid, idmapping);
c0c8f718
AV
839 if (r < 0)
840 return log_error_errno(r, "Failed to map ids for bind mount %s: %m", where);
841 }
842
e83bebef
LP
843 return 0;
844}
845
e091a5df 846static int mount_tmpfs(const char *dest, CustomMount *m, uid_t uid_shift, const char *selinux_apifs_context) {
68cf43c3
LP
847 const char *options;
848 _cleanup_free_ char *buf = NULL, *where = NULL;
e83bebef
LP
849 int r;
850
851 assert(dest);
852 assert(m);
853
f461a28d 854 r = chase(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where, NULL);
68cf43c3 855 if (r < 0)
ec57bd42 856 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
8ce48cf0
LP
857 if (r == 0) { /* Doesn't exist yet? */
858 r = mkdir_p_label(where, 0755);
859 if (r < 0)
860 return log_error_errno(r, "Creating mount point for tmpfs %s failed: %m", where);
861 }
e83bebef 862
2fa017f1 863 r = tmpfs_patch_options(m->options, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &buf);
e83bebef
LP
864 if (r < 0)
865 return log_oom();
866 options = r > 0 ? buf : m->options;
867
511a8cfe 868 return mount_nofollow_verbose(LOG_ERR, "tmpfs", where, "tmpfs", MS_NODEV|MS_STRICTATIME, options);
e83bebef
LP
869}
870
86c0dd4a 871static char *joined_and_escaped_lower_dirs(char **lower) {
e83bebef
LP
872 _cleanup_strv_free_ char **sv = NULL;
873
874 sv = strv_copy(lower);
875 if (!sv)
876 return NULL;
877
878 strv_reverse(sv);
879
880 if (!strv_shell_escape(sv, ",:"))
881 return NULL;
882
883 return strv_join(sv, ":");
884}
885
886static int mount_overlay(const char *dest, CustomMount *m) {
86c0dd4a 887 _cleanup_free_ char *lower = NULL, *where = NULL, *escaped_source = NULL;
68cf43c3 888 const char *options;
e83bebef
LP
889 int r;
890
891 assert(dest);
892 assert(m);
893
f461a28d 894 r = chase(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where, NULL);
68cf43c3 895 if (r < 0)
ec57bd42 896 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
8ce48cf0
LP
897 if (r == 0) { /* Doesn't exist yet? */
898 r = mkdir_label(where, 0755);
899 if (r < 0)
900 return log_error_errno(r, "Creating mount point for overlay %s failed: %m", where);
901 }
e83bebef
LP
902
903 (void) mkdir_p_label(m->source, 0755);
904
905 lower = joined_and_escaped_lower_dirs(m->lower);
906 if (!lower)
907 return log_oom();
908
86c0dd4a
LP
909 escaped_source = shell_escape(m->source, ",:");
910 if (!escaped_source)
911 return log_oom();
e83bebef 912
86c0dd4a 913 if (m->read_only)
e83bebef 914 options = strjoina("lowerdir=", escaped_source, ":", lower);
86c0dd4a
LP
915 else {
916 _cleanup_free_ char *escaped_work_dir = NULL;
e83bebef 917
e83bebef
LP
918 escaped_work_dir = shell_escape(m->work_dir, ",:");
919 if (!escaped_work_dir)
920 return log_oom();
921
922 options = strjoina("lowerdir=", lower, ",upperdir=", escaped_source, ",workdir=", escaped_work_dir);
923 }
924
511a8cfe 925 return mount_nofollow_verbose(LOG_ERR, "overlay", where, "overlay", m->read_only ? MS_RDONLY : 0, options);
e83bebef
LP
926}
927
de40a303 928static int mount_inaccessible(const char *dest, CustomMount *m) {
e5f10caf 929 _cleanup_free_ char *where = NULL, *source = NULL;
de40a303
LP
930 struct stat st;
931 int r;
932
933 assert(dest);
934 assert(m);
935
f461a28d 936 r = chase_and_stat(m->destination, dest, CHASE_PREFIX_ROOT, &where, &st);
de40a303
LP
937 if (r < 0) {
938 log_full_errno(m->graceful ? LOG_DEBUG : LOG_ERR, r, "Failed to resolve %s/%s: %m", dest, m->destination);
939 return m->graceful ? 0 : r;
940 }
941
48b747fa 942 r = mode_to_inaccessible_node(NULL, st.st_mode, &source);
e5f10caf
AZ
943 if (r < 0)
944 return m->graceful ? 0 : r;
de40a303 945
511a8cfe 946 r = mount_nofollow_verbose(m->graceful ? LOG_DEBUG : LOG_ERR, source, where, NULL, MS_BIND, NULL);
de40a303
LP
947 if (r < 0)
948 return m->graceful ? 0 : r;
949
511a8cfe 950 r = mount_nofollow_verbose(m->graceful ? LOG_DEBUG : LOG_ERR, NULL, where, NULL, MS_BIND|MS_RDONLY|MS_REMOUNT, NULL);
2c9b7a7e 951 if (r < 0) {
30f5d104 952 (void) umount_verbose(m->graceful ? LOG_DEBUG : LOG_ERR, where, UMOUNT_NOFOLLOW);
de40a303 953 return m->graceful ? 0 : r;
2c9b7a7e 954 }
de40a303
LP
955
956 return 0;
957}
958
959static int mount_arbitrary(const char *dest, CustomMount *m) {
960 _cleanup_free_ char *where = NULL;
961 int r;
962
963 assert(dest);
964 assert(m);
965
f461a28d 966 r = chase(m->destination, dest, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &where, NULL);
de40a303
LP
967 if (r < 0)
968 return log_error_errno(r, "Failed to resolve %s/%s: %m", dest, m->destination);
969 if (r == 0) { /* Doesn't exist yet? */
970 r = mkdir_p_label(where, 0755);
971 if (r < 0)
972 return log_error_errno(r, "Creating mount point for mount %s failed: %m", where);
973 }
974
511a8cfe 975 return mount_nofollow_verbose(LOG_ERR, m->source, where, m->type_argument, 0, m->options);
de40a303
LP
976}
977
e83bebef
LP
978int mount_custom(
979 const char *dest,
88614c8a 980 CustomMount *mounts, size_t n,
e091a5df 981 uid_t uid_shift,
c0c8f718 982 uid_t uid_range,
de40a303 983 const char *selinux_apifs_context,
5f0a6347 984 MountSettingsMask mount_settings) {
e83bebef
LP
985 int r;
986
987 assert(dest);
988
d2b99ed7 989 for (size_t i = 0; i < n; i++) {
e83bebef
LP
990 CustomMount *m = mounts + i;
991
bd6609eb 992 if (FLAGS_SET(mount_settings, MOUNT_IN_USERNS) != m->in_userns)
5f0a6347
DDM
993 continue;
994
bd6609eb 995 if (FLAGS_SET(mount_settings, MOUNT_ROOT_ONLY) && !path_equal(m->destination, "/"))
5f0a6347
DDM
996 continue;
997
bd6609eb 998 if (FLAGS_SET(mount_settings, MOUNT_NON_ROOT_ONLY) && path_equal(m->destination, "/"))
de40a303
LP
999 continue;
1000
e83bebef
LP
1001 switch (m->type) {
1002
1003 case CUSTOM_MOUNT_BIND:
c0c8f718 1004 r = mount_bind(dest, m, uid_shift, uid_range);
e83bebef
LP
1005 break;
1006
1007 case CUSTOM_MOUNT_TMPFS:
e091a5df 1008 r = mount_tmpfs(dest, m, uid_shift, selinux_apifs_context);
e83bebef
LP
1009 break;
1010
1011 case CUSTOM_MOUNT_OVERLAY:
1012 r = mount_overlay(dest, m);
1013 break;
1014
de40a303
LP
1015 case CUSTOM_MOUNT_INACCESSIBLE:
1016 r = mount_inaccessible(dest, m);
1017 break;
1018
1019 case CUSTOM_MOUNT_ARBITRARY:
1020 r = mount_arbitrary(dest, m);
1021 break;
1022
e83bebef 1023 default:
04499a70 1024 assert_not_reached();
e83bebef
LP
1025 }
1026
1027 if (r < 0)
1028 return r;
1029 }
1030
1031 return 0;
1032}
1033
bbd407ea 1034bool has_custom_root_mount(const CustomMount *mounts, size_t n) {
d2b99ed7
ZJS
1035 for (size_t i = 0; i < n; i++)
1036 if (path_equal(mounts[i].destination, "/"))
bbd407ea 1037 return true;
bbd407ea
DDM
1038
1039 return false;
1040}
1041
e091a5df 1042static int setup_volatile_state(const char *directory, uid_t uid_shift, const char *selinux_apifs_context) {
e83bebef
LP
1043 _cleanup_free_ char *buf = NULL;
1044 const char *p, *options;
1045 int r;
1046
1047 assert(directory);
1048
e5b43a04 1049 /* --volatile=state means we simply overmount /var with a tmpfs, and the rest read-only. */
e83bebef 1050
64e82c19 1051 r = bind_remount_recursive(directory, MS_RDONLY, MS_RDONLY, NULL);
e83bebef
LP
1052 if (r < 0)
1053 return log_error_errno(r, "Failed to remount %s read-only: %m", directory);
1054
1055 p = prefix_roota(directory, "/var");
1056 r = mkdir(p, 0755);
1057 if (r < 0 && errno != EEXIST)
1058 return log_error_errno(errno, "Failed to create %s: %m", directory);
1059
9f563f27 1060 options = "mode=0755" TMPFS_LIMITS_VOLATILE_STATE;
2fa017f1 1061 r = tmpfs_patch_options(options, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &buf);
e83bebef
LP
1062 if (r < 0)
1063 return log_oom();
1064 if (r > 0)
1065 options = buf;
1066
511a8cfe 1067 return mount_nofollow_verbose(LOG_ERR, "tmpfs", p, "tmpfs", MS_STRICTATIME, options);
e83bebef
LP
1068}
1069
e091a5df 1070static int setup_volatile_yes(const char *directory, uid_t uid_shift, const char *selinux_apifs_context) {
e83bebef
LP
1071 bool tmpfs_mounted = false, bind_mounted = false;
1072 char template[] = "/tmp/nspawn-volatile-XXXXXX";
07b9f3f0 1073 _cleanup_free_ char *buf = NULL, *bindir = NULL;
e83bebef 1074 const char *f, *t, *options;
07b9f3f0 1075 struct stat st;
e83bebef
LP
1076 int r;
1077
1078 assert(directory);
1079
07b9f3f0
LP
1080 /* --volatile=yes means we mount a tmpfs to the root dir, and the original /usr to use inside it, and
1081 * that read-only. Before we start setting this up let's validate if the image has the /usr merge
1082 * implemented, and let's output a friendly log message if it hasn't. */
1083
1084 bindir = path_join(directory, "/bin");
1085 if (!bindir)
1086 return log_oom();
1087 if (lstat(bindir, &st) < 0) {
1088 if (errno != ENOENT)
1089 return log_error_errno(errno, "Failed to stat /bin directory below image: %m");
1090
1091 /* ENOENT is fine, just means the image is probably just a naked /usr and we can create the
1092 * rest. */
1093 } else if (S_ISDIR(st.st_mode))
1094 return log_error_errno(SYNTHETIC_ERRNO(EISDIR),
1095 "Sorry, --volatile=yes mode is not supported with OS images that have not merged /bin/, /sbin/, /lib/, /lib64/ into /usr/. "
1096 "Please work with your distribution and help them adopt the merged /usr scheme.");
1097 else if (!S_ISLNK(st.st_mode))
1098 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1099 "Error starting image: if --volatile=yes is used /bin must be a symlink (for merged /usr support) or non-existent (in which case a symlink is created automatically).");
e83bebef
LP
1100
1101 if (!mkdtemp(template))
1102 return log_error_errno(errno, "Failed to create temporary directory: %m");
1103
9f563f27 1104 options = "mode=0755" TMPFS_LIMITS_ROOTFS;
2fa017f1 1105 r = tmpfs_patch_options(options, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &buf);
e83bebef 1106 if (r < 0)
c55d0ae7 1107 goto fail;
e83bebef
LP
1108 if (r > 0)
1109 options = buf;
1110
511a8cfe 1111 r = mount_nofollow_verbose(LOG_ERR, "tmpfs", template, "tmpfs", MS_STRICTATIME, options);
60e76d48 1112 if (r < 0)
e83bebef 1113 goto fail;
e83bebef
LP
1114
1115 tmpfs_mounted = true;
1116
1117 f = prefix_roota(directory, "/usr");
1118 t = prefix_roota(template, "/usr");
1119
1120 r = mkdir(t, 0755);
1121 if (r < 0 && errno != EEXIST) {
1122 r = log_error_errno(errno, "Failed to create %s: %m", t);
1123 goto fail;
1124 }
1125
511a8cfe 1126 r = mount_nofollow_verbose(LOG_ERR, f, t, NULL, MS_BIND|MS_REC, NULL);
60e76d48 1127 if (r < 0)
e83bebef 1128 goto fail;
e83bebef
LP
1129
1130 bind_mounted = true;
1131
64e82c19 1132 r = bind_remount_recursive(t, MS_RDONLY, MS_RDONLY, NULL);
e83bebef
LP
1133 if (r < 0) {
1134 log_error_errno(r, "Failed to remount %s read-only: %m", t);
1135 goto fail;
1136 }
1137
511a8cfe 1138 r = mount_nofollow_verbose(LOG_ERR, template, directory, NULL, MS_MOVE, NULL);
60e76d48 1139 if (r < 0)
e83bebef 1140 goto fail;
e83bebef
LP
1141
1142 (void) rmdir(template);
1143
1144 return 0;
1145
1146fail:
1147 if (bind_mounted)
30f5d104 1148 (void) umount_verbose(LOG_ERR, t, UMOUNT_NOFOLLOW);
e83bebef
LP
1149
1150 if (tmpfs_mounted)
30f5d104
LP
1151 (void) umount_verbose(LOG_ERR, template, UMOUNT_NOFOLLOW);
1152
e83bebef
LP
1153 (void) rmdir(template);
1154 return r;
1155}
b53ede69 1156
e091a5df 1157static int setup_volatile_overlay(const char *directory, uid_t uid_shift, const char *selinux_apifs_context) {
6c610aca
LP
1158 _cleanup_free_ char *buf = NULL, *escaped_directory = NULL, *escaped_upper = NULL, *escaped_work = NULL;
1159 char template[] = "/tmp/nspawn-volatile-XXXXXX";
1160 const char *upper, *work, *options;
1161 bool tmpfs_mounted = false;
1162 int r;
1163
1164 assert(directory);
1165
1166 /* --volatile=overlay means we mount an overlayfs to the root dir. */
1167
1168 if (!mkdtemp(template))
1169 return log_error_errno(errno, "Failed to create temporary directory: %m");
1170
9f563f27 1171 options = "mode=0755" TMPFS_LIMITS_ROOTFS;
6c610aca
LP
1172 r = tmpfs_patch_options(options, uid_shift == 0 ? UID_INVALID : uid_shift, selinux_apifs_context, &buf);
1173 if (r < 0)
1174 goto finish;
1175 if (r > 0)
1176 options = buf;
1177
511a8cfe 1178 r = mount_nofollow_verbose(LOG_ERR, "tmpfs", template, "tmpfs", MS_STRICTATIME, options);
6c610aca
LP
1179 if (r < 0)
1180 goto finish;
1181
1182 tmpfs_mounted = true;
1183
1184 upper = strjoina(template, "/upper");
1185 work = strjoina(template, "/work");
1186
1187 if (mkdir(upper, 0755) < 0) {
1188 r = log_error_errno(errno, "Failed to create %s: %m", upper);
1189 goto finish;
1190 }
1191 if (mkdir(work, 0755) < 0) {
1192 r = log_error_errno(errno, "Failed to create %s: %m", work);
1193 goto finish;
1194 }
1195
1196 /* And now, let's overmount the root dir with an overlayfs that uses the root dir as lower dir. It's kinda nice
1197 * that the kernel allows us to do that without going through some mount point rearrangements. */
1198
1199 escaped_directory = shell_escape(directory, ",:");
1200 escaped_upper = shell_escape(upper, ",:");
1201 escaped_work = shell_escape(work, ",:");
1202 if (!escaped_directory || !escaped_upper || !escaped_work) {
1203 r = -ENOMEM;
1204 goto finish;
1205 }
1206
1207 options = strjoina("lowerdir=", escaped_directory, ",upperdir=", escaped_upper, ",workdir=", escaped_work);
511a8cfe 1208 r = mount_nofollow_verbose(LOG_ERR, "overlay", directory, "overlay", 0, options);
6c610aca
LP
1209
1210finish:
1211 if (tmpfs_mounted)
30f5d104 1212 (void) umount_verbose(LOG_ERR, template, UMOUNT_NOFOLLOW);
6c610aca
LP
1213
1214 (void) rmdir(template);
1215 return r;
1216}
1217
e5b43a04
LP
1218int setup_volatile_mode(
1219 const char *directory,
1220 VolatileMode mode,
e091a5df 1221 uid_t uid_shift,
e5b43a04
LP
1222 const char *selinux_apifs_context) {
1223
1224 switch (mode) {
1225
1226 case VOLATILE_YES:
e091a5df 1227 return setup_volatile_yes(directory, uid_shift, selinux_apifs_context);
e5b43a04
LP
1228
1229 case VOLATILE_STATE:
e091a5df 1230 return setup_volatile_state(directory, uid_shift, selinux_apifs_context);
e5b43a04 1231
6c610aca 1232 case VOLATILE_OVERLAY:
e091a5df 1233 return setup_volatile_overlay(directory, uid_shift, selinux_apifs_context);
6c610aca 1234
e5b43a04
LP
1235 default:
1236 return 0;
1237 }
1238}
1239
b53ede69
PW
1240/* Expects *pivot_root_new and *pivot_root_old to be initialised to allocated memory or NULL. */
1241int pivot_root_parse(char **pivot_root_new, char **pivot_root_old, const char *s) {
1242 _cleanup_free_ char *root_new = NULL, *root_old = NULL;
1243 const char *p = s;
1244 int r;
1245
1246 assert(pivot_root_new);
1247 assert(pivot_root_old);
1248
1249 r = extract_first_word(&p, &root_new, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
1250 if (r < 0)
1251 return r;
1252 if (r == 0)
1253 return -EINVAL;
1254
1255 if (isempty(p))
1256 root_old = NULL;
1257 else {
1258 root_old = strdup(p);
1259 if (!root_old)
1260 return -ENOMEM;
1261 }
1262
1263 if (!path_is_absolute(root_new))
1264 return -EINVAL;
1265 if (root_old && !path_is_absolute(root_old))
1266 return -EINVAL;
1267
1268 free_and_replace(*pivot_root_new, root_new);
1269 free_and_replace(*pivot_root_old, root_old);
1270
1271 return 0;
1272}
1273
1274int setup_pivot_root(const char *directory, const char *pivot_root_new, const char *pivot_root_old) {
1275 _cleanup_free_ char *directory_pivot_root_new = NULL;
1276 _cleanup_free_ char *pivot_tmp_pivot_root_old = NULL;
1277 char pivot_tmp[] = "/tmp/nspawn-pivot-XXXXXX";
1278 bool remove_pivot_tmp = false;
1279 int r;
1280
1281 assert(directory);
1282
1283 if (!pivot_root_new)
1284 return 0;
1285
1286 /* Pivot pivot_root_new to / and the existing / to pivot_root_old.
1287 * If pivot_root_old is NULL, the existing / disappears.
1288 * This requires a temporary directory, pivot_tmp, which is
1289 * not a child of either.
1290 *
32e27670
LP
1291 * This is typically used for OSTree-style containers, where the root partition contains several
1292 * sysroots which could be run. Normally, one would be chosen by the bootloader and pivoted to / by
1293 * initrd.
b53ede69
PW
1294 *
1295 * For example, for an OSTree deployment, pivot_root_new
1296 * would be: /ostree/deploy/$os/deploy/$checksum. Note that this
1297 * code doesn’t do the /var mount which OSTree expects: use
1298 * --bind +/sysroot/ostree/deploy/$os/var:/var for that.
1299 *
1300 * So in the OSTree case, we’ll end up with something like:
1301 * - directory = /tmp/nspawn-root-123456
1302 * - pivot_root_new = /ostree/deploy/os/deploy/123abc
1303 * - pivot_root_old = /sysroot
1304 * - directory_pivot_root_new =
1305 * /tmp/nspawn-root-123456/ostree/deploy/os/deploy/123abc
1306 * - pivot_tmp = /tmp/nspawn-pivot-123456
1307 * - pivot_tmp_pivot_root_old = /tmp/nspawn-pivot-123456/sysroot
1308 *
1309 * Requires all file systems at directory and below to be mounted
1310 * MS_PRIVATE or MS_SLAVE so they can be moved.
1311 */
c6134d3e
LP
1312 directory_pivot_root_new = path_join(directory, pivot_root_new);
1313 if (!directory_pivot_root_new)
1314 return log_oom();
b53ede69
PW
1315
1316 /* Remount directory_pivot_root_new to make it movable. */
511a8cfe 1317 r = mount_nofollow_verbose(LOG_ERR, directory_pivot_root_new, directory_pivot_root_new, NULL, MS_BIND, NULL);
b53ede69
PW
1318 if (r < 0)
1319 goto done;
1320
1321 if (pivot_root_old) {
1322 if (!mkdtemp(pivot_tmp)) {
1323 r = log_error_errno(errno, "Failed to create temporary directory: %m");
1324 goto done;
1325 }
1326
1327 remove_pivot_tmp = true;
c6134d3e
LP
1328 pivot_tmp_pivot_root_old = path_join(pivot_tmp, pivot_root_old);
1329 if (!pivot_tmp_pivot_root_old) {
1330 r = log_oom();
1331 goto done;
1332 }
b53ede69 1333
511a8cfe 1334 r = mount_nofollow_verbose(LOG_ERR, directory_pivot_root_new, pivot_tmp, NULL, MS_MOVE, NULL);
b53ede69
PW
1335 if (r < 0)
1336 goto done;
1337
511a8cfe 1338 r = mount_nofollow_verbose(LOG_ERR, directory, pivot_tmp_pivot_root_old, NULL, MS_MOVE, NULL);
b53ede69
PW
1339 if (r < 0)
1340 goto done;
1341
511a8cfe 1342 r = mount_nofollow_verbose(LOG_ERR, pivot_tmp, directory, NULL, MS_MOVE, NULL);
b53ede69
PW
1343 if (r < 0)
1344 goto done;
1345 } else {
511a8cfe 1346 r = mount_nofollow_verbose(LOG_ERR, directory_pivot_root_new, directory, NULL, MS_MOVE, NULL);
b53ede69
PW
1347 if (r < 0)
1348 goto done;
1349 }
1350
1351done:
1352 if (remove_pivot_tmp)
1353 (void) rmdir(pivot_tmp);
1354
1355 return r;
1356}
b71a0192
CB
1357
1358#define NSPAWN_PRIVATE_FULLY_VISIBLE_PROCFS "/run/host/proc"
1359#define NSPAWN_PRIVATE_FULLY_VISIBLE_SYSFS "/run/host/sys"
1360
1361int pin_fully_visible_fs(void) {
1362 int r;
1363
1364 (void) mkdir_p(NSPAWN_PRIVATE_FULLY_VISIBLE_PROCFS, 0755);
1365 (void) mkdir_p(NSPAWN_PRIVATE_FULLY_VISIBLE_SYSFS, 0755);
1366
1367 r = mount_follow_verbose(LOG_ERR, "proc", NSPAWN_PRIVATE_FULLY_VISIBLE_PROCFS, "proc", PROC_DEFAULT_MOUNT_FLAGS, NULL);
1368 if (r < 0)
1369 return r;
1370
1371 r = mount_follow_verbose(LOG_ERR, "sysfs", NSPAWN_PRIVATE_FULLY_VISIBLE_SYSFS, "sysfs", SYS_DEFAULT_MOUNT_FLAGS, NULL);
1372 if (r < 0)
1373 return r;
1374
1375 return 0;
1376}
1377
1378static int do_wipe_fully_visible_fs(void) {
1379 if (umount2(NSPAWN_PRIVATE_FULLY_VISIBLE_PROCFS, MNT_DETACH) < 0)
1380 return log_error_errno(errno, "Failed to unmount temporary proc: %m");
1381
1382 if (rmdir(NSPAWN_PRIVATE_FULLY_VISIBLE_PROCFS) < 0)
1383 return log_error_errno(errno, "Failed to remove temporary proc mountpoint: %m");
1384
1385 if (umount2(NSPAWN_PRIVATE_FULLY_VISIBLE_SYSFS, MNT_DETACH) < 0)
1386 return log_error_errno(errno, "Failed to unmount temporary sys: %m");
1387
1388 if (rmdir(NSPAWN_PRIVATE_FULLY_VISIBLE_SYSFS) < 0)
1389 return log_error_errno(errno, "Failed to remove temporary sys mountpoint: %m");
1390
1391 return 0;
1392}
1393
1394int wipe_fully_visible_fs(int mntns_fd) {
1395 _cleanup_close_ int orig_mntns_fd = -EBADF;
1396 int r, rr;
1397
d2881ef9
YW
1398 r = namespace_open(0,
1399 /* ret_pidns_fd = */ NULL,
1400 &orig_mntns_fd,
1401 /* ret_netns_fd = */ NULL,
1402 /* ret_userns_fd = */ NULL,
1403 /* ret_root_fd = */ NULL);
b71a0192
CB
1404 if (r < 0)
1405 return log_error_errno(r, "Failed to pin originating mount namespace: %m");
1406
d2881ef9
YW
1407 r = namespace_enter(/* pidns_fd = */ -EBADF,
1408 mntns_fd,
1409 /* netns_fd = */ -EBADF,
1410 /* userns_fd = */ -EBADF,
1411 /* root_fd = */ -EBADF);
b71a0192
CB
1412 if (r < 0)
1413 return log_error_errno(r, "Failed to enter mount namespace: %m");
1414
1415 rr = do_wipe_fully_visible_fs();
1416
d2881ef9
YW
1417 r = namespace_enter(/* pidns_fd = */ -EBADF,
1418 orig_mntns_fd,
1419 /* netns_fd = */ -EBADF,
1420 /* userns_fd = */ -EBADF,
1421 /* root_fd = */ -EBADF);
b71a0192
CB
1422 if (r < 0)
1423 return log_error_errno(r, "Failed to enter original mount namespace: %m");
1424
1425 return rr;
1426}