HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/core/exec-invoke.c
Git blob: ff107cc753cf314807216d8e1747fc30661a6ef4
Lines 5001–6000 of 6,799
safe_close_pair(rt->ephemeral_storage_socket);
exec_shared_runtime_close(rt->shared);
dynamic_creds_close(rt->dynamic_creds);
}
static void exec_params_close(ExecParameters *p) {
if (!p)
return;
p->stdin_fd = safe_close(p->stdin_fd);
p->stdout_fd = safe_close(p->stdout_fd);
p->stderr_fd = safe_close(p->stderr_fd);
}
static int exec_fd_mark_hot(
const ExecContext *c,
ExecParameters *p,
bool hot,
int *reterr_exit_status) {
assert(c);
assert(p);
if (p->exec_fd < 0)
return 0;
uint8_t x = hot;
if (write(p->exec_fd, &x, sizeof(x)) < 0) {
if (reterr_exit_status)
*reterr_exit_status = EXIT_EXEC;
return log_error_errno(errno, "Failed to mark exec_fd as %s: %m", hot ? "hot" : "cold");
}
return 1;
}
static int send_handoff_timestamp(
const ExecContext *c,
ExecParameters *p,
int *reterr_exit_status) {
assert(c);
assert(p);
if (p->handoff_timestamp_fd < 0)
return 0;
dual_timestamp dt;
dual_timestamp_now(&dt);
if (write(p->handoff_timestamp_fd, (const usec_t[2]) { dt.realtime, dt.monotonic }, sizeof(usec_t) * 2) < 0) {
if (reterr_exit_status)
*reterr_exit_status = EXIT_EXEC;
return log_error_errno(errno, "Failed to send handoff timestamp: %m");
}
return 1;
}
static void prepare_terminal(
const ExecContext *context,
ExecParameters *p) {
_cleanup_close_ int lock_fd = -EBADF;
/* This is the "constructive" reset, i.e. is about preparing things for our invocation rather than
* cleaning up things from older invocations. */
assert(context);
assert(p);
/* We only try to reset things if we there's the chance our stdout points to a TTY */
if (!(context->std_output == EXEC_OUTPUT_TTY ||
(context->std_output == EXEC_OUTPUT_INHERIT && exec_input_is_terminal(context->std_input)) ||
context->std_output == EXEC_OUTPUT_NAMED_FD ||
p->stdout_fd >= 0))
return;
/* Let's explicitly determine whether to reset via ANSI sequences or not, taking our ExecContext
* information into account */
bool use_ansi = exec_context_shall_ansi_seq_reset(context);
if (context->tty_reset) {
/* When we are resetting the TTY, then let's create a lock first, to synchronize access. This
* in particular matters as concurrent resets and the TTY size ANSI DSR logic done by the
* exec_context_apply_tty_size() below might interfere */
lock_fd = lock_dev_console();
if (lock_fd < 0)
log_debug_errno(lock_fd, "Failed to lock /dev/console, ignoring: %m");
/* We explicitly control whether to send ansi sequences or not here, since we want to consult
* the env vars explicitly configured in the ExecContext, rather than our own environment
* block. */
(void) terminal_reset_defensive(STDOUT_FILENO, use_ansi ? TERMINAL_RESET_FORCE_ANSI_SEQ : TERMINAL_RESET_AVOID_ANSI_SEQ);
}
(void) exec_context_apply_tty_size(context, STDIN_FILENO, STDOUT_FILENO, /* tty_path= */ NULL);
if (use_ansi)
(void) osc_context_open_service(p->unit_id, p->invocation_id, /* ret_seq= */ NULL);
}
static int setup_term_environment(const ExecContext *context, char ***env) {
int r;
assert(context);
assert(env);
/* Already specified by user? */
if (strv_env_get(*env, "TERM"))
return 0;
/* Do we need $TERM at all? */
if (!exec_context_has_tty(context))
return 0;
const char *tty_path = exec_context_tty_path(context);
if (tty_path) {
/* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try
* to inherit the $TERM set for PID 1. This is useful for containers so that the $TERM the
* container manager passes to PID 1 ends up all the way in the console login shown.
*
* Note that if this doesn't work out we won't bother with querying systemd.tty.term.console
* kernel cmdline option or DCS anymore either, because pid1 also imports $TERM based on those
* and it should have showed up as our $TERM if there were anything. */
if (tty_is_console(tty_path) && getppid() == 1) {
const char *term = strv_find_prefix(environ, "TERM=");
if (term) {
r = strv_env_replace_strdup(env, term);
if (r < 0)
return r;
FOREACH_STRING(i, "COLORTERM=", "NO_COLOR=") {
const char *s = strv_find_prefix(environ, i);
if (!s)
continue;
r = strv_env_replace_strdup(env, s);
if (r < 0)
return r;
}
return 1;
}
} else {
if (in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
_cleanup_free_ char *key = NULL, *cmdline = NULL;
key = strjoin("systemd.tty.term.", skip_dev_prefix(tty_path));
if (!key)
return -ENOMEM;
r = proc_cmdline_get_key(key, /* flags= */ 0, &cmdline);
if (r > 0)
return strv_env_assign(env, "TERM", cmdline);
if (r < 0)
log_debug_errno(r, "Failed to read '%s' from kernel cmdline, ignoring: %m", key);
}
/* This handles real virtual terminals (returning "linux") and
* any terminals which support the DCS +q query sequence. */
_cleanup_free_ char *dcs_term = NULL;
r = query_term_for_tty(tty_path, &dcs_term);
if (r >= 0)
return strv_env_assign(env, "TERM", dcs_term);
}
}
/* If $TERM is not known and we pick a fallback default, then let's also set
* $COLORTERM=truecolor. That's because our fallback default is vt220, which is
* generally a safe bet (as it supports PageUp/PageDown unlike vt100, and is quite
* universally available in terminfo/termcap), except for the fact that real DEC
* vt220 gear never actually supported color. Most tools these days generate color on
* vt220 anyway, ignoring the physical capabilities of the real hardware, but some
* tools actually believe in the historical truth. Which is unfortunate since *we*
* *don't* care about the historical truth, we just want sane defaults if nothing
* better is explicitly configured. It's 2025 after all, at the time of writing,
* pretty much all terminal emulators actually *do* support color, hence if we don't
* know any better let's explicitly claim color support via $COLORTERM. Or in other
* words: we now explicitly claim to be connected to a franken-vt220 with true color
* support. */
r = strv_env_replace_strdup(env, "COLORTERM=truecolor");
if (r < 0)
return r;
return strv_env_replace_strdup(env, "TERM=" FALLBACK_TERM);
}
static inline void free_pressure_paths(char *(*p)[_PRESSURE_RESOURCE_MAX]) {
free_many_charp(*p, _PRESSURE_RESOURCE_MAX);
}
int exec_invoke(
const ExecCommand *command,
const ExecContext *context,
ExecParameters *params,
ExecRuntime *runtime,
const CGroupContext *cgroup_context,
int *exit_status) {
_cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL;
int r;
const char *username = NULL;
_cleanup_free_ char *pwent_home = NULL, *shell = NULL, *_own_user = NULL, *_username = NULL;
_cleanup_(free_pressure_paths) char *pressure_path[_PRESSURE_RESOURCE_MAX] = {};
dev_t journal_stream_dev = 0;
ino_t journal_stream_ino = 0;
bool needs_sandboxing, /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
needs_setuid, /* Do we need to do the actual setresuid()/setresgid() calls? */
needs_mount_namespace, /* Do we need to set up a mount namespace for this kernel? */
have_cap_sys_admin,
userns_set_up = false,
keep_seccomp_privileges = false;
#if HAVE_SELINUX
_cleanup_free_ char *mac_selinux_context_net = NULL;
bool use_selinux = false;
#endif
#if ENABLE_SMACK
bool use_smack = false;
#endif
#if HAVE_APPARMOR
bool use_apparmor = false;
#endif
#if HAVE_SECCOMP
uint64_t saved_bset = 0;
#endif
/* saved_uid → where we started from; uid → where we ended up in; outside_uid → where we ended up in,
* but seen from the outside (covers userns mappings) */
uid_t uid = UID_INVALID, saved_uid = getuid(), outside_uid = UID_INVALID;
gid_t gid = GID_INVALID, saved_gid = getgid(), outside_gid = GID_INVALID;
int secure_bits;
_cleanup_free_ gid_t *gids = NULL, *gids_after_pam = NULL;
int ngids = 0, ngids_after_pam = 0;
int named_iofds[3] = EBADF_TRIPLET;
_cleanup_close_ int socket_fd = -EBADF, bpffs_socket_fd = -EBADF, bpffs_errno_pipe = -EBADF;
_cleanup_(pidref_done_sigkill_wait) PidRef bpffs_pidref = PIDREF_NULL;
assert(command);
assert(context);
assert(params);
assert(runtime);
assert(cgroup_context);
assert(exit_status);
LOG_CONTEXT_PUSH_EXEC(context, params);
/* Explicitly test for CVE-2021-4034 inspired invocations */
if (!command->path || strv_isempty(command->argv)) {
*exit_status = EXIT_EXEC;
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid command line arguments.");
}
rename_process_from_path(command->path);
if (context->std_input == EXEC_INPUT_SOCKET ||
context->std_output == EXEC_OUTPUT_SOCKET ||
context->std_error == EXEC_OUTPUT_SOCKET) {
if (params->n_socket_fds != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Expected exactly one socket, got %zu.",
params->n_socket_fds);
socket_fd = TAKE_FD(params->fds[0]);
free(params->fd_names[0]);
params->n_socket_fds = 0;
memmove(params->fds, params->fds + 1, params->n_stashed_fds * sizeof(int));
memmove(params->fd_names, params->fd_names + 1, params->n_stashed_fds * sizeof(char*));
params->fd_names[params->n_stashed_fds] = NULL;
}
r = exec_context_named_iofds(context, params, named_iofds);
if (r < 0) {
*exit_status = EXIT_FDS;
return log_error_errno(r, "Failed to load a named file descriptor: %m");
}
/* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
* daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
* both of which will be demoted to SIG_DFL. */
(void) default_signals(SIGNALS_CRASH_HANDLER,
SIGNALS_IGNORE);
if (context->ignore_sigpipe)
(void) ignore_signals(SIGPIPE);
r = reset_signal_mask();
if (r < 0) {
*exit_status = EXIT_SIGNAL_MASK;
return log_error_errno(r, "Failed to set process signal mask: %m");
}
if (params->idle_pipe)
do_idle_pipe_dance(params->idle_pipe);
/* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
* sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
* any fds open we don't really want open during the transition. In order to make logging work, we switch the
* log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
log_forget_fds();
log_set_open_when_needed(true);
log_settle_target();
/* In case anything used libc syslog(), close this here, too */
closelog();
r = collect_open_file_fds(params);
if (r < 0) {
*exit_status = EXIT_FDS;
return log_error_errno(r, "Failed to get OpenFile= file descriptors: %m");
}
size_t n_keep_fds = params->n_socket_fds + params->n_stashed_fds;
_cleanup_free_ int *keep_fds = newdup(int, params->fds, n_keep_fds);
if (!keep_fds) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
r = add_shifted_fd(&keep_fds, &n_keep_fds, ¶ms->exec_fd);
if (r < 0) {
*exit_status = EXIT_FDS;
return log_error_errno(r, "Failed to collect shifted fd: %m");
}
r = add_shifted_fd(&keep_fds, &n_keep_fds, ¶ms->handoff_timestamp_fd);
if (r < 0) {
*exit_status = EXIT_FDS;
return log_error_errno(r, "Failed to collect shifted fd: %m");
}
#if HAVE_LIBBPF
r = add_shifted_fd(&keep_fds, &n_keep_fds, ¶ms->bpf_restrict_fs_map_fd);
if (r < 0) {
*exit_status = EXIT_FDS;
return log_error_errno(r, "Failed to collect shifted fd: %m");
}
#endif
r = add_shifted_fd(&keep_fds, &n_keep_fds, ¶ms->root_directory_fd);
if (r < 0) {
*exit_status = EXIT_FDS;
return log_error_errno(r, "Failed to collect shifted fd: %m");
}
r = close_remaining_fds(params, runtime, socket_fd, keep_fds, n_keep_fds);
if (r < 0) {
*exit_status = EXIT_FDS;
return log_error_errno(r, "Failed to close unwanted file descriptors: %m");
}
if (!context->same_pgrp &&
setsid() < 0) {
*exit_status = EXIT_SETSID;
return log_error_errno(errno, "Failed to create new process session: %m");
}
/* Now, reset the TTY associated to this service "destructively" (i.e. possibly even hang up or
* disallocate the VT), to get rid of any prior uses of the device. Note that we do not keep any fd
* open here, hence some of the settings made here might vanish again, depending on the TTY driver
* used. A 2nd ("constructive") initialization after we opened the input/output fds we actually want
* will fix this. Note that we pass a NULL invocation ID here – as exec_context_tty_reset() expects
* the invocation ID associated with the OSC 3008 context ID to close. But we don't want to close any
* OSC 3008 context here, and opening a fresh OSC 3008 context happens a bit further down. */
exec_context_tty_reset(context, params, /* invocation_id= */ SD_ID128_NULL);
if (params->shall_confirm_spawn && exec_context_shall_confirm_spawn(context)) {
_cleanup_free_ char *cmdline = NULL;
cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
if (!cmdline) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
r = ask_for_confirmation(context, params, cmdline);
if (r != CONFIRM_EXECUTE) {
if (r == CONFIRM_PRETEND_SUCCESS) {
*exit_status = EXIT_SUCCESS;
return 0;
}
*exit_status = EXIT_CONFIRM;
return log_error_errno(SYNTHETIC_ERRNO(ECANCELED), "Execution cancelled by the user.");
}
}
/* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
* used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
* that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
* invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
* might internally call into other NSS modules that are involved in hostname resolution, we never know. */
if (setenv("SYSTEMD_ACTIVATION_UNIT", params->unit_id, true) != 0 ||
setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
*exit_status = EXIT_MEMORY;
return log_error_errno(errno, "Failed to update environment: %m");
}
if (exec_context_get_effective_private_users(context, params) == PRIVATE_USERS_MANAGED)
log_debug("Running with a managed user namespace, not initializing UIDs/GIDs.");
else if (context->dynamic_user && runtime->dynamic_creds) {
_cleanup_strv_free_ char **suggested_paths = NULL;
/* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
* checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
*exit_status = EXIT_USER;
return log_error_errno(errno, "Failed to update environment: %m");
}
r = compile_suggested_paths(context, params, &suggested_paths);
if (r < 0) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
if (r < 0) {
*exit_status = EXIT_USER;
if (r == -EILSEQ)
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"Failed to update dynamic user credentials: User or group with specified name already exists.");
return log_error_errno(r, "Failed to update dynamic user credentials: %m");
}
if (!uid_is_valid(uid)) {
*exit_status = EXIT_USER;
return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\".", uid);
}
if (!gid_is_valid(gid)) {
*exit_status = EXIT_USER;
return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\".", gid);
}
if (runtime->dynamic_creds->user)
username = runtime->dynamic_creds->user->name;
} else {
if (context->user)
username = context->user;
else if (context->pam_name || FLAGS_SET(command->flags, EXEC_COMMAND_VIA_SHELL)) {
/* If PAM is enabled but no user name is explicitly selected, then use our own one. */
username = _own_user = getusername_malloc();
if (!username) {
*exit_status = EXIT_USER;
return log_oom();
}
}
if (username) {
/* We can't use nss unconditionally for root without risking deadlocks if some IPC services
* will be started by pid1 and are ordered after us. But if SetLoginEnvironment= is
* enabled *explicitly* (i.e. no exec_context_get_set_login_environment() here),
* or PAM shall be invoked, let's consult NSS even for root, so that the user
* gets accurate $SHELL in session(-like) contexts. */
bool prefer_nss = context->set_login_environment > 0 || context->pam_name;
r = get_user_creds(username,
USER_CREDS_CLEAN|(prefer_nss ? USER_CREDS_PREFER_NSS : 0),
&_username,
&uid,
&gid,
&pwent_home,
&shell);
if (r < 0) {
*exit_status = EXIT_USER;
log_error_errno(r, "Failed to determine credentials for user '%s': %s",
username, STRERROR_USER(r));
return ERRNO_IS_NEG_BAD_ACCOUNT(r) ? -EINVAL : r; /* Suppress confusing errno */
}
username = _username;
}
if (context->group) {
r = get_group_creds(context->group, /* flags= */ 0, /* ret_name= */ NULL, &gid);
if (r < 0) {
*exit_status = EXIT_GROUP;
log_error_errno(r, "Failed to determine credentials for group '%s': %s",
context->group, STRERROR_GROUP(r));
return ERRNO_IS_NEG_BAD_ACCOUNT(r) ? -EINVAL : r; /* Suppress confusing errno */
}
}
}
if (exec_context_get_effective_private_users(context, params) != PRIVATE_USERS_MANAGED) {
/* Initialize user supplementary groups and get SupplementaryGroups= ones */
ngids = get_supplementary_groups(context, username, gid, &gids);
if (ngids < 0) {
*exit_status = EXIT_GROUP;
return log_error_errno(ngids, "Failed to determine supplementary groups: %m");
}
r = send_user_lookup(params->unit_id, params->user_lookup_fd, uid, gid);
if (r < 0) {
*exit_status = EXIT_USER;
return log_error_errno(r, "Failed to send user credentials to PID1: %m");
}
params->user_lookup_fd = safe_close(params->user_lookup_fd);
}
r = acquire_home(context, &pwent_home);
if (r < 0) {
*exit_status = EXIT_CHDIR;
return log_error_errno(r, "Failed to determine $HOME for the invoking user: %m");
}
/* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
if (socket_fd >= 0)
(void) fd_nonblock(socket_fd, false);
/* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
* from it. */
needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
/* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
* Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
if (params->cgroup_path) {
_cleanup_free_ char *subcgroup = NULL;
r = exec_params_get_cgroup_path(params, cgroup_context, params->cgroup_path, &subcgroup);
if (r < 0) {
*exit_status = EXIT_CGROUP;
return log_error_errno(r, "Failed to acquire cgroup path: %m");
}
if (r > 0) {
/* If there is a subcgroup required, let's make sure to create it now. */
r = cg_create(subcgroup);
if (r < 0)
return log_error_errno(r, "Failed to create subcgroup '%s': %m", subcgroup);
}
/* If we need a cgroup namespace, we cannot yet move the service to its configured subgroup,
* as unsharing the cgroup namespace later on makes the current cgroup the root of the
* namespace and we want the root of the namespace to be the main service cgroup and not the
* subgroup. One edge case is if we're a control process that needs to be spawned in a
* subgroup, in this case, we have no choice as moving into the main service cgroup might
* violate the no inner processes rule of cgroupv2. */
const char *cgtarget = needs_sandboxing && exec_needs_cgroup_namespace(context) &&
!exec_params_needs_control_subcgroup(params)
? params->cgroup_path : subcgroup;
r = cg_attach(cgtarget, 0);
if (r == -EUCLEAN) {
*exit_status = EXIT_CGROUP;
return log_error_errno(r,
"Failed to attach process to cgroup '%s', "
"because the cgroup or one of its parents or "
"siblings is in the threaded mode.", cgtarget);
}
if (r < 0) {
*exit_status = EXIT_CGROUP;
return log_error_errno(r, "Failed to attach to cgroup %s: %m", cgtarget);
}
}
if (context->user_namespace_path && runtime->shared && runtime->shared->userns_storage_socket[0] >= 0) {
r = open_shareable_ns_path(runtime->shared->userns_storage_socket, context->user_namespace_path, CLONE_NEWUSER);
if (r < 0) {
*exit_status = EXIT_NAMESPACE;
return log_error_errno(r, "Failed to open user namespace path %s: %m", context->user_namespace_path);
}
}
if (context->network_namespace_path && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
if (r < 0) {
*exit_status = EXIT_NETWORK;
return log_error_errno(r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
}
}
if (context->ipc_namespace_path && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
if (r < 0) {
*exit_status = EXIT_NAMESPACE;
return log_error_errno(r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
}
}
r = setup_input(context, params, socket_fd, named_iofds);
if (r < 0) {
*exit_status = EXIT_STDIN;
return log_error_errno(r, "Failed to set up standard input: %m");
}
_cleanup_free_ char *fname = NULL;
r = path_extract_filename(command->path, &fname);
if (r < 0) {
*exit_status = EXIT_STDOUT;
return log_error_errno(r, "Failed to extract filename from path %s: %m", command->path);
}
r = setup_output(context, params, STDOUT_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
if (r < 0) {
*exit_status = EXIT_STDOUT;
return log_error_errno(r, "Failed to set up standard output: %m");
}
r = setup_output(context, params, STDERR_FILENO, socket_fd, named_iofds, fname, uid, gid, &journal_stream_dev, &journal_stream_ino);
if (r < 0) {
*exit_status = EXIT_STDERR;
return log_error_errno(r, "Failed to set up standard error output: %m");
}
/* Now that stdin/stdout are definiely opened, properly initialize it with our desired
* settings. Note: this is a "constructive" reset, it prepares things for us to use. This is
* different from the "destructive" TTY reset further up. Also note: we apply this on stdin/stdout in
* case this is a tty, regardless if we opened it ourselves or got it passed in pre-opened. */
prepare_terminal(context, params);
if (context->oom_score_adjust_set) {
/* When we can't make this change due to EPERM, then let's silently skip over it. User
* namespaces prohibit write access to this file, and we shouldn't trip up over that. */
r = set_oom_score_adjust(context->oom_score_adjust);
if (ERRNO_IS_NEG_PRIVILEGE(r))
log_debug_errno(r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
else if (r < 0) {
*exit_status = EXIT_OOM_ADJUST;
return log_error_errno(r, "Failed to adjust OOM setting: %m");
}
}
if (context->coredump_filter_set) {
r = set_coredump_filter(context->coredump_filter);
if (ERRNO_IS_NEG_PRIVILEGE(r))
log_debug_errno(r, "Failed to adjust coredump_filter, ignoring: %m");
else if (r < 0) {
*exit_status = EXIT_LIMITS;
return log_error_errno(r, "Failed to adjust coredump_filter: %m");
}
}
if (context->cpu_sched_set) {
struct sched_attr attr = {
.size = sizeof(attr),
.sched_policy = context->cpu_sched_policy,
.sched_priority = context->cpu_sched_priority,
.sched_flags = context->cpu_sched_reset_on_fork ? SCHED_FLAG_RESET_ON_FORK : 0,
};
r = RET_NERRNO(sched_setattr(/* pid= */ 0, &attr, /* flags= */ 0));
if (r == -EPERM && !context->cpu_sched_reset_on_fork) {
/* RestrictRealtime= refuses sched_setattr() altogether (possibly in an outer
* manager), hence fall back to sched_setscheduler(), which it filters per policy.
* We cannot do that with SCHED_RESET_ON_FORK, which the filter refuses too. */
struct sched_param param = { .sched_priority = context->cpu_sched_priority };
r = RET_NERRNO(sched_setscheduler(/* pid= */ 0, context->cpu_sched_policy, ¶m));
}
if (r == -EINVAL && !sched_policy_supported(context->cpu_sched_policy)) {
_cleanup_free_ char *s = NULL;
(void) sched_policy_to_string_alloc(context->cpu_sched_policy, &s);
log_warning_errno(r, "CPU scheduling policy %s is not supported, proceeding without.", strna(s));
} else if (r < 0) {
*exit_status = EXIT_SETSCHEDULER;
return log_error_errno(r, "Failed to set up CPU scheduling: %m");
}
}
/*
* Set nice value _after_ the call to sched_setattr() because struct sched_attr includes sched_nice
* which we do not set, thus it will clobber any previously set nice value. Scheduling policy might
* be reasonably set together with nice value e.g. in case of SCHED_BATCH (see sched(7)).
* It would be ideal to set both with the same call, but we cannot easily do so because of all the
* extra logic in setpriority_closest().
*/
if (context->nice_set) {
r = setpriority_closest(context->nice);
if (r < 0) {
*exit_status = EXIT_NICE;
return log_error_errno(r, "Failed to set up process scheduling priority (nice level): %m");
}
}
if (context->cpu_affinity_from_numa || context->cpu_set.set) {
_cleanup_(cpu_set_done) CPUSet converted_cpu_set = {};
const CPUSet *cpu_set;
if (context->cpu_affinity_from_numa) {
r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
if (r < 0) {
*exit_status = EXIT_CPUAFFINITY;
return log_error_errno(r, "Failed to derive CPU affinity mask from NUMA mask: %m");
}
cpu_set = &converted_cpu_set;
} else
cpu_set = &context->cpu_set;
if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
*exit_status = EXIT_CPUAFFINITY;
return log_error_errno(errno, "Failed to set up CPU affinity: %m");
}
}
if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
r = apply_numa_policy(&context->numa_policy);
if (r == -ENOSYS)
log_debug_errno(r, "NUMA support not available, ignoring.");
else if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
log_warning_errno(r, "NUMA policy not supported by kernel, ignoring.");
else if (r < 0) {
*exit_status = EXIT_NUMA_POLICY;
return log_error_errno(r, "Failed to set NUMA memory policy: %m");
}
}
if (context->ioprio_is_set)
if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
*exit_status = EXIT_IOPRIO;
return log_error_errno(errno, "Failed to set up IO scheduling priority: %m");
}
if (context->timer_slack_nsec != NSEC_INFINITY) {
r = prctl_safe(PR_SET_TIMERSLACK, context->timer_slack_nsec, 0, 0, 0);
if (r < 0) {
*exit_status = EXIT_TIMERSLACK;
return log_error_errno(r, "Failed to set up timer slack: %m");
}
}
if (context->personality != PERSONALITY_INVALID) {
r = safe_personality(context->personality);
if (r < 0) {
*exit_status = EXIT_PERSONALITY;
return log_error_errno(r, "Failed to set up execution domain (personality): %m");
}
}
if (context->memory_ksm >= 0) {
r = prctl_safe(PR_SET_MEMORY_MERGE, context->memory_ksm, 0, 0, 0);
if (r < 0) {
if (ERRNO_IS_NOT_SUPPORTED(r))
log_debug_errno(r, "KSM support not available, ignoring.");
else {
*exit_status = EXIT_KSM;
return log_error_errno(r, "Failed to set KSM: %m");
}
}
}
r = set_memory_thp(context->memory_thp);
if (r == -EOPNOTSUPP)
log_debug_errno(r, "Setting MemoryTHP=%s is not supported, ignoring.",
exec_memory_thp_to_string(context->memory_thp));
else if (r < 0) {
*exit_status = EXIT_MEMORY_THP;
return log_error_errno(r, "Failed to set MemoryTHP=%s: %m",
exec_memory_thp_to_string(context->memory_thp));
}
#if ENABLE_UTMP
if (context->utmp_id) {
_cleanup_free_ char *username_alloc = NULL;
if (!username && context->utmp_mode == EXEC_UTMP_USER) {
username_alloc = uid_to_name(uid_is_valid(uid) ? uid : saved_uid);
if (!username_alloc) {
*exit_status = EXIT_USER;
return log_oom();
}
}
const char *line = context->tty_path ?
(path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
NULL;
utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
line,
context->utmp_mode == EXEC_UTMP_INIT ? INIT_PROCESS :
context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
USER_PROCESS,
username ?: username_alloc);
}
#endif
/* Only adjust ownership for TTYs we acquired via StandardInput=tty*. If stdin is passed
* as an fd, its ownership is managed by the provider of the fd, see exec_context_revert_tty(). */
if (uid_is_valid(uid) &&
params->stdin_fd < 0 &&
exec_input_is_terminal(context->std_input) &&
exec_context_tty_path(context)) {
r = chown_terminal(STDIN_FILENO, uid);
if (r < 0) {
*exit_status = EXIT_STDIN;
return log_error_errno(r, "Failed to change ownership of terminal: %m");
}
}
if (params->cgroup_path) {
/* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
* this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
* safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
* touch a single hierarchy too. */
if (params->flags & EXEC_CGROUP_DELEGATE) {
_cleanup_free_ char *p = NULL;
r = cg_set_access(params->cgroup_path, uid, gid);
if (r < 0) {
*exit_status = EXIT_CGROUP;
return log_error_errno(r, "Failed to adjust control group access: %m");
}
r = exec_params_get_cgroup_path(params, cgroup_context, params->cgroup_path, &p);
if (r < 0) {
*exit_status = EXIT_CGROUP;
return log_error_errno(r, "Failed to acquire cgroup path: %m");
}
if (r > 0) {
r = cg_set_access_recursive(p, uid, gid);
if (r < 0) {
*exit_status = EXIT_CGROUP;
return log_error_errno(r, "Failed to adjust control subgroup access: %m");
}
}
}
if (is_pressure_supported() > 0) {
for (PressureResource t = 0; t < _PRESSURE_RESOURCE_MAX; t++) {
if (cgroup_context_want_pressure(cgroup_context, t)) {
_cleanup_free_ char *pressure_file = strjoin(pressure_resource_to_string(t), ".pressure");
if (!pressure_file) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
r = cg_get_path(params->cgroup_path, pressure_file, &pressure_path[t]);
if (r < 0) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
r = chmod_and_chown(pressure_path[t], 0644, uid, gid);
if (r < 0) {
log_full_errno(r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
"Failed to adjust ownership of '%s', ignoring: %m", pressure_path[t]);
pressure_path[t] = mfree(pressure_path[t]);
}
/* First we use the current cgroup path to chmod and chown the pressure path, then pass the
* path relative to the cgroup namespace to environment variables and mounts. If chown/chmod
* fails, we should not pass pressure path environment variable or read-write mount to the
* unit. This is why we check if pressure_path[t] != NULL in the conditional below. */
if (pressure_path[t] && needs_sandboxing && exec_needs_cgroup_namespace(context)) {
pressure_path[t] = mfree(pressure_path[t]);
r = cg_get_path("/", pressure_file, &pressure_path[t]);
if (r < 0) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
}
} else if (cgroup_context->pressure[t].watch == CGROUP_PRESSURE_WATCH_NO) {
pressure_path[t] = strdup("/dev/null"); /* /dev/null is explicit indicator for turning off pressure watch */
if (!pressure_path[t]) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
}
}
}
}
_cleanup_(sd_varlink_unrefp) sd_varlink *mountfsd_link = NULL, *nsresource_link = NULL;
_cleanup_close_ int keep_parent_fd = -EBADF;
if (needs_sandboxing &&
exec_context_get_effective_private_users(context, params) == PRIVATE_USERS_MANAGED) {
/* In managed mode we need to allocate a userns via nsresource, and then assign mounts to
* it. We must do so with our original privileges (since after creating the userns, we might
* simply not have the necessary privs for the IPC calls anymore), hence do this here, ahead
* of time. */
r = mountfsd_connect(&mountfsd_link);
if (r < 0)
return log_error_errno(r, "Failed to connect to mountfsd: %m");
r = nsresource_connect(&nsresource_link);
if (r < 0)
return log_error_errno(r, "Failed to connect to nsresourced: %m");
}
needs_mount_namespace = exec_needs_mount_namespace(context, params);
for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
if (r < 0)
return log_error_errno(r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
}
r = exec_setup_credentials(context, cgroup_context, params, uid, gid);
if (r < 0) {
*exit_status = EXIT_CREDENTIALS;
return log_error_errno(r, "Failed to set up credentials: %m");
}
r = build_environment(
context,
params,
cgroup_context,
pwent_home,
username,
shell,
journal_stream_dev,
journal_stream_ino,
pressure_path,
needs_sandboxing,
&our_env);
if (r < 0) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
r = build_pass_environment(context, &pass_env);
if (r < 0) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
/* The $PATH variable is set to the default path in params->environment. However, this is overridden
* if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
* not specify PATH but the unit has ExecSearchPath. */
if (!strv_isempty(context->exec_search_path)) {
_cleanup_free_ char *joined = NULL;
joined = strv_join(context->exec_search_path, ":");
if (!joined) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
if (r < 0) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
}
accum_env = strv_env_merge(params->environment,
our_env,
joined_exec_search_path,
pass_env,
context->environment,
params->files_env);
if (!accum_env) {
*exit_status = EXIT_MEMORY;
return log_oom();
}
strv_env_clean(accum_env);
(void) umask(context->umask);
r = setup_term_environment(context, &accum_env);
if (r < 0) {
*exit_status = EXIT_MEMORY;
return log_error_errno(r, "Failed to construct $TERM: %m");
}
r = setup_keyring(context, params, uid, gid);
if (r < 0) {
*exit_status = EXIT_KEYRING;
return log_error_errno(r, "Failed to set up kernel keyring: %m");
}
/* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
* excepted from either whole sandboxing or just setresuid() itself. */
needs_setuid = needs_sandboxing && !FLAGS_SET(command->flags, EXEC_COMMAND_NO_SETUID);
uint64_t capability_ambient_set = context->capability_ambient_set;
/* Check CAP_SYS_ADMIN before we enter user namespace to see if we can mount /proc even though its masked. */
have_cap_sys_admin = have_effective_cap(CAP_SYS_ADMIN) > 0;
if (needs_sandboxing) {
/* MAC enablement checks need to be done before a new mount ns is created, as they rely on
* /sys being present. The actual MAC context application will happen later, as late as
* possible, to avoid impacting our own code paths. */
#if HAVE_SELINUX
use_selinux = mac_selinux_use();
#endif
#if ENABLE_SMACK
use_smack = mac_smack_use();
#endif
#if HAVE_APPARMOR
use_apparmor = mac_apparmor_use();
#endif
}
if (needs_sandboxing) {
int which_failed;
/* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
* is set here. (See below.) */