HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/core/exec-credential.c
Git blob: 9c209404d3a4aee499f37dabc5255368628dba9c
Lines 1001–1358 of 1,358
log_debug_errno(r, "Credential dir '%s' already populated, exchanging with workspace.", cred_dir);
r = RET_NERRNO(renameat2(AT_FDCWD, workspace, AT_FDCWD, cred_dir, RENAME_EXCHANGE));
}
if (r < 0)
return log_debug_errno(r, "Failed to move credentials workspace into place: %m");
/* rename() requires both the source and target to be writable, hence lock down write permission
* as last step. */
r = credentials_dir_finalize_permissions(dfd, context->uid, context->gid, /* ownership_ok= */ false);
if (r < 0)
return log_debug_errno(r, "Failed to adjust ACLs of credentials dir: %m");
return 0;
}
static int setup_credentials_internal(
const SetupCredentialsContext *context,
bool may_reuse,
const char *cred_dir) {
_cleanup_close_ int fs_fd = -EBADF, mfd = -EBADF, dfd = -EBADF;
bool dir_mounted;
int r;
assert(context);
assert(cred_dir);
r = path_is_mount_point(cred_dir);
if (r < 0)
return log_debug_errno(r, "Failed to determine if '%s' is a mountpoint: %m", cred_dir);
dir_mounted = r > 0;
if (may_reuse) {
bool populated;
/* If the cred dir is a mount, let's treat it as populated, and only look at the contents
* if it's a plain dir, where we can't reasonably differentiate populated yet empty vs
* not set up. */
if (dir_mounted)
populated = true;
else {
r = dir_is_empty(cred_dir, /* ignore_hidden_or_backup= */ false);
if (r < 0)
return r;
populated = r == 0;
}
if (populated) {
log_debug("Credential dir for unit '%s' already set up, skipping.", context->unit);
return 0;
}
}
mfd = fsmount_credentials_fs(&fs_fd);
if (ERRNO_IS_NEG_PRIVILEGE(mfd) && !dir_mounted) {
log_debug_errno(mfd, "Lacking privilege to mount credentials fs, falling back to plain directory.");
return setup_credentials_plain_dir(context, cred_dir);
}
if (mfd < 0)
return log_debug_errno(mfd, "Failed to mount credentials fs: %m");
dfd = fd_reopen(mfd, O_DIRECTORY|O_CLOEXEC);
if (dfd < 0)
return dfd;
(void) label_fix_full(dfd, /* inode_path= */ NULL, cred_dir, /* flags= */ 0, /* label_context= */ NULL);
r = acquire_credentials(context, dfd, /* ownership_ok= */ true);
if (r < 0)
return r;
r = credentials_dir_finalize_permissions(dfd, context->uid, context->gid, /* ownership_ok= */ true);
if (r < 0)
return log_debug_errno(r, "Failed to adjust ACLs of credentials dir: %m");
// Work around a kernel bug that results in tmpfs reconfiguration failure.
// FIXME: drop this once https://lore.kernel.org/linux-fsdevel/20251108190930.440685-1-me@yhndnzj.com/
// is merged and hits the distro kernels.
(void) fsconfig(fs_fd, FSCONFIG_SET_FLAG, "noswap", NULL, 0);
if (fsconfig(fs_fd, FSCONFIG_SET_FLAG, "ro", NULL, 0) < 0)
return -errno;
if (fsconfig(fs_fd, FSCONFIG_CMD_RECONFIGURE, NULL, NULL, 0) < 0)
return -errno;
log_debug("Successfully reconfigured credentials fs to be read only.");
if (dir_mounted) {
/* Firstly, try to move beneath the existing mount, which guarantees strictly atomic replacement
* (needs kernel >= 6.5) */
r = move_mount(mfd, "", AT_FDCWD, cred_dir, MOVE_MOUNT_F_EMPTY_PATH|MOVE_MOUNT_BENEATH);
if (r >= 0)
return umount_verbose(LOG_DEBUG, cred_dir, MNT_DETACH|UMOUNT_NOFOLLOW);
if (errno != EINVAL)
return log_debug_errno(errno, "Failed to move credentials fs into place: %m");
log_debug_errno(errno, "Unable to move credentials fs beneath existing mount '%s', unmounting instead: %m",
cred_dir);
r = umount_verbose(LOG_DEBUG, cred_dir, MNT_DETACH|UMOUNT_NOFOLLOW);
if (r < 0)
return r;
}
r = move_mount(mfd, "", AT_FDCWD, cred_dir, MOVE_MOUNT_F_EMPTY_PATH);
if (r < 0)
return log_debug_errno(errno, "Failed to move credentials fs into place: %m");
return 0;
}
int exec_setup_credentials(
const ExecContext *context,
const CGroupContext *cgroup_context,
const ExecParameters *params,
uid_t uid,
gid_t gid) {
_cleanup_free_ char *p = NULL, *q = NULL;
int r;
assert(context);
assert(params);
if (!exec_params_need_credentials(params) || !exec_context_has_credentials(context))
return 0;
if (!params->prefix[EXEC_DIRECTORY_RUNTIME])
return -EINVAL;
/* This is where we'll place stuff when we are done; the main credentials directory is world-readable,
* and the subdir we mount over with a read-only file system readable by the service's user. */
q = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "credentials");
if (!q)
return -ENOMEM;
r = mkdir_label(q, 0755); /* top-level dir: world readable/searchable */
if (r < 0 && r != -EEXIST)
return r;
p = path_join(q, params->unit_id);
if (!p)
return -ENOMEM;
r = mkdir_label(p, 0700); /* per-unit dir: private to user */
if (r < 0 && r != -EEXIST)
return r;
SetupCredentialsContext ctx = {
.scope = params->runtime_scope,
.exec_context = context,
.unit = params->unit_id,
.runtime_prefix = params->prefix[EXEC_DIRECTORY_RUNTIME],
.received_credentials_directory = params->received_credentials_directory,
.received_encrypted_credentials_directory = params->received_encrypted_credentials_directory,
.always_ipc = device_nodes_restricted(context, cgroup_context),
.uid = uid,
.gid = gid,
};
r = setup_credentials_internal(&ctx, /* may_reuse = */ !FLAGS_SET(params->flags, EXEC_SETUP_CREDENTIALS_FRESH), p);
if (r < 0)
(void) rmdir(p);
return r;
}
static int refresh_credentials_in_namespace_child(int cfd, const char *cred_dir) {
int r;
assert(cfd >= 0);
assert(cred_dir);
/* Paranoia: before doing anything, check if the credentials tree inside the mountns is available.
*
* Note that setup_namespace() always installs a mount for cred dir, hence path_is_mount_point()
* is the appropriate check here. */
r = path_is_mount_point(cred_dir);
if (IN_SET(r, 0, -ENOENT)) {
log_full_errno_zerook(LOG_WARNING, r,
"Credentials tree in the unit mount namespace is masked, skipping refresh.");
return 0;
}
if (r < 0)
return log_error_errno(r, "Failed to check whether '%s' is a mountpoint in unit mount namespace: %m",
cred_dir);
/* Inform the parent that we're good to go */
ssize_t n = write(cfd, &r, sizeof(r));
if (n < 0)
return log_error_errno(errno, "Failed to write to socket: %m");
_cleanup_close_ int mfd = receive_one_fd(cfd, /* flags = */ 0);
if (mfd < 0)
return log_error_errno(mfd, "Failed to receive credentials tree fd from socket: %m");
r = mount_exchange_graceful(mfd, cred_dir, /* mount_beneath = */ true);
if (r < 0)
return log_error_errno(r, "Failed to update credentials mount in namespace: %m");
return 1;
}
int unit_refresh_credentials(Unit *u) {
_cleanup_free_ char *cred_dir = NULL;
int r;
/* Refresh the credentials for a unit, potentially forking off a second process to join the mountns
* if needed. Returns > 0 on successful refresh, == 0 if the credentials tree is masked and the operation
* is skipped. */
assert(u);
assert(u->manager);
r = get_credential_directory(u->manager->prefix[EXEC_DIRECTORY_RUNTIME], u->id, &cred_dir);
if (r < 0)
return log_oom();
assert(r > 0);
if (access(cred_dir, F_OK) < 0) {
if (errno == ENOENT) {
log_warning_errno(errno, "Requested to refresh credentials, but credentials aren't populated, skipping.");
return 0;
}
return log_error_errno(errno, "Failed to check if credentials dir '%s' exists: %m", cred_dir);
}
_cleanup_close_pair_ int tunnel_fds[2] = EBADF_PAIR;
_cleanup_(pidref_done) PidRef child = PIDREF_NULL;
_cleanup_close_ int userns_fd = -EBADF;
PidRef *main_pid = unit_main_pid(u);
if (pidref_is_set(main_pid)) {
_cleanup_close_ int mntns_fd = -EBADF, root_fd = -EBADF, pidns_fd = -EBADF;
r = pidref_namespace_open(main_pid,
&pidns_fd,
&mntns_fd,
/* ret_netns_fd = */ NULL,
MANAGER_IS_USER(u->manager) ? &userns_fd : NULL,
&root_fd);
if (r < 0)
return log_error_errno(r, "Failed to open namespace of unit main process '" PID_FMT "': %m",
main_pid->pid);
r = is_our_namespace(mntns_fd, NAMESPACE_MOUNT);
if (r < 0)
return log_error_errno(r, "Failed to check if main process resides in a separate mount namespace: %m");
if (r == 0) {
if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, tunnel_fds) < 0)
return log_error_errno(errno, "Failed to allocate socket pair: %m");
/* User units with PrivateUsers=self only map the user manager's own identity. Keep it
* in that case, but still become root when a managed UID/GID range is mapped. */
r = namespace_fork_full("(sd-creds-ns)", "(sd-creds-ns-inner)",
(int[]) { tunnel_fds[1] }, 1,
FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_CLOSE_ALL_FDS|FORK_REOPEN_LOG,
pidns_fd, mntns_fd, /* netns_fd = */ -EBADF, userns_fd, root_fd,
MANAGER_IS_USER(u->manager) ?
NAMESPACE_ENTER_KEEP_UID_GID_IF_ROOT_UNMAPPED : 0,
&child);
if (r < 0)
return log_full_errno(ERRNO_IS_NEG_PRIVILEGE(r) ? LOG_WARNING : LOG_ERR, r,
"Failed to fork off process into unit namespace to refresh credentials: %m");
if (r == 0) {
r = refresh_credentials_in_namespace_child(tunnel_fds[1], cred_dir);
report_errno_and_exit(tunnel_fds[1], r);
}
tunnel_fds[1] = safe_close(tunnel_fds[1]);
/* Wait for the child to validate the creds tree in the unit namespace is populated. */
ssize_t n = read(tunnel_fds[0], &r, sizeof(r));
if (n < 0)
return log_error_errno(errno, "Failed to read from socket: %m");
if (!IN_SET(n, 0, sizeof(r)))
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Received unexpected amount of bytes (%zi) while reading errno.", n);
if (n == 0 || r == 0) {
/* The child exited without sending anything or 0 is received signifying
* the credentials are masked? Check the exit status to be sure. */
r = pidref_wait_for_terminate_and_check("(sd-creds-ns)", &child, WAIT_LOG);
if (r < 0)
return r;
if (r != EXIT_SUCCESS)
return -EPROTO;
return 0; /* skipped */
}
if (r < 0)
return r;
/* Yay! Got > 0 from child indicating all good, proceed with refreshing. */
}
}
SetupCredentialsContext ctx = {
.scope = u->manager->runtime_scope,
.exec_context = ASSERT_PTR(unit_get_exec_context(u)),
.unit = u->id,
.runtime_prefix = u->manager->prefix[EXEC_DIRECTORY_RUNTIME],
.received_credentials_directory = u->manager->received_credentials_directory,
.received_encrypted_credentials_directory = u->manager->received_encrypted_credentials_directory,
.always_ipc = false, /* we don't migrate to unit cgroup, hence cannot be restricted by cgroup bpf */
.uid = u->ref_uid,
.gid = u->ref_gid,
};
r = setup_credentials_internal(&ctx, /* may_reuse = */ false, cred_dir);
if (r < 0)
return log_error_errno(r, "Failed to set up credentials: %m");
/* The main process doesn't run in a mountns hence nothing got forked off? Then we're all set. */
if (!pidref_is_set(&child))
return 1;
if (userns_fd >= 0) {
assert(MANAGER_IS_USER(u->manager));
/* Enter the unit userns now and unshare mountns, so that we have permissions to clone
* the mount tree using open_tree() */
if (setns(userns_fd, CLONE_NEWUSER) < 0)
return log_error_errno(errno, "Failed to enter user namespace: %m");
if (unshare(CLONE_NEWNS) < 0)
return log_error_errno(errno, "Failed to unshare mount namespace: %m");
}
_cleanup_close_ int tfd = open_tree(AT_FDCWD, cred_dir, OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_SYMLINK_NOFOLLOW);
if (tfd < 0)
return log_error_errno(errno, "Failed to clone mount tree at '%s': %m", cred_dir);
r = send_one_fd(tunnel_fds[0], tfd, /* flags = */ 0);
if (r < 0)
return log_error_errno(r, "Failed to send mount fd to child: %m");
r = pidref_wait_for_terminate_and_check("(sd-creds-ns)", &child, WAIT_LOG_ABNORMAL);
if (r < 0)
return r;
if (r != EXIT_SUCCESS) {
r = read_errno(tunnel_fds[0]);
if (r < 0)
return r;
return -EPROTO;
}
return 1;
}