Resguardo inicial

This commit is contained in:
lastdragon
2026-09-06 12:53:21 -06:00
parent 662efe3c2a
commit ad2088d178
94853 changed files with 43200404 additions and 0 deletions
@@ -0,0 +1,12 @@
nsid_test
file_handle_test
init_ino_test
ns_active_ref_test
listns_test
listns_permissions_test
listns_efault_test
siocgskns_test
cred_change_test
stress_test
listns_pagination_bug
regression_pidfd_setns_test
@@ -0,0 +1,29 @@
# SPDX-License-Identifier: GPL-2.0-only
CFLAGS += -Wall -O0 -g $(KHDR_INCLUDES) $(TOOLS_INCLUDES)
LDLIBS += -lcap
TEST_GEN_PROGS := nsid_test \
file_handle_test \
init_ino_test \
ns_active_ref_test \
listns_test \
listns_permissions_test \
listns_efault_test \
siocgskns_test \
cred_change_test \
stress_test \
listns_pagination_bug \
regression_pidfd_setns_test
include ../lib.mk
$(OUTPUT)/ns_active_ref_test: ../filesystems/utils.c
$(OUTPUT)/listns_test: ../filesystems/utils.c
$(OUTPUT)/listns_permissions_test: ../filesystems/utils.c
$(OUTPUT)/listns_efault_test: ../filesystems/utils.c
$(OUTPUT)/siocgskns_test: ../filesystems/utils.c
$(OUTPUT)/cred_change_test: ../filesystems/utils.c
$(OUTPUT)/stress_test: ../filesystems/utils.c
$(OUTPUT)/listns_pagination_bug: ../filesystems/utils.c
$(OUTPUT)/regression_pidfd_setns_test: ../filesystems/utils.c
@@ -0,0 +1,7 @@
CONFIG_UTS_NS=y
CONFIG_TIME_NS=y
CONFIG_IPC_NS=y
CONFIG_USER_NS=y
CONFIG_PID_NS=y
CONFIG_NET_NS=y
CONFIG_CGROUPS=y
@@ -0,0 +1,814 @@
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/capability.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <linux/nsfs.h>
#include "../kselftest_harness.h"
#include "../filesystems/utils.h"
#include "wrappers.h"
/*
* Test credential changes and their impact on namespace active references.
*/
/*
* Test setuid() in a user namespace properly swaps active references.
* Create a user namespace with multiple UIDs mapped, then setuid() between them.
* Verify that the user namespace remains active throughout.
*/
TEST(setuid_preserves_active_refs)
{
pid_t pid;
int status;
__u64 userns_id;
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids[256];
ssize_t ret;
int i;
bool found = false;
int pipefd[2];
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
int fd, userns_fd;
__u64 child_userns_id;
uid_t orig_uid = getuid();
int setuid_count;
close(pipefd[0]);
/* Create new user namespace with multiple UIDs mapped (0-9) */
userns_fd = get_userns_fd(0, orig_uid, 10);
if (userns_fd < 0) {
close(pipefd[1]);
exit(1);
}
if (setns(userns_fd, CLONE_NEWUSER) < 0) {
close(userns_fd);
close(pipefd[1]);
exit(1);
}
close(userns_fd);
/* Get user namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &child_userns_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
/* Send namespace ID to parent */
write(pipefd[1], &child_userns_id, sizeof(child_userns_id));
/*
* Perform multiple setuid() calls.
* Each setuid() triggers commit_creds() which should properly
* swap active references via switch_cred_namespaces().
*/
for (setuid_count = 0; setuid_count < 50; setuid_count++) {
uid_t target_uid = (setuid_count % 10);
if (setuid(target_uid) < 0) {
if (errno != EPERM) {
close(pipefd[1]);
exit(1);
}
}
}
close(pipefd[1]);
exit(0);
}
/* Parent process */
close(pipefd[1]);
if (read(pipefd[0], &userns_id, sizeof(userns_id)) != sizeof(userns_id)) {
close(pipefd[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
SKIP(return, "Failed to get namespace ID from child");
}
close(pipefd[0]);
TH_LOG("Child user namespace ID: %llu", (unsigned long long)userns_id);
/* Verify namespace is active while child is running */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret, 0);
}
for (i = 0; i < ret; i++) {
if (ns_ids[i] == userns_id) {
found = true;
break;
}
}
ASSERT_TRUE(found);
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
/* Verify namespace becomes inactive after child exits */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
ASSERT_GE(ret, 0);
found = false;
for (i = 0; i < ret; i++) {
if (ns_ids[i] == userns_id) {
found = true;
break;
}
}
ASSERT_FALSE(found);
TH_LOG("setuid() correctly preserved active references (no leak)");
}
/*
* Test setgid() in a user namespace properly handles active references.
*/
TEST(setgid_preserves_active_refs)
{
pid_t pid;
int status;
__u64 userns_id;
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids[256];
ssize_t ret;
int i;
bool found = false;
int pipefd[2];
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
int fd, userns_fd;
__u64 child_userns_id;
uid_t orig_uid = getuid();
int setgid_count;
close(pipefd[0]);
/* Create new user namespace with multiple GIDs mapped */
userns_fd = get_userns_fd(0, orig_uid, 10);
if (userns_fd < 0) {
close(pipefd[1]);
exit(1);
}
if (setns(userns_fd, CLONE_NEWUSER) < 0) {
close(userns_fd);
close(pipefd[1]);
exit(1);
}
close(userns_fd);
/* Get user namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &child_userns_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
write(pipefd[1], &child_userns_id, sizeof(child_userns_id));
/* Perform multiple setgid() calls */
for (setgid_count = 0; setgid_count < 50; setgid_count++) {
gid_t target_gid = (setgid_count % 10);
if (setgid(target_gid) < 0) {
if (errno != EPERM) {
close(pipefd[1]);
exit(1);
}
}
}
close(pipefd[1]);
exit(0);
}
/* Parent process */
close(pipefd[1]);
if (read(pipefd[0], &userns_id, sizeof(userns_id)) != sizeof(userns_id)) {
close(pipefd[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
SKIP(return, "Failed to get namespace ID from child");
}
close(pipefd[0]);
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
/* Verify namespace becomes inactive */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret, 0);
}
for (i = 0; i < ret; i++) {
if (ns_ids[i] == userns_id) {
found = true;
break;
}
}
ASSERT_FALSE(found);
TH_LOG("setgid() correctly preserved active references (no leak)");
}
/*
* Test setresuid() which changes real, effective, and saved UIDs.
* This should properly swap active references via commit_creds().
*/
TEST(setresuid_preserves_active_refs)
{
pid_t pid;
int status;
__u64 userns_id;
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids[256];
ssize_t ret;
int i;
bool found = false;
int pipefd[2];
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
int fd, userns_fd;
__u64 child_userns_id;
uid_t orig_uid = getuid();
int setres_count;
close(pipefd[0]);
/* Create new user namespace */
userns_fd = get_userns_fd(0, orig_uid, 10);
if (userns_fd < 0) {
close(pipefd[1]);
exit(1);
}
if (setns(userns_fd, CLONE_NEWUSER) < 0) {
close(userns_fd);
close(pipefd[1]);
exit(1);
}
close(userns_fd);
/* Get user namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &child_userns_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
write(pipefd[1], &child_userns_id, sizeof(child_userns_id));
/* Perform multiple setresuid() calls */
for (setres_count = 0; setres_count < 30; setres_count++) {
uid_t uid1 = (setres_count % 5);
uid_t uid2 = ((setres_count + 1) % 5);
uid_t uid3 = ((setres_count + 2) % 5);
if (setresuid(uid1, uid2, uid3) < 0) {
if (errno != EPERM) {
close(pipefd[1]);
exit(1);
}
}
}
close(pipefd[1]);
exit(0);
}
/* Parent process */
close(pipefd[1]);
if (read(pipefd[0], &userns_id, sizeof(userns_id)) != sizeof(userns_id)) {
close(pipefd[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
SKIP(return, "Failed to get namespace ID from child");
}
close(pipefd[0]);
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
/* Verify namespace becomes inactive */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret, 0);
}
for (i = 0; i < ret; i++) {
if (ns_ids[i] == userns_id) {
found = true;
break;
}
}
ASSERT_FALSE(found);
TH_LOG("setresuid() correctly preserved active references (no leak)");
}
/*
* Test credential changes across multiple user namespaces.
* Create nested user namespaces and verify active reference tracking.
*/
TEST(cred_change_nested_userns)
{
pid_t pid;
int status;
__u64 parent_userns_id, child_userns_id;
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids[256];
ssize_t ret;
int i;
bool found_parent = false, found_child = false;
int pipefd[2];
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
int fd, userns_fd;
__u64 parent_id, child_id;
uid_t orig_uid = getuid();
close(pipefd[0]);
/* Create first user namespace */
userns_fd = get_userns_fd(0, orig_uid, 1);
if (userns_fd < 0) {
close(pipefd[1]);
exit(1);
}
if (setns(userns_fd, CLONE_NEWUSER) < 0) {
close(userns_fd);
close(pipefd[1]);
exit(1);
}
close(userns_fd);
/* Get first namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &parent_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
/* Create nested user namespace */
userns_fd = get_userns_fd(0, 0, 1);
if (userns_fd < 0) {
close(pipefd[1]);
exit(1);
}
if (setns(userns_fd, CLONE_NEWUSER) < 0) {
close(userns_fd);
close(pipefd[1]);
exit(1);
}
close(userns_fd);
/* Get nested namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &child_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
/* Send both IDs to parent */
write(pipefd[1], &parent_id, sizeof(parent_id));
write(pipefd[1], &child_id, sizeof(child_id));
/* Perform some credential changes in nested namespace */
setuid(0);
setgid(0);
close(pipefd[1]);
exit(0);
}
/* Parent process */
close(pipefd[1]);
/* Read both namespace IDs */
if (read(pipefd[0], &parent_userns_id, sizeof(parent_userns_id)) != sizeof(parent_userns_id)) {
close(pipefd[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
SKIP(return, "Failed to get parent namespace ID");
}
if (read(pipefd[0], &child_userns_id, sizeof(child_userns_id)) != sizeof(child_userns_id)) {
close(pipefd[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
SKIP(return, "Failed to get child namespace ID");
}
close(pipefd[0]);
TH_LOG("Parent userns: %llu, Child userns: %llu",
(unsigned long long)parent_userns_id,
(unsigned long long)child_userns_id);
/* Verify both namespaces are active */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret, 0);
}
for (i = 0; i < ret; i++) {
if (ns_ids[i] == parent_userns_id)
found_parent = true;
if (ns_ids[i] == child_userns_id)
found_child = true;
}
ASSERT_TRUE(found_parent);
ASSERT_TRUE(found_child);
/* Wait for child */
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
/* Verify both namespaces become inactive */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
ASSERT_GE(ret, 0);
found_parent = false;
found_child = false;
for (i = 0; i < ret; i++) {
if (ns_ids[i] == parent_userns_id)
found_parent = true;
if (ns_ids[i] == child_userns_id)
found_child = true;
}
ASSERT_FALSE(found_parent);
ASSERT_FALSE(found_child);
TH_LOG("Nested user namespace credential changes preserved active refs (no leak)");
}
/*
* Test rapid credential changes don't cause refcount imbalances.
* This stress-tests the switch_cred_namespaces() logic.
*/
TEST(rapid_cred_changes_no_leak)
{
pid_t pid;
int status;
__u64 userns_id;
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids[256];
ssize_t ret;
int i;
bool found = false;
int pipefd[2];
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
int fd, userns_fd;
__u64 child_userns_id;
uid_t orig_uid = getuid();
int change_count;
close(pipefd[0]);
/* Create new user namespace with wider range of UIDs/GIDs */
userns_fd = get_userns_fd(0, orig_uid, 100);
if (userns_fd < 0) {
close(pipefd[1]);
exit(1);
}
if (setns(userns_fd, CLONE_NEWUSER) < 0) {
close(userns_fd);
close(pipefd[1]);
exit(1);
}
close(userns_fd);
/* Get user namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &child_userns_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
write(pipefd[1], &child_userns_id, sizeof(child_userns_id));
/*
* Perform many rapid credential changes.
* Mix setuid, setgid, setreuid, setregid, setresuid, setresgid.
*/
for (change_count = 0; change_count < 200; change_count++) {
switch (change_count % 6) {
case 0:
setuid(change_count % 50);
break;
case 1:
setgid(change_count % 50);
break;
case 2:
setreuid(change_count % 50, (change_count + 1) % 50);
break;
case 3:
setregid(change_count % 50, (change_count + 1) % 50);
break;
case 4:
setresuid(change_count % 50, (change_count + 1) % 50, (change_count + 2) % 50);
break;
case 5:
setresgid(change_count % 50, (change_count + 1) % 50, (change_count + 2) % 50);
break;
}
}
close(pipefd[1]);
exit(0);
}
/* Parent process */
close(pipefd[1]);
if (read(pipefd[0], &userns_id, sizeof(userns_id)) != sizeof(userns_id)) {
close(pipefd[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
SKIP(return, "Failed to get namespace ID from child");
}
close(pipefd[0]);
TH_LOG("Testing with user namespace ID: %llu", (unsigned long long)userns_id);
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
/* Verify namespace becomes inactive (no leaked active refs) */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret, 0);
}
for (i = 0; i < ret; i++) {
if (ns_ids[i] == userns_id) {
found = true;
break;
}
}
ASSERT_FALSE(found);
TH_LOG("200 rapid credential changes completed with no active ref leak");
}
/*
* Test setfsuid/setfsgid which change filesystem UID/GID.
* These also trigger credential changes but may have different code paths.
*/
TEST(setfsuid_preserves_active_refs)
{
pid_t pid;
int status;
__u64 userns_id;
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids[256];
ssize_t ret;
int i;
bool found = false;
int pipefd[2];
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
int fd, userns_fd;
__u64 child_userns_id;
uid_t orig_uid = getuid();
int change_count;
close(pipefd[0]);
/* Create new user namespace */
userns_fd = get_userns_fd(0, orig_uid, 10);
if (userns_fd < 0) {
close(pipefd[1]);
exit(1);
}
if (setns(userns_fd, CLONE_NEWUSER) < 0) {
close(userns_fd);
close(pipefd[1]);
exit(1);
}
close(userns_fd);
/* Get user namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &child_userns_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
write(pipefd[1], &child_userns_id, sizeof(child_userns_id));
/* Perform multiple setfsuid/setfsgid calls */
for (change_count = 0; change_count < 50; change_count++) {
setfsuid(change_count % 10);
setfsgid(change_count % 10);
}
close(pipefd[1]);
exit(0);
}
/* Parent process */
close(pipefd[1]);
if (read(pipefd[0], &userns_id, sizeof(userns_id)) != sizeof(userns_id)) {
close(pipefd[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
SKIP(return, "Failed to get namespace ID from child");
}
close(pipefd[0]);
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
/* Verify namespace becomes inactive */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret, 0);
}
for (i = 0; i < ret; i++) {
if (ns_ids[i] == userns_id) {
found = true;
break;
}
}
ASSERT_FALSE(found);
TH_LOG("setfsuid/setfsgid correctly preserved active references (no leak)");
}
TEST_HARNESS_MAIN
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,61 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2025 Christian Brauner <brauner@kernel.org>
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <linux/nsfs.h>
#include "kselftest_harness.h"
struct ns_info {
const char *name;
const char *proc_path;
unsigned int expected_ino;
};
static struct ns_info namespaces[] = {
{ "ipc", "/proc/1/ns/ipc", IPC_NS_INIT_INO },
{ "uts", "/proc/1/ns/uts", UTS_NS_INIT_INO },
{ "user", "/proc/1/ns/user", USER_NS_INIT_INO },
{ "pid", "/proc/1/ns/pid", PID_NS_INIT_INO },
{ "cgroup", "/proc/1/ns/cgroup", CGROUP_NS_INIT_INO },
{ "time", "/proc/1/ns/time", TIME_NS_INIT_INO },
{ "net", "/proc/1/ns/net", NET_NS_INIT_INO },
{ "mnt", "/proc/1/ns/mnt", MNT_NS_INIT_INO },
};
TEST(init_namespace_inodes)
{
struct stat st;
for (int i = 0; i < sizeof(namespaces) / sizeof(namespaces[0]); i++) {
int ret = stat(namespaces[i].proc_path, &st);
/* Some namespaces might not be available (e.g., time namespace on older kernels) */
if (ret < 0) {
if (errno == ENOENT) {
ksft_test_result_skip("%s namespace not available\n",
namespaces[i].name);
continue;
}
ASSERT_GE(ret, 0)
TH_LOG("Failed to stat %s: %s",
namespaces[i].proc_path, strerror(errno));
}
ASSERT_EQ(st.st_ino, namespaces[i].expected_ino)
TH_LOG("Namespace %s has inode 0x%lx, expected 0x%x",
namespaces[i].name, st.st_ino, namespaces[i].expected_ino);
ksft_print_msg("Namespace %s: inode 0x%lx matches expected 0x%x\n",
namespaces[i].name, st.st_ino, namespaces[i].expected_ino);
}
}
TEST_HARNESS_MAIN
@@ -0,0 +1,550 @@
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <sched.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <linux/nsfs.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "../kselftest_harness.h"
#include "../pidfd/pidfd.h"
#include "wrappers.h"
/*
* Test listns() error handling with invalid buffer addresses.
*
* When the buffer pointer is invalid (e.g., crossing page boundaries
* into unmapped memory), listns() returns EINVAL.
*
* This test also creates mount namespaces that get destroyed during
* iteration, testing that namespace cleanup happens outside the RCU
* read lock.
*/
TEST(listns_partial_fault_with_ns_cleanup)
{
void *map;
__u64 *ns_ids;
ssize_t ret;
long page_size;
pid_t pid, iter_pid, ns_pids[5];
int pidfds[5];
int sv[5][2];
int iter_pidfd;
int i, status;
char c;
page_size = sysconf(_SC_PAGESIZE);
ASSERT_GT(page_size, 0);
/*
* Map two pages:
* - First page: readable and writable
* - Second page: will be unmapped to trigger EFAULT
*/
map = mmap(NULL, page_size * 2, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
ASSERT_NE(map, MAP_FAILED);
/* Unmap the second page */
ret = munmap((char *)map + page_size, page_size);
ASSERT_EQ(ret, 0);
/*
* Position the buffer pointer so there's room for exactly one u64
* before the page boundary. The second u64 would fall into the
* unmapped page.
*/
ns_ids = ((__u64 *)((char *)map + page_size)) - 1;
/*
* Create a separate process to run listns() in a loop concurrently
* with namespace creation and destruction.
*/
iter_pid = create_child(&iter_pidfd, 0);
ASSERT_NE(iter_pid, -1);
if (iter_pid == 0) {
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0, /* All types */
.spare2 = 0,
.user_ns_id = 0, /* Global listing */
};
int iter_ret;
/*
* Loop calling listns() until killed.
* The kernel should:
* 1. Successfully write the first namespace ID (within valid page)
* 2. Fail with EFAULT when trying to write the second ID (unmapped page)
* 3. Handle concurrent namespace destruction without deadlock
*/
while (1) {
iter_ret = sys_listns(&req, ns_ids, 2, 0);
if (iter_ret == -1 && errno == ENOSYS)
_exit(PIDFD_SKIP);
}
}
/* Small delay to let iterator start looping */
usleep(50000);
/*
* Create several child processes, each in its own mount namespace.
* These will be destroyed while the iterator is running listns().
*/
for (i = 0; i < 5; i++) {
/* Create socketpair for synchronization */
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sv[i]), 0);
pid = create_child(&pidfds[i], CLONE_NEWNS);
ASSERT_NE(pid, -1);
ns_pids[i] = pid;
if (pid == 0) {
close(sv[i][0]); /* Close parent end */
if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, 0))
_exit(1);
/* Child: create a couple of tmpfs mounts */
if (mkdir("/tmp/test_mnt1", 0755) == -1 && errno != EEXIST)
_exit(1);
if (mkdir("/tmp/test_mnt2", 0755) == -1 && errno != EEXIST)
_exit(1);
if (mount("tmpfs", "/tmp/test_mnt1", "tmpfs", 0, NULL) == -1)
_exit(1);
if (mount("tmpfs", "/tmp/test_mnt2", "tmpfs", 0, NULL) == -1)
_exit(1);
/* Signal parent that setup is complete */
if (write_nointr(sv[i][1], "R", 1) != 1)
_exit(1);
/* Wait for parent to signal us to exit */
if (read_nointr(sv[i][1], &c, 1) != 1)
_exit(1);
close(sv[i][1]);
_exit(0);
}
close(sv[i][1]); /* Close child end */
}
/* Wait for all children to finish setup */
for (i = 0; i < 5; i++) {
ret = read_nointr(sv[i][0], &c, 1);
ASSERT_EQ(ret, 1);
ASSERT_EQ(c, 'R');
}
/*
* Signal children to exit. This will destroy their mount namespaces
* while listns() is iterating the namespace tree.
* This tests that cleanup happens outside the RCU read lock.
*/
for (i = 0; i < 5; i++)
write_nointr(sv[i][0], "X", 1);
/* Wait for all mount namespace children to exit and cleanup */
for (i = 0; i < 5; i++) {
waitpid(ns_pids[i], NULL, 0);
close(sv[i][0]);
close(pidfds[i]);
}
/* Kill iterator and wait for it */
sys_pidfd_send_signal(iter_pidfd, SIGKILL, NULL, 0);
ret = waitpid(iter_pid, &status, 0);
ASSERT_EQ(ret, iter_pid);
close(iter_pidfd);
/* If listns() is not supported the iterator exits cleanly via ENOSYS */
if (WIFEXITED(status) && WEXITSTATUS(status) == PIDFD_SKIP) {
munmap(map, page_size);
SKIP(return, "listns() not supported");
}
/* Should have been killed */
ASSERT_TRUE(WIFSIGNALED(status));
ASSERT_EQ(WTERMSIG(status), SIGKILL);
/* Clean up */
munmap(map, page_size);
}
/*
* Test listns() error handling when the entire buffer is invalid.
* This is a sanity check that basic invalid pointer detection works.
*/
TEST(listns_complete_fault)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 *ns_ids;
ssize_t ret;
/* Use a clearly invalid pointer */
ns_ids = (__u64 *)0xdeadbeef;
ret = sys_listns(&req, ns_ids, 10, 0);
if (ret == -1 && errno == ENOSYS)
SKIP(return, "listns() not supported");
/* Should fail with EFAULT */
ASSERT_EQ(ret, -1);
ASSERT_EQ(errno, EFAULT);
}
/*
* Test listns() error handling when the buffer is NULL.
*/
TEST(listns_null_buffer)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0,
.spare2 = 0,
.user_ns_id = 0,
};
ssize_t ret;
/* NULL buffer with non-zero count should fail */
ret = sys_listns(&req, NULL, 10, 0);
if (ret == -1 && errno == ENOSYS)
SKIP(return, "listns() not supported");
/* Should fail with EFAULT */
ASSERT_EQ(ret, -1);
ASSERT_EQ(errno, EFAULT);
}
/*
* Test listns() with a buffer that becomes invalid mid-iteration
* (after several successful writes), combined with mount namespace
* destruction to test RCU cleanup logic.
*/
TEST(listns_late_fault_with_ns_cleanup)
{
void *map;
__u64 *ns_ids;
ssize_t ret;
long page_size;
pid_t pid, iter_pid, ns_pids[10];
int pidfds[10];
int sv[10][2];
int iter_pidfd;
int i, status;
char c;
page_size = sysconf(_SC_PAGESIZE);
ASSERT_GT(page_size, 0);
/* Map two pages */
map = mmap(NULL, page_size * 2, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
ASSERT_NE(map, MAP_FAILED);
/* Unmap the second page */
ret = munmap((char *)map + page_size, page_size);
ASSERT_EQ(ret, 0);
/*
* Position buffer so we can write several u64s successfully
* before hitting the page boundary.
*/
ns_ids = ((__u64 *)((char *)map + page_size)) - 5;
/*
* Create a separate process to run listns() concurrently.
*/
iter_pid = create_child(&iter_pidfd, 0);
ASSERT_NE(iter_pid, -1);
if (iter_pid == 0) {
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0,
.spare2 = 0,
.user_ns_id = 0,
};
int iter_ret;
/*
* Loop calling listns() until killed.
* Request 10 namespace IDs while namespaces are being destroyed.
* This tests:
* 1. EFAULT handling when buffer becomes invalid
* 2. Namespace cleanup outside RCU read lock during iteration
*/
while (1) {
iter_ret = sys_listns(&req, ns_ids, 10, 0);
if (iter_ret == -1 && errno == ENOSYS)
_exit(PIDFD_SKIP);
}
}
/* Small delay to let iterator start looping */
usleep(50000);
/*
* Create more children with mount namespaces to increase the
* likelihood that namespace cleanup happens during iteration.
*/
for (i = 0; i < 10; i++) {
/* Create socketpair for synchronization */
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sv[i]), 0);
pid = create_child(&pidfds[i], CLONE_NEWNS);
ASSERT_NE(pid, -1);
ns_pids[i] = pid;
if (pid == 0) {
close(sv[i][0]); /* Close parent end */
if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, 0))
_exit(1);
/* Child: create tmpfs mounts */
if (mkdir("/tmp/test_mnt1", 0755) == -1 && errno != EEXIST)
_exit(1);
if (mkdir("/tmp/test_mnt2", 0755) == -1 && errno != EEXIST)
_exit(1);
if (mount("tmpfs", "/tmp/test_mnt1", "tmpfs", 0, NULL) == -1)
_exit(1);
if (mount("tmpfs", "/tmp/test_mnt2", "tmpfs", 0, NULL) == -1)
_exit(1);
/* Signal parent that setup is complete */
if (write_nointr(sv[i][1], "R", 1) != 1)
_exit(1);
/* Wait for parent to signal us to exit */
if (read_nointr(sv[i][1], &c, 1) != 1)
_exit(1);
close(sv[i][1]);
_exit(0);
}
close(sv[i][1]); /* Close child end */
}
/* Wait for all children to finish setup */
for (i = 0; i < 10; i++) {
ret = read_nointr(sv[i][0], &c, 1);
ASSERT_EQ(ret, 1);
ASSERT_EQ(c, 'R');
}
/* Kill half the children */
for (i = 0; i < 5; i++)
write_nointr(sv[i][0], "X", 1);
/* Small delay to let some exit */
usleep(10000);
/* Kill remaining children */
for (i = 5; i < 10; i++)
write_nointr(sv[i][0], "X", 1);
/* Wait for all children and cleanup */
for (i = 0; i < 10; i++) {
waitpid(ns_pids[i], NULL, 0);
close(sv[i][0]);
close(pidfds[i]);
}
/* Kill iterator and wait for it */
sys_pidfd_send_signal(iter_pidfd, SIGKILL, NULL, 0);
ret = waitpid(iter_pid, &status, 0);
ASSERT_EQ(ret, iter_pid);
close(iter_pidfd);
/* If listns() is not supported the iterator exits cleanly via ENOSYS */
if (WIFEXITED(status) && WEXITSTATUS(status) == PIDFD_SKIP) {
munmap(map, page_size);
SKIP(return, "listns() not supported");
}
/* Should have been killed */
ASSERT_TRUE(WIFSIGNALED(status));
ASSERT_EQ(WTERMSIG(status), SIGKILL);
/* Clean up */
munmap(map, page_size);
}
/*
* Test specifically focused on mount namespace cleanup during EFAULT.
* Filter for mount namespaces only.
*/
TEST(listns_mnt_ns_cleanup_on_fault)
{
void *map;
__u64 *ns_ids;
ssize_t ret;
long page_size;
pid_t pid, iter_pid, ns_pids[8];
int pidfds[8];
int sv[8][2];
int iter_pidfd;
int i, status;
char c;
page_size = sysconf(_SC_PAGESIZE);
ASSERT_GT(page_size, 0);
/* Set up partial fault buffer */
map = mmap(NULL, page_size * 2, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
ASSERT_NE(map, MAP_FAILED);
ret = munmap((char *)map + page_size, page_size);
ASSERT_EQ(ret, 0);
/* Position for 3 successful writes, then fault */
ns_ids = ((__u64 *)((char *)map + page_size)) - 3;
/*
* Create a separate process to run listns() concurrently.
*/
iter_pid = create_child(&iter_pidfd, 0);
ASSERT_NE(iter_pid, -1);
if (iter_pid == 0) {
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWNS, /* Only mount namespaces */
.spare2 = 0,
.user_ns_id = 0,
};
int iter_ret;
/*
* Loop calling listns() until killed.
* Call listns() to race with namespace destruction.
*/
while (1) {
iter_ret = sys_listns(&req, ns_ids, 10, 0);
if (iter_ret == -1 && errno == ENOSYS)
_exit(PIDFD_SKIP);
}
}
/* Small delay to let iterator start looping */
usleep(50000);
/* Create children with mount namespaces */
for (i = 0; i < 8; i++) {
/* Create socketpair for synchronization */
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sv[i]), 0);
pid = create_child(&pidfds[i], CLONE_NEWNS);
ASSERT_NE(pid, -1);
ns_pids[i] = pid;
if (pid == 0) {
close(sv[i][0]); /* Close parent end */
if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, 0))
_exit(1);
/* Do some mount operations to make cleanup more interesting */
if (mkdir("/tmp/test_mnt1", 0755) == -1 && errno != EEXIST)
_exit(1);
if (mkdir("/tmp/test_mnt2", 0755) == -1 && errno != EEXIST)
_exit(1);
if (mount("tmpfs", "/tmp/test_mnt1", "tmpfs", 0, NULL) == -1)
_exit(1);
if (mount("tmpfs", "/tmp/test_mnt2", "tmpfs", 0, NULL) == -1)
_exit(1);
/* Signal parent that setup is complete */
if (write_nointr(sv[i][1], "R", 1) != 1)
_exit(1);
/* Wait for parent to signal us to exit */
if (read_nointr(sv[i][1], &c, 1) != 1)
_exit(1);
close(sv[i][1]);
_exit(0);
}
close(sv[i][1]); /* Close child end */
}
/* Wait for all children to finish setup */
for (i = 0; i < 8; i++) {
ret = read_nointr(sv[i][0], &c, 1);
ASSERT_EQ(ret, 1);
ASSERT_EQ(c, 'R');
}
/* Kill children to trigger namespace destruction during iteration */
for (i = 0; i < 8; i++)
write_nointr(sv[i][0], "X", 1);
/* Wait for children and cleanup */
for (i = 0; i < 8; i++) {
waitpid(ns_pids[i], NULL, 0);
close(sv[i][0]);
close(pidfds[i]);
}
/* Kill iterator and wait for it */
sys_pidfd_send_signal(iter_pidfd, SIGKILL, NULL, 0);
ret = waitpid(iter_pid, &status, 0);
ASSERT_EQ(ret, iter_pid);
close(iter_pidfd);
/* If listns() is not supported the iterator exits cleanly via ENOSYS */
if (WIFEXITED(status) && WEXITSTATUS(status) == PIDFD_SKIP) {
munmap(map, page_size);
SKIP(return, "listns() not supported");
}
/* Should have been killed */
ASSERT_TRUE(WIFSIGNALED(status));
ASSERT_EQ(WTERMSIG(status), SIGKILL);
munmap(map, page_size);
}
TEST_HARNESS_MAIN
@@ -0,0 +1,138 @@
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <errno.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include "../kselftest_harness.h"
#include "../filesystems/utils.h"
#include "wrappers.h"
/*
* Minimal test case to reproduce KASAN out-of-bounds in listns pagination.
*
* The bug occurs when:
* 1. Filtering by a specific namespace type (e.g., CLONE_NEWUSER)
* 2. Using pagination (req.ns_id != 0)
* 3. The lookup_ns_id_at() call in do_listns() passes ns_type=0 instead of
* the filtered type, causing it to search the unified tree and potentially
* return a namespace of the wrong type.
*/
TEST(pagination_with_type_filter)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER, /* Filter by user namespace */
.spare2 = 0,
.user_ns_id = 0,
};
pid_t pids[10];
int num_children = 10;
int i;
int sv[2];
__u64 first_batch[3];
ssize_t ret;
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
/* Create children with user namespaces */
for (i = 0; i < num_children; i++) {
pids[i] = fork();
ASSERT_GE(pids[i], 0);
if (pids[i] == 0) {
char c;
close(sv[0]);
if (setup_userns() < 0) {
close(sv[1]);
exit(1);
}
/* Signal parent we're ready */
if (write(sv[1], &c, 1) != 1) {
close(sv[1]);
exit(1);
}
/* Wait for parent signal to exit */
if (read(sv[1], &c, 1) != 1) {
close(sv[1]);
exit(1);
}
close(sv[1]);
exit(0);
}
}
close(sv[1]);
/* Wait for all children to signal ready */
for (i = 0; i < num_children; i++) {
char c;
if (read(sv[0], &c, 1) != 1) {
close(sv[0]);
for (int j = 0; j < num_children; j++)
kill(pids[j], SIGKILL);
for (int j = 0; j < num_children; j++)
waitpid(pids[j], NULL, 0);
ASSERT_TRUE(false);
}
}
/* First batch - this should work */
ret = sys_listns(&req, first_batch, 3, 0);
if (ret < 0) {
if (errno == ENOSYS) {
close(sv[0]);
for (i = 0; i < num_children; i++)
kill(pids[i], SIGKILL);
for (i = 0; i < num_children; i++)
waitpid(pids[i], NULL, 0);
SKIP(return, "listns() not supported");
}
ASSERT_GE(ret, 0);
}
TH_LOG("First batch returned %zd entries", ret);
if (ret == 3) {
__u64 second_batch[3];
/* Second batch - pagination triggers the bug */
req.ns_id = first_batch[2]; /* Continue from last ID */
ret = sys_listns(&req, second_batch, 3, 0);
TH_LOG("Second batch returned %zd entries", ret);
ASSERT_GE(ret, 0);
}
/* Signal all children to exit */
for (i = 0; i < num_children; i++) {
char c = 'X';
if (write(sv[0], &c, 1) != 1) {
close(sv[0]);
for (int j = i; j < num_children; j++)
kill(pids[j], SIGKILL);
for (int j = 0; j < num_children; j++)
waitpid(pids[j], NULL, 0);
ASSERT_TRUE(false);
}
}
close(sv[0]);
/* Cleanup */
for (i = 0; i < num_children; i++) {
int status;
waitpid(pids[i], &status, 0);
}
}
TEST_HARNESS_MAIN
@@ -0,0 +1,759 @@
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <linux/nsfs.h>
#include <sys/capability.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "../kselftest_harness.h"
#include "../filesystems/utils.h"
#include "wrappers.h"
/*
* Test that unprivileged users can only see namespaces they're currently in.
* Create a namespace, drop privileges, verify we can only see our own namespaces.
*/
TEST(listns_unprivileged_current_only)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWNET,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids[100];
ssize_t ret;
int pipefd[2];
pid_t pid;
int status;
bool found_ours;
int unexpected_count;
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
int fd;
__u64 our_netns_id;
bool found_ours;
int unexpected_count;
close(pipefd[0]);
/* Create user namespace to be unprivileged */
if (setup_userns() < 0) {
close(pipefd[1]);
exit(1);
}
/* Create a network namespace */
if (unshare(CLONE_NEWNET) < 0) {
close(pipefd[1]);
exit(1);
}
/* Get our network namespace ID */
fd = open("/proc/self/ns/net", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &our_netns_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
/* Now we're unprivileged - list all network namespaces */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
close(pipefd[1]);
exit(1);
}
/* We should only see our own network namespace */
found_ours = false;
unexpected_count = 0;
for (ssize_t i = 0; i < ret; i++) {
if (ns_ids[i] == our_netns_id) {
found_ours = true;
} else {
/* This is either init_net (which we can see) or unexpected */
unexpected_count++;
}
}
/* Send results to parent */
write(pipefd[1], &found_ours, sizeof(found_ours));
write(pipefd[1], &unexpected_count, sizeof(unexpected_count));
close(pipefd[1]);
exit(0);
}
/* Parent */
close(pipefd[1]);
found_ours = false;
unexpected_count = 0;
read(pipefd[0], &found_ours, sizeof(found_ours));
read(pipefd[0], &unexpected_count, sizeof(unexpected_count));
close(pipefd[0]);
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
/* Child should have seen its own namespace */
ASSERT_TRUE(found_ours);
TH_LOG("Unprivileged child saw its own namespace, plus %d others (likely init_net)",
unexpected_count);
}
/*
* Test that users with CAP_SYS_ADMIN in a user namespace can see
* all namespaces owned by that user namespace.
*/
TEST(listns_cap_sys_admin_in_userns)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0, /* All types */
.spare2 = 0,
.user_ns_id = 0, /* Will be set to our created user namespace */
};
__u64 ns_ids[100];
int pipefd[2];
pid_t pid;
int status;
bool success;
ssize_t count;
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
int fd;
__u64 userns_id;
ssize_t ret;
int min_expected;
bool success;
close(pipefd[0]);
/* Create user namespace - we'll have CAP_SYS_ADMIN in it */
if (setup_userns() < 0) {
close(pipefd[1]);
exit(1);
}
/* Get the user namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &userns_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
/* Create several namespaces owned by this user namespace */
unshare(CLONE_NEWNET);
unshare(CLONE_NEWUTS);
unshare(CLONE_NEWIPC);
/* List namespaces owned by our user namespace */
req.user_ns_id = userns_id;
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
close(pipefd[1]);
exit(1);
}
/*
* We have CAP_SYS_ADMIN in this user namespace,
* so we should see all namespaces owned by it.
* That includes: net, uts, ipc, and the user namespace itself.
*/
min_expected = 4;
success = (ret >= min_expected);
write(pipefd[1], &success, sizeof(success));
write(pipefd[1], &ret, sizeof(ret));
close(pipefd[1]);
exit(0);
}
/* Parent */
close(pipefd[1]);
success = false;
count = 0;
read(pipefd[0], &success, sizeof(success));
read(pipefd[0], &count, sizeof(count));
close(pipefd[0]);
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
ASSERT_TRUE(success);
TH_LOG("User with CAP_SYS_ADMIN saw %zd namespaces owned by their user namespace",
count);
}
/*
* Test that users cannot see namespaces from unrelated user namespaces.
* Create two sibling user namespaces, verify they can't see each other's
* owned namespaces.
*/
TEST(listns_cannot_see_sibling_userns_namespaces)
{
int pipefd[2];
pid_t pid1, pid2;
int status;
__u64 netns_a_id;
int pipefd2[2];
bool found_sibling_netns;
ASSERT_EQ(pipe(pipefd), 0);
/* Fork first child - creates user namespace A */
pid1 = fork();
ASSERT_GE(pid1, 0);
if (pid1 == 0) {
int fd;
__u64 netns_a_id;
char buf;
close(pipefd[0]);
/* Create user namespace A */
if (setup_userns() < 0) {
close(pipefd[1]);
exit(1);
}
/* Create network namespace owned by user namespace A */
if (unshare(CLONE_NEWNET) < 0) {
close(pipefd[1]);
exit(1);
}
/* Get network namespace ID */
fd = open("/proc/self/ns/net", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &netns_a_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
/* Send namespace ID to parent */
write(pipefd[1], &netns_a_id, sizeof(netns_a_id));
/* Keep alive for sibling to check */
read(pipefd[1], &buf, 1);
close(pipefd[1]);
exit(0);
}
/* Parent reads namespace A ID */
close(pipefd[1]);
netns_a_id = 0;
read(pipefd[0], &netns_a_id, sizeof(netns_a_id));
TH_LOG("User namespace A created network namespace with ID %llu",
(unsigned long long)netns_a_id);
/* Fork second child - creates user namespace B */
ASSERT_EQ(pipe(pipefd2), 0);
pid2 = fork();
ASSERT_GE(pid2, 0);
if (pid2 == 0) {
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWNET,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids[100];
ssize_t ret;
bool found_sibling_netns;
close(pipefd[0]);
close(pipefd2[0]);
/* Create user namespace B (sibling to A) */
if (setup_userns() < 0) {
close(pipefd2[1]);
exit(1);
}
/* Try to list all network namespaces */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
found_sibling_netns = false;
if (ret > 0) {
for (ssize_t i = 0; i < ret; i++) {
if (ns_ids[i] == netns_a_id) {
found_sibling_netns = true;
break;
}
}
}
/* We should NOT see the sibling's network namespace */
write(pipefd2[1], &found_sibling_netns, sizeof(found_sibling_netns));
close(pipefd2[1]);
exit(0);
}
/* Parent reads result from second child */
close(pipefd2[1]);
found_sibling_netns = false;
read(pipefd2[0], &found_sibling_netns, sizeof(found_sibling_netns));
close(pipefd2[0]);
/* Signal first child to exit */
close(pipefd[0]);
/* Wait for both children */
waitpid(pid2, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
waitpid(pid1, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
/* Second child should NOT have seen first child's namespace */
ASSERT_FALSE(found_sibling_netns);
TH_LOG("User namespace B correctly could not see sibling namespace A's network namespace");
}
/*
* Test permission checking with LISTNS_CURRENT_USER.
* Verify that listing with LISTNS_CURRENT_USER respects permissions.
*/
TEST(listns_current_user_permissions)
{
int pipefd[2];
pid_t pid;
int status;
bool success;
ssize_t count;
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0,
.spare2 = 0,
.user_ns_id = LISTNS_CURRENT_USER,
};
__u64 ns_ids[100];
ssize_t ret;
bool success;
close(pipefd[0]);
/* Create user namespace */
if (setup_userns() < 0) {
close(pipefd[1]);
exit(1);
}
/* Create some namespaces owned by this user namespace */
if (unshare(CLONE_NEWNET) < 0) {
close(pipefd[1]);
exit(1);
}
if (unshare(CLONE_NEWUTS) < 0) {
close(pipefd[1]);
exit(1);
}
/* List with LISTNS_CURRENT_USER - should see our owned namespaces */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
success = (ret >= 3); /* At least user, net, uts */
write(pipefd[1], &success, sizeof(success));
write(pipefd[1], &ret, sizeof(ret));
close(pipefd[1]);
exit(0);
}
/* Parent */
close(pipefd[1]);
success = false;
count = 0;
read(pipefd[0], &success, sizeof(success));
read(pipefd[0], &count, sizeof(count));
close(pipefd[0]);
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
ASSERT_TRUE(success);
TH_LOG("LISTNS_CURRENT_USER returned %zd namespaces", count);
}
/*
* Test that CAP_SYS_ADMIN in parent user namespace allows seeing
* child user namespace's owned namespaces.
*/
TEST(listns_parent_userns_cap_sys_admin)
{
int pipefd[2];
pid_t pid;
int status;
bool found_child_userns;
ssize_t count;
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
int fd;
__u64 parent_userns_id;
__u64 child_userns_id;
struct ns_id_req req;
__u64 ns_ids[100];
ssize_t ret;
bool found_child_userns;
close(pipefd[0]);
/* Create parent user namespace - we have CAP_SYS_ADMIN in it */
if (setup_userns() < 0) {
close(pipefd[1]);
exit(1);
}
/* Get parent user namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &parent_userns_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
/* Create child user namespace */
if (setup_userns() < 0) {
close(pipefd[1]);
exit(1);
}
/* Get child user namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &child_userns_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
/* Create namespaces owned by child user namespace */
if (unshare(CLONE_NEWNET) < 0) {
close(pipefd[1]);
exit(1);
}
/* List namespaces owned by parent user namespace */
req.size = sizeof(req);
req.spare = 0;
req.ns_id = 0;
req.ns_type = 0;
req.spare2 = 0;
req.user_ns_id = parent_userns_id;
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
/* Should see child user namespace in the list */
found_child_userns = false;
if (ret > 0) {
for (ssize_t i = 0; i < ret; i++) {
if (ns_ids[i] == child_userns_id) {
found_child_userns = true;
break;
}
}
}
write(pipefd[1], &found_child_userns, sizeof(found_child_userns));
write(pipefd[1], &ret, sizeof(ret));
close(pipefd[1]);
exit(0);
}
/* Parent */
close(pipefd[1]);
found_child_userns = false;
count = 0;
read(pipefd[0], &found_child_userns, sizeof(found_child_userns));
read(pipefd[0], &count, sizeof(count));
close(pipefd[0]);
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
ASSERT_TRUE(found_child_userns);
TH_LOG("Process with CAP_SYS_ADMIN in parent user namespace saw child user namespace (total: %zd)",
count);
}
/*
* Test that we can see user namespaces we have CAP_SYS_ADMIN inside of.
* This is different from seeing namespaces owned by a user namespace.
*/
TEST(listns_cap_sys_admin_inside_userns)
{
int pipefd[2];
pid_t pid;
int status;
bool found_ours;
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
int fd;
__u64 our_userns_id;
struct ns_id_req req;
__u64 ns_ids[100];
ssize_t ret;
bool found_ours;
close(pipefd[0]);
/* Create user namespace - we have CAP_SYS_ADMIN inside it */
if (setup_userns() < 0) {
close(pipefd[1]);
exit(1);
}
/* Get our user namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &our_userns_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
/* List all user namespaces globally */
req.size = sizeof(req);
req.spare = 0;
req.ns_id = 0;
req.ns_type = CLONE_NEWUSER;
req.spare2 = 0;
req.user_ns_id = 0;
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
/* We should be able to see our own user namespace */
found_ours = false;
if (ret > 0) {
for (ssize_t i = 0; i < ret; i++) {
if (ns_ids[i] == our_userns_id) {
found_ours = true;
break;
}
}
}
write(pipefd[1], &found_ours, sizeof(found_ours));
close(pipefd[1]);
exit(0);
}
/* Parent */
close(pipefd[1]);
found_ours = false;
read(pipefd[0], &found_ours, sizeof(found_ours));
close(pipefd[0]);
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
ASSERT_TRUE(found_ours);
TH_LOG("Process can see user namespace it has CAP_SYS_ADMIN inside of");
}
/*
* Test that dropping CAP_SYS_ADMIN restricts what we can see.
*/
TEST(listns_drop_cap_sys_admin)
{
cap_t caps;
cap_value_t cap_list[1] = { CAP_SYS_ADMIN };
/* This test needs to start with CAP_SYS_ADMIN */
caps = cap_get_proc();
if (!caps) {
SKIP(return, "Cannot get capabilities");
}
cap_flag_value_t cap_val;
if (cap_get_flag(caps, CAP_SYS_ADMIN, CAP_EFFECTIVE, &cap_val) < 0) {
cap_free(caps);
SKIP(return, "Cannot check CAP_SYS_ADMIN");
}
if (cap_val != CAP_SET) {
cap_free(caps);
SKIP(return, "Test needs CAP_SYS_ADMIN to start");
}
cap_free(caps);
int pipefd[2];
pid_t pid;
int status;
bool correct;
ssize_t count_before, count_after;
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWNET,
.spare2 = 0,
.user_ns_id = LISTNS_CURRENT_USER,
};
__u64 ns_ids_before[100];
ssize_t count_before;
__u64 ns_ids_after[100];
ssize_t count_after;
bool correct;
close(pipefd[0]);
/* Create user namespace */
if (setup_userns() < 0) {
close(pipefd[1]);
exit(1);
}
/* Count namespaces with CAP_SYS_ADMIN */
count_before = sys_listns(&req, ns_ids_before, ARRAY_SIZE(ns_ids_before), 0);
/* Drop CAP_SYS_ADMIN */
caps = cap_get_proc();
if (caps) {
cap_set_flag(caps, CAP_EFFECTIVE, 1, cap_list, CAP_CLEAR);
cap_set_flag(caps, CAP_PERMITTED, 1, cap_list, CAP_CLEAR);
cap_set_proc(caps);
cap_free(caps);
}
/* Ensure we can't regain the capability */
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
/* Count namespaces without CAP_SYS_ADMIN */
count_after = sys_listns(&req, ns_ids_after, ARRAY_SIZE(ns_ids_after), 0);
/* Without CAP_SYS_ADMIN, we should see same or fewer namespaces */
correct = (count_after <= count_before);
write(pipefd[1], &correct, sizeof(correct));
write(pipefd[1], &count_before, sizeof(count_before));
write(pipefd[1], &count_after, sizeof(count_after));
close(pipefd[1]);
exit(0);
}
/* Parent */
close(pipefd[1]);
correct = false;
count_before = 0;
count_after = 0;
read(pipefd[0], &correct, sizeof(correct));
read(pipefd[0], &count_before, sizeof(count_before));
read(pipefd[0], &count_after, sizeof(count_after));
close(pipefd[0]);
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
ASSERT_TRUE(correct);
TH_LOG("With CAP_SYS_ADMIN: %zd namespaces, without: %zd namespaces",
count_before, count_after);
}
TEST_HARNESS_MAIN
@@ -0,0 +1,679 @@
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <linux/nsfs.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "../kselftest_harness.h"
#include "../filesystems/utils.h"
#include "wrappers.h"
/*
* Test basic listns() functionality with the unified namespace tree.
* List all active namespaces globally.
*/
TEST(listns_basic_unified)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0, /* All types */
.spare2 = 0,
.user_ns_id = 0, /* Global listing */
};
__u64 ns_ids[100];
ssize_t ret;
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
TH_LOG("listns failed: %s (errno=%d)", strerror(errno), errno);
ASSERT_TRUE(false);
}
/* Should find at least the initial namespaces */
ASSERT_GT(ret, 0);
TH_LOG("Found %zd active namespaces", ret);
/* Verify all returned IDs are non-zero */
for (ssize_t i = 0; i < ret; i++) {
ASSERT_NE(ns_ids[i], 0);
TH_LOG(" [%zd] ns_id: %llu", i, (unsigned long long)ns_ids[i]);
}
}
/*
* Test listns() with type filtering.
* List only network namespaces.
*/
TEST(listns_filter_by_type)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWNET, /* Only network namespaces */
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids[100];
ssize_t ret;
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
TH_LOG("listns failed: %s (errno=%d)", strerror(errno), errno);
ASSERT_TRUE(false);
}
ASSERT_GE(ret, 0);
/* Should find at least init_net */
ASSERT_GT(ret, 0);
TH_LOG("Found %zd active network namespaces", ret);
/* Verify we can open each namespace and it's actually a network namespace */
for (ssize_t i = 0; i < ret && i < 5; i++) {
struct nsfs_file_handle nsfh = {
.ns_id = ns_ids[i],
.ns_type = CLONE_NEWNET,
.ns_inum = 0,
};
struct file_handle *fh;
int fd;
fh = (struct file_handle *)malloc(sizeof(*fh) + sizeof(nsfh));
ASSERT_NE(fh, NULL);
fh->handle_bytes = sizeof(nsfh);
fh->handle_type = 0;
memcpy(fh->f_handle, &nsfh, sizeof(nsfh));
fd = open_by_handle_at(-10003, fh, O_RDONLY);
free(fh);
if (fd >= 0) {
int ns_type;
/* Verify it's a network namespace via ioctl */
ns_type = ioctl(fd, NS_GET_NSTYPE);
if (ns_type >= 0) {
ASSERT_EQ(ns_type, CLONE_NEWNET);
}
close(fd);
}
}
}
/*
* Test listns() pagination.
* List namespaces in batches.
*/
TEST(listns_pagination)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 batch1[2], batch2[2];
ssize_t ret1, ret2;
/* Get first batch */
ret1 = sys_listns(&req, batch1, ARRAY_SIZE(batch1), 0);
if (ret1 < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
TH_LOG("listns failed: %s (errno=%d)", strerror(errno), errno);
ASSERT_TRUE(false);
}
ASSERT_GE(ret1, 0);
if (ret1 == 0)
SKIP(return, "No namespaces found");
TH_LOG("First batch: %zd namespaces", ret1);
/* Get second batch using last ID from first batch */
if (ret1 == ARRAY_SIZE(batch1)) {
req.ns_id = batch1[ret1 - 1];
ret2 = sys_listns(&req, batch2, ARRAY_SIZE(batch2), 0);
ASSERT_GE(ret2, 0);
TH_LOG("Second batch: %zd namespaces (after ns_id=%llu)",
ret2, (unsigned long long)req.ns_id);
/* If we got more results, verify IDs are monotonically increasing */
if (ret2 > 0) {
ASSERT_GT(batch2[0], batch1[ret1 - 1]);
TH_LOG("Pagination working: %llu > %llu",
(unsigned long long)batch2[0],
(unsigned long long)batch1[ret1 - 1]);
}
} else {
TH_LOG("All namespaces fit in first batch");
}
}
/*
* Test listns() with LISTNS_CURRENT_USER.
* List namespaces owned by current user namespace.
*/
TEST(listns_current_user)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0,
.spare2 = 0,
.user_ns_id = LISTNS_CURRENT_USER,
};
__u64 ns_ids[100];
ssize_t ret;
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
TH_LOG("listns failed: %s (errno=%d)", strerror(errno), errno);
ASSERT_TRUE(false);
}
ASSERT_GE(ret, 0);
/* Should find at least the initial namespaces if we're in init_user_ns */
TH_LOG("Found %zd namespaces owned by current user namespace", ret);
for (ssize_t i = 0; i < ret; i++)
TH_LOG(" [%zd] ns_id: %llu", i, (unsigned long long)ns_ids[i]);
}
/*
* Test that listns() only returns active namespaces.
* Create a namespace, let it become inactive, verify it's not listed.
*/
TEST(listns_only_active)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWNET,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids_before[100], ns_ids_after[100];
ssize_t ret_before, ret_after;
int pipefd[2];
pid_t pid;
__u64 new_ns_id = 0;
int status;
/* Get initial list */
ret_before = sys_listns(&req, ns_ids_before, ARRAY_SIZE(ns_ids_before), 0);
if (ret_before < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
TH_LOG("listns failed: %s (errno=%d)", strerror(errno), errno);
ASSERT_TRUE(false);
}
ASSERT_GE(ret_before, 0);
TH_LOG("Before: %zd active network namespaces", ret_before);
/* Create a new namespace in a child process and get its ID */
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
int fd;
__u64 ns_id;
close(pipefd[0]);
/* Create new network namespace */
if (unshare(CLONE_NEWNET) < 0) {
close(pipefd[1]);
exit(1);
}
/* Get its ID */
fd = open("/proc/self/ns/net", O_RDONLY);
if (fd < 0) {
close(pipefd[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &ns_id) < 0) {
close(fd);
close(pipefd[1]);
exit(1);
}
close(fd);
/* Send ID to parent */
write(pipefd[1], &ns_id, sizeof(ns_id));
close(pipefd[1]);
/* Keep namespace active briefly */
usleep(100000);
exit(0);
}
/* Parent reads the new namespace ID */
{
int bytes;
close(pipefd[1]);
bytes = read(pipefd[0], &new_ns_id, sizeof(new_ns_id));
close(pipefd[0]);
if (bytes == sizeof(new_ns_id)) {
__u64 ns_ids_during[100];
int ret_during;
TH_LOG("Child created namespace with ID %llu", (unsigned long long)new_ns_id);
/* List namespaces while child is still alive - should see new one */
ret_during = sys_listns(&req, ns_ids_during, ARRAY_SIZE(ns_ids_during), 0);
ASSERT_GE(ret_during, 0);
TH_LOG("During: %d active network namespaces", ret_during);
/* Should have more namespaces than before */
ASSERT_GE(ret_during, ret_before);
}
}
/* Wait for child to exit */
waitpid(pid, &status, 0);
/* Give time for namespace to become inactive */
usleep(100000);
/* List namespaces after child exits - should not see new one */
ret_after = sys_listns(&req, ns_ids_after, ARRAY_SIZE(ns_ids_after), 0);
ASSERT_GE(ret_after, 0);
TH_LOG("After: %zd active network namespaces", ret_after);
/* Verify the new namespace ID is not in the after list */
if (new_ns_id != 0) {
bool found = false;
for (ssize_t i = 0; i < ret_after; i++) {
if (ns_ids_after[i] == new_ns_id) {
found = true;
break;
}
}
ASSERT_FALSE(found);
}
}
/*
* Test listns() with specific user namespace ID.
* Create a user namespace and list namespaces it owns.
*/
TEST(listns_specific_userns)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0,
.spare2 = 0,
.user_ns_id = 0, /* Will be filled with created userns ID */
};
__u64 ns_ids[100];
int sv[2];
pid_t pid;
int status;
__u64 user_ns_id = 0;
int bytes;
ssize_t ret;
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
int fd;
__u64 ns_id;
char buf;
close(sv[0]);
/* Create new user namespace */
if (setup_userns() < 0) {
close(sv[1]);
exit(1);
}
/* Get user namespace ID */
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(sv[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &ns_id) < 0) {
close(fd);
close(sv[1]);
exit(1);
}
close(fd);
/* Send ID to parent */
if (write(sv[1], &ns_id, sizeof(ns_id)) != sizeof(ns_id)) {
close(sv[1]);
exit(1);
}
/* Create some namespaces owned by this user namespace */
unshare(CLONE_NEWNET);
unshare(CLONE_NEWUTS);
/* Wait for parent signal */
if (read(sv[1], &buf, 1) != 1) {
close(sv[1]);
exit(1);
}
close(sv[1]);
exit(0);
}
/* Parent */
close(sv[1]);
bytes = read(sv[0], &user_ns_id, sizeof(user_ns_id));
if (bytes != sizeof(user_ns_id)) {
close(sv[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
SKIP(return, "Failed to get user namespace ID from child");
}
TH_LOG("Child created user namespace with ID %llu", (unsigned long long)user_ns_id);
/* List namespaces owned by this user namespace */
req.user_ns_id = user_ns_id;
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
TH_LOG("listns failed: %s (errno=%d)", strerror(errno), errno);
close(sv[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
if (errno == ENOSYS) {
SKIP(return, "listns() not supported");
}
ASSERT_GE(ret, 0);
}
TH_LOG("Found %zd namespaces owned by user namespace %llu", ret,
(unsigned long long)user_ns_id);
/* Should find at least the network and UTS namespaces we created */
if (ret > 0) {
for (ssize_t i = 0; i < ret && i < 10; i++)
TH_LOG(" [%zd] ns_id: %llu", i, (unsigned long long)ns_ids[i]);
}
/* Signal child to exit */
if (write(sv[0], "X", 1) != 1) {
close(sv[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
ASSERT_TRUE(false);
}
close(sv[0]);
waitpid(pid, &status, 0);
}
/*
* Test listns() with multiple namespace types filter.
*/
TEST(listns_multiple_types)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWNET | CLONE_NEWUTS, /* Network and UTS */
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids[100];
ssize_t ret;
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
TH_LOG("listns failed: %s (errno=%d)", strerror(errno), errno);
ASSERT_TRUE(false);
}
ASSERT_GE(ret, 0);
TH_LOG("Found %zd active network/UTS namespaces", ret);
for (ssize_t i = 0; i < ret; i++)
TH_LOG(" [%zd] ns_id: %llu", i, (unsigned long long)ns_ids[i]);
}
/*
* Test that hierarchical active reference propagation keeps parent
* user namespaces visible in listns().
*/
TEST(listns_hierarchical_visibility)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 parent_ns_id = 0, child_ns_id = 0;
int sv[2];
pid_t pid;
int status;
int bytes;
__u64 ns_ids[100];
ssize_t ret;
bool found_parent, found_child;
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
int fd;
char buf;
close(sv[0]);
/* Create parent user namespace */
if (setup_userns() < 0) {
close(sv[1]);
exit(1);
}
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(sv[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &parent_ns_id) < 0) {
close(fd);
close(sv[1]);
exit(1);
}
close(fd);
/* Create child user namespace */
if (setup_userns() < 0) {
close(sv[1]);
exit(1);
}
fd = open("/proc/self/ns/user", O_RDONLY);
if (fd < 0) {
close(sv[1]);
exit(1);
}
if (ioctl(fd, NS_GET_ID, &child_ns_id) < 0) {
close(fd);
close(sv[1]);
exit(1);
}
close(fd);
/* Send both IDs to parent */
if (write(sv[1], &parent_ns_id, sizeof(parent_ns_id)) != sizeof(parent_ns_id)) {
close(sv[1]);
exit(1);
}
if (write(sv[1], &child_ns_id, sizeof(child_ns_id)) != sizeof(child_ns_id)) {
close(sv[1]);
exit(1);
}
/* Wait for parent signal */
if (read(sv[1], &buf, 1) != 1) {
close(sv[1]);
exit(1);
}
close(sv[1]);
exit(0);
}
/* Parent */
close(sv[1]);
/* Read both namespace IDs */
bytes = read(sv[0], &parent_ns_id, sizeof(parent_ns_id));
bytes += read(sv[0], &child_ns_id, sizeof(child_ns_id));
if (bytes != (int)(2 * sizeof(__u64))) {
close(sv[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
SKIP(return, "Failed to get namespace IDs from child");
}
TH_LOG("Parent user namespace ID: %llu", (unsigned long long)parent_ns_id);
TH_LOG("Child user namespace ID: %llu", (unsigned long long)child_ns_id);
/* List all user namespaces */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (ret < 0 && errno == ENOSYS) {
close(sv[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
SKIP(return, "listns() not supported");
}
ASSERT_GE(ret, 0);
TH_LOG("Found %zd active user namespaces", ret);
/* Both parent and child should be visible (active due to child process) */
found_parent = false;
found_child = false;
for (ssize_t i = 0; i < ret; i++) {
if (ns_ids[i] == parent_ns_id)
found_parent = true;
if (ns_ids[i] == child_ns_id)
found_child = true;
}
TH_LOG("Parent namespace %s, child namespace %s",
found_parent ? "found" : "NOT FOUND",
found_child ? "found" : "NOT FOUND");
ASSERT_TRUE(found_child);
/* With hierarchical propagation, parent should also be active */
ASSERT_TRUE(found_parent);
/* Signal child to exit */
if (write(sv[0], "X", 1) != 1) {
close(sv[0]);
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
ASSERT_TRUE(false);
}
close(sv[0]);
waitpid(pid, &status, 0);
}
/*
* Test error cases for listns().
*/
TEST(listns_error_cases)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids[10];
int ret;
/* Test with invalid flags */
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0xFFFF);
if (errno == ENOSYS) {
/* listns() not supported, skip this check */
} else {
ASSERT_LT(ret, 0);
ASSERT_EQ(errno, EINVAL);
}
/* Test with NULL ns_ids array */
ret = sys_listns(&req, NULL, 10, 0);
ASSERT_LT(ret, 0);
/* Test with invalid spare field */
req.spare = 1;
ret = sys_listns(&req, ns_ids, ARRAY_SIZE(ns_ids), 0);
if (errno == ENOSYS) {
/* listns() not supported, skip this check */
} else {
ASSERT_LT(ret, 0);
ASSERT_EQ(errno, EINVAL);
}
req.spare = 0;
/* Test with huge nr_ns_ids */
ret = sys_listns(&req, ns_ids, 2000000, 0);
if (errno == ENOSYS) {
/* listns() not supported, skip this check */
} else {
ASSERT_LT(ret, 0);
}
}
TEST_HARNESS_MAIN
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,993 @@
// SPDX-License-Identifier: GPL-2.0
#include <assert.h>
#include <fcntl.h>
#include <inttypes.h>
#include <libgen.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
#include <sys/mount.h>
#include <poll.h>
#include <sys/epoll.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
#include <linux/fs.h>
#include <linux/limits.h>
#include <linux/nsfs.h>
#include "kselftest_harness.h"
/* Fixture for tests that create child processes */
FIXTURE(nsid) {
pid_t child_pid;
pid_t grandchild_pid;
};
FIXTURE_SETUP(nsid) {
self->child_pid = 0;
self->grandchild_pid = 0;
}
FIXTURE_TEARDOWN(nsid) {
/*
* Kill grandchild first: timens_separate and pidns_separate fork a
* grandchild that calls pause(). It is reparented to init on child
* exit and keeps the test runner's tap pipe open, hanging the runner.
*/
if (self->grandchild_pid > 0) {
kill(self->grandchild_pid, SIGKILL);
waitpid(self->grandchild_pid, NULL, 0);
}
if (self->child_pid > 0) {
kill(self->child_pid, SIGKILL);
waitpid(self->child_pid, NULL, 0);
}
}
TEST(nsid_mntns_basic)
{
__u64 mnt_ns_id = 0;
int fd_mntns;
int ret;
/* Open the current mount namespace */
fd_mntns = open("/proc/self/ns/mnt", O_RDONLY);
ASSERT_GE(fd_mntns, 0);
/* Get the mount namespace ID */
ret = ioctl(fd_mntns, NS_GET_MNTNS_ID, &mnt_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(mnt_ns_id, 0);
/* Verify we can get the same ID again */
__u64 mnt_ns_id2 = 0;
ret = ioctl(fd_mntns, NS_GET_ID, &mnt_ns_id2);
ASSERT_EQ(ret, 0);
ASSERT_EQ(mnt_ns_id, mnt_ns_id2);
close(fd_mntns);
}
TEST_F(nsid, mntns_separate)
{
__u64 parent_mnt_ns_id = 0;
__u64 child_mnt_ns_id = 0;
int fd_parent_mntns, fd_child_mntns;
int ret;
pid_t pid;
int pipefd[2];
/* Get parent's mount namespace ID */
fd_parent_mntns = open("/proc/self/ns/mnt", O_RDONLY);
ASSERT_GE(fd_parent_mntns, 0);
ret = ioctl(fd_parent_mntns, NS_GET_ID, &parent_mnt_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(parent_mnt_ns_id, 0);
/* Create a pipe for synchronization */
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
close(pipefd[0]);
/* Create new mount namespace */
ret = unshare(CLONE_NEWNS);
if (ret != 0) {
/* Skip test if we don't have permission */
if (errno == EPERM || errno == EACCES) {
write(pipefd[1], "S", 1); /* Signal skip */
_exit(0);
}
_exit(1);
}
/* Signal success */
write(pipefd[1], "Y", 1);
close(pipefd[1]);
/* Keep namespace alive */
pause();
_exit(0);
}
/* Track child for cleanup */
self->child_pid = pid;
/* Parent process */
close(pipefd[1]);
char buf;
ASSERT_EQ(read(pipefd[0], &buf, 1), 1);
close(pipefd[0]);
if (buf == 'S') {
/* Child couldn't create namespace, skip test */
close(fd_parent_mntns);
SKIP(return, "No permission to create mount namespace");
}
ASSERT_EQ(buf, 'Y');
/* Open child's mount namespace */
char path[256];
snprintf(path, sizeof(path), "/proc/%d/ns/mnt", pid);
fd_child_mntns = open(path, O_RDONLY);
ASSERT_GE(fd_child_mntns, 0);
/* Get child's mount namespace ID */
ret = ioctl(fd_child_mntns, NS_GET_ID, &child_mnt_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(child_mnt_ns_id, 0);
/* Parent and child should have different mount namespace IDs */
ASSERT_NE(parent_mnt_ns_id, child_mnt_ns_id);
close(fd_parent_mntns);
close(fd_child_mntns);
}
TEST(nsid_cgroupns_basic)
{
__u64 cgroup_ns_id = 0;
int fd_cgroupns;
int ret;
/* Open the current cgroup namespace */
fd_cgroupns = open("/proc/self/ns/cgroup", O_RDONLY);
ASSERT_GE(fd_cgroupns, 0);
/* Get the cgroup namespace ID */
ret = ioctl(fd_cgroupns, NS_GET_ID, &cgroup_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(cgroup_ns_id, 0);
/* Verify we can get the same ID again */
__u64 cgroup_ns_id2 = 0;
ret = ioctl(fd_cgroupns, NS_GET_ID, &cgroup_ns_id2);
ASSERT_EQ(ret, 0);
ASSERT_EQ(cgroup_ns_id, cgroup_ns_id2);
close(fd_cgroupns);
}
TEST_F(nsid, cgroupns_separate)
{
__u64 parent_cgroup_ns_id = 0;
__u64 child_cgroup_ns_id = 0;
int fd_parent_cgroupns, fd_child_cgroupns;
int ret;
pid_t pid;
int pipefd[2];
/* Get parent's cgroup namespace ID */
fd_parent_cgroupns = open("/proc/self/ns/cgroup", O_RDONLY);
ASSERT_GE(fd_parent_cgroupns, 0);
ret = ioctl(fd_parent_cgroupns, NS_GET_ID, &parent_cgroup_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(parent_cgroup_ns_id, 0);
/* Create a pipe for synchronization */
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
close(pipefd[0]);
/* Create new cgroup namespace */
ret = unshare(CLONE_NEWCGROUP);
if (ret != 0) {
/* Skip test if we don't have permission */
if (errno == EPERM || errno == EACCES) {
write(pipefd[1], "S", 1); /* Signal skip */
_exit(0);
}
_exit(1);
}
/* Signal success */
write(pipefd[1], "Y", 1);
close(pipefd[1]);
/* Keep namespace alive */
pause();
_exit(0);
}
/* Track child for cleanup */
self->child_pid = pid;
/* Parent process */
close(pipefd[1]);
char buf;
ASSERT_EQ(read(pipefd[0], &buf, 1), 1);
close(pipefd[0]);
if (buf == 'S') {
/* Child couldn't create namespace, skip test */
close(fd_parent_cgroupns);
SKIP(return, "No permission to create cgroup namespace");
}
ASSERT_EQ(buf, 'Y');
/* Open child's cgroup namespace */
char path[256];
snprintf(path, sizeof(path), "/proc/%d/ns/cgroup", pid);
fd_child_cgroupns = open(path, O_RDONLY);
ASSERT_GE(fd_child_cgroupns, 0);
/* Get child's cgroup namespace ID */
ret = ioctl(fd_child_cgroupns, NS_GET_ID, &child_cgroup_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(child_cgroup_ns_id, 0);
/* Parent and child should have different cgroup namespace IDs */
ASSERT_NE(parent_cgroup_ns_id, child_cgroup_ns_id);
close(fd_parent_cgroupns);
close(fd_child_cgroupns);
}
TEST(nsid_ipcns_basic)
{
__u64 ipc_ns_id = 0;
int fd_ipcns;
int ret;
/* Open the current IPC namespace */
fd_ipcns = open("/proc/self/ns/ipc", O_RDONLY);
ASSERT_GE(fd_ipcns, 0);
/* Get the IPC namespace ID */
ret = ioctl(fd_ipcns, NS_GET_ID, &ipc_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(ipc_ns_id, 0);
/* Verify we can get the same ID again */
__u64 ipc_ns_id2 = 0;
ret = ioctl(fd_ipcns, NS_GET_ID, &ipc_ns_id2);
ASSERT_EQ(ret, 0);
ASSERT_EQ(ipc_ns_id, ipc_ns_id2);
close(fd_ipcns);
}
TEST_F(nsid, ipcns_separate)
{
__u64 parent_ipc_ns_id = 0;
__u64 child_ipc_ns_id = 0;
int fd_parent_ipcns, fd_child_ipcns;
int ret;
pid_t pid;
int pipefd[2];
/* Get parent's IPC namespace ID */
fd_parent_ipcns = open("/proc/self/ns/ipc", O_RDONLY);
ASSERT_GE(fd_parent_ipcns, 0);
ret = ioctl(fd_parent_ipcns, NS_GET_ID, &parent_ipc_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(parent_ipc_ns_id, 0);
/* Create a pipe for synchronization */
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
close(pipefd[0]);
/* Create new IPC namespace */
ret = unshare(CLONE_NEWIPC);
if (ret != 0) {
/* Skip test if we don't have permission */
if (errno == EPERM || errno == EACCES) {
write(pipefd[1], "S", 1); /* Signal skip */
_exit(0);
}
_exit(1);
}
/* Signal success */
write(pipefd[1], "Y", 1);
close(pipefd[1]);
/* Keep namespace alive */
pause();
_exit(0);
}
/* Track child for cleanup */
self->child_pid = pid;
/* Parent process */
close(pipefd[1]);
char buf;
ASSERT_EQ(read(pipefd[0], &buf, 1), 1);
close(pipefd[0]);
if (buf == 'S') {
/* Child couldn't create namespace, skip test */
close(fd_parent_ipcns);
SKIP(return, "No permission to create IPC namespace");
}
ASSERT_EQ(buf, 'Y');
/* Open child's IPC namespace */
char path[256];
snprintf(path, sizeof(path), "/proc/%d/ns/ipc", pid);
fd_child_ipcns = open(path, O_RDONLY);
ASSERT_GE(fd_child_ipcns, 0);
/* Get child's IPC namespace ID */
ret = ioctl(fd_child_ipcns, NS_GET_ID, &child_ipc_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(child_ipc_ns_id, 0);
/* Parent and child should have different IPC namespace IDs */
ASSERT_NE(parent_ipc_ns_id, child_ipc_ns_id);
close(fd_parent_ipcns);
close(fd_child_ipcns);
}
TEST(nsid_utsns_basic)
{
__u64 uts_ns_id = 0;
int fd_utsns;
int ret;
/* Open the current UTS namespace */
fd_utsns = open("/proc/self/ns/uts", O_RDONLY);
ASSERT_GE(fd_utsns, 0);
/* Get the UTS namespace ID */
ret = ioctl(fd_utsns, NS_GET_ID, &uts_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(uts_ns_id, 0);
/* Verify we can get the same ID again */
__u64 uts_ns_id2 = 0;
ret = ioctl(fd_utsns, NS_GET_ID, &uts_ns_id2);
ASSERT_EQ(ret, 0);
ASSERT_EQ(uts_ns_id, uts_ns_id2);
close(fd_utsns);
}
TEST_F(nsid, utsns_separate)
{
__u64 parent_uts_ns_id = 0;
__u64 child_uts_ns_id = 0;
int fd_parent_utsns, fd_child_utsns;
int ret;
pid_t pid;
int pipefd[2];
/* Get parent's UTS namespace ID */
fd_parent_utsns = open("/proc/self/ns/uts", O_RDONLY);
ASSERT_GE(fd_parent_utsns, 0);
ret = ioctl(fd_parent_utsns, NS_GET_ID, &parent_uts_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(parent_uts_ns_id, 0);
/* Create a pipe for synchronization */
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
close(pipefd[0]);
/* Create new UTS namespace */
ret = unshare(CLONE_NEWUTS);
if (ret != 0) {
/* Skip test if we don't have permission */
if (errno == EPERM || errno == EACCES) {
write(pipefd[1], "S", 1); /* Signal skip */
_exit(0);
}
_exit(1);
}
/* Signal success */
write(pipefd[1], "Y", 1);
close(pipefd[1]);
/* Keep namespace alive */
pause();
_exit(0);
}
/* Track child for cleanup */
self->child_pid = pid;
/* Parent process */
close(pipefd[1]);
char buf;
ASSERT_EQ(read(pipefd[0], &buf, 1), 1);
close(pipefd[0]);
if (buf == 'S') {
/* Child couldn't create namespace, skip test */
close(fd_parent_utsns);
SKIP(return, "No permission to create UTS namespace");
}
ASSERT_EQ(buf, 'Y');
/* Open child's UTS namespace */
char path[256];
snprintf(path, sizeof(path), "/proc/%d/ns/uts", pid);
fd_child_utsns = open(path, O_RDONLY);
ASSERT_GE(fd_child_utsns, 0);
/* Get child's UTS namespace ID */
ret = ioctl(fd_child_utsns, NS_GET_ID, &child_uts_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(child_uts_ns_id, 0);
/* Parent and child should have different UTS namespace IDs */
ASSERT_NE(parent_uts_ns_id, child_uts_ns_id);
close(fd_parent_utsns);
close(fd_child_utsns);
}
TEST(nsid_userns_basic)
{
__u64 user_ns_id = 0;
int fd_userns;
int ret;
/* Open the current user namespace */
fd_userns = open("/proc/self/ns/user", O_RDONLY);
ASSERT_GE(fd_userns, 0);
/* Get the user namespace ID */
ret = ioctl(fd_userns, NS_GET_ID, &user_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(user_ns_id, 0);
/* Verify we can get the same ID again */
__u64 user_ns_id2 = 0;
ret = ioctl(fd_userns, NS_GET_ID, &user_ns_id2);
ASSERT_EQ(ret, 0);
ASSERT_EQ(user_ns_id, user_ns_id2);
close(fd_userns);
}
TEST_F(nsid, userns_separate)
{
__u64 parent_user_ns_id = 0;
__u64 child_user_ns_id = 0;
int fd_parent_userns, fd_child_userns;
int ret;
pid_t pid;
int pipefd[2];
/* Get parent's user namespace ID */
fd_parent_userns = open("/proc/self/ns/user", O_RDONLY);
ASSERT_GE(fd_parent_userns, 0);
ret = ioctl(fd_parent_userns, NS_GET_ID, &parent_user_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(parent_user_ns_id, 0);
/* Create a pipe for synchronization */
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
close(pipefd[0]);
/* Create new user namespace */
ret = unshare(CLONE_NEWUSER);
if (ret != 0) {
/* Skip test if we don't have permission */
if (errno == EPERM || errno == EACCES) {
write(pipefd[1], "S", 1); /* Signal skip */
_exit(0);
}
_exit(1);
}
/* Signal success */
write(pipefd[1], "Y", 1);
close(pipefd[1]);
/* Keep namespace alive */
pause();
_exit(0);
}
/* Track child for cleanup */
self->child_pid = pid;
/* Parent process */
close(pipefd[1]);
char buf;
ASSERT_EQ(read(pipefd[0], &buf, 1), 1);
close(pipefd[0]);
if (buf == 'S') {
/* Child couldn't create namespace, skip test */
close(fd_parent_userns);
SKIP(return, "No permission to create user namespace");
}
ASSERT_EQ(buf, 'Y');
/* Open child's user namespace */
char path[256];
snprintf(path, sizeof(path), "/proc/%d/ns/user", pid);
fd_child_userns = open(path, O_RDONLY);
ASSERT_GE(fd_child_userns, 0);
/* Get child's user namespace ID */
ret = ioctl(fd_child_userns, NS_GET_ID, &child_user_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(child_user_ns_id, 0);
/* Parent and child should have different user namespace IDs */
ASSERT_NE(parent_user_ns_id, child_user_ns_id);
close(fd_parent_userns);
close(fd_child_userns);
}
TEST(nsid_timens_basic)
{
__u64 time_ns_id = 0;
int fd_timens;
int ret;
/* Open the current time namespace */
fd_timens = open("/proc/self/ns/time", O_RDONLY);
if (fd_timens < 0) {
SKIP(return, "Time namespaces not supported");
}
/* Get the time namespace ID */
ret = ioctl(fd_timens, NS_GET_ID, &time_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(time_ns_id, 0);
/* Verify we can get the same ID again */
__u64 time_ns_id2 = 0;
ret = ioctl(fd_timens, NS_GET_ID, &time_ns_id2);
ASSERT_EQ(ret, 0);
ASSERT_EQ(time_ns_id, time_ns_id2);
close(fd_timens);
}
TEST_F(nsid, timens_separate)
{
__u64 parent_time_ns_id = 0;
__u64 child_time_ns_id = 0;
int fd_parent_timens, fd_child_timens;
int ret;
pid_t pid;
int pipefd[2];
/* Open the current time namespace */
fd_parent_timens = open("/proc/self/ns/time", O_RDONLY);
if (fd_parent_timens < 0) {
SKIP(return, "Time namespaces not supported");
}
/* Get parent's time namespace ID */
ret = ioctl(fd_parent_timens, NS_GET_ID, &parent_time_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(parent_time_ns_id, 0);
/* Create a pipe for synchronization */
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
close(pipefd[0]);
/* Create new time namespace */
ret = unshare(CLONE_NEWTIME);
if (ret != 0) {
/* Skip test if we don't have permission */
if (errno == EPERM || errno == EACCES || errno == EINVAL) {
write(pipefd[1], "S", 1); /* Signal skip */
_exit(0);
}
_exit(1);
}
/* Fork a grandchild to actually enter the new namespace */
pid_t grandchild = fork();
if (grandchild == 0) {
/* Grandchild is in the new namespace */
write(pipefd[1], "Y", 1);
close(pipefd[1]);
pause();
_exit(0);
} else if (grandchild > 0) {
/* Child writes grandchild PID and waits */
write(pipefd[1], "Y", 1);
write(pipefd[1], &grandchild, sizeof(grandchild));
close(pipefd[1]);
pause(); /* Keep the parent alive to maintain the grandchild */
_exit(0);
} else {
_exit(1);
}
}
/* Track child for cleanup */
self->child_pid = pid;
/* Parent process */
close(pipefd[1]);
char buf;
ASSERT_EQ(read(pipefd[0], &buf, 1), 1);
if (buf == 'S') {
/* Child couldn't create namespace, skip test */
close(fd_parent_timens);
close(pipefd[0]);
SKIP(return, "Cannot create time namespace");
}
ASSERT_EQ(buf, 'Y');
pid_t grandchild_pid;
ASSERT_EQ(read(pipefd[0], &grandchild_pid, sizeof(grandchild_pid)), sizeof(grandchild_pid));
self->grandchild_pid = grandchild_pid;
close(pipefd[0]);
/* Open grandchild's time namespace */
char path[256];
snprintf(path, sizeof(path), "/proc/%d/ns/time", grandchild_pid);
fd_child_timens = open(path, O_RDONLY);
ASSERT_GE(fd_child_timens, 0);
/* Get child's time namespace ID */
ret = ioctl(fd_child_timens, NS_GET_ID, &child_time_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(child_time_ns_id, 0);
/* Parent and child should have different time namespace IDs */
ASSERT_NE(parent_time_ns_id, child_time_ns_id);
close(fd_parent_timens);
close(fd_child_timens);
}
TEST(nsid_pidns_basic)
{
__u64 pid_ns_id = 0;
int fd_pidns;
int ret;
/* Open the current PID namespace */
fd_pidns = open("/proc/self/ns/pid", O_RDONLY);
ASSERT_GE(fd_pidns, 0);
/* Get the PID namespace ID */
ret = ioctl(fd_pidns, NS_GET_ID, &pid_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(pid_ns_id, 0);
/* Verify we can get the same ID again */
__u64 pid_ns_id2 = 0;
ret = ioctl(fd_pidns, NS_GET_ID, &pid_ns_id2);
ASSERT_EQ(ret, 0);
ASSERT_EQ(pid_ns_id, pid_ns_id2);
close(fd_pidns);
}
TEST_F(nsid, pidns_separate)
{
__u64 parent_pid_ns_id = 0;
__u64 child_pid_ns_id = 0;
int fd_parent_pidns, fd_child_pidns;
int ret;
pid_t pid;
int pipefd[2];
/* Get parent's PID namespace ID */
fd_parent_pidns = open("/proc/self/ns/pid", O_RDONLY);
ASSERT_GE(fd_parent_pidns, 0);
ret = ioctl(fd_parent_pidns, NS_GET_ID, &parent_pid_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(parent_pid_ns_id, 0);
/* Create a pipe for synchronization */
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
close(pipefd[0]);
/* Create new PID namespace */
ret = unshare(CLONE_NEWPID);
if (ret != 0) {
/* Skip test if we don't have permission */
if (errno == EPERM || errno == EACCES) {
write(pipefd[1], "S", 1); /* Signal skip */
_exit(0);
}
_exit(1);
}
/* Fork a grandchild to actually enter the new namespace */
pid_t grandchild = fork();
if (grandchild == 0) {
/* Grandchild is in the new namespace */
write(pipefd[1], "Y", 1);
close(pipefd[1]);
pause();
_exit(0);
} else if (grandchild > 0) {
/* Child writes grandchild PID and waits */
write(pipefd[1], "Y", 1);
write(pipefd[1], &grandchild, sizeof(grandchild));
close(pipefd[1]);
pause(); /* Keep the parent alive to maintain the grandchild */
_exit(0);
} else {
_exit(1);
}
}
/* Track child for cleanup */
self->child_pid = pid;
/* Parent process */
close(pipefd[1]);
char buf;
ASSERT_EQ(read(pipefd[0], &buf, 1), 1);
if (buf == 'S') {
/* Child couldn't create namespace, skip test */
close(fd_parent_pidns);
close(pipefd[0]);
SKIP(return, "No permission to create PID namespace");
}
ASSERT_EQ(buf, 'Y');
pid_t grandchild_pid;
ASSERT_EQ(read(pipefd[0], &grandchild_pid, sizeof(grandchild_pid)), sizeof(grandchild_pid));
self->grandchild_pid = grandchild_pid;
close(pipefd[0]);
/* Open grandchild's PID namespace */
char path[256];
snprintf(path, sizeof(path), "/proc/%d/ns/pid", grandchild_pid);
fd_child_pidns = open(path, O_RDONLY);
ASSERT_GE(fd_child_pidns, 0);
/* Get child's PID namespace ID */
ret = ioctl(fd_child_pidns, NS_GET_ID, &child_pid_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(child_pid_ns_id, 0);
/* Parent and child should have different PID namespace IDs */
ASSERT_NE(parent_pid_ns_id, child_pid_ns_id);
close(fd_parent_pidns);
close(fd_child_pidns);
}
TEST(nsid_netns_basic)
{
__u64 net_ns_id = 0;
__u64 netns_cookie = 0;
int fd_netns;
int sock;
socklen_t optlen;
int ret;
/* Open the current network namespace */
fd_netns = open("/proc/self/ns/net", O_RDONLY);
ASSERT_GE(fd_netns, 0);
/* Get the network namespace ID via ioctl */
ret = ioctl(fd_netns, NS_GET_ID, &net_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(net_ns_id, 0);
/* Create a socket to get the SO_NETNS_COOKIE */
sock = socket(AF_UNIX, SOCK_STREAM, 0);
ASSERT_GE(sock, 0);
/* Get the network namespace cookie via socket option */
optlen = sizeof(netns_cookie);
ret = getsockopt(sock, SOL_SOCKET, SO_NETNS_COOKIE, &netns_cookie, &optlen);
ASSERT_EQ(ret, 0);
ASSERT_EQ(optlen, sizeof(netns_cookie));
/* The namespace ID and cookie should be identical */
ASSERT_EQ(net_ns_id, netns_cookie);
/* Verify we can get the same ID again */
__u64 net_ns_id2 = 0;
ret = ioctl(fd_netns, NS_GET_ID, &net_ns_id2);
ASSERT_EQ(ret, 0);
ASSERT_EQ(net_ns_id, net_ns_id2);
close(sock);
close(fd_netns);
}
TEST_F(nsid, netns_separate)
{
__u64 parent_net_ns_id = 0;
__u64 parent_netns_cookie = 0;
__u64 child_net_ns_id = 0;
__u64 child_netns_cookie = 0;
int fd_parent_netns, fd_child_netns;
int parent_sock, child_sock;
socklen_t optlen;
int ret;
pid_t pid;
int pipefd[2];
/* Get parent's network namespace ID */
fd_parent_netns = open("/proc/self/ns/net", O_RDONLY);
ASSERT_GE(fd_parent_netns, 0);
ret = ioctl(fd_parent_netns, NS_GET_ID, &parent_net_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(parent_net_ns_id, 0);
/* Get parent's network namespace cookie */
parent_sock = socket(AF_UNIX, SOCK_STREAM, 0);
ASSERT_GE(parent_sock, 0);
optlen = sizeof(parent_netns_cookie);
ret = getsockopt(parent_sock, SOL_SOCKET, SO_NETNS_COOKIE, &parent_netns_cookie, &optlen);
ASSERT_EQ(ret, 0);
/* Verify parent's ID and cookie match */
ASSERT_EQ(parent_net_ns_id, parent_netns_cookie);
/* Create a pipe for synchronization */
ASSERT_EQ(pipe(pipefd), 0);
pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child process */
close(pipefd[0]);
/* Create new network namespace */
ret = unshare(CLONE_NEWNET);
if (ret != 0) {
/* Skip test if we don't have permission */
if (errno == EPERM || errno == EACCES) {
write(pipefd[1], "S", 1); /* Signal skip */
_exit(0);
}
_exit(1);
}
/* Signal success */
write(pipefd[1], "Y", 1);
close(pipefd[1]);
/* Keep namespace alive */
pause();
_exit(0);
}
/* Track child for cleanup */
self->child_pid = pid;
/* Parent process */
close(pipefd[1]);
char buf;
ASSERT_EQ(read(pipefd[0], &buf, 1), 1);
close(pipefd[0]);
if (buf == 'S') {
/* Child couldn't create namespace, skip test */
close(fd_parent_netns);
close(parent_sock);
SKIP(return, "No permission to create network namespace");
}
ASSERT_EQ(buf, 'Y');
/* Open child's network namespace */
char path[256];
snprintf(path, sizeof(path), "/proc/%d/ns/net", pid);
fd_child_netns = open(path, O_RDONLY);
ASSERT_GE(fd_child_netns, 0);
/* Get child's network namespace ID */
ret = ioctl(fd_child_netns, NS_GET_ID, &child_net_ns_id);
ASSERT_EQ(ret, 0);
ASSERT_NE(child_net_ns_id, 0);
/* Create socket in child's namespace to get cookie */
ret = setns(fd_child_netns, CLONE_NEWNET);
if (ret == 0) {
child_sock = socket(AF_UNIX, SOCK_STREAM, 0);
ASSERT_GE(child_sock, 0);
optlen = sizeof(child_netns_cookie);
ret = getsockopt(child_sock, SOL_SOCKET, SO_NETNS_COOKIE, &child_netns_cookie, &optlen);
ASSERT_EQ(ret, 0);
/* Verify child's ID and cookie match */
ASSERT_EQ(child_net_ns_id, child_netns_cookie);
close(child_sock);
/* Return to parent namespace */
setns(fd_parent_netns, CLONE_NEWNET);
}
/* Parent and child should have different network namespace IDs */
ASSERT_NE(parent_net_ns_id, child_net_ns_id);
if (child_netns_cookie != 0) {
ASSERT_NE(parent_netns_cookie, child_netns_cookie);
}
close(fd_parent_netns);
close(fd_child_netns);
close(parent_sock);
}
TEST_HARNESS_MAIN
@@ -0,0 +1,113 @@
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <errno.h>
#include <sched.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include "../pidfd/pidfd.h"
#include "../kselftest_harness.h"
/*
* Regression tests for the setns(pidfd) active reference counting bug.
*
* These tests are based on the reproducers that triggered the race condition
* fixed by commit 1c465d0518dc ("ns: handle setns(pidfd, ...) cleanly").
*
* The bug: When using setns() with a pidfd, if the target task exits between
* prepare_nsset() and commit_nsset(), the namespaces would become inactive.
* Then ns_ref_active_get() would increment from 0 without properly resurrecting
* the owner chain, causing active reference count underflows.
*/
/*
* Simple pidfd setns test using create_child()+unshare().
*
* Without the fix, this would trigger active refcount warnings when the
* parent exits after doing setns(pidfd) on a child that has already exited.
*/
TEST(simple_pidfd_setns)
{
pid_t child_pid;
int pidfd = -1;
int ret;
int sv[2];
char c;
/* Ignore SIGCHLD for autoreap */
ASSERT_NE(signal(SIGCHLD, SIG_IGN), SIG_ERR);
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
/* Create a child process without namespaces initially */
child_pid = create_child(&pidfd, 0);
ASSERT_GE(child_pid, 0);
if (child_pid == 0) {
close(sv[0]);
if (unshare(CLONE_NEWUTS | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWUSER) < 0) {
close(sv[1]);
_exit(1);
}
/* Signal parent that namespaces are ready */
if (write_nointr(sv[1], "1", 1) < 0) {
close(sv[1]);
_exit(1);
}
close(sv[1]);
_exit(0);
}
ASSERT_GE(pidfd, 0);
EXPECT_EQ(close(sv[1]), 0);
ret = read_nointr(sv[0], &c, 1);
ASSERT_EQ(ret, 1);
EXPECT_EQ(close(sv[0]), 0);
/* Set to child's namespaces via pidfd */
ret = setns(pidfd, CLONE_NEWUTS | CLONE_NEWIPC);
TH_LOG("setns() returned %d", ret);
close(pidfd);
}
/*
* Simple pidfd setns test using create_child().
*
* This variation uses create_child() with namespace flags directly.
* Namespaces are created immediately at clone time.
*/
TEST(simple_pidfd_setns_clone)
{
pid_t child_pid;
int pidfd = -1;
int ret;
/* Ignore SIGCHLD for autoreap */
ASSERT_NE(signal(SIGCHLD, SIG_IGN), SIG_ERR);
/* Create a child process with new namespaces using create_child() */
child_pid = create_child(&pidfd, CLONE_NEWUSER | CLONE_NEWUTS | CLONE_NEWIPC | CLONE_NEWNET);
ASSERT_GE(child_pid, 0);
if (child_pid == 0) {
/* Child: sleep for a while so parent can setns to us */
sleep(2);
_exit(0);
}
/* Parent: pidfd was already created by create_child() */
ASSERT_GE(pidfd, 0);
/* Set to child's namespaces via pidfd */
ret = setns(pidfd, CLONE_NEWUTS | CLONE_NEWIPC);
close(pidfd);
TH_LOG("setns() returned %d", ret);
}
TEST_HARNESS_MAIN
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,626 @@
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <linux/nsfs.h>
#include "../kselftest_harness.h"
#include "../filesystems/utils.h"
#include "wrappers.h"
/*
* Stress tests for namespace active reference counting.
*
* These tests validate that the active reference counting system can handle
* high load scenarios including rapid namespace creation/destruction, large
* numbers of concurrent namespaces, and various edge cases under stress.
*/
/*
* Test rapid creation and destruction of user namespaces.
* Create and destroy namespaces in quick succession to stress the
* active reference tracking and ensure no leaks occur.
*/
TEST(rapid_namespace_creation_destruction)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids_before[256], ns_ids_after[256];
ssize_t ret_before, ret_after;
int i;
/* Get baseline count of active user namespaces */
ret_before = sys_listns(&req, ns_ids_before, ARRAY_SIZE(ns_ids_before), 0);
if (ret_before < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret_before, 0);
}
TH_LOG("Baseline: %zd active user namespaces", ret_before);
/* Rapidly create and destroy 100 user namespaces */
for (i = 0; i < 100; i++) {
pid_t pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child: create user namespace and immediately exit */
if (setup_userns() < 0)
exit(1);
exit(0);
}
/* Parent: wait for child */
int status;
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
}
/* Verify we're back to baseline (no leaked namespaces) */
ret_after = sys_listns(&req, ns_ids_after, ARRAY_SIZE(ns_ids_after), 0);
ASSERT_GE(ret_after, 0);
TH_LOG("After 100 rapid create/destroy cycles: %zd active user namespaces", ret_after);
ASSERT_EQ(ret_before, ret_after);
}
/*
* Test creating many concurrent namespaces.
* Verify that listns() correctly tracks all of them and that they all
* become inactive after processes exit.
*/
TEST(many_concurrent_namespaces)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids_before[512], ns_ids_during[512], ns_ids_after[512];
ssize_t ret_before, ret_during, ret_after;
pid_t pids[50];
int num_children = 50;
int i;
int sv[2];
/* Get baseline */
ret_before = sys_listns(&req, ns_ids_before, ARRAY_SIZE(ns_ids_before), 0);
if (ret_before < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret_before, 0);
}
TH_LOG("Baseline: %zd active user namespaces", ret_before);
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
/* Create many children, each with their own user namespace */
for (i = 0; i < num_children; i++) {
pids[i] = fork();
ASSERT_GE(pids[i], 0);
if (pids[i] == 0) {
/* Child: create user namespace and wait for parent signal */
char c;
close(sv[0]);
if (setup_userns() < 0) {
close(sv[1]);
exit(1);
}
/* Signal parent we're ready */
if (write(sv[1], &c, 1) != 1) {
close(sv[1]);
exit(1);
}
/* Wait for parent signal to exit */
if (read(sv[1], &c, 1) != 1) {
close(sv[1]);
exit(1);
}
close(sv[1]);
exit(0);
}
}
close(sv[1]);
/* Wait for all children to signal ready */
for (i = 0; i < num_children; i++) {
char c;
if (read(sv[0], &c, 1) != 1) {
/* If we fail to read, kill all children and exit */
close(sv[0]);
for (int j = 0; j < num_children; j++)
kill(pids[j], SIGKILL);
for (int j = 0; j < num_children; j++)
waitpid(pids[j], NULL, 0);
ASSERT_TRUE(false);
}
}
/* List namespaces while all children are running */
ret_during = sys_listns(&req, ns_ids_during, ARRAY_SIZE(ns_ids_during), 0);
ASSERT_GE(ret_during, 0);
TH_LOG("With %d children running: %zd active user namespaces", num_children, ret_during);
/* Should have at least num_children more namespaces than baseline */
ASSERT_GE(ret_during, ret_before + num_children);
/* Signal all children to exit */
for (i = 0; i < num_children; i++) {
char c = 'X';
if (write(sv[0], &c, 1) != 1) {
/* If we fail to write, kill remaining children */
close(sv[0]);
for (int j = i; j < num_children; j++)
kill(pids[j], SIGKILL);
for (int j = 0; j < num_children; j++)
waitpid(pids[j], NULL, 0);
ASSERT_TRUE(false);
}
}
close(sv[0]);
/* Wait for all children */
for (i = 0; i < num_children; i++) {
int status;
waitpid(pids[i], &status, 0);
ASSERT_TRUE(WIFEXITED(status));
}
/* Verify we're back to baseline */
ret_after = sys_listns(&req, ns_ids_after, ARRAY_SIZE(ns_ids_after), 0);
ASSERT_GE(ret_after, 0);
TH_LOG("After all children exit: %zd active user namespaces", ret_after);
ASSERT_EQ(ret_before, ret_after);
}
/*
* Test rapid namespace creation with different namespace types.
* Create multiple types of namespaces rapidly to stress the tracking system.
*/
TEST(rapid_mixed_namespace_creation)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0, /* All types */
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids_before[512], ns_ids_after[512];
ssize_t ret_before, ret_after;
int i;
/* Get baseline count */
ret_before = sys_listns(&req, ns_ids_before, ARRAY_SIZE(ns_ids_before), 0);
if (ret_before < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret_before, 0);
}
TH_LOG("Baseline: %zd active namespaces (all types)", ret_before);
/* Rapidly create and destroy namespaces with multiple types */
for (i = 0; i < 50; i++) {
pid_t pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
/* Child: create multiple namespace types */
if (setup_userns() < 0)
exit(1);
/* Create additional namespace types */
if (unshare(CLONE_NEWNET) < 0)
exit(1);
if (unshare(CLONE_NEWUTS) < 0)
exit(1);
if (unshare(CLONE_NEWIPC) < 0)
exit(1);
exit(0);
}
/* Parent: wait for child */
int status;
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
}
/* Verify we're back to baseline */
ret_after = sys_listns(&req, ns_ids_after, ARRAY_SIZE(ns_ids_after), 0);
ASSERT_GE(ret_after, 0);
TH_LOG("After 50 rapid mixed namespace cycles: %zd active namespaces", ret_after);
ASSERT_EQ(ret_before, ret_after);
}
/*
* Test nested namespace creation under stress.
* Create deeply nested namespace hierarchies and verify proper cleanup.
*/
TEST(nested_namespace_stress)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids_before[512], ns_ids_after[512];
ssize_t ret_before, ret_after;
int i;
/* Get baseline */
ret_before = sys_listns(&req, ns_ids_before, ARRAY_SIZE(ns_ids_before), 0);
if (ret_before < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret_before, 0);
}
TH_LOG("Baseline: %zd active user namespaces", ret_before);
/* Create 20 processes, each with nested user namespaces */
for (i = 0; i < 20; i++) {
pid_t pid = fork();
ASSERT_GE(pid, 0);
if (pid == 0) {
int userns_fd;
uid_t orig_uid = getuid();
int depth;
/* Create nested user namespaces (up to 5 levels) */
for (depth = 0; depth < 5; depth++) {
userns_fd = get_userns_fd(0, (depth == 0) ? orig_uid : 0, 1);
if (userns_fd < 0)
exit(1);
if (setns(userns_fd, CLONE_NEWUSER) < 0) {
close(userns_fd);
exit(1);
}
close(userns_fd);
}
exit(0);
}
/* Parent: wait for child */
int status;
waitpid(pid, &status, 0);
ASSERT_TRUE(WIFEXITED(status));
}
/* Verify we're back to baseline */
ret_after = sys_listns(&req, ns_ids_after, ARRAY_SIZE(ns_ids_after), 0);
ASSERT_GE(ret_after, 0);
TH_LOG("After 20 nested namespace hierarchies: %zd active user namespaces", ret_after);
ASSERT_EQ(ret_before, ret_after);
}
/*
* Test listns() pagination under stress.
* Create many namespaces and verify pagination works correctly.
*/
TEST(listns_pagination_stress)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER,
.spare2 = 0,
.user_ns_id = 0,
};
pid_t pids[30];
int num_children = 30;
int i;
int sv[2];
__u64 all_ns_ids[512];
int total_found = 0;
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
/* Create many children with user namespaces */
for (i = 0; i < num_children; i++) {
pids[i] = fork();
ASSERT_GE(pids[i], 0);
if (pids[i] == 0) {
char c;
close(sv[0]);
if (setup_userns() < 0) {
close(sv[1]);
exit(1);
}
/* Signal parent we're ready */
if (write(sv[1], &c, 1) != 1) {
close(sv[1]);
exit(1);
}
/* Wait for parent signal to exit */
if (read(sv[1], &c, 1) != 1) {
close(sv[1]);
exit(1);
}
close(sv[1]);
exit(0);
}
}
close(sv[1]);
/* Wait for all children to signal ready */
for (i = 0; i < num_children; i++) {
char c;
if (read(sv[0], &c, 1) != 1) {
/* If we fail to read, kill all children and exit */
close(sv[0]);
for (int j = 0; j < num_children; j++)
kill(pids[j], SIGKILL);
for (int j = 0; j < num_children; j++)
waitpid(pids[j], NULL, 0);
ASSERT_TRUE(false);
}
}
/* Paginate through all namespaces using small batch sizes */
req.ns_id = 0;
while (1) {
__u64 batch[5]; /* Small batch size to force pagination */
ssize_t ret;
ret = sys_listns(&req, batch, ARRAY_SIZE(batch), 0);
if (ret < 0) {
if (errno == ENOSYS) {
close(sv[0]);
for (i = 0; i < num_children; i++)
kill(pids[i], SIGKILL);
for (i = 0; i < num_children; i++)
waitpid(pids[i], NULL, 0);
SKIP(return, "listns() not supported");
}
ASSERT_GE(ret, 0);
}
if (ret == 0)
break;
/* Store results */
for (i = 0; i < ret && total_found < 512; i++) {
all_ns_ids[total_found++] = batch[i];
}
/* Update cursor for next batch */
if (ret == ARRAY_SIZE(batch))
req.ns_id = batch[ret - 1];
else
break;
}
TH_LOG("Paginated through %d user namespaces", total_found);
/* Verify no duplicates in pagination */
for (i = 0; i < total_found; i++) {
for (int j = i + 1; j < total_found; j++) {
if (all_ns_ids[i] == all_ns_ids[j]) {
TH_LOG("Found duplicate ns_id: %llu at positions %d and %d",
(unsigned long long)all_ns_ids[i], i, j);
ASSERT_TRUE(false);
}
}
}
/* Signal all children to exit */
for (i = 0; i < num_children; i++) {
char c = 'X';
if (write(sv[0], &c, 1) != 1) {
close(sv[0]);
for (int j = i; j < num_children; j++)
kill(pids[j], SIGKILL);
for (int j = 0; j < num_children; j++)
waitpid(pids[j], NULL, 0);
ASSERT_TRUE(false);
}
}
close(sv[0]);
/* Wait for all children */
for (i = 0; i < num_children; i++) {
int status;
waitpid(pids[i], &status, 0);
}
}
/*
* Test concurrent namespace operations.
* Multiple processes creating, querying, and destroying namespaces concurrently.
*/
TEST(concurrent_namespace_operations)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = 0,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids_before[512], ns_ids_after[512];
ssize_t ret_before, ret_after;
pid_t pids[20];
int num_workers = 20;
int i;
/* Get baseline */
ret_before = sys_listns(&req, ns_ids_before, ARRAY_SIZE(ns_ids_before), 0);
if (ret_before < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret_before, 0);
}
TH_LOG("Baseline: %zd active namespaces", ret_before);
/* Create worker processes that do concurrent operations */
for (i = 0; i < num_workers; i++) {
pids[i] = fork();
ASSERT_GE(pids[i], 0);
if (pids[i] == 0) {
/* Each worker: create namespaces, list them, repeat */
int iterations;
for (iterations = 0; iterations < 10; iterations++) {
int userns_fd;
__u64 temp_ns_ids[100];
ssize_t ret;
/* Create a user namespace */
userns_fd = get_userns_fd(0, getuid(), 1);
if (userns_fd < 0)
continue;
/* List namespaces */
ret = sys_listns(&req, temp_ns_ids, ARRAY_SIZE(temp_ns_ids), 0);
(void)ret;
close(userns_fd);
/* Small delay */
usleep(1000);
}
exit(0);
}
}
/* Wait for all workers */
for (i = 0; i < num_workers; i++) {
int status;
waitpid(pids[i], &status, 0);
ASSERT_TRUE(WIFEXITED(status));
ASSERT_EQ(WEXITSTATUS(status), 0);
}
/* Verify we're back to baseline */
ret_after = sys_listns(&req, ns_ids_after, ARRAY_SIZE(ns_ids_after), 0);
ASSERT_GE(ret_after, 0);
TH_LOG("After concurrent operations: %zd active namespaces", ret_after);
ASSERT_EQ(ret_before, ret_after);
}
/*
* Test namespace churn - continuous creation and destruction.
* Simulates high-churn scenarios like container orchestration.
*/
TEST(namespace_churn)
{
struct ns_id_req req = {
.size = sizeof(req),
.spare = 0,
.ns_id = 0,
.ns_type = CLONE_NEWUSER | CLONE_NEWNET | CLONE_NEWUTS,
.spare2 = 0,
.user_ns_id = 0,
};
__u64 ns_ids_before[512], ns_ids_after[512];
ssize_t ret_before, ret_after;
int cycle;
/* Get baseline */
ret_before = sys_listns(&req, ns_ids_before, ARRAY_SIZE(ns_ids_before), 0);
if (ret_before < 0) {
if (errno == ENOSYS)
SKIP(return, "listns() not supported");
ASSERT_GE(ret_before, 0);
}
TH_LOG("Baseline: %zd active namespaces", ret_before);
/* Simulate churn: batches of namespaces created and destroyed */
for (cycle = 0; cycle < 10; cycle++) {
pid_t batch_pids[10];
int i;
/* Create batch */
for (i = 0; i < 10; i++) {
batch_pids[i] = fork();
ASSERT_GE(batch_pids[i], 0);
if (batch_pids[i] == 0) {
/* Create multiple namespace types */
if (setup_userns() < 0)
exit(1);
if (unshare(CLONE_NEWNET) < 0)
exit(1);
if (unshare(CLONE_NEWUTS) < 0)
exit(1);
/* Keep namespaces alive briefly */
usleep(10000);
exit(0);
}
}
/* Wait for batch to complete */
for (i = 0; i < 10; i++) {
int status;
waitpid(batch_pids[i], &status, 0);
}
}
/* Verify we're back to baseline */
ret_after = sys_listns(&req, ns_ids_after, ARRAY_SIZE(ns_ids_after), 0);
ASSERT_GE(ret_after, 0);
TH_LOG("After 10 churn cycles (100 namespace sets): %zd active namespaces", ret_after);
ASSERT_EQ(ret_before, ret_after);
}
TEST_HARNESS_MAIN
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: GPL-2.0
#include <linux/nsfs.h>
#include <linux/types.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifndef __SELFTESTS_NAMESPACES_WRAPPERS_H__
#define __SELFTESTS_NAMESPACES_WRAPPERS_H__
#ifndef __NR_listns
#if defined __alpha__
#define __NR_listns 580
#elif defined _MIPS_SIM
#if _MIPS_SIM == _MIPS_SIM_ABI32 /* o32 */
#define __NR_listns 4470
#endif
#if _MIPS_SIM == _MIPS_SIM_NABI32 /* n32 */
#define __NR_listns 6470
#endif
#if _MIPS_SIM == _MIPS_SIM_ABI64 /* n64 */
#define __NR_listns 5470
#endif
#else
#define __NR_listns 470
#endif
#endif
static inline int sys_listns(const struct ns_id_req *req, __u64 *ns_ids,
size_t nr_ns_ids, unsigned int flags)
{
return syscall(__NR_listns, req, ns_ids, nr_ns_ids, flags);
}
#endif /* __SELFTESTS_NAMESPACES_WRAPPERS_H__ */