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.1.0-beta1~301 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=refs%2Fpull%2F3183%2Fhead;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 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