HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/nsresourced/nsresourcework.c

113,568 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 464f373f21773862291bc192c5f28a0b78e42b97

Lines 1–1000 of 2,683

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <fcntl.h>
#include <linux/if_tun.h>
#include <linux/magic.h>
#include <linux/nsfs.h>
#include <linux/veth.h>
#include <net/if.h>
#include <poll.h>
#include <sched.h>
#include <sys/eventfd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <utmpx.h>
 
#include "sd-daemon.h"
#include "sd-event.h"
#include "sd-netlink.h"
#include "sd-varlink.h"
 
#include "argv-util.h"
#include "bus-polkit.h"
#include "env-util.h"
#include "errno-util.h"
#include "ether-addr-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
#include "hashmap.h"
#include "io-util.h"
#include "json-util.h"
#include "main-func.h"
#include "mountpoint-util.h"
#include "namespace-util.h"
#include "netlink-util.h"
#include "nsresource.h"
#include "pidref.h"
#include "process-util.h"
#include "random-util.h"
#include "siphash24.h"
#include "socket-util.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "time-util.h"
#include "uid-classification.h"
#include "uid-range.h"
#include "user-record.h"
#include "user-util.h"
#include "userdb.h"
#include "userns-registry.h"
#include "userns-restrict.h"
#include "varlink-io.systemd.NamespaceResource.h"
#include "varlink-io.systemd.UserDatabase.h"
#include "varlink-util.h"
 
#define ITERATIONS_MAX 64U
#define RUNTIME_MAX_USEC (5 * USEC_PER_MINUTE)
#define PRESSURE_SLEEP_TIME_USEC (50 * USEC_PER_MSEC)
#define LISTEN_IDLE_USEC (90 * USEC_PER_SEC)
#define USERNS_PER_UID 256
 
typedef struct Context {
        Hashmap *polkit_registry;
        struct userns_restrict_bpf *bpf;
} Context;
 
typedef struct LookupParameters {
        const char *user_name;
        const char *group_name;
        union {
                uid_t uid;
                gid_t gid;
        };
        const char *service;
} LookupParameters;
 
typedef enum AllocateUserRangeType {
        ALLOCATE_USER_RANGE_MANAGED,
        ALLOCATE_USER_RANGE_SELF,
        _ALLOCATE_USER_RANGE_TYPE_MAX,
        _ALLOCATE_USER_RANGE_TYPE_INVALID = -EINVAL,
} AllocateUserRangeType;
 
static const char *const allocate_user_range_type_table[_ALLOCATE_USER_RANGE_TYPE_MAX] = {
        [ALLOCATE_USER_RANGE_MANAGED] = "managed",
        [ALLOCATE_USER_RANGE_SELF]    = "self",
};
 
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(allocate_user_range_type, AllocateUserRangeType);
static JSON_DISPATCH_ENUM_DEFINE(dispatch_allocate_user_range_type, AllocateUserRangeType, allocate_user_range_type_from_string);
 
static int build_user_json(UserNamespaceInfo *userns_info, uid_t offset, sd_json_variant **ret) {
        _cleanup_free_ char *name = NULL, *realname = NULL;
        UserDisposition disposition;
        int r;
 
        assert(userns_info);
        assert(offset < userns_info->size);
 
        if (asprintf(&name, "ns-%s-" UID_FMT, userns_info->name, offset) < 0)
                return -ENOMEM;
 
        if (userns_info->size > 1) {
                disposition = USER_CONTAINER;
                r = asprintf(&realname, "User " UID_FMT " of Allocated Namespace %s", offset, userns_info->name);
        } else {
                disposition = USER_DYNAMIC;
                r = asprintf(&realname, "Allocated Namespace %s", userns_info->name);
        }
        if (r < 0)
                return -ENOMEM;
 
        return sd_json_buildo(
                        ret,
                        SD_JSON_BUILD_PAIR_STRING("userName", name),
                        SD_JSON_BUILD_PAIR_UNSIGNED("uid", userns_info->start_uid + offset),
                        SD_JSON_BUILD_PAIR_UNSIGNED("gid", GID_NOBODY),
                        SD_JSON_BUILD_PAIR_STRING("realName", realname),
                        SD_JSON_BUILD_PAIR("homeDirectory", JSON_BUILD_CONST_STRING("/")),
                        SD_JSON_BUILD_PAIR_STRING("shell", NOLOGIN),
                        SD_JSON_BUILD_PAIR_BOOLEAN("locked", true),
                        SD_JSON_BUILD_PAIR("service", JSON_BUILD_CONST_STRING("io.systemd.NamespaceResource")),
                        SD_JSON_BUILD_PAIR_STRING("disposition", user_disposition_to_string(disposition)));
}
 
static int vl_method_get_user_record(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "uid",      _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid,            offsetof(LookupParameters, uid),       0             },
                { "userName", SD_JSON_VARIANT_STRING,        json_dispatch_const_user_group_name, offsetof(LookupParameters, user_name), SD_JSON_RELAX },
                { "service",  SD_JSON_VARIANT_STRING,        sd_json_dispatch_const_string,       offsetof(LookupParameters, service),   0             },
                {}
        };
 
        _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        LookupParameters p = {
                .uid = UID_INVALID,
        };
        uid_t offset;
        int r;
 
        assert(parameters);
 
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
        if (r != 0)
                return r;
 
        if (!streq_ptr(p.service, "io.systemd.NamespaceResource"))
                return sd_varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
 
        if (p.user_name) {
                _cleanup_free_ char *n = NULL;
                const char *e, *f;
 
                e = startswith(p.user_name, "ns-");
                if (!e)
                        goto not_found;
 
                f = strrchr(e, '-');
                if (!f)
                        goto not_found;
 
                if (parse_uid(f+1, &offset) < 0)
                        goto not_found;
 
                n = strndup(e, f - e);
                if (!n)
                        return log_oom();
 
                r = userns_registry_load_by_name(
                                /* dir_fd= */ -EBADF,
                                n,
                                &userns_info);
                if (r == -ENOENT)
                        goto not_found;
                if (r < 0)
                        return r;
 
                if (offset >= userns_info->size) /* Outside of range? */
                        goto not_found;
 
                if (uid_is_valid(p.uid) && p.uid != userns_info->start_uid + offset)
                        return sd_varlink_error(link, "io.systemd.UserDatabase.ConflictingRecordFound", NULL);
 
        } else if (uid_is_valid(p.uid)) {
                uid_t start, uidmask;
 
                if (uid_is_container(p.uid))
                        uidmask = (uid_t) UINT32_C(0xFFFF0000);
                else if (uid_is_dynamic(p.uid))
                        uidmask = (uid_t) UINT32_C(0xFFFFFFFF);
                else
                        goto not_found;
 
                start = p.uid & uidmask;
                offset = p.uid - start;
 
                r = userns_registry_load_by_start_uid(
                                /* dir_fd= */ -EBADF,
                                start,
                                &userns_info);
                if (r == -ENOENT)
                        goto not_found;
                if (r < 0)
                        return r;
 
                if (offset >= userns_info->size) /* Outside of range? */
                        goto not_found;
        } else
                return sd_varlink_error(link, "io.systemd.UserDatabase.EnumerationNotSupported", NULL);
 
        r = build_user_json(userns_info, offset, &v);
        if (r < 0)
                return r;
 
        return sd_varlink_replybo(link, SD_JSON_BUILD_PAIR_VARIANT("record", v));
 
not_found:
        return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
}
 
static int build_group_json(UserNamespaceInfo *userns_info, gid_t offset, sd_json_variant **ret) {
        _cleanup_free_ char *name = NULL, *description = NULL;
        UserDisposition disposition;
        int r;
 
        assert(userns_info);
        assert(offset < userns_info->size);
 
        if (asprintf(&name, "ns-%s-" GID_FMT, userns_info->name, offset) < 0)
                return -ENOMEM;
 
        if (userns_info->size > 1) {
                disposition = USER_CONTAINER;
                r = asprintf(&description, "Group " GID_FMT " of Allocated Namespace %s", offset, userns_info->name);
        } else {
                disposition = USER_DYNAMIC;
                r = asprintf(&description, "Allocated Namespace %s", userns_info->name);
        }
        if (r < 0)
                return -ENOMEM;
 
        return sd_json_buildo(
                        ret,
                        SD_JSON_BUILD_PAIR_STRING("groupName", name),
                        SD_JSON_BUILD_PAIR_UNSIGNED("gid", userns_info->start_gid + offset),
                        SD_JSON_BUILD_PAIR_STRING("description", description),
                        SD_JSON_BUILD_PAIR("service", JSON_BUILD_CONST_STRING("io.systemd.NamespaceResource")),
                        SD_JSON_BUILD_PAIR_STRING("disposition", user_disposition_to_string(disposition)));
}
 
static int vl_method_get_group_record(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "gid",       _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid,            offsetof(LookupParameters, gid),        0             },
                { "groupName", SD_JSON_VARIANT_STRING,        json_dispatch_const_user_group_name, offsetof(LookupParameters, group_name), SD_JSON_RELAX },
                { "service",   SD_JSON_VARIANT_STRING,        sd_json_dispatch_const_string,       offsetof(LookupParameters, service),    0             },
                {}
        };
 
        _cleanup_(userns_info_freep) UserNamespaceInfo *userns_info = NULL;
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        LookupParameters p = {
                .gid = GID_INVALID,
        };
        gid_t offset;
        int r;
 
        assert(parameters);
 
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
        if (r != 0)
                return r;
 
        if (!streq_ptr(p.service, "io.systemd.NamespaceResource"))
                return sd_varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
 
        if (p.group_name) {
                _cleanup_free_ char *n = NULL;
                const char *e, *f;
 
                e = startswith(p.group_name, "ns-");
                if (!e)
                        goto not_found;
 
                f = strrchr(e, '-');
                if (!f)
                        goto not_found;
 
                if (parse_gid(f+1, &offset) < 0)
                        goto not_found;
 
                n = strndup(e, f - e);
                if (!n)
                        return log_oom();
 
                r = userns_registry_load_by_name(
                                /* dir_fd= */ -EBADF,
                                n,
                                &userns_info);
                if (r == -ENOENT)
                        goto not_found;
                if (r < 0)
                        return r;
 
                if (offset >= userns_info->size) /* Outside of range? */
                        goto not_found;
 
                if (gid_is_valid(p.gid) && p.gid != userns_info->start_gid + offset)
                        return sd_varlink_error(link, "io.systemd.UserDatabase.ConflictingRecordFound", NULL);
 
        } else if (gid_is_valid(p.gid)) {
                gid_t start, gidmask;
 
                if (gid_is_container(p.gid))
                        gidmask = (gid_t) UINT32_C(0xFFFF0000);
                else if (gid_is_dynamic(p.gid))
                        gidmask = (gid_t) UINT32_C(0xFFFFFFFF);
                else
                        goto not_found;
 
                start = p.gid & gidmask;
                offset = p.gid - start;
 
                r = userns_registry_load_by_start_gid(
                                /* dir_fd= */ -EBADF,
                                start,
                                &userns_info);
                if (r == -ENOENT)
                        goto not_found;
                if (r < 0)
                        return r;
 
                if (offset >= userns_info->size) /* Outside of range? */
                        goto not_found;
        } else
                return sd_varlink_error(link, "io.systemd.UserDatabase.EnumerationNotSupported", NULL);
 
        r = build_group_json(userns_info, offset, &v);
        if (r < 0)
                return r;
 
        return sd_varlink_replybo(link, SD_JSON_BUILD_PAIR_VARIANT("record", v));
 
not_found:
        return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
}
 
static int vl_method_get_memberships(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
        static const sd_json_dispatch_field dispatch_table[] = {
                { "userName",  SD_JSON_VARIANT_STRING, json_dispatch_const_user_group_name, offsetof(LookupParameters, user_name),  SD_JSON_RELAX },
                { "groupName", SD_JSON_VARIANT_STRING, json_dispatch_const_user_group_name, offsetof(LookupParameters, group_name), SD_JSON_RELAX },
                { "service",   SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string,       offsetof(LookupParameters, service),    0             },
                {}
        };
 
        LookupParameters p = {};
        int r;
 
        assert(parameters);
 
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
        if (r != 0)
                return r;
 
        if (!streq_ptr(p.service, "io.systemd.NamespaceResource"))
                return sd_varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
 
        /* We don't support auxiliary groups for namespace allocations */
        return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
}
 
static int registry_range_is_available(
                struct userns_restrict_bpf *bpf,
                int registry_dir_fd,
                uid_t candidate,
                bool gid) {
 
        _cleanup_(userns_info_freep) UserNamespaceInfo *owner = NULL;
        int r;
 
        assert(registry_dir_fd >= 0);
 
        /* Checks whether the (UID or GID) range starting at candidate is free to allocate as a fresh
         * transient range. If an existing registry entry claims it but its owning namespace has since
         * died — without a BPF death event reaping it yet — we reclaim it on the spot and treat the range
         * as available. Unlike delegations, transient registrations have no ancestor chain, so a single
         * reap suffices. */
 
        r = gid ? userns_registry_gid_exists(registry_dir_fd, (gid_t) candidate)
                : userns_registry_uid_exists(registry_dir_fd, candidate);
        if (r < 0)
                return r;
        if (r == 0)
                return true; /* No registry entry for this range → available. */
 
        r = gid ? userns_registry_load_by_start_gid(registry_dir_fd, (gid_t) candidate, &owner)
                : userns_registry_load_by_start_uid(registry_dir_fd, candidate, &owner);
        if (r == -ENOENT)
                return true; /* Raced away between the existence check and the load → available. */
        if (r < 0)
                return r;
 
        r = userns_registry_reap_if_dead(bpf, registry_dir_fd, owner->userns_inode, /* ret_info= */ NULL);
        if (r < 0)
                return r;
        if (r == USERNS_REAP_RELEASED)
                return true; /* Owner was dead and reaped → range is now free. */
 
        /* Owner is alive or its liveness couldn't be determined → we can't reclaim it, so the range
         * is taken. */
        log_debug("%s" UID_FMT " unavailable: already registered in userns registry.",
                  gid ? "GID " : "UID ", candidate);
        return false;
}
 
static int delegation_range_is_available(
                struct userns_restrict_bpf *bpf,
                int registry_dir_fd,
                uid_t candidate,
                uint64_t parent_userns_inode,
                bool gid) {
 
        int r;
 
        assert(registry_dir_fd >= 0);
 
        /* Checks whether the (UID or GID) range starting at candidate is free to allocate as far as
         * the delegation registry is concerned. A delegated range is available only if it's owned by
         * the requesting parent user namespace (which may then sub-allocate within it). If it's owned
         * by another namespace that has since died — without a BPF death event reaping it yet — we reclaim
         * it on the spot, which restores the range to its ancestor (possibly the parent), and
         * re-evaluate. This walks a chain of dead ancestors until it reaches a live owner, the
         * requesting parent, or a fully freed range. */
 
        r = gid ? userns_registry_delegation_gid_exists(registry_dir_fd, (gid_t) candidate)
                : userns_registry_delegation_uid_exists(registry_dir_fd, candidate);
        if (r < 0)
                return r;
        if (r == 0)
                return true; /* No delegation for this range → available. */
 
        for (;;) {
                _cleanup_(delegated_userns_info_done) DelegatedUserNamespaceInfo delegation = DELEGATED_USER_NAMESPACE_INFO_NULL;
 
                r = gid ? userns_registry_load_delegation_by_gid(registry_dir_fd, (gid_t) candidate, &delegation)
                        : userns_registry_load_delegation_by_uid(registry_dir_fd, candidate, &delegation);
                if (r == -ENOENT)
                        return true; /* Delegation removed while reaping (no ancestor left) → fully free. */
                if (r < 0)
                        return r;
 
                if (delegation.userns_inode == parent_userns_inode) {
                        /* The parent userns owns this delegation, so the range is available for nested
                         * allocation. */
                        log_debug("%s" UID_FMT " is delegated by parent userns inode %" PRIu64 ", available for nested allocation.",
                                  gid ? "GID " : "UID ", candidate, parent_userns_inode);
                        return true;
                }
 
                /* Owned by some other namespace. If that namespace is dead, reclaim it (restoring the
                 * range to its ancestor) and loop to re-evaluate; otherwise the range is genuinely
                 * taken. */
                r = userns_registry_reap_if_dead(bpf, registry_dir_fd, delegation.userns_inode, /* ret_info= */ NULL);
                if (r < 0)
                        return r;
                if (r == USERNS_REAP_RELEASED)
                        continue; /* Reaped a dead owner; re-evaluate the now-restored delegation. */
 
                /* Owner is alive, or its liveness couldn't be determined (no recorded id, or a dead
                 * ancestor that an earlier reap popped into ownership but left no registry entry to
                 * drive a further restore). We can't reclaim the range here — and mustn't loop, since
                 * re-reaping would not make progress — so treat it as taken. */
                log_debug("%s" UID_FMT " unavailable: delegated to userns inode %" PRIu64 " that can't be reclaimed (parent is %" PRIu64 ").",
                          gid ? "GID " : "UID ", candidate, delegation.userns_inode, parent_userns_inode);
                return false;
        }
}
 
static int uid_is_available(
                struct userns_restrict_bpf *bpf,
                int registry_dir_fd,
                uid_t candidate,
                int parent_userns_fd) {
 
        int r;
 
        assert(registry_dir_fd >= 0);
 
        log_debug("Checking if UID " UID_FMT " is available.", candidate);
 
        uint64_t parent_userns_inode = 0;
        struct stat parent_st;
        if (fstat(parent_userns_fd, &parent_st) < 0)
                return log_debug_errno(errno, "Failed to fstat parent user namespace: %m");
        parent_userns_inode = parent_st.st_ino;
 
        /* Check whether an existing transient registration claims this range; a dead owner is reclaimed
         * inline so its range doesn't stay blocked. The UID and GID are checked separately as either
         * can exist independently. */
        r = registry_range_is_available(bpf, registry_dir_fd, candidate, /* gid= */ false);
        if (r < 0)
                return r;
        if (r == 0)
                return false;
 
        r = registry_range_is_available(bpf, registry_dir_fd, candidate, /* gid= */ true);
        if (r < 0)
                return r;
        if (r == 0)
                return false;
 
        /* Also check delegation files. A delegated range is only available for nested allocation when
         * the requesting parent owns it; dead owners are reclaimed inline so their ranges don't stay
         * blocked. We check the UID and GID delegations separately as either can exist independently. */
        r = delegation_range_is_available(bpf, registry_dir_fd, candidate, parent_userns_inode, /* gid= */ false);
        if (r < 0)
                return r;
        if (r == 0)
                return false;
 
        r = delegation_range_is_available(bpf, registry_dir_fd, candidate, parent_userns_inode, /* gid= */ true);
        if (r < 0)
                return r;
        if (r == 0)
                return false;
 
        r = is_our_namespace(parent_userns_fd, NAMESPACE_USER);
        if (r < 0)
                return log_debug_errno(r, "Failed to check if parent user namespace is our user namespace: %m");
 
        if (r > 0) {
                /* Only check userdb if we're allocating from our current user namespace. userdb won't be
                 * to tell us anything on whether UIDs/GIDs in another user namespace are in use or not. On
                 * top of that, for nspawn containers registered with machined's userdb implementation, it
                 * would tell us that any ranges delegated to the container are in use (which is true in the
                 * nsresourced user namespace, but not in the nspawn user namespace). */
 
                r = userdb_by_uid(candidate, /* match= */ NULL, USERDB_AVOID_MULTIPLEXER, /* ret= */ NULL);
                if (r >= 0) {
                        log_debug("UID " UID_FMT " unavailable: known to userdb.", candidate);
                        return false;
                }
                if (r != -ESRCH)
                        return r;
 
                r = groupdb_by_gid(candidate, /* match= */ NULL, USERDB_AVOID_MULTIPLEXER, /* ret= */ NULL);
                if (r >= 0) {
                        log_debug("UID " UID_FMT " unavailable: GID known to groupdb.", candidate);
                        return false;
                }
                if (r != -ESRCH)
                        return r;
        }
 
        log_debug("UID " UID_FMT " is available.", candidate);
 
        return true;
}
 
static int name_is_available(
                int registry_dir_fd,
                const char *name) {
 
        _cleanup_free_ char *user_name = NULL;
        int r;
 
        assert(registry_dir_fd >= 0);
        assert(name);
 
        r = userns_registry_name_exists(registry_dir_fd, name);
        if (r < 0)
                return r;
        if (r > 0)
                return false;
 
        user_name = strjoin("ns-", name, "-0");
        if (!user_name)
                return -ENOMEM;
 
        r = userdb_by_name(user_name, /* match= */ NULL, USERDB_AVOID_MULTIPLEXER, /* ret= */ NULL);
        if (r >= 0)
                return false;
        if (r != -ESRCH)
                return r;
 
        r = groupdb_by_name(user_name, /* match= */ NULL, USERDB_AVOID_MULTIPLEXER, /* ret= */ NULL);
        if (r >= 0)
                return false;
        if (r != -ESRCH)
                return r;
 
        log_debug("Namespace name '%s' is available.", name);
 
        return true;
}
 
static int inode_slot_is_available(
                int registry_dir_fd,
                int userns_fd,
                struct userns_restrict_bpf *bpf,
                uint64_t inode) {
 
        _cleanup_(userns_info_freep) UserNamespaceInfo *existing = NULL;
        int r;
 
        assert(registry_dir_fd >= 0);
        assert(userns_fd >= 0);
        assert(inode != 0);
 
        /* Returns true if the registry has no entry for this inode (after cleaning up any stale
         * leftover from a previously-registered namespace whose inode was recycled by the kernel),
         * false if a live registration already occupies the slot, negative on error. */
 
        r = userns_registry_load_by_userns_inode(registry_dir_fd, inode, &existing);
        if (r == -ENOENT)
                return true;
        if (r < 0)
                return log_debug_errno(r, "Failed to load existing registry entry: %m");
 
        r = userns_info_verify_fd(userns_fd, existing);
        if (r >= 0)
                return false;
        if (r != -ESTALE)
                return log_debug_errno(r, "Failed to verify user namespace identity: %m");
 
        log_debug("Inode %" PRIu64 " was reused by the kernel; cleaning up stale registry entry for namespace id %" PRIu64 ".",
                  inode, existing->userns_id);
        userns_registry_release_by_info(bpf, registry_dir_fd, existing);
        return true;
}
 
static int allocate_one(
                struct userns_restrict_bpf *bpf,
                int registry_dir_fd,
                const char *name,
                uint32_t size,
                int parent_userns_fd,
                UIDRange *candidates,
                uid_t *ret_candidate) {
 
        static const uint8_t hash_key[16] = {
                0xd4, 0xd7, 0x33, 0xa7, 0x4d, 0xd3, 0x42, 0xcd,
                0xaa, 0xe9, 0x45, 0xd0, 0xfb, 0xec, 0x79, 0xee,
        };
        _cleanup_(uid_range_freep) UIDRange *copy = NULL;
        uid_t candidate, uidmin, uidmax;
        unsigned n_tries = 100;
        size_t idx;
        int r;
 
        assert(registry_dir_fd >= 0);
        assert(candidates);
        assert(ret_candidate);
 
        switch (size) {
 
        case NSRESOURCE_UIDS_64K:
                uidmin = CONTAINER_UID_BASE_MIN;
                uidmax = CONTAINER_UID_BASE_MAX;
                break;
 
        case NSRESOURCE_UIDS_1:
                uidmin = DYNAMIC_UID_MIN;
                uidmax = DYNAMIC_UID_MAX;
                break;
 
        default:
                assert_not_reached();
        }
 
        /* Make a copy of candidates that we can modify for the selection algorithm */
        r = uid_range_copy(candidates, &copy);
        if (r < 0)
                return log_debug_errno(r, "Failed to copy UID range: %m");
 
        /* Clip the copy with the valid UID range for this allocation size */
        r = uid_range_clip(copy, uidmin, uidmax);
        if (r < 0)
                return log_debug_errno(r, "Failed to intersect UID range: %m");
 
        /* Partition entries into entries of exactly the right size */
        r = uid_range_partition(copy, size);
        if (r < 0)
                return log_debug_errno(r, "Failed to partition UID ranges: %m");
 
        if (uid_range_is_empty(copy))
                return log_debug_errno(SYNTHETIC_ERRNO(EHOSTDOWN), "Relevant UID range not delegated, can't allocate.");
 
        log_debug("Partitioned UID range into %zu entries of size %" PRIu32, copy->n_entries, size);
 
        /* Start from a hash of the input name if we have one, use random values afterwards. */
        idx = name ? siphash24_string(name, hash_key) : random_u32();
        for (;; idx = random_u32()) {
                if (uid_range_is_empty(copy))
                        return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "All candidate UIDs already taken.");
 
                if (--n_tries <= 0)
                        return log_debug_errno(SYNTHETIC_ERRNO(EBUSY), "Try limit hit, no UIDs available.");
 
                idx %= copy->n_entries;
 
                candidate = copy->entries[idx].start;
 
                /* We only check the base UID for each range. Pass the parent userns inode so that
                 * allocating from a delegated range owned by the parent is allowed. */
                r = uid_is_available(bpf, registry_dir_fd, candidate, parent_userns_fd);
                if (r < 0)
                        return log_debug_errno(r, "Can't determine if UID range " UID_FMT " is available: %m", candidate);
                if (r > 0)
                        break;
 
                log_debug("UID range " UID_FMT " already taken.", candidate);
 
                /* Remove this unavailable range from candidates so we don't try it again */
                r = uid_range_remove(copy, candidate, size);
                if (r < 0)
                        return log_debug_errno(r, "Failed to remove unavailable range from candidates: %m");
        }
 
        /* Remove the allocated range from the original candidates */
        r = uid_range_remove(candidates, candidate, size);
        if (r < 0)
                return log_debug_errno(r, "Failed to remove allocated range from candidates: %m");
 
        *ret_candidate = candidate;
 
        log_debug("Allocating UID range " UID_FMT "…" UID_FMT, candidate, candidate + size - 1);
 
        return 0;
}
 
static int allocate_now(
                int registry_dir_fd,
                int userns_fd,
                int parent_userns_fd,
                struct userns_restrict_bpf *bpf,
                UserNamespaceInfo *info,
                int *ret_lock_fd) {
 
        _cleanup_(uid_range_freep) UIDRange *candidates = NULL;
        uid_t candidate;
        int r;
 
        /* Returns the following error codes:
         *
         * EBUSY   → all UID candidates we checked are already taken
         * EEXIST  → the name for the userns already exists
         * EDEADLK → the userns is already registered in the registry
         */
 
        assert(registry_dir_fd >= 0);
        assert(userns_fd >= 0);
        assert(info);
 
        r = uid_range_load_userns_by_fd(parent_userns_fd, UID_RANGE_USERNS_INSIDE, &candidates);
        if (r < 0)
                return log_debug_errno(r, "Failed to read userns UID range: %m");
 
        log_debug("Parent user namespace exposes %zu UID range(s) inside:", uid_range_entries(candidates));
        if (DEBUG_LOGGING)
                FOREACH_ARRAY(e, candidates->entries, candidates->n_entries)
                        log_debug("  " UID_FMT "…" UID_FMT " (size " UID_FMT ")",
                                  e->start, e->start + e->nr - 1, e->nr);
 
        _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");
 
        /* Enforce limit on user namespaces per UID */
        r = userns_registry_per_uid(registry_dir_fd, info->owner);
        if (r < 0)
                return log_debug_errno(r, "Failed to determine number of currently registered user namespaces per UID " UID_FMT ": %m", info->owner);
        if (r >= USERNS_PER_UID)
                return log_debug_errno(SYNTHETIC_ERRNO(EUSERS), "User already registered %i user namespaces, refusing.", r);
 
        r = inode_slot_is_available(registry_dir_fd, userns_fd, bpf, info->userns_inode);
        if (r < 0)
                return r;
        if (r == 0)
                return -EDEADLK;
 
        r = name_is_available(registry_dir_fd, info->name);
        if (r < 0)
                return r;
        if (r == 0)
                return -EEXIST;
 
        /* If the source UID/GID are already set we're doing a "self" user namespace and don't need to
         * allocate a transient range. */
        if (!uid_is_valid(info->start_uid) && !gid_is_valid(info->start_gid)) {
                r = allocate_one(
                                bpf,
                                registry_dir_fd,
                                info->name, info->size,
                                parent_userns_fd,
                                candidates,
                                &candidate);
                if (r < 0)
                        return r;
 
                info->start_uid = candidate;
                info->start_gid = (gid_t) candidate;
        }
 
        /* Now allocate delegated ranges if requested */
        if (info->n_delegates > 0) {
                assert(info->delegates);
 
                FOREACH_ARRAY(delegate, info->delegates, info->n_delegates) {
                        r = allocate_one(
                                        bpf,
                                        registry_dir_fd,
                                        /* name= */ NULL,
                                        delegate->size,
                                        parent_userns_fd,
                                        candidates,
                                        &candidate);
                        if (r < 0)
                                return r;
 
                        delegate->userns_inode = info->userns_inode;
                        delegate->start_uid = candidate;
                        delegate->start_gid = (gid_t) candidate;
                }
        }
 
        if (ret_lock_fd)
                *ret_lock_fd = TAKE_FD(lock_fd);
 
        return 0;
}
 
static int write_userns_mappings(PidRef *pidref, const char *uidmap, const char *gidmap) {
        const char *pmap;
        int r;
 
        assert(pidref);
        assert(uidmap);
        assert(gidmap);
 
        pmap = procfs_file_alloca(pidref->pid, "uid_map");
        r = write_string_file(pmap, uidmap, /* flags= */ 0);
        if (r < 0)
                return log_error_errno(r, "Failed to write 'uid_map' file of user namespace: %m");
 
        pmap = procfs_file_alloca(pidref->pid, "gid_map");
        r = write_string_file(pmap, gidmap, /* flags= */ 0);
        if (r < 0)
                return log_error_errno(r, "Failed to write 'gid_map' file of user namespace: %m");
 
        return 0;
}
 
static int write_userns(
                int userns_fd,
                int parent_userns_fd,
                const UserNamespaceInfo *userns_info,
                bool map_foreign) {
 
        _cleanup_(pidref_done_sigkill_wait) PidRef pidref = PIDREF_NULL;
        _cleanup_close_ int efd = -EBADF;
        uint64_t u;
        int r;
 
        assert(userns_fd >= 0);
        assert(parent_userns_fd >= 0);
        assert(userns_info);
        assert(uid_is_valid(userns_info->target_uid));
        assert(uid_is_valid(userns_info->start_uid));
        assert(gid_is_valid(userns_info->target_gid));
        assert(gid_is_valid(userns_info->start_gid));
        assert(userns_info->size > 0);
        assert(userns_info->size <= UINT32_MAX - userns_info->start_uid);
        assert(userns_info->size <= UINT32_MAX - userns_info->start_gid);
 
        efd = eventfd(0, EFD_CLOEXEC);
        if (efd < 0)
                return log_error_errno(errno, "Failed to allocate eventfd(): %m");
 
        r = pidref_safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGKILL|FORK_LOG, &pidref);
        if (r < 0)
                return r;
        if (r == 0) {
                /* child */
 
                if (setns(userns_fd, CLONE_NEWUSER) < 0) {
                        log_error_errno(errno, "Failed to join user namespace: %m");
                        goto child_fail;
                }
 
                if (eventfd_write(efd, 1) < 0) {
                        log_error_errno(errno, "Failed to ping event fd: %m");
                        goto child_fail;
                }
 
                freeze();
 
        child_fail:
                _exit(EXIT_FAILURE);
        }
 
        /* Wait until child joined the user namespace */
        if (eventfd_read(efd, &u) < 0)
                return log_error_errno(errno, "Failed to wait for event fd: %m");
 
        /* Now write mapping */
 
        _cleanup_(uid_range_freep) UIDRange *outside_range = NULL;
        r = uid_range_load_userns_by_fd_full(parent_userns_fd, UID_RANGE_USERNS_OUTSIDE, /* coalesce= */ false, &outside_range);
        if (r < 0)
                return log_debug_errno(r, "Failed to read userns UID range: %m");
 
        _cleanup_(uid_range_freep) UIDRange *inside_range = NULL;
        r = uid_range_load_userns_by_fd_full(parent_userns_fd, UID_RANGE_USERNS_INSIDE, /* coalesce= */ false, &inside_range);
        if (r < 0)
                return log_debug_errno(r, "Failed to read userns UID range: %m");
 
        uid_t start_uid;
        r = uid_range_translate(outside_range, inside_range, userns_info->start_uid, &start_uid);
        if (r < 0)
                return log_debug_errno(r, "Failed to translate UID "UID_FMT" to parent userns: %m", userns_info->start_uid);
 
        /* Let's enforce that the transient UID/GID ranges are mapped 1:1 in the parent user namespace, to
         * avoid any weird mapping shenanigans that might happen otherwise. */
 
        if (uid_is_transient(userns_info->start_uid) && start_uid != userns_info->start_uid)
                return log_debug_errno(
                        SYNTHETIC_ERRNO(ERANGE),
                        "Transient UID range not mapped 1:1 in parent userns ("UID_FMT" -> "UID_FMT")",
                        userns_info->start_uid, start_uid);
 
        /* Build uid_map content: primary mapping + delegated mappings (1:1) */
        _cleanup_free_ char *uidmap = NULL;
        if (asprintf(&uidmap, UID_FMT " " UID_FMT " %" PRIu32 "\n",
                     userns_info->target_uid, start_uid, userns_info->size) < 0)
                return log_oom();
 
        log_debug("UID mapping: " UID_FMT " " UID_FMT " %" PRIu32,
                  userns_info->target_uid, userns_info->start_uid, userns_info->size);
 
        FOREACH_ARRAY(delegate, userns_info->delegates, userns_info->n_delegates) {
                r = uid_range_translate(outside_range, inside_range, delegate->start_uid, &start_uid);
                if (r < 0)
                        return log_debug_errno(r, "Failed to translate UID "UID_FMT" to parent userns: %m", userns_info->start_uid);
 
                if (start_uid != delegate->start_uid)
                        return log_debug_errno(
                                SYNTHETIC_ERRNO(ERANGE),
                                "Delegated transient UID range not mapped 1:1 in parent userns ("UID_FMT" -> "UID_FMT")",
                                delegate->start_uid, start_uid);
 
                if (strextendf(&uidmap,
                               UID_FMT " " UID_FMT " %" PRIu32 "\n",
                               delegate->start_uid,
                               start_uid,
                               delegate->size) < 0)
                        return log_oom();
 
                log_debug("UID mapping: " UID_FMT " " UID_FMT " %" PRIu32,
                          delegate->start_uid, start_uid, delegate->size);
        }
 
        if (map_foreign) {
                r = uid_range_translate(outside_range, inside_range, FOREIGN_UID_MIN, &start_uid);
                if (r < 0)
                        return log_debug_errno(r, "Failed to translate UID "UID_FMT" to parent userns: %m", FOREIGN_UID_MIN);
 
                if (start_uid != FOREIGN_UID_MIN)
                        return log_debug_errno(
                                SYNTHETIC_ERRNO(ERANGE),
                                "Foreign UID range not mapped 1:1 in parent userns ("UID_FMT" -> "UID_FMT")",
                                FOREIGN_UID_MIN, start_uid);
 
                if (strextendf(&uidmap, UID_FMT " " UID_FMT " %" PRIu32 "\n",
                               FOREIGN_UID_MIN, start_uid, NSRESOURCE_UIDS_64K) < 0)
                        return log_oom();
        }
 
        outside_range = uid_range_free(outside_range);
        inside_range = uid_range_free(inside_range);
 
        r = uid_range_load_userns_by_fd_full(parent_userns_fd, GID_RANGE_USERNS_OUTSIDE, /* coalesce= */ false, &outside_range);
        if (r < 0)
                return log_debug_errno(r, "Failed to read userns GID range: %m");
 
        r = uid_range_load_userns_by_fd_full(parent_userns_fd, GID_RANGE_USERNS_INSIDE, /* coalesce= */ false, &inside_range);
        if (r < 0)
                return log_debug_errno(r, "Failed to read userns GID range: %m");
 
        gid_t start_gid;
        r = uid_range_translate(outside_range, inside_range, userns_info->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);