git.iko.soy/typeable/nixpkgs
on master help sign in
chrootenv: make stackable

The problem with stacking chrootenv before was that CLONE_NEWUSER cannot be used when a child uses chroot. So instead of that we use pivot_root which replaces root in the whole namespace. This requires our new root to be an actual fs so we mount tmpfs.

commite0d3bc292caaa2eec3f8360494b6c17618a36f12 authorNikolay Amiantov <ab@fmap.me> dateFri 10 May 2019, 14:59 (8 years ago) parentecb9930
1 file changed+16−10
pkgs/build-support/build-fhs-userenv/chrootenv/chrootenv.c+16−10
pkgs/build-support/build-fhs-userenv/chrootenv/chrootenv.c+16−10
@@ -18,6 +18,7 @@
1818#include <sys/stat.h>
1919#include <sys/types.h>
2020#include <sys/wait.h>
21+#include <sys/syscall.h>
2122
2223int min(int a, int b) {
2324 return a > b ? b : a;
@@ -25,14 +26,23 @@ int min(int a, int b) {
2526
2627const gchar *bind_blacklist[] = {"bin", "etc", "host", "usr", "lib", "lib64", "lib32", "sbin", NULL};
2728
29+int pivot_root(const char *new_root, const char *put_old) {
30+ return syscall(SYS_pivot_root, new_root, put_old);
31+}
32+
33+void mount_tmpfs(const gchar *target) {
34+ fail_if(mount("none", target, "tmpfs", 0, NULL));
35+}
36+
2837void bind_mount(const gchar *source, const gchar *target) {
2938 fail_if(g_mkdir(target, 0755));
3039 fail_if(mount(source, target, "bind", MS_BIND | MS_REC, NULL));
3140}
3241
33−void bind_mount_host(const gchar *host, const gchar *guest) {
42+void pivot_host(const gchar *host, const gchar *guest) {
3443 g_autofree gchar *point = g_build_filename(guest, "host", NULL);
35− bind_mount(host, point);
44+ fail_if(g_mkdir(point, 0755));
45+ fail_if(pivot_root(guest, point));
3646}
3747
3848void bind_mount_item(const gchar *host, const gchar *guest, const gchar *name) {
@@ -44,6 +54,8 @@ void bind_mount_item(const gchar *host, const gchar *guest, const gchar *name) {
4454}
4555
4656void bind(const gchar *host, const gchar *guest) {
57+ mount_tmpfs(guest);
58+
4759 g_autoptr(GError) err = NULL;
4860 g_autoptr(GDir) dir = g_dir_open(host, 0, &err);
4961
@@ -52,11 +64,11 @@ void bind(const gchar *host, const gchar *guest) {
5264
5365 const gchar *item;
5466
55− while (item = g_dir_read_name(dir))
67+ while ((item = g_dir_read_name(dir)))
5668 if (!g_strv_contains(bind_blacklist, item))
5769 bind_mount_item(host, guest, item);
5870
59− bind_mount_host(host, guest);
71+ pivot_host(host, guest);
6072}
6173
6274void spit(const char *path, char *fmt, ...) {
@@ -85,11 +97,6 @@ int main(gint argc, gchar **argv) {
8597 return 1;
8698 }
8799
88− if (g_getenv("NIX_CHROOTENV"))
89− g_warning("chrootenv doesn't stack!");
90− else
91− g_setenv("NIX_CHROOTENV", "", TRUE);
92−
93100 g_autofree gchar *prefix =
94101 g_build_filename(g_get_tmp_dir(), "chrootenvXXXXXX", NULL);
95102
@@ -121,7 +128,6 @@ int main(gint argc, gchar **argv) {
121128
122129 bind("/", prefix);
123130
124− fail_if(chroot(prefix));
125131 fail_if(chdir("/"));
126132 fail_if(execvp(*argv, argv));
127133 }