linux-container.scm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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>
  4. ;;;
  5. ;;; This file is part of GNU Guix.
  6. ;;;
  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.
  11. ;;;
  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.
  16. ;;;
  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/>.
  19. (define-module (gnu build linux-container)
  20. #:use-module (ice-9 format)
  21. #:use-module (ice-9 match)
  22. #:use-module (ice-9 rdelim)
  23. #:use-module (srfi srfi-98)
  24. #:use-module (guix build utils)
  25. #:use-module (guix build syscalls)
  26. #:use-module (gnu system file-systems) ;<file-system>
  27. #:use-module ((gnu build file-systems) #:select (mount-file-system))
  28. #:export (user-namespace-supported?
  29. unprivileged-user-namespace-supported?
  30. setgroups-supported?
  31. %namespaces
  32. run-container
  33. call-with-container
  34. container-excursion
  35. container-excursion*))
  36. (define (user-namespace-supported?)
  37. "Return #t if user namespaces are supported on this system."
  38. (file-exists? "/proc/self/ns/user"))
  39. (define (unprivileged-user-namespace-supported?)
  40. "Return #t if user namespaces can be created by unprivileged users."
  41. (let ((userns-file "/proc/sys/kernel/unprivileged_userns_clone"))
  42. (if (file-exists? userns-file)
  43. (eqv? #\1 (call-with-input-file userns-file read-char))
  44. #t)))
  45. (define (setgroups-supported?)
  46. "Return #t if the setgroups proc file, introduced in Linux-libre 3.19,
  47. exists."
  48. (file-exists? "/proc/self/setgroups"))
  49. (define %namespaces
  50. '(mnt pid ipc uts user net))
  51. (define (call-with-clean-exit thunk)
  52. "Apply THUNK, but exit with a status code of 1 if it fails."
  53. (dynamic-wind
  54. (const #t)
  55. (lambda ()
  56. (thunk)
  57. ;; XXX: Somehow we sometimes get EBADF from write(2) or close(2) upon
  58. ;; exit (coming from fd finalizers) when used by the Shepherd. To work
  59. ;; around that, exit forcefully so fd finalizers don't have a chance to
  60. ;; run and fail.
  61. (primitive-_exit 0))
  62. (lambda ()
  63. (primitive-_exit 1))))
  64. (define (purify-environment)
  65. "Unset all environment variables."
  66. (for-each unsetenv
  67. (match (get-environment-variables)
  68. (((names . _) ...) names))))
  69. ;; The container setup procedure closely resembles that of the Docker
  70. ;; specification:
  71. ;; https://raw.githubusercontent.com/docker/libcontainer/master/SPEC.md
  72. (define* (mount-file-systems root mounts #:key mount-/sys? mount-/proc?)
  73. "Mount the essential file systems and the those in MOUNTS, a list of
  74. <file-system> objects, relative to ROOT; then make ROOT the new root directory
  75. for the process."
  76. (define (scope dir)
  77. (string-append root dir))
  78. (define (touch file-name)
  79. (call-with-output-file file-name (const #t)))
  80. (define (bind-mount src dest)
  81. (mount src dest "none" MS_BIND))
  82. ;; Like mount, but creates the mount point if it doesn't exist.
  83. (define* (mount* source target type #:optional (flags 0) options
  84. #:key (update-mtab? #f))
  85. (mkdir-p target)
  86. (mount source target type flags options #:update-mtab? update-mtab?))
  87. ;; The container's file system is completely ephemeral, sans directories
  88. ;; bind-mounted from the host.
  89. (mount "none" root "tmpfs")
  90. ;; A proc mount requires a new pid namespace.
  91. (when mount-/proc?
  92. (mount* "none" (scope "/proc") "proc"
  93. (logior MS_NOEXEC MS_NOSUID MS_NODEV)))
  94. ;; A sysfs mount requires the user to have the CAP_SYS_ADMIN capability in
  95. ;; the current network namespace.
  96. (when mount-/sys?
  97. (mount* "none" (scope "/sys") "sysfs"
  98. (logior MS_NOEXEC MS_NOSUID MS_NODEV MS_RDONLY)))
  99. (mount* "none" (scope "/dev") "tmpfs"
  100. (logior MS_NOEXEC MS_STRICTATIME)
  101. "mode=755")
  102. ;; Create essential device nodes via bind-mounting them from the
  103. ;; host, because a process within a user namespace cannot create
  104. ;; device nodes.
  105. (for-each (lambda (device)
  106. (when (file-exists? device)
  107. ;; Create the mount point file.
  108. (touch (scope device))
  109. (bind-mount device (scope device))))
  110. '("/dev/null"
  111. "/dev/zero"
  112. "/dev/full"
  113. "/dev/random"
  114. "/dev/urandom"
  115. "/dev/tty"
  116. "/dev/fuse"))
  117. ;; Mount a new devpts instance on /dev/pts.
  118. (when (file-exists? "/dev/ptmx")
  119. (mount* "none" (scope "/dev/pts") "devpts" 0
  120. "newinstance,mode=0620")
  121. (symlink "/dev/pts/ptmx" (scope "/dev/ptmx")))
  122. ;; Setup the container's /dev/console by bind mounting the pseudo-terminal
  123. ;; associated with standard input when there is one.
  124. (let* ((in (current-input-port))
  125. (tty (catch 'system-error
  126. (lambda ()
  127. ;; This call throws if IN does not correspond to a tty.
  128. ;; This is more reliable than 'isatty?'.
  129. (ttyname in))
  130. (const #f)))
  131. (console (scope "/dev/console")))
  132. (when tty
  133. (touch console)
  134. (chmod console #o600)
  135. (bind-mount tty console)))
  136. ;; Setup standard input/output/error.
  137. (symlink "/proc/self/fd" (scope "/dev/fd"))
  138. (symlink "/proc/self/fd/0" (scope "/dev/stdin"))
  139. (symlink "/proc/self/fd/1" (scope "/dev/stdout"))
  140. (symlink "/proc/self/fd/2" (scope "/dev/stderr"))
  141. ;; Mount user-specified file systems.
  142. (for-each (lambda (file-system)
  143. (mount-file-system file-system #:root root))
  144. mounts)
  145. ;; Jail the process inside the container's root file system.
  146. (let ((put-old (string-append root "/real-root")))
  147. (mkdir put-old)
  148. (pivot-root root put-old)
  149. (chdir "/")
  150. (umount "real-root" MNT_DETACH)
  151. (rmdir "real-root")))
  152. (define* (initialize-user-namespace pid host-uids
  153. #:key (guest-uid 0) (guest-gid 0))
  154. "Configure the user namespace for PID. HOST-UIDS specifies the number of
  155. host user identifiers to map into the user namespace. GUEST-UID and GUEST-GID
  156. specify the first UID (respectively GID) that host UIDs (respectively GIDs)
  157. map to in the namespace."
  158. (define proc-dir
  159. (string-append "/proc/" (number->string pid)))
  160. (define (scope file)
  161. (string-append proc-dir file))
  162. (let ((uid (getuid))
  163. (gid (getgid)))
  164. ;; Only root can write to the gid map without first disabling the
  165. ;; setgroups syscall.
  166. (unless (and (zero? uid) (zero? gid))
  167. (call-with-output-file (scope "/setgroups")
  168. (lambda (port)
  169. (display "deny" port))))
  170. ;; Map the user/group that created the container to the root user
  171. ;; within the container.
  172. (call-with-output-file (scope "/uid_map")
  173. (lambda (port)
  174. (format port "~d ~d ~d" guest-uid uid host-uids)))
  175. (call-with-output-file (scope "/gid_map")
  176. (lambda (port)
  177. (format port "~d ~d ~d" guest-gid gid host-uids)))))
  178. (define (namespaces->bit-mask namespaces)
  179. "Return the number suitable for the 'flags' argument of 'clone' that
  180. corresponds to the symbols in NAMESPACES."
  181. ;; Use the same flags as fork(3) in addition to the namespace flags.
  182. (apply logior SIGCHLD
  183. (map (match-lambda
  184. ('mnt CLONE_NEWNS)
  185. ('uts CLONE_NEWUTS)
  186. ('ipc CLONE_NEWIPC)
  187. ('user CLONE_NEWUSER)
  188. ('pid CLONE_NEWPID)
  189. ('net CLONE_NEWNET))
  190. namespaces)))
  191. (define* (run-container root mounts namespaces host-uids thunk
  192. #:key (guest-uid 0) (guest-gid 0))
  193. "Run THUNK in a new container process and return its PID. ROOT specifies
  194. the root directory for the container. MOUNTS is a list of <file-system>
  195. objects that specify file systems to mount inside the container. NAMESPACES
  196. is a list of symbols that correspond to the possible Linux namespaces: mnt,
  197. ipc, uts, user, and net.
  198. HOST-UIDS specifies the number of host user identifiers to map into the user
  199. namespace. GUEST-UID and GUEST-GID specify the first UID (respectively GID)
  200. that host UIDs (respectively GIDs) map to in the namespace."
  201. ;; The parent process must initialize the user namespace for the child
  202. ;; before it can boot. To negotiate this, a pipe is used such that the
  203. ;; child process blocks until the parent writes to it.
  204. (match (socketpair PF_UNIX SOCK_STREAM 0)
  205. ((child . parent)
  206. (let ((flags (namespaces->bit-mask namespaces)))
  207. (match (clone flags)
  208. (0
  209. (call-with-clean-exit
  210. (lambda ()
  211. (close-port parent)
  212. ;; Wait for parent to set things up.
  213. (match (read child)
  214. ('ready
  215. (purify-environment)
  216. (when (memq 'mnt namespaces)
  217. (catch #t
  218. (lambda ()
  219. (mount-file-systems root mounts
  220. #:mount-/proc? (memq 'pid namespaces)
  221. #:mount-/sys? (memq 'net
  222. namespaces)))
  223. (lambda args
  224. ;; Forward the exception to the parent process.
  225. ;; FIXME: SRFI-35 conditions and non-trivial objects
  226. ;; cannot be 'read' so they shouldn't be written as is.
  227. (write args child)
  228. (primitive-exit 3))))
  229. ;; TODO: Manage capabilities.
  230. (write 'ready child)
  231. (close-port child)
  232. (thunk))
  233. (_ ;parent died or something
  234. (primitive-exit 2))))))
  235. (pid
  236. (close-port child)
  237. (when (memq 'user namespaces)
  238. (initialize-user-namespace pid host-uids
  239. #:guest-uid guest-uid
  240. #:guest-gid guest-gid))
  241. ;; TODO: Initialize cgroups.
  242. (write 'ready parent)
  243. (newline parent)
  244. ;; Check whether the child process' setup phase succeeded.
  245. (let ((message (read parent)))
  246. (close-port parent)
  247. (match message
  248. ('ready ;success
  249. pid)
  250. (((? symbol? key) args ...) ;exception
  251. (apply throw key args))
  252. (_ ;unexpected termination
  253. #f)))))))))
  254. ;; FIXME: This is copied from (guix utils), which we cannot use because it
  255. ;; would pull (guix config) and all.
  256. (define (call-with-temporary-directory proc)
  257. "Call PROC with a name of a temporary directory; close the directory and
  258. delete it when leaving the dynamic extent of this call."
  259. (let* ((directory (or (getenv "TMPDIR") "/tmp"))
  260. (template (string-append directory "/guix-directory.XXXXXX"))
  261. (tmp-dir (mkdtemp! template)))
  262. (dynamic-wind
  263. (const #t)
  264. (lambda ()
  265. (proc tmp-dir))
  266. (lambda ()
  267. (false-if-exception (delete-file-recursively tmp-dir))))))
  268. (define* (call-with-container mounts thunk #:key (namespaces %namespaces)
  269. (host-uids 1) (guest-uid 0) (guest-gid 0)
  270. (process-spawned-hook (const #t)))
  271. "Run THUNK in a new container process and return its exit status; call
  272. PROCESS-SPAWNED-HOOK with the PID of the new process that has been spawned.
  273. MOUNTS is a list of <file-system> objects that specify file systems to mount
  274. inside the container. NAMESPACES is a list of symbols corresponding to
  275. the identifiers for Linux namespaces: mnt, ipc, uts, pid, user, and net. By
  276. default, all namespaces are used.
  277. HOST-UIDS is the number of host user identifiers to map into the container's
  278. user namespace, if there is one. By default, only a single uid/gid, that of
  279. the current user, is mapped into the container. The host user that creates
  280. the container is the root user (uid/gid 0) within the container. Only root
  281. can map more than a single uid/gid.
  282. GUEST-UID and GUEST-GID specify the first UID (respectively GID) that host
  283. UIDs (respectively GIDs) map to in the namespace.
  284. Note that if THUNK needs to load any additional Guile modules, the relevant
  285. module files must be present in one of the mappings in MOUNTS and the Guile
  286. load path must be adjusted as needed."
  287. (call-with-temporary-directory
  288. (lambda (root)
  289. (let ((pid (run-container root mounts namespaces host-uids thunk
  290. #:guest-uid guest-uid
  291. #:guest-gid guest-gid)))
  292. ;; Catch SIGINT and kill the container process.
  293. (sigaction SIGINT
  294. (lambda (signum)
  295. (false-if-exception
  296. (kill pid SIGKILL))))
  297. (process-spawned-hook pid)
  298. (match (waitpid pid)
  299. ((_ . status) status))))))
  300. (define (container-excursion pid thunk)
  301. "Run THUNK as a child process within the namespaces of process PID and
  302. return the exit status."
  303. (define (namespace-file pid namespace)
  304. (string-append "/proc/" (number->string pid) "/ns/" namespace))
  305. (match (primitive-fork)
  306. (0
  307. (call-with-clean-exit
  308. (lambda ()
  309. (for-each (lambda (ns)
  310. (let ((source (namespace-file (getpid) ns))
  311. (target (namespace-file pid ns)))
  312. ;; Joining the namespace that the process already
  313. ;; belongs to would throw an error so avoid that.
  314. ;; XXX: This /proc interface leads to TOCTTOU.
  315. (unless (string=? (readlink source) (readlink target))
  316. (call-with-input-file source
  317. (lambda (current-ns-port)
  318. (call-with-input-file target
  319. (lambda (new-ns-port)
  320. (setns (fileno new-ns-port) 0))))))))
  321. ;; It's important that the user namespace is joined first,
  322. ;; so that the user will have the privileges to join the
  323. ;; other namespaces. Furthermore, it's important that the
  324. ;; mount namespace is joined last, otherwise the /proc mount
  325. ;; point would no longer be accessible.
  326. '("user" "ipc" "uts" "net" "pid" "mnt"))
  327. (purify-environment)
  328. (chdir "/")
  329. (thunk))))
  330. (pid
  331. (match (waitpid pid)
  332. ((_ . status)
  333. (status:exit-val status))))))
  334. (define (container-excursion* pid thunk)
  335. "Like 'container-excursion', but return the return value of THUNK."
  336. (match (pipe)
  337. ((in . out)
  338. (match (container-excursion pid
  339. (lambda ()
  340. (close-port in)
  341. (write (thunk) out)
  342. (close-port out)))
  343. (0
  344. (close-port out)
  345. (let ((result (read in)))
  346. (close-port in)
  347. result))
  348. (_ ;maybe PID died already
  349. (close-port out)
  350. (close-port in)
  351. #f)))))