Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When reading rand.Reader may result in error?

Tags:

random

go

Do I understand correctly that crypto/rand.Reader can return Read error only on platforms not listed below, i.e. when it is not actually implemented?

// Reader is a global, shared instance of a cryptographically
// strong pseudo-random generator.
//
// On Linux, Reader uses getrandom(2) if available, /dev/urandom otherwise.
// On OpenBSD, Reader uses getentropy(2).
// On other Unix-like systems, Reader reads from /dev/urandom.
// On Windows systems, Reader uses the CryptGenRandom API.
var Reader io.Reader
like image 842
kopiczko Avatar asked Jan 05 '23 12:01

kopiczko


1 Answers

TL;DR; crypto/rand's Read() (and Reader.Read()) methods may fail due to a variety of reasons, even on the platforms listed as supported. Do not assume that calls to this functions will always succeed. Always check the error return value.


Do I understand correctly that crypto/rand.Reader can return Read error only on platforms not listed below, i.e. when it is not actually implemented?

No. For example, have a look at the Linux implementation of rand.Reader. If available, this implementation will use the getrandom Linux system call, which may fail with a number of errors (most importantly, EAGAIN):

EAGAIN - The requested entropy was not available, and getrandom() would have blocked if the GRND_NONBLOCK flag was not set.

The EAGAIN error quite literally tells you to "try again later"; the official meaning according to man 3 errno is "Resource temporarily unavailable". So when receiving an EAGAIN error you could simply keep trying for a certain time.

If getrandom is not available, the crypto/rand module will try to open and read from /dev/urandom (see source code), which might also fail for any number of reasons. These errors might not necessarily be of temporary nature (for example, issues with file system permissions); if your application depends on the availability of random data, you should treat an error like any other kind of non-recoverable error in your application.

For these reasons, you should not assume that rand.Read() will always succeed on Linux/UNIX and always check rand.Read()'s error return value.

like image 194
helmbert Avatar answered Jan 13 '23 11:01

helmbert