chiark / gitweb /
basic/random-util: do not fall back to /dev/urandom if getrandom() returns short
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Sun, 25 Jun 2017 21:09:05 +0000 (17:09 -0400)
committerSven Eden <yamakuzure@gmx.net>
Tue, 25 Jul 2017 07:46:53 +0000 (09:46 +0200)
commit3daa986ebd3fd6d42853c12020a8c687ce681b26
treed9d07637385cf6cc636dc6f911fd4c5ad631d8e3
parent9742b1e43855b1599bd52ff95af995d9a9d35eac
basic/random-util: do not fall back to /dev/urandom if getrandom() returns short

During early boot, we'd call getrandom(), and immediately fall back to
reading from /dev/urandom unless we got the full requested number of bytes.
Those two sources are the same, so the most likely result is /dev/urandom
producing some pseudorandom numbers for us, complaining widely on the way.

Let's change our behaviour to be more conservative:
- if the numbers are only used to initialize a hash table, a short read is OK,
  we don't really care if we get the first part of the seed truly random and
  then some pseudorandom bytes. So just do that and return "success".

- if getrandom() returns -EAGAIN, fall back to rand() instead of querying
  /dev/urandom again.

  The idea with those two changes is to avoid generating a warning about
  reading from an /dev/urandom when the kernel doesn't have enough entropy.

- only in the cases where we really need to make the best effort possible
  (sd_id128_randomize and firstboot password hashing), fall back to
  /dev/urandom.

When calling getrandom(), drop the checks whether the argument fits in an int —
getrandom() should do that for us already, and we call it with small arguments
only anyway.

Note that this does not really change the (relatively high) number of random
bytes we request from the kernel. On my laptop, during boot, PID 1 and all
other processes using this code through libelogind request:
  74780 bytes with high_quality_required == false
    464 bytes with high_quality_required == true
and it does not eliminate reads from /dev/urandom completely. If the kernel was
short on entropy and getrandom() would fail, we would fall back to /dev/urandom
for those 464 bytes.

When falling back to /dev/urandom, don't lose the short read we already got,
and just read the remaining bytes.

If getrandom() syscall is not available, we fall back to /dev/urandom same
as before.

Fixes #4167 (possibly partially, let's see).
src/basic/random-util.c
src/basic/random-util.h
src/libelogind/sd-id128/sd-id128.c