]> git.proxmox.com Git - systemd.git/blame - src/core/namespace.c
New upstream version 240
[systemd.git] / src / core / namespace.c
CommitLineData
52ad194e 1/* SPDX-License-Identifier: LGPL-2.1+ */
663996b3
MS
2
3#include <errno.h>
db2df898 4#include <sched.h>
663996b3 5#include <stdio.h>
db2df898
MP
6#include <string.h>
7#include <sys/mount.h>
663996b3 8#include <sys/stat.h>
db2df898 9#include <unistd.h>
663996b3
MS
10#include <linux/fs.h>
11
db2df898 12#include "alloc-util.h"
81c58355 13#include "base-filesystem.h"
60f067b4 14#include "dev-setup.h"
db2df898 15#include "fd-util.h"
8a584da2 16#include "fs-util.h"
f5e65279 17#include "label.h"
2897b343 18#include "loop-util.h"
db2df898
MP
19#include "loopback-setup.h"
20#include "missing.h"
e3bff60a 21#include "mkdir.h"
db2df898 22#include "mount-util.h"
6e866b33 23#include "mountpoint-util.h"
db2df898
MP
24#include "namespace.h"
25#include "path-util.h"
26#include "selinux-util.h"
27#include "socket-util.h"
1d42b86d 28#include "stat-util.h"
db2df898
MP
29#include "string-table.h"
30#include "string-util.h"
31#include "strv.h"
32#include "umask-util.h"
33#include "user-util.h"
34#include "util.h"
663996b3 35
aa27b158
MP
36#define DEV_MOUNT_OPTIONS (MS_NOSUID|MS_STRICTATIME|MS_NOEXEC)
37
663996b3
MS
38typedef enum MountMode {
39 /* This is ordered by priority! */
40 INACCESSIBLE,
2897b343
MP
41 BIND_MOUNT,
42 BIND_MOUNT_RECURSIVE,
663996b3 43 PRIVATE_TMP,
60f067b4 44 PRIVATE_DEV,
2897b343 45 BIND_DEV,
f5e65279 46 EMPTY_DIR,
2897b343
MP
47 SYSFS,
48 PROCFS,
49 READONLY,
8a584da2 50 READWRITE,
98393f85 51 TMPFS,
663996b3
MS
52} MountMode;
53
2897b343
MP
54typedef struct MountEntry {
55 const char *path_const; /* Memory allocated on stack or static */
56 MountMode mode:5;
57 bool ignore:1; /* Ignore if path does not exist? */
58 bool has_prefix:1; /* Already is prefixed by the root dir? */
59 bool read_only:1; /* Shall this mount point be read-only? */
b012e921 60 bool applied:1; /* Already applied */
98393f85 61 char *path_malloc; /* Use this instead of 'path_const' if we had to allocate memory */
2897b343
MP
62 const char *source_const; /* The source path, for bind mounts */
63 char *source_malloc;
98393f85
MB
64 const char *options_const;/* Mount options for tmpfs */
65 char *options_malloc;
66 unsigned long flags; /* Mount flags used by EMPTY_DIR and TMPFS. Do not include MS_RDONLY here, but please use read_only. */
b012e921 67 unsigned n_followed;
2897b343
MP
68} MountEntry;
69
70/* If MountAPIVFS= is used, let's mount /sys and /proc into the it, but only as a fallback if the user hasn't mounted
b012e921 71 * something there already. These mounts are hence overridden by any other explicitly configured mounts. */
2897b343
MP
72static const MountEntry apivfs_table[] = {
73 { "/proc", PROCFS, false },
74 { "/dev", BIND_DEV, false },
75 { "/sys", SYSFS, false },
76};
8a584da2
MP
77
78/* ProtectKernelTunables= option and the related filesystem APIs */
2897b343 79static const MountEntry protect_kernel_tunables_table[] = {
2897b343 80 { "/proc/acpi", READONLY, true },
b012e921 81 { "/proc/apm", READONLY, true }, /* Obsolete API, there's no point in permitting access to this, ever */
2897b343
MP
82 { "/proc/asound", READONLY, true },
83 { "/proc/bus", READONLY, true },
84 { "/proc/fs", READONLY, true },
85 { "/proc/irq", READONLY, true },
b012e921
MB
86 { "/proc/kallsyms", INACCESSIBLE, true },
87 { "/proc/kcore", INACCESSIBLE, true },
88 { "/proc/latency_stats", READONLY, true },
89 { "/proc/mtrr", READONLY, true },
90 { "/proc/scsi", READONLY, true },
91 { "/proc/sys", READONLY, false },
92 { "/proc/sysrq-trigger", READONLY, true },
93 { "/proc/timer_stats", READONLY, true },
2897b343 94 { "/sys", READONLY, false },
98393f85 95 { "/sys/fs/bpf", READONLY, true },
2897b343 96 { "/sys/fs/cgroup", READWRITE, false }, /* READONLY is set by ProtectControlGroups= option */
f5e65279 97 { "/sys/fs/selinux", READWRITE, true },
b012e921
MB
98 { "/sys/kernel/debug", READONLY, true },
99 { "/sys/kernel/tracing", READONLY, true },
8a584da2
MP
100};
101
102/* ProtectKernelModules= option */
2897b343 103static const MountEntry protect_kernel_modules_table[] = {
f5e65279 104#if HAVE_SPLIT_USR
2897b343 105 { "/lib/modules", INACCESSIBLE, true },
8a584da2 106#endif
2897b343 107 { "/usr/lib/modules", INACCESSIBLE, true },
8a584da2
MP
108};
109
110/*
111 * ProtectHome=read-only table, protect $HOME and $XDG_RUNTIME_DIR and rest of
112 * system should be protected by ProtectSystem=
113 */
2897b343
MP
114static const MountEntry protect_home_read_only_table[] = {
115 { "/home", READONLY, true },
116 { "/run/user", READONLY, true },
117 { "/root", READONLY, true },
8a584da2
MP
118};
119
98393f85
MB
120/* ProtectHome=tmpfs table */
121static const MountEntry protect_home_tmpfs_table[] = {
122 { "/home", TMPFS, true, .read_only = true, .options_const = "mode=0755", .flags = MS_NODEV|MS_STRICTATIME },
123 { "/run/user", TMPFS, true, .read_only = true, .options_const = "mode=0755", .flags = MS_NODEV|MS_STRICTATIME },
124 { "/root", TMPFS, true, .read_only = true, .options_const = "mode=0700", .flags = MS_NODEV|MS_STRICTATIME },
125};
126
8a584da2 127/* ProtectHome=yes table */
2897b343
MP
128static const MountEntry protect_home_yes_table[] = {
129 { "/home", INACCESSIBLE, true },
130 { "/run/user", INACCESSIBLE, true },
131 { "/root", INACCESSIBLE, true },
8a584da2
MP
132};
133
134/* ProtectSystem=yes table */
2897b343
MP
135static const MountEntry protect_system_yes_table[] = {
136 { "/usr", READONLY, false },
137 { "/boot", READONLY, true },
138 { "/efi", READONLY, true },
98393f85
MB
139#if HAVE_SPLIT_USR
140 { "/lib", READONLY, true },
141 { "/lib64", READONLY, true },
142 { "/bin", READONLY, true },
143# if HAVE_SPLIT_BIN
144 { "/sbin", READONLY, true },
145# endif
146#endif
8a584da2
MP
147};
148
149/* ProtectSystem=full includes ProtectSystem=yes */
2897b343
MP
150static const MountEntry protect_system_full_table[] = {
151 { "/usr", READONLY, false },
152 { "/boot", READONLY, true },
153 { "/efi", READONLY, true },
154 { "/etc", READONLY, false },
98393f85
MB
155#if HAVE_SPLIT_USR
156 { "/lib", READONLY, true },
157 { "/lib64", READONLY, true },
158 { "/bin", READONLY, true },
159# if HAVE_SPLIT_BIN
160 { "/sbin", READONLY, true },
161# endif
162#endif
8a584da2
MP
163};
164
165/*
166 * ProtectSystem=strict table. In this strict mode, we mount everything
167 * read-only, except for /proc, /dev, /sys which are the kernel API VFS,
168 * which are left writable, but PrivateDevices= + ProtectKernelTunables=
169 * protect those, and these options should be fully orthogonal.
170 * (And of course /home and friends are also left writable, as ProtectHome=
171 * shall manage those, orthogonally).
172 */
2897b343
MP
173static const MountEntry protect_system_strict_table[] = {
174 { "/", READONLY, false },
175 { "/proc", READWRITE, false }, /* ProtectKernelTunables= */
176 { "/sys", READWRITE, false }, /* ProtectKernelTunables= */
177 { "/dev", READWRITE, false }, /* PrivateDevices= */
178 { "/home", READWRITE, true }, /* ProtectHome= */
179 { "/run/user", READWRITE, true }, /* ProtectHome= */
180 { "/root", READWRITE, true }, /* ProtectHome= */
8a584da2
MP
181};
182
2897b343
MP
183static const char *mount_entry_path(const MountEntry *p) {
184 assert(p);
185
186 /* Returns the path of this bind mount. If the malloc()-allocated ->path_buffer field is set we return that,
187 * otherwise the stack/static ->path field is returned. */
188
189 return p->path_malloc ?: p->path_const;
190}
191
192static bool mount_entry_read_only(const MountEntry *p) {
193 assert(p);
194
195 return p->read_only || IN_SET(p->mode, READONLY, INACCESSIBLE);
8a584da2
MP
196}
197
2897b343
MP
198static const char *mount_entry_source(const MountEntry *p) {
199 assert(p);
200
201 return p->source_malloc ?: p->source_const;
202}
203
98393f85
MB
204static const char *mount_entry_options(const MountEntry *p) {
205 assert(p);
206
207 return p->options_malloc ?: p->options_const;
208}
209
2897b343
MP
210static void mount_entry_done(MountEntry *p) {
211 assert(p);
212
213 p->path_malloc = mfree(p->path_malloc);
214 p->source_malloc = mfree(p->source_malloc);
98393f85 215 p->options_malloc = mfree(p->options_malloc);
2897b343
MP
216}
217
52ad194e 218static int append_access_mounts(MountEntry **p, char **strv, MountMode mode, bool forcibly_require_prefix) {
663996b3
MS
219 char **i;
220
60f067b4
JS
221 assert(p);
222
2897b343
MP
223 /* Adds a list of user-supplied READWRITE/READONLY/INACCESSIBLE entries */
224
663996b3 225 STRV_FOREACH(i, strv) {
2897b343
MP
226 bool ignore = false, needs_prefix = false;
227 const char *e = *i;
663996b3 228
2897b343
MP
229 /* Look for any prefixes */
230 if (startswith(e, "-")) {
231 e++;
8a584da2 232 ignore = true;
14228c0d 233 }
2897b343
MP
234 if (startswith(e, "+")) {
235 e++;
236 needs_prefix = true;
237 }
14228c0d 238
2897b343 239 if (!path_is_absolute(e))
6e866b33
MB
240 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
241 "Path is not absolute: %s", e);
663996b3 242
2897b343
MP
243 *((*p)++) = (MountEntry) {
244 .path_const = e,
245 .mode = mode,
246 .ignore = ignore,
52ad194e 247 .has_prefix = !needs_prefix && !forcibly_require_prefix,
2897b343 248 };
663996b3
MS
249 }
250
251 return 0;
252}
253
f5e65279
MB
254static int append_empty_dir_mounts(MountEntry **p, char **strv) {
255 char **i;
256
257 assert(p);
258
259 /* Adds tmpfs mounts to provide readable but empty directories. This is primarily used to implement the
260 * "/private/" boundary directories for DynamicUser=1. */
261
262 STRV_FOREACH(i, strv) {
263
264 *((*p)++) = (MountEntry) {
265 .path_const = *i,
266 .mode = EMPTY_DIR,
267 .ignore = false,
f5e65279 268 .read_only = true,
98393f85
MB
269 .options_const = "mode=755",
270 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME,
f5e65279
MB
271 };
272 }
273
274 return 0;
275}
276
b012e921
MB
277static int append_bind_mounts(MountEntry **p, const BindMount *binds, size_t n) {
278 size_t i;
663996b3 279
8a584da2 280 assert(p);
8a584da2 281
2897b343
MP
282 for (i = 0; i < n; i++) {
283 const BindMount *b = binds + i;
8a584da2 284
2897b343
MP
285 *((*p)++) = (MountEntry) {
286 .path_const = b->destination,
287 .mode = b->recursive ? BIND_MOUNT_RECURSIVE : BIND_MOUNT,
288 .read_only = b->read_only,
289 .source_const = b->source,
98393f85
MB
290 .ignore = b->ignore_enoent,
291 };
292 }
293
294 return 0;
295}
296
b012e921
MB
297static int append_tmpfs_mounts(MountEntry **p, const TemporaryFileSystem *tmpfs, size_t n) {
298 size_t i;
98393f85
MB
299 int r;
300
301 assert(p);
302
303 for (i = 0; i < n; i++) {
304 const TemporaryFileSystem *t = tmpfs + i;
305 _cleanup_free_ char *o = NULL, *str = NULL;
6e866b33 306 unsigned long flags;
98393f85
MB
307 bool ro = false;
308
309 if (!path_is_absolute(t->path))
6e866b33
MB
310 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
311 "Path is not absolute: %s",
312 t->path);
98393f85 313
6e866b33
MB
314 str = strjoin("mode=0755,", t->options);
315 if (!str)
316 return -ENOMEM;
98393f85 317
6e866b33
MB
318 r = mount_option_mangle(str, MS_NODEV|MS_STRICTATIME, &flags, &o);
319 if (r < 0)
320 return log_debug_errno(r, "Failed to parse mount option '%s': %m", str);
98393f85 321
6e866b33
MB
322 ro = flags & MS_RDONLY;
323 if (ro)
324 flags ^= MS_RDONLY;
98393f85
MB
325
326 *((*p)++) = (MountEntry) {
327 .path_const = t->path,
328 .mode = TMPFS,
329 .read_only = ro,
6e866b33 330 .options_malloc = TAKE_PTR(o),
98393f85 331 .flags = flags,
2897b343 332 };
8a584da2
MP
333 }
334
335 return 0;
336}
337
b012e921
MB
338static int append_static_mounts(MountEntry **p, const MountEntry *mounts, size_t n, bool ignore_protect) {
339 size_t i;
2897b343 340
8a584da2 341 assert(p);
2897b343 342 assert(mounts);
8a584da2 343
2897b343 344 /* Adds a list of static pre-defined entries */
8a584da2 345
2897b343
MP
346 for (i = 0; i < n; i++)
347 *((*p)++) = (MountEntry) {
348 .path_const = mount_entry_path(mounts+i),
349 .mode = mounts[i].mode,
350 .ignore = mounts[i].ignore || ignore_protect,
351 };
8a584da2 352
2897b343 353 return 0;
8a584da2
MP
354}
355
2897b343 356static int append_protect_home(MountEntry **p, ProtectHome protect_home, bool ignore_protect) {
8a584da2
MP
357 assert(p);
358
2897b343
MP
359 switch (protect_home) {
360
361 case PROTECT_HOME_NO:
8a584da2
MP
362 return 0;
363
8a584da2 364 case PROTECT_HOME_READ_ONLY:
2897b343
MP
365 return append_static_mounts(p, protect_home_read_only_table, ELEMENTSOF(protect_home_read_only_table), ignore_protect);
366
98393f85
MB
367 case PROTECT_HOME_TMPFS:
368 return append_static_mounts(p, protect_home_tmpfs_table, ELEMENTSOF(protect_home_tmpfs_table), ignore_protect);
369
8a584da2 370 case PROTECT_HOME_YES:
2897b343
MP
371 return append_static_mounts(p, protect_home_yes_table, ELEMENTSOF(protect_home_yes_table), ignore_protect);
372
8a584da2 373 default:
2897b343 374 assert_not_reached("Unexpected ProtectHome= value");
8a584da2 375 }
8a584da2 376}
663996b3 377
2897b343 378static int append_protect_system(MountEntry **p, ProtectSystem protect_system, bool ignore_protect) {
8a584da2 379 assert(p);
663996b3 380
2897b343
MP
381 switch (protect_system) {
382
383 case PROTECT_SYSTEM_NO:
663996b3 384 return 0;
8a584da2 385
8a584da2 386 case PROTECT_SYSTEM_STRICT:
2897b343
MP
387 return append_static_mounts(p, protect_system_strict_table, ELEMENTSOF(protect_system_strict_table), ignore_protect);
388
8a584da2 389 case PROTECT_SYSTEM_YES:
2897b343
MP
390 return append_static_mounts(p, protect_system_yes_table, ELEMENTSOF(protect_system_yes_table), ignore_protect);
391
8a584da2 392 case PROTECT_SYSTEM_FULL:
2897b343
MP
393 return append_static_mounts(p, protect_system_full_table, ELEMENTSOF(protect_system_full_table), ignore_protect);
394
8a584da2 395 default:
2897b343 396 assert_not_reached("Unexpected ProtectSystem= value");
663996b3 397 }
8a584da2
MP
398}
399
6e866b33 400static int mount_path_compare(const MountEntry *a, const MountEntry *b) {
8a584da2
MP
401 int d;
402
663996b3 403 /* If the paths are not equal, then order prefixes first */
6e866b33 404 d = path_compare(mount_entry_path(a), mount_entry_path(b));
8a584da2
MP
405 if (d != 0)
406 return d;
407
408 /* If the paths are equal, check the mode */
6e866b33 409 return CMP((int) a->mode, (int) b->mode);
663996b3
MS
410}
411
b012e921
MB
412static int prefix_where_needed(MountEntry *m, size_t n, const char *root_directory) {
413 size_t i;
2897b343 414
6e866b33 415 /* Prefixes all paths in the bind mount table with the root directory if the entry needs that. */
2897b343
MP
416
417 for (i = 0; i < n; i++) {
418 char *s;
419
420 if (m[i].has_prefix)
421 continue;
422
423 s = prefix_root(root_directory, mount_entry_path(m+i));
424 if (!s)
425 return -ENOMEM;
426
98393f85 427 free_and_replace(m[i].path_malloc, s);
2897b343
MP
428 m[i].has_prefix = true;
429 }
430
431 return 0;
432}
433
b012e921 434static void drop_duplicates(MountEntry *m, size_t *n) {
2897b343 435 MountEntry *f, *t, *previous;
663996b3
MS
436
437 assert(m);
438 assert(n);
439
8a584da2
MP
440 /* Drops duplicate entries. Expects that the array is properly ordered already. */
441
2897b343 442 for (f = m, t = m, previous = NULL; f < m + *n; f++) {
663996b3 443
8a584da2 444 /* The first one wins (which is the one with the more restrictive mode), see mount_path_compare()
b012e921
MB
445 * above. Note that we only drop duplicates that haven't been mounted yet. */
446 if (previous &&
447 path_equal(mount_entry_path(f), mount_entry_path(previous)) &&
448 !f->applied && !previous->applied) {
2897b343
MP
449 log_debug("%s is duplicate.", mount_entry_path(f));
450 previous->read_only = previous->read_only || mount_entry_read_only(f); /* Propagate the read-only flag to the remaining entry */
451 mount_entry_done(f);
663996b3 452 continue;
8a584da2 453 }
663996b3 454
5eef597e 455 *t = *f;
663996b3 456 previous = t;
8a584da2
MP
457 t++;
458 }
459
460 *n = t - m;
461}
462
b012e921 463static void drop_inaccessible(MountEntry *m, size_t *n) {
2897b343 464 MountEntry *f, *t;
8a584da2 465 const char *clear = NULL;
663996b3 466
8a584da2
MP
467 assert(m);
468 assert(n);
469
470 /* Drops all entries obstructed by another entry further up the tree. Expects that the array is properly
471 * ordered already. */
472
2897b343 473 for (f = m, t = m; f < m + *n; f++) {
8a584da2
MP
474
475 /* If we found a path set for INACCESSIBLE earlier, and this entry has it as prefix we should drop
476 * it, as inaccessible paths really should drop the entire subtree. */
2897b343
MP
477 if (clear && path_startswith(mount_entry_path(f), clear)) {
478 log_debug("%s is masked by %s.", mount_entry_path(f), clear);
479 mount_entry_done(f);
8a584da2
MP
480 continue;
481 }
482
2897b343 483 clear = f->mode == INACCESSIBLE ? mount_entry_path(f) : NULL;
8a584da2
MP
484
485 *t = *f;
486 t++;
487 }
488
489 *n = t - m;
490}
491
b012e921 492static void drop_nop(MountEntry *m, size_t *n) {
2897b343 493 MountEntry *f, *t;
8a584da2
MP
494
495 assert(m);
496 assert(n);
497
498 /* Drops all entries which have an immediate parent that has the same type, as they are redundant. Assumes the
499 * list is ordered by prefixes. */
500
2897b343 501 for (f = m, t = m; f < m + *n; f++) {
8a584da2
MP
502
503 /* Only suppress such subtrees for READONLY and READWRITE entries */
504 if (IN_SET(f->mode, READONLY, READWRITE)) {
2897b343 505 MountEntry *p;
8a584da2
MP
506 bool found = false;
507
508 /* Now let's find the first parent of the entry we are looking at. */
509 for (p = t-1; p >= m; p--) {
2897b343 510 if (path_startswith(mount_entry_path(f), mount_entry_path(p))) {
8a584da2
MP
511 found = true;
512 break;
513 }
514 }
515
516 /* We found it, let's see if it's the same mode, if so, we can drop this entry */
517 if (found && p->mode == f->mode) {
2897b343
MP
518 log_debug("%s is redundant by %s", mount_entry_path(f), mount_entry_path(p));
519 mount_entry_done(f);
8a584da2
MP
520 continue;
521 }
522 }
523
524 *t = *f;
525 t++;
526 }
527
528 *n = t - m;
529}
530
b012e921 531static void drop_outside_root(const char *root_directory, MountEntry *m, size_t *n) {
2897b343 532 MountEntry *f, *t;
8a584da2
MP
533
534 assert(m);
535 assert(n);
536
2897b343 537 /* Nothing to do */
8a584da2
MP
538 if (!root_directory)
539 return;
540
541 /* Drops all mounts that are outside of the root directory. */
542
2897b343 543 for (f = m, t = m; f < m + *n; f++) {
8a584da2 544
2897b343
MP
545 if (!path_startswith(mount_entry_path(f), root_directory)) {
546 log_debug("%s is outside of root directory.", mount_entry_path(f));
547 mount_entry_done(f);
8a584da2
MP
548 continue;
549 }
550
551 *t = *f;
663996b3
MS
552 t++;
553 }
554
555 *n = t - m;
556}
557
6e866b33
MB
558static int clone_device_node(
559 const char *d,
560 const char *temporary_mount,
561 bool *make_devnode) {
562
563 _cleanup_free_ char *sl = NULL;
564 const char *dn, *bn, *t;
1d42b86d
MB
565 struct stat st;
566 int r;
567
568 if (stat(d, &st) < 0) {
6e866b33
MB
569 if (errno == ENOENT) {
570 log_debug_errno(errno, "Device node '%s' to clone does not exist, ignoring.", d);
b012e921 571 return -ENXIO;
6e866b33
MB
572 }
573
574 return log_debug_errno(errno, "Failed to stat() device node '%s' to clone, ignoring: %m", d);
1d42b86d
MB
575 }
576
577 if (!S_ISBLK(st.st_mode) &&
578 !S_ISCHR(st.st_mode))
6e866b33
MB
579 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
580 "Device node '%s' to clone is not a device node, ignoring.",
581 d);
1d42b86d
MB
582
583 dn = strjoina(temporary_mount, d);
584
6e866b33 585 /* First, try to create device node properly */
b012e921
MB
586 if (*make_devnode) {
587 mac_selinux_create_file_prepare(d, st.st_mode);
588 r = mknod(dn, st.st_mode, st.st_rdev);
589 mac_selinux_create_file_clear();
6e866b33
MB
590 if (r >= 0)
591 goto add_symlink;
b012e921
MB
592 if (errno != EPERM)
593 return log_debug_errno(errno, "mknod failed for %s: %m", d);
594
6e866b33 595 /* This didn't work, let's not try this again for the next iterations. */
b012e921
MB
596 *make_devnode = false;
597 }
598
599 /* We're about to fallback to bind-mounting the device
600 * node. So create a dummy bind-mount target. */
601 mac_selinux_create_file_prepare(d, 0);
602 r = mknod(dn, S_IFREG, 0);
1d42b86d 603 mac_selinux_create_file_clear();
b012e921 604 if (r < 0 && errno != EEXIST)
6e866b33 605 return log_debug_errno(errno, "mknod() fallback failed for '%s': %m", d);
b012e921
MB
606
607 /* Fallback to bind-mounting:
608 * The assumption here is that all used device nodes carry standard
609 * properties. Specifically, the devices nodes we bind-mount should
610 * either be owned by root:root or root:tty (e.g. /dev/tty, /dev/ptmx)
611 * and should not carry ACLs. */
612 if (mount(d, dn, NULL, MS_BIND, NULL) < 0)
6e866b33
MB
613 return log_debug_errno(errno, "Bind mounting failed for '%s': %m", d);
614
615add_symlink:
616 bn = path_startswith(d, "/dev/");
617 if (!bn)
618 return 0;
619
620 /* Create symlinks like /dev/char/1:9 → ../urandom */
621 if (asprintf(&sl, "%s/dev/%s/%u:%u", temporary_mount, S_ISCHR(st.st_mode) ? "char" : "block", major(st.st_rdev), minor(st.st_rdev)) < 0)
622 return log_oom();
623
624 (void) mkdir_parents(sl, 0755);
625
626 t = strjoina("../", bn);
627
628 if (symlink(t, sl) < 0)
629 log_debug_errno(errno, "Failed to symlink '%s' to '%s', ignoring: %m", t, sl);
b012e921
MB
630
631 return 0;
1d42b86d
MB
632}
633
2897b343 634static int mount_private_dev(MountEntry *m) {
60f067b4
JS
635 static const char devnodes[] =
636 "/dev/null\0"
637 "/dev/zero\0"
638 "/dev/full\0"
639 "/dev/random\0"
640 "/dev/urandom\0"
641 "/dev/tty\0";
642
643 char temporary_mount[] = "/tmp/namespace-dev-XXXXXX";
f47781d8 644 const char *d, *dev = NULL, *devpts = NULL, *devshm = NULL, *devhugepages = NULL, *devmqueue = NULL, *devlog = NULL, *devptmx = NULL;
b012e921 645 bool can_mknod = true;
60f067b4
JS
646 _cleanup_umask_ mode_t u;
647 int r;
648
649 assert(m);
650
651 u = umask(0000);
652
653 if (!mkdtemp(temporary_mount))
6e866b33 654 return log_debug_errno(errno, "Failed to create temporary directory '%s': %m", temporary_mount);
60f067b4 655
e735f4d4 656 dev = strjoina(temporary_mount, "/dev");
e3bff60a 657 (void) mkdir(dev, 0755);
aa27b158 658 if (mount("tmpfs", dev, "tmpfs", DEV_MOUNT_OPTIONS, "mode=755") < 0) {
6e866b33 659 r = log_debug_errno(errno, "Failed to mount tmpfs on '%s': %m", dev);
60f067b4
JS
660 goto fail;
661 }
662
e735f4d4 663 devpts = strjoina(temporary_mount, "/dev/pts");
e3bff60a 664 (void) mkdir(devpts, 0755);
60f067b4 665 if (mount("/dev/pts", devpts, NULL, MS_BIND, NULL) < 0) {
6e866b33 666 r = log_debug_errno(errno, "Failed to bind mount /dev/pts on '%s': %m", devpts);
60f067b4
JS
667 goto fail;
668 }
669
6e866b33
MB
670 /* /dev/ptmx can either be a device node or a symlink to /dev/pts/ptmx.
671 * When /dev/ptmx a device node, /dev/pts/ptmx has 000 permissions making it inaccessible.
672 * Thus, in that case make a clone.
673 * In nspawn and other containers it will be a symlink, in that case make it a symlink. */
1d42b86d 674 r = is_symlink("/dev/ptmx");
6e866b33
MB
675 if (r < 0) {
676 log_debug_errno(r, "Failed to detect whether /dev/ptmx is a symlink or not: %m");
e3bff60a 677 goto fail;
6e866b33 678 } else if (r > 0) {
1d42b86d
MB
679 devptmx = strjoina(temporary_mount, "/dev/ptmx");
680 if (symlink("pts/ptmx", devptmx) < 0) {
6e866b33 681 r = log_debug_errno(errno, "Failed to create a symlink '%s' to pts/ptmx: %m", devptmx);
1d42b86d
MB
682 goto fail;
683 }
684 } else {
b012e921 685 r = clone_device_node("/dev/ptmx", temporary_mount, &can_mknod);
1d42b86d
MB
686 if (r < 0)
687 goto fail;
e3bff60a 688 }
60f067b4 689
e735f4d4 690 devshm = strjoina(temporary_mount, "/dev/shm");
1d42b86d 691 (void) mkdir(devshm, 0755);
60f067b4
JS
692 r = mount("/dev/shm", devshm, NULL, MS_BIND, NULL);
693 if (r < 0) {
6e866b33 694 r = log_debug_errno(errno, "Failed to bind mount /dev/shm on '%s': %m", devshm);
60f067b4
JS
695 goto fail;
696 }
697
e735f4d4 698 devmqueue = strjoina(temporary_mount, "/dev/mqueue");
e3bff60a 699 (void) mkdir(devmqueue, 0755);
6e866b33
MB
700 if (mount("/dev/mqueue", devmqueue, NULL, MS_BIND, NULL) < 0)
701 log_debug_errno(errno, "Failed to bind mount /dev/mqueue on '%s', ignoring: %m", devmqueue);
60f067b4 702
e735f4d4 703 devhugepages = strjoina(temporary_mount, "/dev/hugepages");
e3bff60a 704 (void) mkdir(devhugepages, 0755);
6e866b33
MB
705 if (mount("/dev/hugepages", devhugepages, NULL, MS_BIND, NULL) < 0)
706 log_debug_errno(errno, "Failed to bind mount /dev/hugepages on '%s', ignoring: %m", devhugepages);
60f067b4 707
e735f4d4 708 devlog = strjoina(temporary_mount, "/dev/log");
6e866b33
MB
709 if (symlink("/run/systemd/journal/dev-log", devlog) < 0)
710 log_debug_errno(errno, "Failed to create a symlink '%s' to /run/systemd/journal/dev-log, ignoring: %m", devlog);
60f067b4
JS
711
712 NULSTR_FOREACH(d, devnodes) {
b012e921
MB
713 r = clone_device_node(d, temporary_mount, &can_mknod);
714 /* ENXIO means the the *source* is not a device file, skip creation in that case */
715 if (r < 0 && r != -ENXIO)
60f067b4 716 goto fail;
60f067b4
JS
717 }
718
6e866b33
MB
719 r = dev_setup(temporary_mount, UID_INVALID, GID_INVALID);
720 if (r < 0)
721 log_debug_errno(r, "Failed to setup basic device tree at '%s', ignoring: %m", temporary_mount);
e3bff60a
MP
722
723 /* Create the /dev directory if missing. It is more likely to be
724 * missing when the service is started with RootDirectory. This is
725 * consistent with mount units creating the mount points when missing.
726 */
2897b343 727 (void) mkdir_p_label(mount_entry_path(m), 0755);
60f067b4 728
aa27b158 729 /* Unmount everything in old /dev */
6e866b33
MB
730 r = umount_recursive(mount_entry_path(m), 0);
731 if (r < 0)
732 log_debug_errno(r, "Failed to unmount directories below '%s', ignoring: %m", mount_entry_path(m));
733
2897b343 734 if (mount(dev, mount_entry_path(m), NULL, MS_MOVE, NULL) < 0) {
6e866b33 735 r = log_debug_errno(errno, "Failed to move mount point '%s' to '%s': %m", dev, mount_entry_path(m));
60f067b4
JS
736 goto fail;
737 }
738
739 rmdir(dev);
740 rmdir(temporary_mount);
741
742 return 0;
743
744fail:
745 if (devpts)
746 umount(devpts);
747
748 if (devshm)
749 umount(devshm);
750
60f067b4
JS
751 if (devhugepages)
752 umount(devhugepages);
753
754 if (devmqueue)
755 umount(devmqueue);
756
5eef597e
MP
757 umount(dev);
758 rmdir(dev);
759 rmdir(temporary_mount);
760
761 return r;
762}
763
98393f85 764static int mount_bind_dev(const MountEntry *m) {
2897b343
MP
765 int r;
766
767 assert(m);
768
769 /* Implements the little brother of mount_private_dev(): simply bind mounts the host's /dev into the service's
770 * /dev. This is only used when RootDirectory= is set. */
771
f5e65279
MB
772 (void) mkdir_p_label(mount_entry_path(m), 0755);
773
2897b343
MP
774 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
775 if (r < 0)
776 return log_debug_errno(r, "Unable to determine whether /dev is already mounted: %m");
777 if (r > 0) /* make this a NOP if /dev is already a mount point */
778 return 0;
779
780 if (mount("/dev", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL) < 0)
781 return log_debug_errno(errno, "Failed to bind mount %s: %m", mount_entry_path(m));
782
783 return 1;
784}
785
98393f85 786static int mount_sysfs(const MountEntry *m) {
2897b343
MP
787 int r;
788
789 assert(m);
790
f5e65279
MB
791 (void) mkdir_p_label(mount_entry_path(m), 0755);
792
2897b343
MP
793 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
794 if (r < 0)
795 return log_debug_errno(r, "Unable to determine whether /sys is already mounted: %m");
796 if (r > 0) /* make this a NOP if /sys is already a mount point */
797 return 0;
798
799 /* Bind mount the host's version so that we get all child mounts of it, too. */
800 if (mount("/sys", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL) < 0)
801 return log_debug_errno(errno, "Failed to mount %s: %m", mount_entry_path(m));
802
803 return 1;
804}
805
98393f85 806static int mount_procfs(const MountEntry *m) {
2897b343
MP
807 int r;
808
809 assert(m);
810
f5e65279
MB
811 (void) mkdir_p_label(mount_entry_path(m), 0755);
812
2897b343
MP
813 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
814 if (r < 0)
815 return log_debug_errno(r, "Unable to determine whether /proc is already mounted: %m");
816 if (r > 0) /* make this a NOP if /proc is already a mount point */
817 return 0;
818
819 /* Mount a new instance, so that we get the one that matches our user namespace, if we are running in one */
820 if (mount("proc", mount_entry_path(m), "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL) < 0)
821 return log_debug_errno(errno, "Failed to mount %s: %m", mount_entry_path(m));
822
823 return 1;
824}
825
98393f85 826static int mount_tmpfs(const MountEntry *m) {
f5e65279
MB
827 assert(m);
828
98393f85 829 /* First, get rid of everything that is below if there is anything. Then, overmount with our new tmpfs */
f5e65279
MB
830
831 (void) mkdir_p_label(mount_entry_path(m), 0755);
832 (void) umount_recursive(mount_entry_path(m), 0);
833
98393f85 834 if (mount("tmpfs", mount_entry_path(m), "tmpfs", m->flags, mount_entry_options(m)) < 0)
f5e65279
MB
835 return log_debug_errno(errno, "Failed to mount %s: %m", mount_entry_path(m));
836
837 return 1;
838}
839
b012e921 840static int follow_symlink(
2897b343 841 const char *root_directory,
b012e921 842 MountEntry *m) {
2897b343 843
b012e921 844 _cleanup_free_ char *target = NULL;
2897b343
MP
845 int r;
846
b012e921
MB
847 /* Let's chase symlinks, but only one step at a time. That's because depending where the symlink points we
848 * might need to change the order in which we mount stuff. Hence: let's normalize piecemeal, and do one step at
849 * a time by specifying CHASE_STEP. This function returns 0 if we resolved one step, and > 0 if we reached the
850 * end and already have a fully normalized name. */
2897b343 851
b012e921
MB
852 r = chase_symlinks(mount_entry_path(m), root_directory, CHASE_STEP|CHASE_NONEXISTENT, &target);
853 if (r < 0)
854 return log_debug_errno(r, "Failed to chase symlinks '%s': %m", mount_entry_path(m));
855 if (r > 0) /* Reached the end, nothing more to resolve */
856 return 1;
2897b343 857
6e866b33
MB
858 if (m->n_followed >= CHASE_SYMLINKS_MAX) /* put a boundary on things */
859 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
860 "Symlink loop on '%s'.",
861 mount_entry_path(m));
2897b343 862
b012e921 863 log_debug("Followed mount entry path symlink %s → %s.", mount_entry_path(m), target);
2897b343 864
b012e921
MB
865 free_and_replace(m->path_malloc, target);
866 m->has_prefix = true;
2897b343 867
b012e921
MB
868 m->n_followed ++;
869
870 return 0;
2897b343
MP
871}
872
663996b3 873static int apply_mount(
2897b343 874 const char *root_directory,
98393f85 875 MountEntry *m) {
663996b3 876
f5e65279 877 bool rbind = true, make = false;
663996b3
MS
878 const char *what;
879 int r;
880
881 assert(m);
882
2897b343 883 log_debug("Applying namespace mount on %s", mount_entry_path(m));
8a584da2 884
663996b3
MS
885 switch (m->mode) {
886
8a584da2
MP
887 case INACCESSIBLE: {
888 struct stat target;
60f067b4
JS
889
890 /* First, get rid of everything that is below if there
891 * is anything... Then, overmount it with an
5a920b42 892 * inaccessible path. */
2897b343 893 (void) umount_recursive(mount_entry_path(m), 0);
60f067b4 894
b012e921
MB
895 if (lstat(mount_entry_path(m), &target) < 0) {
896 if (errno == ENOENT && m->ignore)
897 return 0;
898
2897b343 899 return log_debug_errno(errno, "Failed to lstat() %s to determine what to mount over it: %m", mount_entry_path(m));
b012e921 900 }
663996b3 901
5a920b42 902 what = mode_to_inaccessible_node(target.st_mode);
6e866b33
MB
903 if (!what)
904 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
905 "File type not supported for inaccessible mounts. Note that symlinks are not allowed");
5a920b42 906 break;
8a584da2
MP
907 }
908
663996b3
MS
909 case READONLY:
910 case READWRITE:
2897b343 911 r = path_is_mount_point(mount_entry_path(m), root_directory, 0);
b012e921
MB
912 if (r == -ENOENT && m->ignore)
913 return 0;
8a584da2 914 if (r < 0)
2897b343 915 return log_debug_errno(r, "Failed to determine whether %s is already a mount point: %m", mount_entry_path(m));
8a584da2
MP
916 if (r > 0) /* Nothing to do here, it is already a mount. We just later toggle the MS_RDONLY bit for the mount point if needed. */
917 return 0;
8a584da2 918 /* This isn't a mount point yet, let's make it one. */
2897b343
MP
919 what = mount_entry_path(m);
920 break;
921
922 case BIND_MOUNT:
923 rbind = false;
2897b343 924
52ad194e 925 _fallthrough_;
b012e921
MB
926 case BIND_MOUNT_RECURSIVE: {
927 _cleanup_free_ char *chased = NULL;
2897b343 928
b012e921
MB
929 /* Since mount() will always follow symlinks we chase the symlinks on our own first. Note that bind
930 * mount source paths are always relative to the host root, hence we pass NULL as root directory to
931 * chase_symlinks() here. */
932
933 r = chase_symlinks(mount_entry_source(m), NULL, CHASE_TRAIL_SLASH, &chased);
934 if (r == -ENOENT && m->ignore) {
935 log_debug_errno(r, "Path %s does not exist, ignoring.", mount_entry_source(m));
936 return 0;
937 }
938 if (r < 0)
939 return log_debug_errno(r, "Failed to follow symlinks on %s: %m", mount_entry_source(m));
940
941 log_debug("Followed source symlinks %s → %s.", mount_entry_source(m), chased);
942
943 free_and_replace(m->source_malloc, chased);
2897b343
MP
944
945 what = mount_entry_source(m);
f5e65279 946 make = true;
8a584da2 947 break;
b012e921 948 }
663996b3 949
f5e65279 950 case EMPTY_DIR:
98393f85
MB
951 case TMPFS:
952 return mount_tmpfs(m);
f5e65279 953
663996b3 954 case PRIVATE_TMP:
98393f85 955 what = mount_entry_source(m);
f5e65279 956 make = true;
663996b3
MS
957 break;
958
60f067b4 959 case PRIVATE_DEV:
2897b343
MP
960 return mount_private_dev(m);
961
962 case BIND_DEV:
963 return mount_bind_dev(m);
964
965 case SYSFS:
966 return mount_sysfs(m);
967
968 case PROCFS:
969 return mount_procfs(m);
60f067b4 970
663996b3
MS
971 default:
972 assert_not_reached("Unknown mode");
973 }
974
975 assert(what);
976
f5e65279
MB
977 if (mount(what, mount_entry_path(m), NULL, MS_BIND|(rbind ? MS_REC : 0), NULL) < 0) {
978 bool try_again = false;
979 r = -errno;
980
981 if (r == -ENOENT && make) {
982 struct stat st;
983
984 /* Hmm, either the source or the destination are missing. Let's see if we can create the destination, then try again */
985
b012e921
MB
986 if (stat(what, &st) < 0)
987 log_debug_errno(errno, "Mount point source '%s' is not accessible: %m", what);
988 else {
989 int q;
f5e65279
MB
990
991 (void) mkdir_parents(mount_entry_path(m), 0755);
992
993 if (S_ISDIR(st.st_mode))
b012e921
MB
994 q = mkdir(mount_entry_path(m), 0755) < 0 ? -errno : 0;
995 else
996 q = touch(mount_entry_path(m));
997
998 if (q < 0)
999 log_debug_errno(q, "Failed to create destination mount point node '%s': %m", mount_entry_path(m));
f5e65279 1000 else
b012e921 1001 try_again = true;
f5e65279
MB
1002 }
1003 }
1004
1005 if (try_again) {
1006 if (mount(what, mount_entry_path(m), NULL, MS_BIND|(rbind ? MS_REC : 0), NULL) < 0)
1007 r = -errno;
1008 else
1009 r = 0;
1010 }
1011
1012 if (r < 0)
1013 return log_debug_errno(r, "Failed to mount %s to %s: %m", what, mount_entry_path(m));
1014 }
8a584da2 1015
2897b343 1016 log_debug("Successfully mounted %s to %s", what, mount_entry_path(m));
8a584da2 1017 return 0;
663996b3
MS
1018}
1019
6e866b33
MB
1020/* Change the per-mount readonly flag on an existing mount */
1021static int remount_bind_readonly(const char *path, unsigned long orig_flags) {
1022 int r;
1023
1024 r = mount(NULL, path, NULL, MS_REMOUNT | MS_BIND | MS_RDONLY | orig_flags, NULL);
1025
1026 return r < 0 ? -errno : 0;
1027}
1028
98393f85 1029static int make_read_only(const MountEntry *m, char **blacklist, FILE *proc_self_mountinfo) {
6e866b33 1030 bool submounts = false;
8a584da2 1031 int r = 0;
663996b3
MS
1032
1033 assert(m);
81c58355 1034 assert(proc_self_mountinfo);
663996b3 1035
98393f85
MB
1036 if (mount_entry_read_only(m)) {
1037 if (IN_SET(m->mode, EMPTY_DIR, TMPFS)) {
6e866b33
MB
1038 r = remount_bind_readonly(mount_entry_path(m), m->flags);
1039 } else {
1040 submounts = true;
98393f85 1041 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), true, blacklist, proc_self_mountinfo);
6e866b33 1042 }
98393f85 1043 } else if (m->mode == PRIVATE_DEV) {
6e866b33
MB
1044 /* Set /dev readonly, but not submounts like /dev/shm. Also, we only set the per-mount read-only flag.
1045 * We can't set it on the superblock, if we are inside a user namespace and running Linux <= 4.17. */
1046 r = remount_bind_readonly(mount_entry_path(m), DEV_MOUNT_OPTIONS);
aa27b158 1047 } else
663996b3
MS
1048 return 0;
1049
8a584da2
MP
1050 /* Not that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked read-only
1051 * already stays this way. This improves compatibility with container managers, where we won't attempt to undo
1052 * read-only mounts already applied. */
1053
2897b343
MP
1054 if (r == -ENOENT && m->ignore)
1055 r = 0;
1056
6e866b33
MB
1057 if (r < 0)
1058 return log_debug_errno(r, "Failed to re-mount '%s'%s read-only: %m", mount_entry_path(m),
1059 submounts ? " and its submounts" : "");
1060
1061 return 0;
60f067b4
JS
1062}
1063
6e866b33 1064static bool namespace_info_mount_apivfs(const NamespaceInfo *ns_info) {
2897b343 1065 assert(ns_info);
8a584da2 1066
81c58355
MB
1067 /*
1068 * ProtectControlGroups= and ProtectKernelTunables= imply MountAPIVFS=,
1069 * since to protect the API VFS mounts, they need to be around in the
6e866b33 1070 * first place...
81c58355 1071 */
8a584da2 1072
6e866b33
MB
1073 return ns_info->mount_apivfs ||
1074 ns_info->protect_control_groups ||
1075 ns_info->protect_kernel_tunables;
8a584da2
MP
1076}
1077
b012e921 1078static size_t namespace_calculate_mounts(
52ad194e 1079 const NamespaceInfo *ns_info,
8a584da2
MP
1080 char** read_write_paths,
1081 char** read_only_paths,
1082 char** inaccessible_paths,
f5e65279 1083 char** empty_directories,
b012e921
MB
1084 size_t n_bind_mounts,
1085 size_t n_temporary_filesystems,
8a584da2
MP
1086 const char* tmp_dir,
1087 const char* var_tmp_dir,
1088 ProtectHome protect_home,
1089 ProtectSystem protect_system) {
1090
b012e921
MB
1091 size_t protect_home_cnt;
1092 size_t protect_system_cnt =
8a584da2
MP
1093 (protect_system == PROTECT_SYSTEM_STRICT ?
1094 ELEMENTSOF(protect_system_strict_table) :
1095 ((protect_system == PROTECT_SYSTEM_FULL) ?
1096 ELEMENTSOF(protect_system_full_table) :
1097 ((protect_system == PROTECT_SYSTEM_YES) ?
1098 ELEMENTSOF(protect_system_yes_table) : 0)));
1099
1100 protect_home_cnt =
1101 (protect_home == PROTECT_HOME_YES ?
1102 ELEMENTSOF(protect_home_yes_table) :
1103 ((protect_home == PROTECT_HOME_READ_ONLY) ?
98393f85
MB
1104 ELEMENTSOF(protect_home_read_only_table) :
1105 ((protect_home == PROTECT_HOME_TMPFS) ?
1106 ELEMENTSOF(protect_home_tmpfs_table) : 0)));
8a584da2
MP
1107
1108 return !!tmp_dir + !!var_tmp_dir +
1109 strv_length(read_write_paths) +
1110 strv_length(read_only_paths) +
1111 strv_length(inaccessible_paths) +
f5e65279 1112 strv_length(empty_directories) +
2897b343 1113 n_bind_mounts +
98393f85 1114 n_temporary_filesystems +
8a584da2
MP
1115 ns_info->private_dev +
1116 (ns_info->protect_kernel_tunables ? ELEMENTSOF(protect_kernel_tunables_table) : 0) +
1117 (ns_info->protect_control_groups ? 1 : 0) +
1118 (ns_info->protect_kernel_modules ? ELEMENTSOF(protect_kernel_modules_table) : 0) +
2897b343 1119 protect_home_cnt + protect_system_cnt +
6e866b33 1120 (namespace_info_mount_apivfs(ns_info) ? ELEMENTSOF(apivfs_table) : 0);
8a584da2
MP
1121}
1122
b012e921 1123static void normalize_mounts(const char *root_directory, MountEntry *mounts, size_t *n_mounts) {
6e866b33 1124 assert(root_directory);
b012e921
MB
1125 assert(n_mounts);
1126 assert(mounts || *n_mounts == 0);
1127
6e866b33 1128 typesafe_qsort(mounts, *n_mounts, mount_path_compare);
b012e921
MB
1129
1130 drop_duplicates(mounts, n_mounts);
1131 drop_outside_root(root_directory, mounts, n_mounts);
1132 drop_inaccessible(mounts, n_mounts);
1133 drop_nop(mounts, n_mounts);
1134}
1135
60f067b4 1136int setup_namespace(
e3bff60a 1137 const char* root_directory,
2897b343 1138 const char* root_image,
52ad194e 1139 const NamespaceInfo *ns_info,
5a920b42
MP
1140 char** read_write_paths,
1141 char** read_only_paths,
1142 char** inaccessible_paths,
f5e65279 1143 char** empty_directories,
2897b343 1144 const BindMount *bind_mounts,
b012e921 1145 size_t n_bind_mounts,
98393f85 1146 const TemporaryFileSystem *temporary_filesystems,
b012e921 1147 size_t n_temporary_filesystems,
5eef597e
MP
1148 const char* tmp_dir,
1149 const char* var_tmp_dir,
60f067b4
JS
1150 ProtectHome protect_home,
1151 ProtectSystem protect_system,
2897b343
MP
1152 unsigned long mount_flags,
1153 DissectImageFlags dissect_image_flags) {
1154
1155 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
1156 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
1157 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
1158 _cleanup_free_ void *root_hash = NULL;
1159 MountEntry *m, *mounts = NULL;
6e866b33 1160 size_t n_mounts, root_hash_size = 0;
52ad194e 1161 bool require_prefix = false;
6e866b33 1162 const char *root;
60f067b4
JS
1163 int r = 0;
1164
2897b343
MP
1165 assert(ns_info);
1166
60f067b4
JS
1167 if (mount_flags == 0)
1168 mount_flags = MS_SHARED;
1169
2897b343
MP
1170 if (root_image) {
1171 dissect_image_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
663996b3 1172
b012e921
MB
1173 if (protect_system == PROTECT_SYSTEM_STRICT &&
1174 protect_home != PROTECT_HOME_NO &&
1175 strv_isempty(read_write_paths))
2897b343 1176 dissect_image_flags |= DISSECT_IMAGE_READ_ONLY;
60f067b4 1177
2897b343
MP
1178 r = loop_device_make_by_path(root_image,
1179 dissect_image_flags & DISSECT_IMAGE_READ_ONLY ? O_RDONLY : O_RDWR,
1180 &loop_device);
60f067b4 1181 if (r < 0)
6e866b33 1182 return log_debug_errno(r, "Failed to create loop device for root image: %m");
60f067b4 1183
2897b343 1184 r = root_hash_load(root_image, &root_hash, &root_hash_size);
60f067b4 1185 if (r < 0)
6e866b33 1186 return log_debug_errno(r, "Failed to load root hash: %m");
60f067b4 1187
2897b343 1188 r = dissect_image(loop_device->fd, root_hash, root_hash_size, dissect_image_flags, &dissected_image);
60f067b4 1189 if (r < 0)
6e866b33 1190 return log_debug_errno(r, "Failed to dissect image: %m");
60f067b4 1191
2897b343
MP
1192 r = dissected_image_decrypt(dissected_image, NULL, root_hash, root_hash_size, dissect_image_flags, &decrypted_image);
1193 if (r < 0)
6e866b33 1194 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
2897b343
MP
1195 }
1196
f5e65279
MB
1197 if (root_directory)
1198 root = root_directory;
b012e921
MB
1199 else {
1200 /* Always create the mount namespace in a temporary directory, instead of operating
1201 * directly in the root. The temporary directory prevents any mounts from being
1202 * potentially obscured my other mounts we already applied.
1203 * We use the same mount point for all images, which is safe, since they all live
1204 * in their own namespaces after all, and hence won't see each other. */
f5e65279
MB
1205
1206 root = "/run/systemd/unit-root";
1207 (void) mkdir_label(root, 0700);
52ad194e 1208 require_prefix = true;
b012e921 1209 }
f5e65279 1210
2897b343
MP
1211 n_mounts = namespace_calculate_mounts(
1212 ns_info,
1213 read_write_paths,
1214 read_only_paths,
1215 inaccessible_paths,
f5e65279 1216 empty_directories,
98393f85
MB
1217 n_bind_mounts,
1218 n_temporary_filesystems,
2897b343
MP
1219 tmp_dir, var_tmp_dir,
1220 protect_home, protect_system);
1221
2897b343
MP
1222 if (n_mounts > 0) {
1223 m = mounts = (MountEntry *) alloca0(n_mounts * sizeof(MountEntry));
52ad194e 1224 r = append_access_mounts(&m, read_write_paths, READWRITE, require_prefix);
2897b343
MP
1225 if (r < 0)
1226 goto finish;
1227
52ad194e 1228 r = append_access_mounts(&m, read_only_paths, READONLY, require_prefix);
2897b343
MP
1229 if (r < 0)
1230 goto finish;
1231
52ad194e 1232 r = append_access_mounts(&m, inaccessible_paths, INACCESSIBLE, require_prefix);
2897b343
MP
1233 if (r < 0)
1234 goto finish;
1235
f5e65279
MB
1236 r = append_empty_dir_mounts(&m, empty_directories);
1237 if (r < 0)
1238 goto finish;
1239
2897b343
MP
1240 r = append_bind_mounts(&m, bind_mounts, n_bind_mounts);
1241 if (r < 0)
1242 goto finish;
1243
98393f85
MB
1244 r = append_tmpfs_mounts(&m, temporary_filesystems, n_temporary_filesystems);
1245 if (r < 0)
1246 goto finish;
1247
60f067b4 1248 if (tmp_dir) {
2897b343
MP
1249 *(m++) = (MountEntry) {
1250 .path_const = "/tmp",
1251 .mode = PRIVATE_TMP,
98393f85 1252 .source_const = tmp_dir,
2897b343 1253 };
60f067b4
JS
1254 }
1255
1256 if (var_tmp_dir) {
2897b343
MP
1257 *(m++) = (MountEntry) {
1258 .path_const = "/var/tmp",
98393f85
MB
1259 .mode = PRIVATE_TMP,
1260 .source_const = var_tmp_dir,
2897b343 1261 };
60f067b4
JS
1262 }
1263
8a584da2 1264 if (ns_info->private_dev) {
2897b343
MP
1265 *(m++) = (MountEntry) {
1266 .path_const = "/dev",
1267 .mode = PRIVATE_DEV,
1268 };
60f067b4
JS
1269 }
1270
8a584da2 1271 if (ns_info->protect_kernel_tunables) {
2897b343 1272 r = append_static_mounts(&m, protect_kernel_tunables_table, ELEMENTSOF(protect_kernel_tunables_table), ns_info->ignore_protect_paths);
60f067b4 1273 if (r < 0)
2897b343 1274 goto finish;
60f067b4
JS
1275 }
1276
8a584da2 1277 if (ns_info->protect_kernel_modules) {
2897b343 1278 r = append_static_mounts(&m, protect_kernel_modules_table, ELEMENTSOF(protect_kernel_modules_table), ns_info->ignore_protect_paths);
60f067b4 1279 if (r < 0)
2897b343 1280 goto finish;
60f067b4
JS
1281 }
1282
8a584da2 1283 if (ns_info->protect_control_groups) {
2897b343
MP
1284 *(m++) = (MountEntry) {
1285 .path_const = "/sys/fs/cgroup",
1286 .mode = READONLY,
1287 };
8a584da2
MP
1288 }
1289
2897b343 1290 r = append_protect_home(&m, protect_home, ns_info->ignore_protect_paths);
8a584da2 1291 if (r < 0)
2897b343 1292 goto finish;
8a584da2 1293
2897b343 1294 r = append_protect_system(&m, protect_system, false);
8a584da2 1295 if (r < 0)
2897b343 1296 goto finish;
8a584da2 1297
6e866b33 1298 if (namespace_info_mount_apivfs(ns_info)) {
2897b343
MP
1299 r = append_static_mounts(&m, apivfs_table, ELEMENTSOF(apivfs_table), ns_info->ignore_protect_paths);
1300 if (r < 0)
1301 goto finish;
1302 }
1303
1304 assert(mounts + n_mounts == m);
60f067b4 1305
2897b343 1306 /* Prepend the root directory where that's necessary */
f5e65279 1307 r = prefix_where_needed(mounts, n_mounts, root);
8a584da2
MP
1308 if (r < 0)
1309 goto finish;
1310
6e866b33 1311 normalize_mounts(root, mounts, &n_mounts);
60f067b4
JS
1312 }
1313
6e866b33
MB
1314 /* All above is just preparation, figuring out what to do. Let's now actually start doing something. */
1315
8a584da2 1316 if (unshare(CLONE_NEWNS) < 0) {
6e866b33
MB
1317 r = log_debug_errno(errno, "Failed to unshare the mount namespace: %m");
1318 if (IN_SET(r, -EACCES, -EPERM, -EOPNOTSUPP, -ENOSYS))
1319 /* If the kernel doesn't support namespaces, or when there's a MAC or seccomp filter in place
1320 * that doesn't allow us to create namespaces (or a missing cap), then propagate a recognizable
1321 * error back, which the caller can use to detect this case (and only this) and optionally
1322 * continue without namespacing applied. */
1323 r = -ENOANO;
1324
8a584da2
MP
1325 goto finish;
1326 }
1327
6e866b33
MB
1328 /* Remount / as SLAVE so that nothing now mounted in the namespace
1329 * shows up in the parent */
1330 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) {
1331 r = log_debug_errno(errno, "Failed to remount '/' as SLAVE: %m");
1332 goto finish;
e3bff60a
MP
1333 }
1334
2897b343 1335 if (root_image) {
f5e65279 1336 /* A root image is specified, mount it to the right place */
52ad194e 1337 r = dissected_image_mount(dissected_image, root, UID_INVALID, dissect_image_flags);
6e866b33
MB
1338 if (r < 0) {
1339 log_debug_errno(r, "Failed to mount root image: %m");
2897b343 1340 goto finish;
6e866b33 1341 }
2897b343 1342
f5e65279
MB
1343 if (decrypted_image) {
1344 r = decrypted_image_relinquish(decrypted_image);
6e866b33
MB
1345 if (r < 0) {
1346 log_debug_errno(r, "Failed to relinquish decrypted image: %m");
f5e65279 1347 goto finish;
6e866b33 1348 }
f5e65279 1349 }
2897b343
MP
1350
1351 loop_device_relinquish(loop_device);
1352
1353 } else if (root_directory) {
1354
f5e65279
MB
1355 /* A root directory is specified. Turn its directory into bind mount, if it isn't one yet. */
1356 r = path_is_mount_point(root, NULL, AT_SYMLINK_FOLLOW);
6e866b33
MB
1357 if (r < 0) {
1358 log_debug_errno(r, "Failed to detect that %s is a mount point or not: %m", root);
8a584da2 1359 goto finish;
6e866b33 1360 }
8a584da2 1361 if (r == 0) {
f5e65279 1362 if (mount(root, root, NULL, MS_BIND|MS_REC, NULL) < 0) {
6e866b33 1363 r = log_debug_errno(errno, "Failed to bind mount '%s': %m", root);
8a584da2
MP
1364 goto finish;
1365 }
1366 }
f5e65279 1367
6e866b33 1368 } else {
f5e65279
MB
1369
1370 /* Let's mount the main root directory to the root directory to use */
1371 if (mount("/", root, NULL, MS_BIND|MS_REC, NULL) < 0) {
6e866b33 1372 r = log_debug_errno(errno, "Failed to bind mount '/' on '%s': %m", root);
f5e65279
MB
1373 goto finish;
1374 }
e3bff60a 1375 }
60f067b4 1376
52ad194e
MB
1377 /* Try to set up the new root directory before mounting anything else there. */
1378 if (root_image || root_directory)
1379 (void) base_filesystem_create(root, UID_INVALID, GID_INVALID);
1380
2897b343 1381 if (n_mounts > 0) {
81c58355 1382 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
8a584da2 1383 char **blacklist;
b012e921 1384 size_t j;
8a584da2 1385
81c58355
MB
1386 /* Open /proc/self/mountinfo now as it may become unavailable if we mount anything on top of /proc.
1387 * For example, this is the case with the option: 'InaccessiblePaths=/proc' */
1388 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
1389 if (!proc_self_mountinfo) {
6e866b33 1390 r = log_debug_errno(errno, "Failed to open /proc/self/mountinfo: %m");
81c58355
MB
1391 goto finish;
1392 }
1393
b012e921
MB
1394 /* First round, establish all mounts we need */
1395 for (;;) {
1396 bool again = false;
1397
1398 for (m = mounts; m < mounts + n_mounts; ++m) {
1399
1400 if (m->applied)
1401 continue;
1402
1403 r = follow_symlink(root, m);
1404 if (r < 0)
1405 goto finish;
1406 if (r == 0) {
1407 /* We hit a symlinked mount point. The entry got rewritten and might point to a
1408 * very different place now. Let's normalize the changed list, and start from
1409 * the beginning. After all to mount the entry at the new location we might
1410 * need some other mounts first */
1411 again = true;
1412 break;
1413 }
1414
1415 r = apply_mount(root, m);
1416 if (r < 0)
1417 goto finish;
1418
1419 m->applied = true;
1420 }
1421
1422 if (!again)
1423 break;
1424
6e866b33 1425 normalize_mounts(root, mounts, &n_mounts);
60f067b4
JS
1426 }
1427
8a584da2 1428 /* Create a blacklist we can pass to bind_mount_recursive() */
2897b343
MP
1429 blacklist = newa(char*, n_mounts+1);
1430 for (j = 0; j < n_mounts; j++)
1431 blacklist[j] = (char*) mount_entry_path(mounts+j);
8a584da2
MP
1432 blacklist[j] = NULL;
1433
1434 /* Second round, flip the ro bits if necessary. */
2897b343 1435 for (m = mounts; m < mounts + n_mounts; ++m) {
81c58355 1436 r = make_read_only(m, blacklist, proc_self_mountinfo);
60f067b4 1437 if (r < 0)
8a584da2 1438 goto finish;
60f067b4
JS
1439 }
1440 }
1441
6e866b33
MB
1442 /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
1443 r = mount_move_root(root);
1444 if (r < 0) {
1445 log_debug_errno(r, "Failed to mount root with MS_MOVE: %m");
1446 goto finish;
e3bff60a
MP
1447 }
1448
98393f85 1449 /* Remount / as the desired mode. Note that this will not
60f067b4
JS
1450 * reestablish propagation from our side to the host, since
1451 * what's disconnected is disconnected. */
8a584da2 1452 if (mount(NULL, "/", NULL, mount_flags | MS_REC, NULL) < 0) {
6e866b33 1453 r = log_debug_errno(errno, "Failed to remount '/' with desired mount flags: %m");
8a584da2
MP
1454 goto finish;
1455 }
60f067b4 1456
8a584da2 1457 r = 0;
60f067b4 1458
8a584da2 1459finish:
2897b343
MP
1460 for (m = mounts; m < mounts + n_mounts; m++)
1461 mount_entry_done(m);
60f067b4
JS
1462
1463 return r;
663996b3
MS
1464}
1465
b012e921
MB
1466void bind_mount_free_many(BindMount *b, size_t n) {
1467 size_t i;
2897b343
MP
1468
1469 assert(b || n == 0);
1470
1471 for (i = 0; i < n; i++) {
1472 free(b[i].source);
1473 free(b[i].destination);
1474 }
1475
1476 free(b);
1477}
1478
b012e921 1479int bind_mount_add(BindMount **b, size_t *n, const BindMount *item) {
2897b343
MP
1480 _cleanup_free_ char *s = NULL, *d = NULL;
1481 BindMount *c;
1482
1483 assert(b);
1484 assert(n);
1485 assert(item);
1486
1487 s = strdup(item->source);
1488 if (!s)
1489 return -ENOMEM;
1490
1491 d = strdup(item->destination);
1492 if (!d)
1493 return -ENOMEM;
1494
98393f85 1495 c = reallocarray(*b, *n + 1, sizeof(BindMount));
2897b343
MP
1496 if (!c)
1497 return -ENOMEM;
1498
1499 *b = c;
1500
1501 c[(*n) ++] = (BindMount) {
b012e921
MB
1502 .source = TAKE_PTR(s),
1503 .destination = TAKE_PTR(d),
2897b343
MP
1504 .read_only = item->read_only,
1505 .recursive = item->recursive,
1506 .ignore_enoent = item->ignore_enoent,
1507 };
1508
2897b343
MP
1509 return 0;
1510}
1511
b012e921
MB
1512void temporary_filesystem_free_many(TemporaryFileSystem *t, size_t n) {
1513 size_t i;
98393f85
MB
1514
1515 assert(t || n == 0);
1516
1517 for (i = 0; i < n; i++) {
1518 free(t[i].path);
1519 free(t[i].options);
1520 }
1521
1522 free(t);
1523}
1524
1525int temporary_filesystem_add(
1526 TemporaryFileSystem **t,
b012e921 1527 size_t *n,
98393f85
MB
1528 const char *path,
1529 const char *options) {
1530
1531 _cleanup_free_ char *p = NULL, *o = NULL;
1532 TemporaryFileSystem *c;
1533
1534 assert(t);
1535 assert(n);
1536 assert(path);
1537
1538 p = strdup(path);
1539 if (!p)
1540 return -ENOMEM;
1541
1542 if (!isempty(options)) {
1543 o = strdup(options);
1544 if (!o)
1545 return -ENOMEM;
1546 }
1547
1548 c = reallocarray(*t, *n + 1, sizeof(TemporaryFileSystem));
1549 if (!c)
1550 return -ENOMEM;
1551
1552 *t = c;
1553
1554 c[(*n) ++] = (TemporaryFileSystem) {
b012e921
MB
1555 .path = TAKE_PTR(p),
1556 .options = TAKE_PTR(o),
98393f85
MB
1557 };
1558
98393f85
MB
1559 return 0;
1560}
1561
60f067b4
JS
1562static int setup_one_tmp_dir(const char *id, const char *prefix, char **path) {
1563 _cleanup_free_ char *x = NULL;
1564 char bid[SD_ID128_STRING_MAX];
1565 sd_id128_t boot_id;
1566 int r;
1567
1568 assert(id);
1569 assert(prefix);
1570 assert(path);
1571
1572 /* We include the boot id in the directory so that after a
1573 * reboot we can easily identify obsolete directories. */
1574
1575 r = sd_id128_get_boot(&boot_id);
1576 if (r < 0)
1577 return r;
1578
2897b343 1579 x = strjoin(prefix, "/systemd-private-", sd_id128_to_string(boot_id, bid), "-", id, "-XXXXXX");
60f067b4
JS
1580 if (!x)
1581 return -ENOMEM;
1582
1583 RUN_WITH_UMASK(0077)
1584 if (!mkdtemp(x))
1585 return -errno;
1586
1587 RUN_WITH_UMASK(0000) {
1588 char *y;
1589
e735f4d4 1590 y = strjoina(x, "/tmp");
60f067b4
JS
1591
1592 if (mkdir(y, 0777 | S_ISVTX) < 0)
1593 return -errno;
1594 }
1595
b012e921 1596 *path = TAKE_PTR(x);
663996b3 1597
60f067b4
JS
1598 return 0;
1599}
1600
1601int setup_tmp_dirs(const char *id, char **tmp_dir, char **var_tmp_dir) {
1602 char *a, *b;
1603 int r;
1604
1605 assert(id);
663996b3
MS
1606 assert(tmp_dir);
1607 assert(var_tmp_dir);
1608
60f067b4 1609 r = setup_one_tmp_dir(id, "/tmp", &a);
663996b3
MS
1610 if (r < 0)
1611 return r;
1612
60f067b4
JS
1613 r = setup_one_tmp_dir(id, "/var/tmp", &b);
1614 if (r < 0) {
1615 char *t;
663996b3 1616
e735f4d4 1617 t = strjoina(a, "/tmp");
60f067b4
JS
1618 rmdir(t);
1619 rmdir(a);
663996b3 1620
60f067b4
JS
1621 free(a);
1622 return r;
1623 }
1624
1625 *tmp_dir = a;
1626 *var_tmp_dir = b;
1627
1628 return 0;
663996b3
MS
1629}
1630
60f067b4
JS
1631int setup_netns(int netns_storage_socket[2]) {
1632 _cleanup_close_ int netns = -1;
6300502b 1633 int r, q;
663996b3 1634
60f067b4
JS
1635 assert(netns_storage_socket);
1636 assert(netns_storage_socket[0] >= 0);
1637 assert(netns_storage_socket[1] >= 0);
663996b3 1638
60f067b4
JS
1639 /* We use the passed socketpair as a storage buffer for our
1640 * namespace reference fd. Whatever process runs this first
1641 * shall create a new namespace, all others should just join
1642 * it. To serialize that we use a file lock on the socket
1643 * pair.
1644 *
1645 * It's a bit crazy, but hey, works great! */
1646
1647 if (lockf(netns_storage_socket[0], F_LOCK, 0) < 0)
663996b3
MS
1648 return -errno;
1649
6300502b
MP
1650 netns = receive_one_fd(netns_storage_socket[0], MSG_DONTWAIT);
1651 if (netns == -EAGAIN) {
60f067b4 1652 /* Nothing stored yet, so let's create a new namespace */
663996b3 1653
60f067b4
JS
1654 if (unshare(CLONE_NEWNET) < 0) {
1655 r = -errno;
1656 goto fail;
1657 }
663996b3 1658
60f067b4 1659 loopback_setup();
663996b3 1660
60f067b4
JS
1661 netns = open("/proc/self/ns/net", O_RDONLY|O_CLOEXEC|O_NOCTTY);
1662 if (netns < 0) {
1663 r = -errno;
1664 goto fail;
1665 }
663996b3 1666
60f067b4 1667 r = 1;
663996b3 1668
6300502b
MP
1669 } else if (netns < 0) {
1670 r = netns;
1671 goto fail;
663996b3 1672
6300502b
MP
1673 } else {
1674 /* Yay, found something, so let's join the namespace */
60f067b4
JS
1675 if (setns(netns, CLONE_NEWNET) < 0) {
1676 r = -errno;
1677 goto fail;
1678 }
663996b3 1679
60f067b4 1680 r = 0;
663996b3
MS
1681 }
1682
6300502b
MP
1683 q = send_one_fd(netns_storage_socket[1], netns, MSG_DONTWAIT);
1684 if (q < 0) {
1685 r = q;
60f067b4 1686 goto fail;
663996b3
MS
1687 }
1688
60f067b4 1689fail:
5a920b42 1690 (void) lockf(netns_storage_socket[0], F_ULOCK, 0);
663996b3
MS
1691 return r;
1692}
60f067b4 1693
52ad194e
MB
1694bool ns_type_supported(NamespaceType type) {
1695 const char *t, *ns_proc;
1696
1697 t = namespace_type_to_string(type);
1698 if (!t) /* Don't know how to translate this? Then it's not supported */
1699 return false;
1700
1701 ns_proc = strjoina("/proc/self/ns/", t);
1702 return access(ns_proc, F_OK) == 0;
1703}
1704
60f067b4
JS
1705static const char *const protect_home_table[_PROTECT_HOME_MAX] = {
1706 [PROTECT_HOME_NO] = "no",
1707 [PROTECT_HOME_YES] = "yes",
1708 [PROTECT_HOME_READ_ONLY] = "read-only",
98393f85 1709 [PROTECT_HOME_TMPFS] = "tmpfs",
60f067b4
JS
1710};
1711
b012e921 1712DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_home, ProtectHome, PROTECT_HOME_YES);
1d42b86d 1713
60f067b4
JS
1714static const char *const protect_system_table[_PROTECT_SYSTEM_MAX] = {
1715 [PROTECT_SYSTEM_NO] = "no",
1716 [PROTECT_SYSTEM_YES] = "yes",
1717 [PROTECT_SYSTEM_FULL] = "full",
8a584da2 1718 [PROTECT_SYSTEM_STRICT] = "strict",
60f067b4
JS
1719};
1720
b012e921 1721DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_system, ProtectSystem, PROTECT_SYSTEM_YES);
1d42b86d 1722
52ad194e
MB
1723static const char* const namespace_type_table[] = {
1724 [NAMESPACE_MOUNT] = "mnt",
1725 [NAMESPACE_CGROUP] = "cgroup",
1726 [NAMESPACE_UTS] = "uts",
1727 [NAMESPACE_IPC] = "ipc",
1728 [NAMESPACE_USER] = "user",
1729 [NAMESPACE_PID] = "pid",
1730 [NAMESPACE_NET] = "net",
1731};
1732
1733DEFINE_STRING_TABLE_LOOKUP(namespace_type, NamespaceType);