Skip to contentSkip to conversation

mount: add OPEN_TREE_NAMESPACE

PATCH In review Christian Brauner 8 participants 24 messages Dec 29, 2025 – Mar 2

Subsystems (3)
lore
Share & tools
lore

Christian Brauner

author maintainer
#0 lore raw

cover mount: add OPEN_TREE_NAMESPACE

When creating containers the setup usually involves using CLONE_NEWNS via clone3() or unshare(). This copies the caller's complete mount namespace. The runtime will also assemble a new rootfs and then use pivot_root() to switch the old mount tree with the new rootfs. Afterward it will recursively umount the old mount tree thereby getting rid of all mounts.

On a basic system here where the mount table isn't particularly large this still copies about 30 mounts. Copying all of these mounts only to get rid of them later is pretty wasteful.

This is exacerbated if intermediary mount namespaces are used that only exist for a very short amount of time and are immediately destroyed again causing a ton of mounts to be copied and destroyed needlessly.

With a large mount table and a system where thousands or ten-thousands of namespaces are spawned in parallel this quickly becomes a bottleneck increasing contention on the semaphore.

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

The caller can setns() into that mount namespace and perform any additionally setup such as move_mount()ing detached mounts in there.

This allows OPEN_TREE_NAMESPACE to function as a combined unshare(CLONE_NEWNS) and pivot_root().

A caller may for example choose to create an extremely minimal rootfs:

fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

This will create a mount namespace where "wootwoot" has become the rootfs mounted on top of the real rootfs. The caller can now setns() into this new mount namespace and assemble additional mounts.

This also works with user namespaces:

unshare(CLONE_NEWUSER);
fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

which creates a new mount namespace owned by the earlier created user namespace with "wootwoot" as the rootfs mounted on top of the real rootfs.

This will scale a lot better when creating tons of mount namespaces and will allow to get rid of a lot of unnecessary mount and umount cycles. It also allows to create mount namespaces without needing to spawn throwaway helper processes.

---
Christian Brauner (2):
mount: add OPEN_TREE_NAMESPACE selftests/open_tree: add OPEN_TREE_NAMESPACE tests

 fs/internal.h                                      |    1 +
 fs/namespace.c                                     |  155 ++-
 fs/nsfs.c                                          |   13 +
 include/uapi/linux/mount.h                         |    3 +-
 .../selftests/filesystems/open_tree_ns/.gitignore  |    1 +
 .../selftests/filesystems/open_tree_ns/Makefile    |   10 +
 .../filesystems/open_tree_ns/open_tree_ns_test.c   | 1030 ++++++++++++++++++++
 tools/testing/selftests/filesystems/utils.c        |   26 +
 tools/testing/selftests/filesystems/utils.h        |    1 +
 9 files changed, 1223 insertions(+), 17 deletions(-)

---
base-commit: 8f0b4cce4481fb22653697cced8d0d04027cb1e8
change-id: 20251229-work-empty-namespace-352a9c2dfe0a

author maintainer
#1 lore raw

PATCH 1/2 mount: add OPEN_TREE_NAMESPACE

When creating containers the setup usually involves using CLONE_NEWNS via clone3() or unshare(). This copies the caller's complete mount namespace. The runtime will also assemble a new rootfs and then use pivot_root() to switch the old mount tree with the new rootfs. Afterward it will recursively umount the old mount tree thereby getting rid of all mounts.

On a basic system here where the mount table isn't particularly large this still copies about 30 mounts. Copying all of these mounts only to get rid of them later is pretty wasteful.

This is exacerbated if intermediary mount namespaces are used that only exist for a very short amount of time and are immediately destroyed again causing a ton of mounts to be copied and destroyed needlessly.

With a large mount table and a system where thousands or ten-thousands of containers are spawned in parallel this quickly becomes a bottleneck increasing contention on the semaphore.

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

The caller can setns() into that mount namespace and perform any additionally required setup such as move_mount() detached mounts in there.

This allows OPEN_TREE_NAMESPACE to function as a combined unshare(CLONE_NEWNS) and pivot_root().

A caller may for example choose to create an extremely minimal rootfs:

fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

This will create a mount namespace where "wootwoot" has become the rootfs mounted on top of the real rootfs. The caller can now setns() into this new mount namespace and assemble additional mounts.

This also works with user namespaces:

unshare(CLONE_NEWUSER);
fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

which creates a new mount namespace owned by the earlier created user namespace with "wootwoot" as the rootfs mounted on top of the real rootfs.

---
 fs/internal.h              |   1 +
 fs/namespace.c             | 155 ++++++++++++++++++++++++++++++++++++++++-----
 fs/nsfs.c                  |  13 ++++
 include/uapi/linux/mount.h |   3 +-
 4 files changed, 155 insertions(+), 17 deletions(-)
fs/internal.h +1 -0
index ab638d41ab81..b5aad5265e0e 100644
@@ -247,6 +247,7 @@ extern void mnt_pin_kill(struct mount *m);
  */
 extern const struct dentry_operations ns_dentry_operations;
 int open_namespace(struct ns_common *ns);
+struct file *open_namespace_file(struct ns_common *ns);
 
 /*
  * fs/stat.c:
fs/namespace.c +139 -16

238 lines not on this page · raw message

fs/nsfs.c +13 -0
index bf27d5da91f1..db91de208645 100644
@@ -99,6 +99,19 @@ int ns_get_path(struct path *path, struct task_struct *task,
 	return ns_get_path_cb(path, ns_get_path_task, &args);
 }
 
+struct file *open_namespace_file(struct ns_common *ns)
+{
+	struct path path __free(path_put) = {};
+	int err;
+
+	/* call first to consume reference */
+	err = path_from_stashed(&ns->stashed, nsfs_mnt, ns, &path);
+	if (err < 0)
+		return ERR_PTR(err);
+
+	return dentry_open(&path, O_RDONLY, current_cred());
+}
+
 /**
  * open_namespace - open a namespace
  * @ns: the namespace to open
include/uapi/linux/mount.h +2 -1
index 5d3f8c9e3a62..acbc22241c9c 100644
@@ -61,7 +61,8 @@
 /*
  * open_tree() flags.
  */
-#define OPEN_TREE_CLONE		1		/* Clone the target tree and attach the clone */
+#define OPEN_TREE_CLONE		(1 << 0)	/* Clone the target tree and attach the clone */
+#define OPEN_TREE_NAMESPACE	(1 << 1)	/* Clone the target tree into a new mount namespace */
 #define OPEN_TREE_CLOEXEC	O_CLOEXEC	/* Close the file on execve() */
 
 /*
Signature · 1 line
2.47.3
author maintainer
#11 lore raw

PATCH 2/2 selftests/open_tree: add OPEN_TREE_NAMESPACE tests

In reply to Christian Brauner

Add tests for OPEN_TREE_NAMESPACE.

---
 .../selftests/filesystems/open_tree_ns/.gitignore  |    1 +
 .../selftests/filesystems/open_tree_ns/Makefile    |   10 +
 .../filesystems/open_tree_ns/open_tree_ns_test.c   | 1030 ++++++++++++++++++++
 tools/testing/selftests/filesystems/utils.c        |   26 +
 tools/testing/selftests/filesystems/utils.h        |    1 +
 5 files changed, 1068 insertions(+)
tools/testing/selftests/filesystems/open_tree_ns/.gitignore new file +1 -0
new file mode 100644
index 000000000000..fb12b93fbcaa
@@ -0,0 +1 @@
+open_tree_ns_test
tools/testing/selftests/filesystems/open_tree_ns/Makefile new file +10 -0
new file mode 100644
index 000000000000..73c03c4a7ef6
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: GPL-2.0
+TEST_GEN_PROGS := open_tree_ns_test
+
+CFLAGS := -Wall -Werror -g $(KHDR_INCLUDES)
+LDLIBS := -lcap
+
+include ../../lib.mk
+
+$(OUTPUT)/open_tree_ns_test: open_tree_ns_test.c ../utils.c
+	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
tools/testing/selftests/filesystems/open_tree_ns/open_tree_ns_test.c new file +1030 -0

1,030 lines not on this page · raw message

tools/testing/selftests/filesystems/utils.c +26 -0
index c9dd5412b37b..d6f26f849053 100644
@@ -515,6 +515,32 @@ int setup_userns(void)
 	return 0;
 }
 
+int enter_userns(void)
+{
+	int ret;
+	char buf[32];
+	uid_t uid = getuid();
+	gid_t gid = getgid();
+
+	ret = unshare(CLONE_NEWUSER);
+	if (ret)
+		return ret;
+
+	sprintf(buf, "0 %d 1", uid);
+	ret = write_file("/proc/self/uid_map", buf);
+	if (ret)
+		return ret;
+	ret = write_file("/proc/self/setgroups", "deny");
+	if (ret)
+		return ret;
+	sprintf(buf, "0 %d 1", gid);
+	ret = write_file("/proc/self/gid_map", buf);
+	if (ret)
+		return ret;
+
+	return 0;
+}
+
 /* caps_down - lower all effective caps */
 int caps_down(void)
 {
tools/testing/selftests/filesystems/utils.h +1 -0
index 70f7ccc607f4..0bccfed666a9 100644
@@ -28,6 +28,7 @@ extern int cap_down(cap_value_t down);
 
 extern bool switch_ids(uid_t uid, gid_t gid);
 extern int setup_userns(void);
+extern int enter_userns(void);
 
 static inline bool switch_userns(int fd, uid_t uid, gid_t gid, bool drop_caps)
 {
Signature · 1 line
2.47.3
#12 lore raw
In reply to Christian Brauner
Quoted 70 lines · Christian Brauner

When creating containers the setup usually involves using CLONE_NEWNS via clone3() or unshare(). This copies the caller's complete mount namespace. The runtime will also assemble a new rootfs and then use pivot_root() to switch the old mount tree with the new rootfs. Afterward it will recursively umount the old mount tree thereby getting rid of all mounts.

On a basic system here where the mount table isn't particularly large this still copies about 30 mounts. Copying all of these mounts only to get rid of them later is pretty wasteful.

This is exacerbated if intermediary mount namespaces are used that only exist for a very short amount of time and are immediately destroyed again causing a ton of mounts to be copied and destroyed needlessly.

With a large mount table and a system where thousands or ten-thousands of namespaces are spawned in parallel this quickly becomes a bottleneck increasing contention on the semaphore.

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

The caller can setns() into that mount namespace and perform any additionally setup such as move_mount()ing detached mounts in there.

This allows OPEN_TREE_NAMESPACE to function as a combined unshare(CLONE_NEWNS) and pivot_root().

A caller may for example choose to create an extremely minimal rootfs:

fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

This will create a mount namespace where "wootwoot" has become the rootfs mounted on top of the real rootfs. The caller can now setns() into this new mount namespace and assemble additional mounts.

This also works with user namespaces:

unshare(CLONE_NEWUSER);
fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

which creates a new mount namespace owned by the earlier created user namespace with "wootwoot" as the rootfs mounted on top of the real rootfs.

This will scale a lot better when creating tons of mount namespaces and will allow to get rid of a lot of unnecessary mount and umount cycles. It also allows to create mount namespaces without needing to spawn throwaway helper processes.

---
Christian Brauner (2):
mount: add OPEN_TREE_NAMESPACE selftests/open_tree: add OPEN_TREE_NAMESPACE tests

 fs/internal.h                                      |    1 +
 fs/namespace.c                                     |  155 ++-
 fs/nsfs.c                                          |   13 +
 include/uapi/linux/mount.h                         |    3 +-
 .../selftests/filesystems/open_tree_ns/.gitignore  |    1 +
 .../selftests/filesystems/open_tree_ns/Makefile    |   10 +
 .../filesystems/open_tree_ns/open_tree_ns_test.c   | 1030 ++++++++++++++++++++
 tools/testing/selftests/filesystems/utils.c        |   26 +
 tools/testing/selftests/filesystems/utils.h        |    1 +
 9 files changed, 1223 insertions(+), 17 deletions(-)
Quoted 3 lines

---
base-commit: 8f0b4cce4481fb22653697cced8d0d04027cb1e8
change-id: 20251229-work-empty-namespace-352a9c2dfe0a

Thanks Christian,

This looks really cool. FWIW, I had a discussion at LPC with Aleksa and Christian a few weeks ago about the performance problems we were seeing with spawning a lot of containers in parallel. Cloning a mount namespace is rather expensive and involves global locks. Hopefully this would help reduce the contention for them.

I'm on holiday until next week, but I'll plan to play with this when I get back, and see how it performs vs. the traditional unshare()/pivot_root().

Cheers!

Signature · 1 line
Jeff Layton <[email protected]>
Reviewed-by Tested-by on the v1 series
#13 lore raw
In reply to Christian Brauner
Quoted 70 lines · Christian Brauner

When creating containers the setup usually involves using CLONE_NEWNS via clone3() or unshare(). This copies the caller's complete mount namespace. The runtime will also assemble a new rootfs and then use pivot_root() to switch the old mount tree with the new rootfs. Afterward it will recursively umount the old mount tree thereby getting rid of all mounts.

On a basic system here where the mount table isn't particularly large this still copies about 30 mounts. Copying all of these mounts only to get rid of them later is pretty wasteful.

This is exacerbated if intermediary mount namespaces are used that only exist for a very short amount of time and are immediately destroyed again causing a ton of mounts to be copied and destroyed needlessly.

With a large mount table and a system where thousands or ten-thousands of namespaces are spawned in parallel this quickly becomes a bottleneck increasing contention on the semaphore.

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

The caller can setns() into that mount namespace and perform any additionally setup such as move_mount()ing detached mounts in there.

This allows OPEN_TREE_NAMESPACE to function as a combined unshare(CLONE_NEWNS) and pivot_root().

A caller may for example choose to create an extremely minimal rootfs:

fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

This will create a mount namespace where "wootwoot" has become the rootfs mounted on top of the real rootfs. The caller can now setns() into this new mount namespace and assemble additional mounts.

This also works with user namespaces:

unshare(CLONE_NEWUSER);
fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

which creates a new mount namespace owned by the earlier created user namespace with "wootwoot" as the rootfs mounted on top of the real rootfs.

This will scale a lot better when creating tons of mount namespaces and will allow to get rid of a lot of unnecessary mount and umount cycles. It also allows to create mount namespaces without needing to spawn throwaway helper processes.

---
Christian Brauner (2):
mount: add OPEN_TREE_NAMESPACE selftests/open_tree: add OPEN_TREE_NAMESPACE tests

 fs/internal.h                                      |    1 +
 fs/namespace.c                                     |  155 ++-
 fs/nsfs.c                                          |   13 +
 include/uapi/linux/mount.h                         |    3 +-
 .../selftests/filesystems/open_tree_ns/.gitignore  |    1 +
 .../selftests/filesystems/open_tree_ns/Makefile    |   10 +
 .../filesystems/open_tree_ns/open_tree_ns_test.c   | 1030 ++++++++++++++++++++
 tools/testing/selftests/filesystems/utils.c        |   26 +
 tools/testing/selftests/filesystems/utils.h        |    1 +
 9 files changed, 1223 insertions(+), 17 deletions(-)
Quoted 3 lines

---
base-commit: 8f0b4cce4481fb22653697cced8d0d04027cb1e8
change-id: 20251229-work-empty-namespace-352a9c2dfe0a

I sat down today and rolled the attached program. It's a nonsensical test that just tries to fork new tasks that then spawn new mount namespaces and switch into them as quickly as possible.

Assuming that I've done this correctly, this gives me rough numbers from a test host that I checked out inside Meta:

With the older pivot_root() based method, I can create about 73k "containers" in 60s. With the newer open_tree() method, I can create about 109k in the same time. So it seems like the new method is roughly 40% faster than the older scheme (and a lot less syscalls too).

Note that the run_pivot() routine in the reproducer is based on a strace of an earlier reproducer. That one used minijail0 to create the containers. It's possible that there are more efficient ways to do what it's doing with the existing APIs. It seems to do some weird stuff too (e.g. setting everything to MS_PRIVATE twice under the old root). Spawning a real container might have other bottlenecks too.

Still, this extension to open_tree() seems like a good idea overall, and gets rid of a lot of useless work that we currently do when spawning a container. The only real downside that I can see is that container orchestrators will need changes to use the new method.

You can add:

#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <sched.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
#include <fcntl.h>
#include <getopt.h>
#include <sys/mount.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <time.h>
#include <stdbool.h>

#define CONCURRENCY 88
#define DURATION 60
#define ROOTDIR "/var/empty"

static uint64_t total_containers;
static bool opentree;

static void run_pivot()

{
	int ret, oldfd, newfd;

	ret = unshare(CLONE_NEWNS);
	if (ret) {
		perror("unshare");
		exit(1);
	}

	ret = mount(NULL, "/", NULL, MS_REC|MS_PRIVATE, NULL);
	if (ret) {
		perror("mount");
		exit(1);
	}

	oldfd = openat(AT_FDCWD, "/", O_RDONLY|O_CLOEXEC|O_DIRECTORY);
	if (oldfd < 0) {
		perror("openat");
		exit(1);
	}

	newfd = openat(AT_FDCWD, ROOTDIR, O_RDONLY|O_CLOEXEC|O_DIRECTORY);
	if (newfd < 0) {
		perror("openat");
		exit(1);
	}

	ret = mount(ROOTDIR, ROOTDIR, NULL, MS_BIND|MS_REC, NULL);
	if (ret) {
		perror("mount");
		exit(1);
	}

	ret = chdir(ROOTDIR);
	if (ret) {
		perror("chdir");
		exit(1);
	}

	ret = syscall(SYS_pivot_root, ".", ".");
	if (ret) {
		perror("pivot_root");
		exit(1);
	}

	ret = fchdir(oldfd);
	if (ret) {
		perror("fchdir");
		exit(1);
	}

	ret = mount(NULL, ".", NULL, MS_REC|MS_PRIVATE, NULL);
	if (ret) {
		perror("mount");
		exit(1);
	}

	ret = umount2(".", MNT_DETACH);
	if (ret) {
		perror("umount");
		exit(1);
	}

	ret = fchdir(newfd);
	if (ret) {
		perror("fchdir");
		exit(1);
	}

	close(oldfd);
	close(newfd);
}

static void run_opentree()

{
	int fd, ret;

	// 2 == OPEN_TREE_NAMESPACE
	fd = syscall(SYS_open_tree, AT_FDCWD, ROOTDIR, 2);
	if (fd < 0) {
		perror("open_tree");
		exit(1);
	}

	ret = setns(fd, CLONE_NEWNS);
	if (ret) {
		perror("setns");
		exit(1);
	}

	close(fd);
}

static void *run_container(void *arg)

{
	pid_t pid;

	for (;;) {
		pid = fork();
		if (pid == 0) {
			if (opentree)
				run_opentree();
			else
				run_pivot();
			break;
		} else if (pid > 0) {
			waitpid(pid, NULL, 0);
			__atomic_add_fetch(&total_containers, 1, __ATOMIC_RELAXED);
		} else {
			perror("fork");
			exit(1);
		}
	}

	return NULL;
}

int main(int argc, char **argv)

{
	int i, opt;
	int concurrency = CONCURRENCY;
	int duration = DURATION;
	time_t start, now;

	while ((opt = getopt(argc, argv, "c:d:o")) != -1) {
		switch (opt) {
		case 'c':
			concurrency = atoi(optarg);
			break;
		case 'd':
			duration = atoi(optarg);
			break;
		case 'o':
			opentree = true;
			break;
		}
	}

	for (i = 0; i < concurrency; ++i) {
		pthread_t tid;
		int ret;

		ret = pthread_create(&tid, NULL, run_container, NULL);
		if (ret != 0) {
			fprintf(stderr, "pthread_create failed! %d\n", ret);
			exit(1);
		}
	}


	start = time(NULL);
	while ((now - start) < duration) {
		uint64_t val;

		__atomic_load(&total_containers, &val, __ATOMIC_RELAXED);
		printf("Total containers: %lu\n", val);
		sleep(2);
		now = time(NULL);
	}
}
author maintainer
#14 lore raw
Quoted 99 lines · Jeff Layton
Quoted 70 lines · Christian Brauner

When creating containers the setup usually involves using CLONE_NEWNS via clone3() or unshare(). This copies the caller's complete mount namespace. The runtime will also assemble a new rootfs and then use pivot_root() to switch the old mount tree with the new rootfs. Afterward it will recursively umount the old mount tree thereby getting rid of all mounts.

On a basic system here where the mount table isn't particularly large this still copies about 30 mounts. Copying all of these mounts only to get rid of them later is pretty wasteful.

This is exacerbated if intermediary mount namespaces are used that only exist for a very short amount of time and are immediately destroyed again causing a ton of mounts to be copied and destroyed needlessly.

With a large mount table and a system where thousands or ten-thousands of namespaces are spawned in parallel this quickly becomes a bottleneck increasing contention on the semaphore.

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

The caller can setns() into that mount namespace and perform any additionally setup such as move_mount()ing detached mounts in there.

This allows OPEN_TREE_NAMESPACE to function as a combined unshare(CLONE_NEWNS) and pivot_root().

A caller may for example choose to create an extremely minimal rootfs:

fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

This will create a mount namespace where "wootwoot" has become the rootfs mounted on top of the real rootfs. The caller can now setns() into this new mount namespace and assemble additional mounts.

This also works with user namespaces:

unshare(CLONE_NEWUSER);
fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

which creates a new mount namespace owned by the earlier created user namespace with "wootwoot" as the rootfs mounted on top of the real rootfs.

This will scale a lot better when creating tons of mount namespaces and will allow to get rid of a lot of unnecessary mount and umount cycles. It also allows to create mount namespaces without needing to spawn throwaway helper processes.

---
Christian Brauner (2):
mount: add OPEN_TREE_NAMESPACE selftests/open_tree: add OPEN_TREE_NAMESPACE tests

 fs/internal.h                                      |    1 +
 fs/namespace.c                                     |  155 ++-
 fs/nsfs.c                                          |   13 +
 include/uapi/linux/mount.h                         |    3 +-
 .../selftests/filesystems/open_tree_ns/.gitignore  |    1 +
 .../selftests/filesystems/open_tree_ns/Makefile    |   10 +
 .../filesystems/open_tree_ns/open_tree_ns_test.c   | 1030 ++++++++++++++++++++
 tools/testing/selftests/filesystems/utils.c        |   26 +
 tools/testing/selftests/filesystems/utils.h        |    1 +
 9 files changed, 1223 insertions(+), 17 deletions(-)
Quoted 3 lines

---
base-commit: 8f0b4cce4481fb22653697cced8d0d04027cb1e8
change-id: 20251229-work-empty-namespace-352a9c2dfe0a

I sat down today and rolled the attached program. It's a nonsensical test that just tries to fork new tasks that then spawn new mount namespaces and switch into them as quickly as possible.

Assuming that I've done this correctly, this gives me rough numbers from a test host that I checked out inside Meta:

With the older pivot_root() based method, I can create about 73k "containers" in 60s. With the newer open_tree() method, I can create about 109k in the same time. So it seems like the new method is roughly 40% faster than the older scheme (and a lot less syscalls too).

Note that the run_pivot() routine in the reproducer is based on a strace of an earlier reproducer. That one used minijail0 to create the containers. It's possible that there are more efficient ways to do what it's doing with the existing APIs. It seems to do some weird stuff too (e.g. setting everything to MS_PRIVATE twice under the old root). Spawning a real container might have other bottlenecks too.

Still, this extension to open_tree() seems like a good idea overall, and gets rid of a lot of useless work that we currently do when spawning a container. The only real downside that I can see is that container orchestrators will need changes to use the new method.

Quoted 4 lines

You can add:

Thank you for testing this!
The basic test looks correct. The pivot_root(".", ".") part could be simplified a tiny bit but that shouldn't matter.

Fwiw, I think swapping out the rootfs isn't something that can always be avoided in the manner I illustrated. Some users want to spawn an empty mount namespace (e.g., just a tmpfs on top of the real rootfs) and then assemble a detached mount tree and swap the two mounts.

But I have a better way of doing this than what pivot_root() currently does. The main problem with pivot_root() is not just that it moves the old rootfs to any other location on the new rootfs it also takes the tasklist read lock and walks all processes on the system trying to find any process that uses the old rootfs as its fs root or its pwd and then rechroots and repwds all of these processes into the new rootfs.

But for 90% of the use-cases (containers) that is not needed. When the container's mount namespace and rootfs are setup the task creating that container is the only task that is using the old rootfs and that task could very well just rechroot itself after it unmounted the old rootfs.

So in essence pivot_root() holds tasklist lock and walks all tasks on the systems for no reason. If the user has a beefy and busy machine with lots of processes coming and going each pivot_root() penalizes the whole system.

I have a patchset that allows MOVE_MOUNT_BENEATH to work with the rootfs (and an extension that adds MOVE_MOUNT_PIVOT_ROOT which optionally does the rechrooting in case someone really needs to rechrooting.).

With MOVE_MOUNT_BENEATH working with the real rootfs that effectively means one can stuff a new rootfs under the current rootfs, unmount the old rootfs and chroot into the new rootfs and then be done.

That completely avoids the tasklist locking and has other benefits.

* You get the pivot_root(".", ".") trick for free.

* MOVE_MOUNT_BENEATH works with detached mounts meaning you can assemble your whole rootfs in a detached mount tree (since detached mounts can now be mounted onto other detached mounts) and then swap the old rootfs with your new rootfs.

* MOVE_MOUNT_BENEATH works with mount propagation. (Which means you could live-update the rootfs for all services. It would be a bit more complicated to actually make this work nicely but it would work.)

I just had a few thoughts in this area I wanted to note.

Reviewed-by on v1 1/2
#2 lore raw
In reply to Christian Brauner
Quoted 41 lines · Christian Brauner

When creating containers the setup usually involves using CLONE_NEWNS via clone3() or unshare(). This copies the caller's complete mount namespace. The runtime will also assemble a new rootfs and then use pivot_root() to switch the old mount tree with the new rootfs. Afterward it will recursively umount the old mount tree thereby getting rid of all mounts.

On a basic system here where the mount table isn't particularly large this still copies about 30 mounts. Copying all of these mounts only to get rid of them later is pretty wasteful.

This is exacerbated if intermediary mount namespaces are used that only exist for a very short amount of time and are immediately destroyed again causing a ton of mounts to be copied and destroyed needlessly.

With a large mount table and a system where thousands or ten-thousands of containers are spawned in parallel this quickly becomes a bottleneck increasing contention on the semaphore.

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

The caller can setns() into that mount namespace and perform any additionally required setup such as move_mount() detached mounts in there.

This allows OPEN_TREE_NAMESPACE to function as a combined unshare(CLONE_NEWNS) and pivot_root().

A caller may for example choose to create an extremely minimal rootfs:

fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

This will create a mount namespace where "wootwoot" has become the rootfs mounted on top of the real rootfs. The caller can now setns() into this new mount namespace and assemble additional mounts.

Quoted 8 lines

This also works with user namespaces:

unshare(CLONE_NEWUSER);
fd_mntns = open_tree(-EBADF, "/var/lib/containers/wootwoot", OPEN_TREE_NAMESPACE);

which creates a new mount namespace owned by the earlier created user namespace with "wootwoot" as the rootfs mounted on top of the real rootfs.

I think there are a few other things I would really like (with my runc hat on), such as being able to move_mount(2) into this new kind of OPEN_TREE_NAMESPACE handle.

However, on the whole I think this seems very reasonable and is much simpler than I anticipated when we talked about this at LPC. I've just taken a general look but feel free to take my

and also maybe a

If you feel it's appropriate, since we came up with this together at LPC? ;)

Quoted 53 lines
---
 fs/internal.h              |   1 +
 fs/namespace.c             | 155 ++++++++++++++++++++++++++++++++++++++++-----
 fs/nsfs.c                  |  13 ++++
 include/uapi/linux/mount.h |   3 +-
 4 files changed, 155 insertions(+), 17 deletions(-)
fs/internal.h +1 -0
index ab638d41ab81..b5aad5265e0e 100644
@@ -247,6 +247,7 @@ extern void mnt_pin_kill(struct mount *m);
  */
 extern const struct dentry_operations ns_dentry_operations;
 int open_namespace(struct ns_common *ns);
+struct file *open_namespace_file(struct ns_common *ns);
 
 /*
  * fs/stat.c:
fs/namespace.c +7 -2
index c58674a20cad..fd9698671c70 100644
@@ -2796,6 +2796,9 @@ static inline void unlock_mount(struct pinned_mountpoint *m)
 		__unlock_mount(m);
 }
 
+static void lock_mount_exact(const struct path *path,
+			     struct pinned_mountpoint *mp);
+
 #define LOCK_MOUNT_MAYBE_BENEATH(mp, path, beneath) \
 	struct pinned_mountpoint mp __cleanup(unlock_mount) = {}; \
 	do_lock_mount((path), &mp, (beneath))
@@ -2946,10 +2949,11 @@ static inline bool may_copy_tree(const struct path *path)
 	return check_anonymous_mnt(mnt);
 }
 
-
-static struct mount *__do_loopback(const struct path *old_path, int recurse)
+static struct mount *__do_loopback(const struct path *old_path,
+				   unsigned int flags, unsigned int copy_flags)
 {
 	struct mount *old = real_mount(old_path->mnt);
+	bool recurse = flags & AT_RECURSIVE;
 
 	if (IS_MNT_UNBINDABLE(old))
 		return ERR_PTR(-EINVAL);
@@ -2960,10 +2964,22 @@ static struct mount *__do_loopback(const struct path *old_path, int recurse)
 	if (!recurse && __has_locked_children(old, old_path->dentry))
 		return ERR_PTR(-EINVAL);
 
+	/*

fs/namespace.c static struct mount *__do_loopback(const struct path *old_path, int recurse) · line 2977

Quoted 10 lines
fs/namespace.c +10 -0
+	 * When creating a new mount namespace we don't want to copy over
+	 * mounts of mount namespaces to avoid the risk of cycles and also to
+	 * minimize the default complex interdependencies between mount
+	 * namespaces.
+	 *
+	 * We could ofc just check whether all mount namespace files aren't
+	 * creating cycles but really let's keep this simple.
+	 */
+	if (!(flags & OPEN_TREE_NAMESPACE))
+		copy_flags |= CL_COPY_MNT_NS_FILE;

I kind of think this is a somewhat theoretical issue but I don't think we'll be bitten by it. My gut feeling is that I'd prefer this to be an OPEN_TREE_* flag that you have to set (so we can support this in the future) but that's kinda ugly too...

Quoted 252 lines
fs/namespace.c +122 -14
+
 	if (recurse)
-		return copy_tree(old, old_path->dentry, CL_COPY_MNT_NS_FILE);
-	else
-		return clone_mnt(old, old_path->dentry, 0);
+		return copy_tree(old, old_path->dentry, copy_flags);
+
+	return clone_mnt(old, old_path->dentry, copy_flags);
 }
 
 /*
@@ -2974,7 +2990,9 @@ static int do_loopback(const struct path *path, const char *old_name,
 {
 	struct path old_path __free(path_put) = {};
 	struct mount *mnt = NULL;
+	unsigned int flags = recurse ? AT_RECURSIVE : 0;
 	int err;
+
 	if (!old_name || !*old_name)
 		return -EINVAL;
 	err = kern_path(old_name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &old_path);
@@ -2991,7 +3009,7 @@ static int do_loopback(const struct path *path, const char *old_name,
 	if (!check_mnt(mp.parent))
 		return -EINVAL;
 
-	mnt = __do_loopback(&old_path, recurse);
+	mnt = __do_loopback(&old_path, flags, 0);
 	if (IS_ERR(mnt))
 		return PTR_ERR(mnt);
 
@@ -3004,7 +3022,7 @@ static int do_loopback(const struct path *path, const char *old_name,
 	return err;
 }
 
-static struct mnt_namespace *get_detached_copy(const struct path *path, bool recursive)
+static struct mnt_namespace *get_detached_copy(const struct path *path, unsigned int flags)
 {
 	struct mnt_namespace *ns, *mnt_ns = current->nsproxy->mnt_ns, *src_mnt_ns;
 	struct user_namespace *user_ns = mnt_ns->user_ns;
@@ -3029,7 +3047,7 @@ static struct mnt_namespace *get_detached_copy(const struct path *path, bool rec
 			ns->seq_origin = src_mnt_ns->ns.ns_id;
 	}
 
-	mnt = __do_loopback(path, recursive);
+	mnt = __do_loopback(path, flags, 0);
 	if (IS_ERR(mnt)) {
 		emptied_ns = ns;
 		return ERR_CAST(mnt);
@@ -3043,9 +3061,9 @@ static struct mnt_namespace *get_detached_copy(const struct path *path, bool rec
 	return ns;
 }
 
-static struct file *open_detached_copy(struct path *path, bool recursive)
+static struct file *open_detached_copy(struct path *path, unsigned int flags)
 {
-	struct mnt_namespace *ns = get_detached_copy(path, recursive);
+	struct mnt_namespace *ns = get_detached_copy(path, flags);
 	struct file *file;
 
 	if (IS_ERR(ns))
@@ -3061,21 +3079,114 @@ static struct file *open_detached_copy(struct path *path, bool recursive)
 	return file;
 }
 
+DEFINE_FREE(put_empty_mnt_ns, struct mnt_namespace *,
+	    if (!IS_ERR_OR_NULL(_T)) free_mnt_ns(_T))
+
+static struct file *open_new_namespace(struct path *path, unsigned int flags)
+{
+	struct mnt_namespace *new_ns __free(put_empty_mnt_ns) = NULL;
+	struct path to_path __free(path_put) = {};
+	struct mnt_namespace *ns = current->nsproxy->mnt_ns;
+	struct user_namespace *user_ns = current_user_ns();
+	struct mount *new_ns_root;
+	struct mount *mnt;
+	struct ns_common *new_ns_common;
+	unsigned int copy_flags = 0;
+	bool locked = false;
+
+	if (user_ns != ns->user_ns)
+		copy_flags |= CL_SLAVE;
+
+	new_ns = alloc_mnt_ns(user_ns, false);
+	if (IS_ERR(new_ns))
+		return ERR_CAST(new_ns);
+
+	scoped_guard(namespace_excl) {
+		new_ns_root = clone_mnt(ns->root, ns->root->mnt.mnt_root, copy_flags);
+		if (IS_ERR(new_ns_root))
+			return ERR_CAST(new_ns_root);
+
+		/*
+		 * If the real rootfs had a locked mount on top of it somewhere
+		 * in the stack, lock the new mount tree as well so it can't be
+		 * exposed.
+		 */
+		mnt = ns->root;
+		while (mnt->overmount) {
+			mnt = mnt->overmount;
+			if (mnt->mnt.mnt_flags & MNT_LOCKED)
+				locked = true;
+		}
+	}
+
+	/*
+	 * We dropped the namespace semaphore so we can actually lock
+	 * the copy for mounting. The copied mount isn't attached to any
+	 * mount namespace and it is thus excluded from any propagation.
+	 * So realistically we're isolated and the mount can't be
+	 * overmounted.
+	 */
+
+	/* Borrow the reference from clone_mnt(). */
+	to_path.mnt = &new_ns_root->mnt;
+	to_path.dentry = dget(new_ns_root->mnt.mnt_root);
+
+	/* Now lock for actual mounting. */
+	LOCK_MOUNT_EXACT(mp, &to_path);
+	if (unlikely(IS_ERR(mp.parent)))
+		return ERR_CAST(mp.parent);
+
+	/*
+	 * We don't emulate unshare()ing a mount namespace. We stick to the
+	 * restrictions of creating detached bind-mounts. It has a lot
+	 * saner and simpler semantics.
+	 */
+	mnt = __do_loopback(path, flags, copy_flags);
+	if (IS_ERR(mnt))
+		return ERR_CAST(mnt);
+
+	scoped_guard(mount_writer) {
+		if (locked)
+			mnt->mnt.mnt_flags |= MNT_LOCKED;
+		/*
+		 * Now mount the detached tree on top of the copy of the
+		 * real rootfs we created.
+		 */
+		attach_mnt(mnt, new_ns_root, mp.mp);
+		if (user_ns != ns->user_ns)
+			lock_mnt_tree(new_ns_root);
+	}
+
+	/* Add all mounts to the new namespace. */
+	for (struct mount *p = new_ns_root; p; p = next_mnt(p, new_ns_root)) {
+		mnt_add_to_ns(new_ns, p);
+		new_ns->nr_mounts++;
+	}
+
+	new_ns->root = real_mount(no_free_ptr(to_path.mnt));
+	ns_tree_add_raw(new_ns);
+	new_ns_common = to_ns_common(no_free_ptr(new_ns));
+	return open_namespace_file(new_ns_common);
+}
+
 static struct file *vfs_open_tree(int dfd, const char __user *filename, unsigned int flags)
 {
 	int ret;
 	struct path path __free(path_put) = {};
 	int lookup_flags = LOOKUP_AUTOMOUNT | LOOKUP_FOLLOW;
-	bool detached = flags & OPEN_TREE_CLONE;
 
 	BUILD_BUG_ON(OPEN_TREE_CLOEXEC != O_CLOEXEC);
 
 	if (flags & ~(AT_EMPTY_PATH | AT_NO_AUTOMOUNT | AT_RECURSIVE |
 		      AT_SYMLINK_NOFOLLOW | OPEN_TREE_CLONE |
-		      OPEN_TREE_CLOEXEC))
+		      OPEN_TREE_CLOEXEC | OPEN_TREE_NAMESPACE))
 		return ERR_PTR(-EINVAL);
 
-	if ((flags & (AT_RECURSIVE | OPEN_TREE_CLONE)) == AT_RECURSIVE)
+	if ((flags & (AT_RECURSIVE | OPEN_TREE_CLONE | OPEN_TREE_NAMESPACE)) ==
+	    AT_RECURSIVE)
+		return ERR_PTR(-EINVAL);
+
+	if (hweight32(flags & (OPEN_TREE_CLONE | OPEN_TREE_NAMESPACE)) > 1)
 		return ERR_PTR(-EINVAL);
 
 	if (flags & AT_NO_AUTOMOUNT)
@@ -3085,15 +3196,27 @@ static struct file *vfs_open_tree(int dfd, const char __user *filename, unsigned
 	if (flags & AT_EMPTY_PATH)
 		lookup_flags |= LOOKUP_EMPTY;
 
-	if (detached && !may_mount())
+	/*
+	 * If we create a new mount namespace with the cloned mount tree we
+	 * just care about being privileged over our current user namespace.
+	 * The new mount namespace will be owned by it.
+	 */
+	if ((flags & OPEN_TREE_NAMESPACE) &&
+	    !ns_capable(current_user_ns(), CAP_SYS_ADMIN))
+		return ERR_PTR(-EPERM);
+
+	if ((flags & OPEN_TREE_CLONE) && !may_mount())
 		return ERR_PTR(-EPERM);
 
 	ret = user_path_at(dfd, filename, lookup_flags, &path);
 	if (unlikely(ret))
 		return ERR_PTR(ret);
 
-	if (detached)
-		return open_detached_copy(&path, flags & AT_RECURSIVE);
+	if (flags & OPEN_TREE_NAMESPACE)
+		return open_new_namespace(&path, flags);
+
+	if (flags & OPEN_TREE_CLONE)
+		return open_detached_copy(&path, flags);
 
 	return dentry_open(&path, O_PATH, current_cred());
 }
fs/nsfs.c +13 -0
index bf27d5da91f1..db91de208645 100644
@@ -99,6 +99,19 @@ int ns_get_path(struct path *path, struct task_struct *task,
 	return ns_get_path_cb(path, ns_get_path_task, &args);
 }
 
+struct file *open_namespace_file(struct ns_common *ns)
+{
+	struct path path __free(path_put) = {};
+	int err;
+
+	/* call first to consume reference */
+	err = path_from_stashed(&ns->stashed, nsfs_mnt, ns, &path);
+	if (err < 0)
+		return ERR_PTR(err);
+
+	return dentry_open(&path, O_RDONLY, current_cred());
+}
+
 /**
  * open_namespace - open a namespace
  * @ns: the namespace to open
include/uapi/linux/mount.h +2 -1
index 5d3f8c9e3a62..acbc22241c9c 100644
@@ -61,7 +61,8 @@
 /*
  * open_tree() flags.
  */
-#define OPEN_TREE_CLONE		1		/* Clone the target tree and attach the clone */
+#define OPEN_TREE_CLONE		(1 << 0)	/* Clone the target tree and attach the clone */
+#define OPEN_TREE_NAMESPACE	(1 << 1)	/* Clone the target tree into a new mount namespace */
 #define OPEN_TREE_CLOEXEC	O_CLOEXEC	/* Close the file on execve() */
 
 /*
Signature · 2 lines
-- 
2.47.3
Signature · 2 lines
Aleksa Sarai
https://www.cyphar.com/
author maintainer
#3 lore raw
Quoted 3 lines

I think there are a few other things I would really like (with my runc hat on), such as being able to move_mount(2) into this new kind of OPEN_TREE_NAMESPACE handle.

As you know I have outlined multiple ways how we can do it on-list and then again in Tokyo. There's a ToDo item I'm going to get to soon. Around end of November someone asked about related changes again. I have the beginnings for that in a branch. I just need to get to it but I need to catch up with the list first...

Quoted 4 lines

However, on the whole I think this seems very reasonable and is much simpler than I anticipated when we talked about this at LPC. I've just taken a general look but feel free to take my

Quoted 8 lines

and also maybe a

If you feel it's appropriate, since we came up with this together at LPC? ;)

Eh, well, this rubs me the wrong way a little bit, I have to say. The idea was basically just "what if we had an empty mount namespace" which doesn't really work without other work I mentioned there. So to me this was basically a fragment thrown around that I then turned into the open_tree() idea that I explained later and which is rather different. So adding a "Suggested-by" for that kinda makes it sound like I was the code monkey which I very much disagree with. But I'll give us both a Suggested-by line which should solve this nicely.

#4 lore raw
Quoted 9 lines · Christian Brauner
Quoted 3 lines

I think there are a few other things I would really like (with my runc hat on), such as being able to move_mount(2) into this new kind of OPEN_TREE_NAMESPACE handle.

As you know I have outlined multiple ways how we can do it on-list and then again in Tokyo. There's a ToDo item I'm going to get to soon. Around end of November someone asked about related changes again. I have the beginnings for that in a branch. I just need to get to it but I need to catch up with the list first...

Sure, I just wanted to have an on-list note about that bit of the discussion.

Quoted 13 lines
Quoted 4 lines

However, on the whole I think this seems very reasonable and is much simpler than I anticipated when we talked about this at LPC. I've just taken a general look but feel free to take my

Quoted 8 lines

and also maybe a

If you feel it's appropriate, since we came up with this together at LPC? ;)

Quoted 8 lines

Eh, well, this rubs me the wrong way a little bit, I have to say. The idea was basically just "what if we had an empty mount namespace" which doesn't really work without other work I mentioned there. So to me this was basically a fragment thrown around that I then turned into the open_tree() idea that I explained later and which is rather different. So adding a "Suggested-by" for that kinda makes it sound like I was the code monkey which I very much disagree with. But I'll give us both a Suggested-by line which should solve this nicely.

Of course I didn't mean to suggest you were a code monkey.

You're quite right that this did turn out differently to the very rough version we spoke about (though I think the same insight about removing the wasted cloning for mounts that get blown away alleviating the cost of the contention on namespace_sem applies regardless) -- in any case, I'll leave it up to you.

Signature · 2 lines
Aleksa Sarai
https://www.cyphar.com/
#15 lore raw
In reply to Christian Brauner

Christian Brauner <[email protected]>:

Quoted 6 lines

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

I want to point at security benefits of this.

[[ TL;DR: [1] and [2] are very big changes to how mount namespaces work. I like them, and I think they should get wider exposure. ]]

If this patchset ([1]) and [2] both land (they are both in "next" now and likely will be submitted to mainline soon) and "nullfs_rootfs" is passed on command line, then mount namespace created by open_tree(OPEN_TREE_NAMESPACE) will usually contain exactly 2 mounts: nullfs and whatever was passed to open_tree(OPEN_TREE_NAMESPACE).

This means that even if attacker somehow is able to unmount its root and get access to underlying mounts, then the only underlying thing they will get is nullfs.

Also this means that other mounts are not only hidden in new namespace, they are fully absent. This prevents attacks discussed here: [3], [4].

Also this means that (assuming we have both [1] and [2] and "nullfs_rootfs" is passed), there is no anymore hidden writable mount shared by all containers, potentially available to attackers. This is concern raised in [5]:

Quoted 5 lines

You want rootfs to be a NULLFS instead of ramfs. You don't seem to want it to actually _be_ a filesystem. Even with your "fix", containers could communicate with each _other_ through it if it becomes accessible. If a container can get access to an empty initramfs and write into it, it can ask/answer the question "Are there any other containers on this machine running stux24" and then coordinate.

Note: as well as I understand all actual security bugs are already fixed in kernel, runc and similar tools. But still [1] and [2] reduce chances of similar bugs in the future, and this is very good thing.

Also: [1] and [2] are pretty big changes to how mount namespaces work, so I added more people and lists to CC.

This mail is answer to [1].

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

[3] https://lore.kernel.org/all/rxh6knvencwjajhgvdgzmrkwmyxwotu3itqyreun3h2pmaujhr@snhuqoq44kkf/
[4] https://github.com/opencontainers/runc/pull/1962
[5] https://lore.kernel.org/all/[email protected]/

Signature · 1 line
Askar Safin
#16 lore raw
Quoted 24 lines · Askar Safin

Christian Brauner <[email protected]>:

Quoted 6 lines

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

I want to point at security benefits of this.

[[ TL;DR: [1] and [2] are very big changes to how mount namespaces work. I like them, and I think they should get wider exposure. ]]

If this patchset ([1]) and [2] both land (they are both in "next" now and likely will be submitted to mainline soon) and "nullfs_rootfs" is passed on command line, then mount namespace created by open_tree(OPEN_TREE_NAMESPACE) will usually contain exactly 2 mounts: nullfs and whatever was passed to open_tree(OPEN_TREE_NAMESPACE).

This means that even if attacker somehow is able to unmount its root and get access to underlying mounts, then the only underlying thing they will get is nullfs.

Quoted 12 lines

Also this means that other mounts are not only hidden in new namespace, they are fully absent. This prevents attacks discussed here: [3], [4].

Also this means that (assuming we have both [1] and [2] and "nullfs_rootfs" is passed), there is no anymore hidden writable mount shared by all containers, potentially available to attackers. This is concern raised in [5]:

Quoted 5 lines

You want rootfs to be a NULLFS instead of ramfs. You don't seem to want it to actually _be_ a filesystem. Even with your "fix", containers could communicate with each _other_ through it if it becomes accessible. If a container can get access to an empty initramfs and write into it, it can ask/answer the question "Are there any other containers on this machine running stux24" and then coordinate.

I think this new OPEN_TREE_NAMESPACE is nifty, but I don't think the path that gives it sensible behavior should be conditional like this. Either make it *always* mount on top of nullfs (regardless of boot options) or find some way to have it actually be the root. I assume the latter is challenging for some reason.

--Andy

#17 lore raw
Quoted 38 lines · Andy Lutomirski
Quoted 24 lines · Askar Safin

Christian Brauner <[email protected]>:

Quoted 6 lines

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

I want to point at security benefits of this.

[[ TL;DR: [1] and [2] are very big changes to how mount namespaces work. I like them, and I think they should get wider exposure. ]]

If this patchset ([1]) and [2] both land (they are both in "next" now and likely will be submitted to mainline soon) and "nullfs_rootfs" is passed on command line, then mount namespace created by open_tree(OPEN_TREE_NAMESPACE) will usually contain exactly 2 mounts: nullfs and whatever was passed to open_tree(OPEN_TREE_NAMESPACE).

This means that even if attacker somehow is able to unmount its root and get access to underlying mounts, then the only underlying thing they will get is nullfs.

Quoted 12 lines

Also this means that other mounts are not only hidden in new namespace, they are fully absent. This prevents attacks discussed here: [3], [4].

Also this means that (assuming we have both [1] and [2] and "nullfs_rootfs" is passed), there is no anymore hidden writable mount shared by all containers, potentially available to attackers. This is concern raised in [5]:

Quoted 5 lines

You want rootfs to be a NULLFS instead of ramfs. You don't seem to want it to actually _be_ a filesystem. Even with your "fix", containers could communicate with each _other_ through it if it becomes accessible. If a container can get access to an empty initramfs and write into it, it can ask/answer the question "Are there any other containers on this machine running stux24" and then coordinate.

Quoted 6 lines

I think this new OPEN_TREE_NAMESPACE is nifty, but I don't think the path that gives it sensible behavior should be conditional like this. Either make it *always* mount on top of nullfs (regardless of boot options) or find some way to have it actually be the root. I assume the latter is challenging for some reason.

I think that's the plan. I suggested the same to Christian last week, and he was amenable to removing the option and just always doing a nullfs_rootfs mount.

We think that older runtimes should still "just work" with this scheme. Out of an abundance of caution, we _might_ want a command-line option to make it go back to old way, in case we find some userland stuff that doesn't like this for some reason, but hopefully we won't even need that.

Signature · 1 line
Jeff Layton <[email protected]>
author maintainer
#18 lore raw
Quoted 46 lines · Jeff Layton
Quoted 38 lines · Andy Lutomirski
Quoted 24 lines · Askar Safin

Christian Brauner <[email protected]>:

Quoted 6 lines

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

I want to point at security benefits of this.

[[ TL;DR: [1] and [2] are very big changes to how mount namespaces work. I like them, and I think they should get wider exposure. ]]

If this patchset ([1]) and [2] both land (they are both in "next" now and likely will be submitted to mainline soon) and "nullfs_rootfs" is passed on command line, then mount namespace created by open_tree(OPEN_TREE_NAMESPACE) will usually contain exactly 2 mounts: nullfs and whatever was passed to open_tree(OPEN_TREE_NAMESPACE).

This means that even if attacker somehow is able to unmount its root and get access to underlying mounts, then the only underlying thing they will get is nullfs.

Quoted 12 lines

Also this means that other mounts are not only hidden in new namespace, they are fully absent. This prevents attacks discussed here: [3], [4].

Also this means that (assuming we have both [1] and [2] and "nullfs_rootfs" is passed), there is no anymore hidden writable mount shared by all containers, potentially available to attackers. This is concern raised in [5]:

Quoted 5 lines

You want rootfs to be a NULLFS instead of ramfs. You don't seem to want it to actually _be_ a filesystem. Even with your "fix", containers could communicate with each _other_ through it if it becomes accessible. If a container can get access to an empty initramfs and write into it, it can ask/answer the question "Are there any other containers on this machine running stux24" and then coordinate.

Quoted 6 lines

I think this new OPEN_TREE_NAMESPACE is nifty, but I don't think the path that gives it sensible behavior should be conditional like this. Either make it *always* mount on top of nullfs (regardless of boot options) or find some way to have it actually be the root. I assume the latter is challenging for some reason.

Quoted 3 lines

I think that's the plan. I suggested the same to Christian last week, and he was amenable to removing the option and just always doing a nullfs_rootfs mount.

Whether or not the underlying mount is nullfs or not is irrelevant. If it's not nullfs but a regular tmpfs it works just as well. If it has any locked overmounts the new rootfs will become locked as well similarly if it'll be owned by a new userns.

#19 lore raw
In reply to Jeff Layton
Quoted 52 lines · Jeff Layton
Quoted 38 lines · Andy Lutomirski
Quoted 25 lines · Askar Safin

Christian Brauner <[email protected]>:

Quoted 6 lines

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

I want to point at security benefits of this.

[[ TL;DR: [1] and [2] are very big changes to how mount namespaces work. I like them, and I think they should get wider exposure. ]]

If this patchset ([1]) and [2] both land (they are both in "next" now and likely will be submitted to mainline soon) and "nullfs_rootfs" is passed on command line, then mount namespace created by open_tree(OPEN_TREE_NAMESPACE) will usually contain exactly 2 mounts: nullfs and whatever was passed to open_tree(OPEN_TREE_NAMESPACE).

This means that even if attacker somehow is able to unmount its root and get access to underlying mounts, then the only underlying thing they will get is nullfs.

Quoted 12 lines

Also this means that other mounts are not only hidden in new namespace, they are fully absent. This prevents attacks discussed here: [3], [4].

Also this means that (assuming we have both [1] and [2] and "nullfs_rootfs" is passed), there is no anymore hidden writable mount shared by all containers, potentially available to attackers. This is concern raised in [5]:

Quoted 5 lines

You want rootfs to be a NULLFS instead of ramfs. You don't seem to want it to actually _be_ a filesystem. Even with your "fix", containers could communicate with each _other_ through it if it becomes accessible. If a container can get access to an empty initramfs and write into it, it can ask/answer the question "Are there any other containers on this machine running stux24" and then coordinate.

Quoted 6 lines

I think this new OPEN_TREE_NAMESPACE is nifty, but I don't think the path that gives it sensible behavior should be conditional like this. Either make it *always* mount on top of nullfs (regardless of boot options) or find some way to have it actually be the root. I assume the latter is challenging for some reason.

I think that's the plan. I suggested the same to Christian last week, and he was amenable to removing the option and just always doing a nullfs_rootfs mount.

Quoted 5 lines

We think that older runtimes should still "just work" with this scheme. Out of an abundance of caution, we _might_ want a command-line option to make it go back to old way, in case we find some userland stuff that doesn't like this for some reason, but hopefully we won't even need that.

What I mean is: even if for some reason the kernel is running in a mode where the *initial* rootfs is a real fs, I think it would be nice for OPEN_TREE_NAMESPACE to use nullfs.

#22 lore raw
In reply to Jeff Layton
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines

You want rootfs to be a NULLFS instead of ramfs. You don't seem to want it to actually _be_ a filesystem. Even with your "fix", containers could communicate with each _other_ through it if it becomes accessible. If a container can get access to an empty initramfs and write into it, it can ask/answer the question "Are there any other containers on this machine running stux24" and then coordinate.

Or you could just make the ROOT= codepath remount the empty initramfs -o ro like some switch_root implementations do. If the PID 1 you launch isn't in initramfs, don't leave initramfs writeable. That seems unlikely to break userspace.

(Having permissions to remount initramfs but _not_ having already "cracked root" seems... a bit funky? You have waaaaay more faith in security modules than I do...)

Quoted 9 lines
Quoted 5 lines

I think this new OPEN_TREE_NAMESPACE is nifty, but I don't think the path that gives it sensible behavior should be conditional like this. Either make it *always* mount on top of nullfs (regardless of boot options) or find some way to have it actually be the root. I assume the latter is challenging for some reason.

I think that's the plan. I suggested the same to Christian last week, and he was amenable to removing the option and just always doing a nullfs_rootfs mount.

Since 2013, initramfs might be ramfs or tmpfs depending on circumstances. Adding a third option for it be nullfs when there's no cpio.gz extracted into it seems reasonable. (You can always mount a tmpfs _over_ it if you need that later, it's writeable so a PID 1 launched in it has workspace.)

That said, if you are changing the semantics, right now we switch_root from initramfs instead of pivot_root because initramfs couldn't be unmounted. With this change would pivot_root become the mechanism for initramfs too? (If the cpio.gz recipient wasn't actually rootfs but was an overmount the way ROOT= does it.)

Aside: it would be nice if inaccessible mount points could automatically be garbage collected. There's already some "lazy umount" plumbing that does that when explicitly requested to, but last I checked there were cases that didn't get caught. It's been a while though, might already have been fixed. Presumably initramfs would always get pinned because it's PID 0's / reference...

Also, could you guys make CONFIG_DEVTMPFS_MOUNT work with initramfs? I've posted patches for that on and off since 2017, most recent one's probably https://landley.net/bin/mkroot/0.8.13/linux-patches/0003-Wire-up-CONFIG_DEVTMPFS_MOUNT-to-initramfs.patch (tested on a 6.17 kernel).

Quoted 5 lines

We think that older runtimes should still "just work" with this scheme. Out of an abundance of caution, we _might_ want a command-line option to make it go back to old way, in case we find some userland stuff that doesn't like this for some reason, but hopefully we won't even need that.

I assume it will break stuff, but I also assume the systems it breaks will never upgrade to a 7.x kernel because the kernel itself would consume all available memory before launching PID 1.

Rob

author maintainer
#20 lore raw
In reply to Andy Lutomirski
Quoted 58 lines · Andy Lutomirski
Quoted 52 lines · Jeff Layton
Quoted 38 lines · Andy Lutomirski
Quoted 25 lines · Askar Safin

Christian Brauner <[email protected]>:

Quoted 6 lines

Extend open_tree() with a new OPEN_TREE_NAMESPACE flag. Similar to OPEN_TREE_CLONE only the indicated mount tree is copied. Instead of returning a file descriptor referring to that mount tree OPEN_TREE_NAMESPACE will cause open_tree() to return a file descriptor to a new mount namespace. In that new mount namespace the copied mount tree has been mounted on top of a copy of the real rootfs.

I want to point at security benefits of this.

[[ TL;DR: [1] and [2] are very big changes to how mount namespaces work. I like them, and I think they should get wider exposure. ]]

If this patchset ([1]) and [2] both land (they are both in "next" now and likely will be submitted to mainline soon) and "nullfs_rootfs" is passed on command line, then mount namespace created by open_tree(OPEN_TREE_NAMESPACE) will usually contain exactly 2 mounts: nullfs and whatever was passed to open_tree(OPEN_TREE_NAMESPACE).

This means that even if attacker somehow is able to unmount its root and get access to underlying mounts, then the only underlying thing they will get is nullfs.

Quoted 12 lines

Also this means that other mounts are not only hidden in new namespace, they are fully absent. This prevents attacks discussed here: [3], [4].

Also this means that (assuming we have both [1] and [2] and "nullfs_rootfs" is passed), there is no anymore hidden writable mount shared by all containers, potentially available to attackers. This is concern raised in [5]:

Quoted 5 lines

You want rootfs to be a NULLFS instead of ramfs. You don't seem to want it to actually _be_ a filesystem. Even with your "fix", containers could communicate with each _other_ through it if it becomes accessible. If a container can get access to an empty initramfs and write into it, it can ask/answer the question "Are there any other containers on this machine running stux24" and then coordinate.

Quoted 6 lines

I think this new OPEN_TREE_NAMESPACE is nifty, but I don't think the path that gives it sensible behavior should be conditional like this. Either make it *always* mount on top of nullfs (regardless of boot options) or find some way to have it actually be the root. I assume the latter is challenging for some reason.

I think that's the plan. I suggested the same to Christian last week, and he was amenable to removing the option and just always doing a nullfs_rootfs mount.

Quoted 5 lines

We think that older runtimes should still "just work" with this scheme. Out of an abundance of caution, we _might_ want a command-line option to make it go back to old way, in case we find some userland stuff that doesn't like this for some reason, but hopefully we won't even need that.

Quoted 3 lines

What I mean is: even if for some reason the kernel is running in a mode where the *initial* rootfs is a real fs, I think it would be nice for OPEN_TREE_NAMESPACE to use nullfs.

The current patchset makes nullfs unconditional. As each mount namespaces creates a new copy of the namespace root of the namespace it was created from all mount namespace have nullfs as namespace root. So every OPEN_TREE_NAMESPACE/FSMOUNT_NAMESPACE will be mounted on top of nullfs as we always take the namespace root. If we have to make nullfs conditional then yes, we could still do that - althoug it would be ugly in various ways.

I would love to keep nullfs unconditional because it means I can wipe a whole class of MNT_LOCKED nonsense from the face of the earth afterwards.

#21 lore raw
Quoted 1 line · Christian Brauner

The current patchset makes nullfs unconditional. As each mount

Oops, I missed that "fs: use nullfs unconditionally as the real rootfs" is present in vfs.all.

Signature · 1 line
Askar Safin
#5 lore raw
In reply to Christian Brauner

* Christian Brauner:

include/uapi/linux/mount.h line 64

Quoted 10 lines
include/uapi/linux/mount.h +1 -1
index 5d3f8c9e3a62..acbc22241c9c 100644
@@ -61,7 +61,8 @@
 /*
  * open_tree() flags.
  */
-#define OPEN_TREE_CLONE		1		/* Clone the target tree and attach the clone */
+#define OPEN_TREE_CLONE		(1 << 0)	/* Clone the target tree and attach the clone */

This change causes pointless -Werror=undef errors in projects that have settled on the old definition.

Reported here:

Bug 33921 - Building with Linux-7.0-rc1 errors on OPEN_TREE_CLONE
<https://sourceware.org/bugzilla/show_bug.cgi?id=33921>

Thanks,
Florian

author maintainer
#6 lore raw
Quoted 16 lines · Florian Weimer

* Christian Brauner:

include/uapi/linux/mount.h line 64

Quoted 10 lines
include/uapi/linux/mount.h +1 -1
index 5d3f8c9e3a62..acbc22241c9c 100644
@@ -61,7 +61,8 @@
 /*
  * open_tree() flags.
  */
-#define OPEN_TREE_CLONE		1		/* Clone the target tree and attach the clone */
+#define OPEN_TREE_CLONE		(1 << 0)	/* Clone the target tree and attach the clone */

This change causes pointless -Werror=undef errors in projects that have settled on the old definition.

Quoted 4 lines

Reported here:

Bug 33921 - Building with Linux-7.0-rc1 errors on OPEN_TREE_CLONE
<https://sourceware.org/bugzilla/show_bug.cgi?id=33921>

Send a patch to change it back, please.
Otherwise it might take a few days until I get around to it.

#7 lore raw

* Christian Brauner:

Quoted 17 lines · Florian Weimer
Quoted 16 lines

* Christian Brauner:

include/uapi/linux/mount.h line 64

Quoted 10 lines
include/uapi/linux/mount.h +1 -1
index 5d3f8c9e3a62..acbc22241c9c 100644
@@ -61,7 +61,8 @@
 /*
  * open_tree() flags.
  */
-#define OPEN_TREE_CLONE		1		/* Clone the target tree and attach the clone */
+#define OPEN_TREE_CLONE		(1 << 0)	/* Clone the target tree and attach the clone */

This change causes pointless -Werror=undef errors in projects that have settled on the old definition.

Quoted 7 lines
Quoted 4 lines

Reported here:

Bug 33921 - Building with Linux-7.0-rc1 errors on OPEN_TREE_CLONE
<https://sourceware.org/bugzilla/show_bug.cgi?id=33921>

Send a patch to change it back, please.
Otherwise it might take a few days until I get around to it.

Rudi, could you post a patch?

Thanks,
Florian

author maintainer
#8 lore raw
Quoted 21 lines · Florian Weimer

* Christian Brauner:

Quoted 19 lines · Florian Weimer
Quoted 18 lines

* Christian Brauner:

include/uapi/linux/mount.h line 64

Quoted 10 lines
include/uapi/linux/mount.h +1 -1
index 5d3f8c9e3a62..acbc22241c9c 100644
@@ -61,7 +61,8 @@
 /*
  * open_tree() flags.
  */
-#define OPEN_TREE_CLONE		1		/* Clone the target tree and attach the clone */
+#define OPEN_TREE_CLONE		(1 << 0)	/* Clone the target tree and attach the clone */

This change causes pointless -Werror=undef errors in projects that have settled on the old definition.

Reported here:

Quoted 7 lines
Quoted 5 lines
Quoted 2 lines

Bug 33921 - Building with Linux-7.0-rc1 errors on OPEN_TREE_CLONE
<https://sourceware.org/bugzilla/show_bug.cgi?id=33921>

Send a patch to change it back, please.
Otherwise it might take a few days until I get around to it.

Rudi, could you post a patch?

I'm a bit confused though and not super happy that you're basically asking us to be so constrained that we aren't even allowed to change 1 to 1 - just syntactically different.

reviewer
#9 lore raw
Quoted 25 lines · Christian Brauner
Quoted 24 lines · Florian Weimer

* Christian Brauner:

Quoted 22 lines · Florian Weimer
Quoted 20 lines

* Christian Brauner:

include/uapi/linux/mount.h line 64

Quoted 10 lines
include/uapi/linux/mount.h +1 -1
index 5d3f8c9e3a62..acbc22241c9c 100644
@@ -61,7 +61,8 @@
 /*
  * open_tree() flags.
  */
-#define OPEN_TREE_CLONE		1		/* Clone the target tree and attach the clone */
+#define OPEN_TREE_CLONE		(1 << 0)	/* Clone the target tree and attach the clone */

This change causes pointless -Werror=undef errors in projects that have settled on the old definition.

Reported here:

Bug 33921 - Building with Linux-7.0-rc1 errors on OPEN_TREE_CLONE
<https://sourceware.org/bugzilla/show_bug.cgi?id=33921>

Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

Send a patch to change it back, please.
Otherwise it might take a few days until I get around to it.

Rudi, could you post a patch?

I'm a bit confused though and not super happy that you're basically asking us to be so constrained that we aren't even allowed to change 1 to 1 - just syntactically different.

Agreed, this looks more like a tooling bug than anything else...

Honza

Signature · 2 lines
Jan Kara <[email protected]>
SUSE Labs, CR
#10 lore raw
In reply to Christian Brauner

* Christian Brauner:

Quoted 25 lines · Florian Weimer
Quoted 24 lines

* Christian Brauner:

Quoted 22 lines · Florian Weimer
Quoted 20 lines

* Christian Brauner:

include/uapi/linux/mount.h line 64

Quoted 10 lines
include/uapi/linux/mount.h +1 -1
index 5d3f8c9e3a62..acbc22241c9c 100644
@@ -61,7 +61,8 @@
 /*
  * open_tree() flags.
  */
-#define OPEN_TREE_CLONE		1		/* Clone the target tree and attach the clone */
+#define OPEN_TREE_CLONE		(1 << 0)	/* Clone the target tree and attach the clone */

This change causes pointless -Werror=undef errors in projects that have settled on the old definition.

Reported here:

Bug 33921 - Building with Linux-7.0-rc1 errors on OPEN_TREE_CLONE
<https://sourceware.org/bugzilla/show_bug.cgi?id=33921>

Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

Send a patch to change it back, please.
Otherwise it might take a few days until I get around to it.

Rudi, could you post a patch?

I'm a bit confused though and not super happy that you're basically asking us to be so constrained that we aren't even allowed to change 1 to 1 - just syntactically different.

I'm not happy about it, either. But it has happened before, for the RENAME_* constants I believe.

We are already including <linux/mount.h> from <sys/mount.h>, so we can work around this reliably on the glibc side, regardless of header inclusion order.

Thanks,
Florian