From: Martin Natano Date: Mon, 30 Oct 2017 15:03:25 +0000 (+0100) Subject: app-layer-htp, stream-tcp: prevent modulo bias in RandomGetWrap() X-Git-Tag: suricata-4.0.4~27 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=7f3d623abc4837ecd418ca5c508a045061791701;p=thirdparty%2Fsuricata.git 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. --- 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