ssh.scm 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2019 Jakob L. Kreuze <zerodaysfordays@sdf.org>
  3. ;;; Copyright © 2020, 2021 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 machine ssh)
  20. #:use-module (gnu bootloader)
  21. #:use-module (gnu machine)
  22. #:autoload (gnu packages gnupg) (guile-gcrypt)
  23. #:use-module (gnu system)
  24. #:use-module (gnu system file-systems)
  25. #:use-module (gnu system uuid)
  26. #:use-module ((gnu services) #:select (sexp->system-provenance))
  27. #:use-module (guix diagnostics)
  28. #:use-module (guix gexp)
  29. #:use-module (guix i18n)
  30. #:use-module (guix modules)
  31. #:use-module (guix monads)
  32. #:use-module (guix pki)
  33. #:use-module (guix records)
  34. #:use-module (guix remote)
  35. #:use-module (guix scripts system reconfigure)
  36. #:use-module (guix ssh)
  37. #:use-module (guix store)
  38. #:use-module (guix utils)
  39. #:use-module ((guix self) #:select (make-config.scm))
  40. #:use-module ((guix inferior)
  41. #:select (inferior-exception?
  42. inferior-exception-arguments))
  43. #:use-module (gcrypt pk-crypto)
  44. #:use-module (ice-9 format)
  45. #:use-module (ice-9 match)
  46. #:use-module (ice-9 textual-ports)
  47. #:use-module (srfi srfi-1)
  48. #:use-module (srfi srfi-9)
  49. #:use-module (srfi srfi-19)
  50. #:use-module (srfi srfi-26)
  51. #:use-module (srfi srfi-34)
  52. #:use-module (srfi srfi-35)
  53. #:export (managed-host-environment-type
  54. machine-ssh-configuration
  55. machine-ssh-configuration?
  56. machine-ssh-configuration
  57. machine-ssh-configuration-host-name
  58. machine-ssh-configuration-build-locally?
  59. machine-ssh-configuration-authorize?
  60. machine-ssh-configuration-allow-downgrades?
  61. machine-ssh-configuration-port
  62. machine-ssh-configuration-user
  63. machine-ssh-configuration-host-key
  64. machine-ssh-configuration-session))
  65. ;;; Commentary:
  66. ;;;
  67. ;;; This module implements remote evaluation and system deployment for
  68. ;;; machines that are accessible over SSH and have a known host-name. In the
  69. ;;; sense of the broader "machine" interface, we describe the environment for
  70. ;;; such machines as 'managed-host.
  71. ;;;
  72. ;;; Code:
  73. ;;;
  74. ;;; Parameters for the SSH client.
  75. ;;;
  76. (define-record-type* <machine-ssh-configuration> machine-ssh-configuration
  77. make-machine-ssh-configuration
  78. machine-ssh-configuration?
  79. (host-name machine-ssh-configuration-host-name) ; string
  80. (system machine-ssh-configuration-system) ; string
  81. (build-locally? machine-ssh-configuration-build-locally? ; boolean
  82. (default #t))
  83. (authorize? machine-ssh-configuration-authorize? ; boolean
  84. (default #t))
  85. (allow-downgrades? machine-ssh-configuration-allow-downgrades? ; boolean
  86. (default #f))
  87. (port machine-ssh-configuration-port ; integer
  88. (default 22))
  89. (user machine-ssh-configuration-user ; string
  90. (default "root"))
  91. (identity machine-ssh-configuration-identity ; path to a private key
  92. (default #f))
  93. (session machine-ssh-configuration-session ; session
  94. (default #f))
  95. (host-key machine-ssh-configuration-host-key ; #f | string
  96. (default #f)))
  97. (define (machine-ssh-session machine)
  98. "Return the SSH session that was given in MACHINE's configuration, or create
  99. one from the configuration's parameters if one was not provided."
  100. (maybe-raise-unsupported-configuration-error machine)
  101. (let ((config (machine-configuration machine)))
  102. (or (machine-ssh-configuration-session config)
  103. (let ((host-name (machine-ssh-configuration-host-name config))
  104. (user (machine-ssh-configuration-user config))
  105. (port (machine-ssh-configuration-port config))
  106. (identity (machine-ssh-configuration-identity config))
  107. (host-key (machine-ssh-configuration-host-key config)))
  108. (unless host-key
  109. (warning (G_ "<machine-ssh-configuration> without a 'host-key' \
  110. is deprecated~%")))
  111. (open-ssh-session host-name
  112. #:user user
  113. #:port port
  114. #:identity identity
  115. #:host-key host-key)))))
  116. ;;;
  117. ;;; Remote evaluation.
  118. ;;;
  119. (define (machine-become-command machine)
  120. "Return as a list of strings the program and arguments necessary to run a
  121. shell command with escalated privileges for MACHINE's configuration."
  122. (if (string= "root" (machine-ssh-configuration-user
  123. (machine-configuration machine)))
  124. '()
  125. '("/run/setuid-programs/sudo" "-n" "--")))
  126. (define (managed-host-remote-eval machine exp)
  127. "Internal implementation of 'machine-remote-eval' for MACHINE instances with
  128. an environment type of 'managed-host."
  129. (maybe-raise-unsupported-configuration-error machine)
  130. (let ((config (machine-configuration machine)))
  131. (remote-eval exp (machine-ssh-session machine)
  132. #:build-locally?
  133. (machine-ssh-configuration-build-locally? config)
  134. #:system
  135. (machine-ssh-configuration-system config)
  136. #:become-command
  137. (machine-become-command machine))))
  138. ;;;
  139. ;;; Safety checks.
  140. ;;;
  141. ;; Assertion to be executed remotely. This abstraction exists to allow us to
  142. ;; gather a list of expressions to be evaluated and eventually evaluate them
  143. ;; all at once instead of one by one. (This is pretty much a monad.)
  144. (define-record-type <remote-assertion>
  145. (remote-assertion exp proc)
  146. remote-assertion?
  147. (exp remote-assertion-expression)
  148. (proc remote-assertion-procedure))
  149. (define-syntax-rule (remote-let ((var exp)) body ...)
  150. "Return a <remote-assertion> that binds VAR to the result of evaluating EXP,
  151. a gexp, remotely, and evaluate BODY in that context."
  152. (remote-assertion exp (lambda (var) body ...)))
  153. (define (machine-check-file-system-availability machine)
  154. "Return a list of <remote-assertion> that raise a '&message' error condition
  155. if any of the file-systems specified in MACHINE's 'system' declaration do not
  156. exist on the machine."
  157. (define file-systems
  158. (filter (lambda (fs)
  159. (and (file-system-mount? fs)
  160. (not (member (file-system-type fs)
  161. %pseudo-file-system-types))
  162. ;; Don't try to validate network file systems.
  163. (not (string-prefix? "nfs" (file-system-type fs)))
  164. (not (memq 'bind-mount (file-system-flags fs)))))
  165. (operating-system-file-systems (machine-operating-system machine))))
  166. (define (check-literal-file-system fs)
  167. (remote-let ((errno #~(catch 'system-error
  168. (lambda ()
  169. (stat #$(file-system-device fs))
  170. #t)
  171. (lambda args
  172. (system-error-errno args)))))
  173. (when (number? errno)
  174. (raise (formatted-message (G_ "device '~a' not found: ~a")
  175. (file-system-device fs)
  176. (strerror errno))))))
  177. (define (check-labeled-file-system fs)
  178. (define remote-exp
  179. (with-imported-modules (source-module-closure
  180. '((gnu build file-systems)))
  181. #~(begin
  182. (use-modules (gnu build file-systems))
  183. (find-partition-by-label #$(file-system-label->string
  184. (file-system-device fs))))))
  185. (remote-let ((result remote-exp))
  186. (unless result
  187. (raise (formatted-message (G_ "no file system with label '~a'")
  188. (file-system-label->string
  189. (file-system-device fs)))))))
  190. (define (check-uuid-file-system fs)
  191. (define remote-exp
  192. (with-imported-modules (source-module-closure
  193. '((gnu build file-systems)
  194. (gnu system uuid)))
  195. #~(begin
  196. (use-modules (gnu build file-systems)
  197. (gnu system uuid))
  198. (let ((uuid (uuid #$(uuid->string (file-system-device fs))
  199. '#$(uuid-type (file-system-device fs)))))
  200. (find-partition-by-uuid uuid)))))
  201. (remote-let ((result remote-exp))
  202. (unless result
  203. (raise (formatted-message (G_ "no file system with UUID '~a'")
  204. (uuid->string (file-system-device fs)))))))
  205. (append (map check-literal-file-system
  206. (filter (lambda (fs)
  207. (string? (file-system-device fs)))
  208. file-systems))
  209. (map check-labeled-file-system
  210. (filter (lambda (fs)
  211. (file-system-label? (file-system-device fs)))
  212. file-systems))
  213. (map check-uuid-file-system
  214. (filter (lambda (fs)
  215. (uuid? (file-system-device fs)))
  216. file-systems))))
  217. (define (machine-check-initrd-modules machine)
  218. "Return a list of <remote-assertion> that raise a '&message' error condition
  219. if any of the modules needed by 'needed-for-boot' file systems in MACHINE are
  220. not available in the initrd."
  221. (define file-systems
  222. (filter file-system-needed-for-boot?
  223. (operating-system-file-systems (machine-operating-system machine))))
  224. (define (missing-modules fs)
  225. (define remote-exp
  226. (let ((device (file-system-device fs)))
  227. (with-imported-modules (source-module-closure
  228. '((gnu build file-systems)
  229. (gnu build linux-modules)
  230. (gnu system uuid)))
  231. #~(begin
  232. (use-modules (gnu build file-systems)
  233. (gnu build linux-modules)
  234. (gnu system uuid))
  235. (define dev
  236. #$(cond ((string? device) device)
  237. ((uuid? device) #~(find-partition-by-uuid
  238. (string->uuid
  239. #$(uuid->string device))))
  240. ((file-system-label? device)
  241. #~(find-partition-by-label
  242. #$(file-system-label->string device)))))
  243. (missing-modules dev '#$(operating-system-initrd-modules
  244. (machine-operating-system machine)))))))
  245. (remote-let ((missing remote-exp))
  246. (unless (null? missing)
  247. (raise (formatted-message (G_ "missing modules for ~a:~{ ~a~}~%")
  248. (file-system-device fs)
  249. missing)))))
  250. (map missing-modules file-systems))
  251. (define* (machine-check-forward-update machine)
  252. "Check whether we are making a forward update for MACHINE. Depending on its
  253. 'allow-upgrades?' field, raise an error or display a warning if we are
  254. potentially downgrading it."
  255. (define config
  256. (machine-configuration machine))
  257. (define validate-reconfigure
  258. (if (machine-ssh-configuration-allow-downgrades? config)
  259. warn-about-backward-reconfigure
  260. ensure-forward-reconfigure))
  261. (remote-let ((provenance #~(call-with-input-file
  262. "/run/current-system/provenance"
  263. read)))
  264. (define channels
  265. (sexp->system-provenance provenance))
  266. (check-forward-update validate-reconfigure
  267. #:current-channels channels)))
  268. (define (machine-check-building-for-appropriate-system machine)
  269. "Raise a '&message' error condition if MACHINE is configured to be built
  270. locally and the 'system' field does not match the '%current-system' reported
  271. by MACHINE."
  272. (let ((config (machine-configuration machine))
  273. (system (remote-system (machine-ssh-session machine))))
  274. (when (and (machine-ssh-configuration-build-locally? config)
  275. (not (string= system (machine-ssh-configuration-system config))))
  276. (raise (formatted-message (G_ "incorrect target system\
  277. ('~a' was given, while the system reports that it is '~a')~%")
  278. (machine-ssh-configuration-system config)
  279. system)))))
  280. (define (check-deployment-sanity machine)
  281. "Raise a '&message' error condition if it is clear that deploying MACHINE's
  282. 'system' declaration would fail."
  283. (define assertions
  284. (append (machine-check-file-system-availability machine)
  285. (machine-check-initrd-modules machine)
  286. (list (machine-check-forward-update machine))))
  287. (define aggregate-exp
  288. ;; Gather all the expressions so that a single round-trip is enough to
  289. ;; evaluate all the ASSERTIONS remotely.
  290. #~(map (lambda (file)
  291. (false-if-exception (primitive-load file)))
  292. '#$(map (lambda (assertion)
  293. (scheme-file "remote-assertion.scm"
  294. (remote-assertion-expression assertion)))
  295. assertions)))
  296. ;; First check MACHINE's system type--an incorrect value for 'system' would
  297. ;; cause subsequent invocations of 'remote-eval' to fail.
  298. (machine-check-building-for-appropriate-system machine)
  299. (mlet %store-monad ((values (machine-remote-eval machine aggregate-exp)))
  300. (for-each (lambda (proc value)
  301. (proc value))
  302. (map remote-assertion-procedure assertions)
  303. values)
  304. (return #t)))
  305. ;;;
  306. ;;; System deployment.
  307. ;;;
  308. (define not-config?
  309. ;; Select (guix …) and (gnu …) modules, except (guix config).
  310. (match-lambda
  311. (('guix 'config) #f)
  312. (('guix _ ...) #t)
  313. (('gnu _ ...) #t)
  314. (_ #f)))
  315. (define (machine-boot-parameters machine)
  316. "Monadic procedure returning a list of 'boot-parameters' for the generations
  317. of MACHINE's system profile, ordered from most recent to oldest."
  318. (define bootable-kernel-arguments
  319. (@@ (gnu system) bootable-kernel-arguments))
  320. (define remote-exp
  321. (with-extensions (list guile-gcrypt)
  322. (with-imported-modules `(((guix config) => ,(make-config.scm))
  323. ,@(source-module-closure
  324. '((guix profiles))
  325. #:select? not-config?))
  326. #~(begin
  327. (use-modules (guix config)
  328. (guix profiles)
  329. (ice-9 textual-ports))
  330. (define %system-profile
  331. (string-append %state-directory "/profiles/system"))
  332. (define (read-file path)
  333. (call-with-input-file path
  334. (lambda (port)
  335. (get-string-all port))))
  336. (map (lambda (generation)
  337. (let* ((system-path (generation-file-name %system-profile
  338. generation))
  339. (boot-parameters-path (string-append system-path
  340. "/parameters"))
  341. (time (stat:mtime (lstat system-path))))
  342. (list generation
  343. system-path
  344. time
  345. (read-file boot-parameters-path))))
  346. (reverse (generation-numbers %system-profile)))))))
  347. (mlet* %store-monad ((generations (machine-remote-eval machine remote-exp)))
  348. (return
  349. (map (lambda (generation)
  350. (match generation
  351. ((generation system-path time serialized-params)
  352. (let* ((params (call-with-input-string serialized-params
  353. read-boot-parameters))
  354. (root (boot-parameters-root-device params))
  355. (label (boot-parameters-label params)))
  356. (boot-parameters
  357. (inherit params)
  358. (label
  359. (string-append label " (#"
  360. (number->string generation) ", "
  361. (let ((time (make-time time-utc 0 time)))
  362. (date->string (time-utc->date time)
  363. "~Y-~m-~d ~H:~M"))
  364. ")"))
  365. (kernel-arguments
  366. (append (bootable-kernel-arguments system-path root)
  367. (boot-parameters-kernel-arguments params))))))))
  368. generations))))
  369. (define-syntax-rule (with-roll-back should-roll-back? mbody ...)
  370. "Catch exceptions that arise when binding MBODY, a monadic expression in
  371. %STORE-MONAD, and collect their arguments in a &deploy-error condition, with
  372. the 'should-roll-back' field set to SHOULD-ROLL-BACK?"
  373. (catch #t
  374. (lambda ()
  375. mbody ...)
  376. (lambda args
  377. (raise (condition (&deploy-error
  378. (should-roll-back should-roll-back?)
  379. (captured-args args)))))))
  380. (define (deploy-managed-host machine)
  381. "Internal implementation of 'deploy-machine' for MACHINE instances with an
  382. environment type of 'managed-host."
  383. (maybe-raise-unsupported-configuration-error machine)
  384. (when (machine-ssh-configuration-authorize?
  385. (machine-configuration machine))
  386. (unless (file-exists? %public-key-file)
  387. (raise (formatted-message (G_ "no signing key '~a'. \
  388. have you run 'guix archive --generate-key?'")
  389. %public-key-file)))
  390. (remote-authorize-signing-key (call-with-input-file %public-key-file
  391. (lambda (port)
  392. (string->canonical-sexp
  393. (get-string-all port))))
  394. (machine-ssh-session machine)
  395. (machine-become-command machine)))
  396. (mlet %store-monad ((_ (check-deployment-sanity machine))
  397. (boot-parameters (machine-boot-parameters machine)))
  398. (let* ((os (machine-operating-system machine))
  399. (host (machine-ssh-configuration-host-name
  400. (machine-configuration machine)))
  401. (eval (cut machine-remote-eval machine <>))
  402. (menu-entries (map boot-parameters->menu-entry boot-parameters))
  403. (bootloader-configuration (operating-system-bootloader os))
  404. (bootcfg (operating-system-bootcfg os menu-entries)))
  405. (define-syntax-rule (eval/error-handling condition handler ...)
  406. ;; Return a wrapper around EVAL such that HANDLER is evaluated if an
  407. ;; exception is raised.
  408. (lambda (exp)
  409. (lambda (store)
  410. (guard (condition ((inferior-exception? condition)
  411. (values (begin handler ...) store)))
  412. (values (run-with-store store (eval exp))
  413. store)))))
  414. (mbegin %store-monad
  415. (with-roll-back #f
  416. (switch-to-system (eval/error-handling c
  417. (raise (formatted-message
  418. (G_ "\
  419. failed to switch systems while deploying '~a':~%~{~s ~}")
  420. host
  421. (inferior-exception-arguments c))))
  422. os))
  423. (with-roll-back #t
  424. (mbegin %store-monad
  425. (upgrade-shepherd-services (eval/error-handling c
  426. (warning (G_ "\
  427. an error occurred while upgrading services on '~a':~%~{~s ~}~%")
  428. host
  429. (inferior-exception-arguments
  430. c)))
  431. os)
  432. (install-bootloader (eval/error-handling c
  433. (raise (formatted-message
  434. (G_ "\
  435. failed to install bootloader on '~a':~%~{~s ~}~%")
  436. host
  437. (inferior-exception-arguments c))))
  438. bootloader-configuration bootcfg)))))))
  439. ;;;
  440. ;;; Roll-back.
  441. ;;;
  442. (define (roll-back-managed-host machine)
  443. "Internal implementation of 'roll-back-machine' for MACHINE instances with
  444. an environment type of 'managed-host."
  445. (define remote-exp
  446. (with-extensions (list guile-gcrypt)
  447. (with-imported-modules (source-module-closure '((guix config)
  448. (guix profiles)))
  449. #~(begin
  450. (use-modules (guix config)
  451. (guix profiles))
  452. (define %system-profile
  453. (string-append %state-directory "/profiles/system"))
  454. (define target-generation
  455. (relative-generation %system-profile -1))
  456. (if target-generation
  457. (switch-to-generation %system-profile target-generation)
  458. 'error)))))
  459. (define roll-back-failure
  460. (condition (&message (message (G_ "could not roll-back machine")))))
  461. (mlet* %store-monad ((boot-parameters (machine-boot-parameters machine))
  462. (_ -> (if (< (length boot-parameters) 2)
  463. (raise roll-back-failure)))
  464. (entries -> (map boot-parameters->menu-entry
  465. (list (second boot-parameters))))
  466. (locale -> (boot-parameters-locale
  467. (second boot-parameters)))
  468. (crypto-dev -> (boot-parameters-store-crypto-devices
  469. (second boot-parameters)))
  470. (store-dir -> (boot-parameters-store-directory-prefix
  471. (second boot-parameters)))
  472. (old-entries -> (map boot-parameters->menu-entry
  473. (drop boot-parameters 2)))
  474. (bootloader -> (operating-system-bootloader
  475. (machine-operating-system machine)))
  476. (bootcfg (lower-object
  477. ((bootloader-configuration-file-generator
  478. (bootloader-configuration-bootloader
  479. bootloader))
  480. bootloader entries
  481. #:locale locale
  482. #:store-crypto-devices crypto-dev
  483. #:store-directory-prefix store-dir
  484. #:old-entries old-entries)))
  485. (remote-result (machine-remote-eval machine remote-exp)))
  486. (when (eqv? 'error remote-result)
  487. (raise roll-back-failure))))
  488. ;;;
  489. ;;; Environment type.
  490. ;;;
  491. (define managed-host-environment-type
  492. (environment-type
  493. (machine-remote-eval managed-host-remote-eval)
  494. (deploy-machine deploy-managed-host)
  495. (roll-back-machine roll-back-managed-host)
  496. (name 'managed-host-environment-type)
  497. (description "Provisioning for machines that are accessible over SSH
  498. and have a known host-name. This entails little more than maintaining an SSH
  499. connection to the host.")))
  500. (define (maybe-raise-unsupported-configuration-error machine)
  501. "Raise an error if MACHINE's configuration is not an instance of
  502. <machine-ssh-configuration>."
  503. (let ((config (machine-configuration machine))
  504. (environment (environment-type-name (machine-environment machine))))
  505. (unless (and config (machine-ssh-configuration? config))
  506. (raise (formatted-message (G_ "unsupported machine configuration '~a'
  507. for environment of type '~a'")
  508. config
  509. environment)))))
  510. ;; Local Variables:
  511. ;; eval: (put 'remote-let 'scheme-indent-function 1)
  512. ;; eval: (put 'with-roll-back 'scheme-indent-function 1)
  513. ;; eval: (put 'eval/error-handling 'scheme-indent-function 1)
  514. ;; End: