1
0
mirror of https://github.com/golang/go synced 2024-11-18 12:04:57 -07:00

crypto/rand: use blocking getrandom call on Linux when supported

By changing getRandomLinux to immediately use the getrandom() syscall
without GRND_NONBLOCK, we now only fall back to reading from
/dev/urandom on Linux if the kernel does not support the getrandom()
syscall. This means reads for crypto/rand will now block if the kernel
has insufficient entropy on Linux kernels after v3.16.

Before, if the kernel had insufficient entropy, it would fall back to
reading from /dev/urandom. This would potentially return predictable
data.

Fixes #19274

Change-Id: I1cb081ce2f3096f18ad2820e52ecdbd993dc2afc
Reviewed-on: https://go-review.googlesource.com/43852
Reviewed-by: Filippo Valsorda <hi@filippo.io>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
Joe Richey joerichey@google.com 2017-05-22 14:36:43 -07:00 committed by Brad Fitzpatrick
parent f3f29d1dea
commit 95d991d30c

View File

@ -6,34 +6,20 @@ package rand
import (
"internal/syscall/unix"
"sync"
)
func init() {
altGetRandom = getRandomLinux
}
var (
once sync.Once
useSyscall bool
)
func pickStrategy() {
// Test whether we should use the system call or /dev/urandom.
// We'll fall back to urandom if:
// - the kernel is too old (before 3.17)
// - the machine has no entropy available (early boot + no hardware
// entropy source?) and we want to avoid blocking later.
var buf [1]byte
n, err := unix.GetRandom(buf[:], unix.GRND_NONBLOCK)
useSyscall = n == 1 && err == nil
}
// If the kernel is too old (before 3.17) to support the getrandom syscall(),
// unix.GetRandom will immediately return ENOSYS and we will then fall back to
// reading from /dev/urandom in rand_unix.go. unix.GetRandom caches the ENOSYS
// result so we only suffer the syscall overhead once in this case.
// If the kernel supports the getrandom() syscall, unix.GetRandom will block
// until the kernel has sufficient randomness (as we don't use GRND_NONBLOCK).
// In this case, unix.GetRandom will not return an error.
func getRandomLinux(p []byte) (ok bool) {
once.Do(pickStrategy)
if !useSyscall {
return false
}
n, err := unix.GetRandom(p, 0)
return n == len(p) && err == nil
}