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