HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/nsresourced/nsresourcework.c
Git blob: 464f373f21773862291bc192c5f28a0b78e42b97
Lines 1001–2000 of 2,683
if (gid_is_transient(userns_info->start_gid) && start_gid != userns_info->start_gid)
return log_debug_errno(
SYNTHETIC_ERRNO(ERANGE),
"Transient GID range not mapped 1:1 in parent userns ("GID_FMT" -> "GID_FMT")",
userns_info->start_gid, start_gid);
_cleanup_free_ char *gidmap = NULL;
if (asprintf(&gidmap, GID_FMT " " GID_FMT " %" PRIu32 "\n",
userns_info->target_gid, start_gid, userns_info->size) < 0)
return log_oom();
log_debug("GID mapping: " GID_FMT " " GID_FMT " %" PRIu32,
userns_info->target_gid, userns_info->start_gid, userns_info->size);
FOREACH_ARRAY(delegate, userns_info->delegates, userns_info->n_delegates) {
r = uid_range_translate(outside_range, inside_range, delegate->start_gid, &start_gid);
if (r < 0)
return log_debug_errno(r, "Failed to translate GID "GID_FMT" to parent userns: %m", userns_info->start_gid);
if (start_gid != delegate->start_gid)
return log_debug_errno(
SYNTHETIC_ERRNO(ERANGE),
"Delegated transient GID range not mapped 1:1 in parent userns ("GID_FMT" -> "GID_FMT")",
delegate->start_gid, start_gid);
/* Delegated ranges are mapped 1:1 (inside GID == outside GID) */
if (strextendf(&gidmap, GID_FMT " " GID_FMT " %" PRIu32 "\n",
delegate->start_gid,
start_gid,
delegate->size) < 0)
return log_oom();
log_debug("GID mapping: " GID_FMT " " GID_FMT " %" PRIu32,
delegate->start_gid, start_gid, delegate->size);
}
if (map_foreign) {
r = uid_range_translate(outside_range, inside_range, FOREIGN_UID_MIN, &start_gid);
if (r < 0)
return log_debug_errno(r, "Failed to translate GID "GID_FMT" to parent userns: %m", FOREIGN_UID_MIN);
if (start_gid != FOREIGN_UID_MIN)
return log_debug_errno(
SYNTHETIC_ERRNO(ERANGE),
"Foreign GID range not mapped 1:1 in parent userns ("GID_FMT" -> "GID_FMT")",
FOREIGN_UID_MIN, start_gid);
if (strextendf(&gidmap, GID_FMT " " GID_FMT " %" PRIu32 "\n",
FOREIGN_UID_MIN, start_gid, NSRESOURCE_UIDS_64K) < 0)
return log_oom();
}
r = is_our_namespace(parent_userns_fd, NAMESPACE_USER);
if (r < 0)
return log_debug_errno(r, "Failed to check if parent user namespace refers to our own user namespace: %m");
if (r > 0)
return write_userns_mappings(&pidref, uidmap, gidmap);
/* The kernel is paranoid that the uid_map and gid_map files are written either from the user
* namespace itself or its parent user namespace, so we have to join the parent user namespace to
* write the files. */
r = pidref_safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_LOG|FORK_WAIT, /* ret= */ NULL);
if (r < 0)
return r;
if (r == 0) {
if (setns(parent_userns_fd, CLONE_NEWUSER) < 0) {
log_error_errno(errno, "Failed to join parent user namespace: %m");
_exit(EXIT_FAILURE);
}
r = write_userns_mappings(&pidref, uidmap, gidmap);
_exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
}
/* We are done! */
log_debug("Successfully configured user namespace.");
return 0;
}
static int test_userns_api_support(sd_varlink *link) {
int r;
assert(link);
/* We only expose the userns API if our manager daemon told us this OK to do. It will set this
* boolean only if it managed to set up BPF correctly for itself (i.e. watches for userns going away
* via BPF APIs). This should make very sure we don't accidentally allow any of the userns stuff to
* go through without the BPF LSM in effect. */
r = getenv_bool("NSRESOURCE_API");
if (r < 0)
return log_error_errno(r, "Failed to parse $NSRESOURCE_API: %m");
if (r == 0)
return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceInterfaceNotSupported", NULL);
return 0;
}
static char* hash_name(sd_varlink *link, const char *name) {
int r;
assert(link);
assert(name);
/* Make up a hashed name for this userns. We take the passed name, and hash it together with the
* connection cookie. This should make collisions unlikely but generation still deterministic (this
* matters because on polkit requests we might be called twice, and should generate the same string
* each time, to ensure the Polkit query looks the same) */
uint64_t cookie = 0;
r = socket_get_cookie(sd_varlink_get_fd(link), &cookie);
if (r < 0)
log_debug_errno(r, "Failed to determine connection cookie, ignoring: %m");
struct siphash h;
static sd_id128_t key = SD_ID128_MAKE(ed,3a,bb,01,3a,14,4b,b3,8a,63,a4,ad,ba,2d,c9,0a);
siphash24_init(&h, key.bytes);
siphash24_compress_typesafe(cookie, &h);
siphash24_compress_string(name, &h);
/* Make sure the hashed name fits into utmpx even if prefixed with "ns-", the peer's UID, "-", and
* suffixed by "-65535". */
assert_cc(STRLEN("ns-65535-") + 16 + STRLEN("-65535") < sizeof_field(struct utmpx, ut_user));
char *s = NULL;
if (asprintf(&s, "%016" PRIx64, siphash24_finalize(&h)) < 0)
return NULL;
return s;
}
static char *shorten_name(const char *name) {
/* Shorten the specified name, so that it works as a userns name */
char *n = strdup(name);
if (!n)
return NULL;
/* make sure the truncated name fits into utmpx even if prefixed with "ns-" and suffixed by "-65535" */
strshorten(n, sizeof_field(struct utmpx, ut_user) - STRLEN("ns-") - STRLEN("-65536") - 1);
return n;
}
static int validate_name(sd_varlink *link, const char *name, bool mangle, char **ret) {
int r;
assert(link);
assert(name);
assert(ret);
uid_t peer_uid;
r = sd_varlink_get_peer_uid(link, &peer_uid);
if (r < 0)
return r;
_cleanup_free_ char *un = NULL;
if (peer_uid == 0) {
/* If the client is root, we'll not prefix it, but we will make sure it's suitable for
* inclusion in a user name */
if (userns_name_is_valid(name)) {
un = strdup(name);
if (!un)
return -ENOMEM;
} else {
if (!mangle)
return sd_varlink_error_invalid_parameter_name(link, "name");
un = shorten_name(name);
if (!un)
return -ENOMEM;
/* Let's see if shortening was enough? (It might not be, for example because an empty
* string was provided – which no truncation would make valid.) */
if (!userns_name_is_valid(un)) {
free(un);
/* if not, make up a hashed name */
un = hash_name(link, name);
if (!un)
return -ENOMEM;
}
}
} else {
/* If the client is not root then prefix the name with the UID of the peer, so that they live
* in separate namespaces and cannot interfere with each other's names. */
if (asprintf(&un, UID_FMT "-%s", peer_uid, name) < 0)
return -ENOMEM;
if (!userns_name_is_valid(un)) {
if (!mangle)
return sd_varlink_error_invalid_parameter_name(link, "name");
_cleanup_free_ char *c = shorten_name(un);
if (!c)
return -ENOMEM;
/* Let's see if shortening was enough? */
if (userns_name_is_valid(c))
free_and_replace(un, c);
else {
free(c);
c = hash_name(link, name);
if (!c)
return -ENOMEM;
un = mfree(un);
if (asprintf(&un, UID_FMT "-%s", peer_uid, c) < 0)
return -ENOMEM;
if (!userns_name_is_valid(un))
return sd_varlink_error_invalid_parameter_name(link, "name");
}
}
}
*ret = TAKE_PTR(un);
return 0;
}
static int validate_target_and_size(sd_varlink *link, uid_t target, uint32_t size, AllocateUserRangeType type) {
assert(link);
if (type == ALLOCATE_USER_RANGE_SELF) {
/* Self userns must have size 1 and target must be 0 or unset */
if (size != 1)
return sd_varlink_error_invalid_parameter_name(link, "size");
if (!IN_SET(target, UID_INVALID, 0))
return sd_varlink_error_invalid_parameter_name(link, "target");
} else {
if (!IN_SET(size, 1U, 0x10000))
return sd_varlink_error_invalid_parameter_name(link, "size");
if (!uid_is_valid(target) || target > UINT32_MAX - size)
return sd_varlink_error_invalid_parameter_name(link, "target");
}
return 0;
}
static int validate_userns(sd_varlink *link, int userns_fd) {
int r;
assert(link);
assert(userns_fd >= 0);
r = fd_verify_safe_flags(userns_fd);
if (r < 0)
return log_debug_errno(r, "User namespace file descriptor has unsafe flags set: %m");
/* Validate this is actually a valid user namespace fd */
r = fd_is_namespace(userns_fd, NAMESPACE_USER);
if (r < 0)
return log_debug_errno(r, "Failed to check if user namespace fd is actually a user namespace: %m");
if (r == 0)
return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
/* And refuse the thing if it is our own */
r = is_our_namespace(userns_fd, NAMESPACE_USER);
if (r < 0)
return log_debug_errno(r, "Failed to check if user namespace fd refers to our own user namespace: %m");
if (r > 0)
return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
uid_t peer_uid;
r = sd_varlink_get_peer_uid(link, &peer_uid);
if (r < 0)
return log_debug_errno(r, "Failed to acquire peer UID: %m");
if (peer_uid != 0) {
/* Refuse if the userns is not actually owned by our client. */
uid_t owner_uid;
if (ioctl(userns_fd, NS_GET_OWNER_UID, &owner_uid) < 0)
return log_debug_errno(errno, "Failed to get owner UID of user namespace: %m");
if (owner_uid != peer_uid)
return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
}
return 0;
}
static int validate_userns_is_empty(sd_varlink *link, int userns_fd) {
int r;
assert(link);
assert(userns_fd >= 0);
_cleanup_(uid_range_freep) UIDRange *range = NULL;
r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_OUTSIDE, &range);
if (r < 0)
return log_debug_errno(r, "Failed to read userns UID range: %m");
if (!uid_range_is_empty(range))
return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
range = uid_range_free(range);
r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_OUTSIDE, &range);
if (r < 0)
return log_debug_errno(r, "Failed to read userns GID range: %m");
if (!uid_range_is_empty(range))
return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
return 0;
}
typedef struct AllocateParameters {
const char *name;
AllocateUserRangeType type;
uint32_t size;
uid_t target;
unsigned userns_fd_idx;
bool mangle_name;
uint32_t delegate_container_ranges;
bool map_foreign;
} AllocateParameters;
static int vl_method_allocate_user_range(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
static const sd_json_dispatch_field dispatch_table[] = {
{ "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(AllocateParameters, name), SD_JSON_MANDATORY },
{ "size", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint32, offsetof(AllocateParameters, size), SD_JSON_MANDATORY },
{ "target", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid, offsetof(AllocateParameters, target), 0 },
{ "userNamespaceFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AllocateParameters, userns_fd_idx), SD_JSON_MANDATORY },
{ "mangleName", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(AllocateParameters, mangle_name), 0 },
{ "type", SD_JSON_VARIANT_STRING, dispatch_allocate_user_range_type, offsetof(AllocateParameters, type), 0 },
{ "delegateContainerRanges", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint32, offsetof(AllocateParameters, delegate_container_ranges), 0 },
{ "mapForeign", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_stdbool, offsetof(AllocateParameters, map_foreign), 0 },
{}
};
_cleanup_close_ int userns_fd = -EBADF, registry_dir_fd = -EBADF, lock_fd = -EBADF;
_cleanup_free_ char *userns_name = NULL;
Context *c = ASSERT_PTR(userdata);
uid_t peer_uid;
gid_t peer_gid;
struct stat userns_st;
AllocateParameters p = {
.type = ALLOCATE_USER_RANGE_MANAGED,
.size = UINT32_MAX,
.target = UID_INVALID,
.userns_fd_idx = UINT_MAX,
};
int r;
assert(link);
assert(parameters);
r = test_userns_api_support(link);
if (r != 0)
return r;
r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
if (r != 0)
return r;
if (p.type != ALLOCATE_USER_RANGE_SELF && p.target == UID_INVALID)
p.target = 0;
r = validate_name(link, p.name, p.mangle_name, &userns_name);
if (r != 0)
return r;
r = validate_target_and_size(link, p.target, p.size, p.type);
if (r != 0)
return r;
if (p.delegate_container_ranges > USER_NAMESPACE_DELEGATIONS_MAX)
return sd_varlink_error(link, "io.systemd.NamespaceResource.TooManyDelegations", NULL);
userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
if (userns_fd < 0)
return log_debug_errno(userns_fd, "Failed to take user namespace fd from Varlink connection: %m");
r = validate_userns(link, userns_fd);
if (r != 0)
return r;
r = validate_userns_is_empty(link, userns_fd);
if (r != 0)
return r;
if (fstat(userns_fd, &userns_st) < 0)
return log_debug_errno(errno, "Failed to fstat() user namespace fd: %m");
_cleanup_close_ int parent_userns_fd = ioctl(userns_fd, NS_GET_PARENT);
if (parent_userns_fd < 0)
return log_debug_errno(errno, "Failed to get parent user namespace: %m");
struct stat parent_st = {};
if (DEBUG_LOGGING && fstat(parent_userns_fd, &parent_st) < 0)
return log_debug_errno(errno, "Failed to fstat() parent user namespace fd: %m");
r = sd_varlink_get_peer_uid(link, &peer_uid);
if (r < 0)
return r;
r = sd_varlink_get_peer_gid(link, &peer_gid);
if (r < 0)
return r;
log_debug("Processing AllocateUserRange request: name='%s' type=%s peer=" UID_FMT ":" GID_FMT
" userns=" INO_FMT " parent_userns=" INO_FMT
" size=%" PRIu32 " delegates=%" PRIu32 " mapForeign=%s",
userns_name,
p.type == ALLOCATE_USER_RANGE_SELF ? "self" : "managed",
peer_uid, peer_gid,
userns_st.st_ino, parent_st.st_ino,
p.size, p.delegate_container_ranges, yes_no(p.map_foreign));
const char *polkit_details[] = {
"name", userns_name,
NULL,
};
r = varlink_verify_polkit_async_full(
link,
/* bus= */ NULL,
"io.systemd.namespace-resource.allocate-user-namespace",
polkit_details,
/* good_user= */ UID_INVALID,
POLKIT_DEFAULT_ALLOW, /* If no polkit is installed, allow unpriv userns namespace allocation */
&c->polkit_registry,
/* ret_admin= */ NULL);
if (r <= 0)
return r;
if (!c->bpf) {
r = userns_restrict_install(/* pin= */ true, &c->bpf);
if (r < 0)
return r;
}
registry_dir_fd = userns_registry_open_fd();
if (registry_dir_fd < 0)
return registry_dir_fd;
_cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = userns_info_new();
if (!userns_info)
return -ENOMEM;
userns_info->name = TAKE_PTR(userns_name);
if (!userns_info->name)
return -ENOMEM;
userns_info->owner = peer_uid;
userns_info->userns_inode = userns_st.st_ino;
if (ioctl(userns_fd, NS_GET_ID, &userns_info->userns_id) < 0)
log_debug_errno(errno, "Failed to query userns ID, ignoring: %m");
userns_info->size = p.size;
userns_info->target_uid = p.target;
userns_info->target_gid = (gid_t) p.target;
/* For "self" allocations we deny setgroups() via the BPF-LSM (see below). Record it so the manager
* can re-establish the denial after a restart that reset the BPF maps. */
userns_info->setgroups_deny = p.type == ALLOCATE_USER_RANGE_SELF;
if (p.type == ALLOCATE_USER_RANGE_SELF) {
/* The start UID/GID will be mapped to the parent userns in write_userns(). If a self
* mapping to the peer UID/GID is requested, we have to map the target UID/GID ourselves here
* as write_userns() doesn't take care of that. */
userns_info->start_uid = peer_uid;
userns_info->start_gid = peer_gid;
if (p.target == UID_INVALID) {
r = uid_range_translate_userns_fd(
parent_userns_fd,
UID_RANGE_USERNS_OUTSIDE,
peer_uid,
&userns_info->target_uid);
if (r < 0)
return log_debug_errno(r, "Failed to translate UID "UID_FMT" to parent user namespace: %m", peer_uid);
r = uid_range_translate_userns_fd(
parent_userns_fd,
GID_RANGE_USERNS_OUTSIDE,
peer_gid,
&userns_info->target_gid);
if (r < 0)
return log_debug_errno(r, "Failed to translate GID "GID_FMT" to parent user namespace: %m", peer_gid);
}
}
/* Set up delegation arrays if requested */
if (p.delegate_container_ranges > 0) {
userns_info->delegates = new0(DelegatedUserNamespaceInfo, p.delegate_container_ranges);
if (!userns_info->delegates)
return -ENOMEM;
FOREACH_ARRAY(delegate, userns_info->delegates, p.delegate_container_ranges) {
*delegate = DELEGATED_USER_NAMESPACE_INFO_NULL;
delegate->size = NSRESOURCE_UIDS_64K;
}
userns_info->n_delegates = p.delegate_container_ranges;
}
r = allocate_now(registry_dir_fd, userns_fd, parent_userns_fd, c->bpf, userns_info, &lock_fd);
if (r == -EHOSTDOWN) /* The needed UID range is not delegated to us */
return sd_varlink_error(link, "io.systemd.NamespaceResource.DynamicRangeUnavailable", NULL);
if (r == -EBUSY) /* All used up */
return sd_varlink_error(link, "io.systemd.NamespaceResource.NoDynamicRange", NULL);
if (r == -EDEADLK)
return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceExists", NULL);
if (r == -EEXIST)
return sd_varlink_error(link, "io.systemd.NamespaceResource.NameExists", NULL);
if (r < 0)
return r;
r = userns_registry_store(registry_dir_fd, userns_info);
if (r < 0)
return r;
/* Subject the userns to the BPF-LSM policy that keeps its transient range off persistent file systems */
r = userns_restrict_register_by_fd(c->bpf, userns_fd);
if (r < 0)
goto fail;
if (userns_info->setgroups_deny > 0) {
/* For "self" allocations we deny setgroups() via the BPF LSM. We can't use
* /proc/self/setgroups for this as that is transitive and also applies to child user
* namespaces. The BPF LSM hook only applies to the specific user namespace. */
r = userns_restrict_setgroups_deny_by_fd(c->bpf, userns_fd);
if (r < 0)
goto fail;
}
r = write_userns(userns_fd, parent_userns_fd, userns_info, p.map_foreign);
if (r < 0)
goto fail;
lock_fd = safe_close(lock_fd);
/* Send user namespace and process fd to our manager process, which will watch the process and user namespace */
r = sd_pid_notifyf_with_fds(
/* pid= */ 0,
/* unset_environment= */ false,
&userns_fd, 1,
"FDSTORE=1\n"
"FDNAME=userns-" INO_FMT "\n", userns_info->userns_inode);
if (r < 0)
goto fail;
/* Note, we'll not return UID values from the host, since the child might not run in the same
* user namespace as us. If they want to know the ranges they should read them off the userns fd, so
* that they are translated into their PoV */
return sd_varlink_replybo(link, SD_JSON_BUILD_PAIR_STRING("name", userns_info->name));
fail:
/* Note: we don't have to clean-up the BPF maps in the error path: the bpf map type used will
* automatically do that once the userns inode goes away */
userns_registry_remove(registry_dir_fd, userns_info);
return r;
}
static int validate_userns_is_safe(sd_varlink *link, int userns_fd) {
int r;
assert(link);
assert(userns_fd >= 0);
/* Read the outside UID range and verify it isn't empty */
_cleanup_(uid_range_freep) UIDRange *outside_range = NULL;
r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_OUTSIDE, &outside_range);
if (r < 0)
return log_debug_errno(r, "Failed to read userns UID range: %m");
if (uid_range_is_empty(outside_range))
return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
/* Read the outside GID range and check it is the same as the UID range */
_cleanup_(uid_range_freep) UIDRange *outside_range_gid = NULL;
r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_OUTSIDE, &outside_range_gid);
if (r < 0)
return log_debug_errno(r, "Failed to read userns GID range: %m");
if (!uid_range_equal(outside_range, outside_range_gid))
return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
/* Read the inside UID range, and verify it matches the size of the outside UID range */
_cleanup_(uid_range_freep) UIDRange *inside_range = NULL;
r = uid_range_load_userns_by_fd(userns_fd, UID_RANGE_USERNS_INSIDE, &inside_range);
if (r < 0)
return log_debug_errno(r, "Failed to read userns contents: %m");
if (uid_range_size(outside_range) != uid_range_size(inside_range))
return log_debug_errno(SYNTHETIC_ERRNO(ENOTRECOVERABLE), "Uh, inside and outside UID range sizes don't match.");
/* Read the inside GID range, and verify it matches the inside UID range */
_cleanup_(uid_range_freep) UIDRange *inside_range_gid = NULL;
r = uid_range_load_userns_by_fd(userns_fd, GID_RANGE_USERNS_INSIDE, &inside_range_gid);
if (r < 0)
return log_debug_errno(r, "Failed to read userns contents: %m");
if (!uid_range_equal(inside_range, inside_range_gid))
return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
uid_t peer_uid;
r = sd_varlink_get_peer_uid(link, &peer_uid);
if (r < 0)
return r;
uid_t peer_gid;
r = sd_varlink_get_peer_gid(link, &peer_gid);
if (r < 0)
return r;
/* Insist that the first UID/GID in the range matches the client's UID/GID */
if (outside_range->entries[0].start != peer_uid ||
outside_range_gid->entries[0].start != peer_gid)
return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
/* If there are more than one UID in the range, then also insist that the first UID maps to root inside the userns */
if (uid_range_size(outside_range) > 1 && inside_range->entries[0].start != 0)
return sd_varlink_error_invalid_parameter_name(link, "userNamespaceFileDescriptor");
return 0;
}
typedef struct RegisterParameters {
const char *name;
unsigned userns_fd_idx;
bool mangle_name;
} RegisterParameters;
static int vl_method_register_user_namespace(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
static const sd_json_dispatch_field dispatch_table[] = {
{ "name", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, offsetof(RegisterParameters, name), SD_JSON_MANDATORY },
{ "userNamespaceFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(RegisterParameters, userns_fd_idx), SD_JSON_MANDATORY },
{ "mangleName", SD_JSON_VARIANT_BOOLEAN, sd_json_dispatch_stdbool, offsetof(RegisterParameters, mangle_name), 0 },
{}
};
_cleanup_close_ int userns_fd = -EBADF, registry_dir_fd = -EBADF;
_cleanup_free_ char *userns_name = NULL;
Context *c = ASSERT_PTR(userdata);
uid_t peer_uid;
struct stat userns_st;
RegisterParameters p = {
.userns_fd_idx = UINT_MAX,
};
int r;
assert(link);
assert(parameters);
r = test_userns_api_support(link);
if (r != 0)
return r;
r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
if (r != 0)
return r;
r = validate_name(link, p.name, p.mangle_name, &userns_name);
if (r != 0)
return r;
userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
if (userns_fd < 0)
return userns_fd;
r = validate_userns(link, userns_fd);
if (r != 0)
return r;
r = validate_userns_is_safe(link, userns_fd);
if (r != 0)
return r;
if (fstat(userns_fd, &userns_st) < 0)
return log_debug_errno(errno, "Failed to fstat() user namespace fd: %m");
r = sd_varlink_get_peer_uid(link, &peer_uid);
if (r < 0)
return r;
const char *polkit_details[] = {
"name", userns_name,
NULL,
};
r = varlink_verify_polkit_async_full(
link,
/* bus= */ NULL,
"io.systemd.namespace-resource.register-user-namespace",
polkit_details,
/* good_user= */ UID_INVALID,
POLKIT_DEFAULT_ALLOW, /* If no polkit is installed, allow unpriv userns namespace registration */
&c->polkit_registry,
/* ret_admin= */ NULL);
if (r <= 0)
return r;
if (!c->bpf) {
r = userns_restrict_install(/* pin= */ true, &c->bpf);
if (r < 0)
return r;
}
registry_dir_fd = userns_registry_open_fd();
if (registry_dir_fd < 0)
return registry_dir_fd;
_cleanup_close_ int lock_fd = -EBADF;
lock_fd = userns_registry_lock(registry_dir_fd);
if (lock_fd < 0)
return log_debug_errno(lock_fd, "Failed to open nsresource registry lock file: %m");
r = inode_slot_is_available(registry_dir_fd, userns_fd, c->bpf, userns_st.st_ino);
if (r < 0)
return r;
if (r == 0)
return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceExists", NULL);
r = name_is_available(registry_dir_fd, userns_name);
if (r < 0)
return r;
if (r == 0)
return sd_varlink_error(link, "io.systemd.NamespaceResource.NameExists", NULL);
_cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = userns_info_new();
if (!userns_info)
return -ENOMEM;
userns_info->name = TAKE_PTR(userns_name);
if (!userns_info->name)
return -ENOMEM;
userns_info->owner = peer_uid;
userns_info->userns_inode = userns_st.st_ino;
if (ioctl(userns_fd, NS_GET_ID, &userns_info->userns_id) < 0)
log_debug_errno(errno, "Failed to query userns ID, ignoring: %m");
r = userns_registry_store(registry_dir_fd, userns_info);
if (r < 0)
return log_debug_errno(r, "Failed to update userns registry: %m");
/* Subject the userns to the BPF-LSM policy that keeps its transient range off persistent file systems */
r = userns_restrict_register_by_fd(c->bpf, userns_fd);
if (r < 0)
goto fail;
/* Send user namespace and process fd to our manager process, which will watch the process and user namespace */
r = sd_pid_notifyf_with_fds(
/* pid= */ 0,
/* unset_environment= */ false,
&userns_fd, 1,
"FDSTORE=1\n"
"FDNAME=userns-" INO_FMT "\n", userns_info->userns_inode);
if (r < 0)
goto fail;
return sd_varlink_replybo(link, SD_JSON_BUILD_PAIR_STRING("name", userns_info->name));
fail:
userns_registry_remove(registry_dir_fd, userns_info);
return r;
}
typedef struct AddMountParameters {
unsigned userns_fd_idx;
unsigned mount_fd_idx;
} AddMountParameters;
static int vl_method_add_mount_to_user_namespace(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
static const sd_json_dispatch_field parameter_dispatch_table[] = {
{ "userNamespaceFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AddMountParameters, userns_fd_idx), SD_JSON_MANDATORY },
{ "mountFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AddMountParameters, mount_fd_idx), SD_JSON_MANDATORY },
{}
};
_cleanup_close_ int userns_fd = -EBADF, mount_fd = -EBADF, registry_dir_fd = -EBADF;
Context *c = ASSERT_PTR(userdata);
AddMountParameters p = {
.userns_fd_idx = UINT_MAX,
.mount_fd_idx = UINT_MAX,
};
int r, mnt_id = 0;
struct stat userns_st;
assert(link);
assert(parameters);
r = test_userns_api_support(link);
if (r != 0)
return r;
/* Allowlisting arbitrary mounts is a privileged operation */
r = varlink_check_privileged_peer(link);
if (r < 0)
return r;
r = sd_varlink_dispatch(link, parameters, parameter_dispatch_table, &p);
if (r != 0)
return r;
userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
if (userns_fd < 0)
return userns_fd;
r = validate_userns(link, userns_fd);
if (r != 0)
return r;
if (fstat(userns_fd, &userns_st) < 0)
return -errno;
mount_fd = sd_varlink_peek_dup_fd(link, p.mount_fd_idx);
if (mount_fd < 0)
return mount_fd;
r = fd_verify_safe_flags_full(mount_fd, O_PATH|O_DIRECTORY);
if (r < 0)
return log_debug_errno(r, "Mount file descriptor has unsafe flags set: %m");
r = fd_verify_directory(mount_fd);
if (r < 0)
return r;
r = path_get_mnt_id_at(mount_fd, NULL, &mnt_id);
if (r < 0)
return r;
r = varlink_verify_polkit_async_full(
link,
/* bus= */ NULL,
"io.systemd.namespace-resource.delegate-mount",
/* details= */ NULL,
/* good_user= */ UID_INVALID,
POLKIT_DEFAULT_ALLOW, /* If no polkit is installed, allow delegation of mounts to registered userns */
&c->polkit_registry,
/* ret_admin= */ NULL);
if (r <= 0)
return r;
registry_dir_fd = userns_registry_open_fd();
if (registry_dir_fd < 0)
return registry_dir_fd;
_cleanup_close_ int lock_fd = -EBADF;
lock_fd = userns_registry_lock(registry_dir_fd);
if (lock_fd < 0)
return log_debug_errno(lock_fd, "Failed to open nsresource registry lock file: %m");
_cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
r = userns_registry_load_by_userns_inode(
registry_dir_fd,
userns_st.st_ino,
&userns_info);
if (r == -ENOENT)
return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceNotRegistered", NULL);
if (r < 0)
return r;
r = userns_info_verify_fd(userns_fd, userns_info);
if (r == -ESTALE)
return sd_varlink_error(link, "io.systemd.NamespaceResource.UserNamespaceNotRegistered", NULL);
if (r < 0)
return log_debug_errno(r, "Failed to verify user namespace identity: %m");
if (!c->bpf) {
r = userns_restrict_install(/* pin= */ true, &c->bpf);
if (r < 0)
return r;
}
/* Pin the mount fd */
r = sd_pid_notifyf_with_fds(
/* pid= */ 0,
/* unset_environment= */ false,
&mount_fd, 1,
"FDSTORE=1\n"
"FDNAME=userns-" INO_FMT "\n", userns_st.st_ino);
if (r < 0)
return r;
/* There's no mount allowlist anymore: the BPF-LSM policy decides per operation whether the ID that
* would be recorded on disk is a transient one, which needs no per-mount knowledge. We keep
* accepting and validating the call for the sake of older clients, and keep the mount pinned as
* before, but there is nothing left to allowlist. */
if (DEBUG_LOGGING) {
if (userns_info->size > 0)
log_debug("Delegated mount %i to user namespace " INO_FMT " ('%s' @ UID " UID_FMT ")",
mnt_id, userns_st.st_ino, userns_info->name, userns_info->start_uid);
else
log_debug("Delegated mount %i to user namespace " INO_FMT " ('%s')",
mnt_id, userns_st.st_ino, userns_info->name);
}
return sd_varlink_replyb(link, SD_JSON_BUILD_EMPTY_OBJECT);
}
static int validate_cgroup(sd_varlink *link, int fd, uint64_t *ret_cgroup_id) {
int r;
assert(link);
assert(fd >= 0);
assert(ret_cgroup_id);
r = fd_verify_safe_flags_full(fd, O_DIRECTORY);
if (r < 0)
return log_debug_errno(r, "Control group file descriptor has unsafe flags set: %m");
r = fd_verify_directory(fd);
if (r < 0)
return log_debug_errno(r, "Verification that cgroup fd refers to directory failed: %m");
r = fd_is_fs_type(fd, CGROUP2_SUPER_MAGIC);
if (r < 0)
return log_debug_errno(r, "Failed to check if cgroup fd actually refers to cgroupfs: %m");
if (r == 0)
return sd_varlink_error_invalid_parameter_name(link, "controlGroupFileDescriptor");
r = fd_to_handle_u64(fd, ret_cgroup_id);
if (r < 0)
return log_debug_errno(r, "Failed to read cgroup ID from cgroupfs: %m");
return 0;
}
typedef struct AddCGroupParameters {
unsigned userns_fd_idx;
unsigned cgroup_fd_idx;
} AddCGroupParameters;
static int vl_method_add_cgroup_to_user_namespace(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
static const sd_json_dispatch_field parameter_dispatch_table[] = {
{ "userNamespaceFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AddCGroupParameters, userns_fd_idx), SD_JSON_MANDATORY },
{ "controlGroupFileDescriptor", _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uint, offsetof(AddCGroupParameters, cgroup_fd_idx), SD_JSON_MANDATORY },
{}
};
_cleanup_close_ int userns_fd = -EBADF, cgroup_fd = -EBADF, registry_dir_fd = -EBADF;
AddCGroupParameters p = {
.userns_fd_idx = UINT_MAX,
.cgroup_fd_idx = UINT_MAX,
};
_cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
Context *c = ASSERT_PTR(userdata);
struct stat userns_st, cgroup_st;
uid_t peer_uid;
int r;
assert(link);
assert(parameters);
r = test_userns_api_support(link);
if (r != 0)
return r;
r = sd_varlink_dispatch(link, parameters, parameter_dispatch_table, &p);
if (r != 0)
return r;
userns_fd = sd_varlink_peek_dup_fd(link, p.userns_fd_idx);
if (userns_fd < 0)
return log_debug_errno(userns_fd, "Failed to take user namespace fd from Varlink connection: %m");
r = validate_userns(link, userns_fd);
if (r != 0)
return r;
if (fstat(userns_fd, &userns_st) < 0)
return log_debug_errno(errno, "Failed to fstat() user namespace fd: %m");
cgroup_fd = sd_varlink_peek_dup_fd(link, p.cgroup_fd_idx);
if (cgroup_fd < 0)
return log_debug_errno(cgroup_fd, "Failed to take cgroup fd from Varlink connection: %m");
uint64_t cgroup_id;
r = validate_cgroup(link, cgroup_fd, &cgroup_id);
if (r != 0)
return r;
if (fstat(cgroup_fd, &cgroup_st) < 0)
return log_debug_errno(errno, "Failed to fstat() cgroup fd: %m");
r = varlink_verify_polkit_async_full(
link,
/* bus= */ NULL,
"io.systemd.namespace-resource.delegate-cgroup",
/* details= */ NULL,
/* good_user= */ UID_INVALID,
POLKIT_DEFAULT_ALLOW, /* If no polkit is installed, allow delegation of cgroups to registered userns */
&c->polkit_registry,
/* ret_admin= */ NULL);
if (r <= 0)
return r;
registry_dir_fd = userns_registry_open_fd();
if (registry_dir_fd < 0)
return registry_dir_fd;