Skip to content

Commit 5545e33

Browse files
authored
Fix fread check for reading randomness (#384)
* Fix fread check for reading randomness Fallback CSPRNG on generic UNIX will read `urandom` for randomness. The read has a bug where if `fread` reads say 10 bytes but the size is 32. The buffer is only partially updated and returned successful. This patch ensures the fallback read returns success only when the buffer is fully filled. * Fix fread condition to check for equality * Use microseconds
1 parent 85245fa commit 5545e33

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

trantor/utils/Utilities.cc

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ static bool systemRandomBytes(void *ptr, size_t size)
441441
LOG_FATAL << "Failed to open /dev/urandom for randomness";
442442
abort();
443443
}
444-
if (fread(ptr, 1, size, fptr.get()) != 0)
444+
if (fread(ptr, 1, size, fptr.get()) == size)
445445
return true;
446446
#endif
447447
return false;
@@ -533,9 +533,9 @@ bool secureRandomBytes(void *data, size_t len)
533533
auto now = chrono::steady_clock::now();
534534
// the proposed algorithm uses the time in nanoseconds, but we don't have a
535535
// way to read it (yet) not C++ provided a standard way to do it. Falling
536-
// back to milliseconds. This along with additional entropy is hopefully
536+
// back to microseconds. This along with additional entropy is hopefully
537537
// good enough.
538-
state.time = chrono::time_point_cast<chrono::milliseconds>(now)
538+
state.time = chrono::time_point_cast<chrono::microseconds>(now)
539539
.time_since_epoch()
540540
.count();
541541
// `now` lives on the stack, so address in each call _may_ be different.

0 commit comments

Comments
 (0)