Bug 359485

Summary: KRandom::random reads 16384 bytes from /dev/urandom per invocation instead of 4
Product: [Frameworks and Libraries] frameworks-kcoreaddons Reporter: Cristian Rodríguez <crrodriguez>
Component: generalAssignee: Michael Pyne <mpyne>
Status: RESOLVED FIXED    
Severity: normal CC: kdelibs-bugs
Priority: NOR    
Version: unspecified   
Target Milestone: ---   
Platform: openSUSE   
OS: Linux   
Latest Commit: Version Fixed In: 5.20.0

Description Cristian Rodríguez 2016-02-16 23:18:06 UTC
reads 16384 bytes from /dev/urandom per invocation, this is because QFile stream is buffered by default.

Reproducible: Always

Steps to Reproduce:
Call  KRandom::random from any application

Actual Results:  
reads 16384 bytes from /dev/urandom

Expected Results:  
A read of sizeof(seed)

git diff
diff --git a/src/lib/randomness/krandom.cpp b/src/lib/randomness/krandom.cpp
index da78388..93b917d 100644
--- a/src/lib/randomness/krandom.cpp
+++ b/src/lib/randomness/krandom.cpp
@@ -43,7 +43,7 @@ int KRandom::random()
         unsigned int seed;
         init = true;
         QFile urandom(QStringLiteral("/dev/urandom"));
-        bool opened = urandom.open(QIODevice::ReadOnly);
+        bool opened = urandom.open(QIODevice::ReadOnly | QIODevice::Unbuffered);
         if (!opened || urandom.read((char *)&seed, sizeof(seed)) != sizeof(seed)) {
             // No /dev/urandom... try something else.
             srand(getpid());
Comment 1 Michael Pyne 2016-02-17 05:04:11 UTC
Git commit 47fd753a9a7e19a446896362528f69f76fd03029 by Michael Pyne.
Committed on 17/02/2016 at 05:00.
Pushed by mpyne into branch 'master'.

KRandom: Don't use up 16K of /dev/urandom to seed rand().

According to a bug report KRandom reads 16K from /dev/urandom when
seeding its RNG (which is just the libc RNG). This is because we simply
use QFile, which buffers by default, the fix is to avoid buffering the
output of this special file.
REVIEW:127094
FIXED-IN:5.20.0

M  +1    -1    src/lib/randomness/krandom.cpp

http://commits.kde.org/kcoreaddons/47fd753a9a7e19a446896362528f69f76fd03029