• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 13912360373

17 Mar 2025 10:34PM UTC coverage: 71.946% (+0.03%) from 71.915%
13912360373

push

github

web-flow
nsresourced,vmspawn: allow unpriv "tap" based networking in vmspawn (#36688)

This extends nsresourced to also allow delegation of a network tap
device (in addition to veth) to unpriv clients, with a strictly enforced
naming scheme.

also tightens security on a couple of things:

* enforces polkit on all nsresourced ops too (though by default still
everything is allowed)
* put a limit on delegated network devices
* forcibly clean up delegated network devices when the userns goes away

145 of 375 new or added lines in 14 files covered. (38.67%)

2324 existing lines in 47 files now uncovered.

296268 of 411794 relevant lines covered (71.95%)

711485.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

48.61
/src/shared/mount-setup.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <errno.h>
4
#include <stdlib.h>
5
#include <sys/mount.h>
6
#include <sys/statvfs.h>
7
#include <unistd.h>
8

9
#include "alloc-util.h"
10
#include "bus-util.h"
11
#include "cgroup-setup.h"
12
#include "cgroup-util.h"
13
#include "conf-files.h"
14
#include "dev-setup.h"
15
#include "dirent-util.h"
16
#include "efi-loader.h"
17
#include "fd-util.h"
18
#include "fileio.h"
19
#include "fs-util.h"
20
#include "label-util.h"
21
#include "log.h"
22
#include "macro.h"
23
#include "mkdir-label.h"
24
#include "mount-setup.h"
25
#include "mount-util.h"
26
#include "mountpoint-util.h"
27
#include "nulstr-util.h"
28
#include "path-util.h"
29
#include "recurse-dir.h"
30
#include "set.h"
31
#include "smack-util.h"
32
#include "strv.h"
33
#include "user-util.h"
34
#include "virt.h"
35

36
typedef enum MountMode {
37
        MNT_NONE              = 0,
38
        MNT_FATAL             = 1 << 0,
39
        MNT_IN_CONTAINER      = 1 << 1,
40
        MNT_CHECK_WRITABLE    = 1 << 2,
41
        MNT_FOLLOW_SYMLINK    = 1 << 3,
42
        MNT_USRQUOTA_GRACEFUL = 1 << 4,
43
} MountMode;
44

45
typedef struct MountPoint {
46
        const char *what;
47
        const char *where;
48
        const char *type;
49
        const char *options;
50
        unsigned long flags;
51
        bool (*condition_fn)(void);
52
        MountMode mode;
53
} MountPoint;
54

55
bool cgroupfs_recursiveprot_supported(void) {
120✔
56
        int r;
120✔
57

58
        /* Added in kernel 5.7 */
59

60
        r = mount_option_supported("cgroup2", "memory_recursiveprot", /* value = */ NULL);
120✔
61
        if (r < 0)
120✔
UNCOV
62
                log_debug_errno(r, "Failed to determine whether cgroupfs supports 'memory_recursiveprot' mount option, assuming not: %m");
×
63
        else if (r == 0)
120✔
UNCOV
64
                log_debug("'memory_recursiveprot' not supported by cgroupfs, not using mount option.");
×
65

66
        return r > 0;
120✔
67
}
68

69
static const MountPoint mount_table[] = {
70
        { "proc",        "/proc",                     "proc",       NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
71
          NULL,          MNT_FATAL|MNT_IN_CONTAINER|MNT_FOLLOW_SYMLINK },
72
        { "sysfs",       "/sys",                      "sysfs",      NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
73
          NULL,          MNT_FATAL|MNT_IN_CONTAINER },
74
        { "devtmpfs",    "/dev",                      "devtmpfs",   "mode=0755" TMPFS_LIMITS_DEV,               MS_NOSUID|MS_STRICTATIME,
75
          NULL,          MNT_FATAL|MNT_IN_CONTAINER },
76
        { "securityfs",  "/sys/kernel/security",      "securityfs", NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
77
          NULL,          MNT_NONE                   },
78
#if ENABLE_SMACK
79
        { "smackfs",     "/sys/fs/smackfs",           "smackfs",    "smackfsdef=*",                             MS_NOSUID|MS_NOEXEC|MS_NODEV,
80
          mac_smack_use, MNT_FATAL                  },
81
        { "tmpfs",       "/dev/shm",                  "tmpfs",      "mode=01777,smackfsroot=*",                 MS_NOSUID|MS_NODEV|MS_STRICTATIME,
82
          mac_smack_use, MNT_FATAL|MNT_USRQUOTA_GRACEFUL },
83
#endif
84
        { "tmpfs",       "/dev/shm",                  "tmpfs",      "mode=01777",                               MS_NOSUID|MS_NODEV|MS_STRICTATIME,
85
          NULL,          MNT_FATAL|MNT_IN_CONTAINER|MNT_USRQUOTA_GRACEFUL },
86
        { "devpts",      "/dev/pts",                  "devpts",     "mode=" STRINGIFY(TTY_MODE) ",gid=" STRINGIFY(TTY_GID), MS_NOSUID|MS_NOEXEC,
87
          NULL,          MNT_IN_CONTAINER           },
88
#if ENABLE_SMACK
89
        { "tmpfs",       "/run",                      "tmpfs",      "mode=0755,smackfsroot=*" TMPFS_LIMITS_RUN, MS_NOSUID|MS_NODEV|MS_STRICTATIME,
90
          mac_smack_use, MNT_FATAL                  },
91
#endif
92
        { "tmpfs",       "/run",                      "tmpfs",      "mode=0755" TMPFS_LIMITS_RUN,               MS_NOSUID|MS_NODEV|MS_STRICTATIME,
93
          NULL,          MNT_FATAL|MNT_IN_CONTAINER },
94
        { "cgroup2",     "/sys/fs/cgroup",            "cgroup2",    "nsdelegate,memory_recursiveprot",          MS_NOSUID|MS_NOEXEC|MS_NODEV,
95
          cgroupfs_recursiveprot_supported, MNT_FATAL|MNT_IN_CONTAINER|MNT_CHECK_WRITABLE },
96
        { "cgroup2",     "/sys/fs/cgroup",            "cgroup2",    "nsdelegate",                               MS_NOSUID|MS_NOEXEC|MS_NODEV,
97
          NULL, MNT_FATAL|MNT_IN_CONTAINER|MNT_CHECK_WRITABLE },
98
#if ENABLE_PSTORE
99
        { "pstore",      "/sys/fs/pstore",            "pstore",     NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
100
          NULL,          MNT_NONE                   },
101
#endif
102
#if ENABLE_EFI
103
        { "efivarfs",    "/sys/firmware/efi/efivars", "efivarfs",   NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
104
          is_efi_boot,   MNT_NONE                   },
105
#endif
106
        { "bpf",         "/sys/fs/bpf",               "bpf",        "mode=0700",                                MS_NOSUID|MS_NOEXEC|MS_NODEV,
107
          NULL,          MNT_NONE,                  },
108
};
109

110
/* The first three entries we might need before SELinux is up. The
111
 * fourth (securityfs) is needed by IMA to load a custom policy. The
112
 * other ones we can delay until SELinux and IMA are loaded. When
113
 * SMACK is enabled we need smackfs, too, so it's a fifth one. */
114
#if ENABLE_SMACK
115
#define N_EARLY_MOUNT 5
116
#else
117
#define N_EARLY_MOUNT 4
118
#endif
119

120
assert_cc(N_EARLY_MOUNT <= ELEMENTSOF(mount_table));
121

122
bool mount_point_is_api(const char *path) {
109,719✔
123
        /* Checks if this mount point is considered "API", and hence
124
         * should be ignored */
125

126
        FOREACH_ELEMENT(i, mount_table)
1,472,828✔
127
                if (path_equal(path, i->where))
1,394,108✔
128
                        return true;
129

130
        return path_startswith(path, "/sys/fs/cgroup/");
78,720✔
131
}
132

133
bool mount_point_ignore(const char *path) {
78,708✔
134
        /* These are API file systems that might be mounted by other software, we just list them here so that
135
         * we know that we should ignore them. */
136
        FOREACH_STRING(i,
464,492✔
137
                       /* SELinux file systems */
138
                       "/sys/fs/selinux",
139
                       /* Container bind mounts */
140
                       "/dev/console",
141
                       "/proc/kmsg",
142
                       "/proc/sys",
143
                       "/proc/sys/kernel/random/boot_id")
144
                if (path_equal(path, i))
390,216✔
145
                        return true;
4,432✔
146

147
        if (path_startswith(path, "/run/host")) /* All mounts passed in from the container manager are
74,276✔
148
                                                 * something we better ignore. */
149
                return true;
6,648✔
150

151
        return false;
152
}
153

154
static int mount_one(const MountPoint *p, bool relabel) {
2,015✔
155
        int r, priority;
2,015✔
156

157
        assert(p);
2,015✔
158
        assert(p->what);
2,015✔
159
        assert(p->where);
2,015✔
160
        assert(p->type);
2,015✔
161

162
        priority = FLAGS_SET(p->mode, MNT_FATAL) ? LOG_ERR : LOG_DEBUG;
2,015✔
163

164
        if (p->condition_fn && !p->condition_fn())
2,015✔
165
                return 0;
2,015✔
166

167
        /* Relabel first, just in case */
168
        if (relabel)
1,511✔
UNCOV
169
                (void) label_fix(p->where, LABEL_IGNORE_ENOENT|LABEL_IGNORE_EROFS);
×
170

171
        r = path_is_mount_point_full(p->where, /* root = */ NULL, AT_SYMLINK_FOLLOW);
1,511✔
172
        if (r < 0 && r != -ENOENT) {
1,511✔
UNCOV
173
                log_full_errno(priority, r, "Failed to determine whether %s is a mount point: %m", p->where);
×
UNCOV
174
                return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
×
175
        }
176
        if (r > 0)
1,511✔
177
                return 0;
178

179
        if (!FLAGS_SET(p->mode, MNT_IN_CONTAINER) && detect_container() > 0)
738✔
180
                return 0;
181

182
        /* The access mode here doesn't really matter too much, since
183
         * the mounted file system will take precedence anyway. */
184
        if (relabel)
618✔
UNCOV
185
                (void) mkdir_p_label(p->where, 0755);
×
186
        else
187
                (void) mkdir_p(p->where, 0755);
618✔
188

189
        _cleanup_free_ char *extend_options = NULL;
618✔
190
        const char *o = p->options;
618✔
191
        if (FLAGS_SET(p->mode, MNT_USRQUOTA_GRACEFUL)) {
618✔
192
                r = mount_option_supported(p->type, "usrquota", /* value= */ NULL);
61✔
193
                if (r < 0)
61✔
UNCOV
194
                        log_full_errno(priority, r, "Unable to determine whether %s supports 'usrquota' mount option, assuming not: %m", p->type);
×
195
                else if (r == 0)
61✔
UNCOV
196
                        log_debug("Not enabling 'usrquota' on '%s' as kernel lacks support for it.", p->where);
×
197
                else {
198
                        if (!strextend_with_separator(&extend_options, ",", p->options ?: POINTER_MAX, "usrquota"))
122✔
199
                                return log_oom();
×
200

201
                        o = extend_options;
61✔
202
                }
203
        }
204

205
        log_debug("Mounting %s to %s of type %s with options %s.",
992✔
206
                  p->what,
207
                  p->where,
208
                  p->type,
209
                  strna(o));
210

211
        r = mount_verbose_full(priority, p->what, p->where, p->type, p->flags, o, FLAGS_SET(p->mode, MNT_FOLLOW_SYMLINK));
618✔
212
        if (r < 0)
618✔
UNCOV
213
                return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
×
214

215
        /* Relabel again, since we now mounted something fresh here */
216
        if (relabel)
618✔
UNCOV
217
                (void) label_fix(p->where, 0);
×
218

219
        if (FLAGS_SET(p->mode, MNT_CHECK_WRITABLE))
618✔
220
                if (access(p->where, W_OK) < 0) {
61✔
UNCOV
221
                        r = -errno;
×
222

UNCOV
223
                        (void) umount2(p->where, UMOUNT_NOFOLLOW);
×
224
                        (void) rmdir(p->where);
×
225

226
                        log_full_errno(priority, r, "Mount point '%s' not writable after mounting, undoing: %m", p->where);
×
227
                        return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
×
228
                }
229

230
        return 1;
231
}
232

233
static int mount_points_setup(size_t n, bool loaded_policy) {
179✔
234
        int r = 0;
179✔
235

236
        assert(n <= ELEMENTSOF(mount_table));
179✔
237

238
        FOREACH_ARRAY(mp, mount_table, n)
2,194✔
239
                RET_GATHER(r, mount_one(mp, loaded_policy));
2,015✔
240

241
        return r;
179✔
242
}
243

244
int mount_setup_early(void) {
67✔
245
        /* Do a minimal mount of /proc and friends to enable the most basic stuff, such as SELinux */
246
        return mount_points_setup(N_EARLY_MOUNT, /* loaded_policy= */ false);
67✔
247
}
248

249
#if HAVE_SELINUX || ENABLE_SMACK
UNCOV
250
static int relabel_cb(
×
251
                RecurseDirEvent event,
252
                const char *path,
253
                int dir_fd,
254
                int inode_fd,
255
                const struct dirent *de,
256
                const struct statx *sx,
257
                void *userdata) {
258

UNCOV
259
        switch (event) {
×
260

261
        case RECURSE_DIR_LEAVE:
262
        case RECURSE_DIR_SKIP_MOUNT:
263
                /* If we already saw this dirent when entering it or this is a dirent that on a different
264
                 * mount, don't relabel it. */
265
                return RECURSE_DIR_CONTINUE;
266

267
        case RECURSE_DIR_ENTER:
×
268
                /* /run/initramfs/ + /run/nextroot/ are static data and big, no need to dynamically relabel
269
                 * its contents at boot... */
UNCOV
270
                if (PATH_STARTSWITH_SET(path, "/run/initramfs", "/run/nextroot"))
×
UNCOV
271
                        return RECURSE_DIR_SKIP_ENTRY;
×
272

UNCOV
273
                _fallthrough_;
×
274

275
        default:
276
                /* Otherwise, label it, even if we had trouble stat()ing it and similar. SELinux can figure this out */
277
                (void) label_fix(path, 0);
×
278
                return RECURSE_DIR_CONTINUE;
×
279
        }
280
}
281

UNCOV
282
static int relabel_tree(const char *path) {
×
283
        int r;
×
284

285
        r = recurse_dir_at(AT_FDCWD, path, 0, UINT_MAX, RECURSE_DIR_ENSURE_TYPE|RECURSE_DIR_SAME_MOUNT, relabel_cb, NULL);
×
286
        if (r < 0)
×
287
                log_debug_errno(r, "Failed to recursively relabel '%s': %m", path);
×
288

UNCOV
289
        return r;
×
290
}
291

UNCOV
292
static int relabel_extra(void) {
×
UNCOV
293
        _cleanup_strv_free_ char **files = NULL;
×
UNCOV
294
        int r, c = 0;
×
295

296
        /* Support for relabelling additional files or directories after loading the policy. For this, code in the
297
         * initrd simply has to drop in *.relabel files into /run/systemd/relabel-extra.d/. We'll read all such files
298
         * expecting one absolute path by line and will relabel each (and everyone below that in case the path refers
299
         * to a directory). These drop-in files are supposed to be absolutely minimal, and do not understand comments
300
         * and such. After the operation succeeded the files are removed, and the drop-in directory as well, if
301
         * possible.
302
         */
303

UNCOV
304
        r = conf_files_list(&files, ".relabel", NULL,
×
305
                            CONF_FILES_FILTER_MASKED | CONF_FILES_REGULAR,
306
                            "/run/systemd/relabel-extra.d/");
UNCOV
307
        if (r < 0)
×
UNCOV
308
                return log_error_errno(r, "Failed to enumerate /run/systemd/relabel-extra.d/, ignoring: %m");
×
309

UNCOV
310
        STRV_FOREACH(file, files) {
×
UNCOV
311
                _cleanup_fclose_ FILE *f = NULL;
×
312

UNCOV
313
                f = fopen(*file, "re");
×
UNCOV
314
                if (!f) {
×
UNCOV
315
                        log_warning_errno(errno, "Failed to open %s, ignoring: %m", *file);
×
UNCOV
316
                        continue;
×
317
                }
318

UNCOV
319
                for (;;) {
×
320
                        _cleanup_free_ char *line = NULL;
×
321

UNCOV
322
                        r = read_line(f, LONG_LINE_MAX, &line);
×
323
                        if (r < 0) {
×
324
                                log_warning_errno(r, "Failed to read %s, ignoring: %m", *file);
×
325
                                break;
326
                        }
UNCOV
327
                        if (r == 0) /* EOF */
×
328
                                break;
329

330
                        path_simplify(line);
×
331

UNCOV
332
                        if (!path_is_normalized(line)) {
×
UNCOV
333
                                log_warning("Path to relabel is not normalized, ignoring: %s", line);
×
UNCOV
334
                                continue;
×
335
                        }
336

UNCOV
337
                        if (!path_is_absolute(line)) {
×
338
                                log_warning("Path to relabel is not absolute, ignoring: %s", line);
×
339
                                continue;
×
340
                        }
341

342
                        log_debug("Relabelling additional file/directory '%s'.", line);
×
UNCOV
343
                        (void) label_fix(line, 0);
×
UNCOV
344
                        (void) relabel_tree(line);
×
345
                        c++;
×
346
                }
347

UNCOV
348
                if (unlink(*file) < 0)
×
UNCOV
349
                        log_warning_errno(errno, "Failed to remove %s, ignoring: %m", *file);
×
350
        }
351

352
        /* Remove when we complete things. */
UNCOV
353
        if (rmdir("/run/systemd/relabel-extra.d") < 0 &&
×
UNCOV
354
            errno != ENOENT)
×
UNCOV
355
                log_warning_errno(errno, "Failed to remove /run/systemd/relabel-extra.d/ directory: %m");
×
356

357
        return c;
358
}
359
#endif
360

361
int mount_setup(bool loaded_policy, bool leave_propagation) {
112✔
362
        int r;
112✔
363

364
        r = mount_points_setup(ELEMENTSOF(mount_table), loaded_policy);
112✔
365
        if (r < 0)
112✔
366
                return r;
367

368
#if HAVE_SELINUX || ENABLE_SMACK
369
        /* Nodes in devtmpfs and /run need to be manually updated for
370
         * the appropriate labels, after mounting. The other virtual
371
         * API file systems like /sys and /proc do not need that, they
372
         * use the same label for all their files. */
373
        if (loaded_policy) {
112✔
UNCOV
374
                usec_t before_relabel, after_relabel;
×
375
                int n_extra;
×
376

377
                before_relabel = now(CLOCK_MONOTONIC);
×
378

UNCOV
379
                FOREACH_STRING(i, "/dev", "/dev/shm", "/run")
×
380
                        (void) relabel_tree(i);
×
381

UNCOV
382
                n_extra = relabel_extra();
×
383

UNCOV
384
                after_relabel = now(CLOCK_MONOTONIC);
×
385

386
                log_info("Relabeled /dev/, /dev/shm/, /run/%s in %s.",
×
387
                         n_extra > 0 ? ", and additional files" : "",
388
                         FORMAT_TIMESPAN(after_relabel - before_relabel, 0));
389
        }
390
#endif
391

392
        /* Create a few default symlinks, which are normally created
393
         * by udevd, but some scripts might need them before we start
394
         * udevd. */
395
        dev_setup(NULL, UID_INVALID, GID_INVALID);
112✔
396

397
        /* Mark the root directory as shared in regards to mount propagation. The kernel defaults to "private", but we
398
         * think it makes more sense to have a default of "shared" so that nspawn and the container tools work out of
399
         * the box. If specific setups need other settings they can reset the propagation mode to private if
400
         * needed. Note that we set this only when we are invoked directly by the kernel. If we are invoked by a
401
         * container manager we assume the container manager knows what it is doing (for example, because it set up
402
         * some directories with different propagation modes). */
403
        if (detect_container() <= 0 && !leave_propagation)
112✔
404
                if (mount(NULL, "/", NULL, MS_REC|MS_SHARED, NULL) < 0)
67✔
UNCOV
405
                        log_warning_errno(errno, "Failed to set up the root directory for shared mount propagation: %m");
×
406

407
        /* Create a few directories we always want around, Note that sd_booted() checks for /run/systemd/system, so
408
         * this mkdir really needs to stay for good, otherwise software that copied sd-daemon.c into their sources will
409
         * misdetect systemd. */
410
        (void) mkdir_label("/run/systemd", 0755);
112✔
411
        (void) mkdir_label("/run/systemd/system", 0755);
112✔
412

413
        /* Make sure there's always a place where sandboxed environments can mount root file systems they are
414
         * about to move into, even when unprivileged, without having to create a temporary one in /tmp/
415
         * (which they then have to keep track of and clean) */
416
        (void) mkdir_label("/run/systemd/mount-rootfs", 0555);
112✔
417

418
        /* Make sure we have a mount point to hide in sandboxes */
419
        (void) mkdir_label("/run/credentials", 0755);
112✔
420

421
        /* Also create /run/systemd/inaccessible nodes, so that we always have something to mount
422
         * inaccessible nodes from. If we run in a container the host might have created these for us already
423
         * in /run/host/inaccessible/. Use those if we can, since that way we likely get access to block/char
424
         * device nodes that are inaccessible, and if userns is used to nodes that are on mounts owned by a
425
         * userns outside the container and thus nicely read-only and not remountable. */
426
        if (access("/run/host/inaccessible/", F_OK) < 0) {
112✔
427
                if (errno != ENOENT)
72✔
428
                        log_debug_errno(errno, "Failed to check if /run/host/inaccessible exists, ignoring: %m");
×
429

430
                (void) make_inaccessible_nodes("/run/systemd", UID_INVALID, GID_INVALID);
72✔
431
        } else
432
                (void) symlink("../host/inaccessible", "/run/systemd/inaccessible");
40✔
433

434
        return 0;
435
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc