1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2016, 2017, 2018, 2019 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 (define-module (guix ssh)
20 #:use-module (guix store)
21 #:use-module (guix inferior)
22 #:use-module (guix i18n)
23 #:use-module ((guix utils) #:select (&fix-hint))
24 #:use-module (gcrypt pk-crypto)
25 #:use-module (ssh session)
26 #:use-module (ssh auth)
27 #:use-module (ssh key)
28 #:use-module (ssh channel)
29 #:use-module (ssh popen)
30 #:use-module (ssh session)
31 #:use-module (srfi srfi-1)
32 #:use-module (srfi srfi-11)
33 #:use-module (srfi srfi-26)
34 #:use-module (srfi srfi-34)
35 #:use-module (srfi srfi-35)
36 #:use-module (ice-9 match)
37 #:use-module (ice-9 format)
38 #:use-module (ice-9 binary-ports)
39 #:export (open-ssh-session
44 connect-to-remote-daemon
46 remote-authorize-signing-key
57 ;;; This module provides tools to support communication with remote stores
58 ;;; over SSH, using Guile-SSH.
63 "zlib@openssh.com,zlib")
65 (define (host-key->type+key host-key)
66 "Destructure HOST-KEY, an OpenSSH host key string, and return two values:
67 its key type as a symbol, and the actual base64-encoded string."
68 (define (type->symbol type)
69 (and (string-prefix? "ssh-" type)
70 (string->symbol (string-drop type 4))))
72 (match (string-tokenize host-key)
74 (values (type->symbol type) key))
76 (values (type->symbol type) key))))
78 (define (authenticate-server* session key)
79 "Make sure the server for SESSION has the given KEY, where KEY is a string
80 such as \"ssh-ed25519 AAAAC3Nz… root@example.org\". Raise an exception if the
81 actual key does not match."
82 (let-values (((server) (get-server-public-key session))
83 ((type key) (host-key->type+key key)))
84 (unless (and (or (not (get-key-type server))
85 (eq? (get-key-type server) type))
86 (string=? (public-key->string server) key))
87 ;; Key mismatch: something's wrong. XXX: It could be that the server
88 ;; provided its Ed25519 key when we where expecting its RSA key. XXX:
89 ;; Guile-SSH 0.10.1 doesn't know about ed25519 keys and 'get-key-type'
90 ;; returns #f in that case.
93 (message (format #f (G_ "server at '~a' returned host key \
94 '~a' of type '~a' instead of '~a' of type '~a'~%")
95 (session-get session 'host)
96 (public-key->string server)
100 (define* (open-ssh-session host #:key user port identity
102 (compression %compression)
104 "Open an SSH session for HOST and return it. IDENTITY specifies the file
105 name of a private key to use for authenticating with the host. When USER,
106 PORT, or IDENTITY are #f, use default values or whatever '~/.ssh/config'
107 specifies; otherwise use them.
109 When HOST-KEY is true, it must be a string like \"ssh-ed25519 AAAAC3Nz…
110 root@example.org\"; the server is authenticated and an error is raised if its
111 host key is different from HOST-KEY.
113 Install TIMEOUT as the maximum time in seconds after which a read or write
114 operation on a channel of the returned session is considered as failing.
116 Throw an error on failure."
117 (let ((session (make-session #:user user
121 #:timeout 10 ;seconds
122 ;; #:log-verbosity 'protocol
124 ;; Prevent libssh from reading
125 ;; ~/.ssh/known_hosts when the caller provides
126 ;; a HOST-KEY to match against.
127 #:knownhosts (and host-key "/dev/null")
129 ;; We need lightweight compression when
130 ;; exchanging full archives.
131 #:compression compression
132 #:compression-level 3)))
134 ;; Honor ~/.ssh/config.
135 (session-parse-config! session)
137 (match (connect! session)
140 ;; Make sure the server's key is what we expect.
141 (authenticate-server* session host-key)
143 ;; Authenticate against ~/.ssh/known_hosts.
144 (match (authenticate-server session)
149 (message (format #f (G_ "failed to authenticate \
151 (session-get session 'host)
154 ;; Use public key authentication, via the SSH agent if it's available.
155 (match (userauth-public-key/auto! session)
157 (session-set! session 'timeout timeout)
160 (disconnect! session)
163 (message (format #f (G_ "SSH authentication failed for '~a': ~a~%")
164 host (get-error session)))))))))
166 ;; Connection failed or timeout expired.
169 (message (format #f (G_ "SSH connection to '~a' failed: ~a~%")
170 host (get-error session))))))))))
172 (define* (remote-inferior session #:optional become-command)
173 "Return a remote inferior for the given SESSION. If BECOME-COMMAND is
174 given, use that to invoke the remote Guile REPL."
175 (let* ((repl-command (append (or become-command '())
176 '("guix" "repl" "-t" "machine")))
177 (pipe (apply open-remote-pipe* session OPEN_BOTH repl-command)))
178 (when (eof-object? (peek-char pipe))
179 (let ((status (channel-get-exit-status pipe)))
183 (message (format #f (G_ "remote command '~{~a~^ ~}' failed \
185 repl-command status)))))))
186 (port->inferior pipe)))
188 (define* (inferior-remote-eval exp session #:optional become-command)
189 "Evaluate EXP in a new inferior running in SESSION, and close the inferior
190 right away. If BECOME-COMMAND is given, use that to invoke the remote Guile
192 (let ((inferior (remote-inferior session become-command)))
196 (inferior-eval exp inferior))
198 ;; Close INFERIOR right away to prevent finalization from happening in
199 ;; another thread at the wrong time (see
200 ;; <https://bugs.gnu.org/26976>.)
201 (close-inferior inferior)))))
203 (define* (remote-daemon-channel session
206 "/var/guix/daemon-socket/socket"))
207 "Return an input/output port (an SSH channel) to the daemon at SESSION."
209 ;; Code run in SESSION to redirect the remote process' stdin/stdout to the
210 ;; daemon's socket, à la socat. The SSH protocol supports forwarding to
211 ;; Unix-domain sockets but libssh doesn't have an API for that, hence this
214 (use-modules (ice-9 match) (rnrs io ports)
217 (let ((sock (socket AF_UNIX SOCK_STREAM 0))
218 (stdin (current-input-port))
219 (stdout (current-output-port))
220 (select* (lambda (read write except)
221 ;; This is a workaround for
222 ;; <https://bugs.gnu.org/30365> in Guile < 2.2.4:
223 ;; since 'select' sometimes returns non-empty sets for
224 ;; no good reason, call 'select' a second time with a
225 ;; zero timeout to filter out incorrect replies.
226 (match (select read write except)
228 (select read write except 0))))))
229 (setvbuf stdout 'none)
231 ;; Use buffered ports so that 'get-bytevector-some' returns up to the
232 ;; whole buffer like read(2) would--see <https://bugs.gnu.org/30066>.
233 (setvbuf stdin 'block 65536)
234 (setvbuf sock 'block 65536)
236 (connect sock AF_UNIX ,socket-name)
239 (match (select* (list stdin sock) '() '())
241 (when (memq stdin reads)
242 (match (get-bytevector-some stdin)
246 (put-bytevector sock bv)
247 (force-output sock))))
248 (when (memq sock reads)
249 (match (get-bytevector-some sock)
253 (put-bytevector stdout bv))))
256 (primitive-exit 1)))))))
258 (open-remote-pipe* session OPEN_BOTH
259 ;; Sort-of shell-quote REDIRECT.
262 (object->string redirect))))
264 (define* (connect-to-remote-daemon session
267 "/var/guix/daemon-socket/socket"))
268 "Connect to the remote build daemon listening on SOCKET-NAME over SESSION,
269 an SSH session. Return a <store-connection> object."
270 (open-connection #:port (remote-daemon-channel session socket-name)))
273 (define (store-import-channel session)
274 "Return an output port to which archives to be exported to SESSION's store
276 ;; Using the 'import-paths' RPC on a remote store would be slow because it
277 ;; makes a round trip every time 32 KiB have been transferred. This
278 ;; procedure instead opens a separate channel to use the remote
279 ;; 'import-paths' procedure, which consumes all the data in a single round
280 ;; trip. This optimizes the successful case at the expense of error
281 ;; conditions: errors can only be reported once all the input has been
285 (use-modules (guix) (srfi srfi-34)
286 (rnrs io ports) (rnrs bytevectors))
288 (define (consume-input port)
289 (let ((bv (make-bytevector 32768)))
291 (let ((n (get-bytevector-n! port bv 0
292 (bytevector-length bv))))
293 (unless (eof-object? n)
296 ;; Upon completion, write an sexp that denotes the status.
300 (guard (c ((nix-protocol-error? c)
301 ;; Consume all the input since the only time we can
302 ;; report the error is after everything has been
304 (consume-input (current-input-port))
305 (list 'protocol-error (nix-protocol-error-message c))))
307 (setvbuf (current-input-port) 'none)
308 (import-paths store (current-input-port))
311 (cons 'error args))))))
313 (open-remote-pipe session
316 ,(object->string (object->string import))))
319 (define* (store-export-channel session files
321 "Return an input port from which an export of FILES from SESSION's store can
322 be read. When RECURSIVE? is true, the closure of FILES is exported."
323 ;; Same as above: this is more efficient than calling 'export-paths' on a
327 (eval-when (load expand eval)
328 (unless (resolve-module '(guix) #:ensure #f)
329 (write `(module-error))
332 (use-modules (guix) (srfi srfi-1)
333 (srfi srfi-26) (srfi srfi-34))
335 (guard (c ((nix-connection-error? c)
336 (write `(connection-error ,(nix-connection-error-file c)
337 ,(nix-connection-error-code c))))
338 ((nix-protocol-error? c)
339 (write `(protocol-error ,(nix-protocol-error-status c)
340 ,(nix-protocol-error-message c))))
342 (write `(exception))))
344 (let* ((files ',files)
345 (invalid (remove (cut valid-path? store <>)
347 (unless (null? invalid)
348 (write `(invalid-items ,invalid))
351 ;; TODO: When RECURSIVE? is true, we could send the list of store
352 ;; items in the closure so that the other end can filter out
353 ;; those it already has.
355 (write '(exporting)) ;we're ready
358 (setvbuf (current-output-port) 'none)
359 (export-paths store files (current-output-port)
360 #:recursive? ,recursive?))))))
362 (open-remote-input-pipe session
366 (object->string export))))))
368 (define (remote-system session)
369 "Return the system type as expected by Nix, usually ARCHITECTURE-KERNEL, of
370 the machine on the other end of SESSION."
371 (inferior-remote-eval '(begin (use-modules (guix utils)) (%current-system))
374 (define* (remote-authorize-signing-key key session #:optional become-command)
375 "Send KEY, a canonical sexp containing a public key, over SESSION and add it
376 to the system ACL file if it has not yet been authorized."
377 (inferior-remote-eval
379 (use-modules (guix build utils)
385 (define acl (current-acl))
386 (define key (string->canonical-sexp ,(canonical-sexp->string key)))
388 (unless (authorized-key? key)
389 (let ((acl (public-keys->acl (cons key (acl->public-keys acl)))))
390 (mkdir-p (dirname %acl-file))
391 (with-atomic-file-output %acl-file
392 (cut write-acl acl <>)))))
396 (define* (send-files local files remote
399 (log-port (current-error-port)))
400 "Send the subset of FILES from LOCAL (a local store) that's missing to
401 REMOTE, a remote store. When RECURSIVE? is true, send the closure of FILES.
402 Return the list of store items actually sent."
403 ;; Compute the subset of FILES missing on SESSION and send them.
404 (let* ((files (if recursive? (requisites local files) files))
405 (session (channel-get-session (store-connection-socket remote)))
406 (missing (inferior-remote-eval
409 (srfi srfi-1) (srfi srfi-26))
412 (remove (cut valid-path? store <>)
415 (count (length missing))
416 (sizes (map (lambda (item)
417 (path-info-nar-size (query-path-info local item)))
419 (port (store-import-channel session)))
420 (format log-port (N_ "sending ~a store item (~h MiB) to '~a'...~%"
421 "sending ~a store items (~h MiB) to '~a'...~%" count)
423 (inexact->exact (round (/ (reduce + 0 sizes) (expt 2. 20))))
424 (session-get session 'host))
426 ;; Send MISSING in topological order.
427 (export-paths local missing port)
429 ;; Tell the remote process that we're done. (In theory the end-of-archive
430 ;; mark of 'export-paths' would be enough, but in practice it's not.)
431 (channel-send-eof port)
433 ;; Wait for completion of the remote process and read the status sexp from
434 ;; PORT. Wait for the exit status only when 'read' completed; otherwise,
435 ;; we might wait forever if the other end is stuck.
436 (let* ((result (false-if-exception (read port)))
438 (zero? (channel-get-exit-status port)))))
443 (('protocol-error message)
445 (&store-protocol-error (message message) (status 42)))))
446 (('error key args ...)
448 (&store-protocol-error
449 (message (call-with-output-string
451 (print-exception port #f key args))))
455 (&store-protocol-error
456 (message "unknown error while sending files over SSH")
459 (define (remote-store-session remote)
460 "Return the SSH channel beneath REMOTE, a remote store as returned by
461 'connect-to-remote-daemon', or #f."
462 (channel-get-session (store-connection-socket remote)))
464 (define (remote-store-host remote)
465 "Return the name of the host REMOTE is connected to, where REMOTE is a
466 remote store as returned by 'connect-to-remote-daemon'."
467 (match (remote-store-session remote)
469 ((? session? session)
470 (session-get session 'host))))
472 (define* (file-retrieval-port files remote
474 "Return an input port from which to retrieve FILES (a list of store items)
475 from REMOTE, along with the number of items to retrieve (lower than or equal
476 to the length of FILES.)"
477 (values (store-export-channel (remote-store-session remote) files
478 #:recursive? recursive?)
479 (length files))) ;XXX: inaccurate when RECURSIVE? is true
481 (define-syntax raise-error
483 ((_ fmt args ... (=> hint-fmt hint-args ...))
486 (message (format #f fmt args ...)))
488 (hint (format #f hint-fmt hint-args ...))))))
492 (message (format #f fmt args ...))))))))
494 (define* (retrieve-files* files remote
495 #:key recursive? (log-port (current-error-port))
497 "Pass IMPORT an input port from which to read the sequence of FILES coming
498 from REMOTE. When RECURSIVE? is true, retrieve the closure of FILES."
499 (let-values (((port count)
500 (file-retrieval-port files remote
501 #:recursive? recursive?)))
502 (match (read port) ;read the initial status
504 (format #t (N_ "retrieving ~a store item from '~a'...~%"
505 "retrieving ~a store items from '~a'...~%" count)
506 count (remote-store-host remote))
515 (report-guile-error (remote-store-host remote)))
517 (report-module-error (remote-store-host remote)))
518 (('connection-error file code . _)
519 (raise-error (G_ "failed to connect to '~A' on remote host '~A': ~a")
520 file (remote-store-host remote) (strerror code)))
521 (('invalid-items items . _)
522 (raise-error (N_ "no such item on remote host '~A':~{ ~a~}"
523 "no such items on remote host '~A':~{ ~a~}"
525 (remote-store-host remote) items))
526 (('protocol-error status message . _)
527 (raise-error (G_ "protocol error on remote host '~A': ~a")
528 (remote-store-host remote) message))
530 (raise-error (G_ "failed to retrieve store items from '~a'")
531 (remote-store-host remote))))))
533 (define* (retrieve-files local files remote
534 #:key recursive? (log-port (current-error-port)))
535 "Retrieve FILES from REMOTE and import them using the 'import-paths' RPC on
536 LOCAL. When RECURSIVE? is true, retrieve the closure of FILES."
537 (retrieve-files* (remove (cut valid-path? local <>) files)
539 #:recursive? recursive?
541 #:import (lambda (port)
542 (import-paths local port))))
549 (define (report-guile-error host)
550 (raise-error (G_ "failed to start Guile on remote host '~A'") host
551 (=> (G_ "Make sure @command{guile} can be found in
552 @code{$PATH} on the remote host. Run @command{ssh ~A guile --version} to
556 (define (report-module-error host)
557 "Report an error about missing Guix modules on HOST."
558 ;; TRANSLATORS: Leave "Guile" untranslated.
559 (raise-error (G_ "Guile modules not found on remote host '~A'") host
560 (=> (G_ "Make sure @code{GUILE_LOAD_PATH} includes Guix'
561 own module directory. Run @command{ssh ~A env | grep GUILE_LOAD_PATH} to
565 ;;; ssh.scm ends here