ssh.scm 23 KB

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