Linux/MacOSX: Read at least 32 bytes from /dev/random before allowing it to fail gracefully

This commit is contained in:
Mounir IDRASSI 2020-06-21 17:37:11 +02:00
parent e97114e7a0
commit a4c5f03bee
No known key found for this signature in database
GPG Key ID: 02C30AE90FAE4A6F
2 changed files with 11 additions and 3 deletions

View File

@ -44,12 +44,12 @@ namespace VeraCrypt
throw_sys_sub_if (random == -1, L"/dev/random");
finally_do_arg (int, random, { close (finally_arg); });
// ensure that we have read /dev/random successfully at least once before continuing
// ensure that we have read at least 32 bytes from /dev/random before allowing it to fail gracefully
while (true)
{
int rndCount = read (random, buffer, buffer.Size());
throw_sys_sub_if ((rndCount == -1) && errno != EAGAIN, L"/dev/random");
if (rndCount == -1 && !DevRandomSucceeded)
throw_sys_sub_if ((rndCount == -1) && errno != EAGAIN && errno != ERESTART && errno != EINTR, L"/dev/random");
if (rndCount == -1 && (!DevRandomSucceeded || (DevRandomBytesCount < 32)))
{
// wait 250ms before querying /dev/random again
::usleep (250 * 1000);
@ -57,7 +57,12 @@ namespace VeraCrypt
else
{
if (rndCount != -1)
{
// We count returned bytes untill 32-bytes treshold reached
if (DevRandomBytesCount < 32)
DevRandomBytesCount += rndCount;
DevRandomSucceeded = true;
}
break;
}
}
@ -236,6 +241,7 @@ namespace VeraCrypt
EnrichedByUser = false;
Running = false;
DevRandomSucceeded = false;
DevRandomBytesCount = 0;
}
void RandomNumberGenerator::Test ()
@ -274,4 +280,5 @@ namespace VeraCrypt
size_t RandomNumberGenerator::WriteOffset;
struct rand_data *RandomNumberGenerator::JitterRngCtx = NULL;
bool RandomNumberGenerator::DevRandomSucceeded = false;
int RandomNumberGenerator::DevRandomBytesCount = 0;
}

View File

@ -56,6 +56,7 @@ namespace VeraCrypt
static size_t WriteOffset;
static struct rand_data *JitterRngCtx;
static bool DevRandomSucceeded;
static int DevRandomBytesCount;
};
}