From 142c3099763ee5aff33f7365ad1948e944b92c3b Mon Sep 17 00:00:00 2001 From: Mason Simon Date: Fri, 25 May 2018 18:56:59 -0700 Subject: [PATCH] Use /dev/urandom --- ipscrub/src/ngx_ipscrub_module.c | 7 ++++++- ipscrub/src/ngx_ipscrub_support.c | 21 +++++++++++++++++++++ ipscrub/src/ngx_ipscrub_support.h | 1 + 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/ipscrub/src/ngx_ipscrub_module.c b/ipscrub/src/ngx_ipscrub_module.c index 09a2ef4..78361df 100644 --- a/ipscrub/src/ngx_ipscrub_module.c +++ b/ipscrub/src/ngx_ipscrub_module.c @@ -146,7 +146,12 @@ ngx_http_variable_remote_addr_ipscrub(ngx_http_request_t *r, ngx_http_variable_v // Regenerate salt if past end of period. time_t now = time(NULL); if (period_start == -1 || now - period_start > icf->period_seconds) { - nonce = ngx_random(); + // nonce = ngx_random(); + rc = randlong(&nonce); + if (rc != NGX_OK) { + return NGX_HTTP_INTERNAL_SERVER_ERROR; + } + // TODO: actually calculate when period_start should have been. period_start = now; } diff --git a/ipscrub/src/ngx_ipscrub_support.c b/ipscrub/src/ngx_ipscrub_support.c index c409d20..2f68691 100644 --- a/ipscrub/src/ngx_ipscrub_support.c +++ b/ipscrub/src/ngx_ipscrub_support.c @@ -36,3 +36,24 @@ ngx_int_t concat(ngx_pool_t *pool, ngx_str_t prefix, ngx_str_t suffix, u_char ** return NGX_OK; } + +// randlong fills out with secure random bytes and returns NGX_OK iff successful. +ngx_int_t randlong(long *out) { + #if !(NGX_DARWIN || NGX_SOLARIS || NGX_FREEBSD || NGX_LINUX) + // Windows not supported a.t.m. + // TODO: support Windows (https://msdn.microsoft.com/en-us/library/sxtz2fa8.aspx). + return -1; + #endif + + int rand = open("/dev/urandom", O_RDONLY); + if (rand < 0) { + return -1; + } + + ssize_t ret = read(rand, out, sizeof(long)); + if (ret != sizeof(long)) { + return -1; + } + + return NGX_OK; +} diff --git a/ipscrub/src/ngx_ipscrub_support.h b/ipscrub/src/ngx_ipscrub_support.h index e509f07..7509911 100644 --- a/ipscrub/src/ngx_ipscrub_support.h +++ b/ipscrub/src/ngx_ipscrub_support.h @@ -8,5 +8,6 @@ ngx_int_t null_terminate(ngx_pool_t *pool, ngx_str_t input, u_char **hashed); ngx_int_t concat(ngx_pool_t *pool, ngx_str_t prefix, ngx_str_t suffix, u_char **out); +ngx_int_t randlong(long *out); #endif /* _IPSCRUB_SUPPORT_H_INCLUDED_ */