Debian Codegraph @

src/shared/mount-setup.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/mount.h>
4 #include <unistd.h>
5
6 #include "alloc-util.h"
7 #include "conf-files.h"
8 #include "dev-setup.h"
9 #include "efivars.h"
10 #include "errno-util.h"
11 #include "fd-util.h"
12 #include "fileio.h"
13 #include "label-util.h"
14 #include "log.h"
15 #include "mkdir.h"
16 #include "mount-setup.h"
17 #include "mount-util.h"
18 #include "mountpoint-util.h"
19 #include "path-util.h"
20 #include "recurse-dir.h"
21 #include "smack-util.h"
22 #include "string-util.h"
23 #include "strv.h"
24 #include "time-util.h"
25 #include "virt.h"
26
27 typedef enum MountMode {
28 MNT_FATAL = 1 << 0,
29 MNT_IN_CONTAINER = 1 << 1,
30 MNT_CHECK_WRITABLE = 1 << 2,
31 MNT_FOLLOW_SYMLINK = 1 << 3,
32 } MountMode;
33
34 typedef struct MountPoint {
35 const char *what;
36 const char *where;
37 const char *type;
38 const char *options;
39 int (*options_fn)(int priority, const char *type, char **ret);
40 unsigned long flags;
41 MountMode mode;
42 bool (*condition_fn)(void);
43 } MountPoint;
44
45 static int cgroupfs_mount_options(int priority, const char *type, char **ret) {
46 int r;
47
48 assert(type);
49 assert(streq(type, "cgroup2"));
50 assert(ret);
51
52 /* memory_hugetlb_accounting mount option is since kernel v6.7 (8cba9576df601c384abd334a503c3f6e1e29eefb). */
53
54 r = mount_option_supported("cgroup2", "memory_hugetlb_accounting", /* value= */ NULL);
55 if (r <= 0) {
56 if (r < 0)
57 log_full_errno(priority, r, "Failed to determine whether cgroupfs supports 'memory_hugetlb_accounting' mount option, assuming not: %m");
58 else
59 log_debug("'memory_hugetlb_accounting' not supported by cgroupfs, not using mount option.");
60
61 *ret = NULL;
62 return 0;
63 }
64
65 return strdup_to(ret, "memory_hugetlb_accounting");
66 }
67
68 int mount_cgroupfs(const char *path) {
69 int r;
70
71 assert(path);
72
73 /* Mount a separate cgroupfs instance, taking all options we initial set into account. This is
74 * especially useful when cgroup namespace is *not* employed, since the kernel overrides all
75 * previous options if a new mount is established in initial cgns (c.f.
76 * https://github.com/torvalds/linux/blob/b69bb476dee99d564d65d418e9a20acca6f32c3f/kernel/cgroup/cgroup.c#L1984)
77 */
78
79 _cleanup_free_ char *opts = NULL;
80 r = cgroupfs_mount_options(LOG_WARNING, "cgroup2", &opts);
81 if (r < 0)
82 return r;
83
84 /* These options shall be kept in sync with those in mount_table below. */
85 if (!strprepend_with_separator(&opts, ",", "nsdelegate,memory_recursiveprot"))
86 return log_oom();
87
88 return mount_nofollow_verbose(LOG_ERR, "cgroup2", path, "cgroup2", MS_NOSUID|MS_NOEXEC|MS_NODEV, opts);
89 }
90
91 static int usrquota_mount_option(int priority, const char *type, char **ret) {
92 _cleanup_free_ char *o = NULL;
93 int r;
94
95 assert(type);
96 assert(ret);
97
98 r = mount_option_supported(type, "usrquota", /* value= */ NULL);
99 if (r < 0)
100 log_full_errno(priority, r, "Unable to determine whether %s supports 'usrquota' mount option, assuming not: %m", type);
101 else if (r == 0)
102 log_debug("Not enabling 'usrquota' for '%s' as kernel lacks support for it.", type);
103 else {
104 o = strdup("usrquota");
105 if (!o)
106 return log_oom_full(priority);
107 }
108
109 *ret = TAKE_PTR(o);
110 return 0;
111 }
112
113 static const MountPoint mount_table[] = {
114 {
115 .what = "proc",
116 .where = "/proc",
117 .type = "proc",
118 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV,
119 .mode = MNT_FATAL|MNT_IN_CONTAINER|MNT_FOLLOW_SYMLINK,
120 },
121 {
122 .what = "sysfs",
123 .where = "/sys",
124 .type = "sysfs",
125 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV,
126 .mode = MNT_FATAL|MNT_IN_CONTAINER,
127 },
128 {
129 .what = "devtmpfs",
130 .where = "/dev",
131 .type = "devtmpfs",
132 .options = "mode=0755" TMPFS_LIMITS_DEV,
133 .flags = MS_NOSUID|MS_STRICTATIME,
134 .mode = MNT_FATAL|MNT_IN_CONTAINER,
135 },
136 {
137 .what = "securityfs",
138 .where = "/sys/kernel/security",
139 .type = "securityfs",
140 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV,
141 },
142 #if ENABLE_SMACK
143 {
144 .what = "smackfs",
145 .where = "/sys/fs/smackfs",
146 .type = "smackfs",
147 .options = "smackfsdef=*",
148 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV,
149 .mode = MNT_FATAL,
150 .condition_fn = mac_smack_use,
151 },
152 {
153 .what = "tmpfs",
154 .where = "/dev/shm",
155 .type = "tmpfs",
156 .options = "mode=01777,smackfsroot=*",
157 .options_fn = usrquota_mount_option,
158 .flags = MS_NOSUID|MS_NODEV|MS_STRICTATIME,
159 .mode = MNT_FATAL,
160 .condition_fn = mac_smack_use,
161 },
162 #endif
163 {
164 .what = "tmpfs",
165 .where = "/dev/shm",
166 .type = "tmpfs",
167 .options = "mode=01777",
168 .options_fn = usrquota_mount_option,
169 .flags = MS_NOSUID|MS_NODEV|MS_STRICTATIME,
170 .mode = MNT_FATAL|MNT_IN_CONTAINER,
171 },
172 {
173 .what = "devpts",
174 .where = "/dev/pts",
175 .type = "devpts",
176 .options = "mode=" STRINGIFY(TTY_MODE) ",gid=" STRINGIFY(TTY_GID),
177 .flags = MS_NOSUID|MS_NOEXEC,
178 .mode = MNT_IN_CONTAINER,
179 },
180 #if ENABLE_SMACK
181 {
182 .what = "tmpfs",
183 .where = "/run",
184 .type = "tmpfs",
185 .options = "mode=0755,smackfsroot=*" TMPFS_LIMITS_RUN,
186 .flags = MS_NOSUID|MS_NODEV|MS_STRICTATIME,
187 .mode = MNT_FATAL,
188 .condition_fn = mac_smack_use,
189 },
190 #endif
191 {
192 .what = "tmpfs",
193 .where = "/run",
194 .type = "tmpfs",
195 .options = "mode=0755" TMPFS_LIMITS_RUN,
196 .flags = MS_NOSUID|MS_NODEV|MS_STRICTATIME,
197 .mode = MNT_FATAL|MNT_IN_CONTAINER,
198 },
199 {
200 .what = "cgroup2",
201 .where = "/sys/fs/cgroup",
202 .type = "cgroup2",
203 .options = "nsdelegate,memory_recursiveprot",
204 .options_fn = cgroupfs_mount_options,
205 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV,
206 .mode = MNT_FATAL|MNT_IN_CONTAINER|MNT_CHECK_WRITABLE,
207 },
208 #if ENABLE_PSTORE
209 {
210 .what = "pstore",
211 .where = "/sys/fs/pstore",
212 .type = "pstore",
213 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV,
214 },
215 #endif
216 #if ENABLE_EFI
217 {
218 .what = "efivarfs",
219 .where = "/sys/firmware/efi/efivars",
220 .type = "efivarfs",
221 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV,
222 .condition_fn = is_efi_boot,
223 },
224 #endif
225 {
226 .what = "bpf",
227 .where = "/sys/fs/bpf",
228 .type = "bpf",
229 .options = "mode=0700",
230 .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV,
231 },
232 };
233
234 /* The first three entries we might need before SELinux is up. The
235 * fourth (securityfs) is needed by IMA to load a custom policy. The
236 * other ones we can delay until SELinux and IMA are loaded. When
237 * SMACK is enabled we need smackfs, too, so it's a fifth one. */
238 #if ENABLE_SMACK
239 #define N_EARLY_MOUNT 5
240 #else
241 #define N_EARLY_MOUNT 4
242 #endif
243
244 assert_cc(N_EARLY_MOUNT <= ELEMENTSOF(mount_table));
245
246 bool mount_point_is_api(const char *path) {
247 /* Checks if this mount point is considered "API", and hence
248 * should be ignored */
249
250 FOREACH_ELEMENT(i, mount_table)
251 if (path_equal(path, i->where))
252 return true;
253
254 return path_startswith(path, "/sys/fs/cgroup/");
255 }
256
257 bool mount_point_ignore(const char *path) {
258 /* These are API file systems that might be mounted by other software, we just list them here so that
259 * we know that we should ignore them. */
260 FOREACH_STRING(i,
261 /* SELinux file systems */
262 "/sys/fs/selinux",
263 /* Container bind mounts */
264 "/dev/console",
265 "/proc/kmsg",
266 "/proc/sys",
267 "/proc/sys/kernel/random/boot_id")
268 if (path_equal(path, i))
269 return true;
270
271 if (path_startswith(path, "/run/host")) /* All mounts passed in from the container manager are
272 * something we better ignore. */
273 return true;
274
275 return false;
276 }
277
278 static int mount_one(const MountPoint *p, bool relabel) {
279 int r, priority;
280
281 assert(p);
282 assert(p->what);
283 assert(p->where);
284 assert(p->type);
285
286 priority = FLAGS_SET(p->mode, MNT_FATAL) ? LOG_ERR : LOG_DEBUG;
287
288 if (p->condition_fn && !p->condition_fn())
289 return 0;
290
291 /* Relabel first, just in case */
292 if (relabel)
293 (void) label_fix(p->where, LABEL_IGNORE_ENOENT|LABEL_IGNORE_EROFS);
294
295 r = path_is_mount_point_full(p->where, /* root= */ NULL, AT_SYMLINK_FOLLOW);
296 if (r < 0 && r != -ENOENT) {
297 log_full_errno(priority, r, "Failed to determine whether %s is a mount point: %m", p->where);
298 return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
299 }
300 if (r > 0)
301 return 0;
302
303 if (!FLAGS_SET(p->mode, MNT_IN_CONTAINER) && detect_container() > 0)
304 return 0;
305
306 /* The access mode here doesn't really matter too much, since
307 * the mounted file system will take precedence anyway. */
308 if (relabel)
309 (void) mkdir_p_label(p->where, 0755);
310 else
311 (void) mkdir_p(p->where, 0755);
312
313 _cleanup_free_ char *extend_options = NULL;
314 const char *o;
315 if (p->options_fn) {
316 r = p->options_fn(priority, p->type, &extend_options);
317 if (r < 0)
318 return r;
319
320 if (!strprepend_with_separator(&extend_options, ",", p->options))
321 return log_oom();
322
323 o = extend_options;
324 } else
325 o = p->options;
326
327 r = mount_verbose_full(priority, p->what, p->where, p->type, p->flags, o, FLAGS_SET(p->mode, MNT_FOLLOW_SYMLINK));
328 if (r < 0)
329 return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
330
331 /* Relabel again, since we now mounted something fresh here */
332 if (relabel)
333 (void) label_fix(p->where, 0);
334
335 if (FLAGS_SET(p->mode, MNT_CHECK_WRITABLE))
336 if (access(p->where, W_OK) < 0) {
337 r = -errno;
338
339 (void) umount2(p->where, UMOUNT_NOFOLLOW);
340 (void) rmdir(p->where);
341
342 log_full_errno(priority, r, "Mount point '%s' not writable after mounting, undoing: %m", p->where);
343 return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
344 }
345
346 return 1;
347 }
348
349 static int mount_points_setup(size_t n, bool loaded_policy) {
350 int r = 0;
351
352 assert(n <= ELEMENTSOF(mount_table));
353
354 FOREACH_ARRAY(mp, mount_table, n)
355 RET_GATHER(r, mount_one(mp, loaded_policy));
356
357 return r;
358 }
359
360 int mount_setup_early(void) {
361 /* Do a minimal mount of /proc and friends to enable the most basic stuff, such as SELinux */
362 return mount_points_setup(N_EARLY_MOUNT, /* loaded_policy= */ false);
363 }
364
365 #if HAVE_SELINUX || ENABLE_SMACK
366 static int relabel_cb(
367 RecurseDirEvent event,
368 const char *path,
369 int dir_fd,
370 int inode_fd,
371 const struct dirent *de,
372 const struct statx *sx,
373 void *userdata) {
374
375 switch (event) {
376
377 case RECURSE_DIR_LEAVE:
378 case RECURSE_DIR_SKIP_MOUNT:
379 /* If we already saw this dirent when entering it or this is a dirent that on a different
380 * mount, don't relabel it. */
381 return RECURSE_DIR_CONTINUE;
382
383 case RECURSE_DIR_ENTER:
384 /* /run/initramfs/ + /run/nextroot/ are static data and big, no need to dynamically relabel
385 * its contents at boot... */
386 if (PATH_STARTSWITH_SET(path, "/run/initramfs", "/run/nextroot"))
387 return RECURSE_DIR_SKIP_ENTRY;
388
389 _fallthrough_;
390
391 default:
392 /* Otherwise, label it, even if we had trouble stat()ing it and similar. SELinux can figure this out */
393 (void) label_fix(path, 0);
394 return RECURSE_DIR_CONTINUE;
395 }
396 }
397
398 static int relabel_tree(const char *path) {
399 int r;
400
401 r = recurse_dir_at(AT_FDCWD, path, 0, UINT_MAX, RECURSE_DIR_ENSURE_TYPE|RECURSE_DIR_SAME_MOUNT, relabel_cb, NULL);
402 if (r < 0)
403 log_debug_errno(r, "Failed to recursively relabel '%s': %m", path);
404
405 return r;
406 }
407
408 static int relabel_extra(void) {
409 _cleanup_strv_free_ char **files = NULL;
410 int r, c = 0;
411
412 /* Support for relabelling additional files or directories after loading the policy. For this, code in the
413 * initrd simply has to drop in *.relabel files into /run/systemd/relabel-extra.d/. We'll read all such files
414 * expecting one absolute path by line and will relabel each (and everyone below that in case the path refers
415 * to a directory). These drop-in files are supposed to be absolutely minimal, and do not understand comments
416 * and such. After the operation succeeded the files are removed, and the drop-in directory as well, if
417 * possible.
418 */
419
420 r = conf_files_list(&files, ".relabel", NULL,
421 CONF_FILES_FILTER_MASKED | CONF_FILES_REGULAR | CONF_FILES_WARN,
422 "/run/systemd/relabel-extra.d/");
423 if (r < 0)
424 return log_error_errno(r, "Failed to enumerate /run/systemd/relabel-extra.d/, ignoring: %m");
425
426 STRV_FOREACH(file, files) {
427 _cleanup_fclose_ FILE *f = NULL;
428
429 f = fopen(*file, "re");
430 if (!f) {
431 log_warning_errno(errno, "Failed to open %s, ignoring: %m", *file);
432 continue;
433 }
434
435 for (;;) {
436 _cleanup_free_ char *line = NULL;
437
438 r = read_line(f, LONG_LINE_MAX, &line);
439 if (r < 0) {
440 log_warning_errno(r, "Failed to read %s, ignoring: %m", *file);
441 break;
442 }
443 if (r == 0) /* EOF */
444 break;
445
446 path_simplify(line);
447
448 if (!path_is_normalized(line)) {
449 log_warning("Path to relabel is not normalized, ignoring: %s", line);
450 continue;
451 }
452
453 if (!path_is_absolute(line)) {
454 log_warning("Path to relabel is not absolute, ignoring: %s", line);
455 continue;
456 }
457
458 log_debug("Relabelling additional file/directory '%s'.", line);
459 (void) label_fix(line, 0);
460 (void) relabel_tree(line);
461 c++;
462 }
463
464 if (unlink(*file) < 0)
465 log_warning_errno(errno, "Failed to remove %s, ignoring: %m", *file);
466 }
467
468 /* Remove when we complete things. */
469 if (rmdir("/run/systemd/relabel-extra.d") < 0 &&
470 errno != ENOENT)
471 log_warning_errno(errno, "Failed to remove /run/systemd/relabel-extra.d/ directory: %m");
472
473 return c;
474 }
475 #endif
476
477 int mount_setup(bool loaded_policy, bool leave_propagation) {
478 int r;
479
480 r = mount_points_setup(ELEMENTSOF(mount_table), loaded_policy);
481 if (r < 0)
482 return r;
483
484 #if HAVE_SELINUX || ENABLE_SMACK
485 /* Nodes in devtmpfs and /run need to be manually updated for
486 * the appropriate labels, after mounting. The other virtual
487 * API file systems like /sys and /proc do not need that, they
488 * use the same label for all their files. */
489 if (loaded_policy) {
490 usec_t before_relabel, after_relabel;
491 int n_extra;
492
493 before_relabel = now(CLOCK_MONOTONIC);
494
495 FOREACH_STRING(i, "/dev", "/dev/shm", "/run")
496 (void) relabel_tree(i);
497
498 n_extra = relabel_extra();
499
500 after_relabel = now(CLOCK_MONOTONIC);
501
502 log_info("Relabeled /dev/, /dev/shm/, /run/%s in %s.",
503 n_extra > 0 ? ", and additional files" : "",
504 FORMAT_TIMESPAN(after_relabel - before_relabel, 0));
505 }
506 #endif
507
508 /* Create a few default symlinks, which are normally created
509 * by udevd, but some scripts might need them before we start
510 * udevd. */
511 dev_setup(NULL, UID_INVALID, GID_INVALID);
512
513 /* Mark the root directory as shared in regards to mount propagation. The kernel defaults to "private", but we
514 * think it makes more sense to have a default of "shared" so that nspawn and the container tools work out of
515 * the box. If specific setups need other settings they can reset the propagation mode to private if
516 * needed. Note that we set this only when we are invoked directly by the kernel. If we are invoked by a
517 * container manager we assume the container manager knows what it is doing (for example, because it set up
518 * some directories with different propagation modes). */
519 if (detect_container() <= 0 && !leave_propagation)
520 if (mount(NULL, "/", NULL, MS_REC|MS_SHARED, NULL) < 0)
521 log_warning_errno(errno, "Failed to set up the root directory for shared mount propagation: %m");
522
523 /* Create a few directories we always want around, Note that sd_booted() checks for /run/systemd/system, so
524 * this mkdir really needs to stay for good, otherwise software that copied sd-daemon.c into their sources will
525 * misdetect systemd. */
526 (void) mkdir_label("/run/systemd", 0755);
527 (void) mkdir_label("/run/systemd/system", 0755);
528
529 /* Make sure there's always a place where sandboxed environments can mount root file systems they are
530 * about to move into, even when unprivileged, without having to create a temporary one in /tmp/
531 * (which they then have to keep track of and clean) */
532 (void) mkdir_label("/run/systemd/mount-rootfs", 0555);
533
534 /* Make sure we have a mount point to hide in sandboxes */
535 (void) mkdir_label("/run/credentials", 0755);
536
537 /* Also create /run/systemd/inaccessible nodes, so that we always have something to mount
538 * inaccessible nodes from. If we run in a container the host might have created these for us already
539 * in /run/host/inaccessible/. Use those if we can, since that way we likely get access to block/char
540 * device nodes that are inaccessible, and if userns is used to nodes that are on mounts owned by a
541 * userns outside the container and thus nicely read-only and not remountable. */
542 if (access("/run/host/inaccessible/", F_OK) < 0) {
543 if (errno != ENOENT)
544 log_debug_errno(errno, "Failed to check if /run/host/inaccessible exists, ignoring: %m");
545
546 (void) make_inaccessible_nodes("/run/systemd", UID_INVALID, GID_INVALID);
547 } else
548 (void) symlink("../host/inaccessible", "/run/systemd/inaccessible");
549
550 return 0;
551 }