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