1 /* GNU Guix --- Functional package management for GNU
2 Copyright (C) 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
4 This file is part of GNU Guix.
6 GNU Guix is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or (at
9 your option) any later version.
11 GNU Guix is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Guix. If not, see <http://www.gnu.org/licenses/>. */
19 /* Make the given @WRAPPED_PROGRAM@ relocatable by executing it in a separate
20 mount namespace where the store is mounted in its right place.
22 We would happily do that in Scheme using 'call-with-container'. However,
23 this very program needs to be relocatable, so it needs to be statically
24 linked, which complicates things (Guile's modules can hardly be "linked"
25 into a single executable.) */
32 #include <sys/mount.h>
39 #include <sys/types.h>
43 #include <sys/syscall.h>
45 /* Whether we're building the ld.so/libfakechroot wrapper. */
46 #define HAVE_EXEC_WITH_LOADER \
47 (defined PROGRAM_INTERPRETER) && (defined LOADER_AUDIT_MODULE) \
48 && (defined FAKECHROOT_LIBRARY)
50 /* The original store, "/gnu/store" by default. */
51 static const char original_store
[] = "@STORE_DIRECTORY@";
54 /* Like 'malloc', but abort if 'malloc' returns NULL. */
58 void *result
= malloc (size
);
59 assert (result
!= NULL
);
63 /* Concatenate DIRECTORY, a slash, and FILE. Return the result, which the
64 caller must eventually free. */
66 concat (const char *directory
, const char *file
)
68 char *result
= xmalloc (strlen (directory
) + 2 + strlen (file
));
70 strcpy (result
, directory
);
72 strcat (result
, file
);
77 mkdir_p (const char *directory
)
79 if (strcmp (directory
, "/") != 0)
81 char *parent
= dirname (strdupa (directory
));
83 int err
= mkdir (directory
, 0700);
84 if (err
< 0 && errno
!= EEXIST
)
85 assert_perror (errno
);
90 rm_rf (const char *directory
)
92 DIR *stream
= opendir (directory
);
94 for (struct dirent
*entry
= readdir (stream
);
96 entry
= readdir (stream
))
98 if (strcmp (entry
->d_name
, ".") == 0
99 || strcmp (entry
->d_name
, "..") == 0)
102 char *full
= concat (directory
, entry
->d_name
);
104 int err
= unlink (full
);
108 /* Recurse (we expect a shallow directory structure so there's
109 little risk of stack overflow.) */
112 assert_perror (errno
);
120 int err
= rmdir (directory
);
121 if (err
< 0 && errno
!= ENOENT
)
122 assert_perror (errno
);
125 /* Make TARGET a bind-mount of SOURCE. Take into account ENTRY's type, which
126 corresponds to SOURCE. */
128 bind_mount (const char *source
, const struct dirent
*entry
,
131 if (entry
->d_type
== DT_DIR
)
133 int err
= mkdir (target
, 0700);
138 close (open (target
, O_WRONLY
| O_CREAT
));
140 return mount (source
, target
, "none",
141 MS_BIND
| MS_REC
| MS_RDONLY
, NULL
);
144 #if HAVE_EXEC_WITH_LOADER
146 /* Make TARGET a symlink to SOURCE. */
148 make_symlink (const char *source
, const struct dirent
*entry
,
151 return symlink (source
, target
);
156 /* Mirror with FIRMLINK all the top-level entries in SOURCE to TARGET. */
158 mirror_directory (const char *source
, const char *target
,
159 int (* firmlink
) (const char *, const struct dirent
*,
162 DIR *stream
= opendir (source
);
164 for (struct dirent
*entry
= readdir (stream
);
166 entry
= readdir (stream
))
168 /* XXX: Some file systems may not report a useful 'd_type'. Ignore them
170 assert (entry
->d_type
!= DT_UNKNOWN
);
172 if (strcmp (entry
->d_name
, ".") == 0
173 || strcmp (entry
->d_name
, "..") == 0)
176 char *abs_source
= concat (source
, entry
->d_name
);
177 char *new_entry
= concat (target
, entry
->d_name
);
179 if (entry
->d_type
== DT_LNK
)
181 char target
[PATH_MAX
];
183 ssize_t result
= readlink (abs_source
, target
, sizeof target
- 1);
186 target
[result
] = '\0';
187 int err
= symlink (target
, new_entry
);
189 assert_perror (errno
);
194 /* Create the mount point. */
195 int err
= firmlink (abs_source
, entry
, new_entry
);
197 /* It used to be that only directories could be bind-mounted. Thus,
198 keep going if we fail to bind-mount a non-directory entry.
199 That's OK because regular files in the root file system are
200 usually uninteresting. */
201 if (err
!= 0 && entry
->d_type
!= DT_DIR
)
202 assert_perror (errno
);
212 /* Write the user/group ID map for PID to FILE, mapping ID to itself. See
213 user_namespaces(7). */
215 write_id_map (pid_t pid
, const char *file
, int id
)
217 char id_map_file
[100];
218 snprintf (id_map_file
, sizeof id_map_file
, "/proc/%d/%s", pid
, file
);
222 /* Map root and the current user. */
223 int len
= snprintf (id_map
, sizeof id_map
, "%d %d 1\n", id
, id
);
224 int fd
= open (id_map_file
, O_WRONLY
);
226 assert_perror (errno
);
228 int n
= write (fd
, id_map
, len
);
230 assert_perror (errno
);
235 /* Disallow setgroups(2) for PID. */
237 disallow_setgroups (pid_t pid
)
241 snprintf (file
, sizeof file
, "/proc/%d/setgroups", pid
);
243 int fd
= open (file
, O_WRONLY
);
245 assert_perror (errno
);
247 int err
= write (fd
, "deny", 5);
249 assert_perror (errno
);
254 /* Run the wrapper program in a separate mount user namespace. Return only
257 exec_in_user_namespace (const char *store
, int argc
, char *argv
[])
259 /* Spawn @WRAPPED_PROGRAM@ in a separate namespace where STORE is
260 bind-mounted in the right place. */
262 char *new_root
= mkdtemp (strdup ("/tmp/guix-exec-XXXXXX"));
263 char *new_store
= concat (new_root
, original_store
);
264 char *cwd
= get_current_dir_name ();
266 /* Create a child with separate namespaces and set up bind-mounts from
267 there. That way, bind-mounts automatically disappear when the child
268 exits, which simplifies cleanup for the parent. Note: clone is more
269 convenient than fork + unshare since the parent can directly write
270 the child uid_map/gid_map files. */
271 pid_t child
= syscall (SYS_clone
, SIGCHLD
| CLONE_NEWNS
| CLONE_NEWUSER
,
276 /* Note: Due to <https://bugzilla.kernel.org/show_bug.cgi?id=183461>
277 we cannot make NEW_ROOT a tmpfs (which would have saved the need
279 mirror_directory ("/", new_root
, bind_mount
);
281 err
= mount (store
, new_store
, "none", MS_BIND
| MS_REC
| MS_RDONLY
,
284 assert_perror (errno
);
287 err
= chroot (new_root
);
289 assert_perror (errno
);
291 /* Change back to where we were before chroot'ing. */
294 int err
= execv ("@WRAPPED_PROGRAM@", argv
);
296 assert_perror (errno
);
300 /* Failure: user namespaces not supported. */
301 fprintf (stderr
, "%s: error: 'clone' failed: %m\n", argv
[0]);
307 /* Map the current user/group ID in the child's namespace (the
308 default is to get the "overflow UID", i.e., the UID of
309 "nobody"). We must first disallow 'setgroups' for that
311 disallow_setgroups (child
);
312 write_id_map (child
, "uid_map", getuid ());
313 write_id_map (child
, "gid_map", getgid ());
316 waitpid (child
, &status
, 0);
317 chdir ("/"); /* avoid EBUSY */
321 if (WIFEXITED (status
))
322 exit (WEXITSTATUS (status
));
324 /* Abnormal termination cannot really be reproduced, so exit
334 /* Execute the wrapped program with PRoot, passing it ARGC and ARGV, and
335 "bind-mounting" STORE in the right place. */
337 exec_with_proot (const char *store
, int argc
, char *argv
[])
339 int proot_specific_argc
= 4;
340 int proot_argc
= argc
+ proot_specific_argc
;
341 char *proot_argv
[proot_argc
+ 1], *proot
;
342 char bind_spec
[strlen (store
) + 1 + sizeof original_store
];
344 strcpy (bind_spec
, store
);
345 strcat (bind_spec
, ":");
346 strcat (bind_spec
, original_store
);
348 proot
= concat (store
, PROOT_PROGRAM
);
350 proot_argv
[0] = proot
;
351 proot_argv
[1] = "-b";
352 proot_argv
[2] = bind_spec
;
353 proot_argv
[3] = "@WRAPPED_PROGRAM@";
355 for (int i
= 0; i
< argc
; i
++)
356 proot_argv
[i
+ proot_specific_argc
] = argv
[i
+ 1];
358 proot_argv
[proot_argc
] = NULL
;
360 /* Seccomp support seems to invariably lead to segfaults; disable it by
362 setenv ("PROOT_NO_SECCOMP", "1", 0);
364 int err
= execv (proot
, proot_argv
);
366 assert_perror (errno
);
372 #if HAVE_EXEC_WITH_LOADER
374 /* Execute the wrapped program by invoking the loader (ld.so) directly,
375 passing it the audit module and preloading libfakechroot.so. */
377 exec_with_loader (const char *store
, int argc
, char *argv
[])
379 char *loader
= concat (store
,
380 PROGRAM_INTERPRETER
+ sizeof original_store
);
381 size_t loader_specific_argc
= 6;
382 size_t loader_argc
= argc
+ loader_specific_argc
;
383 char *loader_argv
[loader_argc
+ 1];
384 loader_argv
[0] = argv
[0];
385 loader_argv
[1] = "--audit";
386 loader_argv
[2] = concat (store
,
387 LOADER_AUDIT_MODULE
+ sizeof original_store
);
388 loader_argv
[3] = "--preload";
389 loader_argv
[4] = concat (store
,
390 FAKECHROOT_LIBRARY
+ sizeof original_store
);
391 loader_argv
[5] = concat (store
,
392 "@WRAPPED_PROGRAM@" + sizeof original_store
);
394 for (size_t i
= 0; i
< argc
; i
++)
395 loader_argv
[i
+ loader_specific_argc
] = argv
[i
+ 1];
397 loader_argv
[loader_argc
] = NULL
;
399 /* Set up the root directory. */
401 char *new_root
= mkdtemp (strdup ("/tmp/guix-exec-XXXXXX"));
402 mirror_directory ("/", new_root
, make_symlink
);
404 char *new_store
= concat (new_root
, original_store
);
405 char *new_store_parent
= dirname (strdup (new_store
));
406 mkdir_p (new_store_parent
);
407 symlink (store
, new_store
);
409 #ifdef GCONV_DIRECTORY
410 /* Tell libc where to find its gconv modules. This is necessary because
411 gconv uses non-interposable 'open' calls. */
412 char *gconv_path
= concat (store
,
413 GCONV_DIRECTORY
+ sizeof original_store
);
414 setenv ("GCONV_PATH", gconv_path
, 1);
418 setenv ("FAKECHROOT_BASE", new_root
, 1);
420 pid_t child
= fork ();
424 err
= execv (loader
, loader_argv
);
426 assert_perror (errno
);
431 assert_perror (errno
);
438 waitpid (child
, &status
, 0);
439 chdir ("/"); /* avoid EBUSY */
443 close (2); /* flushing stderr should be silent */
445 if (WIFEXITED (status
))
446 exit (WEXITSTATUS (status
));
448 /* Abnormal termination cannot really be reproduced, so exit
458 /* Execution engines. */
463 void (* exec
) (const char *, int, char **);
469 static char stderr_buffer
[4096];
470 setvbuf (stderr
, stderr_buffer
, _IOFBF
, sizeof stderr_buffer
);
473 /* The default engine: choose a robust method. */
475 exec_default (const char *store
, int argc
, char *argv
[])
477 /* Buffer stderr so that nothing's displayed if 'exec_in_user_namespace'
478 fails but 'exec_with_proot' works. */
481 exec_in_user_namespace (store
, argc
, argv
);
483 exec_with_proot (store
, argc
, argv
);
487 /* The "performance" engine: choose performance over robustness. */
489 exec_performance (const char *store
, int argc
, char *argv
[])
493 exec_in_user_namespace (store
, argc
, argv
);
494 #if HAVE_EXEC_WITH_LOADER
495 exec_with_loader (store
, argc
, argv
);
499 /* List of supported engines. */
500 static const struct engine engines
[] =
502 { "default", exec_default
},
503 { "performance", exec_performance
},
504 { "userns", exec_in_user_namespace
},
506 { "proot", exec_with_proot
},
508 #if HAVE_EXEC_WITH_LOADER
509 { "fakechroot", exec_with_loader
},
514 /* Return the "execution engine" to use. */
515 static const struct engine
*
516 execution_engine (void)
518 const char *str
= getenv ("GUIX_EXECUTION_ENGINE");
524 for (const struct engine
*engine
= engines
;
525 engine
->name
!= NULL
;
528 if (strcmp (engine
->name
, str
) == 0)
532 fprintf (stderr
, "%s: unsupported Guix execution engine; ignoring\n",
540 main (int argc
, char *argv
[])
544 size
= readlink ("/proc/self/exe", self
, sizeof self
- 1);
547 /* SELF is something like "/home/ludo/.local/gnu/store/…-foo/bin/ls" and we
548 want to extract "/home/ludo/.local/gnu/store". */
549 size_t index
= strlen (self
)
550 - strlen ("@WRAPPED_PROGRAM@") + strlen (original_store
);
551 char *store
= strdup (self
);
556 /* If STORE is already at the "right" place, we can execute
557 @WRAPPED_PROGRAM@ right away. This is not just an optimization: it's
558 needed when running one of these wrappers from within an unshare'd
559 namespace, because 'unshare' fails with EPERM in that context. */
560 if (strcmp (store
, original_store
) != 0
561 && lstat ("@WRAPPED_PROGRAM@", &statbuf
) != 0)
563 const struct engine
*engine
= execution_engine ();
564 engine
->exec (store
, argc
, argv
);
566 /* If we reach this point, that's because ENGINE failed to do the
569 This may be because \"user namespaces\" are not supported on this system.\n\
570 Consequently, we cannot run '@WRAPPED_PROGRAM@',\n\
571 unless you move it to the '@STORE_DIRECTORY@' directory.\n\
573 Please refer to the 'guix pack' documentation for more information.\n");
577 /* The executable is available under @STORE_DIRECTORY@, so we can now
579 int err
= execv ("@WRAPPED_PROGRAM@", argv
);
581 assert_perror (errno
);