1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2015 David Thompson <davet@gnu.org>
3 ;;; Copyright © 2017, 2018, 2019 Ludovic Courtès <ludo@gnu.org>
5 ;;; This file is part of GNU Guix.
7 ;;; GNU Guix is free software; you can redistribute it and/or modify it
8 ;;; under the terms of the GNU General Public License as published by
9 ;;; the Free Software Foundation; either version 3 of the License, or (at
10 ;;; your option) any later version.
12 ;;; GNU Guix is distributed in the hope that it will be useful, but
13 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;;; GNU General Public License for more details.
17 ;;; You should have received a copy of the GNU General Public License
18 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
20 (define-module (gnu build linux-container)
21 #:use-module (ice-9 format)
22 #:use-module (ice-9 match)
23 #:use-module (ice-9 rdelim)
24 #:use-module (srfi srfi-98)
25 #:use-module (guix build utils)
26 #:use-module (guix build syscalls)
27 #:use-module (gnu system file-systems) ;<file-system>
28 #:use-module ((gnu build file-systems) #:select (mount-file-system))
29 #:export (user-namespace-supported?
30 unprivileged-user-namespace-supported?
36 container-excursion*))
38 (define (user-namespace-supported?)
39 "Return #t if user namespaces are supported on this system."
40 (file-exists? "/proc/self/ns/user"))
42 (define (unprivileged-user-namespace-supported?)
43 "Return #t if user namespaces can be created by unprivileged users."
44 (let ((userns-file "/proc/sys/kernel/unprivileged_userns_clone"))
45 (if (file-exists? userns-file)
46 (eqv? #\1 (call-with-input-file userns-file read-char))
49 (define (setgroups-supported?)
50 "Return #t if the setgroups proc file, introduced in Linux-libre 3.19,
52 (file-exists? "/proc/self/setgroups"))
55 '(mnt pid ipc uts user net))
57 (define (call-with-clean-exit thunk)
58 "Apply THUNK, but exit with a status code of 1 if it fails."
64 ;; XXX: Somehow we sometimes get EBADF from write(2) or close(2) upon
65 ;; exit (coming from fd finalizers) when used by the Shepherd. To work
66 ;; around that, exit forcefully so fd finalizers don't have a chance to
70 (primitive-_exit 1))))
72 (define (purify-environment)
73 "Unset all environment variables."
75 (match (get-environment-variables)
76 (((names . _) ...) names))))
78 ;; The container setup procedure closely resembles that of the Docker
80 ;; https://raw.githubusercontent.com/docker/libcontainer/master/SPEC.md
81 (define* (mount-file-systems root mounts #:key mount-/sys? mount-/proc?)
82 "Mount the essential file systems and the those in MOUNTS, a list of
83 <file-system> objects, relative to ROOT; then make ROOT the new root directory
86 (string-append root dir))
88 (define (touch file-name)
89 (call-with-output-file file-name (const #t)))
91 (define (bind-mount src dest)
92 (mount src dest "none" MS_BIND))
94 ;; Like mount, but creates the mount point if it doesn't exist.
95 (define* (mount* source target type #:optional (flags 0) options
96 #:key (update-mtab? #f))
98 (mount source target type flags options #:update-mtab? update-mtab?))
100 ;; The container's file system is completely ephemeral, sans directories
101 ;; bind-mounted from the host.
102 (mount "none" root "tmpfs")
104 ;; A proc mount requires a new pid namespace.
106 (mount* "none" (scope "/proc") "proc"
107 (logior MS_NOEXEC MS_NOSUID MS_NODEV)))
109 ;; A sysfs mount requires the user to have the CAP_SYS_ADMIN capability in
110 ;; the current network namespace.
112 (mount* "none" (scope "/sys") "sysfs"
113 (logior MS_NOEXEC MS_NOSUID MS_NODEV MS_RDONLY)))
115 (mount* "none" (scope "/dev") "tmpfs"
116 (logior MS_NOEXEC MS_STRICTATIME)
119 ;; Create essential device nodes via bind-mounting them from the
120 ;; host, because a process within a user namespace cannot create
122 (for-each (lambda (device)
123 (when (file-exists? device)
124 ;; Create the mount point file.
125 (touch (scope device))
126 (bind-mount device (scope device))))
135 ;; Mount a new devpts instance on /dev/pts.
136 (when (file-exists? "/dev/ptmx")
137 (mount* "none" (scope "/dev/pts") "devpts" 0
138 "newinstance,mode=0620")
139 (symlink "/dev/pts/ptmx" (scope "/dev/ptmx")))
141 ;; Setup the container's /dev/console by bind mounting the pseudo-terminal
142 ;; associated with standard input when there is one.
143 (let* ((in (current-input-port))
144 (tty (catch 'system-error
146 ;; This call throws if IN does not correspond to a tty.
147 ;; This is more reliable than 'isatty?'.
150 (console (scope "/dev/console")))
153 (chmod console #o600)
154 (bind-mount tty console)))
156 ;; Setup standard input/output/error.
157 (symlink "/proc/self/fd" (scope "/dev/fd"))
158 (symlink "/proc/self/fd/0" (scope "/dev/stdin"))
159 (symlink "/proc/self/fd/1" (scope "/dev/stdout"))
160 (symlink "/proc/self/fd/2" (scope "/dev/stderr"))
162 ;; Mount user-specified file systems.
163 (for-each (lambda (file-system)
164 (mount-file-system file-system #:root root))
167 ;; Jail the process inside the container's root file system.
168 (let ((put-old (string-append root "/real-root")))
170 (pivot-root root put-old)
172 (umount "real-root" MNT_DETACH)
173 (rmdir "real-root")))
175 (define* (initialize-user-namespace pid host-uids
176 #:key (guest-uid 0) (guest-gid 0))
177 "Configure the user namespace for PID. HOST-UIDS specifies the number of
178 host user identifiers to map into the user namespace. GUEST-UID and GUEST-GID
179 specify the first UID (respectively GID) that host UIDs (respectively GIDs)
180 map to in the namespace."
182 (string-append "/proc/" (number->string pid)))
185 (string-append proc-dir file))
190 ;; Only root can write to the gid map without first disabling the
191 ;; setgroups syscall.
192 (unless (and (zero? uid) (zero? gid))
193 (call-with-output-file (scope "/setgroups")
195 (display "deny" port))))
197 ;; Map the user/group that created the container to the root user
198 ;; within the container.
199 (call-with-output-file (scope "/uid_map")
201 (format port "~d ~d ~d" guest-uid uid host-uids)))
202 (call-with-output-file (scope "/gid_map")
204 (format port "~d ~d ~d" guest-gid gid host-uids)))))
206 (define (namespaces->bit-mask namespaces)
207 "Return the number suitable for the 'flags' argument of 'clone' that
208 corresponds to the symbols in NAMESPACES."
209 ;; Use the same flags as fork(3) in addition to the namespace flags.
210 (apply logior SIGCHLD
215 ('user CLONE_NEWUSER)
220 (define* (run-container root mounts namespaces host-uids thunk
221 #:key (guest-uid 0) (guest-gid 0))
222 "Run THUNK in a new container process and return its PID. ROOT specifies
223 the root directory for the container. MOUNTS is a list of <file-system>
224 objects that specify file systems to mount inside the container. NAMESPACES
225 is a list of symbols that correspond to the possible Linux namespaces: mnt,
226 ipc, uts, user, and net.
228 HOST-UIDS specifies the number of host user identifiers to map into the user
229 namespace. GUEST-UID and GUEST-GID specify the first UID (respectively GID)
230 that host UIDs (respectively GIDs) map to in the namespace."
231 ;; The parent process must initialize the user namespace for the child
232 ;; before it can boot. To negotiate this, a pipe is used such that the
233 ;; child process blocks until the parent writes to it.
234 (match (socketpair PF_UNIX SOCK_STREAM 0)
236 (let ((flags (namespaces->bit-mask namespaces)))
239 (call-with-clean-exit
242 ;; Wait for parent to set things up.
246 (when (memq 'mnt namespaces)
249 (mount-file-systems root mounts
250 #:mount-/proc? (memq 'pid namespaces)
251 #:mount-/sys? (memq 'net
254 ;; Forward the exception to the parent process.
255 ;; FIXME: SRFI-35 conditions and non-trivial objects
256 ;; cannot be 'read' so they shouldn't be written as is.
258 (primitive-exit 3))))
259 ;; TODO: Manage capabilities.
263 (_ ;parent died or something
264 (primitive-exit 2))))))
267 (when (memq 'user namespaces)
268 (initialize-user-namespace pid host-uids
269 #:guest-uid guest-uid
270 #:guest-gid guest-gid))
271 ;; TODO: Initialize cgroups.
272 (write 'ready parent)
275 ;; Check whether the child process' setup phase succeeded.
276 (let ((message (read parent)))
281 (((? symbol? key) args ...) ;exception
282 (apply throw key args))
283 (_ ;unexpected termination
286 ;; FIXME: This is copied from (guix utils), which we cannot use because it
287 ;; would pull (guix config) and all.
288 (define (call-with-temporary-directory proc)
289 "Call PROC with a name of a temporary directory; close the directory and
290 delete it when leaving the dynamic extent of this call."
291 (let* ((directory (or (getenv "TMPDIR") "/tmp"))
292 (template (string-append directory "/guix-directory.XXXXXX"))
293 (tmp-dir (mkdtemp! template)))
299 (false-if-exception (delete-file-recursively tmp-dir))))))
301 (define* (call-with-container mounts thunk #:key (namespaces %namespaces)
302 (host-uids 1) (guest-uid 0) (guest-gid 0)
303 (process-spawned-hook (const #t)))
304 "Run THUNK in a new container process and return its exit status; call
305 PROCESS-SPAWNED-HOOK with the PID of the new process that has been spawned.
306 MOUNTS is a list of <file-system> objects that specify file systems to mount
307 inside the container. NAMESPACES is a list of symbols corresponding to
308 the identifiers for Linux namespaces: mnt, ipc, uts, pid, user, and net. By
309 default, all namespaces are used.
311 HOST-UIDS is the number of host user identifiers to map into the container's
312 user namespace, if there is one. By default, only a single uid/gid, that of
313 the current user, is mapped into the container. The host user that creates
314 the container is the root user (uid/gid 0) within the container. Only root
315 can map more than a single uid/gid.
317 GUEST-UID and GUEST-GID specify the first UID (respectively GID) that host
318 UIDs (respectively GIDs) map to in the namespace.
320 Note that if THUNK needs to load any additional Guile modules, the relevant
321 module files must be present in one of the mappings in MOUNTS and the Guile
322 load path must be adjusted as needed."
323 (call-with-temporary-directory
325 (let ((pid (run-container root mounts namespaces host-uids thunk
326 #:guest-uid guest-uid
327 #:guest-gid guest-gid)))
328 ;; Catch SIGINT and kill the container process.
332 (kill pid SIGKILL))))
334 (process-spawned-hook pid)
336 ((_ . status) status))))))
338 (define (container-excursion pid thunk)
339 "Run THUNK as a child process within the namespaces of process PID and
340 return the exit status."
341 (define (namespace-file pid namespace)
342 (string-append "/proc/" (number->string pid) "/ns/" namespace))
344 (match (primitive-fork)
346 (call-with-clean-exit
348 (for-each (lambda (ns)
349 (let ((source (namespace-file (getpid) ns))
350 (target (namespace-file pid ns)))
351 ;; Joining the namespace that the process already
352 ;; belongs to would throw an error so avoid that.
353 ;; XXX: This /proc interface leads to TOCTTOU.
354 (unless (string=? (readlink source) (readlink target))
355 (call-with-input-file source
356 (lambda (current-ns-port)
357 (call-with-input-file target
358 (lambda (new-ns-port)
359 (setns (fileno new-ns-port) 0))))))))
360 ;; It's important that the user namespace is joined first,
361 ;; so that the user will have the privileges to join the
362 ;; other namespaces. Furthermore, it's important that the
363 ;; mount namespace is joined last, otherwise the /proc mount
364 ;; point would no longer be accessible.
365 '("user" "ipc" "uts" "net" "pid" "mnt"))
372 (status:exit-val status))))))
374 (define (container-excursion* pid thunk)
375 "Like 'container-excursion', but return the return value of THUNK."
378 (match (container-excursion pid
385 (let ((result (read in)))
388 (_ ;maybe PID died already