ssh: Always authenticate the server [security fix].
[jackhill/guix/guix.git] / guix / ssh.scm
CommitLineData
987a29ba 1;;; GNU Guix --- Functional package management for GNU
76832d34 2;;; Copyright © 2016, 2017, 2018, 2019 Ludovic Courtès <ludo@gnu.org>
987a29ba
LC
3;;;
4;;; This file is part of GNU Guix.
5;;;
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.
10;;;
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.
15;;;
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/>.
18
19(define-module (guix ssh)
20 #:use-module (guix store)
af15fe13 21 #:use-module (guix inferior)
52d174d6 22 #:use-module (guix i18n)
896fec47 23 #:use-module ((guix utils) #:select (&fix-hint))
3033d59a 24 #:use-module (gcrypt pk-crypto)
615c5298
LC
25 #:use-module (ssh session)
26 #:use-module (ssh auth)
27 #:use-module (ssh key)
987a29ba
LC
28 #:use-module (ssh channel)
29 #:use-module (ssh popen)
30 #:use-module (ssh session)
0e3c8528 31 #:use-module (srfi srfi-1)
987a29ba 32 #:use-module (srfi srfi-11)
d06d54e3 33 #:use-module (srfi srfi-26)
13164a21
LC
34 #:use-module (srfi srfi-34)
35 #:use-module (srfi srfi-35)
987a29ba 36 #:use-module (ice-9 match)
416a7c69 37 #:use-module (ice-9 format)
13164a21 38 #:use-module (ice-9 binary-ports)
615c5298 39 #:export (open-ssh-session
114dcb42
LC
40 authenticate-server*
41
af15fe13 42 remote-inferior
e5378337 43 remote-daemon-channel
615c5298 44 connect-to-remote-daemon
2c8e04f1 45 remote-system
3033d59a 46 remote-authorize-signing-key
987a29ba
LC
47 send-files
48 retrieve-files
d06d54e3 49 retrieve-files*
4eb0f9ae
LC
50 remote-store-host
51
52 report-guile-error
53 report-module-error))
987a29ba
LC
54
55;;; Commentary:
56;;;
57;;; This module provides tools to support communication with remote stores
58;;; over SSH, using Guile-SSH.
59;;;
60;;; Code:
61
615c5298
LC
62(define %compression
63 "zlib@openssh.com,zlib")
64
114dcb42
LC
65(define (host-key->type+key host-key)
66 "Destructure HOST-KEY, an OpenSSH host key string, and return two values:
67its 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))))
71
72 (match (string-tokenize host-key)
73 ((type key x)
74 (values (type->symbol type) key))
75 ((type key)
76 (values (type->symbol type) key))))
77
78(define (authenticate-server* session key)
79 "Make sure the server for SESSION has the given KEY, where KEY is a string
80such as \"ssh-ed25519 AAAAC3Nz… root@example.org\". Raise an exception if the
81actual 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.
91 (raise (condition
92 (&message
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)
97 (get-key-type server)
98 key type))))))))
99
a9b09ed7 100(define* (open-ssh-session host #:key user port identity
81c5873a
LC
101 (compression %compression)
102 (timeout 3600))
a9b09ed7
JK
103 "Open an SSH session for HOST and return it. IDENTITY specifies the file
104name of a private key to use for authenticating with the host. When USER,
105PORT, or IDENTITY are #f, use default values or whatever '~/.ssh/config'
81c5873a
LC
106specifies; otherwise use them. Install TIMEOUT as the maximum time in seconds
107after which a read or write operation on a channel of the returned session is
108considered as failing.
109
110Throw an error on failure."
615c5298 111 (let ((session (make-session #:user user
a9b09ed7 112 #:identity identity
615c5298
LC
113 #:host host
114 #:port port
115 #:timeout 10 ;seconds
116 ;; #:log-verbosity 'protocol
117
118 ;; We need lightweight compression when
119 ;; exchanging full archives.
120 #:compression compression
121 #:compression-level 3)))
122
123 ;; Honor ~/.ssh/config.
124 (session-parse-config! session)
125
126 (match (connect! session)
127 ('ok
f5c18018
LC
128 ;; Authenticate against ~/.ssh/known_hosts.
129 (match (authenticate-server session)
130 ('ok #f)
131 (reason
132 (raise (condition
133 (&message
134 (message (format #f (G_ "failed to authenticate \
135server at '~a': ~a")
136 (session-get session 'host)
137 reason)))))))
138
615c5298
LC
139 ;; Use public key authentication, via the SSH agent if it's available.
140 (match (userauth-public-key/auto! session)
141 ('success
81c5873a 142 (session-set! session 'timeout timeout)
615c5298
LC
143 session)
144 (x
145 (disconnect! session)
146 (raise (condition
147 (&message
69daee23 148 (message (format #f (G_ "SSH authentication failed for '~a': ~a~%")
615c5298
LC
149 host (get-error session)))))))))
150 (x
151 ;; Connection failed or timeout expired.
152 (raise (condition
153 (&message
69daee23 154 (message (format #f (G_ "SSH connection to '~a' failed: ~a~%")
615c5298
LC
155 host (get-error session))))))))))
156
5ea7537b
JK
157(define* (remote-inferior session #:optional become-command)
158 "Return a remote inferior for the given SESSION. If BECOME-COMMAND is
159given, use that to invoke the remote Guile REPL."
160 (let* ((repl-command (append (or become-command '())
161 '("guix" "repl" "-t" "machine")))
162 (pipe (apply open-remote-pipe* session OPEN_BOTH repl-command)))
5ea7537b 163 (when (eof-object? (peek-char pipe))
e09c7f4a
LC
164 (let ((status (channel-get-exit-status pipe)))
165 (close-port pipe)
166 (raise (condition
167 (&message
168 (message (format #f (G_ "remote command '~{~a~^ ~}' failed \
169with status ~a")
170 repl-command status)))))))
af15fe13
LC
171 (port->inferior pipe)))
172
5ea7537b 173(define* (inferior-remote-eval exp session #:optional become-command)
ed7b4437 174 "Evaluate EXP in a new inferior running in SESSION, and close the inferior
5ea7537b
JK
175right away. If BECOME-COMMAND is given, use that to invoke the remote Guile
176REPL."
177 (let ((inferior (remote-inferior session become-command)))
ed7b4437
LC
178 (dynamic-wind
179 (const #t)
180 (lambda ()
181 (inferior-eval exp inferior))
182 (lambda ()
183 ;; Close INFERIOR right away to prevent finalization from happening in
184 ;; another thread at the wrong time (see
185 ;; <https://bugs.gnu.org/26976>.)
186 (close-inferior inferior)))))
187
e5378337
LC
188(define* (remote-daemon-channel session
189 #:optional
190 (socket-name
191 "/var/guix/daemon-socket/socket"))
192 "Return an input/output port (an SSH channel) to the daemon at SESSION."
987a29ba
LC
193 (define redirect
194 ;; Code run in SESSION to redirect the remote process' stdin/stdout to the
195 ;; daemon's socket, à la socat. The SSH protocol supports forwarding to
196 ;; Unix-domain sockets but libssh doesn't have an API for that, hence this
197 ;; hack.
198 `(begin
17af5d51 199 (use-modules (ice-9 match) (rnrs io ports)
0dcf675c 200 (rnrs bytevectors))
987a29ba 201
8446dc5a
LC
202 (let ((sock (socket AF_UNIX SOCK_STREAM 0))
203 (stdin (current-input-port))
204 (stdout (current-output-port))
205 (select* (lambda (read write except)
206 ;; This is a workaround for
207 ;; <https://bugs.gnu.org/30365> in Guile < 2.2.4:
208 ;; since 'select' sometimes returns non-empty sets for
209 ;; no good reason, call 'select' a second time with a
210 ;; zero timeout to filter out incorrect replies.
211 (match (select read write except)
212 ((read write except)
213 (select read write except 0))))))
76832d34 214 (setvbuf stdout 'none)
0dcf675c
LC
215
216 ;; Use buffered ports so that 'get-bytevector-some' returns up to the
217 ;; whole buffer like read(2) would--see <https://bugs.gnu.org/30066>.
76832d34
LC
218 (setvbuf stdin 'block 65536)
219 (setvbuf sock 'block 65536)
0dcf675c 220
987a29ba
LC
221 (connect sock AF_UNIX ,socket-name)
222
223 (let loop ()
8446dc5a 224 (match (select* (list stdin sock) '() '())
55f40fdb 225 ((reads () ())
987a29ba 226 (when (memq stdin reads)
0dcf675c
LC
227 (match (get-bytevector-some stdin)
228 ((? eof-object?)
987a29ba 229 (primitive-exit 0))
0dcf675c
LC
230 (bv
231 (put-bytevector sock bv)
232 (force-output sock))))
987a29ba 233 (when (memq sock reads)
0dcf675c
LC
234 (match (get-bytevector-some sock)
235 ((? eof-object?)
987a29ba 236 (primitive-exit 0))
0dcf675c
LC
237 (bv
238 (put-bytevector stdout bv))))
987a29ba
LC
239 (loop))
240 (_
241 (primitive-exit 1)))))))
242
e5378337
LC
243 (open-remote-pipe* session OPEN_BOTH
244 ;; Sort-of shell-quote REDIRECT.
245 "guile" "-c"
246 (object->string
247 (object->string redirect))))
248
249(define* (connect-to-remote-daemon session
250 #:optional
251 (socket-name
252 "/var/guix/daemon-socket/socket"))
253 "Connect to the remote build daemon listening on SOCKET-NAME over SESSION,
de9fbe9c 254an SSH session. Return a <store-connection> object."
2e4d8339 255 (open-connection #:port (remote-daemon-channel session socket-name)))
e5378337 256
987a29ba
LC
257
258(define (store-import-channel session)
259 "Return an output port to which archives to be exported to SESSION's store
260can be written."
261 ;; Using the 'import-paths' RPC on a remote store would be slow because it
262 ;; makes a round trip every time 32 KiB have been transferred. This
263 ;; procedure instead opens a separate channel to use the remote
264 ;; 'import-paths' procedure, which consumes all the data in a single round
de9d8f0e
LC
265 ;; trip. This optimizes the successful case at the expense of error
266 ;; conditions: errors can only be reported once all the input has been
267 ;; consumed.
987a29ba
LC
268 (define import
269 `(begin
de9d8f0e
LC
270 (use-modules (guix) (srfi srfi-34)
271 (rnrs io ports) (rnrs bytevectors))
987a29ba 272
de9d8f0e
LC
273 (define (consume-input port)
274 (let ((bv (make-bytevector 32768)))
275 (let loop ()
276 (let ((n (get-bytevector-n! port bv 0
277 (bytevector-length bv))))
278 (unless (eof-object? n)
279 (loop))))))
987a29ba 280
de9d8f0e
LC
281 ;; Upon completion, write an sexp that denotes the status.
282 (write
283 (catch #t
284 (lambda ()
285 (guard (c ((nix-protocol-error? c)
286 ;; Consume all the input since the only time we can
287 ;; report the error is after everything has been
288 ;; consumed.
289 (consume-input (current-input-port))
290 (list 'protocol-error (nix-protocol-error-message c))))
291 (with-store store
76832d34 292 (setvbuf (current-input-port) 'none)
de9d8f0e
LC
293 (import-paths store (current-input-port))
294 '(success))))
295 (lambda args
296 (cons 'error args))))))
987a29ba 297
de9d8f0e
LC
298 (open-remote-pipe session
299 (string-join
300 `("guile" "-c"
301 ,(object->string (object->string import))))
302 OPEN_BOTH))
987a29ba 303
e9629e82
LC
304(define* (store-export-channel session files
305 #:key recursive?)
987a29ba 306 "Return an input port from which an export of FILES from SESSION's store can
e9629e82 307be read. When RECURSIVE? is true, the closure of FILES is exported."
987a29ba
LC
308 ;; Same as above: this is more efficient than calling 'export-paths' on a
309 ;; remote store.
310 (define export
311 `(begin
896fec47
LC
312 (eval-when (load expand eval)
313 (unless (resolve-module '(guix) #:ensure #f)
314 (write `(module-error))
315 (exit 7)))
316
317 (use-modules (guix) (srfi srfi-1)
318 (srfi srfi-26) (srfi srfi-34))
319
320 (guard (c ((nix-connection-error? c)
321 (write `(connection-error ,(nix-connection-error-file c)
322 ,(nix-connection-error-code c))))
323 ((nix-protocol-error? c)
324 (write `(protocol-error ,(nix-protocol-error-status c)
325 ,(nix-protocol-error-message c))))
326 (else
327 (write `(exception))))
328 (with-store store
329 (let* ((files ',files)
330 (invalid (remove (cut valid-path? store <>)
331 files)))
332 (unless (null? invalid)
333 (write `(invalid-items ,invalid))
334 (exit 1))
335
0e3c8528
LC
336 ;; TODO: When RECURSIVE? is true, we could send the list of store
337 ;; items in the closure so that the other end can filter out
338 ;; those it already has.
339
896fec47
LC
340 (write '(exporting)) ;we're ready
341 (force-output)
342
76832d34 343 (setvbuf (current-output-port) 'none)
896fec47
LC
344 (export-paths store files (current-output-port)
345 #:recursive? ,recursive?))))))
987a29ba
LC
346
347 (open-remote-input-pipe session
348 (string-join
349 `("guile" "-c"
350 ,(object->string
351 (object->string export))))))
352
2c8e04f1
JK
353(define (remote-system session)
354 "Return the system type as expected by Nix, usually ARCHITECTURE-KERNEL, of
355the machine on the other end of SESSION."
356 (inferior-remote-eval '(begin (use-modules (guix utils)) (%current-system))
357 session))
3033d59a 358
4cc5e520 359(define* (remote-authorize-signing-key key session #:optional become-command)
3033d59a
JK
360 "Send KEY, a canonical sexp containing a public key, over SESSION and add it
361to the system ACL file if it has not yet been authorized."
362 (inferior-remote-eval
363 `(begin
364 (use-modules (guix build utils)
365 (guix pki)
366 (guix utils)
367 (gcrypt pk-crypto)
368 (srfi srfi-26))
369
370 (define acl (current-acl))
371 (define key (string->canonical-sexp ,(canonical-sexp->string key)))
372
373 (unless (authorized-key? key)
374 (let ((acl (public-keys->acl (cons key (acl->public-keys acl)))))
375 (mkdir-p (dirname %acl-file))
376 (with-atomic-file-output %acl-file
377 (cut write-acl acl <>)))))
4cc5e520
JK
378 session
379 become-command))
2c8e04f1 380
987a29ba 381(define* (send-files local files remote
e9629e82
LC
382 #:key
383 recursive?
384 (log-port (current-error-port)))
987a29ba 385 "Send the subset of FILES from LOCAL (a local store) that's missing to
23973e4f
LC
386REMOTE, a remote store. When RECURSIVE? is true, send the closure of FILES.
387Return the list of store items actually sent."
987a29ba 388 ;; Compute the subset of FILES missing on SESSION and send them.
e9629e82 389 (let* ((files (if recursive? (requisites local files) files))
de9fbe9c 390 (session (channel-get-session (store-connection-socket remote)))
ed7b4437
LC
391 (missing (inferior-remote-eval
392 `(begin
393 (use-modules (guix)
394 (srfi srfi-1) (srfi srfi-26))
987a29ba 395
ed7b4437
LC
396 (with-store store
397 (remove (cut valid-path? store <>)
398 ',files)))
399 session))
987a29ba 400 (count (length missing))
b90d97ec
LC
401 (sizes (map (lambda (item)
402 (path-info-nar-size (query-path-info local item)))
403 missing))
987a29ba 404 (port (store-import-channel session)))
b90d97ec
LC
405 (format log-port (N_ "sending ~a store item (~h MiB) to '~a'...~%"
406 "sending ~a store items (~h MiB) to '~a'...~%" count)
407 count
408 (inexact->exact (round (/ (reduce + 0 sizes) (expt 2. 20))))
409 (session-get session 'host))
987a29ba
LC
410
411 ;; Send MISSING in topological order.
412 (export-paths local missing port)
413
414 ;; Tell the remote process that we're done. (In theory the end-of-archive
415 ;; mark of 'export-paths' would be enough, but in practice it's not.)
416 (channel-send-eof port)
417
de9d8f0e 418 ;; Wait for completion of the remote process and read the status sexp from
63fd9f08
LC
419 ;; PORT. Wait for the exit status only when 'read' completed; otherwise,
420 ;; we might wait forever if the other end is stuck.
de9d8f0e 421 (let* ((result (false-if-exception (read port)))
63fd9f08
LC
422 (status (and result
423 (zero? (channel-get-exit-status port)))))
987a29ba 424 (close-port port)
de9d8f0e
LC
425 (match result
426 (('success . _)
427 missing)
428 (('protocol-error message)
429 (raise (condition
f9e8a123 430 (&store-protocol-error (message message) (status 42)))))
de9d8f0e
LC
431 (('error key args ...)
432 (raise (condition
f9e8a123 433 (&store-protocol-error
de9d8f0e
LC
434 (message (call-with-output-string
435 (lambda (port)
436 (print-exception port #f key args))))
437 (status 43)))))
438 (_
439 (raise (condition
f9e8a123 440 (&store-protocol-error
de9d8f0e
LC
441 (message "unknown error while sending files over SSH")
442 (status 44)))))))))
987a29ba
LC
443
444(define (remote-store-session remote)
445 "Return the SSH channel beneath REMOTE, a remote store as returned by
446'connect-to-remote-daemon', or #f."
de9fbe9c 447 (channel-get-session (store-connection-socket remote)))
987a29ba
LC
448
449(define (remote-store-host remote)
450 "Return the name of the host REMOTE is connected to, where REMOTE is a
451remote store as returned by 'connect-to-remote-daemon'."
452 (match (remote-store-session remote)
453 (#f #f)
454 ((? session? session)
455 (session-get session 'host))))
456
e9629e82
LC
457(define* (file-retrieval-port files remote
458 #:key recursive?)
987a29ba
LC
459 "Return an input port from which to retrieve FILES (a list of store items)
460from REMOTE, along with the number of items to retrieve (lower than or equal
461to the length of FILES.)"
e9629e82
LC
462 (values (store-export-channel (remote-store-session remote) files
463 #:recursive? recursive?)
464 (length files))) ;XXX: inaccurate when RECURSIVE? is true
987a29ba 465
896fec47
LC
466(define-syntax raise-error
467 (syntax-rules (=>)
468 ((_ fmt args ... (=> hint-fmt hint-args ...))
469 (raise (condition
470 (&message
471 (message (format #f fmt args ...)))
472 (&fix-hint
473 (hint (format #f hint-fmt hint-args ...))))))
474 ((_ fmt args ...)
475 (raise (condition
476 (&message
477 (message (format #f fmt args ...))))))))
478
d06d54e3
LC
479(define* (retrieve-files* files remote
480 #:key recursive? (log-port (current-error-port))
481 (import (const #f)))
482 "Pass IMPORT an input port from which to read the sequence of FILES coming
483from REMOTE. When RECURSIVE? is true, retrieve the closure of FILES."
987a29ba 484 (let-values (((port count)
e9629e82
LC
485 (file-retrieval-port files remote
486 #:recursive? recursive?)))
896fec47
LC
487 (match (read port) ;read the initial status
488 (('exporting)
489 (format #t (N_ "retrieving ~a store item from '~a'...~%"
490 "retrieving ~a store items from '~a'...~%" count)
491 count (remote-store-host remote))
492
d06d54e3
LC
493 (dynamic-wind
494 (const #t)
495 (lambda ()
496 (import port))
497 (lambda ()
498 (close-port port))))
896fec47 499 ((? eof-object?)
4eb0f9ae 500 (report-guile-error (remote-store-host remote)))
896fec47 501 (('module-error . _)
4eb0f9ae 502 (report-module-error (remote-store-host remote)))
896fec47
LC
503 (('connection-error file code . _)
504 (raise-error (G_ "failed to connect to '~A' on remote host '~A': ~a")
505 file (remote-store-host remote) (strerror code)))
506 (('invalid-items items . _)
507 (raise-error (N_ "no such item on remote host '~A':~{ ~a~}"
508 "no such items on remote host '~A':~{ ~a~}"
509 (length items))
510 (remote-store-host remote) items))
511 (('protocol-error status message . _)
512 (raise-error (G_ "protocol error on remote host '~A': ~a")
513 (remote-store-host remote) message))
514 (_
515 (raise-error (G_ "failed to retrieve store items from '~a'")
516 (remote-store-host remote))))))
987a29ba 517
d06d54e3
LC
518(define* (retrieve-files local files remote
519 #:key recursive? (log-port (current-error-port)))
520 "Retrieve FILES from REMOTE and import them using the 'import-paths' RPC on
521LOCAL. When RECURSIVE? is true, retrieve the closure of FILES."
0e3c8528
LC
522 (retrieve-files* (remove (cut valid-path? local <>) files)
523 remote
d06d54e3
LC
524 #:recursive? recursive?
525 #:log-port log-port
526 #:import (lambda (port)
527 (import-paths local port))))
528
4eb0f9ae
LC
529\f
530;;;
531;;; Error reporting.
532;;;
533
534(define (report-guile-error host)
535 (raise-error (G_ "failed to start Guile on remote host '~A'") host
536 (=> (G_ "Make sure @command{guile} can be found in
537@code{$PATH} on the remote host. Run @command{ssh ~A guile --version} to
538check.")
539 host)))
540
541(define (report-module-error host)
542 "Report an error about missing Guix modules on HOST."
543 ;; TRANSLATORS: Leave "Guile" untranslated.
544 (raise-error (G_ "Guile modules not found on remote host '~A'") host
545 (=> (G_ "Make sure @code{GUILE_LOAD_PATH} includes Guix'
546own module directory. Run @command{ssh ~A env | grep GUILE_LOAD_PATH} to
547check.")
548 host)))
549
987a29ba 550;;; ssh.scm ends here