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 1001–2000 of 6,799

                return 0;
 
        r = prctl_safe(PR_SET_SECUREBITS, applied, 0, 0, 0);
        if (r < 0)
                return r;
 
        return 1;
}
 
static int enforce_user(
                const ExecContext *context,
                uid_t uid,
                uint64_t capability_ambient_set) {
 
        int r;
 
        assert(context);
 
        if (!uid_is_valid(uid))
                return 0;
 
        /* Sets (but doesn't look up) the UIS and makes sure we keep the capabilities while doing so. For
         * setting secure bits the capability CAP_SETPCAP is required, so we also need keep-caps in this
         * case. */
 
        if ((capability_ambient_set != 0 || context->secure_bits != 0) && uid != 0) {
 
                /* First step: If we need to keep capabilities but drop privileges we need to make sure we
                 * keep our caps, while we drop privileges. Add KEEP_CAPS to the securebits */
                r = set_securebits(1U << SECURE_KEEP_CAPS, 0);
                if (r < 0)
                        return r;
        }
 
        /* Second step: actually set the uids */
        if (setresuid(uid, uid, uid) < 0)
                return -errno;
 
        /* At this point we should have all necessary capabilities but are otherwise a normal user. However,
         * the caps might got corrupted due to the setresuid() so we need clean them up later. This is done
         * outside of this call. */
        return 0;
}
 
#if HAVE_PAM
 
static void pam_response_done(struct pam_response *response) {
        erase_and_free(ASSERT_PTR(response)->resp);
}
 
static DEFINE_ARRAY_FREE_FUNC(pam_response_free_array, struct pam_response, pam_response_done);
 
typedef struct AskPasswordConvData {
        const ExecContext *context;
        const ExecParameters *params;
} AskPasswordConvData;
 
static int ask_password_conv(
                int num_msg,
                const struct pam_message *msg[],
                struct pam_response **ret,
                void *userdata) {
 
        AskPasswordConvData *data = ASSERT_PTR(userdata);
        bool set_credential_env_var = false;
        int r;
 
        assert(num_msg >= 0);
        assert(msg);
        assert(data->context);
        assert(data->params);
        assert(ret);
 
        size_t n = num_msg;
        struct pam_response *responses = new0(struct pam_response, n);
        if (!responses)
                return PAM_BUF_ERR;
        CLEANUP_ARRAY(responses, n, pam_response_free_array);
 
        for (size_t i = 0; i < n; i++) {
                const struct pam_message *mi = *msg + i;
 
                switch (mi->msg_style) {
 
                case PAM_PROMPT_ECHO_ON:
                case PAM_PROMPT_ECHO_OFF: {
 
                        /* Locally set the $CREDENTIALS_DIRECTORY to the credentials directory we just populated */
                        if (!set_credential_env_var) {
                                _cleanup_free_ char *creds_dir = NULL;
                                r = exec_context_get_credential_directory(data->context, data->params, data->params->unit_id, &creds_dir);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to determine credentials directory: %m");
 
                                if (creds_dir) {
                                        if (setenv("CREDENTIALS_DIRECTORY", creds_dir, /* overwrite= */ true) < 0)
                                                return log_error_errno(errno, "Failed to set $CREDENTIALS_DIRECTORY: %m");
                                } else
                                        (void) unsetenv("CREDENTIALS_DIRECTORY");
 
                                set_credential_env_var = true;
                        }
 
                        _cleanup_free_ char *credential_name = strjoin("pam.authtok.", data->context->pam_name);
                        if (!credential_name)
                                return log_oom();
 
                        AskPasswordRequest req = {
                                .message = mi->msg,
                                .credential = credential_name,
                                .tty_fd = -EBADF,
                                .hup_fd = -EBADF,
                                .until = usec_add(now(CLOCK_MONOTONIC), 15 * USEC_PER_SEC),
                        };
 
                        _cleanup_strv_free_erase_ char **acquired = NULL;
                        r = ask_password_auto(
                                        &req,
                                        ASK_PASSWORD_ACCEPT_CACHED|
                                        ASK_PASSWORD_NO_TTY|
                                        (mi->msg_style == PAM_PROMPT_ECHO_ON ? ASK_PASSWORD_ECHO : 0),
                                        &acquired);
                        if (r < 0) {
                                log_error_errno(r, "Failed to query for password: %m");
                                return PAM_CONV_ERR;
                        }
 
                        responses[i].resp = strdup(ASSERT_PTR(acquired[0]));
                        if (!responses[i].resp) {
                                log_oom();
                                return PAM_BUF_ERR;
                        }
                        break;
                }
 
                case PAM_ERROR_MSG:
                        log_error("PAM: %s", mi->msg);
                        break;
 
                case PAM_TEXT_INFO:
                        log_info("PAM: %s", mi->msg);
                        break;
 
                default:
                        return PAM_CONV_ERR;
                }
        }
 
        *ret = TAKE_PTR(responses);
        n = 0;
 
        return PAM_SUCCESS;
}
 
static int pam_close_session_and_delete_credentials(pam_handle_t *pamh, int flags) {
        int r, s;
 
        assert(pamh);
 
        r = sym_pam_close_session(pamh, flags);
        if (r != PAM_SUCCESS)
                pam_syslog_pam_error(pamh, LOG_DEBUG, r, "pam_close_session() failed: @PAMERR@");
 
        s = sym_pam_setcred(pamh, PAM_DELETE_CRED | flags);
        if (s != PAM_SUCCESS)
                pam_syslog_pam_error(pamh, LOG_DEBUG, s, "pam_setcred(PAM_DELETE_CRED) failed: @PAMERR@");
 
        return r != PAM_SUCCESS ? r : s;
}
#endif
 
static int attach_to_subcgroup(
                const ExecContext *context,
                const CGroupContext *cgroup_context,
                const ExecParameters *params,
                const char *prefix) { /* may be NULL */
 
        _cleanup_free_ char *subgroup = NULL;
        int r;
 
        assert(context);
        assert(cgroup_context);
        assert(params);
 
        /* If we're a control process that needs a subgroup, we've already been spawned into it as otherwise
         * we'd violate the "no inner processes" rule, so no need to do anything. */
        if (exec_params_needs_control_subcgroup(params))
                return 0;
 
        r = exec_params_get_cgroup_path(params, cgroup_context, prefix, &subgroup);
        if (r < 0)
                return log_error_errno(r, "Failed to acquire cgroup path: %m");
        /* No subgroup required? Then there's nothing to do. */
        if (r == 0)
                return 0;
 
        r = cg_attach(subgroup, 0);
        if (r == -EUCLEAN)
                return log_error_errno(r,
                                "Failed to attach process " PID_FMT " to cgroup '%s', "
                                "because the cgroup or one of its parents or "
                                "siblings is in the threaded mode.",
                                getpid_cached(), subgroup);
        if (r < 0)
                return log_error_errno(r,
                                "Failed to attach process " PID_FMT " to cgroup %s: %m",
                                getpid_cached(), subgroup);
 
        return 0;
}
 
#if HAVE_PAM
static int exec_context_get_tty_for_pam(const ExecContext *context, char **ret) {
        _cleanup_free_ char *tty = NULL;
        int r;
 
        assert(context);
        assert(ret);
 
        /* First, let's get TTY from STDIN. We may already set STDIN in setup_output(). */
        r = getttyname_malloc(STDIN_FILENO, &tty);
        if (r == -ENOMEM)
                return log_oom_debug();
        if (r >= 0) {
                _cleanup_free_ char *q = path_join("/dev/", tty);
                if (!q)
                        return log_oom_debug();
 
                log_debug("Got TTY '%s' from STDIN.", q);
                *ret = TAKE_PTR(q);
                return 1;
        }
 
        /* Do not implicitly configure TTY unless TTYPath= or StandardInput=tty is specified. See issue
         * #39334. Note, exec_context_tty_path() returns "/dev/console" when TTYPath= is unspecified, hence
         * explicitly check context->tty_path here. */
        if (!context->tty_path && !exec_input_is_terminal(context->std_input)) {
                *ret = NULL;
                return 0;
        }
 
        /* Next, let's try to use the TTY specified in TTYPath=. */
        const char *t = exec_context_tty_path(context);
        if (!t) {
                *ret = NULL;
                return 0;
        }
 
        /* If /dev/console is specified, resolve it. */
        if (tty_is_console(t)) {
                r = resolve_dev_console(&tty);
                if (r < 0) {
                        log_debug_errno(r, "Failed to resolve /dev/console, ignoring: %m");
                        *ret = NULL;
                        return 0;
                }
 
                log_debug("Got TTY '%s' from /dev/console.", tty);
                *ret = TAKE_PTR(tty);
                return 1;
        }
 
        /* Otherwise, use the specified TTY as is. */
        if (path_startswith(t, "/dev/"))
                tty = strdup(t);
        else
                tty = path_join("/dev/", t);
        if (!tty)
                return log_oom_debug();
 
        log_debug("Got TTY '%s' from TTYPath= setting.", tty);
        *ret = TAKE_PTR(tty);
        return 1;
}
#endif
 
static int setup_pam(
                const ExecContext *context,
                const CGroupContext *cgroup_context,
                ExecParameters *params,
                const char *user,
                uid_t uid,
                gid_t gid,
                char ***env, /* updated on success */
                bool needs_sandboxing,
                int exec_fd) {
 
#if HAVE_PAM
        AskPasswordConvData conv_data = {
                .context = context,
                .params = params,
        };
 
        const struct pam_conv conv = {
                .conv = ask_password_conv,
                .appdata_ptr = &conv_data,
        };
 
        _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
        _cleanup_strv_free_ char **e = NULL;
        _cleanup_free_ char *tty = NULL;
        pam_handle_t *pamh = NULL;
        sigset_t old_ss;
        int pam_code = PAM_SUCCESS, r;
        bool close_session = false;
        pid_t parent_pid;
        int flags = 0;
 
        assert(context);
        assert(cgroup_context);
        assert(params);
        assert(user);
        assert(uid_is_valid(uid));
        assert(gid_is_valid(gid));
        assert(env);
 
        /* We set up PAM in the parent process, then fork. The child will then stay around until killed via
         * PR_GET_PDEATHSIG or systemd via the cgroup logic. It will then remove the PAM session again. The
         * parent process will exec() the actual daemon. We do things this way to ensure that the main PID of
         * the daemon is the one we initially fork()ed. */
 
        r = dlopen_libpam(LOG_ERR);
        if (r < 0)
                return r;
 
        r = barrier_create(&barrier);
        if (r < 0)
                goto fail;
 
        if (log_get_max_level() < LOG_DEBUG)
                flags |= PAM_SILENT;
 
        pam_code = sym_pam_start(context->pam_name, user, &conv, &pamh);
        if (pam_code != PAM_SUCCESS) {
                pamh = NULL;
                goto fail;
        }
 
        r = exec_context_get_tty_for_pam(context, &tty);
        if (r < 0)
                goto fail;
        if (r > 0) {
                pam_code = sym_pam_set_item(pamh, PAM_TTY, tty);
                if (pam_code != PAM_SUCCESS)
                        goto fail;
        }
 
        STRV_FOREACH(nv, *env) {
                pam_code = sym_pam_putenv(pamh, *nv);
                if (pam_code != PAM_SUCCESS)
                        goto fail;
        }
 
        pam_code = sym_pam_acct_mgmt(pamh, flags);
        if (pam_code != PAM_SUCCESS)
                goto fail;
 
        pam_code = sym_pam_setcred(pamh, PAM_ESTABLISH_CRED | flags);
        if (pam_code != PAM_SUCCESS)
                pam_syslog_pam_error(pamh, LOG_DEBUG, pam_code, "pam_setcred(PAM_ESTABLISH_CRED) failed, ignoring: @PAMERR@");
 
        pam_code = sym_pam_open_session(pamh, flags);
        if (pam_code != PAM_SUCCESS)
                goto fail;
 
        close_session = true;
 
        e = sym_pam_getenvlist(pamh);
        if (!e) {
                pam_code = PAM_BUF_ERR;
                goto fail;
        }
 
        /* Block SIGTERM, so that we know that it won't get lost in the child */
 
        assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM) >= 0);
 
        parent_pid = getpid_cached();
 
        r = pidref_safe_fork("(sd-pam)", /* flags= */ 0, /* ret= */ NULL);
        if (r < 0)
                goto fail;
        if (r == 0) {
                int ret = EXIT_PAM;
 
                if (needs_sandboxing && exec_needs_cgroup_namespace(context) && params->cgroup_path) {
                        /* Move PAM process into subgroup immediately if the main process hasn't been moved
                         * into the subgroup yet (when cgroup namespacing is enabled) and a subgroup is
                         * configured. */
                        r = attach_to_subcgroup(context, cgroup_context, params, params->cgroup_path);
                        if (r < 0)
                                return r;
                }
 
                /* The child's job is to reset the PAM session on termination */
                barrier_set_role(&barrier, BARRIER_CHILD);
 
                /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only
                 * those fds are open here that have been opened by PAM. */
                close_many(params->fds, params->n_socket_fds + params->n_stashed_fds);
 
                /* Also close the 'exec_fd' in the child, since the service manager waits for the EOF induced
                 * by the execve() to wait for completion, and if we'd keep the fd open here in the child
                 * we'd never signal completion. */
                exec_fd = safe_close(exec_fd);
 
                /* Drop privileges - we don't need any to pam_close_session and this will make
                 * PR_SET_PDEATHSIG work in most cases.  If this fails, ignore the error - but expect sd-pam
                 * threads to fail to exit normally */
 
                r = fully_set_uid_gid(uid, gid, /* supplementary_gids= */ NULL, /* n_supplementary_gids= */ 0);
                if (r < 0)
                        log_warning_errno(r, "Failed to drop privileges in sd-pam: %m");
 
                (void) ignore_signals(SIGPIPE);
 
                /* Wait until our parent died. This will only work if the above setresuid() succeeds,
                 * otherwise the kernel will not allow unprivileged parents kill their privileged children
                 * this way. We rely on the control groups kill logic to do the rest for us. */
                r = prctl_safe(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0);
                if (r < 0)
                        goto child_finish;
 
                /* Tell the parent that our setup is done. This is especially important regarding dropping
                 * privileges. Otherwise, unit setup might race against our setresuid(2) call.
                 *
                 * If the parent aborted, we'll detect this below, hence ignore return failure here. */
                (void) barrier_place(&barrier);
 
                /* Check if our parent process might already have died? */
                if (getppid() == parent_pid) {
                        sigset_t ss;
                        int sig;
 
                        assert_se(sigemptyset(&ss) >= 0);
                        assert_se(sigaddset(&ss, SIGTERM) >= 0);
 
                        assert_se(sigwait(&ss, &sig) == 0);
                        assert(sig == SIGTERM);
                }
 
                /* If our parent died we'll end the session */
                if (getppid() != parent_pid) {
                        pam_code = pam_close_session_and_delete_credentials(pamh, flags);
                        if (pam_code != PAM_SUCCESS)
                                goto child_finish;
                }
 
                ret = 0;
 
        child_finish:
                /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module
                 * know about this. See pam_end(3) */
                (void) sym_pam_end(pamh, pam_code | flags | PAM_DATA_SILENT);
                _exit(ret);
        }
 
        barrier_set_role(&barrier, BARRIER_PARENT);
 
        /* If the child was forked off successfully it will do all the cleanups, so forget about the handle
         * here. */
        pamh = NULL;
 
        /* Unblock SIGTERM again in the parent */
        assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
 
        /* We close the log explicitly here, since the PAM modules might have opened it, but we don't want
         * this fd around. */
        closelog();
 
        /* Synchronously wait for the child to initialize. We don't care for errors as we cannot
         * recover. However, warn loudly if it happens. */
        if (!barrier_place_and_sync(&barrier))
                log_error("PAM initialization failed");
 
        return strv_free_and_replace(*env, e);
 
fail:
        if (pam_code != PAM_SUCCESS) {
                pam_syslog_pam_error(pamh, LOG_ERR, pam_code, "PAM failed: @PAMERR@");
                r = -EPERM;  /* PAM errors do not map to errno */
        } else
                log_error_errno(r, "PAM failed: %m");
 
        if (pamh) {
                if (close_session)
                        pam_code = pam_close_session_and_delete_credentials(pamh, flags);
 
                (void) sym_pam_end(pamh, pam_code | flags);
        }
 
        closelog();
        return r;
#else
        return 0;
#endif
}
 
static void rename_process_from_path(const char *path) {
        int r;
 
        assert(path);
 
        _cleanup_free_ char *buf = NULL;
        r = path_extract_filename(path, &buf);
        if (r < 0) {
                log_debug_errno(r, "Failed to extract file name from '%s', ignoring: %m", path);
                return (void) rename_process("(...)");
        }
 
        size_t len = strlen(buf);
        char comm[TASK_COMM_LEN], *p = comm;
        *p++ = '(';
        strnpcpy(&p, TASK_COMM_LEN - 2, buf, len); /* strnpcpy() accounts for NUL byte internally */
        *p++ = ')';
        *p = '\0';
 
        size_t len_invocation = program_invocation_name ? strlen(program_invocation_name) : SIZE_MAX;
        _cleanup_free_ char *invocation = strjoin("(", buf + LESS_BY(len, len_invocation - 2), ")");
        if (!invocation)
                log_oom_debug();
 
        (void) rename_process_full(comm, invocation ?: comm);
}
 
static bool context_has_address_families(const ExecContext *c) {
        assert(c);
 
        return c->address_families_allow_list ||
                !set_isempty(c->address_families);
}
 
static bool context_has_syscall_filters(const ExecContext *c) {
        assert(c);
 
        return c->syscall_allow_list ||
                !hashmap_isempty(c->syscall_filter);
}
 
static bool context_has_syscall_logs(const ExecContext *c) {
        assert(c);
 
        return c->syscall_log_allow_list ||
                !hashmap_isempty(c->syscall_log);
}
 
static bool context_has_seccomp(const ExecContext *c) {
        assert(c);
 
        /* We need NNP if we have any form of seccomp and are unprivileged */
        return c->lock_personality ||
                c->memory_deny_write_execute ||
                c->private_devices ||
                c->protect_clock ||
                c->protect_hostname == PROTECT_HOSTNAME_YES ||
                c->protect_kernel_tunables ||
                c->protect_kernel_modules ||
                c->protect_kernel_logs ||
                context_has_address_families(c) ||
                exec_context_restrict_namespaces_set(c) ||
                c->restrict_realtime ||
                c->restrict_suid_sgid ||
                !set_isempty(c->syscall_archs) ||
                context_has_syscall_filters(c) ||
                context_has_syscall_logs(c);
}
 
static bool context_has_no_new_privileges(const ExecContext *c) {
        assert(c);
 
        if (c->no_new_privileges)
                return true;
 
        if (have_effective_cap(CAP_SYS_ADMIN) > 0) /* if we are privileged, we don't need NNP */
                return false;
 
        return context_has_seccomp(c);
}
 
#if HAVE_SECCOMP
 
static bool seccomp_allows_drop_privileges(const ExecContext *c) {
        void *id, *val;
        bool have_capget = false, have_capset = false, have_prctl = false;
 
        assert(c);
 
        /* No libseccomp, all is fine */
        if (dlopen_libseccomp(LOG_DEBUG) < 0)
                return true;
 
        /* No syscall filter, we are allowed to drop privileges */
        if (hashmap_isempty(c->syscall_filter))
                return true;
 
        HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) {
                _cleanup_free_ char *name = NULL;
 
                name = sym_seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
 
                if (streq(name, "capget"))
                        have_capget = true;
                else if (streq(name, "capset"))
                        have_capset = true;
                else if (streq(name, "prctl"))
                        have_prctl = true;
        }
 
        if (c->syscall_allow_list)
                return have_capget && have_capset && have_prctl;
        else
                return !(have_capget || have_capset || have_prctl);
}
 
static bool skip_seccomp_unavailable(const char *msg) {
        assert(msg);
 
        if (is_seccomp_available())
                return false;
 
        log_debug("SECCOMP features not detected in the kernel, skipping %s", msg);
        return true;
}
 
static int apply_syscall_filter(const ExecContext *c, const ExecParameters *p) {
        uint32_t negative_action, default_action, action;
        int r;
 
        assert(c);
        assert(p);
 
        if (!context_has_syscall_filters(c))
                return 0;
 
        if (skip_seccomp_unavailable("SystemCallFilter="))
                return 0;
 
        negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? SCMP_ACT_KILL_PROCESS : SCMP_ACT_ERRNO(c->syscall_errno);
 
        if (c->syscall_allow_list) {
                default_action = negative_action;
                action = SCMP_ACT_ALLOW;
        } else {
                default_action = SCMP_ACT_ALLOW;
                action = negative_action;
        }
 
        /* Sending over exec_fd or handoff_timestamp_fd requires write() syscall.
         *
         * Note: this mutates c->syscall_filter despite the 'const ExecContext *c' qualifier.
         * That is intentional and safe here because apply_syscall_filter() runs only in the
         * post-fork child, which holds a private copy of the address space; the hashmap
         * change is never visible to the manager process. */
        if (p->exec_fd >= 0 || p->handoff_timestamp_fd >= 0) {
                if (c->syscall_allow_list)
                        log_debug("SystemCallFilter= allow-list in effect; adding 'write' syscall required for exec handoff.");
 
                r = seccomp_filter_set_add_by_name(c->syscall_filter, c->syscall_allow_list, "write");
                if (r < 0)
                        return r;
        }
 
        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
}
 
static int apply_syscall_log(const ExecContext *c, const ExecParameters *p) {
        uint32_t default_action, action;
 
        assert(c);
        assert(p);
 
        if (!context_has_syscall_logs(c))
                return 0;
 
        if (skip_seccomp_unavailable("SystemCallLog="))
                return 0;
 
        if (c->syscall_log_allow_list) {
                /* Log nothing but the ones listed */
                default_action = SCMP_ACT_ALLOW;
                action = SCMP_ACT_LOG;
        } else {
                /* Log everything but the ones listed */
                default_action = SCMP_ACT_LOG;
                action = SCMP_ACT_ALLOW;
        }
 
        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false);
}
 
static int apply_syscall_archs(const ExecContext *c, const ExecParameters *p) {
        assert(c);
        assert(p);
 
        if (set_isempty(c->syscall_archs))
                return 0;
 
        if (skip_seccomp_unavailable("SystemCallArchitectures="))
                return 0;
 
        return seccomp_restrict_archs(c->syscall_archs);
}
 
static int apply_address_families(const ExecContext *c, const ExecParameters *p) {
        assert(c);
        assert(p);
 
        if (!context_has_address_families(c))
                return 0;
 
        if (skip_seccomp_unavailable("RestrictAddressFamilies="))
                return 0;
 
        return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list);
}
 
static int apply_memory_deny_write_execute(const ExecContext *c, const ExecParameters *p) {
        int r;
 
        assert(c);
        assert(p);
 
        if (!c->memory_deny_write_execute)
                return 0;
 
        /* use prctl() if kernel supports it (6.3) */
        r = prctl_safe(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0);
        if (r == 0) {
                log_debug("Enabled MemoryDenyWriteExecute= with PR_SET_MDWE");
                return 0;
        }
        if (r < 0 && r != -EINVAL)
                return log_debug_errno(r, "Failed to enable MemoryDenyWriteExecute= with PR_SET_MDWE: %m");
        /* else use seccomp */
        log_debug("Kernel doesn't support PR_SET_MDWE: falling back to seccomp");
 
        if (skip_seccomp_unavailable("MemoryDenyWriteExecute="))
                return 0;
 
        return seccomp_memory_deny_write_execute();
}
 
static int apply_restrict_realtime(const ExecContext *c, const ExecParameters *p) {
        assert(c);
        assert(p);
 
        if (!c->restrict_realtime)
                return 0;
 
        if (skip_seccomp_unavailable("RestrictRealtime="))
                return 0;
 
        return seccomp_restrict_realtime();
}
 
static int apply_restrict_suid_sgid(const ExecContext *c, const ExecParameters *p) {
        assert(c);
        assert(p);
 
        if (!c->restrict_suid_sgid)
                return 0;
 
        if (skip_seccomp_unavailable("RestrictSUIDSGID="))
                return 0;
 
        return seccomp_restrict_suid_sgid();
}
 
static int apply_protect_sysctl(const ExecContext *c, const ExecParameters *p) {
        assert(c);
        assert(p);
 
        /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
         * let's protect even those systems where this is left on in the kernel. */
 
        if (!c->protect_kernel_tunables)
                return 0;
 
        if (skip_seccomp_unavailable("ProtectKernelTunables="))
                return 0;
 
        return seccomp_protect_sysctl();
}
 
static int apply_protect_kernel_modules(const ExecContext *c, const ExecParameters *p) {
        assert(c);
        assert(p);
 
        /* Turn off module syscalls on ProtectKernelModules=yes */
 
        if (!c->protect_kernel_modules)
                return 0;
 
        if (skip_seccomp_unavailable("ProtectKernelModules="))
                return 0;
 
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
}
 
static int apply_protect_kernel_logs(const ExecContext *c, const ExecParameters *p) {
        assert(c);
        assert(p);
 
        if (!c->protect_kernel_logs)
                return 0;
 
        if (skip_seccomp_unavailable("ProtectKernelLogs="))
                return 0;
 
        return seccomp_protect_syslog();
}
 
static int apply_protect_clock(const ExecContext *c, const ExecParameters *p) {
        assert(c);
        assert(p);
 
        if (!c->protect_clock)
                return 0;
 
        if (skip_seccomp_unavailable("ProtectClock="))
                return 0;
 
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false);
}
 
static int apply_private_devices(const ExecContext *c, const ExecParameters *p) {
        assert(c);
        assert(p);
 
        /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
 
        if (!c->private_devices)
                return 0;
 
        if (skip_seccomp_unavailable("PrivateDevices="))
                return 0;
 
        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
}
 
static int apply_restrict_namespaces(const ExecContext *c, const ExecParameters *p) {
        assert(c);
        assert(p);
 
        if (!exec_context_restrict_namespaces_set(c))
                return 0;
 
        if (skip_seccomp_unavailable("RestrictNamespaces="))
                return 0;
 
        return seccomp_restrict_namespaces(c->restrict_namespaces);
}
 
static int apply_lock_personality(const ExecContext *c, const ExecParameters *p) {
        unsigned long personality;
        int r;
 
        assert(c);
        assert(p);
 
        if (!c->lock_personality)
                return 0;
 
        if (skip_seccomp_unavailable("LockPersonality="))
                return 0;
 
        personality = c->personality;
 
        /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */
        if (personality == PERSONALITY_INVALID) {
 
                r = opinionated_personality(&personality);
                if (r < 0)
                        return r;
        }
 
        return seccomp_lock_personality(personality);
}
 
#endif
 
#if HAVE_LIBBPF
static int apply_restrict_filesystems(const ExecContext *c, const ExecParameters *p) {
        int r;
 
        assert(c);
        assert(p);
 
        if (!exec_context_restrict_filesystems_set(c))
                return 0;
 
        if (p->bpf_restrict_fs_map_fd < 0) {
                /* LSM BPF is unsupported or lsm_bpf_setup failed */
                log_debug("LSM BPF not supported, skipping RestrictFileSystems=");
                return 0;
        }
 
        /* We are in a new binary, so dl-open again */
        r = dlopen_bpf(LOG_DEBUG);
        if (r < 0)
                return r;
 
        return bpf_restrict_fs_update(c->restrict_filesystems, p->cgroup_id, p->bpf_restrict_fs_map_fd, c->restrict_filesystems_allow_list);
}
#endif
 
static int apply_protect_hostname(const ExecContext *c, const ExecParameters *p, int *ret_exit_status) {
        int r;
 
        assert(c);
        assert(p);
        assert(ret_exit_status);
 
        if (c->protect_hostname == PROTECT_HOSTNAME_NO)
                return 0;
 
        if (namespace_type_supported(NAMESPACE_UTS)) {
                if (unshare(CLONE_NEWUTS) < 0) {
                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
                                *ret_exit_status = EXIT_NAMESPACE;
                                return log_error_errno(errno, "Failed to set up UTS namespacing: %m");
                        }
 
                        log_warning("ProtectHostname=%s is configured, but UTS namespace setup is prohibited (container manager?), ignoring namespace setup.",
                                    protect_hostname_to_string(c->protect_hostname));
 
                } else if (c->private_hostname) {
                        r = sethostname_idempotent(c->private_hostname);
                        if (r < 0) {
                                *ret_exit_status = EXIT_NAMESPACE;
                                return log_error_errno(r, "Failed to set private hostname '%s': %m", c->private_hostname);
                        }
                }
        } else
                log_warning("ProtectHostname=%s is configured, but the kernel does not support UTS namespaces, ignoring namespace setup.",
                            protect_hostname_to_string(c->protect_hostname));
 
#if HAVE_SECCOMP
        if (c->protect_hostname == PROTECT_HOSTNAME_YES) {
                if (skip_seccomp_unavailable("ProtectHostname="))
                        return 0;
 
                r = seccomp_protect_hostname();
                if (r < 0) {
                        *ret_exit_status = EXIT_SECCOMP;
                        return log_error_errno(r, "Failed to apply hostname restrictions: %m");
                }
        }
#endif
 
        return 1;
}
 
static void do_idle_pipe_dance(int idle_pipe[static 4]) {
        assert(idle_pipe);
 
        idle_pipe[1] = safe_close(idle_pipe[1]);
        idle_pipe[2] = safe_close(idle_pipe[2]);
 
        if (idle_pipe[0] >= 0) {
                int r;
 
                r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
 
                if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
                        ssize_t n;
 
                        /* Signal systemd that we are bored and want to continue. */
                        n = write(idle_pipe[3], "x", 1);
                        if (n > 0)
                                /* Wait for systemd to react to the signal above. */
                                (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
                }
 
                idle_pipe[0] = safe_close(idle_pipe[0]);
 
        }
 
        idle_pipe[3] = safe_close(idle_pipe[3]);
}
 
/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
 * the service payload in. */
static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
        [EXEC_DIRECTORY_RUNTIME]       = "RUNTIME_DIRECTORY",
        [EXEC_DIRECTORY_STATE]         = "STATE_DIRECTORY",
        [EXEC_DIRECTORY_CACHE]         = "CACHE_DIRECTORY",
        [EXEC_DIRECTORY_LOGS]          = "LOGS_DIRECTORY",
        [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
 
static int build_environment(
                const ExecContext *c,
                const ExecParameters *p,
                const CGroupContext *cgroup_context,
                const char *home,     /* may be NULL */
                const char *username, /* may be NULL */
                const char *shell,    /* may be NULL */