HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/exec-invoke.c

290,468 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: ff107cc753cf314807216d8e1747fc30661a6ef4

Lines 4001–5000 of 6,799

                if (setup_os_release_symlink &&
                    asprintf(&host_os_release_stage,
                             "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage",
                             geteuid()) < 0)
                        return -ENOMEM;
        }
 
        if (rootfs->image) {
                r = verity_settings_prepare(
                        &verity,
                        rootfs->image,
                        &context->root_hash, context->root_hash_path,
                        &context->root_hash_sig, context->root_hash_sig_path,
                        context->root_verity);
                if (r < 0)
                        return r;
        }
 
        NamespaceParameters parameters = {
                .runtime_scope = params->runtime_scope,
 
                .rootfs = rootfs,
                .root_image_options = context->root_image_options,
                .root_image_policy = context->root_image_policy ?: &image_policy_service,
 
                .read_write_paths = read_write_paths,
                .read_only_paths = needs_sandboxing ? context->read_only_paths : NULL,
                .inaccessible_paths = needs_sandboxing ? context->inaccessible_paths : NULL,
 
                .exec_paths = needs_sandboxing ? context->exec_paths : NULL,
                .no_exec_paths = needs_sandboxing ? context->no_exec_paths : NULL,
 
                .empty_directories = empty_directories,
                .symlinks = symlinks,
 
                .bind_mounts = bind_mounts,
                .n_bind_mounts = n_bind_mounts,
 
                .temporary_filesystems = context->temporary_filesystems,
                .n_temporary_filesystems = context->n_temporary_filesystems,
 
                .mount_images = context->mount_images,
                .n_mount_images = context->n_mount_images,
                .mount_image_policy = context->mount_image_policy ?: &image_policy_service,
 
                .tmp_dir = tmp_dir,
                .var_tmp_dir = var_tmp_dir,
 
                .creds_path = creds_path,
                .log_namespace = context->log_namespace,
                .mount_propagation_flag = context->mount_propagation_flag,
 
                .verity = &verity,
 
                .extension_images = context->extension_images,
                .n_extension_images = context->n_extension_images,
                .extension_image_policy = context->extension_image_policy ?: &image_policy_sysext,
                .extension_directories = context->extension_directories,
 
                .propagate_dir = propagate_dir,
                .incoming_dir = incoming_dir,
                .private_namespace_dir = private_namespace_dir,
                .host_notify_socket = params->notify_socket,
                .notify_socket_path = exec_get_private_notify_socket_path(context, params, needs_sandboxing),
                .host_os_release_stage = host_os_release_stage,
 
                /* If DynamicUser=no and RootDirectory= is set then lets pass a relaxed sandbox info,
                 * otherwise enforce it, don't ignore protected paths and fail if we are enable to apply the
                 * sandbox inside the mount namespace. */
                .ignore_protect_paths = !needs_sandboxing && !context->dynamic_user && pinned_resource_is_set(rootfs),
 
                .protect_control_groups = needs_sandboxing ? exec_get_protect_control_groups(context) : PROTECT_CONTROL_GROUPS_NO,
                .protect_kernel_tunables = needs_sandboxing && context->protect_kernel_tunables,
                .protect_kernel_modules = needs_sandboxing && context->protect_kernel_modules,
                .protect_kernel_logs = needs_sandboxing && context->protect_kernel_logs,
 
                .private_dev = needs_sandboxing && context->private_devices,
                .private_network = needs_sandboxing && exec_needs_network_namespace(context),
                .private_ipc = needs_sandboxing && exec_needs_ipc_namespace(context),
                .private_pids = needs_sandboxing && exec_needs_pid_namespace(context, params) ? context->private_pids : PRIVATE_PIDS_NO,
                .private_tmp = needs_sandboxing ? context->private_tmp : PRIVATE_TMP_NO,
                .private_var_tmp = needs_sandboxing ? context->private_var_tmp : PRIVATE_TMP_NO,
 
                .mount_apivfs = needs_sandboxing && exec_context_get_effective_mount_apivfs(context),
                .bind_log_sockets = needs_sandboxing && exec_context_get_effective_bind_log_sockets(context),
 
                /* If NNP is on, we can turn on MS_NOSUID, since it won't have any effect anymore. */
                .mount_nosuid = needs_sandboxing && context->no_new_privileges && !mac_selinux_use(),
 
                .protect_home = needs_sandboxing ? context->protect_home : PROTECT_HOME_NO,
                .protect_hostname = needs_sandboxing ? context->protect_hostname : PROTECT_HOSTNAME_NO,
                .protect_system = needs_sandboxing ? context->protect_system : PROTECT_SYSTEM_NO,
                .protect_proc = needs_sandboxing ? context->protect_proc : PROTECT_PROC_DEFAULT,
                .proc_subset = needs_sandboxing ? context->proc_subset : PROC_SUBSET_ALL,
                .private_bpf = needs_sandboxing ? context->private_bpf : PRIVATE_BPF_NO,
                .private_users = needs_sandboxing ? context->private_users : PRIVATE_USERS_NO,
 
                .bpffs_pidref = bpffs_pidref,
                .bpffs_socket_fd = bpffs_socket_fd,
                .bpffs_errno_pipe = bpffs_errno_pipe,
 
                .mountfsd_link = mountfsd_link,
        };
 
        r = setup_namespace(&parameters, reterr_path);
        /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
         * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
         * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
         * completely different execution environment. */
        if (r == -ENOANO) {
                if (insist_on_sandboxing(
                                    context,
                                    rootfs,
                                    bind_mounts,
                                    n_bind_mounts))
                        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
                                               "Failed to set up namespace, and refusing to continue since "
                                               "the selected namespacing options alter mount environment non-trivially.\n"
                                               "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, root mstack: %s, dynamic user: %s",
                                               n_bind_mounts,
                                               context->n_temporary_filesystems,
                                               yes_no(rootfs->directory_fd >= 0),
                                               yes_no(rootfs->image_fd >= 0),
                                               yes_no(!!rootfs->mstack_loaded),
                                               yes_no(context->dynamic_user));
 
                log_debug("Failed to set up namespace, assuming containerized execution and ignoring.");
                return 0;
        }
 
        return r;
}
 
static int apply_working_directory(
                const ExecContext *context,
                const ExecParameters *params,
                ExecRuntime *runtime,
                const char *pwent_home, /* may be NULL */
                char * const *env) {    /* can be NULL */
 
        const char *wd;
        int r;
 
        assert(context);
        assert(params);
        assert(runtime);
 
        if (context->working_directory_home) {
                /* Preferably use the data from $HOME, in case it was updated by a PAM module */
                wd = strv_env_get(env, "HOME");
                if (!wd) {
                        /* If that's not available, use the data from the struct passwd entry: */
                        if (!pwent_home)
                                return -ENXIO;
 
                        wd = pwent_home;
                }
        } else
                wd = empty_to_root(context->working_directory);
 
        if (params->flags & EXEC_APPLY_CHROOT)
                r = RET_NERRNO(chdir(wd));
        else {
                _cleanup_close_ int dfd = -EBADF;
 
                r = chase(wd,
                          runtime->ephemeral_copy ?: context->root_directory,
                          CHASE_PREFIX_ROOT|CHASE_TRIGGER_AUTOFS,
                          /* ret_path= */ NULL,
                          &dfd);
                if (r >= 0)
                        r = RET_NERRNO(fchdir(dfd));
        }
        return context->working_directory_missing_ok ? 0 : r;
}
 
static int apply_root_directory(
                const ExecContext *context,
                const ExecParameters *params,
                ExecRuntime *runtime,
                const bool needs_mount_ns,
                int *exit_status) {
 
        assert(context);
        assert(params);
        assert(runtime);
        assert(exit_status);
 
        if (params->flags & EXEC_APPLY_CHROOT)
                if (!needs_mount_ns && context->root_directory) {
                        if (chroot(runtime->ephemeral_copy ?: context->root_directory) < 0) {
                                *exit_status = EXIT_CHROOT;
                                return -errno;
                        }
 
                        /* chroot(2) changes only the process root, not cwd. Move cwd into the new root
                         * immediately so that a subsequent apply_working_directory() failure that is
                         * silently ignored via working_directory_missing_ok cannot leave cwd pointing
                         * at a pre-chroot dentry outside the new root. */
                        if (chdir("/") < 0) {
                                *exit_status = EXIT_CHROOT;
                                return -errno;
                        }
                }
 
        return 0;
}
 
static int setup_keyring(
                const ExecContext *context,
                const ExecParameters *p,
                uid_t uid,
                gid_t gid) {
 
        key_serial_t keyring;
        int r = 0;
        uid_t saved_uid;
        gid_t saved_gid;
 
        assert(context);
        assert(p);
 
        /* Let's set up a new per-service "session" kernel keyring for each system service. This has the benefit that
         * each service runs with its own keyring shared among all processes of the service, but with no hook-up beyond
         * that scope, and in particular no link to the per-UID keyring. If we don't do this the keyring will be
         * automatically created on-demand and then linked to the per-UID keyring, by the kernel. The kernel's built-in
         * on-demand behaviour is very appropriate for login users, but probably not so much for system services, where
         * UIDs are not necessarily specific to a service but reused (at least in the case of UID 0). */
 
        if (context->keyring_mode == EXEC_KEYRING_INHERIT)
                return 0;
 
        /* Acquiring a reference to the user keyring is nasty. We briefly change identity in order to get things set up
         * properly by the kernel. If we don't do that then we can't create it atomically, and that sucks for parallel
         * execution. This mimics what pam_keyinit does, too. Setting up session keyring, to be owned by the right user
         * & group is just as nasty as acquiring a reference to the user keyring. */
 
        saved_uid = getuid();
        saved_gid = getgid();
 
        if (gid_is_valid(gid) && gid != saved_gid) {
                if (setregid(gid, -1) < 0)
                        return log_error_errno(errno, "Failed to change GID for user keyring: %m");
        }
 
        if (uid_is_valid(uid) && uid != saved_uid) {
                if (setreuid(uid, -1) < 0) {
                        r = log_error_errno(errno, "Failed to change UID for user keyring: %m");
                        goto out;
                }
        }
 
        keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
        if (keyring == -1) {
                if (errno == ENOSYS)
                        log_debug_errno(errno, "Kernel keyring not supported, ignoring.");
                else if (ERRNO_IS_PRIVILEGE(errno))
                        log_debug_errno(errno, "Kernel keyring access prohibited, ignoring.");
                else if (errno == EDQUOT)
                        log_debug_errno(errno, "Out of kernel keyrings to allocate, ignoring.");
                else
                        r = log_error_errno(errno, "Setting up kernel keyring failed: %m");
 
                goto out;
        }
 
        /* When requested link the user keyring into the session keyring. */
        if (context->keyring_mode == EXEC_KEYRING_SHARED) {
 
                if (keyctl(KEYCTL_LINK,
                           KEY_SPEC_USER_KEYRING,
                           KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
                        r = log_error_errno(errno, "Failed to link user keyring into session keyring: %m");
                        goto out;
                }
        }
 
        /* Restore uid/gid back */
        if (uid_is_valid(uid) && uid != saved_uid) {
                if (setreuid(saved_uid, -1) < 0) {
                        r = log_error_errno(errno, "Failed to change UID back for user keyring: %m");
                        goto out;
                }
        }
 
        if (gid_is_valid(gid) && gid != saved_gid) {
                if (setregid(saved_gid, -1) < 0)
                        return log_error_errno(errno, "Failed to change GID back for user keyring: %m");
        }
 
        /* Populate the keyring with the invocation ID by default, as original saved_uid. */
        if (!sd_id128_is_null(p->invocation_id)) {
                key_serial_t key;
 
                key = add_key("user",
                              "invocation_id",
                              &p->invocation_id,
                              sizeof(p->invocation_id),
                              KEY_SPEC_SESSION_KEYRING);
                if (key == -1)
                        log_debug_errno(errno, "Failed to add invocation ID to keyring, ignoring: %m");
                else {
                        if (keyctl(KEYCTL_SETPERM, key,
                                   KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
                                   KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
                                r = log_error_errno(errno, "Failed to restrict invocation ID permission: %m");
                }
        }
 
out:
        /* Revert back uid & gid for the last time, and exit */
        /* no extra logging, as only the first already reported error matters */
        if (getuid() != saved_uid)
                (void) setreuid(saved_uid, -1);
 
        if (getgid() != saved_gid)
                (void) setregid(saved_gid, -1);
 
        return r;
}
 
#define FD_PAIR_CONDITION(cond, pair)                           \
        (cond) ? pair[0] : -EBADF, (cond) ? pair[1] : -EBADF
 
#define FD_PAIR(pair) FD_PAIR_CONDITION(true, pair)
 
static int close_remaining_fds(
                const ExecParameters *params,
                const ExecRuntime *runtime,
                int socket_fd,
                const int fds[],
                size_t n_fds) {
 
        assert(params);
        assert(runtime);
        assert(fds || n_fds == 0);
 
        /* fds listed here shall be closed before second close_all_fds() call to avoid double close! */
        int static_fds[] = {
                params->stdin_fd, params->stdout_fd, params->stderr_fd,
                socket_fd,
                FD_PAIR(runtime->ephemeral_storage_socket),
                FD_PAIR_CONDITION(runtime->shared, runtime->shared->userns_storage_socket),
                FD_PAIR_CONDITION(runtime->shared, runtime->shared->netns_storage_socket),
                FD_PAIR_CONDITION(runtime->shared, runtime->shared->ipcns_storage_socket),
                FD_PAIR_CONDITION(runtime->dynamic_creds && runtime->dynamic_creds->user,
                                  runtime->dynamic_creds->user->storage_socket),
                FD_PAIR_CONDITION(runtime->dynamic_creds && runtime->dynamic_creds->group,
                                  runtime->dynamic_creds->group->storage_socket),
                params->user_lookup_fd,
                params->pidref_transport_fd,
        };
 
        _cleanup_free_ int *accum_fds = NULL;
        if (n_fds > 0) {
                accum_fds = new(int, ELEMENTSOF(static_fds) + n_fds);
                if (!accum_fds)
                        return -ENOMEM;
 
                memcpy(mempcpy_typesafe(accum_fds, static_fds, ELEMENTSOF(static_fds)), fds, sizeof(int) * n_fds);
        }
 
        return close_all_fds(accum_fds ?: static_fds, ELEMENTSOF(static_fds) + n_fds);
}
 
static int send_user_lookup(
                const char *unit_id,
                int user_lookup_fd,
                uid_t uid,
                gid_t gid) {
 
        assert(unit_id);
 
        /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
         * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
         * specified. */
 
        if (user_lookup_fd < 0)
                return 0;
 
        if (!uid_is_valid(uid) && !gid_is_valid(gid))
                return 0;
 
        if (writev(user_lookup_fd,
               (struct iovec[]) {
                           IOVEC_MAKE(&uid, sizeof(uid)),
                           IOVEC_MAKE(&gid, sizeof(gid)),
                           IOVEC_MAKE_STRING(unit_id) }, 3) < 0)
                return -errno;
 
        return 0;
}
 
static int acquire_home(const ExecContext *c, char **home) {
        assert(c);
        assert(home);
 
        /* If WorkingDirectory=~ is set, try to acquire a usable home directory. */
 
        if (*home) /* Already acquired from get_user_creds()? */
                return 0;
 
        if (!c->working_directory_home)
                return 0;
 
        if (c->dynamic_user || (c->user && is_this_me(c->user) <= 0))
                return -EADDRNOTAVAIL;
 
        return get_home_dir(home);
}
 
static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
        _cleanup_strv_free_ char ** list = NULL;
        int r;
 
        assert(c);
        assert(p);
        assert(ret);
 
        assert(c->dynamic_user);
 
        /* Compile a list of paths that it might make sense to read the owning UID from to use as initial candidate for
         * dynamic UID allocation, in order to save us from doing costly recursive chown()s of the special
         * directories. */
 
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
 
                if (!EXEC_DIRECTORY_TYPE_SHALL_CHOWN(t))
                        continue;
 
                if (!p->prefix[t])
                        continue;
 
                for (size_t i = 0; i < c->directories[t].n_items; i++) {
                        char *e;
 
                        if (exec_directory_is_private(c, t))
                                e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
                        else
                                e = path_join(p->prefix[t], c->directories[t].items[i].path);
                        if (!e)
                                return -ENOMEM;
 
                        r = strv_consume(&list, e);
                        if (r < 0)
                                return r;
                }
        }
 
        *ret = TAKE_PTR(list);
 
        return 0;
}
 
static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
        int r;
 
        assert(c);
        assert(ret);
 
        if (!c->numa_policy.nodes.set) {
                log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
                *ret = (CPUSet) {};
                return 0;
        }
 
        _cleanup_(cpu_set_done) CPUSet s = {};
        r = numa_to_cpu_set(&c->numa_policy, &s);
        if (r < 0)
                return r;
 
        *ret = TAKE_STRUCT(s);
        return 0;
}
 
static int add_shifted_fd(int **fds, size_t *n_fds, int *fd) {
        int r;
 
        assert(fds);
        assert(n_fds);
        assert(fd);
 
        if (*fd < 0)
               return 0;
 
        if (*fd < 3 + (int) *n_fds) {
                /* Let's move the fd up, so that it's outside of the fd range we will use to store
                 * the fds we pass to the process (or which are closed only during execve). */
 
                r = fcntl(*fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
                if (r < 0)
                        return -errno;
 
                close_and_replace(*fd, r);
        }
 
        if (!GREEDY_REALLOC(*fds, *n_fds + 1))
                return -ENOMEM;
 
        (*fds)[(*n_fds)++] = *fd;
        return 1;
}
 
static int connect_unix_harder(const OpenFile *of, int ofd) {
        static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
 
        union sockaddr_union addr = {
                .un.sun_family = AF_UNIX,
        };
        socklen_t sa_len;
        int r;
 
        assert(of);
        assert(ofd >= 0);
 
        r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
        if (r < 0)
                return log_debug_errno(r, "Failed to set sockaddr for '%s': %m", of->path);
        sa_len = r;
 
        FOREACH_ELEMENT(i, socket_types) {
                _cleanup_close_ int fd = -EBADF;
 
                fd = socket(AF_UNIX, *i|SOCK_CLOEXEC, 0);
                if (fd < 0)
                        return log_debug_errno(errno, "Failed to create socket for '%s': %m", of->path);
 
                r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
                if (r >= 0)
                        return TAKE_FD(fd);
                if (r != -EPROTOTYPE)
                        return log_debug_errno(r, "Failed to connect to socket for '%s': %m", of->path);
        }
 
        return log_debug_errno(SYNTHETIC_ERRNO(EPROTOTYPE), "No suitable socket type to connect to socket '%s'.", of->path);
}
 
static int get_open_file_fd(const OpenFile *of) {
        _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
        struct stat st;
 
        assert(of);
 
        ofd = open(of->path, O_PATH | O_CLOEXEC);
        if (ofd < 0)
                return log_debug_errno(errno, "Failed to open '%s' as O_PATH: %m", of->path);
 
        if (fstat(ofd, &st) < 0)
                return log_debug_errno( errno, "Failed to stat '%s': %m", of->path);
 
        if (S_ISSOCK(st.st_mode)) {
                fd = connect_unix_harder(of, ofd);
                if (fd < 0)
                        return fd;
 
                if (FLAGS_SET(of->flags, OPENFILE_READ_ONLY) && shutdown(fd, SHUT_WR) < 0)
                        return log_debug_errno(errno, "Failed to shutdown send for socket '%s': %m", of->path);
 
                log_debug("Opened socket '%s' as fd %d.", of->path, fd);
        } else {
                int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
                if (FLAGS_SET(of->flags, OPENFILE_APPEND))
                        flags |= O_APPEND;
                else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
                        flags |= O_TRUNC;
 
                fd = fd_reopen(ofd, flags|O_NOCTTY|O_CLOEXEC);
                if (fd < 0)
                        return log_debug_errno(fd, "Failed to reopen file '%s': %m", of->path);
 
                log_debug("Opened file '%s' as fd %d.", of->path, fd);
        }
 
        return TAKE_FD(fd);
}
 
static int collect_open_file_fds(ExecParameters *p) {
        assert(p);
 
        LIST_FOREACH(open_files, of, p->open_files) {
                _cleanup_close_ int fd = -EBADF;
 
                fd = get_open_file_fd(of);
                if (fd < 0) {
                        if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
                                log_full_errno(fd == -ENOENT || ERRNO_IS_NEG_PRIVILEGE(fd) ? LOG_DEBUG : LOG_WARNING,
                                               fd,
                                               "Failed to get OpenFile= file descriptor for '%s', ignoring: %m",
                                               of->path);
                                continue;
                        }
 
                        return log_error_errno(fd, "Failed to get OpenFile= file descriptor for '%s': %m", of->path);
                }
 
                if (!GREEDY_REALLOC(p->fds, p->n_socket_fds + p->n_stashed_fds + 1))
                        return log_oom();
 
                if (strv_extend(&p->fd_names, of->fdname) < 0)
                        return log_oom();
 
                p->fds[p->n_socket_fds + p->n_stashed_fds++] = TAKE_FD(fd);
        }
 
        return 0;
}
 
static void log_command_line(
                const ExecContext *context,
                const ExecParameters *params,
                const char *msg,
                const char *executable,
                char **argv) {
 
        assert(context);
        assert(params);
        assert(msg);
        assert(executable);
        assert(argv);
 
        if (!DEBUG_LOGGING)
                return;
 
        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
 
        log_struct(LOG_DEBUG,
                   LOG_ITEM("EXECUTABLE=%s", executable),
                   LOG_EXEC_MESSAGE(params, "%s: %s", msg, strnull(cmdline)),
                   LOG_EXEC_INVOCATION_ID(params));
}
 
static bool exec_needs_cap_sys_admin(const ExecContext *context, const ExecParameters *params) {
        assert(context);
        assert(params);
 
        /* We only want to ever imply PrivateUsers= for user managers, as they're not expected to setuid() to
         * other users, unlike the system manager which needs all users to be around. */
        if (params->runtime_scope != RUNTIME_SCOPE_USER)
                return false;
 
        return context->private_users != PRIVATE_USERS_NO ||
               context->private_tmp != PRIVATE_TMP_NO || /* no need to check for private_var_tmp here, private_tmp is never demoted to "no" */
               context->private_devices ||
               context->private_network ||
               context->user_namespace_path ||
               context->network_namespace_path ||
               context->private_ipc ||
               context->ipc_namespace_path ||
               context->private_mounts > 0 ||
               context->mount_apivfs > 0 ||
               context->bind_log_sockets > 0 ||
               context->n_bind_mounts > 0 ||
               context->n_temporary_filesystems > 0 ||
               exec_context_with_rootfs_strict(context) ||
               !strv_isempty(context->extension_directories) ||
               context->n_mount_images > 0 ||
               context->n_extension_images > 0 ||
               context->protect_system != PROTECT_SYSTEM_NO ||
               context->protect_home != PROTECT_HOME_NO ||
               exec_needs_pid_namespace(context, params) ||
               context->protect_kernel_tunables ||
               context->protect_kernel_modules ||
               context->protect_kernel_logs ||
               exec_needs_cgroup_mount(context) ||
               context->protect_clock ||
               context->protect_hostname != PROTECT_HOSTNAME_NO ||
               !strv_isempty(context->read_write_paths) ||
               !strv_isempty(context->read_only_paths) ||
               !strv_isempty(context->inaccessible_paths) ||
               !strv_isempty(context->exec_paths) ||
               !strv_isempty(context->no_exec_paths) ||
               context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL;
}
 
static PrivateUsers exec_context_get_effective_private_users(
                const ExecContext *context,
                const ExecParameters *params) {
 
        assert(context);
        assert(params);
 
        if (context->private_users != PRIVATE_USERS_NO)
                return context->private_users;
 
        /* If any namespace is delegated with DelegateNamespaces=, always set up a user namespace. */
        if (context->delegate_namespaces != NAMESPACE_FLAGS_INITIAL)
                return PRIVATE_USERS_SELF;
 
        return PRIVATE_USERS_NO;
}
 
static bool exec_namespace_is_delegated(
                const ExecContext *context,
                const ExecParameters *params,
                bool have_cap_sys_admin,
                unsigned long namespace) {
 
        assert(context);
        assert(params);
        assert(namespace != CLONE_NEWUSER);
 
        /* If we need unprivileged private users, we've already unshared a user namespace by the time we call
         * setup_delegated_namespaces() for the first time so let's make sure we do all other namespace
         * unsharing in the first call to setup_delegated_namespaces() by returning false here. */
        if (!have_cap_sys_admin && exec_needs_cap_sys_admin(context, params))
                return false;
 
        if (context->delegate_namespaces == NAMESPACE_FLAGS_INITIAL)
                return params->runtime_scope == RUNTIME_SCOPE_USER;
 
        if (FLAGS_SET(context->delegate_namespaces, namespace))
                return true;
 
        /* Various namespaces imply mountns for private procfs/sysfs/cgroupfs instances, which means when
         * those are delegated mountns must be deferred too.
         *
         * The list should stay in sync with exec_needs_mount_namespace(). */
        if (namespace == CLONE_NEWNS)
                return context->delegate_namespaces & (CLONE_NEWPID|CLONE_NEWCGROUP|CLONE_NEWNET);
 
        return false;
}
 
static int setup_delegated_namespaces(
                const ExecContext *context,
                ExecParameters *params,
                const ExecRuntime *runtime,
                const PinnedResource *rootfs,
                bool delegate,
                char *const *pressure_path,
                uid_t uid,
                gid_t gid,
                const ExecCommand *command,
                bool needs_sandboxing,
                bool have_cap_sys_admin,
                PidRef *bpffs_pidref,
                int bpffs_socket_fd,
                int bpffs_errno_pipe,
                sd_varlink *mountfsd_link, /* may be NULL */
                int *keep_parent_fd,
                int *reterr_exit_status) {
 
        int r;
 
        /* This function is called twice, once before unsharing the user namespace, and once after unsharing
         * the user namespace. When called before unsharing the user namespace, "delegate" is set to "false".
         * When called after unsharing the user namespace, "delegate" is set to "true". The net effect is
         * that all namespaces that should not be delegated are unshared when this function is called the
         * first time and all namespaces that should be delegated are unshared when this function is called
         * the second time. */
 
        assert(context);
        assert(params);
        assert(runtime);
        assert(rootfs);
        assert(pressure_path);
        assert(command);
        assert(bpffs_pidref);
        assert(keep_parent_fd);
        assert(reterr_exit_status);
 
        if (exec_needs_network_namespace(context) &&
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNET) == delegate &&
            runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
 
                /* Try to enable network namespacing if network namespacing is available and we have
                 * CAP_NET_ADMIN in the current user namespace (either the system manager one or the unit's
                 * own user namespace). We need CAP_NET_ADMIN to be able to configure the loopback device in
                 * the new network namespace. And if we don't have that, then we could only create a network
                 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
                if (namespace_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
                        r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
                                log_notice_errno(r, "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
                        else if (r < 0) {
                                *reterr_exit_status = EXIT_NETWORK;
                                return log_error_errno(r, "Failed to set up network namespacing: %m");
                        } else
                                log_debug("Set up %snetwork namespace", delegate ? "delegated " : "");
                } else if (context->network_namespace_path) {
                        *reterr_exit_status = EXIT_NETWORK;
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "NetworkNamespacePath= is not supported, refusing.");
                } else
                        log_notice("PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
        }
 
        if (exec_needs_ipc_namespace(context) &&
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWIPC) == delegate &&
            runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
 
                if (namespace_type_supported(NAMESPACE_IPC)) {
                        r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
                        if (ERRNO_IS_NEG_PRIVILEGE(r))
                                log_warning_errno(r, "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
                        else if (r < 0) {
                                *reterr_exit_status = EXIT_NAMESPACE;
                                return log_error_errno(r, "Failed to set up IPC namespacing: %m");
                        } else
                                log_debug("Set up %sIPC namespace", delegate ? "delegated " : "");
                } else if (context->ipc_namespace_path) {
                        *reterr_exit_status = EXIT_NAMESPACE;
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "IPCNamespacePath= is not supported, refusing.");
                } else
                        log_warning("PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
        }
 
        if (needs_sandboxing && exec_needs_cgroup_namespace(context) &&
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWCGROUP) == delegate) {
                if (unshare(CLONE_NEWCGROUP) < 0) {
                        *reterr_exit_status = EXIT_NAMESPACE;
                        return log_error_errno(errno, "Failed to set up cgroup namespacing: %m");
                }
 
                log_debug("Set up %scgroup namespace", delegate ? "delegated " : "");
        }
 
        /* Unshare a new PID namespace before setting up mounts to ensure /proc/ is mounted with only processes in PID namespace visible.
         * Note PrivatePIDs=yes implies MountAPIVFS=yes so we'll always ensure procfs is remounted. */
        if (needs_sandboxing && exec_needs_pid_namespace(context, params) &&
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWPID) == delegate) {
                if (params->pidref_transport_fd < 0) {
                        *reterr_exit_status = EXIT_NAMESPACE;
                        return log_error_errno(SYNTHETIC_ERRNO(ENOTCONN), "PidRef socket is not set up.");
                }
 
                /* If we had CAP_SYS_ADMIN prior to joining the user namespace, then we are privileged and don't need
                 * to check if we can mount /proc/.
                 *
                 * We need to check prior to entering the user namespace because if we're running unprivileged or in a
                 * system without CAP_SYS_ADMIN, then we can have CAP_SYS_ADMIN in the current user namespace but not
                 * once we unshare a mount namespace. */
                if (!have_cap_sys_admin || delegate) {
                        r = can_mount_proc();
                        if (r < 0) {
                                *reterr_exit_status = EXIT_NAMESPACE;
                                return log_error_errno(r, "Failed to detect if /proc/ can be remounted: %m");
                        }
                        if (r == 0) {
                                *reterr_exit_status = EXIT_NAMESPACE;
                                return log_error_errno(SYNTHETIC_ERRNO(EPERM),
                                                       "PrivatePIDs=yes is configured, but /proc/ cannot be re-mounted due to lack of privileges, refusing.");
                        }
                }
 
                r = setup_private_pids(context, params, mountfsd_link ? keep_parent_fd : NULL);
                if (r < 0) {
                        *reterr_exit_status = EXIT_NAMESPACE;
                        return log_error_errno(r, "Failed to set up pid namespace: %m");
                }
 
                log_debug("Set up %spid namespace", delegate ? "delegated " : "");
        }
 
        /* If PrivatePIDs= yes is configured, we're now running as pid 1 in a pid namespace! */
 
        if (exec_needs_mount_namespace(context, params) &&
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWNS) == delegate) {
                _cleanup_free_ char *error_path = NULL;
 
                r = apply_mount_namespace(
                                command->flags,
                                context,
                                params,
                                runtime,
                                rootfs,
                                pressure_path,
                                needs_sandboxing,
                                uid,
                                gid,
                                bpffs_pidref,
                                bpffs_socket_fd,
                                bpffs_errno_pipe,
                                mountfsd_link,
                                &error_path);
                if (r < 0) {
                        *reterr_exit_status = EXIT_NAMESPACE;
                        return log_error_errno(r, "Failed to set up mount namespacing%s%s: %m",
                                               error_path ? ": " : "", strempty(error_path));
                }
 
                log_debug("Set up %smount namespace", delegate ? "delegated " : "");
        }
 
        if (needs_sandboxing &&
            exec_namespace_is_delegated(context, params, have_cap_sys_admin, CLONE_NEWUTS) == delegate) {
                r = apply_protect_hostname(context, params, reterr_exit_status);
                if (r < 0)
                        return r;
                if (r > 0)
                        log_debug("Set up %sUTS namespace", delegate ? "delegated " : "");
        }
 
        return 0;
}
 
static int set_memory_thp(ExecMemoryTHP thp) {
        int r;
 
        switch (thp) {
 
        case EXEC_MEMORY_THP_INHERIT:
                return 0;
 
        case EXEC_MEMORY_THP_DISABLE:
                r = prctl_safe(PR_SET_THP_DISABLE, 1, 0, 0, 0);
                break;
 
        case EXEC_MEMORY_THP_MADVISE:
                r = prctl_safe(PR_SET_THP_DISABLE, 1, PR_THP_DISABLE_EXCEPT_ADVISED, 0, 0);
                break;
 
        case EXEC_MEMORY_THP_SYSTEM:
                r = prctl_safe(PR_SET_THP_DISABLE, 0, 0, 0, 0);
                break;
 
        default:
                assert_not_reached();
        }
 
        return r == -EINVAL ? -EOPNOTSUPP : r;
}
 
static bool exec_context_shall_confirm_spawn(const ExecContext *context) {
        assert(context);
 
        if (confirm_spawn_disabled())
                return false;
 
        /* For some reasons units remaining in the same process group
         * as PID 1 fail to acquire the console even if it's not used
         * by any process. So skip the confirmation question for them. */
        return !context->same_pgrp;
}
 
static int exec_context_named_iofds(
                const ExecContext *c,
                const ExecParameters *p,
                int named_iofds[static 3]) {
 
        const char *stdio_fdname[3];
        size_t targets;
 
        assert(c);
        assert(p);
        assert(named_iofds);
 
        targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
                  (c->std_output == EXEC_OUTPUT_NAMED_FD) +
                  (c->std_error == EXEC_OUTPUT_NAMED_FD);
 
        for (size_t i = 0; i < 3; i++)
                stdio_fdname[i] = exec_context_fdname(c, i);
 
        /* Note that socket fds are always placed at the beginning of the fds array, no need for extra
         * manipulation. */
        for (size_t i = 0; i < p->n_socket_fds && targets > 0; i++) {
                if (named_iofds[STDIN_FILENO] < 0 &&
                    c->std_input == EXEC_INPUT_NAMED_FD &&
                    streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
 
                        named_iofds[STDIN_FILENO] = p->fds[i];
                        targets--;
                        continue;
                }
 
                /* Allow stdout and stderr to use the same named fd */
 
                if (named_iofds[STDOUT_FILENO] < 0 &&
                    c->std_output == EXEC_OUTPUT_NAMED_FD &&
                    streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
 
                        named_iofds[STDOUT_FILENO] = p->fds[i];
                        targets--;
                }
 
                if (named_iofds[STDERR_FILENO] < 0 &&
                    c->std_error == EXEC_OUTPUT_NAMED_FD &&
                    streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
 
                        named_iofds[STDERR_FILENO] = p->fds[i];
                        targets--;
                }
        }
 
        return targets == 0 ? 0 : -ENOENT;
}
 
static void exec_shared_runtime_close(ExecSharedRuntime *shared) {
        if (!shared)
                return;
 
        safe_close_pair(shared->userns_storage_socket);
        safe_close_pair(shared->netns_storage_socket);
        safe_close_pair(shared->ipcns_storage_socket);
}
 
static void exec_runtime_close(ExecRuntime *rt) {
        if (!rt)
                return;