aboutsummaryrefslogtreecommitdiff
path: root/nix/scripts/list-runtime-roots.in
blob: 5f2660fb5e67f50162335e54c107fd59c20ad7bd (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#!@GUILE@ -ds
!#
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2012, 2013, 2014, 2017 Ludovic Courtès <ludo@gnu.org>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

;;;
;;; List files being used at run time; these files are garbage collector
;;; roots.  This is equivalent to `find-runtime-roots.pl' in Nix.
;;;

(use-modules (ice-9 ftw)
             (ice-9 regex)
             (ice-9 rdelim)
             (ice-9 match)
             (srfi srfi-1)
             (srfi srfi-26)
             (rnrs io ports))

(define %proc-directory
  ;; Mount point of Linuxish /proc file system.
  "/proc")

(define %store-directory
  (or (getenv "NIX_STORE_DIR")
      "@storedir@"))

(define (proc-file-roots dir file)
  "Return a one-element list containing the file pointed to by DIR/FILE,
or the empty list."
  (or (and=> (false-if-exception (readlink (string-append dir "/" file)))
             list)
      '()))

(define proc-exe-roots (cut proc-file-roots <> "exe"))
(define proc-cwd-roots (cut proc-file-roots <> "cwd"))

(define (proc-fd-roots dir)
  "Return the list of store files referenced by DIR, which is a
/proc/XYZ directory."
  (let ((dir (string-append dir "/fd")))
    (filter-map (lambda (file)
                  (let ((target (false-if-exception
                                 (readlink (string-append dir "/" file)))))
                    (and target
                         (string-prefix? "/" target)
                         target)))
                (or (scandir dir string->number) '()))))

(define (proc-maps-roots dir)
  "Return the list of store files referenced by DIR, which is a
/proc/XYZ directory."
  (define %file-mapping-line
    (make-regexp "^.*[[:blank:]]+/([^ ]+)$"))

  (call-with-input-file (string-append dir "/maps")
    (lambda (maps)
      (let loop ((line  (read-line maps))
                 (roots '()))
        (cond ((eof-object? line)
               roots)
              ((regexp-exec %file-mapping-line line)
               =>
               (lambda (match)
                 (let ((file (string-append "/"
                                            (match:substring match 1))))
                   (loop (read-line maps)
                         (cons file roots)))))
              (else
               (loop (read-line maps) roots)))))))

(define (proc-environ-roots dir)
  "Return the list of store files referenced by DIR/environ, where DIR is a
/proc/XYZ directory."
  (define split-on-nul
    (cute string-tokenize <>
          (char-set-complement (char-set #\nul))))

  (define (rhs-file-names str)
    (let ((equal (string-index str #\=)))
      (if equal
          (let* ((str (substring str (+ 1 equal)))
                 (rx  (string-append (regexp-quote %store-directory)
                                     "/[0-9a-z]{32}-[a-zA-Z0-9\\._+-]+")))
            (map match:substring (list-matches rx str)))
          '())))

  (define environ
    (string-append dir "/environ"))

  (append-map rhs-file-names
              (split-on-nul
               (call-with-input-file environ
                 get-string-all))))

(define (referenced-files)
  "Return the list of referenced store items."
  (append-map (lambda (pid)
                (let ((proc (string-append %proc-directory "/" pid)))
                  (catch 'system-error
                    (lambda ()
                      (append (proc-exe-roots proc)
                              (proc-cwd-roots proc)
                              (proc-fd-roots proc)
                              (proc-maps-roots proc)
                              (proc-environ-roots proc)))
                    (lambda args
                      (let ((err (system-error-errno args)))
                        (if (or (= ENOENT err)    ;TOCTTOU race
                                (= ESRCH err)     ;ditto
                                (= EACCES err))   ;not running as root
                            '()
                            (apply throw args)))))))
              (scandir %proc-directory string->number
                       (lambda (a b)
                         (< (string->number a) (string->number b))))))

(define canonicalize-store-item
  (let* ((store  (string-append %store-directory "/"))
         (prefix (string-length store)))
    (lambda (file)
      "Return #f if FILE is not a store item; otherwise, return the store file
name without any sub-directory components."
      (and (string-prefix? store file)
           (string-append store
                          (let ((base (string-drop file prefix)))
                            (match (string-index base #\/)
                              (#f    base)
                              (slash (string-take base slash)))))))))

(for-each (cut simple-format #t "~a~%" <>)
          (delete-duplicates
           (filter-map canonicalize-store-item (referenced-files))))
source of static files for /etc." ;; /etc is a mixture of static and dynamic settings. Here is where we ;; initialize it from the static part. (define (rm-f file) (false-if-exception (delete-file file))) (format #t "populating /etc from ~a...~%" etc) (mkdir-p "/etc") ;; Create the /etc/ssl -> /run/current-system/profile/etc/ssl symlink. This ;; symlink, to a target outside of the store, probably doesn't belong in the ;; static 'etc' store directory. However, if it were to be put there, ;; beware that if /run/current-system/profile/etc/ssl doesn't exist at the ;; time of activation (e.g. when installing a fresh system), the call to ;; 'file-is-directory?' below will fail because it uses 'stat', not 'lstat'. (rm-f "/etc/ssl") (symlink "/run/current-system/profile/etc/ssl" "/etc/ssl") (rm-f "/etc/static") (symlink etc "/etc/static") (for-each (lambda (file) (let ((target (string-append "/etc/" file)) (source (string-append "/etc/static/" file))) (rm-f target) ;; Things such as /etc/sudoers must be regular files, not ;; symlinks; furthermore, they could be modified behind our ;; back---e.g., with 'visudo'. Thus, make a copy instead of ;; symlinking them. (if (file-is-directory? source) (symlink source target) (copy-file source target)) ;; XXX: Dirty hack to meet sudo's expectations. (when (string=? (basename target) "sudoers") (chmod target #o440)))) (scandir etc (negate dot-or-dot-dot?) ;; The default is 'string-locale<?', but we don't have ;; it when run from the initrd's statically-linked ;; Guile. string<?))) (define %setuid-directory ;; Place where setuid programs used to be stored. It exists for backwards ;; compatibility & will be removed. Use %PRIVILEGED-PROGRAM-DIRECTORY instead. "/run/setuid-programs") (define %privileged-program-directory ;; Place where privileged copies of programs are stored. "/run/privileged/bin") (define (activate-privileged-programs programs libcap) "Turn PROGRAMS, a list of file privileged-programs records, into privileged copies stored under %PRIVILEGED-PROGRAM-DIRECTORY, using LIBCAP's setcap(8) binary if needed." (define (ensure-empty-directory directory) (if (file-exists? directory) (for-each (compose delete-file (cut string-append directory "/" <>)) (scandir directory (lambda (file) (not (member file '("." "..")))) string<?)) (mkdir-p directory)) ) (define (make-privileged-program program setuid? setgid? uid gid capabilities) (let ((target (string-append %privileged-program-directory "/" (basename program))) (mode (+ #o0555 ; base permissions (if setuid? #o4000 0) ; setuid bit (if setgid? #o2000 0)))) ; setgid bit (copy-file program target) (chown target uid gid) (chmod target mode) (when (and capabilities libcap) (system* (string-append libcap "/sbin/setcap") "-q" capabilities target)))) (define (make-deprecated-wrapper program) ;; This will eventually become a script that warns on usage, then vanish. (symlink (string-append %privileged-program-directory "/" (basename program)) (string-append %setuid-directory "/" (basename program)))) (format #t "setting up privileged programs in '~a'...~%" %privileged-program-directory) (ensure-empty-directory %privileged-program-directory) (ensure-empty-directory %setuid-directory) (for-each (lambda (program) (catch 'system-error (lambda () (let* ((program-name (privileged-program-program program)) (setuid? (privileged-program-setuid? program)) (setgid? (privileged-program-setgid? program)) (user (privileged-program-user program)) (group (privileged-program-group program)) (capabilities (privileged-program-capabilities program)) (uid (match user ((? string?) (passwd:uid (getpwnam user))) ((? integer?) user))) (gid (match group ((? string?) (group:gid (getgrnam group))) ((? integer?) group)))) (make-privileged-program program-name setuid? setgid? uid gid capabilities) (make-deprecated-wrapper program-name))) (lambda args ;; If we fail to create a privileged program, better keep going ;; so that we don't leave %PRIVILEGED-PROGRAM-DIRECTORY empty ;; or half-populated. This can happen if PROGRAMS contains ;; incorrect file names: <https://bugs.gnu.org/38800>. (format (current-error-port) "warning: failed to privilege ~s: ~a~%" (privileged-program-program program) (strerror (system-error-errno args)))))) programs)) (define (activate-special-files special-files) "Install the files listed in SPECIAL-FILES. Each element of SPECIAL-FILES is a pair where the first element is the name of the special file and the second element is the name it should appear at, such as: ((\"/bin/sh\" \"/gnu/store/…-bash/bin/sh\") (\"/usr/bin/env\" \"/gnu/store/…-coreutils/bin/env\")) " (define install-special-file (match-lambda ((target file) (let ((pivot (string-append target ".new"))) (mkdir-p (dirname target)) (symlink file pivot) (rename-file pivot target))))) (for-each install-special-file special-files)) (define (activate-modprobe modprobe) "Tell the kernel to use MODPROBE to load modules." ;; If the kernel was built without loadable module support, this file is ;; unavailable, so check for its existence first. (when (file-exists? "/proc/sys/kernel/modprobe") (call-with-output-file "/proc/sys/kernel/modprobe" (lambda (port) (display modprobe port))))) (define (activate-firmware directory) "Tell the kernel to look for device firmware under DIRECTORY. This mechanism bypasses udev: it allows Linux to handle firmware loading directly by itself, without having to resort to a \"user helper\"." ;; If the kernel was built without firmware loading support, this file ;; does not exist. Do nothing in that case. (let ((firmware-path "/sys/module/firmware_class/parameters/path")) (when (file-exists? firmware-path) (call-with-output-file firmware-path (lambda (port) (display directory port)))))) (define (activate-ptrace-attach) "Allow users to PTRACE_ATTACH their own processes. This works around a regression introduced in the default \"security\" policy found in Linux 3.4 onward that prevents users from attaching to their own processes--see Yama.txt in the Linux source tree for the rationale. This sounds like an unacceptable restriction for little or no security improvement." (let ((file "/proc/sys/kernel/yama/ptrace_scope")) (when (file-exists? file) (call-with-output-file file (lambda (port) (display 0 port)))))) (define %current-system ;; The system that is current (a symlink.) This is not necessarily the same ;; as the system we booted (aka. /run/booted-system) because we can re-build ;; a new system configuration and activate it, without rebooting. "/run/current-system") (define (boot-time-system) "Return the 'gnu.system' argument passed on the kernel command line." (find-long-option "gnu.system" (if (string-contains %host-type "linux-gnu") (linux-command-line) (command-line)))) (define* (activate-current-system #:optional (system (or (getenv "GUIX_NEW_SYSTEM") (boot-time-system)))) "Atomically make SYSTEM the current system." ;; The 'GUIX_NEW_SYSTEM' environment variable is used as a way for 'guix ;; system reconfigure' to pass the file name of the new system. (format #t "making '~a' the current system...~%" system) (mkdir-p "/run") ;; Atomically make SYSTEM current. (let ((new (string-append %current-system ".new"))) (symlink system new) (rename-file new %current-system))) ;;; activation.scm ends here