linux-lvm.redhat.com archive mirror
 help / color / mirror / Atom feed
* [linux-lvm] [PATCH] misc: use getrandom(GRND_INSECURE) instead of /dev/urandom when possible
@ 2022-04-08 15:30 Jason A. Donenfeld
  0 siblings, 0 replies; only message in thread
From: Jason A. Donenfeld @ 2022-04-08 15:30 UTC (permalink / raw)
  To: linux-lvm, David Teigland, Zdenek Kabelac; +Cc: Jason A. Donenfeld

getrandom(GRND_INSECURE) is the same as /dev/urandom, except:

- It won't leave a warning in dmesg if used at early boot time, which is
  a common occurance;

- It won't introduce a tiny delay at early boot on newer kernels when
  /dev/urandom tries to opportunistically create jitter entropy;

- It only requires 1 syscall, rather than 3.

Other than that, it returns the same "quality" of randomness as
/dev/urandom, and never blocks.

It's only available on kernels ≥5.6, so we try to use it, cache the
result of that attempt, and fall back to /dev/urandom if it didn't work
out.
---
 lib/misc/lvm-wrappers.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/lib/misc/lvm-wrappers.c b/lib/misc/lvm-wrappers.c
index 2e0cfd514..1239f1085 100644
--- a/lib/misc/lvm-wrappers.c
+++ b/lib/misc/lvm-wrappers.c
@@ -16,6 +16,7 @@
 
 #include <unistd.h>
 #include <fcntl.h>
+#include <sys/random.h>
 
 #ifdef UDEV_SYNC_SUPPORT
 #include <libudev.h>
@@ -111,8 +112,17 @@ int lvm_getpagesize(void)
 
 int read_urandom(void *buf, size_t len)
 {
+	static int have_getrandom = -1;
 	int fd;
 
+	if (have_getrandom) {
+		bool success = getrandom(buf, len, GRND_INSECURE) == len;
+		if (have_getrandom == -1)
+			have_getrandom = success;
+		if (success)
+			return 1;
+	}
+
 	/* FIXME: we should stat here, and handle other cases */
 	/* FIXME: use common _io() routine's open/read/close */
 	if ((fd = open("/dev/urandom", O_RDONLY)) < 0) {
-- 
2.35.1

_______________________________________________
linux-lvm mailing list
linux-lvm@redhat.com
https://listman.redhat.com/mailman/listinfo/linux-lvm
read the LVM HOW-TO at http://tldp.org/HOWTO/LVM-HOWTO/

^ permalink raw reply related	[flat|nested] only message in thread

only message in thread, other threads:[~2022-04-08 15:37 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-04-08 15:30 [linux-lvm] [PATCH] misc: use getrandom(GRND_INSECURE) instead of /dev/urandom when possible Jason A. Donenfeld

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).