]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/namespace.c
core: don't use the unified hierarchy for the systemd cgroup yet (#4628)
[thirdparty/systemd.git] / src / core / namespace.c
CommitLineData
15ae422b
LP
1/***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
15ae422b
LP
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 14 Lesser General Public License for more details.
15ae422b 15
5430f7f2 16 You should have received a copy of the GNU Lesser General Public License
15ae422b
LP
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
20#include <errno.h>
07630cea 21#include <sched.h>
15ae422b 22#include <stdio.h>
07630cea
LP
23#include <string.h>
24#include <sys/mount.h>
15ae422b 25#include <sys/stat.h>
07630cea 26#include <unistd.h>
25e870b5 27#include <linux/fs.h>
15ae422b 28
b5efdb8a 29#include "alloc-util.h"
7f112f50 30#include "dev-setup.h"
3ffd4af2 31#include "fd-util.h"
d944dc95 32#include "fs-util.h"
07630cea
LP
33#include "loopback-setup.h"
34#include "missing.h"
35#include "mkdir.h"
4349cd7c 36#include "mount-util.h"
3ffd4af2 37#include "namespace.h"
07630cea 38#include "path-util.h"
d7b8eec7 39#include "selinux-util.h"
2583fbea 40#include "socket-util.h"
8b43440b 41#include "string-table.h"
07630cea
LP
42#include "string-util.h"
43#include "strv.h"
affb60b1 44#include "umask-util.h"
ee104e11 45#include "user-util.h"
07630cea 46#include "util.h"
15ae422b 47
737ba3c8 48#define DEV_MOUNT_OPTIONS (MS_NOSUID|MS_STRICTATIME|MS_NOEXEC)
49
c17ec25e 50typedef enum MountMode {
15ae422b
LP
51 /* This is ordered by priority! */
52 INACCESSIBLE,
53 READONLY,
ac0930c8
LP
54 PRIVATE_TMP,
55 PRIVATE_VAR_TMP,
7f112f50 56 PRIVATE_DEV,
59eeb84b 57 READWRITE,
c17ec25e 58} MountMode;
15ae422b 59
c17ec25e 60typedef struct BindMount {
f0a4feb0 61 char *path;
c17ec25e 62 MountMode mode;
11a30cec 63 bool ignore; /* Ignore if path does not exist */
c17ec25e 64} BindMount;
15ae422b 65
11a30cec
DH
66typedef struct TargetMount {
67 const char *path;
68 MountMode mode;
69 bool ignore; /* Ignore if path does not exist */
70} TargetMount;
71
f471b2af
DH
72/*
73 * The following Protect tables are to protect paths and mark some of them
74 * READONLY, in case a path is covered by an option from another table, then
75 * it is marked READWRITE in the current one, and the more restrictive mode is
76 * applied from that other table. This way all options can be combined in a
77 * safe and comprehensible way for users.
78 */
79
11a30cec
DH
80/* ProtectKernelTunables= option and the related filesystem APIs */
81static const TargetMount protect_kernel_tunables_table[] = {
82 { "/proc/sys", READONLY, false },
83 { "/proc/sysrq-trigger", READONLY, true },
49accde7
DH
84 { "/proc/latency_stats", READONLY, true },
85 { "/proc/mtrr", READONLY, true },
86 { "/proc/apm", READONLY, true },
87 { "/proc/acpi", READONLY, true },
88 { "/proc/timer_stats", READONLY, true },
89 { "/proc/asound", READONLY, true },
90 { "/proc/bus", READONLY, true },
91 { "/proc/fs", READONLY, true },
92 { "/proc/irq", READONLY, true },
11a30cec 93 { "/sys", READONLY, false },
49accde7
DH
94 { "/sys/kernel/debug", READONLY, true },
95 { "/sys/kernel/tracing", READONLY, true },
11a30cec
DH
96 { "/sys/fs/cgroup", READWRITE, false }, /* READONLY is set by ProtectControlGroups= option */
97};
98
c575770b
DH
99/* ProtectKernelModules= option */
100static const TargetMount protect_kernel_modules_table[] = {
101#ifdef HAVE_SPLIT_USR
102 { "/lib/modules", INACCESSIBLE, true },
103#endif
104 { "/usr/lib/modules", INACCESSIBLE, true },
105};
106
b6c432ca
DH
107/*
108 * ProtectHome=read-only table, protect $HOME and $XDG_RUNTIME_DIR and rest of
109 * system should be protected by ProtectSystem=
110 */
111static const TargetMount protect_home_read_only_table[] = {
112 { "/home", READONLY, true },
113 { "/run/user", READONLY, true },
114 { "/root", READONLY, true },
115};
116
117/* ProtectHome=yes table */
118static const TargetMount protect_home_yes_table[] = {
119 { "/home", INACCESSIBLE, true },
120 { "/run/user", INACCESSIBLE, true },
121 { "/root", INACCESSIBLE, true },
122};
123
f471b2af
DH
124/* ProtectSystem=yes table */
125static const TargetMount protect_system_yes_table[] = {
126 { "/usr", READONLY, false },
127 { "/boot", READONLY, true },
128 { "/efi", READONLY, true },
129};
130
131/* ProtectSystem=full includes ProtectSystem=yes */
132static const TargetMount protect_system_full_table[] = {
133 { "/usr", READONLY, false },
134 { "/boot", READONLY, true },
135 { "/efi", READONLY, true },
136 { "/etc", READONLY, false },
137};
138
139/*
140 * ProtectSystem=strict table. In this strict mode, we mount everything
141 * read-only, except for /proc, /dev, /sys which are the kernel API VFS,
142 * which are left writable, but PrivateDevices= + ProtectKernelTunables=
143 * protect those, and these options should be fully orthogonal.
144 * (And of course /home and friends are also left writable, as ProtectHome=
145 * shall manage those, orthogonally).
146 */
147static const TargetMount protect_system_strict_table[] = {
148 { "/", READONLY, false },
149 { "/proc", READWRITE, false }, /* ProtectKernelTunables= */
150 { "/sys", READWRITE, false }, /* ProtectKernelTunables= */
151 { "/dev", READWRITE, false }, /* PrivateDevices= */
152 { "/home", READWRITE, true }, /* ProtectHome= */
153 { "/run/user", READWRITE, true }, /* ProtectHome= */
154 { "/root", READWRITE, true }, /* ProtectHome= */
155};
156
46c3230d
ZJS
157static void set_bind_mount(BindMount *p, char *path, MountMode mode, bool ignore) {
158 p->path = path;
159 p->mode = mode;
160 p->ignore = ignore;
f471b2af
DH
161}
162
f0a4feb0
DH
163static int append_one_mount(BindMount **p, const char *root_directory,
164 const char *path, MountMode mode, bool ignore) {
165 char *lpath;
166 assert(p);
167
168 lpath = prefix_root(root_directory, path);
169 if (!lpath)
170 return -ENOMEM;
171
46c3230d 172 set_bind_mount((*p)++, lpath, mode, ignore);
f0a4feb0
DH
173 return 0;
174}
175
c17ec25e 176static int append_mounts(BindMount **p, char **strv, MountMode mode) {
15ae422b
LP
177 char **i;
178
613b411c
LP
179 assert(p);
180
15ae422b 181 STRV_FOREACH(i, strv) {
9c94d52e 182 bool ignore = false;
f0a4feb0 183 char *path;
15ae422b 184
9c94d52e 185 if (IN_SET(mode, INACCESSIBLE, READONLY, READWRITE) && startswith(*i, "-")) {
ea92ae33 186 (*i)++;
9c94d52e 187 ignore = true;
ea92ae33
MW
188 }
189
15ae422b
LP
190 if (!path_is_absolute(*i))
191 return -EINVAL;
192
f0a4feb0
DH
193 path = strdup(*i);
194 if (!path)
195 return -ENOMEM;
196
46c3230d 197 set_bind_mount((*p)++, path, mode, ignore);
15ae422b
LP
198 }
199
200 return 0;
201}
202
af964954
DH
203static int append_target_mounts(BindMount **p, const char *root_directory,
204 const TargetMount *mounts, const size_t size, bool ignore_protect) {
f471b2af 205 unsigned i;
11a30cec
DH
206
207 assert(p);
f471b2af 208 assert(mounts);
11a30cec 209
f471b2af 210 for (i = 0; i < size; i++) {
af964954 211 bool ignore;
f471b2af
DH
212 /*
213 * Here we assume that the ignore field is set during
214 * declaration we do not support "-" at the beginning.
215 */
216 const TargetMount *m = &mounts[i];
f0a4feb0
DH
217 char *path;
218
219 path = prefix_root(root_directory, m->path);
220 if (!path)
221 return -ENOMEM;
f471b2af
DH
222
223 if (!path_is_absolute(path))
224 return -EINVAL;
225
af964954
DH
226 /*
227 * Ignore paths if they are not present. First we use our
228 * static tables otherwise fallback to Unit context.
229 */
230 ignore = m->ignore || ignore_protect;
231
232 set_bind_mount((*p)++, path, m->mode, ignore);
11a30cec 233 }
f471b2af
DH
234
235 return 0;
236}
237
af964954 238static int append_protect_kernel_tunables(BindMount **p, const char *root_directory, bool ignore_protect) {
f471b2af
DH
239 assert(p);
240
241 return append_target_mounts(p, root_directory, protect_kernel_tunables_table,
af964954 242 ELEMENTSOF(protect_kernel_tunables_table), ignore_protect);
f471b2af
DH
243}
244
af964954 245static int append_protect_kernel_modules(BindMount **p, const char *root_directory, bool ignore_protect) {
c575770b
DH
246 assert(p);
247
248 return append_target_mounts(p, root_directory, protect_kernel_modules_table,
af964954 249 ELEMENTSOF(protect_kernel_modules_table), ignore_protect);
c575770b
DH
250}
251
af964954 252static int append_protect_home(BindMount **p, const char *root_directory, ProtectHome protect_home, bool ignore_protect) {
b6c432ca
DH
253 int r = 0;
254
255 assert(p);
256
257 if (protect_home == PROTECT_HOME_NO)
258 return 0;
259
260 switch (protect_home) {
261 case PROTECT_HOME_READ_ONLY:
262 r = append_target_mounts(p, root_directory, protect_home_read_only_table,
af964954
DH
263 ELEMENTSOF(protect_home_read_only_table),
264 ignore_protect);
b6c432ca
DH
265 break;
266 case PROTECT_HOME_YES:
267 r = append_target_mounts(p, root_directory, protect_home_yes_table,
af964954 268 ELEMENTSOF(protect_home_yes_table), ignore_protect);
b6c432ca
DH
269 break;
270 default:
271 r = -EINVAL;
272 break;
273 }
274
275 return r;
276}
277
af964954 278static int append_protect_system(BindMount **p, const char *root_directory, ProtectSystem protect_system, bool ignore_protect) {
f471b2af
DH
279 int r = 0;
280
281 assert(p);
282
283 if (protect_system == PROTECT_SYSTEM_NO)
284 return 0;
285
286 switch (protect_system) {
287 case PROTECT_SYSTEM_STRICT:
288 r = append_target_mounts(p, root_directory, protect_system_strict_table,
af964954 289 ELEMENTSOF(protect_system_strict_table), ignore_protect);
f471b2af
DH
290 break;
291 case PROTECT_SYSTEM_YES:
292 r = append_target_mounts(p, root_directory, protect_system_yes_table,
af964954 293 ELEMENTSOF(protect_system_yes_table), ignore_protect);
f471b2af
DH
294 break;
295 case PROTECT_SYSTEM_FULL:
296 r = append_target_mounts(p, root_directory, protect_system_full_table,
af964954 297 ELEMENTSOF(protect_system_full_table), ignore_protect);
f471b2af
DH
298 break;
299 default:
300 r = -EINVAL;
301 break;
302 }
303
304 return r;
11a30cec
DH
305}
306
c17ec25e
MS
307static int mount_path_compare(const void *a, const void *b) {
308 const BindMount *p = a, *q = b;
a0827e2b 309 int d;
15ae422b 310
6ee1a919 311 /* If the paths are not equal, then order prefixes first */
a0827e2b 312 d = path_compare(p->path, q->path);
6ee1a919
LP
313 if (d != 0)
314 return d;
15ae422b 315
6ee1a919
LP
316 /* If the paths are equal, check the mode */
317 if (p->mode < q->mode)
318 return -1;
15ae422b 319
6ee1a919
LP
320 if (p->mode > q->mode)
321 return 1;
15ae422b 322
6ee1a919 323 return 0;
15ae422b
LP
324}
325
c17ec25e
MS
326static void drop_duplicates(BindMount *m, unsigned *n) {
327 BindMount *f, *t, *previous;
15ae422b 328
c17ec25e 329 assert(m);
15ae422b 330 assert(n);
15ae422b 331
fe3c2583
LP
332 /* Drops duplicate entries. Expects that the array is properly ordered already. */
333
c17ec25e 334 for (f = m, t = m, previous = NULL; f < m+*n; f++) {
15ae422b 335
fe3c2583
LP
336 /* The first one wins (which is the one with the more restrictive mode), see mount_path_compare()
337 * above. */
338 if (previous && path_equal(f->path, previous->path)) {
339 log_debug("%s is duplicate.", f->path);
f0a4feb0 340 f->path = mfree(f->path);
15ae422b 341 continue;
fe3c2583 342 }
15ae422b 343
e2d7c1a0 344 *t = *f;
15ae422b 345 previous = t;
fe3c2583
LP
346 t++;
347 }
348
349 *n = t - m;
350}
351
352static void drop_inaccessible(BindMount *m, unsigned *n) {
353 BindMount *f, *t;
354 const char *clear = NULL;
355
356 assert(m);
357 assert(n);
358
359 /* Drops all entries obstructed by another entry further up the tree. Expects that the array is properly
360 * ordered already. */
361
362 for (f = m, t = m; f < m+*n; f++) {
363
364 /* If we found a path set for INACCESSIBLE earlier, and this entry has it as prefix we should drop
365 * it, as inaccessible paths really should drop the entire subtree. */
366 if (clear && path_startswith(f->path, clear)) {
367 log_debug("%s is masked by %s.", f->path, clear);
f0a4feb0 368 f->path = mfree(f->path);
fe3c2583
LP
369 continue;
370 }
15ae422b 371
fe3c2583
LP
372 clear = f->mode == INACCESSIBLE ? f->path : NULL;
373
374 *t = *f;
15ae422b
LP
375 t++;
376 }
377
c17ec25e 378 *n = t - m;
15ae422b
LP
379}
380
7648a565
LP
381static void drop_nop(BindMount *m, unsigned *n) {
382 BindMount *f, *t;
383
384 assert(m);
385 assert(n);
386
387 /* Drops all entries which have an immediate parent that has the same type, as they are redundant. Assumes the
388 * list is ordered by prefixes. */
389
390 for (f = m, t = m; f < m+*n; f++) {
391
392 /* Only suppress such subtrees for READONLY and READWRITE entries */
393 if (IN_SET(f->mode, READONLY, READWRITE)) {
394 BindMount *p;
395 bool found = false;
396
397 /* Now let's find the first parent of the entry we are looking at. */
398 for (p = t-1; p >= m; p--) {
399 if (path_startswith(f->path, p->path)) {
400 found = true;
401 break;
402 }
403 }
404
405 /* We found it, let's see if it's the same mode, if so, we can drop this entry */
406 if (found && p->mode == f->mode) {
407 log_debug("%s is redundant by %s", f->path, p->path);
f0a4feb0 408 f->path = mfree(f->path);
7648a565
LP
409 continue;
410 }
411 }
412
413 *t = *f;
414 t++;
415 }
416
417 *n = t - m;
418}
419
cd2902c9
LP
420static void drop_outside_root(const char *root_directory, BindMount *m, unsigned *n) {
421 BindMount *f, *t;
422
423 assert(m);
424 assert(n);
425
426 if (!root_directory)
427 return;
428
429 /* Drops all mounts that are outside of the root directory. */
430
431 for (f = m, t = m; f < m+*n; f++) {
432
433 if (!path_startswith(f->path, root_directory)) {
434 log_debug("%s is outside of root directory.", f->path);
f0a4feb0 435 f->path = mfree(f->path);
cd2902c9
LP
436 continue;
437 }
438
439 *t = *f;
440 t++;
441 }
442
443 *n = t - m;
444}
445
7f112f50
LP
446static int mount_dev(BindMount *m) {
447 static const char devnodes[] =
448 "/dev/null\0"
449 "/dev/zero\0"
450 "/dev/full\0"
451 "/dev/random\0"
452 "/dev/urandom\0"
453 "/dev/tty\0";
454
2b85f4e1 455 char temporary_mount[] = "/tmp/namespace-dev-XXXXXX";
63cc4c31 456 const char *d, *dev = NULL, *devpts = NULL, *devshm = NULL, *devhugepages = NULL, *devmqueue = NULL, *devlog = NULL, *devptmx = NULL;
7f112f50
LP
457 _cleanup_umask_ mode_t u;
458 int r;
459
460 assert(m);
461
462 u = umask(0000);
463
2b85f4e1
LP
464 if (!mkdtemp(temporary_mount))
465 return -errno;
466
63c372cb 467 dev = strjoina(temporary_mount, "/dev");
dc751688 468 (void) mkdir(dev, 0755);
737ba3c8 469 if (mount("tmpfs", dev, "tmpfs", DEV_MOUNT_OPTIONS, "mode=755") < 0) {
2b85f4e1
LP
470 r = -errno;
471 goto fail;
472 }
473
63c372cb 474 devpts = strjoina(temporary_mount, "/dev/pts");
dc751688 475 (void) mkdir(devpts, 0755);
2b85f4e1
LP
476 if (mount("/dev/pts", devpts, NULL, MS_BIND, NULL) < 0) {
477 r = -errno;
478 goto fail;
479 }
480
63c372cb 481 devptmx = strjoina(temporary_mount, "/dev/ptmx");
3164e3cb
ZJS
482 if (symlink("pts/ptmx", devptmx) < 0) {
483 r = -errno;
484 goto fail;
485 }
e06b6479 486
63c372cb 487 devshm = strjoina(temporary_mount, "/dev/shm");
dc751688 488 (void) mkdir(devshm, 01777);
2b85f4e1
LP
489 r = mount("/dev/shm", devshm, NULL, MS_BIND, NULL);
490 if (r < 0) {
491 r = -errno;
492 goto fail;
493 }
494
63c372cb 495 devmqueue = strjoina(temporary_mount, "/dev/mqueue");
dc751688 496 (void) mkdir(devmqueue, 0755);
3164e3cb 497 (void) mount("/dev/mqueue", devmqueue, NULL, MS_BIND, NULL);
2b85f4e1 498
63c372cb 499 devhugepages = strjoina(temporary_mount, "/dev/hugepages");
dc751688 500 (void) mkdir(devhugepages, 0755);
3164e3cb 501 (void) mount("/dev/hugepages", devhugepages, NULL, MS_BIND, NULL);
2b85f4e1 502
63c372cb 503 devlog = strjoina(temporary_mount, "/dev/log");
3164e3cb 504 (void) symlink("/run/systemd/journal/dev-log", devlog);
82d25240 505
7f112f50 506 NULSTR_FOREACH(d, devnodes) {
2b85f4e1
LP
507 _cleanup_free_ char *dn = NULL;
508 struct stat st;
509
510 r = stat(d, &st);
7f112f50 511 if (r < 0) {
2b85f4e1
LP
512
513 if (errno == ENOENT)
514 continue;
515
516 r = -errno;
517 goto fail;
7f112f50
LP
518 }
519
2b85f4e1
LP
520 if (!S_ISBLK(st.st_mode) &&
521 !S_ISCHR(st.st_mode)) {
522 r = -EINVAL;
523 goto fail;
524 }
525
526 if (st.st_rdev == 0)
527 continue;
528
529 dn = strappend(temporary_mount, d);
530 if (!dn) {
531 r = -ENOMEM;
532 goto fail;
533 }
534
ecabcf8b 535 mac_selinux_create_file_prepare(d, st.st_mode);
2b85f4e1 536 r = mknod(dn, st.st_mode, st.st_rdev);
ecabcf8b 537 mac_selinux_create_file_clear();
dd078a1e 538
2b85f4e1
LP
539 if (r < 0) {
540 r = -errno;
541 goto fail;
542 }
7f112f50
LP
543 }
544
03cfe0d5 545 dev_setup(temporary_mount, UID_INVALID, GID_INVALID);
7f112f50 546
ee818b89
AC
547 /* Create the /dev directory if missing. It is more likely to be
548 * missing when the service is started with RootDirectory. This is
549 * consistent with mount units creating the mount points when missing.
550 */
551 (void) mkdir_p_label(m->path, 0755);
552
9e5f8252 553 /* Unmount everything in old /dev */
554 umount_recursive(m->path, 0);
ee818b89 555 if (mount(dev, m->path, NULL, MS_MOVE, NULL) < 0) {
2b85f4e1
LP
556 r = -errno;
557 goto fail;
558 }
7f112f50 559
2b85f4e1
LP
560 rmdir(dev);
561 rmdir(temporary_mount);
7f112f50 562
2b85f4e1 563 return 0;
7f112f50 564
2b85f4e1
LP
565fail:
566 if (devpts)
567 umount(devpts);
7f112f50 568
2b85f4e1
LP
569 if (devshm)
570 umount(devshm);
7f112f50 571
2b85f4e1
LP
572 if (devhugepages)
573 umount(devhugepages);
7f112f50 574
2b85f4e1
LP
575 if (devmqueue)
576 umount(devmqueue);
7f112f50 577
d267c5aa
ZJS
578 umount(dev);
579 rmdir(dev);
2b85f4e1 580 rmdir(temporary_mount);
7f112f50 581
2b85f4e1 582 return r;
7f112f50
LP
583}
584
ac0930c8 585static int apply_mount(
c17ec25e 586 BindMount *m,
ac0930c8 587 const char *tmp_dir,
c17ec25e 588 const char *var_tmp_dir) {
ac0930c8 589
15ae422b 590 const char *what;
15ae422b 591 int r;
15ae422b 592
c17ec25e 593 assert(m);
15ae422b 594
fe3c2583
LP
595 log_debug("Applying namespace mount on %s", m->path);
596
c17ec25e 597 switch (m->mode) {
15ae422b 598
160cfdbe
LP
599 case INACCESSIBLE: {
600 struct stat target;
6d313367
LP
601
602 /* First, get rid of everything that is below if there
603 * is anything... Then, overmount it with an
c4b41707 604 * inaccessible path. */
fe3c2583 605 (void) umount_recursive(m->path, 0);
6d313367 606
d944dc95 607 if (lstat(m->path, &target) < 0)
160cfdbe 608 return log_debug_errno(errno, "Failed to lstat() %s to determine what to mount over it: %m", m->path);
15ae422b 609
c4b41707 610 what = mode_to_inaccessible_node(target.st_mode);
5fd7cf6f
LP
611 if (!what) {
612 log_debug("File type not supported for inaccessible mounts. Note that symlinks are not allowed");
c4b41707
AP
613 return -ELOOP;
614 }
615 break;
160cfdbe 616 }
fe3c2583 617
15ae422b 618 case READONLY:
15ae422b 619 case READWRITE:
6b7c9f8b
LP
620
621 r = path_is_mount_point(m->path, 0);
d944dc95 622 if (r < 0)
6b7c9f8b 623 return log_debug_errno(r, "Failed to determine whether %s is already a mount point: %m", m->path);
6b7c9f8b
LP
624 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. */
625 return 0;
6b7c9f8b
LP
626 /* This isn't a mount point yet, let's make it one. */
627 what = m->path;
628 break;
15ae422b 629
ac0930c8
LP
630 case PRIVATE_TMP:
631 what = tmp_dir;
632 break;
633
634 case PRIVATE_VAR_TMP:
635 what = var_tmp_dir;
15ae422b 636 break;
e364ad06 637
d6797c92
LP
638 case PRIVATE_DEV:
639 return mount_dev(m);
640
e364ad06
LP
641 default:
642 assert_not_reached("Unknown mode");
15ae422b
LP
643 }
644
ac0930c8 645 assert(what);
15ae422b 646
d944dc95 647 if (mount(what, m->path, NULL, MS_BIND|MS_REC, NULL) < 0)
5fd7cf6f 648 return log_debug_errno(errno, "Failed to mount %s to %s: %m", what, m->path);
6b7c9f8b
LP
649
650 log_debug("Successfully mounted %s to %s", what, m->path);
651 return 0;
ac0930c8 652}
15ae422b 653
6b7c9f8b
LP
654static int make_read_only(BindMount *m, char **blacklist) {
655 int r = 0;
15ae422b 656
c17ec25e 657 assert(m);
ac0930c8 658
d6797c92 659 if (IN_SET(m->mode, INACCESSIBLE, READONLY))
6b7c9f8b
LP
660 r = bind_remount_recursive(m->path, true, blacklist);
661 else if (m->mode == PRIVATE_DEV) { /* Can be readonly but the submounts can't*/
662 if (mount(NULL, m->path, NULL, MS_REMOUNT|DEV_MOUNT_OPTIONS|MS_RDONLY, NULL) < 0)
663 r = -errno;
737ba3c8 664 } else
6b7c9f8b
LP
665 return 0;
666
667 /* Not that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked read-only
668 * already stays this way. This improves compatibility with container managers, where we won't attempt to undo
669 * read-only mounts already applied. */
ac0930c8 670
d6797c92 671 return r;
15ae422b
LP
672}
673
d944dc95
LP
674static int chase_all_symlinks(const char *root_directory, BindMount *m, unsigned *n) {
675 BindMount *f, *t;
676 int r;
677
678 assert(m);
679 assert(n);
680
681 /* Since mount() will always follow symlinks and we need to take the different root directory into account we
682 * chase the symlinks on our own first. This call wil do so for all entries and remove all entries where we
683 * can't resolve the path, and which have been marked for such removal. */
684
49fedb40 685 for (f = m, t = m; f < m + *n; f++) {
f0a4feb0 686 _cleanup_free_ char *chased = NULL;
49fedb40 687
f0a4feb0
DH
688 r = chase_symlinks(f->path, root_directory, &chased);
689 if (r == -ENOENT && f->ignore) {
690 /* Doesn't exist? Then remove it! */
691 f->path = mfree(f->path);
d944dc95 692 continue;
f0a4feb0 693 }
d944dc95
LP
694 if (r < 0)
695 return log_debug_errno(r, "Failed to chase symlinks for %s: %m", f->path);
696
f0a4feb0
DH
697 if (!path_equal(f->path, chased)) {
698 log_debug("Chased %s → %s", f->path, chased);
49fedb40 699 r = free_and_replace(f->path, chased);
f0a4feb0
DH
700 if (r < 0)
701 return r;
d944dc95
LP
702 }
703
704 *t = *f;
705 t++;
706 }
707
708 *n = t - m;
709 return 0;
710}
711
2652c6c1 712static unsigned namespace_calculate_mounts(
c575770b 713 const NameSpaceInfo *ns_info,
2652c6c1
DH
714 char** read_write_paths,
715 char** read_only_paths,
716 char** inaccessible_paths,
717 const char* tmp_dir,
718 const char* var_tmp_dir,
2652c6c1
DH
719 ProtectHome protect_home,
720 ProtectSystem protect_system) {
721
b6c432ca 722 unsigned protect_home_cnt;
f471b2af
DH
723 unsigned protect_system_cnt =
724 (protect_system == PROTECT_SYSTEM_STRICT ?
725 ELEMENTSOF(protect_system_strict_table) :
726 ((protect_system == PROTECT_SYSTEM_FULL) ?
727 ELEMENTSOF(protect_system_full_table) :
728 ((protect_system == PROTECT_SYSTEM_YES) ?
729 ELEMENTSOF(protect_system_yes_table) : 0)));
730
b6c432ca
DH
731 protect_home_cnt =
732 (protect_home == PROTECT_HOME_YES ?
733 ELEMENTSOF(protect_home_yes_table) :
734 ((protect_home == PROTECT_HOME_READ_ONLY) ?
735 ELEMENTSOF(protect_home_read_only_table) : 0));
736
2652c6c1
DH
737 return !!tmp_dir + !!var_tmp_dir +
738 strv_length(read_write_paths) +
739 strv_length(read_only_paths) +
740 strv_length(inaccessible_paths) +
c575770b
DH
741 ns_info->private_dev +
742 (ns_info->protect_kernel_tunables ? ELEMENTSOF(protect_kernel_tunables_table) : 0) +
743 (ns_info->protect_control_groups ? 1 : 0) +
744 (ns_info->protect_kernel_modules ? ELEMENTSOF(protect_kernel_modules_table) : 0) +
b6c432ca 745 protect_home_cnt + protect_system_cnt;
2652c6c1
DH
746}
747
613b411c 748int setup_namespace(
ee818b89 749 const char* root_directory,
c575770b 750 const NameSpaceInfo *ns_info,
2a624c36
AP
751 char** read_write_paths,
752 char** read_only_paths,
753 char** inaccessible_paths,
a004cb4c
LP
754 const char* tmp_dir,
755 const char* var_tmp_dir,
1b8689f9
LP
756 ProtectHome protect_home,
757 ProtectSystem protect_system,
e6547662 758 unsigned long mount_flags) {
15ae422b 759
7ff7394d 760 BindMount *m, *mounts = NULL;
d944dc95 761 bool make_slave = false;
f0a4feb0 762 unsigned n_mounts;
c17ec25e 763 int r = 0;
15ae422b 764
613b411c 765 if (mount_flags == 0)
c17ec25e 766 mount_flags = MS_SHARED;
ac0930c8 767
f0a4feb0
DH
768 n_mounts = namespace_calculate_mounts(ns_info,
769 read_write_paths,
770 read_only_paths,
771 inaccessible_paths,
772 tmp_dir, var_tmp_dir,
773 protect_home, protect_system);
613b411c 774
2652c6c1 775 /* Set mount slave mode */
f0a4feb0 776 if (root_directory || n_mounts > 0)
d944dc95
LP
777 make_slave = true;
778
f0a4feb0
DH
779 if (n_mounts > 0) {
780 m = mounts = (BindMount *) alloca0(n_mounts * sizeof(BindMount));
2a624c36 781 r = append_mounts(&m, read_write_paths, READWRITE);
613b411c 782 if (r < 0)
f0a4feb0 783 goto finish;
613b411c 784
2a624c36 785 r = append_mounts(&m, read_only_paths, READONLY);
613b411c 786 if (r < 0)
f0a4feb0 787 goto finish;
613b411c 788
2a624c36 789 r = append_mounts(&m, inaccessible_paths, INACCESSIBLE);
613b411c 790 if (r < 0)
f0a4feb0 791 goto finish;
7ff7394d 792
613b411c 793 if (tmp_dir) {
f0a4feb0
DH
794 r = append_one_mount(&m, root_directory, "/tmp", PRIVATE_TMP, false);
795 if (r < 0)
796 goto finish;
613b411c 797 }
7ff7394d 798
613b411c 799 if (var_tmp_dir) {
f0a4feb0
DH
800 r = append_one_mount(&m, root_directory, "/var/tmp", PRIVATE_VAR_TMP, false);
801 if (r < 0)
802 goto finish;
7ff7394d 803 }
ac0930c8 804
c575770b 805 if (ns_info->private_dev) {
f0a4feb0
DH
806 r = append_one_mount(&m, root_directory, "/dev", PRIVATE_DEV, false);
807 if (r < 0)
808 goto finish;
7f112f50
LP
809 }
810
c575770b 811 if (ns_info->protect_kernel_tunables) {
af964954
DH
812 r = append_protect_kernel_tunables(&m, root_directory,
813 ns_info->ignore_protect_paths);
c575770b 814 if (r < 0)
f0a4feb0 815 goto finish;
c575770b
DH
816 }
817
818 if (ns_info->protect_kernel_modules) {
af964954
DH
819 r = append_protect_kernel_modules(&m, root_directory,
820 ns_info->ignore_protect_paths);
c575770b 821 if (r < 0)
f0a4feb0 822 goto finish;
c575770b 823 }
59eeb84b 824
c575770b 825 if (ns_info->protect_control_groups) {
f0a4feb0
DH
826 r = append_one_mount(&m, root_directory, "/sys/fs/cgroup", READONLY, false);
827 if (r < 0)
828 goto finish;
59eeb84b
LP
829 }
830
af964954
DH
831 r = append_protect_home(&m, root_directory, protect_home,
832 ns_info->ignore_protect_paths);
b6c432ca 833 if (r < 0)
f0a4feb0 834 goto finish;
417116f2 835
af964954 836 r = append_protect_system(&m, root_directory, protect_system, false);
f471b2af 837 if (r < 0)
f0a4feb0 838 goto finish;
417116f2 839
f0a4feb0 840 assert(mounts + n_mounts == m);
ac0930c8 841
d944dc95
LP
842 /* Resolve symlinks manually first, as mount() will always follow them relative to the host's
843 * root. Moreover we want to suppress duplicates based on the resolved paths. This of course is a bit
844 * racy. */
f0a4feb0 845 r = chase_all_symlinks(root_directory, mounts, &n_mounts);
d944dc95
LP
846 if (r < 0)
847 goto finish;
848
f0a4feb0 849 qsort(mounts, n_mounts, sizeof(BindMount), mount_path_compare);
fe3c2583 850
f0a4feb0
DH
851 drop_duplicates(mounts, &n_mounts);
852 drop_outside_root(root_directory, mounts, &n_mounts);
853 drop_inaccessible(mounts, &n_mounts);
854 drop_nop(mounts, &n_mounts);
15ae422b
LP
855 }
856
d944dc95
LP
857 if (unshare(CLONE_NEWNS) < 0) {
858 r = -errno;
859 goto finish;
860 }
1e4e94c8 861
d944dc95 862 if (make_slave) {
c2c13f2d
LP
863 /* Remount / as SLAVE so that nothing now mounted in the namespace
864 shows up in the parent */
d944dc95
LP
865 if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) {
866 r = -errno;
867 goto finish;
868 }
ee818b89
AC
869 }
870
871 if (root_directory) {
8f1ad200
LP
872 /* Turn directory into bind mount, if it isn't one yet */
873 r = path_is_mount_point(root_directory, AT_SYMLINK_FOLLOW);
874 if (r < 0)
d944dc95 875 goto finish;
8f1ad200
LP
876 if (r == 0) {
877 if (mount(root_directory, root_directory, NULL, MS_BIND|MS_REC, NULL) < 0) {
878 r = -errno;
879 goto finish;
880 }
d944dc95 881 }
ee818b89 882 }
c2c13f2d 883
f0a4feb0 884 if (n_mounts > 0) {
6b7c9f8b
LP
885 char **blacklist;
886 unsigned j;
887
888 /* First round, add in all special mounts we need */
f0a4feb0 889 for (m = mounts; m < mounts + n_mounts; ++m) {
c2c13f2d
LP
890 r = apply_mount(m, tmp_dir, var_tmp_dir);
891 if (r < 0)
d944dc95 892 goto finish;
c2c13f2d 893 }
15ae422b 894
6b7c9f8b 895 /* Create a blacklist we can pass to bind_mount_recursive() */
f0a4feb0
DH
896 blacklist = newa(char*, n_mounts+1);
897 for (j = 0; j < n_mounts; j++)
6b7c9f8b
LP
898 blacklist[j] = (char*) mounts[j].path;
899 blacklist[j] = NULL;
900
901 /* Second round, flip the ro bits if necessary. */
f0a4feb0 902 for (m = mounts; m < mounts + n_mounts; ++m) {
6b7c9f8b 903 r = make_read_only(m, blacklist);
c2c13f2d 904 if (r < 0)
d944dc95 905 goto finish;
c2c13f2d 906 }
15ae422b
LP
907 }
908
ee818b89
AC
909 if (root_directory) {
910 /* MS_MOVE does not work on MS_SHARED so the remount MS_SHARED will be done later */
911 r = mount_move_root(root_directory);
d944dc95
LP
912 if (r < 0)
913 goto finish;
ee818b89
AC
914 }
915
c2c13f2d
LP
916 /* Remount / as the desired mode. Not that this will not
917 * reestablish propagation from our side to the host, since
918 * what's disconnected is disconnected. */
d944dc95
LP
919 if (mount(NULL, "/", NULL, mount_flags | MS_REC, NULL) < 0) {
920 r = -errno;
921 goto finish;
922 }
15ae422b 923
d944dc95 924 r = 0;
15ae422b 925
d944dc95 926finish:
f0a4feb0
DH
927 for (m = mounts; m < mounts + n_mounts; m++)
928 free(m->path);
613b411c
LP
929
930 return r;
931}
932
933static int setup_one_tmp_dir(const char *id, const char *prefix, char **path) {
934 _cleanup_free_ char *x = NULL;
6b46ea73
LP
935 char bid[SD_ID128_STRING_MAX];
936 sd_id128_t boot_id;
937 int r;
613b411c
LP
938
939 assert(id);
940 assert(prefix);
941 assert(path);
942
6b46ea73
LP
943 /* We include the boot id in the directory so that after a
944 * reboot we can easily identify obsolete directories. */
945
946 r = sd_id128_get_boot(&boot_id);
947 if (r < 0)
948 return r;
949
605405c6 950 x = strjoin(prefix, "/systemd-private-", sd_id128_to_string(boot_id, bid), "-", id, "-XXXXXX");
613b411c
LP
951 if (!x)
952 return -ENOMEM;
953
954 RUN_WITH_UMASK(0077)
955 if (!mkdtemp(x))
956 return -errno;
957
958 RUN_WITH_UMASK(0000) {
959 char *y;
960
63c372cb 961 y = strjoina(x, "/tmp");
613b411c
LP
962
963 if (mkdir(y, 0777 | S_ISVTX) < 0)
964 return -errno;
c17ec25e 965 }
15ae422b 966
613b411c
LP
967 *path = x;
968 x = NULL;
969
970 return 0;
971}
972
973int setup_tmp_dirs(const char *id, char **tmp_dir, char **var_tmp_dir) {
974 char *a, *b;
975 int r;
976
977 assert(id);
978 assert(tmp_dir);
979 assert(var_tmp_dir);
980
981 r = setup_one_tmp_dir(id, "/tmp", &a);
982 if (r < 0)
983 return r;
984
985 r = setup_one_tmp_dir(id, "/var/tmp", &b);
986 if (r < 0) {
987 char *t;
988
63c372cb 989 t = strjoina(a, "/tmp");
613b411c
LP
990 rmdir(t);
991 rmdir(a);
992
993 free(a);
994 return r;
995 }
996
997 *tmp_dir = a;
998 *var_tmp_dir = b;
999
1000 return 0;
1001}
1002
1003int setup_netns(int netns_storage_socket[2]) {
1004 _cleanup_close_ int netns = -1;
3ee897d6 1005 int r, q;
613b411c
LP
1006
1007 assert(netns_storage_socket);
1008 assert(netns_storage_socket[0] >= 0);
1009 assert(netns_storage_socket[1] >= 0);
1010
1011 /* We use the passed socketpair as a storage buffer for our
76cd584b
LP
1012 * namespace reference fd. Whatever process runs this first
1013 * shall create a new namespace, all others should just join
1014 * it. To serialize that we use a file lock on the socket
1015 * pair.
613b411c
LP
1016 *
1017 * It's a bit crazy, but hey, works great! */
1018
1019 if (lockf(netns_storage_socket[0], F_LOCK, 0) < 0)
1020 return -errno;
1021
3ee897d6
LP
1022 netns = receive_one_fd(netns_storage_socket[0], MSG_DONTWAIT);
1023 if (netns == -EAGAIN) {
613b411c
LP
1024 /* Nothing stored yet, so let's create a new namespace */
1025
1026 if (unshare(CLONE_NEWNET) < 0) {
1027 r = -errno;
1028 goto fail;
1029 }
1030
1031 loopback_setup();
1032
1033 netns = open("/proc/self/ns/net", O_RDONLY|O_CLOEXEC|O_NOCTTY);
1034 if (netns < 0) {
1035 r = -errno;
1036 goto fail;
1037 }
1038
1039 r = 1;
613b411c 1040
3ee897d6
LP
1041 } else if (netns < 0) {
1042 r = netns;
1043 goto fail;
613b411c 1044
3ee897d6
LP
1045 } else {
1046 /* Yay, found something, so let's join the namespace */
613b411c
LP
1047 if (setns(netns, CLONE_NEWNET) < 0) {
1048 r = -errno;
1049 goto fail;
1050 }
1051
1052 r = 0;
1053 }
1054
3ee897d6
LP
1055 q = send_one_fd(netns_storage_socket[1], netns, MSG_DONTWAIT);
1056 if (q < 0) {
1057 r = q;
613b411c
LP
1058 goto fail;
1059 }
1060
1061fail:
fe048ce5 1062 (void) lockf(netns_storage_socket[0], F_ULOCK, 0);
15ae422b
LP
1063 return r;
1064}
417116f2 1065
1b8689f9
LP
1066static const char *const protect_home_table[_PROTECT_HOME_MAX] = {
1067 [PROTECT_HOME_NO] = "no",
1068 [PROTECT_HOME_YES] = "yes",
1069 [PROTECT_HOME_READ_ONLY] = "read-only",
417116f2
LP
1070};
1071
1b8689f9
LP
1072DEFINE_STRING_TABLE_LOOKUP(protect_home, ProtectHome);
1073
1074static const char *const protect_system_table[_PROTECT_SYSTEM_MAX] = {
1075 [PROTECT_SYSTEM_NO] = "no",
1076 [PROTECT_SYSTEM_YES] = "yes",
1077 [PROTECT_SYSTEM_FULL] = "full",
3f815163 1078 [PROTECT_SYSTEM_STRICT] = "strict",
1b8689f9
LP
1079};
1080
1081DEFINE_STRING_TABLE_LOOKUP(protect_system, ProtectSystem);