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 2001–3000 of 4,291

                                m->filter_class >= 0 ? m->filter_class : IMAGE_SYSEXT,
                                extension_name,
                                /* relax_extension_release_check= */ false,
                                &extension_release);
                if (r == -ENOENT) {
                        if (m->filter_class >= 0)
                                return 0; /* Nothing to do, wrong class */
 
                        r = load_extension_release_pairs(
                                        mount_entry_source(m),
                                        IMAGE_CONFEXT,
                                        extension_name,
                                        /* relax_extension_release_check= */ false,
                                        &extension_release);
                        if (r >= 0)
                                class = IMAGE_CONFEXT;
                }
                if (r == -ENOENT && m->ignore)
                        return 0;
                if (r < 0)
                        return log_debug_errno(r, "Failed to acquire 'extension-release' data of extension tree %s: %m", mount_entry_source(m));
 
                r = parse_os_release(
                                empty_to_root(root_directory),
                                "ID", &host_os_release_id,
                                "ID_LIKE", &host_os_release_id_like,
                                "VERSION_ID", &host_os_release_version_id,
                                image_class_info[class].level_env, &host_os_release_level,
                                NULL);
                if (r < 0)
                        return log_debug_errno(r, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory));
                if (isempty(host_os_release_id))
                        return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "'ID' field not found or empty in 'os-release' data of OS tree '%s'.", empty_to_root(root_directory));
 
                r = extension_release_validate(
                                extension_name,
                                host_os_release_id,
                                host_os_release_id_like,
                                host_os_release_version_id,
                                host_os_release_level,
                                /* host_extension_scope= */ NULL, /* Leave empty, we need to accept both system and portable */
                                extension_release,
                                class);
                if (r < 0)
                        return log_debug_errno(r, "Failed to compare directory %s extension-release metadata with the root's os-release: %m", extension_name);
                if (r == 0)
                        return log_debug_errno(SYNTHETIC_ERRNO(ESTALE), "Directory %s extension-release metadata does not match the root's.", extension_name);
 
                _fallthrough_;
        }
 
        case MOUNT_BIND:
                rbind = false;
 
                _fallthrough_;
        case MOUNT_BIND_RECURSIVE: {
                _cleanup_free_ char *chased = NULL;
 
                /* Since mount() will always follow symlinks we chase the symlinks on our own first. Note
                 * that bind mount source paths are always relative to the host root, hence we pass NULL as
                 * root directory to chase() here. */
 
                /* When we create implicit mounts, we might need to create the path ourselves as it is on a
                 * just-created tmpfs, for example. */
                if (m->create_source_dir) {
                        r = mkdir_p(mount_entry_source(m), m->source_dir_mode);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to create source directory %s: %m", mount_entry_source(m));
 
                        r = label_fix_full(AT_FDCWD, mount_entry_source(m), mount_entry_unprefixed_path(m), /* flags= */ 0, /* label_context= */ NULL);
                        if (r < 0)
                                return log_error_errno(r, "Failed to set label of the source directory %s: %m", mount_entry_source(m));
                }
 
                r = chase(mount_entry_source(m), NULL, CHASE_TRAIL_SLASH|CHASE_TRIGGER_AUTOFS, &chased, NULL);
                if (r < 0) {
                        if (m->ignore) {
                                if (r == -ENOENT) {
                                        log_debug_errno(r, "Path '%s' does not exist, ignoring.", mount_entry_source(m));
                                        return 0;
                                }
                                if (ERRNO_IS_NEG_PRIVILEGE(r)) {
                                        log_debug_errno(r, "Path '%s' is not accessible, ignoring: %m", mount_entry_source(m));
                                        return 0;
                                }
                        }
 
                        return log_debug_errno(r, "Failed to follow symlinks on %s: %m", mount_entry_source(m));
                }
 
                log_debug("Followed source symlinks %s %s %s.",
                          mount_entry_source(m), glyph(GLYPH_ARROW_RIGHT), chased);
 
                free_and_replace(m->source_malloc, chased);
 
                what = mount_entry_source(m);
                make = true;
                break;
        }
 
        case MOUNT_EMPTY_DIR:
        case MOUNT_PRIVATE_TMPFS:
        case MOUNT_TMPFS:
                return mount_tmpfs(m);
 
        case MOUNT_PRIVATE_TMP:
                what = mount_entry_source(m);
                make = true;
                break;
 
        case MOUNT_PRIVATE_DEV:
                return mount_private_dev(m, p);
 
        case MOUNT_BIND_DEV:
                return mount_bind_dev(m);
 
        case MOUNT_PRIVATE_SYSFS:
                return mount_private_sysfs(m, p);
 
        case MOUNT_BIND_SYSFS:
                return mount_bind_sysfs(m);
 
        case MOUNT_PROCFS:
                return mount_procfs(m, p);
 
        case MOUNT_PRIVATE_CGROUP2FS:
                return mount_private_cgroup2fs(m, p);
 
        case MOUNT_RUN:
                return mount_run(m);
 
        case MOUNT_MQUEUEFS:
                return mount_mqueuefs(m);
 
        case MOUNT_IMAGE:
                return mount_image(m, NULL, p->mount_image_policy, p->runtime_scope);
 
        case MOUNT_EXTENSION_IMAGE:
                return mount_image(m, root_directory, p->extension_image_policy, p->runtime_scope);
 
        case MOUNT_OVERLAY:
                return mount_overlay(m);
 
        default:
                assert_not_reached();
        }
 
        assert(what);
 
        r = mount_bind(m, what, rbind, make);
        if (r < 0)
                return r;
 
        log_debug("Successfully mounted %s to %s", what, mount_entry_path(m));
 
        /* Take care of id-mapped mounts */
        if (m->idmapped && uid_is_valid(m->idmap_uid) && gid_is_valid(m->idmap_gid)) {
                _cleanup_close_ int userns_fd = -EBADF;
                _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
 
                log_debug("Setting an id-mapped mount on %s", mount_entry_path(m));
 
                /* Do mapping from nobody (in setup_exec_directory()) -> this uid */
                if (strextendf(&uid_map, UID_FMT " " UID_FMT " 1\n", UID_NOBODY, m->idmap_uid) < 0)
                        return log_oom();
 
                /* Consider StateDirectory=xxx aaa xxx:aaa/222
                 * To allow for later symlink creation (by root) in create_symlinks_from_tuples(), map root as well. */
                if (m->idmap_uid != 0)
                        if (!strextend(&uid_map, "0 0 1\n"))
                                return log_oom();
 
                if (strextendf(&gid_map, GID_FMT " " GID_FMT " 1\n", GID_NOBODY, m->idmap_gid) < 0)
                        return log_oom();
 
                if (m->idmap_gid != 0)
                        if (!strextend(&gid_map, "0 0 1\n"))
                                return log_oom();
 
                userns_fd = userns_acquire(uid_map, gid_map, /* setgroups_deny= */ true);
                if (userns_fd < 0)
                        return log_error_errno(userns_fd, "Failed to allocate user namespace: %m");
 
                /* Drop SUID, add NOEXEC for the mount to avoid root exploits */
                r = remount_idmap_fd(STRV_MAKE(mount_entry_path(m)), userns_fd, MOUNT_ATTR_NOSUID | MOUNT_ATTR_NOEXEC | MOUNT_ATTR_NODEV);
                if (r < 0)
                        return log_error_errno(r, "Failed to create an id-mapped mount: %m");
 
                log_debug("ID-mapped mount created successfully for %s from " UID_FMT " to " UID_FMT "", mount_entry_path(m), UID_NOBODY, m->idmap_uid);
        }
 
        return 1;
}
 
static bool should_propagate_to_submounts(const MountEntry *m) {
        assert(m);
        return !IN_SET(m->mode, MOUNT_EMPTY_DIR, MOUNT_TMPFS, MOUNT_PRIVATE_TMPFS);
}
 
static int make_read_only(const MountEntry *m, char **deny_list, FILE *proc_self_mountinfo) {
        unsigned long new_flags = 0, flags_mask = 0;
        bool submounts;
        int r;
 
        assert(m);
        assert(proc_self_mountinfo);
 
        if (m->state != MOUNT_APPLIED)
                return 0;
 
        if (mount_entry_read_only(m) || m->mode == MOUNT_PRIVATE_DEV) {
                new_flags |= MS_RDONLY;
                flags_mask |= MS_RDONLY;
        }
 
        if (m->nosuid) {
                new_flags |= MS_NOSUID;
                flags_mask |= MS_NOSUID;
        }
 
        if (flags_mask == 0) /* No Change? */
                return 0;
 
        /* We generally apply these changes recursively, except for /dev, and the cases we know there's
         * nothing further down.  Set /dev readonly, but not submounts like /dev/shm. Also, we only set the
         * per-mount read-only flag.  We can't set it on the superblock, if we are inside a user namespace
         * and running Linux <= 4.17. */
        submounts = mount_entry_read_only(m) && should_propagate_to_submounts(m);
        if (submounts)
                r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, deny_list, proc_self_mountinfo);
        else
                r = bind_remount_one_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, proc_self_mountinfo);
 
        /* Note that we only turn on the MS_RDONLY flag here, we never turn it off. Something that was marked
         * read-only already stays this way. This improves compatibility with container managers, where we
         * won't attempt to undo read-only mounts already applied. */
 
        if (r == -ENOENT && m->ignore)
                return 0;
        if (r < 0)
                return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
                                       submounts ? " and its submounts" : "");
        return 0;
}
 
static int make_noexec(const MountEntry *m, char **deny_list, FILE *proc_self_mountinfo) {
        unsigned long new_flags = 0, flags_mask = 0;
        bool submounts;
        int r;
 
        assert(m);
        assert(proc_self_mountinfo);
 
        if (m->state != MOUNT_APPLIED)
                return 0;
 
        if (mount_entry_noexec(m)) {
                new_flags |= MS_NOEXEC;
                flags_mask |= MS_NOEXEC;
        } else if (mount_entry_exec(m)) {
                new_flags &= ~MS_NOEXEC;
                flags_mask |= MS_NOEXEC;
        }
 
        if (flags_mask == 0) /* No Change? */
                return 0;
 
        submounts = should_propagate_to_submounts(m);
        if (submounts)
                r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, deny_list, proc_self_mountinfo);
        else
                r = bind_remount_one_with_mountinfo(mount_entry_path(m), new_flags, flags_mask, proc_self_mountinfo);
 
        if (r == -ENOENT && m->ignore)
                return 0;
        if (r < 0)
                return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
                                       submounts ? " and its submounts" : "");
        return 0;
}
 
static int make_nosuid(const MountEntry *m, FILE *proc_self_mountinfo) {
        bool submounts;
        int r;
 
        assert(m);
        assert(proc_self_mountinfo);
 
        if (m->state != MOUNT_APPLIED)
                return 0;
 
        submounts = should_propagate_to_submounts(m);
        if (submounts)
                r = bind_remount_recursive_with_mountinfo(mount_entry_path(m), MS_NOSUID, MS_NOSUID, NULL, proc_self_mountinfo);
        else
                r = bind_remount_one_with_mountinfo(mount_entry_path(m), MS_NOSUID, MS_NOSUID, proc_self_mountinfo);
        if (r == -ENOENT && m->ignore)
                return 0;
        if (r < 0)
                return log_debug_errno(r, "Failed to re-mount '%s'%s: %m", mount_entry_path(m),
                                       submounts ? " and its submounts" : "");
        return 0;
}
 
static bool namespace_parameters_mount_apivfs(const NamespaceParameters *p) {
        assert(p);
 
        /*
         * ProtectControlGroups= and ProtectKernelTunables= imply MountAPIVFS=,
         * since to protect the API VFS mounts, they need to be around in the
         * first place...
         */
 
        return p->mount_apivfs ||
                p->protect_control_groups != PROTECT_CONTROL_GROUPS_NO ||
                p->protect_kernel_tunables ||
                p->protect_proc != PROTECT_PROC_DEFAULT ||
                p->proc_subset != PROC_SUBSET_ALL ||
                p->private_bpf != PRIVATE_BPF_NO ||
                p->private_pids != PRIVATE_PIDS_NO;
}
 
/* Walk all mount entries and dropping any unused mounts. This affects all
 * mounts:
 * - that are implicitly protected by a path that has been rendered inaccessible
 * - whose immediate parent requests the same protection mode as the mount itself
 * - that are outside of the relevant root directory
 * - which are duplicates
 */
static void sort_and_drop_unused_mounts(MountList *ml, const char *root_directory) {
        assert(ml);
        assert(root_directory);
 
        assert(ml->mounts || ml->n_mounts == 0);
 
        typesafe_qsort(ml->mounts, ml->n_mounts, mount_path_compare);
 
        drop_duplicates(ml);
        drop_outside_root(ml, root_directory);
        drop_inaccessible(ml);
        drop_nop(ml);
}
 
static int create_symlinks_from_tuples(const char *root, char **strv_symlinks) {
        int r;
 
        STRV_FOREACH_PAIR(src, dst, strv_symlinks) {
                _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
 
                src_abs = path_join(root, *src);
                dst_abs = path_join(root, *dst);
                if (!src_abs || !dst_abs)
                        return -ENOMEM;
 
                r = mkdir_parents_label(dst_abs, 0755);
                if (r < 0)
                        return log_debug_errno(
                                        r,
                                        "Failed to create parent directory for symlink '%s': %m",
                                        dst_abs);
 
                r = symlink_idempotent(src_abs, dst_abs, true);
                if (r < 0)
                        return log_debug_errno(
                                        r,
                                        "Failed to create symlink from '%s' to '%s': %m",
                                        src_abs,
                                        dst_abs);
        }
 
        return 0;
}
 
static void mount_entry_path_debug_string(const char *root, MountEntry *m, char **ret_path) {
        assert(m);
 
        /* Create a string suitable for debugging logs, stripping for example the local working directory.
         * For example, with a BindPaths=/var/bar that does not exist on the host:
         *
         * Before:
         *  foo.service: Failed to set up mount namespacing: /run/systemd/unit-root/var/bar: No such file or directory
         * After:
         *  foo.service: Failed to set up mount namespacing: /var/bar: No such file or directory
         *
         * Note that this is an error path, so no OOM check is done on purpose. */
 
        if (!ret_path)
                return;
 
        if (!mount_entry_path(m)) {
                *ret_path = NULL;
                return;
        }
 
        if (root) {
                const char *e = startswith(mount_entry_path(m), root);
                if (e) {
                        *ret_path = strdup(e);
                        return;
                }
        }
 
        *ret_path = strdup(mount_entry_path(m));
        return;
}
 
static int apply_mounts(
                MountList *ml,
                const char *root,
                const NamespaceParameters *p,
                char **reterr_path) {
 
        _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
        _cleanup_free_ char **deny_list = NULL;
        int r;
 
        assert(ml);
        assert(root);
        assert(p);
 
        if (ml->n_mounts == 0) /* Shortcut: nothing to do */
                return 0;
 
        /* Open /proc/self/mountinfo now as it may become unavailable if we mount anything on top of
         * /proc. For example, this is the case with the option: 'InaccessiblePaths=/proc'. */
        proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
        if (!proc_self_mountinfo) {
                r = -errno;
 
                if (reterr_path)
                        *reterr_path = strdup("/proc/self/mountinfo");
 
                return log_debug_errno(r, "Failed to open %s: %m", "/proc/self/mountinfo");
        }
 
        /* First round, establish all mounts we need */
        for (;;) {
                bool again = false;
 
                FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
 
                        if (m->state != MOUNT_PENDING)
                                continue;
 
                        /* ExtensionImages/Directories are first opened in the propagate directory, not in
                         * the root_directory. A private (invisible to the guest) tmpfs instance is mounted
                         * on /run/[user/xyz/]systemd/unit-private-tmp as the storage backend of private
                         * /tmp and /var/tmp. */
                        r = follow_symlink(!IN_SET(m->mode, MOUNT_EXTENSION_IMAGE, MOUNT_EXTENSION_DIRECTORY, MOUNT_PRIVATE_TMPFS) ? root : NULL, m);
                        if (r < 0) {
                                mount_entry_path_debug_string(root, m, reterr_path);
                                return r;
                        }
                        if (r == 0) {
                                /* We hit a symlinked mount point. The entry got rewritten and might
                                 * point to a very different place now. Let's normalize the changed
                                 * list, and start from the beginning. After all to mount the entry
                                 * at the new location we might need some other mounts first */
                                again = true;
                                break;
                        }
 
                        /* Returns 1 if the mount should be post-processed, 0 otherwise */
                        r = apply_one_mount(root, m, p);
                        if (r < 0) {
                                mount_entry_path_debug_string(root, m, reterr_path);
                                return r;
                        }
                        m->state = r == 0 ? MOUNT_SKIPPED : MOUNT_APPLIED;
                }
 
                if (!again)
                        break;
 
                sort_and_drop_unused_mounts(ml, root);
        }
 
        /* Now that all filesystems have been set up, but before the
         * read-only switches are flipped, create the exec dirs and other symlinks.
         * Note that when /var/lib is not empty/tmpfs, these symlinks will already
         * exist, which means this will be a no-op. */
        r = create_symlinks_from_tuples(root, p->symlinks);
        if (r < 0)
                return log_debug_errno(r, "Failed to set up symlinks inside mount namespace: %m");
 
        /* Create a deny list we can pass to bind_mount_recursive() */
        deny_list = new(char*, ml->n_mounts+1);
        if (!deny_list)
                return -ENOMEM;
        for (size_t j = 0; j < ml->n_mounts; j++)
                deny_list[j] = (char*) mount_entry_path(ml->mounts+j);
        deny_list[ml->n_mounts] = NULL;
 
        /* Second round, flip the ro bits if necessary. */
        FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
                r = make_read_only(m, deny_list, proc_self_mountinfo);
                if (r < 0) {
                        mount_entry_path_debug_string(root, m, reterr_path);
                        return r;
                }
        }
 
        /* Third round, flip the noexec bits with a simplified deny list. */
        for (size_t j = 0; j < ml->n_mounts; j++)
                if (IN_SET((ml->mounts+j)->mode, MOUNT_EXEC, MOUNT_NOEXEC))
                        deny_list[j] = (char*) mount_entry_path(ml->mounts+j);
        deny_list[ml->n_mounts] = NULL;
 
        FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
                r = make_noexec(m, deny_list, proc_self_mountinfo);
                if (r < 0) {
                        mount_entry_path_debug_string(root, m, reterr_path);
                        return r;
                }
        }
 
        /* Fourth round, flip the nosuid bits without a deny list. */
        if (p->mount_nosuid)
                FOREACH_ARRAY(m, ml->mounts, ml->n_mounts) {
                        r = make_nosuid(m, proc_self_mountinfo);
                        if (r < 0) {
                                mount_entry_path_debug_string(root, m, reterr_path);
                                return r;
                        }
                }
 
        return 1;
}
 
static bool root_read_only(
                char **read_only_paths,
                ProtectSystem protect_system) {
 
        /* Determine whether the root directory is going to be read-only given the configured settings. */
 
        if (protect_system == PROTECT_SYSTEM_STRICT)
                return true;
 
        if (prefixed_path_strv_contains(read_only_paths, "/"))
                return true;
 
        return false;
}
 
static bool home_read_only(
                char * const *read_only_paths,
                char * const *inaccessible_paths,
                char * const *empty_directories,
                const BindMount *bind_mounts,
                size_t n_bind_mounts,
                const TemporaryFileSystem *temporary_filesystems,
                size_t n_temporary_filesystems,
                ProtectHome protect_home) {
 
        /* Determine whether the /home directory is going to be read-only given the configured settings. Yes,
         * this is a bit sloppy, since we don't bother checking for cases where / is affected by multiple
         * settings. */
 
        if (protect_home != PROTECT_HOME_NO)
                return true;
 
        if (prefixed_path_strv_contains(read_only_paths, "/home") ||
            prefixed_path_strv_contains(inaccessible_paths, "/home") ||
            prefixed_path_strv_contains(empty_directories, "/home"))
                return true;
 
        FOREACH_ARRAY(i, temporary_filesystems, n_temporary_filesystems)
                if (path_equal(i->path, "/home"))
                        return true;
 
        /* If /home is overmounted with some dir from the host it's not writable. */
        FOREACH_ARRAY(i, bind_mounts, n_bind_mounts)
                if (path_equal(i->destination, "/home"))
                        return true;
 
        return false;
}
 
static bool namespace_read_only(const NamespaceParameters *p) {
        assert(p);
 
        return root_read_only(p->read_only_paths,
                              p->protect_system) &&
                home_read_only(p->read_only_paths, p->inaccessible_paths, p->empty_directories,
                               p->bind_mounts, p->n_bind_mounts, p->temporary_filesystems, p->n_temporary_filesystems,
                               p->protect_home) &&
                strv_isempty(p->read_write_paths);
}
 
int setup_namespace(const NamespaceParameters *p, char **reterr_path) {
 
        _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
        _cleanup_(dissected_image_unrefp) DissectedImage *dissected_image = NULL;
        _cleanup_strv_free_ char **hierarchies = NULL;
        _cleanup_(mount_list_done) MountList ml = {};
        _cleanup_close_ int userns_fd = -EBADF;
        bool require_prefix = false;
        const char *root;
        DissectImageFlags dissect_image_flags =
                DISSECT_IMAGE_GENERIC_ROOT |
                DISSECT_IMAGE_REQUIRE_ROOT |
                DISSECT_IMAGE_DISCARD_ON_LOOP |
                DISSECT_IMAGE_RELAX_VAR_CHECK |
                DISSECT_IMAGE_FSCK |
                DISSECT_IMAGE_USR_NO_ROOT |
                DISSECT_IMAGE_GROWFS |
                DISSECT_IMAGE_ADD_PARTITION_DEVICES |
                DISSECT_IMAGE_PIN_PARTITION_DEVICES |
                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY |
                DISSECT_IMAGE_VERITY_SHARE;
        MStackFlags mstack_flags = 0;
        int r;
 
        assert(p);
 
        /* Make sure that all mknod(), mkdir() calls we do are unaffected by the umask, and the access modes
         * we configure take effect */
        BLOCK_WITH_UMASK(0000);
 
        bool setup_propagate = !isempty(p->propagate_dir) && !isempty(p->incoming_dir);
        unsigned long mount_propagation_flag = p->mount_propagation_flag != 0 ? p->mount_propagation_flag : MS_SHARED;
 
        /* Make the whole image read-only if we can determine that we only access it in a read-only fashion. */
        bool ro = namespace_read_only(p);
        if (ro) {
                dissect_image_flags |= DISSECT_IMAGE_READ_ONLY;
                mstack_flags |= MSTACK_RDONLY;
        }
 
        _cleanup_close_ int _root_mount_fd = -EBADF;
        int root_mount_fd = -EBADF;
        if (pinned_resource_is_set(p->rootfs)) {
                if (p->rootfs->directory_fd >= 0) {
 
                        /* In "managed" mode we need to map from foreign UID/GID space, hence go via mountfsd */
                        if (p->private_users == PRIVATE_USERS_MANAGED) {
                                userns_fd = namespace_open_by_type(NAMESPACE_USER);
                                if (userns_fd < 0)
                                        return log_debug_errno(userns_fd, "Failed to open our own user namespace: %m");
 
                                r = mountfsd_mount_directory_fd(
                                                p->mountfsd_link,
                                                p->rootfs->directory_fd,
                                                userns_fd,
                                                dissect_image_flags,
                                                &_root_mount_fd);
                                if (r < 0)
                                        return r;
 
                                root_mount_fd = _root_mount_fd;
                        }
 
                        /* Try to clone the directory mount if we have privs to, so that we can apply the
                         * MS_SLAVE propagation settings right-away. */
                        if (root_mount_fd < 0) {
                                _root_mount_fd = open_tree_attr_with_fallback(
                                                p->rootfs->directory_fd,
                                                "",
                                                OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH|AT_RECURSIVE,
                                                &(struct mount_attr) {
                                                        /* We just remounted / as slave, but that didn't affect the detached
                                                         * mount that we just mounted, so remount that one as slave recursive
                                                         * as well now. */
                                                        .propagation = MS_SLAVE,
                                                });
                                if (_root_mount_fd < 0 && !ERRNO_IS_NEG_PRIVILEGE(_root_mount_fd) && _root_mount_fd != -EINVAL)
                                        return log_debug_errno(_root_mount_fd, "Failed to clone specified directory: %m");
 
                                root_mount_fd = _root_mount_fd;
                        }
                        /* If we have only a root fd (and we couldn't make it ours), and we have no path,
                         * then try to go on with the literal fd */
                        if (root_mount_fd < 0 && !p->rootfs->directory)
                                root_mount_fd = p->rootfs->directory_fd;
                }
 
                if (p->rootfs->image_fd >= 0) {
                        SET_FLAG(dissect_image_flags, DISSECT_IMAGE_NO_PARTITION_TABLE, p->verity && p->verity->data_path);
 
                        if (p->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
                                /* In system mode we mount directly */
 
                                /* First check if we have a verity device already open and with a fstype pinned by policy. If it
                                 * cannot be found, then fallback to the slow path (full dissect). */
                                r = dissected_image_new_from_existing_verity(
                                                p->rootfs->image,
                                                p->verity,
                                                p->root_image_options,
                                                p->root_image_policy,
                                                /* image_filter= */ NULL,
                                                p->runtime_scope,
                                                dissect_image_flags,
                                                &dissected_image);
                                if (r < 0 && !ERRNO_IS_NEG_DEVICE_ABSENT(r) && r != -ENOPKG)
                                        return r;
                                if (r >= 0)
                                        log_debug("Reusing pre-existing verity-protected root image %s", p->rootfs->image);
                                else {
                                        r = loop_device_make(
                                                        p->rootfs->image_fd,
                                                        FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_DEVICE_READ_ONLY) ? O_RDONLY : -1 /* < 0 means take access mode from fd */,
                                                        /* offset= */ 0,
                                                        /* size= */ UINT64_MAX,
                                                        /* sector_size= */ UINT32_MAX,
                                                        FLAGS_SET(dissect_image_flags, DISSECT_IMAGE_NO_PARTITION_TABLE) ? 0 : LO_FLAGS_PARTSCAN,
                                                        LOCK_SH,
                                                        &loop_device);
                                        if (r < 0)
                                                return log_debug_errno(r, "Failed to create loop device for root image: %m");
 
                                        r = dissect_loop_device(
                                                        loop_device,
                                                        p->verity,
                                                        p->root_image_options,
                                                        p->root_image_policy,
                                                        /* image_filter= */ NULL,
                                                        dissect_image_flags,
                                                        &dissected_image);
                                        if (r < 0)
                                                return log_debug_errno(r, "Failed to dissect image: %m");
 
                                        r = dissected_image_load_verity_sig_partition(
                                                        dissected_image,
                                                        loop_device->fd,
                                                        p->verity);
                                        if (r < 0)
                                                return r;
 
                                        r = dissected_image_guess_verity_roothash(
                                                        dissected_image,
                                                        p->verity);
                                        if (r < 0)
                                                return r;
 
                                        r = dissected_image_decrypt(
                                                        dissected_image,
                                                        /* root= */ NULL,
                                                        /* passphrase= */ NULL,
                                                        p->verity,
                                                        p->root_image_policy,
                                                        dissect_image_flags);
                                        if (r < 0)
                                                return log_debug_errno(r, "Failed to decrypt dissected image: %m");
                                }
                        } else {
                                userns_fd = namespace_open_by_type(NAMESPACE_USER);
                                if (userns_fd < 0)
                                        return log_debug_errno(userns_fd, "Failed to open our own user namespace: %m");
 
                                r = mountfsd_mount_image_fd(
                                                p->mountfsd_link,
                                                p->rootfs->image_fd,
                                                userns_fd,
                                                p->root_image_options,
                                                p->root_image_policy,
                                                p->verity,
                                                dissect_image_flags,
                                                &dissected_image);
                                if (r < 0)
                                        return r;
                        }
                }
 
                if (p->rootfs->mstack_loaded) {
                        if (p->runtime_scope != RUNTIME_SCOPE_SYSTEM) {
                                userns_fd = namespace_open_by_type(NAMESPACE_USER);
                                if (userns_fd < 0)
                                        return log_debug_errno(userns_fd, "Failed to open our own user namespace: %m");
                        }
 
                        r = mstack_open_images(
                                        p->rootfs->mstack_loaded,
                                        p->mountfsd_link,
                                        userns_fd,
                                        p->root_image_policy,
                                        /* image_filter= */ NULL,
                                        mstack_flags);
                        if (r < 0)
                                return r;
                }
        }
 
        if (p->rootfs && p->rootfs->directory)
                root = p->rootfs->directory;
        else {
                /* /run/systemd should have been created by PID 1 early on already, but in some cases, like
                 * when running tests (test-execute), it might not have been created yet so let's make sure
                 * we create it if it doesn't already exist. */
                (void) mkdir_p_label("/run/systemd", 0755);
 
                /* Always create the mount namespace in a temporary directory, instead of operating directly
                 * in the root. The temporary directory prevents any mounts from being potentially obscured
                 * my other mounts we already applied.  We use the same mount point for all images, which is
                 * safe, since they all live in their own namespaces after all, and hence won't see each
                 * other. (Note: this directory is also created by PID 1 early on, we create it here for
                 * similar reasons as /run/systemd/ first.) */
                root = "/run/systemd/mount-rootfs";
                (void) mkdir_label(root, 0555);
 
                require_prefix = true;
        }
 
        if (p->n_extension_images > 0 || !strv_isempty(p->extension_directories)) {
                /* Hierarchy population needs to be done for sysext and confext extension images */
                r = parse_env_extension_hierarchies(&hierarchies, "SYSTEMD_SYSEXT_AND_CONFEXT_HIERARCHIES");
                if (r < 0)
                        return r;
        }
 
        r = append_access_mounts(&ml, p->read_write_paths, MOUNT_READ_WRITE, require_prefix);
        if (r < 0)
                return r;
 
        r = append_access_mounts(&ml, p->read_only_paths, MOUNT_READ_ONLY, require_prefix);
        if (r < 0)
                return r;
 
        r = append_access_mounts(&ml, p->inaccessible_paths, MOUNT_INACCESSIBLE, require_prefix);
        if (r < 0)
                return r;
 
        r = append_access_mounts(&ml, p->exec_paths, MOUNT_EXEC, require_prefix);
        if (r < 0)
                return r;
 
        r = append_access_mounts(&ml, p->no_exec_paths, MOUNT_NOEXEC, require_prefix);
        if (r < 0)
                return r;
 
        r = append_empty_dir_mounts(&ml, p->empty_directories);
        if (r < 0)
                return r;
 
        r = append_bind_mounts(&ml, p->bind_mounts, p->n_bind_mounts);
        if (r < 0)
                return r;
 
        r = append_tmpfs_mounts(&ml, p->temporary_filesystems, p->n_temporary_filesystems);
        if (r < 0)
                return r;
 
        r = append_private_tmp(&ml, p);
        if (r < 0)
                return r;
 
        r = append_mount_images(&ml, p->mount_images, p->n_mount_images);
        if (r < 0)
                return r;
 
        r = append_extensions(&ml, root, p->private_namespace_dir, hierarchies, p->extension_images, p->n_extension_images, p->extension_directories);
        if (r < 0)
                return r;
 
        if (p->private_dev) {
                MountEntry *me = mount_list_extend(&ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = "/dev",
                        .mode = MOUNT_PRIVATE_DEV,
                        .flags = DEV_MOUNT_OPTIONS,
                };
        }
 
        /* In case /proc is successfully mounted with pid tree subset only (ProcSubset=pid), the protective
           mounts to non-pid /proc paths would fail. But the pid only option may have failed gracefully, so
           let's try the mounts but it's not fatal if they don't succeed. */
        bool ignore_protect_proc = p->ignore_protect_paths || p->proc_subset == PROC_SUBSET_PID;
        if (p->protect_kernel_tunables) {
                r = append_static_mounts(&ml,
                                         protect_kernel_tunables_proc_table,
                                         ELEMENTSOF(protect_kernel_tunables_proc_table),
                                         ignore_protect_proc);
                if (r < 0)
                        return r;
 
                r = append_static_mounts(&ml,
                                         protect_kernel_tunables_sys_table,
                                         ELEMENTSOF(protect_kernel_tunables_sys_table),
                                         p->ignore_protect_paths);
                if (r < 0)
                        return r;
        }
 
        if (p->protect_kernel_modules) {
                r = append_static_mounts(&ml,
                                         protect_kernel_modules_table,
                                         ELEMENTSOF(protect_kernel_modules_table),
                                         p->ignore_protect_paths);
                if (r < 0)
                        return r;
        }
 
        if (p->protect_kernel_logs) {
                r = append_static_mounts(&ml,
                                         protect_kernel_logs_proc_table,
                                         ELEMENTSOF(protect_kernel_logs_proc_table),
                                         ignore_protect_proc);
                if (r < 0)
                        return r;
 
                r = append_static_mounts(&ml,
                                         protect_kernel_logs_dev_table,
                                         ELEMENTSOF(protect_kernel_logs_dev_table),
                                         p->ignore_protect_paths);
                if (r < 0)
                        return r;
        }
 
        r = append_protect_control_groups(&ml, p->protect_control_groups, false);
        if (r < 0)
                return r;
 
        r = append_protect_home(&ml, p->protect_home, p->ignore_protect_paths);
        if (r < 0)
                return r;
 
        r = append_protect_system(&ml, p->protect_system, false);
        if (r < 0)
                return r;
 
        r = append_private_bpf(&ml, p->private_bpf, p->protect_kernel_tunables, /* ignore_protect= */ false, p);
        if (r < 0)
                return r;
 
        if (namespace_parameters_mount_apivfs(p)) {
                r = append_static_mounts(&ml,
                                         apivfs_table,
                                         ELEMENTSOF(apivfs_table),
                                         p->ignore_protect_paths);
                if (r < 0)
                        return r;
        }
 
        /* Only mount /proc/sys/kernel/hostname and domainname read-only if ProtectHostname=yes. Otherwise,
         * ProtectHostname=no allows changing hostname for the host, and ProtectHostname=private allows
         * changing the hostname in the unit's UTS namespace. Note, if proc is mounted with subset=pid then
         * neither of the two paths will exist, i.e. they are implicitly protected by the mount option. */
        if (p->protect_hostname == PROTECT_HOSTNAME_YES) {
                r = append_static_mounts(
                                &ml,
                                protect_hostname_yes_table,
                                ELEMENTSOF(protect_hostname_yes_table),
                                ignore_protect_proc);
                if (r < 0)
                        return r;
        }
 
        if (p->private_network) {
                MountEntry *me = mount_list_extend(&ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = "/sys",
                        .mode = MOUNT_PRIVATE_SYSFS,
                };
        }
 
        if (p->private_ipc) {
                MountEntry *me = mount_list_extend(&ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .path_const = "/dev/mqueue",
                        .mode = MOUNT_MQUEUEFS,
                        .flags = MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RELATIME,
                };
        }
 
        if (p->creds_path) {
                /* If our service has a credentials store configured, then bind that one in, but hide
                 * everything else. */
 
                MountEntry *me = mount_list_extend(&ml);
                if (!me)
                        return log_oom_debug();
 
                *me = (MountEntry) {
                        .mode = MOUNT_TMPFS,
                        .read_only = true,
                        .options_const = "mode=0755" TMPFS_LIMITS_EMPTY_OR_ALMOST,
                        .flags = MS_NODEV|MS_STRICTATIME|MS_NOSUID|MS_NOEXEC,
                };
 
                if (p->runtime_scope == RUNTIME_SCOPE_SYSTEM)
                        me->path_const = "/run/credentials";
                else {
                        r = path_extract_directory(p->creds_path, &me->path_malloc);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to extract parent directory from '%s': %m",
                                                       p->creds_path);
                }
 
                me = mount_list_extend(&ml);
                if (!me)
                        return log_oom_debug();