HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/namespace.c

173,584 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: dd15bda3ac6915b01bea339ebbd5f9b2ab083c7e

Lines 1–1000 of 4,291

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <linux/loop.h>
#include <linux/magic.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/file.h>
#include <sys/mount.h>
#include <unistd.h>
 
#include "alloc-util.h"
#include "base-filesystem.h"
#include "bitfield.h"
#include "chase.h"
#include "cryptsetup-util.h"
#include "dev-setup.h"
#include "devnum-util.h"
#include "dissect-image.h"
#include "errno-util.h"
#include "escape.h"
#include "extension-util.h"
#include "extract-word.h"
#include "fd-util.h"
#include "format-util.h"
#include "fs-util.h"
#include "glyph-util.h"
#include "iovec-util.h"
#include "label-util.h"
#include "lock-util.h"
#include "log.h"
#include "loop-util.h"
#include "loopback-setup.h"
#include "mkdir.h"
#include "mount-util.h"
#include "mountpoint-util.h"
#include "mstack.h"
#include "namespace.h"
#include "namespace-util.h"
#include "nsflags.h"
#include "nulstr-util.h"
#include "os-util.h"
#include "path-util.h"
#include "pidref.h"
#include "process-util.h"
#include "selinux-util.h"
#include "socket-util.h"
#include "sort-util.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "tmpfile-util.h"
#include "umask-util.h"
#include "user-util.h"
#include "vpick.h"
 
#define DEV_MOUNT_OPTIONS (MS_NOSUID|MS_STRICTATIME|MS_NOEXEC)
 
typedef enum MountMode {
        /* This is ordered by priority! */
        MOUNT_INACCESSIBLE,
        MOUNT_OVERLAY,
        MOUNT_IMAGE,
        MOUNT_BIND,
        MOUNT_BIND_RECURSIVE,
        MOUNT_PRIVATE_TMP,
        MOUNT_PRIVATE_DEV,
        MOUNT_BIND_DEV,
        MOUNT_EMPTY_DIR,
        MOUNT_PRIVATE_SYSFS,
        MOUNT_BIND_SYSFS,
        MOUNT_PROCFS,
        MOUNT_PRIVATE_CGROUP2FS,
        MOUNT_READ_ONLY,
        MOUNT_READ_WRITE,
        MOUNT_NOEXEC,
        MOUNT_EXEC,
        MOUNT_TMPFS,
        MOUNT_RUN,
        MOUNT_PRIVATE_TMPFS,       /* Mounted outside the root directory, and used by subsequent mounts */
        MOUNT_EXTENSION_DIRECTORY, /* Bind-mounted outside the root directory, and used by subsequent mounts */
        MOUNT_EXTENSION_IMAGE,     /* Mounted outside the root directory, and used by subsequent mounts */
        MOUNT_MQUEUEFS,
        MOUNT_READ_WRITE_IMPLICIT, /* Should have the lowest priority. */
        MOUNT_BPFFS,               /* Special mount for bpffs, which is mounted with fsmount() and move_mount() */
        _MOUNT_MODE_MAX,
        _MOUNT_MODE_INVALID = -EINVAL,
} MountMode;
 
typedef enum MountEntryState {
        MOUNT_PENDING,
        MOUNT_APPLIED,
        MOUNT_SKIPPED,
        _MOUNT_ENTRY_STATE_MAX,
        _MOUNT_ENTRY_STATE_INVALID = -EINVAL,
} MountEntryState;
 
typedef struct MountEntry {
        const char *path_const;   /* Memory allocated on stack or static */
        MountMode mode;
        bool ignore:1;            /* Ignore if path does not exist? */
        bool has_prefix:1;        /* Already prefixed by the root dir? */
        bool read_only:1;         /* Shall this mount point be read-only? */
        bool nosuid:1;            /* Shall set MS_NOSUID on the mount itself */
        bool noexec:1;            /* Shall set MS_NOEXEC on the mount itself */
        bool exec:1;              /* Shall clear MS_NOEXEC on the mount itself */
        bool create_source_dir:1; /* Create the source directory if it doesn't exist - for implicit bind mounts */
        mode_t source_dir_mode;   /* Mode for the source directory, if it is to be created */
        MountEntryState state;    /* Whether it was already processed or skipped */
        char *path_malloc;        /* Use this instead of 'path_const' if we had to allocate memory */
        const char *unprefixed_path_const; /* If the path was amended with a prefix, these will save the original */
        char *unprefixed_path_malloc;
        const char *source_const; /* The source path, for bind mounts or images */
        char *source_malloc;
        const char *options_const;/* Mount options for tmpfs */
        char *options_malloc;
        unsigned long flags;      /* Mount flags used by EMPTY_DIR and TMPFS. Do not include MS_RDONLY here, but please use read_only. */
        unsigned n_followed;
        MountOptions *image_options_const;
        char **overlay_layers;
        VeritySettings verity;
        ImageClass filter_class; /* Used for live updates to skip inapplicable images */
        bool idmapped;
        uid_t idmap_uid;
        gid_t idmap_gid;
} MountEntry;
 
typedef struct MountList {
        MountEntry *mounts;
        size_t n_mounts;
} MountList;
 
static const BindMount bind_log_sockets_table[] = {
        { (char*) "/run/systemd/journal/socket",  (char*) "/run/systemd/journal/socket",  .read_only = true, .nosuid = true, .noexec = true, .nodev = true, .ignore_enoent = true },
        { (char*) "/run/systemd/journal/stdout",  (char*) "/run/systemd/journal/stdout",  .read_only = true, .nosuid = true, .noexec = true, .nodev = true, .ignore_enoent = true },
        { (char*) "/run/systemd/journal/dev-log", (char*) "/run/systemd/journal/dev-log", .read_only = true, .nosuid = true, .noexec = true, .nodev = true, .ignore_enoent = true },
};
 
/* If MountAPIVFS= is used, let's mount /proc/, /dev/, /sys/, and /run/, but only as a fallback if the user
 * hasn't mounted something already. These mounts are hence overridden by any other explicitly configured
 * mounts. */
static const MountEntry apivfs_table[] = {
        { "/proc",               MOUNT_PROCFS,       false },
        { "/dev",                MOUNT_BIND_DEV,     false },
        { "/sys",                MOUNT_BIND_SYSFS,   false },
        { "/run",                MOUNT_RUN,          false, .options_const = "mode=0755" TMPFS_LIMITS_RUN, .flags = MS_NOSUID|MS_NODEV|MS_STRICTATIME },
};
 
/* ProtectKernelTunables= option and the related filesystem APIs */
static const MountEntry protect_kernel_tunables_proc_table[] = {
        { "/proc/acpi",          MOUNT_READ_ONLY,           true  },
        { "/proc/apm",           MOUNT_READ_ONLY,           true  }, /* Obsolete API, there's no point in permitting access to this, ever */
        { "/proc/asound",        MOUNT_READ_ONLY,           true  },
        { "/proc/bus",           MOUNT_READ_ONLY,           true  },
        { "/proc/fs",            MOUNT_READ_ONLY,           true  },
        { "/proc/irq",           MOUNT_READ_ONLY,           true  },
        { "/proc/kallsyms",      MOUNT_INACCESSIBLE,        true  },
        { "/proc/kcore",         MOUNT_INACCESSIBLE,        true  },
        { "/proc/latency_stats", MOUNT_READ_ONLY,           true  },
        { "/proc/mtrr",          MOUNT_READ_ONLY,           true  },
        { "/proc/scsi",          MOUNT_READ_ONLY,           true  },
        { "/proc/sys",           MOUNT_READ_ONLY,           true  },
        { "/proc/sysrq-trigger", MOUNT_READ_ONLY,           true  },
        { "/proc/timer_stats",   MOUNT_READ_ONLY,           true  },
};
 
static const MountEntry protect_kernel_tunables_sys_table[] = {
        { "/sys",                MOUNT_READ_ONLY,           false },
        { "/sys/fs/cgroup",      MOUNT_READ_WRITE_IMPLICIT, false }, /* READ_ONLY is set by ProtectControlGroups= option */
        { "/sys/fs/selinux",     MOUNT_READ_WRITE_IMPLICIT, true  },
        { "/sys/kernel/debug",   MOUNT_READ_ONLY,           true  },
        { "/sys/kernel/tracing", MOUNT_READ_ONLY,           true  },
};
 
/* PrivateBPF= option */
static const MountEntry private_bpf_no_table[] = {
        { "/sys/fs/bpf",         MOUNT_READ_ONLY,    true  },
};
 
/* ProtectKernelModules= option */
static const MountEntry protect_kernel_modules_table[] = {
        { "/usr/lib/modules",    MOUNT_INACCESSIBLE, true  },
};
 
/* ProtectKernelLogs= option */
static const MountEntry protect_kernel_logs_proc_table[] = {
        { "/proc/kmsg",          MOUNT_INACCESSIBLE, true },
};
 
static const MountEntry protect_kernel_logs_dev_table[] = {
        { "/dev/kmsg",           MOUNT_INACCESSIBLE, true },
};
 
/*
 * ProtectHome=read-only. Protect $HOME and $XDG_RUNTIME_DIR and rest of
 * system should be protected by ProtectSystem=.
 */
static const MountEntry protect_home_read_only_table[] = {
        { "/home",               MOUNT_READ_ONLY,     true  },
        { "/run/user",           MOUNT_READ_ONLY,     true  },
        { "/root",               MOUNT_READ_ONLY,     true  },
};
 
/* ProtectHome=tmpfs */
static const MountEntry protect_home_tmpfs_table[] = {
        { "/home",               MOUNT_TMPFS,        true, .read_only = true, .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
        { "/run/user",           MOUNT_TMPFS,        true, .read_only = true, .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
        { "/root",               MOUNT_TMPFS,        true, .read_only = true, .options_const = "mode=0700" TMPFS_LIMITS_EMPTY_OR_ALMOST, .flags = MS_NODEV|MS_STRICTATIME },
};
 
/* ProtectHome=yes */
static const MountEntry protect_home_yes_table[] = {
        { "/home",               MOUNT_INACCESSIBLE, true  },
        { "/run/user",           MOUNT_INACCESSIBLE, true  },
        { "/root",               MOUNT_INACCESSIBLE, true  },
};
 
/* ProtectControlGroups=yes */
static const MountEntry protect_control_groups_yes_table[] = {
        { "/sys/fs/cgroup",      MOUNT_READ_ONLY,         false  },
};
 
/* ProtectControlGroups=private. Note mount_private_apivfs() always use MS_NOSUID|MS_NOEXEC|MS_NODEV so
 * flags are not set here. */
static const MountEntry protect_control_groups_private_table[] = {
        { "/sys/fs/cgroup",      MOUNT_PRIVATE_CGROUP2FS, false, .read_only = false },
};
 
/* ProtectControlGroups=strict */
static const MountEntry protect_control_groups_strict_table[] = {
        { "/sys/fs/cgroup",      MOUNT_PRIVATE_CGROUP2FS, false, .read_only = true },
};
 
/* ProtectSystem=yes */
static const MountEntry protect_system_yes_table[] = {
        { "/usr",                MOUNT_READ_ONLY,     false },
        { "/boot",               MOUNT_READ_ONLY,     true  },
        { "/efi",                MOUNT_READ_ONLY,     true  },
};
 
/* ProtectSystem=full includes ProtectSystem=yes */
static const MountEntry protect_system_full_table[] = {
        { "/usr",                MOUNT_READ_ONLY,     false },
        { "/boot",               MOUNT_READ_ONLY,     true  },
        { "/efi",                MOUNT_READ_ONLY,     true  },
        { "/etc",                MOUNT_READ_ONLY,     false },
};
 
/* ProtectSystem=strict. In this strict mode, we mount everything read-only, except for /proc, /dev, and
 * /sys which are the kernel API VFS and left writable. PrivateDevices= + ProtectKernelTunables=
 * protect those, and these options should be fully orthogonal. (And of course /home and friends are also
 * left writable, as ProtectHome= shall manage those, orthogonally).
 */
static const MountEntry protect_system_strict_table[] = {
        { "/",                   MOUNT_READ_ONLY,           false },
        { "/proc",               MOUNT_READ_WRITE_IMPLICIT, false },      /* ProtectKernelTunables= */
        { "/sys",                MOUNT_READ_WRITE_IMPLICIT, false },      /* ProtectKernelTunables= */
        { "/dev",                MOUNT_READ_WRITE_IMPLICIT, false },      /* PrivateDevices= */
        { "/home",               MOUNT_READ_WRITE_IMPLICIT, true  },      /* ProtectHome= */
        { "/run/user",           MOUNT_READ_WRITE_IMPLICIT, true  },      /* ProtectHome= */
        { "/root",               MOUNT_READ_WRITE_IMPLICIT, true  },      /* ProtectHome= */
};
 
/* ProtectHostname=yes */
static const MountEntry protect_hostname_yes_table[] = {
        { "/proc/sys/kernel/hostname",   MOUNT_READ_ONLY, false },
        { "/proc/sys/kernel/domainname", MOUNT_READ_ONLY, false },
};
 
static const char * const mount_mode_table[_MOUNT_MODE_MAX] = {
        [MOUNT_INACCESSIBLE]          = "inaccessible",
        [MOUNT_OVERLAY]               = "overlay",
        [MOUNT_IMAGE]                 = "image",
        [MOUNT_BIND]                  = "bind",
        [MOUNT_BIND_RECURSIVE]        = "bind-recursive",
        [MOUNT_PRIVATE_TMP]           = "private-tmp",
        [MOUNT_PRIVATE_DEV]           = "private-dev",
        [MOUNT_BIND_DEV]              = "bind-dev",
        [MOUNT_EMPTY_DIR]             = "empty-dir",
        [MOUNT_PRIVATE_SYSFS]         = "private-sysfs",
        [MOUNT_BIND_SYSFS]            = "bind-sysfs",
        [MOUNT_PRIVATE_CGROUP2FS]     = "private-cgroup2fs",
        [MOUNT_PROCFS]                = "procfs",
        [MOUNT_READ_ONLY]             = "read-only",
        [MOUNT_READ_WRITE]            = "read-write",
        [MOUNT_NOEXEC]                = "noexec",
        [MOUNT_EXEC]                  = "exec",
        [MOUNT_TMPFS]                 = "tmpfs",
        [MOUNT_RUN]                   = "run",
        [MOUNT_PRIVATE_TMPFS]         = "private-tmpfs",
        [MOUNT_EXTENSION_DIRECTORY]   = "extension-directory",
        [MOUNT_EXTENSION_IMAGE]       = "extension-image",
        [MOUNT_MQUEUEFS]              = "mqueuefs",
        [MOUNT_READ_WRITE_IMPLICIT]   = "read-write-implicit",
};
 
/* Helper struct for naming simplicity and reusability */
static const struct {
        const char *level_env;
        const char *level_env_print;
} image_class_info[_IMAGE_CLASS_MAX] = {
        [IMAGE_SYSEXT] = {
                .level_env = "SYSEXT_LEVEL",
                .level_env_print = " SYSEXT_LEVEL=",
        },
        [IMAGE_CONFEXT] = {
                .level_env = "CONFEXT_LEVEL",
                .level_env_print = " CONFEXT_LEVEL=",
        }
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(mount_mode, MountMode);
 
static const char* mount_entry_path(const MountEntry *p) {
        assert(p);
 
        /* Returns the path of this bind mount. If the malloc()-allocated ->path_buffer field is set we return that,
         * otherwise the stack/static ->path field is returned. */
 
        return p->path_malloc ?: p->path_const;
}
 
static const char* mount_entry_unprefixed_path(const MountEntry *p) {
        assert(p);
 
        /* Returns the unprefixed path (ie: before prefix_where_needed() ran), if any */
 
        return p->unprefixed_path_malloc ?: p->unprefixed_path_const ?: mount_entry_path(p);
}
 
static void mount_entry_consume_prefix(MountEntry *p, char *new_path) {
        assert(p);
        assert(p->path_malloc || p->path_const);
        assert(new_path);
 
        /* Saves current path in unprefixed_ variable, and takes over new_path */
 
        free_and_replace(p->unprefixed_path_malloc, p->path_malloc);
        /* If we didn't have a path on the heap, then it's a static one */
        if (!p->unprefixed_path_malloc)
                p->unprefixed_path_const = p->path_const;
        p->path_malloc = new_path;
        p->has_prefix = true;
}
 
static bool mount_entry_read_only(const MountEntry *p) {
        assert(p);
 
        return p->read_only || IN_SET(p->mode, MOUNT_READ_ONLY, MOUNT_INACCESSIBLE);
}
 
static bool mount_entry_noexec(const MountEntry *p) {
        assert(p);
 
        return p->noexec || IN_SET(p->mode, MOUNT_NOEXEC, MOUNT_INACCESSIBLE, MOUNT_PRIVATE_SYSFS, MOUNT_BIND_SYSFS, MOUNT_PROCFS, MOUNT_PRIVATE_CGROUP2FS);
}
 
static bool mount_entry_exec(const MountEntry *p) {
        assert(p);
 
        return p->exec || p->mode == MOUNT_EXEC;
}
 
static const char* mount_entry_source(const MountEntry *p) {
        assert(p);
 
        return p->source_malloc ?: p->source_const;
}
 
static const char* mount_entry_options(const MountEntry *p) {
        assert(p);
 
        return p->options_malloc ?: p->options_const;
}
 
static void mount_entry_done(MountEntry *p) {
        assert(p);
 
        p->path_malloc = mfree(p->path_malloc);
        p->unprefixed_path_malloc = mfree(p->unprefixed_path_malloc);
        p->source_malloc = mfree(p->source_malloc);
        p->options_malloc = mfree(p->options_malloc);
        p->overlay_layers = strv_free(p->overlay_layers);
        verity_settings_done(&p->verity);
}
 
static void mount_list_done(MountList *ml) {
        assert(ml);
 
        FOREACH_ARRAY(m, ml->mounts, ml->n_mounts)
                mount_entry_done(m);
 
        ml->mounts = mfree(ml->mounts);
        ml->n_mounts = 0;
}
 
static MountEntry* mount_list_extend(MountList *ml) {
        assert(ml);
 
        if (!GREEDY_REALLOC0(ml->mounts, ml->n_mounts+1))
                return NULL;
 
        return ml->mounts + ml->n_mounts++;
}
 
static int append_access_mounts(MountList *ml, char **strv, MountMode mode, bool forcibly_require_prefix) {
        assert(ml);
 
        /* Adds a list of user-supplied READ_WRITE/READ_WRITE_IMPLICIT/READ_ONLY/INACCESSIBLE entries */
 
        STRV_FOREACH(i, strv) {
                bool ignore = false, needs_prefix = false;
                const char *e = *i;
 
                /* Look for any prefixes */
                if (startswith(e, "-")) {
                        e++;
                        ignore = true;
                }
                if (startswith(e, "+")) {
                        e++;
                        needs_prefix = true;
                }
 
                if (!path_is_absolute(e))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not absolute: %s", e);
 
                MountEntry *me = mount_list_extend(ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = e,
                        .mode = mode,
                        .ignore = ignore,
                        .has_prefix = !needs_prefix && !forcibly_require_prefix,
                };
        }
 
        return 0;
}
 
static int append_empty_dir_mounts(MountList *ml, char **strv) {
        assert(ml);
 
        /* Adds tmpfs mounts to provide readable but empty directories. This is primarily used to implement the
         * "/private/" boundary directories for DynamicUser=1. */
 
        STRV_FOREACH(i, strv) {
                MountEntry *me = mount_list_extend(ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = *i,
                        .mode = MOUNT_EMPTY_DIR,
                        .ignore = false,
                        .read_only = true,
                        .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST,
                        .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME,
                };
        }
 
        return 0;
}
 
static int append_bind_mounts(MountList *ml, const BindMount *binds, size_t n) {
        assert(ml);
        assert(binds || n == 0);
 
        FOREACH_ARRAY(b, binds, n) {
                MountEntry *me = mount_list_extend(ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = b->destination,
                        .mode = b->recursive ? MOUNT_BIND_RECURSIVE : MOUNT_BIND,
                        .read_only = b->read_only,
                        .nosuid = b->nosuid,
                        .noexec = b->noexec,
                        .flags = b->nodev ? MS_NODEV : 0,
                        .source_const = b->source,
                        .ignore = b->ignore_enoent,
                        .idmapped = b->idmapped,
                        .idmap_uid = b->uid,
                        .idmap_gid = b->gid,
                };
        }
 
        return 0;
}
 
static int append_mount_images(MountList *ml, const MountImage *mount_images, size_t n) {
        int r;
 
        assert(ml);
        assert(mount_images || n == 0);
 
        FOREACH_ARRAY(m, mount_images, n) {
                _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
                MountEntry *me = mount_list_extend(ml);
                if (!me)
                        return log_oom_debug();
 
                r = verity_settings_load(&verity, m->source, /* root_hash_path= */ NULL, /* root_hash_sig_path= */ NULL);
                if (r < 0)
                        return log_debug_errno(r, "Failed to check verity root hash of %s: %m", m->source);
 
                *me = (MountEntry) {
                        .path_const = m->destination,
                        .mode = MOUNT_IMAGE,
                        .source_const = m->source,
                        .image_options_const = m->mount_options,
                        .ignore = m->ignore_enoent,
                        .verity = TAKE_GENERIC(verity, VeritySettings, VERITY_SETTINGS_DEFAULT),
                        .filter_class = _IMAGE_CLASS_INVALID,
                };
        }
 
        return 0;
}
 
static int append_extensions(
                MountList *ml,
                const char *root,
                const char *private_namespace_dir,
                char **hierarchies,
                const MountImage *mount_images,
                size_t n_mount_images,
                char **extension_directories) {
 
        char ***overlays = NULL;
        size_t n_overlays = 0;
        int r;
 
        assert(ml);
 
        if (n_mount_images == 0 && strv_isempty(extension_directories))
                return 0;
 
        assert(private_namespace_dir);
 
        n_overlays = strv_length(hierarchies);
        if (n_overlays == 0)
                return 0;
 
        /* Prepare a list of overlays, that will have as each element a strv containing all the layers that
         * will later be concatenated as a lowerdir= parameter for the mount operation.
         * The overlays vector will have the same number of elements and will correspond to the
         * hierarchies vector, so they can be iterated upon together. */
        overlays = new0(char**, n_overlays);
        if (!overlays)
                return -ENOMEM;
 
        CLEANUP_ARRAY(overlays, n_overlays, strv_free_many);
 
        /* First, prepare a mount for each image, but these won't be visible to the unit, instead
         * they will be mounted in our propagate directory, and used as a source for the overlay. */
        for (size_t i = 0; i < n_mount_images; i++) {
                _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
                _cleanup_free_ char *mount_point = NULL;
                const MountImage *m = mount_images + i;
 
                r = path_pick(/* root_path= */ NULL,
                              /* root_fd= */ AT_FDCWD,
                              /* dir_fd= */ AT_FDCWD,
                              m->source,
                              pick_filter_image_raw,
                              ELEMENTSOF(pick_filter_image_raw),
                              PICK_ARCHITECTURE|PICK_TRIES,
                              &result);
                if (r == -ENOENT && m->ignore_enoent)
                        continue;
                if (r < 0)
                        return r;
                if (!result.path) {
                        if (m->ignore_enoent)
                                continue;
 
                        return log_debug_errno(
                                        SYNTHETIC_ERRNO(ENOENT),
                                        "No matching entry in .v/ directory %s found.",
                                        m->source);
                }
 
                r = verity_settings_load(&verity, result.path, /* root_hash_path= */ NULL, /* root_hash_sig_path= */ NULL);
                if (r < 0)
                        return log_debug_errno(r, "Failed to check verity root hash of %s: %m", result.path);
 
                if (asprintf(&mount_point, "%s/unit-extensions/%zu", private_namespace_dir, i) < 0)
                        return -ENOMEM;
 
                for (size_t j = 0; hierarchies && hierarchies[j]; ++j) {
                        char *prefixed_hierarchy = path_join(mount_point, hierarchies[j]);
                        if (!prefixed_hierarchy)
                                return -ENOMEM;
 
                        r = strv_consume(&overlays[j], TAKE_PTR(prefixed_hierarchy));
                        if (r < 0)
                                return r;
                }
 
                MountEntry *me = mount_list_extend(ml);
                if (!me)
                        return -ENOMEM;
 
                *me = (MountEntry) {
                        .path_malloc = TAKE_PTR(mount_point),
                        .image_options_const = m->mount_options,
                        .ignore = m->ignore_enoent,
                        .source_malloc = TAKE_PTR(result.path),
                        .mode = MOUNT_EXTENSION_IMAGE,
                        .has_prefix = true,
                        .verity = TAKE_GENERIC(verity, VeritySettings, VERITY_SETTINGS_DEFAULT),
                        .filter_class = _IMAGE_CLASS_INVALID,
                };
        }
 
        /* Secondly, extend the lowerdir= parameters with each ExtensionDirectory.
         * Bind mount them in the same location as the ExtensionImages, so that we
         * can check that they are valid trees (extension-release.d). */
        STRV_FOREACH(extension_directory, extension_directories) {
                _cleanup_(pick_result_done) PickResult result = PICK_RESULT_NULL;
                _cleanup_free_ char *mount_point = NULL;
                const char *e = *extension_directory;
                bool ignore_enoent = false;
 
                /* Look for any prefixes */
                if (startswith(e, "-")) {
                        e++;
                        ignore_enoent = true;
                }
                /* Ignore this for now */
                if (startswith(e, "+"))
                        e++;
 
                r = path_pick(/* root_path= */ NULL,
                              /* root_fd= */ AT_FDCWD,
                              /* dir_fd= */ AT_FDCWD,
                              e,
                              pick_filter_image_dir,
                              ELEMENTSOF(pick_filter_image_dir),
                              PICK_ARCHITECTURE|PICK_TRIES,
                              &result);
                if (r == -ENOENT && ignore_enoent)
                        continue;
                if (r < 0)
                        return r;
                if (!result.path) {
                        if (ignore_enoent)
                                continue;
 
                        return log_debug_errno(
                                        SYNTHETIC_ERRNO(ENOENT),
                                        "No matching entry in .v/ directory %s found.",
                                        e);
                }
 
                /* Pick up the counter where the ExtensionImages left it. */
                if (asprintf(&mount_point, "%s/unit-extensions/%zu", private_namespace_dir, n_mount_images++) < 0)
                        return -ENOMEM;
 
                for (size_t j = 0; hierarchies && hierarchies[j]; ++j) {
                        char *prefixed_hierarchy = path_join(mount_point, hierarchies[j]);
                        if (!prefixed_hierarchy)
                                return -ENOMEM;
 
                        r = strv_consume(&overlays[j], TAKE_PTR(prefixed_hierarchy));
                        if (r < 0)
                                return r;
                }
 
                MountEntry *me = mount_list_extend(ml);
                if (!me)
                        return -ENOMEM;
 
                *me = (MountEntry) {
                        .path_malloc = TAKE_PTR(mount_point),
                        .source_malloc = TAKE_PTR(result.path),
                        .mode = MOUNT_EXTENSION_DIRECTORY,
                        .ignore = ignore_enoent,
                        .has_prefix = true,
                        .read_only = true,
                        .filter_class = _IMAGE_CLASS_INVALID,
                };
        }
 
        /* Then, for each hierarchy, prepare an overlay with the list of lowerdir= strings
         * set up earlier. */
        for (size_t i = 0; hierarchies && hierarchies[i]; ++i) {
                _cleanup_free_ char *prefixed_hierarchy = NULL;
 
                prefixed_hierarchy = path_join(root, hierarchies[i]);
                if (!prefixed_hierarchy)
                        return -ENOMEM;
 
                MountEntry *me = mount_list_extend(ml);
                if (!me)
                        return -ENOMEM;
 
                *me = (MountEntry) {
                        .path_malloc = TAKE_PTR(prefixed_hierarchy),
                        .overlay_layers = TAKE_PTR(overlays[i]),
                        .mode = MOUNT_OVERLAY,
                        .has_prefix = true,
                        .ignore = true, /* If the source image doesn't set the ignore bit it will fail earlier. */
                };
        }
 
        return 0;
}
 
static int append_tmpfs_mounts(MountList *ml, const TemporaryFileSystem *tmpfs, size_t n) {
        assert(ml);
        assert(tmpfs || n == 0);
 
        FOREACH_ARRAY(t, tmpfs, n) {
                _cleanup_free_ char *o = NULL, *str = NULL;
                unsigned long flags;
                bool ro = false;
                int r;
 
                if (!path_is_absolute(t->path))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Path is not absolute: %s", t->path);
 
                str = strjoin("mode=0755" NESTED_TMPFS_LIMITS ",", t->options);
                if (!str)
                        return -ENOMEM;
 
                r = mount_option_mangle(str, MS_NODEV|MS_STRICTATIME, &flags, &o);
                if (r < 0)
                        return log_debug_errno(r, "Failed to parse mount option '%s': %m", str);
 
                ro = flags & MS_RDONLY;
                flags &= ~MS_RDONLY;
 
                MountEntry *me = mount_list_extend(ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = t->path,
                        .mode = MOUNT_TMPFS,
                        .read_only = ro,
                        .options_malloc = TAKE_PTR(o),
                        .flags = flags,
                };
        }
 
        return 0;
}
 
static int append_private_tmp_one(
                MountList *ml,
                PrivateTmp mode,
                const char *path,
                const char *connected_source) {
 
        assert(ml);
        assert(mode >= 0 && mode < _PRIVATE_TMP_MAX);
        assert(path);
 
        if (mode == PRIVATE_TMP_NO)
                return 0;
 
        if (mode == PRIVATE_TMP_CONNECTED && !connected_source)
                /* Do nothing if the private tmp dir was suppressed as it would be made inaccessible anyways
                 * (see exec_shared_runtime_make()). */
                return 0;
 
        MountEntry *me = mount_list_extend(ml);
        if (!me)
                return log_oom_debug();
 
        if (mode == PRIVATE_TMP_CONNECTED)
                *me = (MountEntry) {
                        .path_const = path,
                        .mode = MOUNT_PRIVATE_TMP,
                        .read_only = streq(connected_source, RUN_SYSTEMD_EMPTY),
                        .source_const = connected_source,
                };
        else
                *me = (MountEntry) {
                        .path_const = path,
                        .mode = MOUNT_PRIVATE_TMPFS,
                        .options_const = "mode=0700" NESTED_TMPFS_LIMITS,
                        .flags = MS_NODEV|MS_STRICTATIME,
                };
 
        return 0;
}
 
static int append_private_tmp(MountList *ml, const NamespaceParameters *p) {
        int r;
 
        assert(ml);
        assert(p);
        assert(p->private_tmp >= 0 && p->private_tmp < _PRIVATE_TMP_MAX);
        assert(p->private_var_tmp >= 0 && p->private_var_tmp < _PRIVATE_TMP_MAX);
 
        if (p->private_tmp != PRIVATE_TMP_DISCONNECTED || p->private_var_tmp != PRIVATE_TMP_DISCONNECTED) {
                r = append_private_tmp_one(ml, p->private_tmp, "/tmp/", p->tmp_dir);
                if (r < 0)
                        return r;
 
                r = append_private_tmp_one(ml, p->private_var_tmp, "/var/tmp/", p->var_tmp_dir);
                if (r < 0)
                        return r;
 
                return 0;
        }
 
        /* Fully disconnected private tmp: we mount a single tmpfs instance with two subdirs which are
         * bind mounted to /tmp/ and /var/tmp/. */
 
        MountEntry *me;
 
        _cleanup_free_ char *tmpfs_dir = NULL, *tmp_dir = NULL, *var_tmp_dir = NULL;
        tmpfs_dir = path_join(p->private_namespace_dir, "unit-private-tmp");
        tmp_dir = path_join(tmpfs_dir, "tmp");
        var_tmp_dir = path_join(tmpfs_dir, "var-tmp");
        if (!tmpfs_dir || !tmp_dir || !var_tmp_dir)
                return log_oom_debug();
 
        me = mount_list_extend(ml);
        if (!me)
                return log_oom_debug();
        *me = (MountEntry) {
                .path_malloc = TAKE_PTR(tmpfs_dir),
                .mode = MOUNT_PRIVATE_TMPFS,
                .options_const = "mode=0700" NESTED_TMPFS_LIMITS,
                .flags = MS_NODEV|MS_STRICTATIME,
                .has_prefix = true,
        };
 
        me = mount_list_extend(ml);
        if (!me)
                return log_oom_debug();
        *me = (MountEntry) {
                .source_malloc = TAKE_PTR(tmp_dir),
                .path_const = "/tmp/",
                .mode = MOUNT_BIND,
                .source_dir_mode = 01777,
                .create_source_dir = true,
        };
 
        me = mount_list_extend(ml);
        if (!me)
                return log_oom_debug();
        *me = (MountEntry) {
                .source_malloc = TAKE_PTR(var_tmp_dir),
                .path_const = "/var/tmp/",
                .mode = MOUNT_BIND,
                .source_dir_mode = 01777,
                .create_source_dir = true,
        };
 
        return 0;
}
 
static int append_static_mounts(MountList *ml, const MountEntry *mounts, size_t n, bool ignore_protect) {
        assert(ml);
        assert(mounts || n == 0);
 
        /* Adds a list of static pre-defined entries */
 
        FOREACH_ARRAY(m, mounts, n) {
                MountEntry *me = mount_list_extend(ml);
                if (!me)
                        return log_oom_debug();
 
                /* No dynamic values allowed. */
                assert(m->path_const);
                assert(!m->path_malloc);
                assert(!m->unprefixed_path_malloc);
                assert(!m->source_malloc);
                assert(!m->options_malloc);
                assert(!m->overlay_layers);
 
                *me = *m;
                me->ignore = me->ignore || ignore_protect;
        }
 
        return 0;
}
 
static int append_protect_control_groups(MountList *ml, ProtectControlGroups protect_control_groups, bool ignore_protect) {
        assert(ml);
 
        switch (protect_control_groups) {
 
        case PROTECT_CONTROL_GROUPS_NO:
                return 0;
 
        case PROTECT_CONTROL_GROUPS_YES:
                return append_static_mounts(ml, protect_control_groups_yes_table, ELEMENTSOF(protect_control_groups_yes_table), ignore_protect);
 
        case PROTECT_CONTROL_GROUPS_PRIVATE:
                return append_static_mounts(ml, protect_control_groups_private_table, ELEMENTSOF(protect_control_groups_private_table), ignore_protect);
 
        case PROTECT_CONTROL_GROUPS_STRICT:
                return append_static_mounts(ml, protect_control_groups_strict_table, ELEMENTSOF(protect_control_groups_strict_table), ignore_protect);
 
        default:
                assert_not_reached();
        }
}
 
static int append_protect_home(MountList *ml, ProtectHome protect_home, bool ignore_protect) {
        assert(ml);
 
        switch (protect_home) {
 
        case PROTECT_HOME_NO:
                return 0;
 
        case PROTECT_HOME_READ_ONLY:
                return append_static_mounts(ml, protect_home_read_only_table, ELEMENTSOF(protect_home_read_only_table), ignore_protect);
 
        case PROTECT_HOME_TMPFS:
                return append_static_mounts(ml, protect_home_tmpfs_table, ELEMENTSOF(protect_home_tmpfs_table), ignore_protect);
 
        case PROTECT_HOME_YES:
                return append_static_mounts(ml, protect_home_yes_table, ELEMENTSOF(protect_home_yes_table), ignore_protect);
 
        default:
                assert_not_reached();
        }
}
 
static int append_protect_system(MountList *ml, ProtectSystem protect_system, bool ignore_protect) {
        assert(ml);
 
        switch (protect_system) {
 
        case PROTECT_SYSTEM_NO:
                return 0;
 
        case PROTECT_SYSTEM_STRICT:
                return append_static_mounts(ml, protect_system_strict_table, ELEMENTSOF(protect_system_strict_table), ignore_protect);
 
        case PROTECT_SYSTEM_YES:
                return append_static_mounts(ml, protect_system_yes_table, ELEMENTSOF(protect_system_yes_table), ignore_protect);
 
        case PROTECT_SYSTEM_FULL:
                return append_static_mounts(ml, protect_system_full_table, ELEMENTSOF(protect_system_full_table), ignore_protect);
 
        default:
                assert_not_reached();
        }
}
 
static int append_private_bpf(
                MountList *ml,
                PrivateBPF private_bpf,
                bool protect_kernel_tunables,
                bool ignore_protect,
                const NamespaceParameters *p) {
 
        assert(ml);
 
        switch (private_bpf) {
        case PRIVATE_BPF_NO:
                if (protect_kernel_tunables)
                        return append_static_mounts(ml, private_bpf_no_table, ELEMENTSOF(private_bpf_no_table), ignore_protect);
                return 0;
        case PRIVATE_BPF_YES: {
                MountEntry *me = mount_list_extend(ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = "/sys/fs/bpf",
                        .mode = MOUNT_BPFFS,
                        .ignore = !protect_kernel_tunables, /* indicate whether we should fall back to MOUNT_READ_ONLY on failure. */
                };
                return 0;
        }
        default:
                assert_not_reached();
        }
}
 
static int mount_path_compare(const MountEntry *a, const MountEntry *b) {
        int d;
 
        /* ExtensionImages/Directories will be used by other mounts as a base, so sort them first
         * regardless of the prefix - they are set up in the propagate directory anyway */
        d = -CMP(a->mode == MOUNT_EXTENSION_IMAGE, b->mode == MOUNT_EXTENSION_IMAGE);
        if (d != 0)
                return d;
        d = -CMP(a->mode == MOUNT_EXTENSION_DIRECTORY, b->mode == MOUNT_EXTENSION_DIRECTORY);
        if (d != 0)
                return d;
 
        /* MOUNT_PRIVATE_TMPFS needs to be set up earlier, especially than MOUNT_BIND. */
        d = -CMP(a->mode == MOUNT_PRIVATE_TMPFS, b->mode == MOUNT_PRIVATE_TMPFS);