Fix off-by-one error in BN_bn2hex
authorMatt Caswell <matt@openssl.org>
Tue, 19 May 2015 12:59:47 +0000 (13:59 +0100)
committerMatt Caswell <matt@openssl.org>
Thu, 4 Jun 2015 08:23:02 +0000 (09:23 +0100)
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 <tjh@openssl.org>
crypto/bn/bn_print.c

index b0b70b5daee8bce5ba387587c7bff4770cb38e8d..f528a36ff489303e87b73f8a66c70300f99462b6 100644 (file)
@@ -71,7 +71,12 @@ char *BN_bn2hex(const BIGNUM *a)
     char *buf;
     char *p;
 
-    buf = 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;