From: Matt Caswell Date: Tue, 19 May 2015 12:59:47 +0000 (+0100) Subject: Fix off-by-one error in BN_bn2hex X-Git-Tag: OpenSSL_1_0_2b~32 X-Git-Url: https://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff_plain;h=361071993182c0a37d421e2ea9a1f84ec4f1ac4f;hp=af3aa2b5ef741a35394c92872cbdbab4d46b9c90 Fix off-by-one error in BN_bn2hex A BIGNUM can have the value of -0. The function BN_bn2hex fails to account for this and can allocate a buffer one byte too short in the event of -0 being used, leading to a one byte buffer overrun. All usage within the OpenSSL library is considered safe. Any security risk is considered negligible. With thanks to Mateusz Kocielski (LogicalTrust), Marek Kroemeke and Filip Palian for discovering and reporting this issue. Reviewed-by: Tim Hudson (cherry picked from commit c56353071d9849220714d8a556806703771b9269) Conflicts: crypto/bn/bn_print.c --- diff --git a/crypto/bn/bn_print.c b/crypto/bn/bn_print.c index 4dcaae32bf..ab10b957ba 100644 --- a/crypto/bn/bn_print.c +++ b/crypto/bn/bn_print.c @@ -71,7 +71,12 @@ char *BN_bn2hex(const BIGNUM *a) char *buf; char *p; - buf = (char *)OPENSSL_malloc(a->top * BN_BYTES * 2 + 2); + if (a->neg && BN_is_zero(a)) { + /* "-0" == 3 bytes including NULL terminator */ + buf = OPENSSL_malloc(3); + } else { + buf = OPENSSL_malloc(a->top * BN_BYTES * 2 + 2); + } if (buf == NULL) { BNerr(BN_F_BN_BN2HEX, ERR_R_MALLOC_FAILURE); goto err;