Subject: [PATCH 2/2] services: urandom-seed: Try using a HWRNG to seed the Linux CRNG at boot.

From: Leo Famulari <[email-masked]>
Date: Fri, 15 Dec 2017 15:18:13 -0500

* gnu/services/base.scm (urandom-seed-shepherd-service): Try to read from
'/dev/hwrng' at boot, as a supplement to any saved random seed.
* doc/guix.texi (Base Services): Document the new feature.
---
 doc/guix.texi         |  4 +++-
 gnu/services/base.scm | 19 +++++++++++++++++++
 2 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/doc/guix.texi b/doc/guix.texi
index 64f73b38a..e08f264e9 100644
--- a/doc/guix.texi
+++ b/doc/guix.texi
@@ -10013,7 +10013,9 @@ well as in the @var{groups} field of the @var{operating-system} record.
 
 @deffn {Scheme Procedure} urandom-seed-service
 Save some entropy in @var{%random-seed-file} to seed @file{/dev/urandom}
-when rebooting.
+when rebooting.  This also tries to seed @file{/dev/urandom} from
+@file{/dev/hwrng} while booting, if @file{/dev/hwrng} exists and is
+readable.
 @end deffn
 
 @defvr {Scheme Variable} %random-seed-file
diff --git a/gnu/services/base.scm b/gnu/services/base.scm
index 291dd6325..be9e8ee36 100644
--- a/gnu/services/base.scm
+++ b/gnu/services/base.scm
@@ -516,6 +516,25 @@ stopped before 'kill' is called."
                           (call-with-output-file "/dev/urandom"
                             (lambda (urandom)
                               (dump-port seed urandom))))))
+
+                    ;; Try writing from /dev/hwrng into /dev/urandom.
+                    ;; It seems that the file '/dev/hwrng' always exists, even
+                    ;; when there is no hardware random number generator
+                    ;; available. So, we handle any errors caused by a failed
+                    ;; read.
+                    (when (file-exists? "/dev/hwrng")
+                      (call-with-input-file "/dev/hwrng"
+                        (lambda (hwrng)
+                          (let ((buf (make-bytevector 512)))
+                            (catch #t
+                              (lambda ()
+                                (get-bytevector-n! hwrng buf 0 512))
+                              ;; Silence is golden...
+                              (lambda _ (const #f)))
+                            (call-with-output-file "/dev/urandom"
+                              (lambda (urandom)
+                                (put-bytevector urandom buf)))))))
+
                     ;; Immediately refresh the seed in case the system doesn't
                     ;; shut down cleanly.
                     (call-with-input-file "/dev/urandom"
-- 
2.15.1