]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/namespace.c
MountImages: actually support optional paths
[thirdparty/systemd.git] / src / core / namespace.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
15ae422b
LP
2
3#include <errno.h>
e08f94ac 4#include <linux/loop.h>
07630cea 5#include <sched.h>
15ae422b 6#include <stdio.h>
07630cea 7#include <sys/mount.h>
07630cea 8#include <unistd.h>
25e870b5 9#include <linux/fs.h>
15ae422b 10
b5efdb8a 11#include "alloc-util.h"
10404d52 12#include "base-filesystem.h"
7f112f50 13#include "dev-setup.h"
3ffd4af2 14#include "fd-util.h"
e5f10caf 15#include "format-util.h"
d944dc95 16#include "fs-util.h"
e908468b 17#include "label.h"
b3d13314 18#include "list.h"
915e6d16 19#include "loop-util.h"
07630cea 20#include "loopback-setup.h"
07630cea 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"
a652f050 35#include "tmpfile-util.h"
affb60b1 36#include "umask-util.h"
ee104e11 37#include "user-util.h"
15ae422b 38
737ba3c8 39#define DEV_MOUNT_OPTIONS (MS_NOSUID|MS_STRICTATIME|MS_NOEXEC)
40
c17ec25e 41typedef enum MountMode {
15ae422b
LP
42 /* This is ordered by priority! */
43 INACCESSIBLE,
b3d13314 44 MOUNT_IMAGES,
d2d6c096
LP
45 BIND_MOUNT,
46 BIND_MOUNT_RECURSIVE,
ac0930c8 47 PRIVATE_TMP,
56a13a49 48 PRIVATE_TMP_READONLY,
7f112f50 49 PRIVATE_DEV,
5d997827 50 BIND_DEV,
6c47cd7d 51 EMPTY_DIR,
5d997827
LP
52 SYSFS,
53 PROCFS,
94293d65 54 RUN,
5d997827 55 READONLY,
59eeb84b 56 READWRITE,
ddc155b2
TM
57 NOEXEC,
58 EXEC,
2abd4e38 59 TMPFS,
1e05071d 60 READWRITE_IMPLICIT, /* Should have the lowest priority. */
5beb8688 61 _MOUNT_MODE_MAX,
c17ec25e 62} MountMode;
15ae422b 63
34de407a 64typedef struct MountEntry {
5327c910 65 const char *path_const; /* Memory allocated on stack or static */
cfbeb4ef 66 MountMode mode:5;
5327c910
LP
67 bool ignore:1; /* Ignore if path does not exist? */
68 bool has_prefix:1; /* Already is prefixed by the root dir? */
cfbeb4ef 69 bool read_only:1; /* Shall this mount point be read-only? */
9ce4e4b0 70 bool nosuid:1; /* Shall set MS_NOSUID on the mount itself */
ddc155b2
TM
71 bool noexec:1; /* Shall set MS_NOEXEC on the mount itself */
72 bool exec:1; /* Shall clear MS_NOEXEC on the mount itself */
088696fe 73 bool applied:1; /* Already applied */
55fe7432 74 char *path_malloc; /* Use this instead of 'path_const' if we had to allocate memory */
b3d13314 75 const char *source_const; /* The source path, for bind mounts or images */
d2d6c096 76 char *source_malloc;
2abd4e38
YW
77 const char *options_const;/* Mount options for tmpfs */
78 char *options_malloc;
79 unsigned long flags; /* Mount flags used by EMPTY_DIR and TMPFS. Do not include MS_RDONLY here, but please use read_only. */
088696fe 80 unsigned n_followed;
427353f6 81 LIST_HEAD(MountOptions, image_options);
34de407a 82} MountEntry;
15ae422b 83
94293d65 84/* If MountAPIVFS= is used, let's mount /sys, /proc, /dev and /run into the it, but only as a fallback if the user hasn't mounted
3fe91079 85 * something there already. These mounts are hence overridden by any other explicitly configured mounts. */
5d997827
LP
86static const MountEntry apivfs_table[] = {
87 { "/proc", PROCFS, false },
88 { "/dev", BIND_DEV, false },
89 { "/sys", SYSFS, false },
94293d65 90 { "/run", RUN, false, .options_const = "mode=755" TMPFS_LIMITS_RUN, .flags = MS_NOSUID|MS_NODEV|MS_STRICTATIME },
5d997827 91};
f471b2af 92
11a30cec 93/* ProtectKernelTunables= option and the related filesystem APIs */
34de407a 94static const MountEntry protect_kernel_tunables_table[] = {
1e05071d
YW
95 { "/proc/acpi", READONLY, true },
96 { "/proc/apm", READONLY, true }, /* Obsolete API, there's no point in permitting access to this, ever */
97 { "/proc/asound", READONLY, true },
98 { "/proc/bus", READONLY, true },
99 { "/proc/fs", READONLY, true },
100 { "/proc/irq", READONLY, true },
101 { "/proc/kallsyms", INACCESSIBLE, true },
102 { "/proc/kcore", INACCESSIBLE, true },
103 { "/proc/latency_stats", READONLY, true },
104 { "/proc/mtrr", READONLY, true },
105 { "/proc/scsi", READONLY, true },
4e399953 106 { "/proc/sys", READONLY, true },
1e05071d
YW
107 { "/proc/sysrq-trigger", READONLY, true },
108 { "/proc/timer_stats", READONLY, true },
109 { "/sys", READONLY, false },
110 { "/sys/fs/bpf", READONLY, true },
111 { "/sys/fs/cgroup", READWRITE_IMPLICIT, false }, /* READONLY is set by ProtectControlGroups= option */
112 { "/sys/fs/selinux", READWRITE_IMPLICIT, true },
113 { "/sys/kernel/debug", READONLY, true },
114 { "/sys/kernel/tracing", READONLY, true },
11a30cec
DH
115};
116
c575770b 117/* ProtectKernelModules= option */
34de407a 118static const MountEntry protect_kernel_modules_table[] = {
349cc4a5 119#if HAVE_SPLIT_USR
c6232fb0 120 { "/lib/modules", INACCESSIBLE, true },
c575770b 121#endif
c6232fb0 122 { "/usr/lib/modules", INACCESSIBLE, true },
c575770b
DH
123};
124
94a7b275
KK
125/* ProtectKernelLogs= option */
126static const MountEntry protect_kernel_logs_table[] = {
127 { "/proc/kmsg", INACCESSIBLE, true },
128 { "/dev/kmsg", INACCESSIBLE, true },
129};
130
b6c432ca
DH
131/*
132 * ProtectHome=read-only table, protect $HOME and $XDG_RUNTIME_DIR and rest of
133 * system should be protected by ProtectSystem=
134 */
34de407a 135static const MountEntry protect_home_read_only_table[] = {
c6232fb0
LP
136 { "/home", READONLY, true },
137 { "/run/user", READONLY, true },
138 { "/root", READONLY, true },
b6c432ca
DH
139};
140
e4da7d8c
YW
141/* ProtectHome=tmpfs table */
142static const MountEntry protect_home_tmpfs_table[] = {
7d85383e
TM
143 { "/home", TMPFS, true, .read_only = true, .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
144 { "/run/user", TMPFS, true, .read_only = true, .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
145 { "/root", TMPFS, true, .read_only = true, .options_const = "mode=0700" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
e4da7d8c
YW
146};
147
b6c432ca 148/* ProtectHome=yes table */
34de407a 149static const MountEntry protect_home_yes_table[] = {
c6232fb0
LP
150 { "/home", INACCESSIBLE, true },
151 { "/run/user", INACCESSIBLE, true },
152 { "/root", INACCESSIBLE, true },
b6c432ca
DH
153};
154
f471b2af 155/* ProtectSystem=yes table */
34de407a 156static const MountEntry protect_system_yes_table[] = {
c6232fb0
LP
157 { "/usr", READONLY, false },
158 { "/boot", READONLY, true },
159 { "/efi", READONLY, true },
7486f305
AB
160#if HAVE_SPLIT_USR
161 { "/lib", READONLY, true },
162 { "/lib64", READONLY, true },
163 { "/bin", READONLY, true },
671f0f8d 164# if HAVE_SPLIT_BIN
7486f305 165 { "/sbin", READONLY, true },
671f0f8d 166# endif
7486f305 167#endif
f471b2af
DH
168};
169
170/* ProtectSystem=full includes ProtectSystem=yes */
34de407a 171static const MountEntry protect_system_full_table[] = {
c6232fb0
LP
172 { "/usr", READONLY, false },
173 { "/boot", READONLY, true },
174 { "/efi", READONLY, true },
175 { "/etc", READONLY, false },
7486f305
AB
176#if HAVE_SPLIT_USR
177 { "/lib", READONLY, true },
178 { "/lib64", READONLY, true },
179 { "/bin", READONLY, true },
671f0f8d 180# if HAVE_SPLIT_BIN
7486f305 181 { "/sbin", READONLY, true },
671f0f8d 182# endif
7486f305 183#endif
f471b2af
DH
184};
185
186/*
187 * ProtectSystem=strict table. In this strict mode, we mount everything
188 * read-only, except for /proc, /dev, /sys which are the kernel API VFS,
189 * which are left writable, but PrivateDevices= + ProtectKernelTunables=
190 * protect those, and these options should be fully orthogonal.
191 * (And of course /home and friends are also left writable, as ProtectHome=
192 * shall manage those, orthogonally).
193 */
34de407a 194static const MountEntry protect_system_strict_table[] = {
1e05071d
YW
195 { "/", READONLY, false },
196 { "/proc", READWRITE_IMPLICIT, false }, /* ProtectKernelTunables= */
197 { "/sys", READWRITE_IMPLICIT, false }, /* ProtectKernelTunables= */
198 { "/dev", READWRITE_IMPLICIT, false }, /* PrivateDevices= */
199 { "/home", READWRITE_IMPLICIT, true }, /* ProtectHome= */
200 { "/run/user", READWRITE_IMPLICIT, true }, /* ProtectHome= */
201 { "/root", READWRITE_IMPLICIT, true }, /* ProtectHome= */
f471b2af
DH
202};
203
5beb8688
YW
204static const char * const mount_mode_table[_MOUNT_MODE_MAX] = {
205 [INACCESSIBLE] = "inaccessible",
206 [BIND_MOUNT] = "bind",
207 [BIND_MOUNT_RECURSIVE] = "rbind",
208 [PRIVATE_TMP] = "private-tmp",
209 [PRIVATE_DEV] = "private-dev",
210 [BIND_DEV] = "bind-dev",
211 [EMPTY_DIR] = "empty",
212 [SYSFS] = "sysfs",
213 [PROCFS] = "procfs",
214 [READONLY] = "read-only",
215 [READWRITE] = "read-write",
216 [TMPFS] = "tmpfs",
b3d13314 217 [MOUNT_IMAGES] = "mount-images",
5beb8688 218 [READWRITE_IMPLICIT] = "rw-implicit",
ddc155b2
TM
219 [EXEC] = "exec",
220 [NOEXEC] = "noexec",
5beb8688
YW
221};
222
223DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(mount_mode, MountMode);
224
34de407a 225static const char *mount_entry_path(const MountEntry *p) {
f0a4feb0
DH
226 assert(p);
227
5327c910
LP
228 /* Returns the path of this bind mount. If the malloc()-allocated ->path_buffer field is set we return that,
229 * otherwise the stack/static ->path field is returned. */
f0a4feb0 230
5327c910 231 return p->path_malloc ?: p->path_const;
f0a4feb0
DH
232}
233
34de407a 234static bool mount_entry_read_only(const MountEntry *p) {
cfbeb4ef
LP
235 assert(p);
236
56a13a49 237 return p->read_only || IN_SET(p->mode, READONLY, INACCESSIBLE, PRIVATE_TMP_READONLY);
cfbeb4ef
LP
238}
239
ddc155b2
TM
240static bool mount_entry_noexec(const MountEntry *p) {
241 assert(p);
242
243 return p->noexec || IN_SET(p->mode, NOEXEC, INACCESSIBLE, SYSFS, PROCFS);
244}
245
246static bool mount_entry_exec(const MountEntry *p) {
247 assert(p);
248
249 return p->exec || p->mode == EXEC;
250}
251
d2d6c096
LP
252static const char *mount_entry_source(const MountEntry *p) {
253 assert(p);
254
255 return p->source_malloc ?: p->source_const;
256}
257
2abd4e38
YW
258static const char *mount_entry_options(const MountEntry *p) {
259 assert(p);
260
261 return p->options_malloc ?: p->options_const;
262}
263
1eb7e08e
LP
264static void mount_entry_done(MountEntry *p) {
265 assert(p);
266
267 p->path_malloc = mfree(p->path_malloc);
268 p->source_malloc = mfree(p->source_malloc);
2abd4e38 269 p->options_malloc = mfree(p->options_malloc);
427353f6 270 p->image_options = mount_options_free_all(p->image_options);
1eb7e08e
LP
271}
272
d18aff04 273static int append_access_mounts(MountEntry **p, char **strv, MountMode mode, bool forcibly_require_prefix) {
15ae422b
LP
274 char **i;
275
613b411c
LP
276 assert(p);
277
1e05071d 278 /* Adds a list of user-supplied READWRITE/READWRITE_IMPLICIT/READONLY/INACCESSIBLE entries */
5327c910 279
15ae422b 280 STRV_FOREACH(i, strv) {
5327c910
LP
281 bool ignore = false, needs_prefix = false;
282 const char *e = *i;
15ae422b 283
5327c910
LP
284 /* Look for any prefixes */
285 if (startswith(e, "-")) {
286 e++;
9c94d52e 287 ignore = true;
ea92ae33 288 }
5327c910
LP
289 if (startswith(e, "+")) {
290 e++;
291 needs_prefix = true;
292 }
ea92ae33 293
baaa35ad
ZJS
294 if (!path_is_absolute(e))
295 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
296 "Path is not absolute: %s", e);
15ae422b 297
34de407a 298 *((*p)++) = (MountEntry) {
5327c910
LP
299 .path_const = e,
300 .mode = mode,
301 .ignore = ignore,
d18aff04 302 .has_prefix = !needs_prefix && !forcibly_require_prefix,
5327c910 303 };
15ae422b
LP
304 }
305
306 return 0;
307}
308
6c47cd7d
LP
309static int append_empty_dir_mounts(MountEntry **p, char **strv) {
310 char **i;
311
312 assert(p);
313
314 /* Adds tmpfs mounts to provide readable but empty directories. This is primarily used to implement the
315 * "/private/" boundary directories for DynamicUser=1. */
316
317 STRV_FOREACH(i, strv) {
318
319 *((*p)++) = (MountEntry) {
320 .path_const = *i,
321 .mode = EMPTY_DIR,
322 .ignore = false,
6c47cd7d 323 .read_only = true,
7d85383e 324 .options_const = "mode=755" TMPFS_LIMITS_EMPTY_OR_ALMOST,
2abd4e38 325 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME,
6c47cd7d
LP
326 };
327 }
328
329 return 0;
330}
331
da6053d0 332static int append_bind_mounts(MountEntry **p, const BindMount *binds, size_t n) {
d2d6c096
LP
333 assert(p);
334
fe96c0f8 335 for (size_t i = 0; i < n; i++) {
d2d6c096
LP
336 const BindMount *b = binds + i;
337
338 *((*p)++) = (MountEntry) {
339 .path_const = b->destination,
340 .mode = b->recursive ? BIND_MOUNT_RECURSIVE : BIND_MOUNT,
341 .read_only = b->read_only,
9ce4e4b0 342 .nosuid = b->nosuid,
d2d6c096 343 .source_const = b->source,
4ca763a9 344 .ignore = b->ignore_enoent,
d2d6c096
LP
345 };
346 }
347
348 return 0;
349}
350
b3d13314
LB
351static int append_mount_images(MountEntry **p, const MountImage *mount_images, size_t n) {
352 assert(p);
353
354 for (size_t i = 0; i < n; i++) {
355 const MountImage *m = mount_images + i;
356
357 *((*p)++) = (MountEntry) {
358 .path_const = m->destination,
359 .mode = MOUNT_IMAGES,
360 .source_const = m->source,
427353f6 361 .image_options = m->mount_options,
b3d13314
LB
362 .ignore = m->ignore_enoent,
363 };
364 }
365
366 return 0;
367}
368
da6053d0 369static int append_tmpfs_mounts(MountEntry **p, const TemporaryFileSystem *tmpfs, size_t n) {
2abd4e38
YW
370 assert(p);
371
b67ec8e5 372 for (size_t i = 0; i < n; i++) {
2abd4e38
YW
373 const TemporaryFileSystem *t = tmpfs + i;
374 _cleanup_free_ char *o = NULL, *str = NULL;
ad8e66dc 375 unsigned long flags;
2abd4e38 376 bool ro = false;
b67ec8e5 377 int r;
2abd4e38 378
baaa35ad
ZJS
379 if (!path_is_absolute(t->path))
380 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
381 "Path is not absolute: %s",
382 t->path);
2abd4e38 383
b67ec8e5 384 str = strjoin("mode=0755" NESTED_TMPFS_LIMITS ",", t->options);
ad8e66dc
AJ
385 if (!str)
386 return -ENOMEM;
2abd4e38 387
ad8e66dc
AJ
388 r = mount_option_mangle(str, MS_NODEV|MS_STRICTATIME, &flags, &o);
389 if (r < 0)
390 return log_debug_errno(r, "Failed to parse mount option '%s': %m", str);
2abd4e38 391
ad8e66dc
AJ
392 ro = flags & MS_RDONLY;
393 if (ro)
394 flags ^= MS_RDONLY;
2abd4e38
YW
395
396 *((*p)++) = (MountEntry) {
397 .path_const = t->path,
398 .mode = TMPFS,
399 .read_only = ro,
ad8e66dc 400 .options_malloc = TAKE_PTR(o),
2abd4e38
YW
401 .flags = flags,
402 };
2abd4e38
YW
403 }
404
405 return 0;
406}
407
da6053d0 408static int append_static_mounts(MountEntry **p, const MountEntry *mounts, size_t n, bool ignore_protect) {
11a30cec 409 assert(p);
f471b2af 410 assert(mounts);
11a30cec 411
5327c910 412 /* Adds a list of static pre-defined entries */
f471b2af 413
fe96c0f8 414 for (size_t i = 0; i < n; i++)
34de407a
LP
415 *((*p)++) = (MountEntry) {
416 .path_const = mount_entry_path(mounts+i),
5327c910
LP
417 .mode = mounts[i].mode,
418 .ignore = mounts[i].ignore || ignore_protect,
419 };
f471b2af
DH
420
421 return 0;
422}
423
34de407a 424static int append_protect_home(MountEntry **p, ProtectHome protect_home, bool ignore_protect) {
c575770b
DH
425 assert(p);
426
5327c910 427 switch (protect_home) {
b6c432ca 428
5327c910 429 case PROTECT_HOME_NO:
b6c432ca
DH
430 return 0;
431
b6c432ca 432 case PROTECT_HOME_READ_ONLY:
5327c910
LP
433 return append_static_mounts(p, protect_home_read_only_table, ELEMENTSOF(protect_home_read_only_table), ignore_protect);
434
e4da7d8c
YW
435 case PROTECT_HOME_TMPFS:
436 return append_static_mounts(p, protect_home_tmpfs_table, ELEMENTSOF(protect_home_tmpfs_table), ignore_protect);
437
b6c432ca 438 case PROTECT_HOME_YES:
5327c910
LP
439 return append_static_mounts(p, protect_home_yes_table, ELEMENTSOF(protect_home_yes_table), ignore_protect);
440
b6c432ca 441 default:
5327c910 442 assert_not_reached("Unexpected ProtectHome= value");
b6c432ca 443 }
b6c432ca
DH
444}
445
34de407a 446static int append_protect_system(MountEntry **p, ProtectSystem protect_system, bool ignore_protect) {
f471b2af
DH
447 assert(p);
448
5327c910
LP
449 switch (protect_system) {
450
451 case PROTECT_SYSTEM_NO:
f471b2af
DH
452 return 0;
453
f471b2af 454 case PROTECT_SYSTEM_STRICT:
5327c910
LP
455 return append_static_mounts(p, protect_system_strict_table, ELEMENTSOF(protect_system_strict_table), ignore_protect);
456
f471b2af 457 case PROTECT_SYSTEM_YES:
5327c910
LP
458 return append_static_mounts(p, protect_system_yes_table, ELEMENTSOF(protect_system_yes_table), ignore_protect);
459
f471b2af 460 case PROTECT_SYSTEM_FULL:
5327c910
LP
461 return append_static_mounts(p, protect_system_full_table, ELEMENTSOF(protect_system_full_table), ignore_protect);
462
f471b2af 463 default:
5327c910 464 assert_not_reached("Unexpected ProtectSystem= value");
f471b2af 465 }
11a30cec
DH
466}
467
93bab288 468static int mount_path_compare(const MountEntry *a, const MountEntry *b) {
a0827e2b 469 int d;
15ae422b 470
6ee1a919 471 /* If the paths are not equal, then order prefixes first */
93bab288 472 d = path_compare(mount_entry_path(a), mount_entry_path(b));
6ee1a919
LP
473 if (d != 0)
474 return d;
15ae422b 475
6ee1a919 476 /* If the paths are equal, check the mode */
93bab288 477 return CMP((int) a->mode, (int) b->mode);
15ae422b
LP
478}
479
da6053d0 480static int prefix_where_needed(MountEntry *m, size_t n, const char *root_directory) {
4a756839 481 /* Prefixes all paths in the bind mount table with the root directory if the entry needs that. */
5327c910 482
fe96c0f8
SS
483 assert(m || n == 0);
484
485 for (size_t i = 0; i < n; i++) {
5327c910
LP
486 char *s;
487
488 if (m[i].has_prefix)
489 continue;
490
c6134d3e 491 s = path_join(root_directory, mount_entry_path(m+i));
5327c910
LP
492 if (!s)
493 return -ENOMEM;
494
e282f51f 495 free_and_replace(m[i].path_malloc, s);
5327c910
LP
496 m[i].has_prefix = true;
497 }
498
499 return 0;
500}
501
da6053d0 502static void drop_duplicates(MountEntry *m, size_t *n) {
34de407a 503 MountEntry *f, *t, *previous;
15ae422b 504
c17ec25e 505 assert(m);
15ae422b 506 assert(n);
15ae422b 507
fe3c2583
LP
508 /* Drops duplicate entries. Expects that the array is properly ordered already. */
509
1d54cd5d 510 for (f = m, t = m, previous = NULL; f < m + *n; f++) {
15ae422b 511
fe3c2583 512 /* The first one wins (which is the one with the more restrictive mode), see mount_path_compare()
088696fe
LP
513 * above. Note that we only drop duplicates that haven't been mounted yet. */
514 if (previous &&
515 path_equal(mount_entry_path(f), mount_entry_path(previous)) &&
516 !f->applied && !previous->applied) {
5beb8688 517 log_debug("%s (%s) is duplicate.", mount_entry_path(f), mount_mode_to_string(f->mode));
ddc155b2
TM
518 /* Propagate the flags to the remaining entry */
519 previous->read_only = previous->read_only || mount_entry_read_only(f);
520 previous->noexec = previous->noexec || mount_entry_noexec(f);
521 previous->exec = previous->exec || mount_entry_exec(f);
1eb7e08e 522 mount_entry_done(f);
15ae422b 523 continue;
fe3c2583 524 }
15ae422b 525
e2d7c1a0 526 *t = *f;
15ae422b 527 previous = t;
fe3c2583
LP
528 t++;
529 }
530
531 *n = t - m;
532}
533
da6053d0 534static void drop_inaccessible(MountEntry *m, size_t *n) {
34de407a 535 MountEntry *f, *t;
fe3c2583
LP
536 const char *clear = NULL;
537
538 assert(m);
539 assert(n);
540
541 /* Drops all entries obstructed by another entry further up the tree. Expects that the array is properly
542 * ordered already. */
543
1d54cd5d 544 for (f = m, t = m; f < m + *n; f++) {
fe3c2583
LP
545
546 /* If we found a path set for INACCESSIBLE earlier, and this entry has it as prefix we should drop
547 * it, as inaccessible paths really should drop the entire subtree. */
34de407a
LP
548 if (clear && path_startswith(mount_entry_path(f), clear)) {
549 log_debug("%s is masked by %s.", mount_entry_path(f), clear);
1eb7e08e 550 mount_entry_done(f);
fe3c2583
LP
551 continue;
552 }
15ae422b 553
34de407a 554 clear = f->mode == INACCESSIBLE ? mount_entry_path(f) : NULL;
fe3c2583
LP
555
556 *t = *f;
15ae422b
LP
557 t++;
558 }
559
c17ec25e 560 *n = t - m;
15ae422b
LP
561}
562
da6053d0 563static void drop_nop(MountEntry *m, size_t *n) {
34de407a 564 MountEntry *f, *t;
7648a565
LP
565
566 assert(m);
567 assert(n);
568
569 /* Drops all entries which have an immediate parent that has the same type, as they are redundant. Assumes the
570 * list is ordered by prefixes. */
571
1d54cd5d 572 for (f = m, t = m; f < m + *n; f++) {
7648a565 573
1e05071d
YW
574 /* Only suppress such subtrees for READONLY, READWRITE and READWRITE_IMPLICIT entries */
575 if (IN_SET(f->mode, READONLY, READWRITE, READWRITE_IMPLICIT)) {
34de407a 576 MountEntry *p;
7648a565
LP
577 bool found = false;
578
579 /* Now let's find the first parent of the entry we are looking at. */
580 for (p = t-1; p >= m; p--) {
34de407a 581 if (path_startswith(mount_entry_path(f), mount_entry_path(p))) {
7648a565
LP
582 found = true;
583 break;
584 }
585 }
586
587 /* We found it, let's see if it's the same mode, if so, we can drop this entry */
588 if (found && p->mode == f->mode) {
5beb8688
YW
589 log_debug("%s (%s) is made redundant by %s (%s)",
590 mount_entry_path(f), mount_mode_to_string(f->mode),
591 mount_entry_path(p), mount_mode_to_string(p->mode));
1eb7e08e 592 mount_entry_done(f);
7648a565
LP
593 continue;
594 }
595 }
596
597 *t = *f;
598 t++;
599 }
600
601 *n = t - m;
602}
603
da6053d0 604static void drop_outside_root(const char *root_directory, MountEntry *m, size_t *n) {
34de407a 605 MountEntry *f, *t;
cd2902c9
LP
606
607 assert(m);
608 assert(n);
609
1d54cd5d 610 /* Nothing to do */
cd2902c9
LP
611 if (!root_directory)
612 return;
613
614 /* Drops all mounts that are outside of the root directory. */
615
1d54cd5d 616 for (f = m, t = m; f < m + *n; f++) {
cd2902c9 617
34de407a
LP
618 if (!path_startswith(mount_entry_path(f), root_directory)) {
619 log_debug("%s is outside of root directory.", mount_entry_path(f));
1eb7e08e 620 mount_entry_done(f);
cd2902c9
LP
621 continue;
622 }
623
624 *t = *f;
625 t++;
626 }
627
628 *n = t - m;
629}
630
b2a60844
LP
631static int clone_device_node(
632 const char *d,
633 const char *temporary_mount,
634 bool *make_devnode) {
635
636 _cleanup_free_ char *sl = NULL;
637 const char *dn, *bn, *t;
b5e99f23
ДГ
638 struct stat st;
639 int r;
640
414b304b 641 if (stat(d, &st) < 0) {
b2a60844
LP
642 if (errno == ENOENT) {
643 log_debug_errno(errno, "Device node '%s' to clone does not exist, ignoring.", d);
af984e13 644 return -ENXIO;
b2a60844
LP
645 }
646
647 return log_debug_errno(errno, "Failed to stat() device node '%s' to clone, ignoring: %m", d);
b5e99f23
ДГ
648 }
649
650 if (!S_ISBLK(st.st_mode) &&
baaa35ad
ZJS
651 !S_ISCHR(st.st_mode))
652 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
653 "Device node '%s' to clone is not a device node, ignoring.",
654 d);
b5e99f23 655
6f7f3a33 656 dn = strjoina(temporary_mount, d);
b5e99f23 657
b2a60844 658 /* First, try to create device node properly */
16498617
CB
659 if (*make_devnode) {
660 mac_selinux_create_file_prepare(d, st.st_mode);
661 r = mknod(dn, st.st_mode, st.st_rdev);
662 mac_selinux_create_file_clear();
b2a60844
LP
663 if (r >= 0)
664 goto add_symlink;
16498617
CB
665 if (errno != EPERM)
666 return log_debug_errno(errno, "mknod failed for %s: %m", d);
667
b2a60844 668 /* This didn't work, let's not try this again for the next iterations. */
16498617
CB
669 *make_devnode = false;
670 }
671
2aed63f4 672 /* We're about to fall back to bind-mounting the device
1acf344d
CG
673 * node. So create a dummy bind-mount target.
674 * Do not prepare device-node SELinux label (see issue 13762) */
16498617 675 r = mknod(dn, S_IFREG, 0);
16498617 676 if (r < 0 && errno != EEXIST)
b2a60844 677 return log_debug_errno(errno, "mknod() fallback failed for '%s': %m", d);
16498617 678
21935150
LP
679 /* Fallback to bind-mounting: The assumption here is that all used device nodes carry standard
680 * properties. Specifically, the devices nodes we bind-mount should either be owned by root:root or
681 * root:tty (e.g. /dev/tty, /dev/ptmx) and should not carry ACLs. */
682 r = mount_nofollow_verbose(LOG_DEBUG, d, dn, NULL, MS_BIND, NULL);
683 if (r < 0)
684 return r;
b2a60844
LP
685
686add_symlink:
687 bn = path_startswith(d, "/dev/");
688 if (!bn)
689 return 0;
690
691 /* Create symlinks like /dev/char/1:9 → ../urandom */
cbc056c8
ZJS
692 if (asprintf(&sl, "%s/dev/%s/%u:%u",
693 temporary_mount,
694 S_ISCHR(st.st_mode) ? "char" : "block",
695 major(st.st_rdev), minor(st.st_rdev)) < 0)
b2a60844
LP
696 return log_oom();
697
698 (void) mkdir_parents(sl, 0755);
699
700 t = strjoina("../", bn);
b2a60844 701 if (symlink(t, sl) < 0)
2e4a4fae 702 log_debug_errno(errno, "Failed to symlink '%s' to '%s', ignoring: %m", t, sl);
b5e99f23 703
af984e13 704 return 0;
b5e99f23
ДГ
705}
706
5d997827 707static int mount_private_dev(MountEntry *m) {
7f112f50
LP
708 static const char devnodes[] =
709 "/dev/null\0"
710 "/dev/zero\0"
711 "/dev/full\0"
712 "/dev/random\0"
713 "/dev/urandom\0"
714 "/dev/tty\0";
715
2b85f4e1 716 char temporary_mount[] = "/tmp/namespace-dev-XXXXXX";
63cc4c31 717 const char *d, *dev = NULL, *devpts = NULL, *devshm = NULL, *devhugepages = NULL, *devmqueue = NULL, *devlog = NULL, *devptmx = NULL;
16498617 718 bool can_mknod = true;
7f112f50
LP
719 _cleanup_umask_ mode_t u;
720 int r;
721
722 assert(m);
723
724 u = umask(0000);
725
2b85f4e1 726 if (!mkdtemp(temporary_mount))
2e4a4fae 727 return log_debug_errno(errno, "Failed to create temporary directory '%s': %m", temporary_mount);
2b85f4e1 728
63c372cb 729 dev = strjoina(temporary_mount, "/dev");
dc751688 730 (void) mkdir(dev, 0755);
21935150
LP
731 r = mount_nofollow_verbose(LOG_DEBUG, "tmpfs", dev, "tmpfs", DEV_MOUNT_OPTIONS, "mode=755" TMPFS_LIMITS_DEV);
732 if (r < 0)
2b85f4e1 733 goto fail;
21935150 734
c3151977
TM
735 r = label_fix_container(dev, "/dev", 0);
736 if (r < 0) {
737 log_debug_errno(errno, "Failed to fix label of '%s' as /dev: %m", dev);
738 goto fail;
739 }
2b85f4e1 740
63c372cb 741 devpts = strjoina(temporary_mount, "/dev/pts");
dc751688 742 (void) mkdir(devpts, 0755);
21935150
LP
743 r = mount_nofollow_verbose(LOG_DEBUG, "/dev/pts", devpts, NULL, MS_BIND, NULL);
744 if (r < 0)
2b85f4e1 745 goto fail;
2b85f4e1 746
2e4a4fae
YW
747 /* /dev/ptmx can either be a device node or a symlink to /dev/pts/ptmx.
748 * When /dev/ptmx a device node, /dev/pts/ptmx has 000 permissions making it inaccessible.
749 * Thus, in that case make a clone.
750 * In nspawn and other containers it will be a symlink, in that case make it a symlink. */
36ce7110 751 r = is_symlink("/dev/ptmx");
2e4a4fae
YW
752 if (r < 0) {
753 log_debug_errno(r, "Failed to detect whether /dev/ptmx is a symlink or not: %m");
3164e3cb 754 goto fail;
2e4a4fae 755 } else if (r > 0) {
414b304b
ДГ
756 devptmx = strjoina(temporary_mount, "/dev/ptmx");
757 if (symlink("pts/ptmx", devptmx) < 0) {
2e4a4fae 758 r = log_debug_errno(errno, "Failed to create a symlink '%s' to pts/ptmx: %m", devptmx);
414b304b
ДГ
759 goto fail;
760 }
761 } else {
16498617 762 r = clone_device_node("/dev/ptmx", temporary_mount, &can_mknod);
152c475f
LP
763 if (r < 0)
764 goto fail;
414b304b 765 }
e06b6479 766
63c372cb 767 devshm = strjoina(temporary_mount, "/dev/shm");
8d953682 768 (void) mkdir(devshm, 0755);
21935150
LP
769 r = mount_nofollow_verbose(LOG_DEBUG, "/dev/shm", devshm, NULL, MS_BIND, NULL);
770 if (r < 0)
2b85f4e1 771 goto fail;
2b85f4e1 772
63c372cb 773 devmqueue = strjoina(temporary_mount, "/dev/mqueue");
dc751688 774 (void) mkdir(devmqueue, 0755);
21935150 775 (void) mount_nofollow_verbose(LOG_DEBUG, "/dev/mqueue", devmqueue, NULL, MS_BIND, NULL);
2b85f4e1 776
63c372cb 777 devhugepages = strjoina(temporary_mount, "/dev/hugepages");
dc751688 778 (void) mkdir(devhugepages, 0755);
21935150 779 (void) mount_nofollow_verbose(LOG_DEBUG, "/dev/hugepages", devhugepages, NULL, MS_BIND, NULL);
2b85f4e1 780
63c372cb 781 devlog = strjoina(temporary_mount, "/dev/log");
2e4a4fae
YW
782 if (symlink("/run/systemd/journal/dev-log", devlog) < 0)
783 log_debug_errno(errno, "Failed to create a symlink '%s' to /run/systemd/journal/dev-log, ignoring: %m", devlog);
82d25240 784
7f112f50 785 NULSTR_FOREACH(d, devnodes) {
16498617 786 r = clone_device_node(d, temporary_mount, &can_mknod);
37b22b3b 787 /* ENXIO means the *source* is not a device file, skip creation in that case */
af984e13 788 if (r < 0 && r != -ENXIO)
2b85f4e1 789 goto fail;
7f112f50
LP
790 }
791
2e4a4fae
YW
792 r = dev_setup(temporary_mount, UID_INVALID, GID_INVALID);
793 if (r < 0)
105a1a36 794 log_debug_errno(r, "Failed to set up basic device tree at '%s', ignoring: %m", temporary_mount);
7f112f50 795
ee818b89
AC
796 /* Create the /dev directory if missing. It is more likely to be
797 * missing when the service is started with RootDirectory. This is
798 * consistent with mount units creating the mount points when missing.
799 */
34de407a 800 (void) mkdir_p_label(mount_entry_path(m), 0755);
ee818b89 801
9e5f8252 802 /* Unmount everything in old /dev */
2e4a4fae
YW
803 r = umount_recursive(mount_entry_path(m), 0);
804 if (r < 0)
805 log_debug_errno(r, "Failed to unmount directories below '%s', ignoring: %m", mount_entry_path(m));
806
21935150
LP
807 r = mount_nofollow_verbose(LOG_DEBUG, dev, mount_entry_path(m), NULL, MS_MOVE, NULL);
808 if (r < 0)
2b85f4e1 809 goto fail;
7f112f50 810
1019a48f
LP
811 (void) rmdir(dev);
812 (void) rmdir(temporary_mount);
7f112f50 813
2b85f4e1 814 return 0;
7f112f50 815
2b85f4e1
LP
816fail:
817 if (devpts)
21935150 818 (void) umount_verbose(LOG_DEBUG, devpts, UMOUNT_NOFOLLOW);
7f112f50 819
2b85f4e1 820 if (devshm)
21935150 821 (void) umount_verbose(LOG_DEBUG, devshm, UMOUNT_NOFOLLOW);
7f112f50 822
2b85f4e1 823 if (devhugepages)
21935150 824 (void) umount_verbose(LOG_DEBUG, devhugepages, UMOUNT_NOFOLLOW);
7f112f50 825
2b85f4e1 826 if (devmqueue)
21935150 827 (void) umount_verbose(LOG_DEBUG, devmqueue, UMOUNT_NOFOLLOW);
7f112f50 828
21935150 829 (void) umount_verbose(LOG_DEBUG, dev, UMOUNT_NOFOLLOW);
1019a48f
LP
830 (void) rmdir(dev);
831 (void) rmdir(temporary_mount);
7f112f50 832
2b85f4e1 833 return r;
7f112f50
LP
834}
835
2a2969fd 836static int mount_bind_dev(const MountEntry *m) {
5d997827
LP
837 int r;
838
839 assert(m);
840
841 /* Implements the little brother of mount_private_dev(): simply bind mounts the host's /dev into the service's
842 * /dev. This is only used when RootDirectory= is set. */
843
645767d6
LP
844 (void) mkdir_p_label(mount_entry_path(m), 0755);
845
5d997827
LP
846 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
847 if (r < 0)
848 return log_debug_errno(r, "Unable to determine whether /dev is already mounted: %m");
849 if (r > 0) /* make this a NOP if /dev is already a mount point */
850 return 0;
851
21935150
LP
852 r = mount_nofollow_verbose(LOG_DEBUG, "/dev", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL);
853 if (r < 0)
854 return r;
5d997827
LP
855
856 return 1;
857}
858
2a2969fd 859static int mount_sysfs(const MountEntry *m) {
5d997827
LP
860 int r;
861
862 assert(m);
863
645767d6
LP
864 (void) mkdir_p_label(mount_entry_path(m), 0755);
865
5d997827
LP
866 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
867 if (r < 0)
868 return log_debug_errno(r, "Unable to determine whether /sys is already mounted: %m");
869 if (r > 0) /* make this a NOP if /sys is already a mount point */
870 return 0;
871
872 /* Bind mount the host's version so that we get all child mounts of it, too. */
21935150
LP
873 r = mount_nofollow_verbose(LOG_DEBUG, "/sys", mount_entry_path(m), NULL, MS_BIND|MS_REC, NULL);
874 if (r < 0)
875 return r;
5d997827
LP
876
877 return 1;
878}
879
4e399953 880static int mount_procfs(const MountEntry *m, const NamespaceInfo *ns_info) {
61f8a7bd 881 _cleanup_free_ char *opts = NULL;
4e399953 882 const char *entry_path;
61f8a7bd 883 int r, n;
5d997827
LP
884
885 assert(m);
4e399953 886 assert(ns_info);
5d997827 887
4e399953
LP
888 if (ns_info->protect_proc != PROTECT_PROC_DEFAULT ||
889 ns_info->proc_subset != PROC_SUBSET_ALL) {
4e399953
LP
890
891 /* Starting with kernel 5.8 procfs' hidepid= logic is truly per-instance (previously it
892 * pretended to be per-instance but actually was per-namespace), hence let's make use of it
893 * if requested. To make sure this logic succeeds only on kernels where hidepid= is
894 * per-instance, we'll exclusively use the textual value for hidepid=, since support was
895 * added in the same commit: if it's supported it is thus also per-instance. */
896
897 opts = strjoin("hidepid=",
898 ns_info->protect_proc == PROTECT_PROC_DEFAULT ? "off" :
899 protect_proc_to_string(ns_info->protect_proc),
900 ns_info->proc_subset == PROC_SUBSET_PID ? ",subset=pid" : "");
901 if (!opts)
902 return -ENOMEM;
4e399953
LP
903 }
904
61f8a7bd
YW
905 entry_path = mount_entry_path(m);
906 (void) mkdir_p_label(entry_path, 0755);
907
908 /* Mount a new instance, so that we get the one that matches our user namespace, if we are running in
909 * one. i.e we don't reuse existing mounts here under any condition, we want a new instance owned by
910 * our user namespace and with our hidepid= settings applied. Hence, let's get rid of everything
911 * mounted on /proc/ first. */
912
913 n = umount_recursive(entry_path, 0);
914
915 r = mount_nofollow_verbose(LOG_DEBUG, "proc", entry_path, "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, opts);
916 if (r == -EINVAL && opts)
917 /* If this failed with EINVAL then this likely means the textual hidepid= stuff is
918 * not supported by the kernel, and thus the per-instance hidepid= neither, which
919 * means we really don't want to use it, since it would affect our host's /proc
920 * mount. Hence let's gracefully fallback to a classic, unrestricted version. */
921 r = mount_nofollow_verbose(LOG_DEBUG, "proc", entry_path, "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
922 if (r == -EPERM) {
24ee0f9d 923 /* When we do not have enough privileges to mount /proc, fallback to use existing /proc. */
61f8a7bd
YW
924
925 if (n > 0)
926 /* /proc or some of sub-mounts are umounted in the above. Refuse incomplete tree.
927 * Propagate the original error code returned by mount() in the above. */
928 return -EPERM;
929
930 r = path_is_mount_point(entry_path, NULL, 0);
931 if (r < 0)
932 return log_debug_errno(r, "Unable to determine whether /proc is already mounted: %m");
933 if (r == 0)
934 /* /proc is not mounted. Propagate the original error code. */
935 return -EPERM;
ad74f28a
YW
936 } else if (r < 0)
937 return r;
5d997827
LP
938
939 return 1;
940}
941
2abd4e38 942static int mount_tmpfs(const MountEntry *m) {
df6b900a 943 const char *entry_path, *inner_path;
abad72be 944 int r;
abad72be 945
6c47cd7d
LP
946 assert(m);
947
df6b900a
LP
948 entry_path = mount_entry_path(m);
949 inner_path = m->path_const;
950
2abd4e38 951 /* First, get rid of everything that is below if there is anything. Then, overmount with our new tmpfs */
6c47cd7d 952
abad72be
CG
953 (void) mkdir_p_label(entry_path, 0755);
954 (void) umount_recursive(entry_path, 0);
6c47cd7d 955
21935150
LP
956 r = mount_nofollow_verbose(LOG_DEBUG, "tmpfs", entry_path, "tmpfs", m->flags, mount_entry_options(m));
957 if (r < 0)
958 return r;
abad72be 959
df6b900a 960 r = label_fix_container(entry_path, inner_path, 0);
abad72be 961 if (r < 0)
df6b900a 962 return log_debug_errno(r, "Failed to fix label of '%s' as '%s': %m", entry_path, inner_path);
6c47cd7d
LP
963
964 return 1;
965}
966
94293d65
LB
967static int mount_run(const MountEntry *m) {
968 int r;
969
970 assert(m);
971
972 r = path_is_mount_point(mount_entry_path(m), NULL, 0);
973 if (r < 0 && r != -ENOENT)
974 return log_debug_errno(r, "Unable to determine whether /run is already mounted: %m");
975 if (r > 0) /* make this a NOP if /run is already a mount point */
976 return 0;
977
978 return mount_tmpfs(m);
979}
980
b3d13314 981static int mount_images(const MountEntry *m) {
b3d13314
LB
982 int r;
983
89e62e0b
LP
984 assert(m);
985
4beda316 986 r = verity_dissect_and_mount(mount_entry_source(m), mount_entry_path(m), m->image_options);
b850a9b2
LB
987 if (r == -ENOENT && m->ignore)
988 return 0;
b3d13314 989 if (r < 0)
4beda316 990 return log_debug_errno(r, "Failed to mount image %s on %s: %m", mount_entry_source(m), mount_entry_path(m));
b3d13314
LB
991
992 return 1;
993}
994
088696fe 995static int follow_symlink(
d2d6c096 996 const char *root_directory,
088696fe 997 MountEntry *m) {
d2d6c096 998
088696fe 999 _cleanup_free_ char *target = NULL;
8fceda93
LP
1000 int r;
1001
088696fe
LP
1002 /* Let's chase symlinks, but only one step at a time. That's because depending where the symlink points we
1003 * might need to change the order in which we mount stuff. Hence: let's normalize piecemeal, and do one step at
1004 * a time by specifying CHASE_STEP. This function returns 0 if we resolved one step, and > 0 if we reached the
1005 * end and already have a fully normalized name. */
8fceda93 1006
a5648b80 1007 r = chase_symlinks(mount_entry_path(m), root_directory, CHASE_STEP|CHASE_NONEXISTENT, &target, NULL);
088696fe
LP
1008 if (r < 0)
1009 return log_debug_errno(r, "Failed to chase symlinks '%s': %m", mount_entry_path(m));
1010 if (r > 0) /* Reached the end, nothing more to resolve */
1011 return 1;
8fceda93 1012
baaa35ad
ZJS
1013 if (m->n_followed >= CHASE_SYMLINKS_MAX) /* put a boundary on things */
1014 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
1015 "Symlink loop on '%s'.",
1016 mount_entry_path(m));
8fceda93 1017
088696fe 1018 log_debug("Followed mount entry path symlink %s → %s.", mount_entry_path(m), target);
8fceda93 1019
088696fe
LP
1020 free_and_replace(m->path_malloc, target);
1021 m->has_prefix = true;
8fceda93 1022
088696fe
LP
1023 m->n_followed ++;
1024
1025 return 0;
8fceda93
LP
1026}
1027
ac0930c8 1028static int apply_mount(
8fceda93 1029 const char *root_directory,
4e399953
LP
1030 MountEntry *m,
1031 const NamespaceInfo *ns_info) {
ac0930c8 1032
e5f10caf 1033 _cleanup_free_ char *inaccessible = NULL;
a227a4be 1034 bool rbind = true, make = false;
15ae422b 1035 const char *what;
15ae422b 1036 int r;
15ae422b 1037
c17ec25e 1038 assert(m);
4e399953 1039 assert(ns_info);
15ae422b 1040
34de407a 1041 log_debug("Applying namespace mount on %s", mount_entry_path(m));
fe3c2583 1042
c17ec25e 1043 switch (m->mode) {
15ae422b 1044
160cfdbe 1045 case INACCESSIBLE: {
e5f10caf
AZ
1046 _cleanup_free_ char *tmp = NULL;
1047 const char *runtime_dir;
160cfdbe 1048 struct stat target;
6d313367
LP
1049
1050 /* First, get rid of everything that is below if there
1051 * is anything... Then, overmount it with an
c4b41707 1052 * inaccessible path. */
34de407a 1053 (void) umount_recursive(mount_entry_path(m), 0);
6d313367 1054
088696fe
LP
1055 if (lstat(mount_entry_path(m), &target) < 0) {
1056 if (errno == ENOENT && m->ignore)
1057 return 0;
1058
cbc056c8
ZJS
1059 return log_debug_errno(errno, "Failed to lstat() %s to determine what to mount over it: %m",
1060 mount_entry_path(m));
088696fe 1061 }
15ae422b 1062
e5f10caf 1063 if (geteuid() == 0)
48b747fa 1064 runtime_dir = "/run";
e5f10caf 1065 else {
48b747fa
LP
1066 if (asprintf(&tmp, "/run/user/" UID_FMT, geteuid()) < 0)
1067 return -ENOMEM;
e5f10caf
AZ
1068
1069 runtime_dir = tmp;
1070 }
1071
1072 r = mode_to_inaccessible_node(runtime_dir, target.st_mode, &inaccessible);
1073 if (r < 0)
baaa35ad
ZJS
1074 return log_debug_errno(SYNTHETIC_ERRNO(ELOOP),
1075 "File type not supported for inaccessible mounts. Note that symlinks are not allowed");
e5f10caf 1076 what = inaccessible;
c4b41707 1077 break;
160cfdbe 1078 }
fe3c2583 1079
15ae422b 1080 case READONLY:
15ae422b 1081 case READWRITE:
1e05071d 1082 case READWRITE_IMPLICIT:
ddc155b2
TM
1083 case EXEC:
1084 case NOEXEC:
8fceda93 1085 r = path_is_mount_point(mount_entry_path(m), root_directory, 0);
088696fe
LP
1086 if (r == -ENOENT && m->ignore)
1087 return 0;
d944dc95 1088 if (r < 0)
cbc056c8
ZJS
1089 return log_debug_errno(r, "Failed to determine whether %s is already a mount point: %m",
1090 mount_entry_path(m));
1091 if (r > 0) /* Nothing to do here, it is already a mount. We just later toggle the MS_RDONLY
ddc155b2 1092 * and MS_NOEXEC bits for the mount point if needed. */
6b7c9f8b 1093 return 0;
6b7c9f8b 1094 /* This isn't a mount point yet, let's make it one. */
34de407a 1095 what = mount_entry_path(m);
6b7c9f8b 1096 break;
15ae422b 1097
d2d6c096
LP
1098 case BIND_MOUNT:
1099 rbind = false;
d2d6c096 1100
4831981d 1101 _fallthrough_;
088696fe
LP
1102 case BIND_MOUNT_RECURSIVE: {
1103 _cleanup_free_ char *chased = NULL;
5d997827 1104
cbc056c8
ZJS
1105 /* Since mount() will always follow symlinks we chase the symlinks on our own first. Note
1106 * that bind mount source paths are always relative to the host root, hence we pass NULL as
1107 * root directory to chase_symlinks() here. */
088696fe 1108
a5648b80 1109 r = chase_symlinks(mount_entry_source(m), NULL, CHASE_TRAIL_SLASH, &chased, NULL);
088696fe
LP
1110 if (r == -ENOENT && m->ignore) {
1111 log_debug_errno(r, "Path %s does not exist, ignoring.", mount_entry_source(m));
1112 return 0;
1113 }
1114 if (r < 0)
1115 return log_debug_errno(r, "Failed to follow symlinks on %s: %m", mount_entry_source(m));
1116
1117 log_debug("Followed source symlinks %s → %s.", mount_entry_source(m), chased);
1118
1119 free_and_replace(m->source_malloc, chased);
d2d6c096
LP
1120
1121 what = mount_entry_source(m);
a227a4be 1122 make = true;
d2d6c096 1123 break;
088696fe 1124 }
d2d6c096 1125
6c47cd7d 1126 case EMPTY_DIR:
2abd4e38
YW
1127 case TMPFS:
1128 return mount_tmpfs(m);
6c47cd7d 1129
ac0930c8 1130 case PRIVATE_TMP:
56a13a49 1131 case PRIVATE_TMP_READONLY:
89bd586c 1132 what = mount_entry_source(m);
a227a4be 1133 make = true;
15ae422b 1134 break;
e364ad06 1135
d6797c92 1136 case PRIVATE_DEV:
5d997827
LP
1137 return mount_private_dev(m);
1138
1139 case BIND_DEV:
1140 return mount_bind_dev(m);
1141
1142 case SYSFS:
1143 return mount_sysfs(m);
1144
1145 case PROCFS:
4e399953 1146 return mount_procfs(m, ns_info);
d6797c92 1147
94293d65
LB
1148 case RUN:
1149 return mount_run(m);
1150
b3d13314
LB
1151 case MOUNT_IMAGES:
1152 return mount_images(m);
1153
e364ad06
LP
1154 default:
1155 assert_not_reached("Unknown mode");
15ae422b
LP
1156 }
1157
ac0930c8 1158 assert(what);
15ae422b 1159
21935150
LP
1160 r = mount_nofollow_verbose(LOG_DEBUG, what, mount_entry_path(m), NULL, MS_BIND|(rbind ? MS_REC : 0), NULL);
1161 if (r < 0) {
a227a4be 1162 bool try_again = false;
a227a4be
LP
1163
1164 if (r == -ENOENT && make) {
8bab8029 1165 int q;
a227a4be 1166
cbc056c8
ZJS
1167 /* Hmm, either the source or the destination are missing. Let's see if we can create
1168 the destination, then try again. */
a227a4be 1169
8bab8029 1170 (void) mkdir_parents(mount_entry_path(m), 0755);
a227a4be 1171
8bab8029
LB
1172 q = make_mount_point_inode_from_path(what, mount_entry_path(m), 0755);
1173 if (q < 0)
1174 log_error_errno(q, "Failed to create destination mount point node '%s': %m",
1175 mount_entry_path(m));
1176 else
1177 try_again = true;
a227a4be
LP
1178 }
1179
21935150
LP
1180 if (try_again)
1181 r = mount_nofollow_verbose(LOG_DEBUG, what, mount_entry_path(m), NULL, MS_BIND|(rbind ? MS_REC : 0), NULL);
a227a4be 1182 if (r < 0)
5dc60faa 1183 return log_error_errno(r, "Failed to mount %s to %s: %m", what, mount_entry_path(m));
a227a4be 1184 }
6b7c9f8b 1185
34de407a 1186 log_debug("Successfully mounted %s to %s", what, mount_entry_path(m));
6b7c9f8b 1187 return 0;
ac0930c8 1188}
15ae422b 1189
6b000af4 1190static int make_read_only(const MountEntry *m, char **deny_list, FILE *proc_self_mountinfo) {
9ce4e4b0 1191 unsigned long new_flags = 0, flags_mask = 0;
763a260a 1192 bool submounts = false;
6b7c9f8b 1193 int r = 0;
15ae422b 1194
c17ec25e 1195 assert(m);
ac9de0b3 1196 assert(proc_self_mountinfo);
ac0930c8 1197
9ce4e4b0
LP
1198 if (mount_entry_read_only(m) || m->mode == PRIVATE_DEV) {
1199 new_flags |= MS_RDONLY;
1200 flags_mask |= MS_RDONLY;
1201 }
1202
1203 if (m->nosuid) {
1204 new_flags |= MS_NOSUID;
1205 flags_mask |= MS_NOSUID;
1206 }
1207
1208 if (flags_mask == 0) /* No Change? */
6b7c9f8b
LP
1209 return 0;
1210
9ce4e4b0
LP
1211 /* We generally apply these changes recursively, except for /dev, and the cases we know there's
1212 * nothing further down. Set /dev readonly, but not submounts like /dev/shm. Also, we only set the
1213 * per-mount read-only flag. We can't set it on the superblock, if we are inside a user namespace
1214 * and running Linux <= 4.17. */
1215 submounts =
1216 mount_entry_read_only(m) &&
1217 !IN_SET(m->mode, EMPTY_DIR, TMPFS);
1218 if (submounts)
6b000af4 1219 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, deny_list, proc_self_mountinfo);
9ce4e4b0 1220 else
7cce68e1 1221 r = bind_remount_one_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, proc_self_mountinfo);
9ce4e4b0 1222
ddc155b2 1223 /* Note that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked
867189b5
LP
1224 * read-only already stays this way. This improves compatibility with container managers, where we
1225 * won't attempt to undo read-only mounts already applied. */
ac0930c8 1226
8fceda93 1227 if (r == -ENOENT && m->ignore)
867189b5 1228 return 0;
763a260a 1229 if (r < 0)
9ce4e4b0 1230 return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
763a260a 1231 submounts ? " and its submounts" : "");
763a260a 1232 return 0;
d944dc95
LP
1233}
1234
ddc155b2
TM
1235static int make_noexec(const MountEntry *m, char **deny_list, FILE *proc_self_mountinfo) {
1236 unsigned long new_flags = 0, flags_mask = 0;
1237 bool submounts = false;
1238 int r = 0;
1239
1240 assert(m);
1241 assert(proc_self_mountinfo);
1242
1243 if (mount_entry_noexec(m)) {
1244 new_flags |= MS_NOEXEC;
1245 flags_mask |= MS_NOEXEC;
1246 } else if (mount_entry_exec(m)) {
1247 new_flags &= ~MS_NOEXEC;
1248 flags_mask |= MS_NOEXEC;
1249 }
1250
1251 if (flags_mask == 0) /* No Change? */
1252 return 0;
1253
1254 submounts = !IN_SET(m->mode, EMPTY_DIR, TMPFS);
1255
1256 if (submounts)
1257 r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, deny_list, proc_self_mountinfo);
1258 else
1259 r = bind_remount_one_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, proc_self_mountinfo);
1260
1261 if (r == -ENOENT && m->ignore)
1262 return 0;
1263 if (r < 0)
1264 return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
1265 submounts ? " and its submounts" : "");
1266 return 0;
1267}
1268
9b68367b 1269static bool namespace_info_mount_apivfs(const NamespaceInfo *ns_info) {
5d997827
LP
1270 assert(ns_info);
1271
9c988f93
DH
1272 /*
1273 * ProtectControlGroups= and ProtectKernelTunables= imply MountAPIVFS=,
1274 * since to protect the API VFS mounts, they need to be around in the
9b68367b 1275 * first place...
9c988f93 1276 */
5d997827 1277
9b68367b
YW
1278 return ns_info->mount_apivfs ||
1279 ns_info->protect_control_groups ||
4e399953
LP
1280 ns_info->protect_kernel_tunables ||
1281 ns_info->protect_proc != PROTECT_PROC_DEFAULT ||
1282 ns_info->proc_subset != PROC_SUBSET_ALL;
5d997827
LP
1283}
1284
da6053d0 1285static size_t namespace_calculate_mounts(
bb0ff3fb 1286 const NamespaceInfo *ns_info,
2652c6c1
DH
1287 char** read_write_paths,
1288 char** read_only_paths,
1289 char** inaccessible_paths,
ddc155b2
TM
1290 char** exec_paths,
1291 char** no_exec_paths,
6c47cd7d 1292 char** empty_directories,
da6053d0
LP
1293 size_t n_bind_mounts,
1294 size_t n_temporary_filesystems,
b3d13314 1295 size_t n_mount_images,
2652c6c1
DH
1296 const char* tmp_dir,
1297 const char* var_tmp_dir,
bbb4e7f3 1298 const char *creds_path,
5e8deb94 1299 const char* log_namespace,
3bdc25a4
LP
1300 bool setup_propagate,
1301 const char* notify_socket) {
2652c6c1 1302
da6053d0
LP
1303 size_t protect_home_cnt;
1304 size_t protect_system_cnt =
52b3d652 1305 (ns_info->protect_system == PROTECT_SYSTEM_STRICT ?
f471b2af 1306 ELEMENTSOF(protect_system_strict_table) :
52b3d652 1307 ((ns_info->protect_system == PROTECT_SYSTEM_FULL) ?
f471b2af 1308 ELEMENTSOF(protect_system_full_table) :
52b3d652 1309 ((ns_info->protect_system == PROTECT_SYSTEM_YES) ?
f471b2af
DH
1310 ELEMENTSOF(protect_system_yes_table) : 0)));
1311
b6c432ca 1312 protect_home_cnt =
52b3d652 1313 (ns_info->protect_home == PROTECT_HOME_YES ?
b6c432ca 1314 ELEMENTSOF(protect_home_yes_table) :
52b3d652 1315 ((ns_info->protect_home == PROTECT_HOME_READ_ONLY) ?
e4da7d8c 1316 ELEMENTSOF(protect_home_read_only_table) :
52b3d652 1317 ((ns_info->protect_home == PROTECT_HOME_TMPFS) ?
e4da7d8c 1318 ELEMENTSOF(protect_home_tmpfs_table) : 0)));
b6c432ca 1319
2652c6c1
DH
1320 return !!tmp_dir + !!var_tmp_dir +
1321 strv_length(read_write_paths) +
1322 strv_length(read_only_paths) +
1323 strv_length(inaccessible_paths) +
ddc155b2
TM
1324 strv_length(exec_paths) +
1325 strv_length(no_exec_paths) +
6c47cd7d 1326 strv_length(empty_directories) +
d2d6c096 1327 n_bind_mounts +
b3d13314 1328 n_mount_images +
2abd4e38 1329 n_temporary_filesystems +
c575770b
DH
1330 ns_info->private_dev +
1331 (ns_info->protect_kernel_tunables ? ELEMENTSOF(protect_kernel_tunables_table) : 0) +
c575770b 1332 (ns_info->protect_kernel_modules ? ELEMENTSOF(protect_kernel_modules_table) : 0) +
94a7b275
KK
1333 (ns_info->protect_kernel_logs ? ELEMENTSOF(protect_kernel_logs_table) : 0) +
1334 (ns_info->protect_control_groups ? 1 : 0) +
5d997827 1335 protect_home_cnt + protect_system_cnt +
aecd5ac6 1336 (ns_info->protect_hostname ? 2 : 0) +
91dd5f7c 1337 (namespace_info_mount_apivfs(ns_info) ? ELEMENTSOF(apivfs_table) : 0) +
bbb4e7f3 1338 (creds_path ? 2 : 1) +
3bdc25a4
LP
1339 !!log_namespace +
1340 setup_propagate + /* /run/systemd/incoming */
1341 !!notify_socket;
2652c6c1
DH
1342}
1343
da6053d0 1344static void normalize_mounts(const char *root_directory, MountEntry *mounts, size_t *n_mounts) {
9b68367b 1345 assert(root_directory);
f8b64b57
LP
1346 assert(n_mounts);
1347 assert(mounts || *n_mounts == 0);
1348
93bab288 1349 typesafe_qsort(mounts, *n_mounts, mount_path_compare);
f8b64b57
LP
1350
1351 drop_duplicates(mounts, n_mounts);
1352 drop_outside_root(root_directory, mounts, n_mounts);
1353 drop_inaccessible(mounts, n_mounts);
1354 drop_nop(mounts, n_mounts);
1355}
1356
c8c535d5
LP
1357static bool root_read_only(
1358 char **read_only_paths,
1359 ProtectSystem protect_system) {
1360
1361 /* Determine whether the root directory is going to be read-only given the configured settings. */
1362
1363 if (protect_system == PROTECT_SYSTEM_STRICT)
1364 return true;
1365
de46b2be 1366 if (prefixed_path_strv_contains(read_only_paths, "/"))
c8c535d5
LP
1367 return true;
1368
1369 return false;
1370}
1371
1372static bool home_read_only(
1373 char** read_only_paths,
1374 char** inaccessible_paths,
1375 char** empty_directories,
1376 const BindMount *bind_mounts,
1377 size_t n_bind_mounts,
1378 const TemporaryFileSystem *temporary_filesystems,
1379 size_t n_temporary_filesystems,
1380 ProtectHome protect_home) {
1381
1382 size_t i;
1383
1384 /* Determine whether the /home directory is going to be read-only given the configured settings. Yes,
1385 * this is a bit sloppy, since we don't bother checking for cases where / is affected by multiple
1386 * settings. */
1387
1388 if (protect_home != PROTECT_HOME_NO)
1389 return true;
1390
de46b2be
TM
1391 if (prefixed_path_strv_contains(read_only_paths, "/home") ||
1392 prefixed_path_strv_contains(inaccessible_paths, "/home") ||
1393 prefixed_path_strv_contains(empty_directories, "/home"))
c8c535d5
LP
1394 return true;
1395
1396 for (i = 0; i < n_temporary_filesystems; i++)
1397 if (path_equal(temporary_filesystems[i].path, "/home"))
1398 return true;
1399
1400 /* If /home is overmounted with some dir from the host it's not writable. */
1401 for (i = 0; i < n_bind_mounts; i++)
1402 if (path_equal(bind_mounts[i].destination, "/home"))
1403 return true;
1404
1405 return false;
1406}
1407
89e62e0b
LP
1408static int verity_settings_prepare(
1409 VeritySettings *verity,
1410 const char *root_image,
1411 const void *root_hash,
1412 size_t root_hash_size,
1413 const char *root_hash_path,
1414 const void *root_hash_sig,
1415 size_t root_hash_sig_size,
1416 const char *root_hash_sig_path,
1417 const char *verity_data_path) {
1418
1419 int r;
1420
1421 assert(verity);
1422
1423 if (root_hash) {
1424 void *d;
1425
1426 d = memdup(root_hash, root_hash_size);
1427 if (!d)
1428 return -ENOMEM;
1429
1430 free_and_replace(verity->root_hash, d);
1431 verity->root_hash_size = root_hash_size;
aee36b4e 1432 verity->designator = PARTITION_ROOT;
89e62e0b
LP
1433 }
1434
1435 if (root_hash_sig) {
1436 void *d;
1437
1438 d = memdup(root_hash_sig, root_hash_sig_size);
1439 if (!d)
1440 return -ENOMEM;
1441
1442 free_and_replace(verity->root_hash_sig, d);
1443 verity->root_hash_sig_size = root_hash_sig_size;
aee36b4e 1444 verity->designator = PARTITION_ROOT;
89e62e0b
LP
1445 }
1446
1447 if (verity_data_path) {
1448 r = free_and_strdup(&verity->data_path, verity_data_path);
1449 if (r < 0)
1450 return r;
1451 }
1452
1453 r = verity_settings_load(
1454 verity,
1455 root_image,
1456 root_hash_path,
1457 root_hash_sig_path);
1458 if (r < 0)
1459 return log_debug_errno(r, "Failed to load root hash: %m");
1460
1461 return 0;
1462}
1463
613b411c 1464int setup_namespace(
ee818b89 1465 const char* root_directory,
915e6d16 1466 const char* root_image,
18d73705 1467 const MountOptions *root_image_options,
bb0ff3fb 1468 const NamespaceInfo *ns_info,
2a624c36
AP
1469 char** read_write_paths,
1470 char** read_only_paths,
1471 char** inaccessible_paths,
ddc155b2
TM
1472 char** exec_paths,
1473 char** no_exec_paths,
6c47cd7d 1474 char** empty_directories,
d2d6c096 1475 const BindMount *bind_mounts,
da6053d0 1476 size_t n_bind_mounts,
2abd4e38 1477 const TemporaryFileSystem *temporary_filesystems,
da6053d0 1478 size_t n_temporary_filesystems,
b3d13314
LB
1479 const MountImage *mount_images,
1480 size_t n_mount_images,
a004cb4c
LP
1481 const char* tmp_dir,
1482 const char* var_tmp_dir,
bbb4e7f3 1483 const char *creds_path,
91dd5f7c 1484 const char *log_namespace,
915e6d16 1485 unsigned long mount_flags,
0389f4fa
LB
1486 const void *root_hash,
1487 size_t root_hash_size,
1488 const char *root_hash_path,
d4d55b0d
LB
1489 const void *root_hash_sig,
1490 size_t root_hash_sig_size,
1491 const char *root_hash_sig_path,
89e62e0b 1492 const char *verity_data_path,
5e8deb94
LB
1493 const char *propagate_dir,
1494 const char *incoming_dir,
3bdc25a4 1495 const char *notify_socket,
7cc5ef5f
ZJS
1496 DissectImageFlags dissect_image_flags,
1497 char **error_path) {
15ae422b 1498
915e6d16 1499 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
78ebe980 1500 _cleanup_(decrypted_image_unrefp) DecryptedImage *decrypted_image = NULL;
915e6d16 1501 _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
aee36b4e 1502 _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
5f7a690a 1503 MountEntry *m = NULL, *mounts = NULL;
5e8deb94 1504 bool require_prefix = false, setup_propagate = false;
9b68367b 1505 const char *root;
89e62e0b
LP
1506 size_t n_mounts;
1507 int r;
15ae422b 1508
915e6d16
LP
1509 assert(ns_info);
1510
5e8deb94
LB
1511 if (!isempty(propagate_dir) && !isempty(incoming_dir))
1512 setup_propagate = true;
1513
613b411c 1514 if (mount_flags == 0)
c17ec25e 1515 mount_flags = MS_SHARED;
ac0930c8 1516
915e6d16
LP
1517 if (root_image) {
1518 dissect_image_flags |= DISSECT_IMAGE_REQUIRE_ROOT;
1519
c8c535d5
LP
1520 /* Make the whole image read-only if we can determine that we only access it in a read-only fashion. */
1521 if (root_read_only(read_only_paths,
52b3d652 1522 ns_info->protect_system) &&
c8c535d5
LP
1523 home_read_only(read_only_paths, inaccessible_paths, empty_directories,
1524 bind_mounts, n_bind_mounts, temporary_filesystems, n_temporary_filesystems,
52b3d652 1525 ns_info->protect_home) &&
c9ef8573 1526 strv_isempty(read_write_paths))
915e6d16
LP
1527 dissect_image_flags |= DISSECT_IMAGE_READ_ONLY;
1528
89e62e0b
LP
1529 r = verity_settings_prepare(
1530 &verity,
1531 root_image,
1532 root_hash, root_hash_size, root_hash_path,
1533 root_hash_sig, root_hash_sig_size, root_hash_sig_path,
1534 verity_data_path);
915e6d16 1535 if (r < 0)
89e62e0b
LP
1536 return r;
1537
1538 SET_FLAG(dissect_image_flags, DISSECT_IMAGE_NO_PARTITION_TABLE, verity.data_path);
915e6d16 1539
89e62e0b
LP
1540 r = loop_device_make_by_path(
1541 root_image,
1542 FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_READ_ONLY) ? O_RDONLY : -1 /* < 0 means writable if possible, read-only as fallback */,
1543 FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
1544 &loop_device);
78ebe980 1545 if (r < 0)
89e62e0b
LP
1546 return log_debug_errno(r, "Failed to create loop device for root image: %m");
1547
1548 r = dissect_image(
1549 loop_device->fd,
1550 &verity,
1551 root_image_options,
1552 dissect_image_flags,
1553 &dissected_image);
78ebe980 1554 if (r < 0)
763a260a 1555 return log_debug_errno(r, "Failed to dissect image: %m");
78ebe980 1556
89e62e0b
LP
1557 r = dissected_image_decrypt(
1558 dissected_image,
1559 NULL,
1560 &verity,
1561 dissect_image_flags,
1562 &decrypted_image);
915e6d16 1563 if (r < 0)
763a260a 1564 return log_debug_errno(r, "Failed to decrypt dissected image: %m");
915e6d16
LP
1565 }
1566
e908468b
LP
1567 if (root_directory)
1568 root = root_directory;
0722b359 1569 else {
77f16dbd
DDM
1570 /* /run/systemd should have been created by PID 1 early on already, but in some cases, like
1571 * when running tests (test-execute), it might not have been created yet so let's make sure
1572 * we create it if it doesn't already exist. */
1573 (void) mkdir_p_label("/run/systemd", 0755);
1574
0722b359
JS
1575 /* Always create the mount namespace in a temporary directory, instead of operating
1576 * directly in the root. The temporary directory prevents any mounts from being
1577 * potentially obscured my other mounts we already applied.
1578 * We use the same mount point for all images, which is safe, since they all live
1579 * in their own namespaces after all, and hence won't see each other. */
e908468b
LP
1580
1581 root = "/run/systemd/unit-root";
1582 (void) mkdir_label(root, 0700);
d18aff04 1583 require_prefix = true;
0722b359 1584 }
e908468b 1585
cfbeb4ef
LP
1586 n_mounts = namespace_calculate_mounts(
1587 ns_info,
1588 read_write_paths,
1589 read_only_paths,
1590 inaccessible_paths,
ddc155b2
TM
1591 exec_paths,
1592 no_exec_paths,
6c47cd7d 1593 empty_directories,
f5c52a77 1594 n_bind_mounts,
2abd4e38 1595 n_temporary_filesystems,
b3d13314 1596 n_mount_images,
cfbeb4ef 1597 tmp_dir, var_tmp_dir,
bbb4e7f3 1598 creds_path,
5e8deb94 1599 log_namespace,
3bdc25a4
LP
1600 setup_propagate,
1601 notify_socket);
613b411c 1602
f0a4feb0 1603 if (n_mounts > 0) {
5f7a690a
LP
1604 m = mounts = new0(MountEntry, n_mounts);
1605 if (!mounts)
1606 return -ENOMEM;
1607
d18aff04 1608 r = append_access_mounts(&m, read_write_paths, READWRITE, require_prefix);
613b411c 1609 if (r < 0)
f0a4feb0 1610 goto finish;
613b411c 1611
d18aff04 1612 r = append_access_mounts(&m, read_only_paths, READONLY, require_prefix);
613b411c 1613 if (r < 0)
f0a4feb0 1614 goto finish;
613b411c 1615
d18aff04 1616 r = append_access_mounts(&m, inaccessible_paths, INACCESSIBLE, require_prefix);
613b411c 1617 if (r < 0)
f0a4feb0 1618 goto finish;
7ff7394d 1619
ddc155b2
TM
1620 r = append_access_mounts(&m, exec_paths, EXEC, require_prefix);
1621 if (r < 0)
1622 goto finish;
1623
1624 r = append_access_mounts(&m, no_exec_paths, NOEXEC, require_prefix);
1625 if (r < 0)
1626 goto finish;
1627
6c47cd7d
LP
1628 r = append_empty_dir_mounts(&m, empty_directories);
1629 if (r < 0)
1630 goto finish;
1631
d2d6c096
LP
1632 r = append_bind_mounts(&m, bind_mounts, n_bind_mounts);
1633 if (r < 0)
1634 goto finish;
1635
2abd4e38
YW
1636 r = append_tmpfs_mounts(&m, temporary_filesystems, n_temporary_filesystems);
1637 if (r < 0)
1638 goto finish;
1639
613b411c 1640 if (tmp_dir) {
56a13a49
ZJS
1641 bool ro = streq(tmp_dir, RUN_SYSTEMD_EMPTY);
1642
34de407a 1643 *(m++) = (MountEntry) {
5327c910 1644 .path_const = "/tmp",
56a13a49 1645 .mode = ro ? PRIVATE_TMP_READONLY : PRIVATE_TMP,
89bd586c 1646 .source_const = tmp_dir,
5327c910 1647 };
613b411c 1648 }
7ff7394d 1649
613b411c 1650 if (var_tmp_dir) {
56a13a49
ZJS
1651 bool ro = streq(var_tmp_dir, RUN_SYSTEMD_EMPTY);
1652
34de407a 1653 *(m++) = (MountEntry) {
5327c910 1654 .path_const = "/var/tmp",
56a13a49 1655 .mode = ro ? PRIVATE_TMP_READONLY : PRIVATE_TMP,
89bd586c 1656 .source_const = var_tmp_dir,
5327c910 1657 };
7ff7394d 1658 }
ac0930c8 1659
b3d13314
LB
1660 r = append_mount_images(&m, mount_images, n_mount_images);
1661 if (r < 0)
1662 goto finish;
1663
d46b79bb 1664 if (ns_info->private_dev)
34de407a 1665 *(m++) = (MountEntry) {
5327c910
LP
1666 .path_const = "/dev",
1667 .mode = PRIVATE_DEV,
9ce4e4b0 1668 .flags = DEV_MOUNT_OPTIONS,
5327c910 1669 };
7f112f50 1670
c575770b 1671 if (ns_info->protect_kernel_tunables) {
cbc056c8
ZJS
1672 r = append_static_mounts(&m,
1673 protect_kernel_tunables_table,
1674 ELEMENTSOF(protect_kernel_tunables_table),
1675 ns_info->ignore_protect_paths);
c575770b 1676 if (r < 0)
f0a4feb0 1677 goto finish;
c575770b
DH
1678 }
1679
1680 if (ns_info->protect_kernel_modules) {
cbc056c8
ZJS
1681 r = append_static_mounts(&m,
1682 protect_kernel_modules_table,
1683 ELEMENTSOF(protect_kernel_modules_table),
1684 ns_info->ignore_protect_paths);
c575770b 1685 if (r < 0)
f0a4feb0 1686 goto finish;
c575770b 1687 }
59eeb84b 1688
94a7b275 1689 if (ns_info->protect_kernel_logs) {
cbc056c8
ZJS
1690 r = append_static_mounts(&m,
1691 protect_kernel_logs_table,
1692 ELEMENTSOF(protect_kernel_logs_table),
1693 ns_info->ignore_protect_paths);
94a7b275
KK
1694 if (r < 0)
1695 goto finish;
1696 }
1697
d46b79bb 1698 if (ns_info->protect_control_groups)
34de407a 1699 *(m++) = (MountEntry) {
5327c910
LP
1700 .path_const = "/sys/fs/cgroup",
1701 .mode = READONLY,
1702 };
59eeb84b 1703
52b3d652 1704 r = append_protect_home(&m, ns_info->protect_home, ns_info->ignore_protect_paths);
b6c432ca 1705 if (r < 0)
f0a4feb0 1706 goto finish;
417116f2 1707
52b3d652 1708 r = append_protect_system(&m, ns_info->protect_system, false);
f471b2af 1709 if (r < 0)
f0a4feb0 1710 goto finish;
417116f2 1711
9b68367b 1712 if (namespace_info_mount_apivfs(ns_info)) {
cbc056c8
ZJS
1713 r = append_static_mounts(&m,
1714 apivfs_table,
1715 ELEMENTSOF(apivfs_table),
1716 ns_info->ignore_protect_paths);
5d997827
LP
1717 if (r < 0)
1718 goto finish;
1719 }
1720
aecd5ac6
TM
1721 if (ns_info->protect_hostname) {
1722 *(m++) = (MountEntry) {
1723 .path_const = "/proc/sys/kernel/hostname",
1724 .mode = READONLY,
1725 };
1726 *(m++) = (MountEntry) {
1727 .path_const = "/proc/sys/kernel/domainname",
1728 .mode = READONLY,
1729 };
1730 }
1731
bbb4e7f3
LP
1732 if (creds_path) {
1733 /* If our service has a credentials store configured, then bind that one in, but hide
1734 * everything else. */
1735
1736 *(m++) = (MountEntry) {
1737 .path_const = "/run/credentials",
1738 .mode = TMPFS,
1739 .read_only = true,
1740 .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST,
1741 .flags = MS_NODEV|MS_STRICTATIME|MS_NOSUID|MS_NOEXEC,
1742 };
1743
1744 *(m++) = (MountEntry) {
1745 .path_const = creds_path,
1746 .mode = BIND_MOUNT,
1747 .read_only = true,
1748 .source_const = creds_path,
1749 };
1750 } else {
1751 /* If our service has no credentials store configured, then make the whole
1752 * credentials tree inaccessible wholesale. */
1753
1754 *(m++) = (MountEntry) {
1755 .path_const = "/run/credentials",
1756 .mode = INACCESSIBLE,
1757 .ignore = true,
1758 };
1759 }
1760
91dd5f7c
LP
1761 if (log_namespace) {
1762 _cleanup_free_ char *q;
1763
1764 q = strjoin("/run/systemd/journal.", log_namespace);
1765 if (!q) {
1766 r = -ENOMEM;
1767 goto finish;
1768 }
1769
1770 *(m++) = (MountEntry) {
1771 .path_const = "/run/systemd/journal",
1772 .mode = BIND_MOUNT_RECURSIVE,
1773 .read_only = true,
1774 .source_malloc = TAKE_PTR(q),
1775 };
1776 }
1777
5e8deb94
LB
1778 /* Will be used to add bind mounts at runtime */
1779 if (setup_propagate)
1780 *(m++) = (MountEntry) {
1781 .source_const = propagate_dir,
1782 .path_const = incoming_dir,
1783 .mode = BIND_MOUNT,
1784 .read_only = true,
1785 };
1786
3bdc25a4
LP
1787 if (notify_socket)
1788 *(m++) = (MountEntry) {
1789 .path_const = notify_socket,
1790 .source_const = notify_socket,
1791 .mode = BIND_MOUNT,
1792 .read_only = true,
1793 };
1794
f0a4feb0 1795 assert(mounts + n_mounts == m);
ac0930c8 1796
5327c910 1797 /* Prepend the root directory where that's necessary */
e908468b 1798 r = prefix_where_needed(mounts, n_mounts, root);
5327c910
LP
1799 if (r < 0)
1800 goto finish;
1801
839f1877 1802 normalize_mounts(root, mounts, &n_mounts);
15ae422b
LP
1803 }
1804
1beab8b0
LP
1805 /* All above is just preparation, figuring out what to do. Let's now actually start doing something. */
1806
d944dc95 1807 if (unshare(CLONE_NEWNS) < 0) {
763a260a 1808 r = log_debug_errno(errno, "Failed to unshare the mount namespace: %m");
1beab8b0 1809 if (IN_SET(r, -EACCES, -EPERM, -EOPNOTSUPP, -ENOSYS))
cbc056c8
ZJS
1810 /* If the kernel doesn't support namespaces, or when there's a MAC or seccomp filter
1811 * in place that doesn't allow us to create namespaces (or a missing cap), then
1812 * propagate a recognizable error back, which the caller can use to detect this case
1813 * (and only this) and optionally continue without namespacing applied. */
1beab8b0
LP
1814 r = -ENOANO;
1815
d944dc95
LP
1816 goto finish;
1817 }
1e4e94c8 1818
5e8deb94
LB
1819 /* Create the source directory to allow runtime propagation of mounts */
1820 if (setup_propagate)
1821 (void) mkdir_p(propagate_dir, 0600);
1822
9b68367b
YW
1823 /* Remount / as SLAVE so that nothing now mounted in the namespace
1824 * shows up in the parent */
1825 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) {
763a260a 1826 r = log_debug_errno(errno, "Failed to remount '/' as SLAVE: %m");
9b68367b 1827 goto finish;
ee818b89
AC
1828 }
1829
915e6d16 1830 if (root_image) {
e908468b 1831 /* A root image is specified, mount it to the right place */
2d3a5a73 1832 r = dissected_image_mount(dissected_image, root, UID_INVALID, dissect_image_flags);
763a260a
YW
1833 if (r < 0) {
1834 log_debug_errno(r, "Failed to mount root image: %m");
915e6d16 1835 goto finish;
763a260a 1836 }
915e6d16 1837
07ce7407
TM
1838 if (decrypted_image) {
1839 r = decrypted_image_relinquish(decrypted_image);
763a260a
YW
1840 if (r < 0) {
1841 log_debug_errno(r, "Failed to relinquish decrypted image: %m");
07ce7407 1842 goto finish;
763a260a 1843 }
07ce7407 1844 }
78ebe980 1845
915e6d16
LP
1846 loop_device_relinquish(loop_device);
1847
1848 } else if (root_directory) {
1849
e908468b
LP
1850 /* A root directory is specified. Turn its directory into bind mount, if it isn't one yet. */
1851 r = path_is_mount_point(root, NULL, AT_SYMLINK_FOLLOW);
763a260a
YW
1852 if (r < 0) {
1853 log_debug_errno(r, "Failed to detect that %s is a mount point or not: %m", root);
d944dc95 1854 goto finish;
763a260a 1855 }
8f1ad200 1856 if (r == 0) {
21935150
LP
1857 r = mount_nofollow_verbose(LOG_DEBUG, root, root, NULL, MS_BIND|MS_REC, NULL);
1858 if (r < 0)
8f1ad200 1859 goto finish;
d944dc95 1860 }
e908468b 1861
9b68367b 1862 } else {
e908468b 1863 /* Let's mount the main root directory to the root directory to use */
21935150
LP
1864 r = mount_nofollow_verbose(LOG_DEBUG, "/", root, NULL, MS_BIND|MS_REC, NULL);
1865 if (r < 0)
e908468b 1866 goto finish;
ee818b89 1867 }
c2c13f2d 1868
4e0c20de
LP
1869 /* Try to set up the new root directory before mounting anything else there. */
1870 if (root_image || root_directory)
1871 (void) base_filesystem_create(root, UID_INVALID, GID_INVALID);
1872
f0a4feb0 1873 if (n_mounts > 0) {
ac9de0b3 1874 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6b000af4 1875 _cleanup_free_ char **deny_list = NULL;
da6053d0 1876 size_t j;
6b7c9f8b 1877
cbc056c8
ZJS
1878 /* Open /proc/self/mountinfo now as it may become unavailable if we mount anything on top of
1879 * /proc. For example, this is the case with the option: 'InaccessiblePaths=/proc'. */
ac9de0b3
TR
1880 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
1881 if (!proc_self_mountinfo) {
763a260a 1882 r = log_debug_errno(errno, "Failed to open /proc/self/mountinfo: %m");
7cc5ef5f
ZJS
1883 if (error_path)
1884 *error_path = strdup("/proc/self/mountinfo");
ac9de0b3
TR
1885 goto finish;
1886 }
1887
088696fe
LP
1888 /* First round, establish all mounts we need */
1889 for (;;) {
1890 bool again = false;
1891
1892 for (m = mounts; m < mounts + n_mounts; ++m) {
1893
1894 if (m->applied)
1895 continue;
1896
1897 r = follow_symlink(root, m);
7cc5ef5f
ZJS
1898 if (r < 0) {
1899 if (error_path && mount_entry_path(m))
1900 *error_path = strdup(mount_entry_path(m));
088696fe 1901 goto finish;
7cc5ef5f 1902 }
088696fe 1903 if (r == 0) {
cbc056c8
ZJS
1904 /* We hit a symlinked mount point. The entry got rewritten and might
1905 * point to a very different place now. Let's normalize the changed
1906 * list, and start from the beginning. After all to mount the entry
1907 * at the new location we might need some other mounts first */
088696fe
LP
1908 again = true;
1909 break;
1910 }
1911
4e399953 1912 r = apply_mount(root, m, ns_info);
7cc5ef5f
ZJS
1913 if (r < 0) {
1914 if (error_path && mount_entry_path(m))
1915 *error_path = strdup(mount_entry_path(m));
088696fe 1916 goto finish;
7cc5ef5f 1917 }
088696fe
LP
1918
1919 m->applied = true;
1920 }
1921
1922 if (!again)
1923 break;
1924
839f1877 1925 normalize_mounts(root, mounts, &n_mounts);
c2c13f2d 1926 }
15ae422b 1927
6b000af4
LP
1928 /* Create a deny list we can pass to bind_mount_recursive() */
1929 deny_list = new(char*, n_mounts+1);
1930 if (!deny_list) {
5f7a690a
LP
1931 r = -ENOMEM;
1932 goto finish;
1933 }
f0a4feb0 1934 for (j = 0; j < n_mounts; j++)
6b000af4
LP
1935 deny_list[j] = (char*) mount_entry_path(mounts+j);
1936 deny_list[j] = NULL;
6b7c9f8b
LP
1937
1938 /* Second round, flip the ro bits if necessary. */
f0a4feb0 1939 for (m = mounts; m < mounts + n_mounts; ++m) {
6b000af4 1940 r = make_read_only(m, deny_list, proc_self_mountinfo);
7cc5ef5f
ZJS
1941 if (r < 0) {
1942 if (error_path && mount_entry_path(m))
1943 *error_path = strdup(mount_entry_path(m));
d944dc95 1944 goto finish;
7cc5ef5f 1945 }
c2c13f2d 1946 }
ddc155b2
TM
1947
1948 /* Third round, flip the noexec bits with a simplified deny list. */
1949 for (m = mounts, j = 0; m < mounts + n_mounts; ++m)
1950 if (IN_SET(m->mode, EXEC, NOEXEC))
1951 deny_list[j++] = (char*) mount_entry_path(m);
1952 deny_list[j] = NULL;
1953
1954 for (m = mounts; m < mounts + n_mounts; ++m) {
1955 r = make_noexec(m, deny_list, proc_self_mountinfo);
1956 if (r < 0) {
1957 if (error_path && mount_entry_path(m))
1958 *error_path = strdup(mount_entry_path(m));
1959 goto finish;
1960 }
1961 }
15ae422b
LP
1962 }
1963
9b68367b
YW
1964 /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
1965 r = mount_move_root(root);
763a260a
YW
1966 if (r < 0) {
1967 log_debug_errno(r, "Failed to mount root with MS_MOVE: %m");
9b68367b 1968 goto finish;
763a260a 1969 }
ee818b89 1970
55fe7432 1971 /* Remount / as the desired mode. Note that this will not
c2c13f2d
LP
1972 * reestablish propagation from our side to the host, since
1973 * what's disconnected is disconnected. */
d944dc95 1974 if (mount(NULL, "/", NULL, mount_flags | MS_REC, NULL) < 0) {
763a260a 1975 r = log_debug_errno(errno, "Failed to remount '/' with desired mount flags: %m");
d944dc95
LP
1976 goto finish;
1977 }
15ae422b 1978
5e8deb94
LB
1979 /* bind_mount_in_namespace() will MS_MOVE into that directory, and that's only
1980 * supported for non-shared mounts. This needs to happen after remounting / or it will fail. */
1981 if (setup_propagate) {
1982 r = mount(NULL, incoming_dir, NULL, MS_SLAVE, NULL);
1983 if (r < 0) {
1984 log_error_errno(r, "Failed to remount %s with MS_SLAVE: %m", incoming_dir);
1985 goto finish;
1986 }
1987 }
1988
d944dc95 1989 r = 0;
15ae422b 1990
d944dc95 1991finish:
0cd41757
LP
1992 if (n_mounts > 0)
1993 for (m = mounts; m < mounts + n_mounts; m++)
1994 mount_entry_done(m);
613b411c 1995
5f7a690a
LP
1996 free(mounts);
1997
613b411c
LP
1998 return r;
1999}
2000
da6053d0 2001void bind_mount_free_many(BindMount *b, size_t n) {
d2d6c096
LP
2002 assert(b || n == 0);
2003
fe96c0f8 2004 for (size_t i = 0; i < n; i++) {
d2d6c096
LP
2005 free(b[i].source);
2006 free(b[i].destination);
2007 }
2008
2009 free(b);
2010}
2011
da6053d0 2012int bind_mount_add(BindMount **b, size_t *n, const BindMount *item) {
d2d6c096
LP
2013 _cleanup_free_ char *s = NULL, *d = NULL;
2014 BindMount *c;
2015
2016 assert(b);
2017 assert(n);
2018 assert(item);
2019
2020 s = strdup(item->source);
2021 if (!s)
2022 return -ENOMEM;
2023
2024 d = strdup(item->destination);
2025 if (!d)
2026 return -ENOMEM;
2027
aa484f35 2028 c = reallocarray(*b, *n + 1, sizeof(BindMount));
d2d6c096
LP
2029 if (!c)
2030 return -ENOMEM;
2031
2032 *b = c;
2033
2034 c[(*n) ++] = (BindMount) {
1cc6c93a
YW
2035 .source = TAKE_PTR(s),
2036 .destination = TAKE_PTR(d),
d2d6c096 2037 .read_only = item->read_only,
9ce4e4b0 2038 .nosuid = item->nosuid,
d2d6c096
LP
2039 .recursive = item->recursive,
2040 .ignore_enoent = item->ignore_enoent,
2041 };
2042
d2d6c096
LP
2043 return 0;
2044}
2045
b3d13314 2046MountImage* mount_image_free_many(MountImage *m, size_t *n) {
b3d13314
LB
2047 assert(n);
2048 assert(m || *n == 0);
2049
fe96c0f8 2050 for (size_t i = 0; i < *n; i++) {
b3d13314
LB
2051 free(m[i].source);
2052 free(m[i].destination);
427353f6 2053 mount_options_free_all(m[i].mount_options);
b3d13314
LB
2054 }
2055
2056 free(m);
2057 *n = 0;
2058 return NULL;
2059}
2060
2061int mount_image_add(MountImage **m, size_t *n, const MountImage *item) {
2062 _cleanup_free_ char *s = NULL, *d = NULL;
427353f6
LB
2063 _cleanup_(mount_options_free_allp) MountOptions *options = NULL;
2064 MountOptions *i;
b3d13314
LB
2065 MountImage *c;
2066
2067 assert(m);
2068 assert(n);
2069 assert(item);
2070
2071 s = strdup(item->source);
2072 if (!s)
2073 return -ENOMEM;
2074
2075 d = strdup(item->destination);
2076 if (!d)
2077 return -ENOMEM;
2078
427353f6
LB
2079 LIST_FOREACH(mount_options, i, item->mount_options) {
2080 _cleanup_(mount_options_free_allp) MountOptions *o;
2081
2082 o = new(MountOptions, 1);
2083 if (!o)
2084 return -ENOMEM;
2085
2086 *o = (MountOptions) {
2087 .partition_designator = i->partition_designator,
2088 .options = strdup(i->options),
2089 };
2090 if (!o->options)
2091 return -ENOMEM;
2092
2093 LIST_APPEND(mount_options, options, TAKE_PTR(o));
2094 }
2095
b3d13314
LB
2096 c = reallocarray(*m, *n + 1, sizeof(MountImage));
2097 if (!c)
2098 return -ENOMEM;
2099
2100 *m = c;
2101
2102 c[(*n) ++] = (MountImage) {
2103 .source = TAKE_PTR(s),
2104 .destination = TAKE_PTR(d),
427353f6 2105 .mount_options = TAKE_PTR(options),
b3d13314
LB
2106 .ignore_enoent = item->ignore_enoent,
2107 };
2108
2109 return 0;
2110}
2111
da6053d0 2112void temporary_filesystem_free_many(TemporaryFileSystem *t, size_t n) {
2abd4e38
YW
2113 assert(t || n == 0);
2114
fe96c0f8 2115 for (size_t i = 0; i < n; i++) {
2abd4e38
YW
2116 free(t[i].path);
2117 free(t[i].options);
2118 }
2119
2120 free(t);
2121}
2122
2123int temporary_filesystem_add(
2124 TemporaryFileSystem **t,
da6053d0 2125 size_t *n,
2abd4e38
YW
2126 const char *path,
2127 const char *options) {
2128
2129 _cleanup_free_ char *p = NULL, *o = NULL;
2130 TemporaryFileSystem *c;
2131
2132 assert(t);
2133 assert(n);
2134 assert(path);
2135
2136 p = strdup(path);
2137 if (!p)
2138 return -ENOMEM;
2139
2140 if (!isempty(options)) {
2141 o = strdup(options);
2142 if (!o)
2143 return -ENOMEM;
2144 }
2145
aa484f35 2146 c = reallocarray(*t, *n + 1, sizeof(TemporaryFileSystem));
2abd4e38
YW
2147 if (!c)
2148 return -ENOMEM;
2149
2150 *t = c;
2151
2152 c[(*n) ++] = (TemporaryFileSystem) {
1cc6c93a
YW
2153 .path = TAKE_PTR(p),
2154 .options = TAKE_PTR(o),
2abd4e38
YW
2155 };
2156
2abd4e38
YW
2157 return 0;
2158}
2159
a652f050
JR
2160static int make_tmp_prefix(const char *prefix) {
2161 _cleanup_free_ char *t = NULL;
2162 int r;
2163
2164 /* Don't do anything unless we know the dir is actually missing */
2165 r = access(prefix, F_OK);
2166 if (r >= 0)
2167 return 0;
2168 if (errno != ENOENT)
2169 return -errno;
2170
2171 r = mkdir_parents(prefix, 0755);
2172 if (r < 0)
2173 return r;
2174
2175 r = tempfn_random(prefix, NULL, &t);
2176 if (r < 0)
2177 return r;
2178
2179 if (mkdir(t, 0777) < 0)
2180 return -errno;
2181
2182 if (chmod(t, 01777) < 0) {
2183 r = -errno;
2184 (void) rmdir(t);
2185 return r;
2186 }
2187
2188 if (rename(t, prefix) < 0) {
2189 r = -errno;
2190 (void) rmdir(t);
2191 return r == -EEXIST ? 0 : r; /* it's fine if someone else created the dir by now */
2192 }
2193
2194 return 0;
2195
2196}
2197
56a13a49 2198static int setup_one_tmp_dir(const char *id, const char *prefix, char **path, char **tmp_path) {
613b411c 2199 _cleanup_free_ char *x = NULL;
19cd4e19 2200 _cleanup_free_ char *y = NULL;
6b46ea73
LP
2201 char bid[SD_ID128_STRING_MAX];
2202 sd_id128_t boot_id;
56a13a49 2203 bool rw = true;
6b46ea73 2204 int r;
613b411c
LP
2205
2206 assert(id);
2207 assert(prefix);
2208 assert(path);
2209
6b46ea73
LP
2210 /* We include the boot id in the directory so that after a
2211 * reboot we can easily identify obsolete directories. */
2212
2213 r = sd_id128_get_boot(&boot_id);
2214 if (r < 0)
2215 return r;
2216
605405c6 2217 x = strjoin(prefix, "/systemd-private-", sd_id128_to_string(boot_id, bid), "-", id, "-XXXXXX");
613b411c
LP
2218 if (!x)
2219 return -ENOMEM;
2220
a652f050
JR
2221 r = make_tmp_prefix(prefix);
2222 if (r < 0)
2223 return r;
2224
613b411c 2225 RUN_WITH_UMASK(0077)
56a13a49
ZJS
2226 if (!mkdtemp(x)) {
2227 if (errno == EROFS || ERRNO_IS_DISK_SPACE(errno))
2228 rw = false;
2229 else
2230 return -errno;
2231 }
613b411c 2232
56a13a49 2233 if (rw) {
19cd4e19 2234 y = strjoin(x, "/tmp");
2235 if (!y)
2236 return -ENOMEM;
2237
2238 RUN_WITH_UMASK(0000) {
2239 if (mkdir(y, 0777 | S_ISVTX) < 0)
2240 return -errno;
2241 }
2242
2243 r = label_fix_container(y, prefix, 0);
56a13a49
ZJS
2244 if (r < 0)
2245 return r;
19cd4e19 2246
2247 if (tmp_path)
2248 *tmp_path = TAKE_PTR(y);
56a13a49
ZJS
2249 } else {
2250 /* Trouble: we failed to create the directory. Instead of failing, let's simulate /tmp being
2251 * read-only. This way the service will get the EROFS result as if it was writing to the real
2252 * file system. */
2253 r = mkdir_p(RUN_SYSTEMD_EMPTY, 0500);
2254 if (r < 0)
2255 return r;
613b411c 2256
3f181262
LP
2257 r = free_and_strdup(&x, RUN_SYSTEMD_EMPTY);
2258 if (r < 0)
2259 return r;
c17ec25e 2260 }
15ae422b 2261
1cc6c93a 2262 *path = TAKE_PTR(x);
613b411c
LP
2263 return 0;
2264}
2265
2266int setup_tmp_dirs(const char *id, char **tmp_dir, char **var_tmp_dir) {
56a13a49
ZJS
2267 _cleanup_(namespace_cleanup_tmpdirp) char *a = NULL;
2268 _cleanup_(rmdir_and_freep) char *a_tmp = NULL;
2269 char *b;
613b411c
LP
2270 int r;
2271
2272 assert(id);
2273 assert(tmp_dir);
2274 assert(var_tmp_dir);
2275
56a13a49 2276 r = setup_one_tmp_dir(id, "/tmp", &a, &a_tmp);
613b411c
LP
2277 if (r < 0)
2278 return r;
2279
56a13a49
ZJS
2280 r = setup_one_tmp_dir(id, "/var/tmp", &b, NULL);
2281 if (r < 0)
613b411c 2282 return r;
613b411c 2283
56a13a49
ZJS
2284 a_tmp = mfree(a_tmp); /* avoid rmdir */
2285 *tmp_dir = TAKE_PTR(a);
2286 *var_tmp_dir = TAKE_PTR(b);
613b411c
LP
2287
2288 return 0;
2289}
2290
2caa38e9 2291int setup_netns(const int netns_storage_socket[static 2]) {
613b411c 2292 _cleanup_close_ int netns = -1;
3ee897d6 2293 int r, q;
613b411c
LP
2294
2295 assert(netns_storage_socket);
2296 assert(netns_storage_socket[0] >= 0);
2297 assert(netns_storage_socket[1] >= 0);
2298
2299 /* We use the passed socketpair as a storage buffer for our
76cd584b
LP
2300 * namespace reference fd. Whatever process runs this first
2301 * shall create a new namespace, all others should just join
2302 * it. To serialize that we use a file lock on the socket
2303 * pair.
613b411c
LP
2304 *
2305 * It's a bit crazy, but hey, works great! */
2306
2307 if (lockf(netns_storage_socket[0], F_LOCK, 0) < 0)
2308 return -errno;
2309
3ee897d6
LP
2310 netns = receive_one_fd(netns_storage_socket[0], MSG_DONTWAIT);
2311 if (netns == -EAGAIN) {
44ffcbae 2312 /* Nothing stored yet, so let's create a new namespace. */
613b411c
LP
2313
2314 if (unshare(CLONE_NEWNET) < 0) {
2315 r = -errno;
2316 goto fail;
2317 }
2318
44ffcbae 2319 (void) loopback_setup();
613b411c
LP
2320
2321 netns = open("/proc/self/ns/net", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2322 if (netns < 0) {
2323 r = -errno;
2324 goto fail;
2325 }
2326
2327 r = 1;
613b411c 2328
3ee897d6
LP
2329 } else if (netns < 0) {
2330 r = netns;
2331 goto fail;
613b411c 2332
3ee897d6
LP
2333 } else {
2334 /* Yay, found something, so let's join the namespace */
613b411c
LP
2335 if (setns(netns, CLONE_NEWNET) < 0) {
2336 r = -errno;
2337 goto fail;
2338 }
2339
2340 r = 0;
2341 }
2342
3ee897d6
LP
2343 q = send_one_fd(netns_storage_socket[1], netns, MSG_DONTWAIT);
2344 if (q < 0) {
2345 r = q;
613b411c
LP
2346 goto fail;
2347 }
2348
2349fail:
fe048ce5 2350 (void) lockf(netns_storage_socket[0], F_ULOCK, 0);
15ae422b
LP
2351 return r;
2352}
417116f2 2353
2caa38e9 2354int open_netns_path(const int netns_storage_socket[static 2], const char *path) {
51af7fb2
LP
2355 _cleanup_close_ int netns = -1;
2356 int q, r;
2357
2358 assert(netns_storage_socket);
2359 assert(netns_storage_socket[0] >= 0);
2360 assert(netns_storage_socket[1] >= 0);
2361 assert(path);
2362
2363 /* If the storage socket doesn't contain a netns fd yet, open one via the file system and store it in
2364 * it. This is supposed to be called ahead of time, i.e. before setup_netns() which will allocate a
2365 * new anonymous netns if needed. */
2366
2367 if (lockf(netns_storage_socket[0], F_LOCK, 0) < 0)
2368 return -errno;
2369
2370 netns = receive_one_fd(netns_storage_socket[0], MSG_DONTWAIT);
2371 if (netns == -EAGAIN) {
2372 /* Nothing stored yet. Open the file from the file system. */
2373
2374 netns = open(path, O_RDONLY|O_NOCTTY|O_CLOEXEC);
2375 if (netns < 0) {
2376 r = -errno;
2377 goto fail;
2378 }
2379
2380 r = fd_is_network_ns(netns);
2381 if (r == 0) { /* Not a netns? Refuse early. */
2382 r = -EINVAL;
2383 goto fail;
2384 }
2385 if (r < 0 && r != -EUCLEAN) /* EUCLEAN: we don't know */
2386 goto fail;
2387
2388 r = 1;
2389
2390 } else if (netns < 0) {
2391 r = netns;
2392 goto fail;
2393 } else
2394 r = 0; /* Already allocated */
2395
2396 q = send_one_fd(netns_storage_socket[1], netns, MSG_DONTWAIT);
2397 if (q < 0) {
2398 r = q;
2399 goto fail;
2400 }
2401
2402fail:
2403 (void) lockf(netns_storage_socket[0], F_ULOCK, 0);
2404 return r;
2405}
2406
6e2d7c4f
MS
2407bool ns_type_supported(NamespaceType type) {
2408 const char *t, *ns_proc;
2409
0fa5b831
LP
2410 t = namespace_type_to_string(type);
2411 if (!t) /* Don't know how to translate this? Then it's not supported */
6e2d7c4f
MS
2412 return false;
2413
6e2d7c4f 2414 ns_proc = strjoina("/proc/self/ns/", t);
6e2d7c4f
MS
2415 return access(ns_proc, F_OK) == 0;
2416}
2417
1b8689f9 2418static const char *const protect_home_table[_PROTECT_HOME_MAX] = {
cbc056c8
ZJS
2419 [PROTECT_HOME_NO] = "no",
2420 [PROTECT_HOME_YES] = "yes",
1b8689f9 2421 [PROTECT_HOME_READ_ONLY] = "read-only",
cbc056c8 2422 [PROTECT_HOME_TMPFS] = "tmpfs",
417116f2
LP
2423};
2424
1e8c7bd5 2425DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_home, ProtectHome, PROTECT_HOME_YES);
5e1c6154 2426
1b8689f9 2427static const char *const protect_system_table[_PROTECT_SYSTEM_MAX] = {
cbc056c8
ZJS
2428 [PROTECT_SYSTEM_NO] = "no",
2429 [PROTECT_SYSTEM_YES] = "yes",
2430 [PROTECT_SYSTEM_FULL] = "full",
3f815163 2431 [PROTECT_SYSTEM_STRICT] = "strict",
1b8689f9
LP
2432};
2433
1e8c7bd5 2434DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(protect_system, ProtectSystem, PROTECT_SYSTEM_YES);
03c791aa 2435
6e2d7c4f 2436static const char* const namespace_type_table[] = {
cbc056c8 2437 [NAMESPACE_MOUNT] = "mnt",
6e2d7c4f 2438 [NAMESPACE_CGROUP] = "cgroup",
cbc056c8
ZJS
2439 [NAMESPACE_UTS] = "uts",
2440 [NAMESPACE_IPC] = "ipc",
2441 [NAMESPACE_USER] = "user",
2442 [NAMESPACE_PID] = "pid",
2443 [NAMESPACE_NET] = "net",
6e2d7c4f
MS
2444};
2445
2446DEFINE_STRING_TABLE_LOOKUP(namespace_type, NamespaceType);
4e399953
LP
2447
2448static const char* const protect_proc_table[_PROTECT_PROC_MAX] = {
2449 [PROTECT_PROC_DEFAULT] = "default",
2450 [PROTECT_PROC_NOACCESS] = "noaccess",
2451 [PROTECT_PROC_INVISIBLE] = "invisible",
2452 [PROTECT_PROC_PTRACEABLE] = "ptraceable",
2453};
2454
2455DEFINE_STRING_TABLE_LOOKUP(protect_proc, ProtectProc);
2456
2457static const char* const proc_subset_table[_PROC_SUBSET_MAX] = {
2458 [PROC_SUBSET_ALL] = "all",
2459 [PROC_SUBSET_PID] = "pid",
2460};
2461
2462DEFINE_STRING_TABLE_LOOKUP(proc_subset, ProcSubset);