]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
app-layer-htp, stream-tcp: prevent modulo bias in RandomGetWrap() 3183/head
authorMartin Natano <martin.natano@radarservices.com>
Mon, 30 Oct 2017 15:03:25 +0000 (16:03 +0100)
committerVictor Julien <victor@inliniac.net>
Tue, 23 Jan 2018 07:59:34 +0000 (08:59 +0100)
RAND_MAX is not guaranteed to be a divisor of ULONG_MAX, so take the
necessary precautions to get unbiased random numbers. Although the
bias might be negligible, it's not advisable to rely on it.

src/app-layer-htp.c
src/stream-tcp.c

index 321bbfd64d5c85b453b06fb76fc1bb0ebe1a2a2a..9a9084fc1faabc6cb8353dd42aa47cf75b68d279 100644 (file)
@@ -2215,9 +2215,13 @@ static void HTPConfigSetDefaultsPhase1(HTPCfgRec *cfg_prec)
  */
 static int RandomGetWrap(void)
 {
-    long int r = RandomGet();
-    int r_int = r % (long int)RAND_MAX;
-    return abs(r_int);
+    unsigned long r;
+
+    do {
+        r = RandomGet();
+    } while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
+
+    return r % RAND_MAX;
 }
 
 /*
index aebad500750c453f5d5e602e94a9fbf9f7c487f3..46f53740f7f4e50b6234fef974d31c481c583cf3 100644 (file)
@@ -344,9 +344,13 @@ int StreamTcpInlineDropInvalid(void)
  */
 static int RandomGetWrap(void)
 {
-    long int r = RandomGet();
-    int r_int = r % (long int)RAND_MAX;
-    return abs(r_int);
+    unsigned long r;
+
+    do {
+        r = RandomGet();
+    } while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
+
+    return r % RAND_MAX;
 }
 
 /** \brief          To initialize the stream global configuration data