From 7f3d623abc4837ecd418ca5c508a045061791701 Mon Sep 17 00:00:00 2001 From: Martin Natano Date: Mon, 30 Oct 2017 16:03:25 +0100 Subject: [PATCH] app-layer-htp, stream-tcp: prevent modulo bias in RandomGetWrap() 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 | 10 +++++++--- src/stream-tcp.c | 10 +++++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/app-layer-htp.c b/src/app-layer-htp.c index d8a3308856..b81b557eb4 100644 --- a/src/app-layer-htp.c +++ b/src/app-layer-htp.c @@ -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; } /* diff --git a/src/stream-tcp.c b/src/stream-tcp.c index ae4379f355..20a73fcd35 100644 --- a/src/stream-tcp.c +++ b/src/stream-tcp.c @@ -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 -- 2.47.2