From 18f64e0d21d56a364679eaab7c7fee862290e4b0 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 321bbfd64d..9a9084fc1f 100644 --- a/src/app-layer-htp.c +++ b/src/app-layer-htp.c @@ -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; } /* diff --git a/src/stream-tcp.c b/src/stream-tcp.c index aebad50075..46f53740f7 100644 --- a/src/stream-tcp.c +++ b/src/stream-tcp.c @@ -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 -- 2.47.2