]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
app-layer-htp, stream-tcp: prevent modulo bias in RandomGetWrap()
authorMartin Natano <martin.natano@radarservices.com>
Mon, 30 Oct 2017 15:03:25 +0000 (16:03 +0100)
committerVictor Julien <victor@inliniac.net>
Tue, 30 Jan 2018 10:26:47 +0000 (11:26 +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 d8a33088563fd981b25d1ef5fd7dfb740a00a237..b81b557eb4aa3a52e48a22d1f0868cb0edffa9aa 100644 (file)
@@ -2213,9 +2213,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 ae4379f35553db84c3f9cda1ddbc748ae0d97a46..20a73fcd35b05a584dcddc0dbeeea51babb7ffbd 100644 (file)
@@ -317,9 +317,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