HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/core/exec-invoke.c
Git blob: ff107cc753cf314807216d8e1747fc30661a6ef4
Lines 2001–3000 of 6,799
dev_t journal_stream_dev,
ino_t journal_stream_ino,
char *const *pressure_path,
bool needs_sandboxing,
char ***ret) {
_cleanup_strv_free_ char **e = NULL;
_cleanup_free_ char *_username = NULL, *_home = NULL, *_shell = NULL;
size_t n = 0;
pid_t exec_pid;
int r;
assert(c);
assert(p);
assert(cgroup_context);
assert(pressure_path);
assert(ret);
exec_pid = needs_sandboxing && exec_needs_pid_namespace(c, p) ? 1 : getpid_cached();
if (p->n_socket_fds + p->n_stashed_fds > 0) {
_cleanup_free_ char *joined = NULL;
r = strv_extendf_with_size(&e, &n, "LISTEN_PID="PID_FMT, exec_pid);
if (r < 0)
return r;
uint64_t pidfdid;
if (pidfd_get_inode_id_self_cached(&pidfdid) >= 0) {
r = strv_extendf_with_size(&e, &n, "LISTEN_PIDFDID=%"PRIu64, pidfdid);
if (r < 0)
return r;
}
r = strv_extendf_with_size(&e, &n, "LISTEN_FDS=%zu", p->n_socket_fds + p->n_stashed_fds);
if (r < 0)
return r;
joined = strv_join(p->fd_names, ":");
if (!joined)
return -ENOMEM;
r = strv_extend_joined_with_size(&e, &n, "LISTEN_FDNAMES=", joined);
if (r < 0)
return r;
}
if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
r = strv_extendf_with_size(&e, &n, "WATCHDOG_PID="PID_FMT, exec_pid);
if (r < 0)
return r;
r = strv_extendf_with_size(&e, &n, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec);
if (r < 0)
return r;
}
/* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use blocking
* Varlink calls back to us for look up dynamic users in PID 1. Break the deadlock between D-Bus and
* PID 1 by disabling use of PID1's NSS interface for looking up dynamic users. */
if (p->flags & EXEC_NSS_DYNAMIC_BYPASS) {
r = strv_extend_with_size(&e, &n, "SYSTEMD_NSS_DYNAMIC_BYPASS=1");
if (r < 0)
return r;
}
/* We query "root" if this is a system unit and User= is not specified. $USER is always set. $HOME
* could cause problem for e.g. getty, since login doesn't override $HOME, and $LOGNAME and $SHELL
* don't really make much sense since we're not logged in. Hence we conditionalize the three based on
* SetLoginEnvironment= switch. */
if (!username && !c->dynamic_user && p->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
assert(!c->user);
r = get_user_creds("root", USER_CREDS_CLEAN, &_username, NULL, NULL, &_home, &_shell);
if (r < 0) {
log_debug_errno(r, "Failed to determine credentials for user root: %s",
STRERROR_USER(r));
return ERRNO_IS_NEG_BAD_ACCOUNT(r) ? -EINVAL : r; /* Suppress confusing errno */
}
username = _username;
home = _home;
shell = _shell;
}
bool set_user_login_env = exec_context_get_set_login_environment(c);
if (username) {
r = strv_extend_joined_with_size(&e, &n, "USER=", username);
if (r < 0)
return r;
if (set_user_login_env) {
r = strv_extend_joined_with_size(&e, &n, "LOGNAME=", username);
if (r < 0)
return r;
}
}
/* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
* (i.e. are "/" or "/bin/nologin"). */
if (home && set_user_login_env && !empty_or_root(home)) {
_cleanup_free_ char *x = NULL;
r = path_simplify_alloc(home, &x);
if (r < 0)
return r;
r = strv_extend_joined_with_size(&e, &n, "HOME=", x);
if (r < 0)
return r;
}
if (shell && set_user_login_env && !shell_is_placeholder(shell)) {
_cleanup_free_ char *x = NULL;
r = path_simplify_alloc(shell, &x);
if (r < 0)
return r;
r = strv_extend_joined_with_size(&e, &n, "SHELL=", x);
if (r < 0)
return r;
}
if (!sd_id128_is_null(p->invocation_id)) {
assert(!isempty(p->invocation_id_string));
r = strv_extend_joined_with_size(&e, &n, "INVOCATION_ID=", p->invocation_id_string);
if (r < 0)
return r;
}
if (journal_stream_dev != 0 && journal_stream_ino != 0) {
r = strv_extendf_with_size(&e, &n, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino);
if (r < 0)
return r;
}
if (c->log_namespace) {
r = strv_extend_joined_with_size(&e, &n, "LOG_NAMESPACE=", c->log_namespace);
if (r < 0)
return r;
}
for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
_cleanup_free_ char *joined = NULL;
if (!p->prefix[t])
continue;
if (c->directories[t].n_items == 0)
continue;
const char *name = exec_directory_env_name_to_string(t);
if (!name)
continue;
for (size_t i = 0; i < c->directories[t].n_items; i++) {
_cleanup_free_ char *prefixed = NULL;
prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
if (!prefixed)
return -ENOMEM;
if (!strextend_with_separator(&joined, ":", prefixed))
return -ENOMEM;
}
r = strv_extend_joined_with_size(&e, &n, name, "=", joined);
if (r < 0)
return r;
}
_cleanup_free_ char *creds_dir = NULL;
r = exec_context_get_credential_directory(c, p, p->unit_id, &creds_dir);
if (r < 0)
return r;
if (r > 0) {
r = strv_extend_joined_with_size(&e, &n, "CREDENTIALS_DIRECTORY=", creds_dir);
if (r < 0)
return r;
}
r = strv_extendf_with_size(&e, &n, "SYSTEMD_EXEC_PID=" PID_FMT, exec_pid);
if (r < 0)
return r;
for (PressureResource t = 0; t < _PRESSURE_RESOURCE_MAX; t++) {
if (!pressure_path[t])
continue;
const PressureResourceInfo *info = pressure_resource_get_info(t);
_cleanup_free_ char *env_watch = strjoin(info->env_watch, "=");
if (!env_watch)
return -ENOMEM;
r = strv_extend_joined_with_size(&e, &n, env_watch, pressure_path[t]);
if (r < 0)
return r;
if (!path_equal(pressure_path[t], "/dev/null")) {
_cleanup_free_ char *b = NULL, *x = NULL;
if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
PRESSURE_DEFAULT_TYPE,
cgroup_context->pressure[t].threshold_usec == USEC_INFINITY ? PRESSURE_DEFAULT_THRESHOLD_USEC :
CLAMP(cgroup_context->pressure[t].threshold_usec, 1U, PRESSURE_DEFAULT_WINDOW_USEC),
PRESSURE_DEFAULT_WINDOW_USEC) < 0)
return -ENOMEM;
if (base64mem(b, strlen(b) + 1, &x) < 0)
return -ENOMEM;
_cleanup_free_ char *env_write = strjoin(info->env_write, "=");
if (!env_write)
return -ENOMEM;
r = strv_extend_joined_with_size(&e, &n, env_write, x);
if (r < 0)
return r;
}
}
if (p->notify_socket) {
r = strv_extend_joined_with_size(
&e, &n, "NOTIFY_SOCKET=",
exec_get_private_notify_socket_path(c, p, needs_sandboxing) ?: p->notify_socket);
if (r < 0)
return r;
}
assert(c->private_var_tmp >= 0 && c->private_var_tmp < _PRIVATE_TMP_MAX);
if (needs_sandboxing &&
c->private_var_tmp == PRIVATE_TMP_NO && c->private_tmp != PRIVATE_TMP_NO) {
/* When private tmpfs is enabled only on /tmp/, then explicitly set $TMPDIR to suggest the
* service to use /tmp/. */
r = strv_extend_with_size(&e, &n, "TMPDIR=/tmp");
if (r < 0)
return r;
}
*ret = TAKE_PTR(e);
return 0;
}
static int build_pass_environment(const ExecContext *c, char ***ret) {
_cleanup_strv_free_ char **pass_env = NULL;
size_t n_env = 0;
assert(c);
assert(ret);
STRV_FOREACH(i, c->pass_environment) {
_cleanup_free_ char *x = NULL;
char *v;
v = getenv(*i);
if (!v)
continue;
x = strjoin(*i, "=", v);
if (!x)
return -ENOMEM;
if (!GREEDY_REALLOC(pass_env, n_env + 2))
return -ENOMEM;
pass_env[n_env++] = TAKE_PTR(x);
pass_env[n_env] = NULL;
}
*ret = TAKE_PTR(pass_env);
return 0;
}
static int bpffs_helper(const ExecContext *c, int socket_fd) {
assert(c);
assert(socket_fd >= 0);
_cleanup_close_ int fs_fd = receive_one_fd(socket_fd, /* flags= */ 0);
if (fs_fd < 0)
return log_debug_errno(fs_fd, "Failed to receive file descriptor from parent: %m");
char number[STRLEN("0x") + sizeof(c->bpf_delegate_commands) * 2 + 1];
xsprintf(number, "0x%"PRIx64, c->bpf_delegate_commands);
if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "delegate_cmds", number, /* aux= */ 0) < 0)
return log_debug_errno(errno, "Failed to FSCONFIG_SET_STRING: %m");
xsprintf(number, "0x%"PRIx64, c->bpf_delegate_maps);
if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "delegate_maps", number, /* aux= */ 0) < 0)
return log_debug_errno(errno, "Failed to FSCONFIG_SET_STRING: %m");
xsprintf(number, "0x%"PRIx64, c->bpf_delegate_programs);
if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "delegate_progs", number, /* aux= */ 0) < 0)
return log_debug_errno(errno, "Failed to FSCONFIG_SET_STRING: %m");
xsprintf(number, "0x%"PRIx64, c->bpf_delegate_attachments);
if (fsconfig(fs_fd, FSCONFIG_SET_STRING, "delegate_attachs", number, /* aux= */ 0) < 0)
return log_debug_errno(errno, "Failed to FSCONFIG_SET_STRING: %m");
if (fsconfig(fs_fd, FSCONFIG_CMD_CREATE, /* key= */ NULL, /* value= */ NULL, /* aux= */ 0) < 0)
return log_debug_errno(errno, "Failed to create bpffs superblock: %m");
return 0;
}
static int bpffs_prepare(
const ExecContext *c,
PidRef *ret_pid,
int *ret_sock_fd,
int *ret_errno_pipe) {
_cleanup_close_pair_ int socket_fds[2] = EBADF_PAIR, errno_pipe[2] = EBADF_PAIR;
int r;
assert(c);
assert(ret_sock_fd);
assert(ret_pid);
assert(ret_errno_pipe);
r = pipe2(errno_pipe, O_CLOEXEC|O_NONBLOCK);
if (r < 0)
return log_debug_errno(errno, "Failed to create pipe: %m");
r = socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, socket_fds);
if (r < 0)
return log_debug_errno(errno, "Failed to create socket pair: %m");
r = pidref_safe_fork("(sd-bpffs)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL, ret_pid);
if (r < 0)
return log_debug_errno(r, "Failed to fork bpffs privileged helper: %m");
if (r == 0) {
errno_pipe[0] = safe_close(errno_pipe[0]);
socket_fds[0] = safe_close(socket_fds[0]);
report_errno_and_exit(errno_pipe[1], bpffs_helper(c, socket_fds[1]));
}
*ret_sock_fd = TAKE_FD(socket_fds[0]);
*ret_errno_pipe = TAKE_FD(errno_pipe[0]);
return 0;
}
static int setup_private_users_child(int unshare_ready_fd, const char *uid_map, const char *gid_map, bool allow_setgroups) {
int r;
assert(uid_map);
assert(gid_map);
/* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
* here, after the parent opened its own user namespace. */
pid_t ppid = getppid();
/* Wait until the parent unshared the user namespace */
uint64_t c;
ssize_t n = read(unshare_ready_fd, &c, sizeof(c));
if (n < 0)
return log_debug_errno(errno, "Failed to read from signaling eventfd: %m");
if (n != sizeof(c))
return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Short read from signaling eventfd.");
/* Disable the setgroups() system call in the child user namespace, for good, unless PrivateUsers=full
* and using the system service manager. */
const char *a = procfs_file_alloca(ppid, "setgroups");
const char *setgroups = allow_setgroups ? "allow" : "deny";
r = write_string_file(a, setgroups, WRITE_STRING_FILE_DISABLE_BUFFER);
if (r < 0)
return log_debug_errno(r, "Failed to write '%s' to %s: %m", setgroups, a);
/* First write the GID map */
a = procfs_file_alloca(ppid, "gid_map");
r = write_string_file(a, gid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
if (r < 0)
return log_debug_errno(r, "Failed to write GID map to %s: %m", a);
/* Then write the UID map */
a = procfs_file_alloca(ppid, "uid_map");
r = write_string_file(a, uid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
if (r < 0)
return log_debug_errno(r, "Failed to write UID map to %s: %m", a);
return 0;
}
static int setup_private_users(
sd_varlink *nsresource_link, /* may be NULL */
PrivateUsers private_users,
uid_t saved_uid, /* service manager uid */
gid_t saved_gid, /* service manager gid */
uid_t *uid, /* unit uid (seen from inside) [input+output] */
gid_t *gid, /* unit gid (ditto) [input+output] */
uid_t *outside_uid, /* uid seen from the outside (which is the same as *uid, except of userns is used) */
gid_t *outside_gid, /* gid seen from the outside (similar) */
bool allow_setgroups) {
_cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
_cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
_cleanup_close_ int unshare_ready_fd = -EBADF;
_cleanup_(pidref_done_sigkill_wait) PidRef pidref = PIDREF_NULL;
uint64_t c = 1;
ssize_t n;
int r;
assert(uid);
assert(gid);
assert(outside_uid);
assert(outside_gid);
/* Set up a user namespace and map the original UID/GID (IDs from before any user or group changes, i.e.
* the IDs from the user or system manager(s)) to itself, the selected UID/GID to itself, and everything else to
* nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
* we however lack after opening the user namespace. To work around this we fork() a temporary child process,
* which waits for the parent to create the new user namespace while staying in the original namespace. The
* child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
* continues execution normally.
* For unprivileged users (i.e. without capabilities), the root to root mapping is excluded. As such, it
* does not need CAP_SETUID to write the single line mapping to itself. */
switch (private_users) { /* Prepare the UID mappings */
case PRIVATE_USERS_NO:
return 0; /* Early exit */
case PRIVATE_USERS_MANAGED: {
if (uid_is_valid(*uid) || uid_is_valid(*gid))
return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "When allocating dynamic user namespace range, target UID/GID must be root, refusing.");
_cleanup_close_ int userns_fd = nsresource_allocate_userns(
nsresource_link,
/* name= */ NULL,
NSRESOURCE_UIDS_64K);
if (userns_fd < 0)
return userns_fd;
_cleanup_(uid_range_freep) UIDRange *uid_range = NULL;
r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_OUTSIDE, &uid_range);
if (r < 0)
return log_debug_errno(r, "Failed to read outside userns UID range: %m");
_cleanup_(uid_range_freep) UIDRange *gid_range = NULL;
r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_OUTSIDE, &gid_range);
if (r < 0)
return log_debug_errno(r, "Failed to read outside userns GID range: %m");
if (setns(userns_fd, CLONE_NEWUSER) < 0)
return log_debug_errno(errno, "Failed to join freshly allocated user namespace: %m");
/* In "managed" mode the originating UID is not mapped hence we need to explicitly become root in the new userns now. */
r = reset_uid_gid();
if (r < 0)
return log_debug_errno(r, "Failed to reset UID/GID to root: %m");
/* Now report are new UIDs/GIDS, both inside and outside */
*uid = 0;
*gid = 0;
*outside_uid = uid_range_base(uid_range);
*outside_gid = uid_range_base(gid_range);
return 1; /* Early exit */
}
case PRIVATE_USERS_IDENTITY:
uid_map = strdup("0 0 65536\n");
if (!uid_map)
return -ENOMEM;
break;
case PRIVATE_USERS_FULL:
/* Map all UID/GID from original to new user namespace.
*
* Note the kernel defines the UID range between 0 and UINT32_MAX so we map all UIDs even though
* the UID range beyond INT32_MAX (e.g. i.e. the range above the signed 32-bit range) is
* icky. For example, setfsuid() returns the old UID as signed integer. But units can decide to
* use these UIDs/GIDs so we need to map them. */
if (asprintf(&uid_map, "0 0 " UID_FMT "\n", (uid_t) UINT32_MAX) < 0)
return -ENOMEM;
break;
case PRIVATE_USERS_SELF:
/* Can only set up multiple mappings with CAP_SETUID. */
if (uid_is_valid(*uid) && *uid != saved_uid && have_effective_cap(CAP_SETUID) > 0)
r = asprintf(&uid_map,
UID_FMT " " UID_FMT " 1\n" /* Map $OUID → $OUID */
UID_FMT " " UID_FMT " 1\n", /* Map $UID → $UID */
saved_uid, saved_uid, *uid, *uid);
else
r = asprintf(&uid_map,
UID_FMT " " UID_FMT " 1\n", /* Map $OUID → $OUID */
saved_uid, saved_uid);
if (r < 0)
return -ENOMEM;
break;
default:
assert_not_reached();
}
switch (private_users) { /* Prepare the GID mappings */
case PRIVATE_USERS_IDENTITY:
gid_map = strdup("0 0 65536\n");
if (!gid_map)
return -ENOMEM;
break;
case PRIVATE_USERS_FULL:
if (asprintf(&gid_map, "0 0 " GID_FMT "\n", (gid_t) UINT32_MAX) < 0)
return -ENOMEM;
break;
case PRIVATE_USERS_SELF:
/* Can only set up multiple mappings with CAP_SETGID. */
if (gid_is_valid(*gid) && *gid != saved_gid && have_effective_cap(CAP_SETGID) > 0)
r = asprintf(&gid_map,
GID_FMT " " GID_FMT " 1\n" /* Map $OGID → $OGID */
GID_FMT " " GID_FMT " 1\n", /* Map $GID → $GID */
saved_gid, saved_gid, *gid, *gid);
else
r = asprintf(&gid_map,
GID_FMT " " GID_FMT " 1\n", /* Map $OGID -> $OGID */
saved_gid, saved_gid);
if (r < 0)
return -ENOMEM;
break;
default:
assert_not_reached();
}
/* Create a communication channel so that the parent can tell the child when it finished creating the user
* namespace. */
unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
if (unshare_ready_fd < 0)
return -errno;
/* Create a communication channel so that the child can tell the parent a proper error code in case it
* failed. */
if (pipe2(errno_pipe, O_CLOEXEC) < 0)
return -errno;
r = pidref_safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL, &pidref);
if (r < 0)
return r;
if (r == 0) {
errno_pipe[0] = safe_close(errno_pipe[0]);
r = setup_private_users_child(unshare_ready_fd, uid_map, gid_map, allow_setgroups);
if (r < 0)
report_errno_and_exit(errno_pipe[1], r);
_exit(EXIT_SUCCESS);
}
errno_pipe[1] = safe_close(errno_pipe[1]);
if (unshare(CLONE_NEWUSER) < 0)
return log_debug_errno(errno, "Failed to unshare user namespace: %m");
/* Let the child know that the namespace is ready now */
if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
return -errno;
/* Try to read an error code from the child */
n = read(errno_pipe[0], &r, sizeof(r));
if (n < 0)
return -errno;
if (n == sizeof(r)) { /* an error code was sent to us */
if (r < 0)
return r;
return -EIO;
}
if (n != 0) /* on success we should have read 0 bytes */
return -EIO;
r = pidref_wait_for_terminate_and_check("(sd-userns)", &pidref, 0);
if (r < 0)
return r;
pidref_done(&pidref);
if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
return -EIO;
return 1;
}
static int can_mount_proc(void) {
_cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR;
_cleanup_(pidref_done_sigkill_wait) PidRef pidref = PIDREF_NULL;
ssize_t n;
int r;
/* If running via unprivileged user manager and /proc/ is masked (e.g. /proc/kmsg is over-mounted with tmpfs
* like systemd-nspawn does), then mounting /proc/ will fail with EPERM. This is due to a kernel restriction
* where unprivileged user namespaces cannot mount a less restrictive instance of /proc. */
/* Create a communication channel so that the child can tell the parent a proper error code in case it
* failed. */
if (pipe2(errno_pipe, O_CLOEXEC) < 0)
return log_debug_errno(errno, "Failed to create pipe for communicating with child process (sd-proc-check): %m");
/* Fork a child process into its own mount and PID namespace. Note safe_fork() already remounts / as SLAVE
* with FORK_MOUNTNS_SLAVE. */
r = pidref_safe_fork(
"(sd-proc-check)",
FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_NEW_PIDNS,
&pidref);
if (r < 0)
return log_debug_errno(r, "Failed to fork child process (sd-proc-check): %m");
if (r == 0) {
errno_pipe[0] = safe_close(errno_pipe[0]);
/* Try mounting /proc on /dev/shm/. No need to clean up the mount since the mount
* namespace will be cleaned up once the process exits. */
r = mount_follow_verbose(LOG_DEBUG, "proc", "/dev/shm/", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL);
if (r < 0) {
(void) write(errno_pipe[1], &r, sizeof(r));
_exit(EXIT_FAILURE);
}
_exit(EXIT_SUCCESS);
}
errno_pipe[1] = safe_close(errno_pipe[1]);
/* Try to read an error code from the child */
n = read(errno_pipe[0], &r, sizeof(r));
if (n < 0)
return log_debug_errno(errno, "Failed to read errno from pipe with child process (sd-proc-check): %m");
if (n == sizeof(r)) { /* an error code was sent to us */
/* This is the expected case where proc cannot be mounted due to permissions. */
if (ERRNO_IS_NEG_PRIVILEGE(r))
return 0;
if (r < 0)
return r;
return -EIO;
}
if (n != 0) /* on success we should have read 0 bytes */
return -EIO;
r = pidref_wait_for_terminate_and_check("(sd-proc-check)", &pidref, /* flags= */ 0);
if (r < 0)
return log_debug_errno(r, "Failed to wait for (sd-proc-check) child process to terminate: %m");
pidref_done(&pidref);
if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Child process (sd-proc-check) exited with unexpected exit status '%d'.", r);
return 1;
}
static int setup_private_pids(const ExecContext *c, ExecParameters *p, int *ret_keep_parent_fd /* may be NULL */) {
_cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
_cleanup_close_pair_ int errno_pipe[2] = EBADF_PAIR, keep_parent_pipe[2] = EBADF_PAIR;
ssize_t n;
int r, q;
assert(c);
assert(p);
assert(p->pidref_transport_fd >= 0);
/* The first process created after unsharing a pid namespace becomes PID 1 in the pid namespace, so
* we have to fork after unsharing the pid namespace to become PID 1. The parent sends the child
* pidref to the manager and exits while the child process continues with the rest of exec_invoke()
* and finally executes the actual payload. */
/* Create a communication channel so that the parent can tell the child a proper error code in case it
* failed to send child pidref to the manager. */
if (pipe2(errno_pipe, O_CLOEXEC) < 0)
return log_debug_errno(errno, "Failed to create pipe for communicating with parent process: %m");
/* The parent opened connections to mountfsd and nsresourced, so those services will lookup
* information through the parent process. So the parent needs to stick around until the child is
* done. The parent waits until the child closes the fd returned in ret_keep_parent_fd. */
if (ret_keep_parent_fd && pipe2(keep_parent_pipe, O_CLOEXEC) < 0)
return log_debug_errno(errno, "Failed to create pipe for waiting for child process: %m");
/* Set FORK_DETACH to immediately re-parent the child process to the invoking manager process. */
r = pidref_safe_fork("(sd-pidns-child)", FORK_NEW_PIDNS|FORK_DETACH, &pidref);
if (r < 0)
return log_debug_errno(r, "Failed to fork child into new pid namespace: %m");
if (r > 0) {
errno_pipe[0] = safe_close(errno_pipe[0]);
/* In the parent process, we send the child pidref to the manager and exit.
* If PIDFD is not supported, only the child PID is sent. The server then
* uses the child PID to set the new exec main process. */
q = send_one_fd_iov(
p->pidref_transport_fd,
pidref.fd,
&IOVEC_MAKE(&pidref.pid, sizeof(pidref.pid)),
/* iovlen= */ 1,
/* flags= */ 0);
/* Send error code to child process. Close the pipe right away so that the child doesn't
* block in read() if the write failed, as we might wait for the child below. */
(void) write(errno_pipe[1], &q, sizeof(q));
errno_pipe[1] = safe_close(errno_pipe[1]);
if (ret_keep_parent_fd) {
keep_parent_pipe[1] = safe_close(keep_parent_pipe[1]);
for (;;) {
r = fd_wait_for_event(keep_parent_pipe[0], POLLHUP, USEC_INFINITY);
if (r != -EINTR)
break;
}
}
/* Exit here so we only go through the destructors in exec_invoke only once - in the child - as
* some destructors have external effects. The main codepaths continue in the child process. */
_exit(q < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
}
errno_pipe[1] = safe_close(errno_pipe[1]);
keep_parent_pipe[0] = safe_close(keep_parent_pipe[0]);
p->pidref_transport_fd = safe_close(p->pidref_transport_fd);
/* Try to read an error code from the parent. Note a child process cannot wait for the parent so we always
* receive an errno even on success. */
n = read(errno_pipe[0], &r, sizeof(r));
if (n < 0)
return log_debug_errno(errno, "Failed to read errno from pipe with parent process: %m");
if (n != sizeof(r))
return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Failed to read enough bytes from pipe with parent process");
if (r < 0)
return log_debug_errno(r, "Failed to send child pidref to manager: %m");
if (ret_keep_parent_fd)
*ret_keep_parent_fd = TAKE_FD(keep_parent_pipe[1]);
/* NOTE! This function returns in the child process only. */
return r;
}
static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
_cleanup_free_ char *src_abs = NULL;
int r;
assert(root);
assert(source);
src_abs = path_join(root, source);
if (!src_abs)
return -ENOMEM;
STRV_FOREACH(dst, symlinks) {
_cleanup_free_ char *dst_abs = NULL;
dst_abs = path_join(root, *dst);
if (!dst_abs)
return -ENOMEM;
r = mkdir_parents_label(dst_abs, 0755);
if (r < 0)
return r;
r = symlink_idempotent(src_abs, dst_abs, true);
if (r < 0)
return r;
}
return 0;
}
static int set_exec_storage_quota(int fd, uint32_t proj_id, const ExecQuotaLimit *ql) {
int r;
uint64_t block_limit = 0, inode_limit = 0;
assert(fd >= 0);
assert(ql);
if (ql->quota_absolute == 0 || ql->quota_scale == 0)
/* Limit of 0 means no usage is allowed. For quotactl, use 1 as the limit, since 0 means that
* hard limits are disabled */
block_limit = inode_limit = 1;
else if (ql->quota_absolute == UINT64_MAX) {
_cleanup_close_ int fd_parent = -EBADF;
/* Use target_dir's parent when setting quotas. If a FD for target_dir has been previously
* used for quotactl_fd(SET) and is passed again for fstatvfs(), the total number of blocks is not
* reported accurately (instead, the block limit is reported as total blocks). Thus, use the FD
* associated with the parent, so that total blocks is accurate */
fd_parent = openat(fd, "..", O_PATH|O_CLOEXEC|O_DIRECTORY);
if (fd_parent < 0)
return -errno;
uint32_t xattr_flags = 0;
r = read_fs_xattr_fd(fd_parent, &xattr_flags, /* ret_projid= */ NULL);
if (r < 0)
return r;
/* Refuse if parent has FS_XFLAG_PROJINHERIT since this will mean the total number of blocks will not
* be reported accurately */
if (FLAGS_SET(xattr_flags, FS_XFLAG_PROJINHERIT))
return -ENOMEDIUM;
struct statvfs disk_st;
if (fstatvfs(fd_parent, &disk_st) < 0)
return -errno;
block_limit = (uint64_t) DIV_ROUND_UP((uint64_t)((double) (disk_st.f_frsize * disk_st.f_blocks) / UINT32_MAX * ql->quota_scale), QIF_DQBLKSIZE);
inode_limit = (uint64_t) ((double) disk_st.f_files / UINT32_MAX * ql->quota_scale);
} else
block_limit = (uint64_t) DIV_ROUND_UP(ql->quota_absolute, QIF_DQBLKSIZE);
struct dqblk req = {
.dqb_bhardlimit = block_limit,
.dqb_ihardlimit = inode_limit,
.dqb_valid = QIF_LIMITS,
};
r = quotactl_fd_with_fallback(fd, QCMD_FIXED(Q_SETQUOTA, PRJQUOTA), proj_id, &req);
if (r < 0)
return r;
log_debug("Storage quotas set for project id %" PRIu32 ". Block limit = %" PRIu64 ", inode limit = %" PRIu64, proj_id, block_limit, inode_limit);
return 0;
}
static int unset_exec_storage_quota(int fd, uint32_t proj_id, bool quota_accounting) {
int r, quota_supported;
struct dqblk req;
assert(fd >= 0);
quota_supported = quota_query_proj_id(fd, proj_id, &req);
if (quota_supported < 0)
return log_debug_errno(quota_supported, "Failed to query disk quota for project ID %" PRIu32 ": %m", proj_id);
/* Do not enforce quotas anymore */
if (quota_supported && FLAGS_SET(req.dqb_valid, QIF_BLIMITS) && (req.dqb_bhardlimit > 0 || req.dqb_ihardlimit > 0)) {
req.dqb_bhardlimit = 0, req.dqb_ihardlimit = 0;
r = quotactl_fd_with_fallback(fd, QCMD_FIXED(Q_SETQUOTA, PRJQUOTA), proj_id, &req);
if (r < 0)
return log_debug_errno(r, "Failed to disable project quotas for project ID %" PRIu32 ": %m", proj_id);
log_debug("Storage quotas for project ID %" PRIu32 " were disabled", proj_id);
}
/* Release project ID if no accounting needed */
if (!quota_accounting) {
r = set_proj_id_recursive(fd, 0);
if (r < 0)
log_warning_errno(r, "Failed to release project ID %" PRIu32 ", ignoring: %m", proj_id);
}
return 0;
}
static int apply_exec_quotas(
const char *target_dir,
const char *cgroup_path,
ExecDirectoryType type,
const ExecQuotaLimit *ql,
uint32_t *exec_dt_proj_id, /* in/out */
bool *already_enforced) { /* in/out */
_cleanup_close_ int fd = -EBADF;
int r, quota_supported = 0;
assert(target_dir);
assert(cgroup_path);
assert(ql);
assert(exec_dt_proj_id);
assert(already_enforced);
/* Do not apply to the Runtime directory since tmpfs does not support project IDs yet */
if (!IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_CACHE, EXEC_DIRECTORY_LOGS))
return 0;
fd = open(target_dir, O_PATH|O_CLOEXEC|O_DIRECTORY);
if (fd < 0)
return log_debug_errno(errno, "Failed to open %s: %m", target_dir);
/* Get the project ID of the current directory */
uint32_t proj_id;
r = read_fs_xattr_fd(fd, /* ret_xflags= */ NULL, &proj_id);
if (ERRNO_IS_NEG_IOCTL_NOT_SUPPORTED(r)) {
log_debug_errno(r, "Not applying storage quotas. FS_IOC_FSGETXATTR not supported for %s: %m", target_dir);
return 0;
}
if (r < 0)
return log_debug_errno(r, "Failed to retrieve project ID for %s: %m", target_dir);
/* If the first directory of this ExecType already has a project ID, adopt it as the project ID for all dirs of this ExecType */
bool proj_id_exists = PROJ_ID_MIN <= proj_id && proj_id <= PROJ_ID_MAX;
if (proj_id_exists && *exec_dt_proj_id == 0)
*exec_dt_proj_id = proj_id;
/* Check if enforcement should be disabled. Do not release project ID if accounting is enabled */
if (!ql->quota_enforce) {
if (proj_id_exists) {
r = unset_exec_storage_quota(fd, proj_id, ql->quota_accounting);
if (r < 0)
return log_debug_errno(r, "Failed to unset project quotas for %s: %m", target_dir);
}
if (!ql->quota_accounting)
return 0;
}
if (*exec_dt_proj_id > 0 && *exec_dt_proj_id != proj_id) {
/* Set the existing project ID only if the current directory's ID does not exist or does not match */
proj_id = *exec_dt_proj_id;
r = quota_proj_id_set_recursive(fd, proj_id, false);
if (r < 0)
return log_debug_errno(r, "Failed to set project ID for %s: %m", target_dir);
} else if (*exec_dt_proj_id == 0) {
/* Only generate a new project ID if it's the first directory of this ExecType to be processed and does not have an existing ID */
static const sd_id128_t k = SD_ID128_ARRAY(e1,4a,79,9b,64,40,41,4a,a8,46,c2,f3,f9,19,4f,01);
_cleanup_free_ char *proj_id_plain = NULL;
/* Generate candidate project id */
proj_id_plain = strjoin(cgroup_path, "|", exec_directory_type_to_string(type));
if (!proj_id_plain)
return log_oom_debug();
struct siphash state;
siphash24_init(&state, k.bytes);
siphash24_compress_string(proj_id_plain, &state);
proj_id = PROJ_ID_CLAMP_INTO_QUOTA_RANGE(siphash24_finalize(&state));
#define MAX_PROJ_ID_RETRIES 10
for (unsigned attempt = 0;; attempt++) {
if (attempt >= MAX_PROJ_ID_RETRIES)
return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "Failed to generate unique project ID for '%s'.", target_dir);
/* Check if project quotas are supported */
struct dqblk req;
quota_supported = quota_query_proj_id(fd, proj_id, &req);
if (quota_supported < 0)
return log_debug_errno(quota_supported, "Failed to query disk quota for project ID %" PRIu32 ": %m", proj_id);
if (!quota_supported) {
log_debug("Not applying storage quotas. Project quotas are not supported for %s", target_dir);
return 0;
}
if (!quota_dqblk_is_populated(&req)) {
int proj_id_was_set = quota_proj_id_set_recursive(fd, proj_id, true);
if (proj_id_was_set < 0)
return log_debug_errno(proj_id_was_set, "Failed to set project ID for %s: %m", target_dir);
if (proj_id_was_set) {
*exec_dt_proj_id = proj_id;
log_debug("Project ID %u generated for %s", proj_id, target_dir);
break;
}
}
proj_id = (uint32_t) (random_u64_range(PROJ_ID_MAX - PROJ_ID_MIN + 1) + PROJ_ID_MIN);
}
}
if (ql->quota_enforce && !*already_enforced) {
if (!quota_supported) {
struct dqblk req;
quota_supported = quota_query_proj_id(fd, proj_id, &req);
if (quota_supported < 0)
return log_debug_errno(quota_supported, "Failed to query disk quota for project ID %" PRIu32 ": %m", proj_id);
if (!quota_supported) {
log_debug("Not applying storage quotas. Project quotas are not supported for %s", target_dir);
return 0;
}
}
r = set_exec_storage_quota(fd, proj_id, ql);
if (r < 0)
return log_debug_errno(r, "Failed to set storage quotas for %s: %m", target_dir);
*already_enforced = true;
}
return r;
}
static int setup_exec_directory(
const ExecContext *context,
const ExecParameters *params,
uid_t uid,
gid_t gid,
ExecDirectoryType type,
bool needs_mount_namespace,
int *exit_status) {
static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
[EXEC_DIRECTORY_RUNTIME] = EXIT_RUNTIME_DIRECTORY,
[EXEC_DIRECTORY_STATE] = EXIT_STATE_DIRECTORY,
[EXEC_DIRECTORY_CACHE] = EXIT_CACHE_DIRECTORY,
[EXEC_DIRECTORY_LOGS] = EXIT_LOGS_DIRECTORY,
[EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
};
int r;
assert(context);
assert(params);
assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
assert(exit_status);