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