]> git.ipfire.org Git - thirdparty/systemd.git/commit - src/firstboot/firstboot.c
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)
committerZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Wed, 28 Jun 2017 14:32:02 +0000 (10:32 -0400)
commitf0d09059bd4a195840f7c79943be942b240d5500
treeee45eaf6c7d2e86f8eda4f0a12c81d2b4c7e201e
parent6a06b1a5d9d6a05404ea6ace739d39e6256968c3
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 libsystemd 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/firstboot/firstboot.c
src/libsystemd/sd-id128/sd-id128.c