HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/nsresourced/userns-registry.c

55,262 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 26d8c28e57be2aedf8c3912be9344c2fc9661bee

Lines 1001–1391 of 1,391

                                                SD_JSON_BUILD_UNSIGNED(existing.ancestor_userns[j]));
                                if (r < 0)
                                        return log_debug_errno(r, "Failed to append to JSON array: %m");
                        }
 
                        r = sd_json_buildo(
                                        &delegate_def,
                                        SD_JSON_BUILD_PAIR_UNSIGNED("userns", new_owner),
                                        SD_JSON_BUILD_PAIR_UNSIGNED("start", existing.start_uid),
                                        SD_JSON_BUILD_PAIR_UNSIGNED("startGid", existing.start_gid),
                                        SD_JSON_BUILD_PAIR_UNSIGNED("size", existing.size),
                                        SD_JSON_BUILD_PAIR_CONDITION(!!ancestor_array, "ancestorUserns", SD_JSON_BUILD_VARIANT(ancestor_array)));
                        if (r < 0)
                                return log_debug_errno(r, "Failed to build delegate JSON object: %m");
 
                        r = sd_json_variant_format(delegate_def, /* flags= */ 0, &delegate_buf);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to format delegation JSON object: %m");
 
                        r = write_string_file_at(dir_fd, delegate_uid_fn, delegate_buf, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
                        if (r < 0) {
                                RET_GATHER(ret, log_debug_errno(r, "Failed to write restored delegation data to '%s' in registry: %m", delegate_uid_fn));
                                continue;
                        }
 
                        /* The atomic write above replaced the UID file with a new inode, so the
                         * hardlink to the GID file is now broken. Re-create it to keep the two in
                         * sync. */
                        r = linkat_replace(dir_fd, delegate_uid_fn, dir_fd, delegate_gid_fn);
                        if (r < 0)
                                RET_GATHER(ret, log_debug_errno(r, "Failed to re-link '%s' to '%s' in registry: %m", delegate_uid_fn, delegate_gid_fn));
 
                        continue;
                }
 
                log_debug("Removing delegated UID range starting at "UID_FMT":"GID_FMT" for userns %"PRIu64 ".",
                          delegate->start_uid, delegate->start_gid, delegate->userns_inode);
 
                /* No ancestor chain — just remove the delegation files */
                r = RET_NERRNO(unlinkat(dir_fd, delegate_uid_fn, 0));
                if (r < 0)
                        RET_GATHER(ret, log_debug_errno(r, "Failed to remove %s: %m", delegate_uid_fn));
 
                r = RET_NERRNO(unlinkat(dir_fd, delegate_gid_fn, 0));
                if (r < 0)
                        RET_GATHER(ret, log_debug_errno(r, "Failed to remove %s: %m", delegate_gid_fn));
        }
 
        return ret;
}
 
bool userns_info_has_cgroup(UserNamespaceInfo *userns, uint64_t cgroup_id) {
        assert(userns);
 
        FOREACH_ARRAY(i, userns->cgroups, userns->n_cgroups)
                if (*i == cgroup_id)
                        return true;
 
        return false;
}
 
int userns_info_add_cgroup(UserNamespaceInfo *userns, uint64_t cgroup_id) {
        assert(userns);
 
        if (userns_info_has_cgroup(userns, cgroup_id))
                return 0;
 
        if (!GREEDY_REALLOC(userns->cgroups, userns->n_cgroups+1))
                return -ENOMEM;
 
        userns->cgroups[userns->n_cgroups++] = cgroup_id;
        return 1;
}
 
static int userns_destroy_cgroup(uint64_t cgroup_id) {
        _cleanup_close_ int cgroup_fd = -EBADF, parent_fd = -EBADF;
        int r;
 
        cgroup_fd = cg_cgroupid_open(/* cgroupfs_fd= */ -EBADF, cgroup_id);
        if (cgroup_fd == -ESTALE) {
                log_debug_errno(cgroup_fd, "Control group %" PRIu64 " already gone, ignoring.", cgroup_id);
                return 0;
        }
        if (cgroup_fd < 0)
                return log_debug_errno(cgroup_fd, "Failed to open cgroup %" PRIu64 ", ignoring: %m", cgroup_id);
 
        _cleanup_free_ char *path = NULL;
        r = fd_get_path(cgroup_fd, &path);
        if (r < 0)
                return log_debug_errno(r, "Failed to get path of cgroup %" PRIu64 ", ignoring: %m", cgroup_id);
 
        const char *e = path_startswith(path, "/sys/fs/cgroup/");
        if (!e)
                return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "Got cgroup path that doesn't start with /sys/fs/cgroup/, refusing: %s", path);
        if (isempty(e))
                return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "Got root cgroup path, which can't be right, refusing.");
 
        log_debug("Destroying cgroup %" PRIu64 " (%s)", cgroup_id, path);
 
        _cleanup_free_ char *fname = NULL;
        r = path_extract_filename(path, &fname);
        if (r < 0)
                return log_debug_errno(r, "Failed to extract name of cgroup %" PRIu64 ", ignoring: %m", cgroup_id);
 
        parent_fd = openat(cgroup_fd, "..", O_CLOEXEC|O_DIRECTORY);
        if (parent_fd < 0)
                return log_debug_errno(errno, "Failed to open parent cgroup of %" PRIu64 ", ignoring: %m", cgroup_id);
 
        /* Safety check, never leave cgroupfs */
        r = fd_is_fs_type(parent_fd, CGROUP2_SUPER_MAGIC);
        if (r < 0)
                return log_debug_errno(r, "Failed to determine if parent directory of cgroup %" PRIu64 " is still a cgroup, ignoring: %m", cgroup_id);
        if (!r)
                return log_debug_errno(SYNTHETIC_ERRNO(EPERM), "Parent directory of cgroup %" PRIu64 " is not a cgroup, refusing.", cgroup_id);
 
        cgroup_fd = safe_close(cgroup_fd);
 
        r = rm_rf_child(parent_fd, fname, REMOVE_ONLY_DIRECTORIES|REMOVE_CHMOD);
        if (r < 0)
                log_debug_errno(r, "Failed to remove delegated cgroup %" PRIu64 ", ignoring: %m", cgroup_id);
 
        return 0;
}
 
int userns_info_remove_cgroups(UserNamespaceInfo *userns) {
        int ret = 0;
 
        assert(userns);
 
        FOREACH_ARRAY(c, userns->cgroups, userns->n_cgroups)
                RET_GATHER(ret, userns_destroy_cgroup(*c));
 
        userns->cgroups = mfree(userns->cgroups);
        userns->n_cgroups = 0;
 
        return ret;
}
 
int userns_info_add_netif(UserNamespaceInfo *userns, const char *netif) {
        int r;
 
        assert(userns);
        assert(netif);
 
        if (strv_contains(userns->netifs, netif))
                return 0;
 
        r = strv_extend(&userns->netifs, netif);
        if (r < 0)
                return r;
 
        return 1;
}
 
static int userns_destroy_netif(sd_netlink **rtnl, const char *name) {
        int r;
 
        assert(rtnl);
        assert(name);
 
        log_debug("Removing delegated network interface '%s'", name);
 
        if (!*rtnl) {
                r = sd_netlink_open(rtnl);
                if (r < 0)
                        return log_debug_errno(r, "Failed to connect to netlink: %m");
        }
 
        _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *m = NULL;
        r = sd_rtnl_message_new_link(*rtnl, &m, RTM_DELLINK, /* ifindex= */ 0);
        if (r < 0)
                return r;
 
        r = sd_netlink_message_append_string(m, IFLA_IFNAME, name);
        if (r < 0)
                return r;
 
        r = sd_netlink_call(*rtnl, m, /* timeout= */ 0, /* ret= */ NULL);
        if (ERRNO_IS_NEG_DEVICE_ABSENT(r)) /* Already gone? */
                return 0;
        if (r < 0)
                return log_debug_errno(r, "Failed to remove interface %s: %m", name);
 
        return 1;
}
 
int userns_info_remove_netifs(UserNamespaceInfo *userns) {
        _cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL;
        int ret = 0;
 
        assert(userns);
 
        STRV_FOREACH(c, userns->netifs)
                RET_GATHER(ret, userns_destroy_netif(&rtnl, *c));
 
        userns->netifs = strv_free(userns->netifs);
        return ret;
}
 
bool userns_name_is_valid(const char *name) {
 
        /* Checks if the specified string is suitable as user namespace name. */
 
        if (isempty(name))
                return false;
 
        if (strlen(name) > NAME_MAX) /* before we use alloca(), let's check for size */
                return false;
 
        const char *f = strjoina("n", name, ".userns"); /* Make sure we can name our lookup symlink with this name */
        if (!filename_is_valid(f))
                return false;
 
        const char *u = strjoina("ns-", name, "-65535"); /* Make sure we can turn this into valid user names */
        if (!valid_user_group_name(u, 0))
                return false;
 
        return true;
}
 
int userns_registry_per_uid(int dir_fd, uid_t owner) {
        _cleanup_close_ int registry_fd = -EBADF;
        int n = 0, r;
 
        if (dir_fd < 0) {
                registry_fd = userns_registry_open_fd();
                if (registry_fd < 0)
                        return registry_fd;
 
                dir_fd = registry_fd;
        }
 
        _cleanup_free_ char *uid_fn = NULL;
        if (asprintf(&uid_fn, "o" UID_FMT ".owns", owner) < 0)
                return log_oom_debug();
 
        _cleanup_free_ DirectoryEntries *de = NULL;
 
        r = readdir_all_at(dir_fd, uid_fn, RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_MUST_BE_REGULAR, &de);
        if (r == -ENOENT)
                return 0;
        if (r < 0)
                return log_debug_errno(r, "Failed to enumerate contents of '%s' sub-directory: %m", uid_fn);
 
        FOREACH_ARRAY(i, de->entries, de->n_entries) {
                struct dirent *e = *i;
 
                if (!startswith(e->d_name, "i") || !endswith(e->d_name, ".userns"))
                        continue;
 
                n++;
 
                if (n == INT_MAX) /* overflow safety check, just in case */
                        break;
        }
 
        return n;
}
 
int userns_registry_delegation_uid_exists(int dir_fd, uid_t start) {
        _cleanup_free_ char *fn = NULL;
 
        assert(dir_fd >= 0);
 
        if (!uid_is_valid(start))
                return -ENOENT;
 
        if (start == 0)
                return true;
 
        if (asprintf(&fn, "u" UID_FMT ".delegate", start) < 0)
                return -ENOMEM;
 
        if (faccessat(dir_fd, fn, F_OK, AT_SYMLINK_NOFOLLOW) < 0)
                return errno == ENOENT ? false : -errno;
 
        return true;
}
 
int userns_registry_delegation_gid_exists(int dir_fd, gid_t start) {
        _cleanup_free_ char *fn = NULL;
 
        assert(dir_fd >= 0);
 
        if (!gid_is_valid(start))
                return -ENOENT;
 
        if (start == 0)
                return true;
 
        if (asprintf(&fn, "g" GID_FMT ".delegate", start) < 0)
                return -ENOMEM;
 
        if (faccessat(dir_fd, fn, F_OK, AT_SYMLINK_NOFOLLOW) < 0)
                return errno == ENOENT ? false : -errno;
 
        return true;
}
 
static int userns_registry_load_delegation(int dir_fd, const char *filename, DelegatedUserNamespaceInfo *ret) {
 
        static const sd_json_dispatch_field dispatch_table[] = {
                { "userns",         SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint64,        offsetof(DelegatedUserNamespaceInfo, userns_inode), SD_JSON_MANDATORY },
                { "start",          SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uid_gid,       offsetof(DelegatedUserNamespaceInfo, start_uid),    SD_JSON_MANDATORY },
                { "startGid",       SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uid_gid,       offsetof(DelegatedUserNamespaceInfo, start_gid),    0                 },
                { "size",           SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint32,        offsetof(DelegatedUserNamespaceInfo, size),         SD_JSON_MANDATORY },
                { "ancestorUserns", SD_JSON_VARIANT_ARRAY,    dispatch_ancestor_userns_array, 0,                                                  0                 },
                {}
        };
 
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        _cleanup_close_ int registry_fd = -EBADF;
        int r;
 
        if (dir_fd < 0) {
                registry_fd = userns_registry_open_fd();
                if (registry_fd < 0)
                        return registry_fd;
 
                dir_fd = registry_fd;
        }
 
        r = sd_json_parse_file_at(/* f= */ NULL, dir_fd, filename, /* flags= */ 0, &v, /* reterr_line= */ NULL, /* reterr_column= */ NULL);
        if (r < 0)
                return r;
 
        _cleanup_(delegated_userns_info_done) DelegatedUserNamespaceInfo data = DELEGATED_USER_NAMESPACE_INFO_NULL;
 
        r = sd_json_dispatch(v, dispatch_table, /* flags= */ 0, &data);
        if (r < 0)
                return r;
 
        if (data.userns_inode == 0)
                return -EBADMSG;
        if (data.size == 0)
                return -EBADMSG;
 
        if (ret)
                *ret = TAKE_GENERIC(data, DelegatedUserNamespaceInfo, DELEGATED_USER_NAMESPACE_INFO_NULL);
 
        return 0;
}
 
int userns_registry_load_delegation_by_uid(int dir_fd, uid_t start, DelegatedUserNamespaceInfo *ret) {
        _cleanup_free_ char *fn = NULL;
        int r;
 
        if (!uid_is_valid(start))
                return -ENOENT;
 
        if (asprintf(&fn, "u" UID_FMT ".delegate", start) < 0)
                return -ENOMEM;
 
        _cleanup_(delegated_userns_info_done) DelegatedUserNamespaceInfo data = DELEGATED_USER_NAMESPACE_INFO_NULL;
        r = userns_registry_load_delegation(dir_fd, fn, &data);
        if (r < 0)
                return r;
 
        if (data.start_uid != start)
                return -EBADMSG;
 
        if (ret)
                *ret = TAKE_GENERIC(data, DelegatedUserNamespaceInfo, DELEGATED_USER_NAMESPACE_INFO_NULL);
 
        return 0;
}
 
int userns_registry_load_delegation_by_gid(int dir_fd, gid_t start, DelegatedUserNamespaceInfo *ret) {
        _cleanup_free_ char *fn = NULL;
        int r;
 
        if (!gid_is_valid(start))
                return -ENOENT;
 
        if (asprintf(&fn, "g" UID_FMT ".delegate", start) < 0)
                return -ENOMEM;
 
        _cleanup_(delegated_userns_info_done) DelegatedUserNamespaceInfo data = DELEGATED_USER_NAMESPACE_INFO_NULL;
        r = userns_registry_load_delegation(dir_fd, fn, &data);
        if (r < 0)
                return r;
 
        if (data.start_gid != start)
                return -EBADMSG;
 
        if (ret)
                *ret = TAKE_GENERIC(data, DelegatedUserNamespaceInfo, DELEGATED_USER_NAMESPACE_INFO_NULL);
 
        return 0;
}