From 20dd1ddc60085f991a8b79bec38107221ffc2340 Mon Sep 17 00:00:00 2001 From: Andrew Kozlik Date: Tue, 14 Apr 2020 15:22:02 +0200 Subject: [PATCH] crypto: Fix buffer overflow in b58tobin. --- crypto/base58.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/crypto/base58.c b/crypto/base58.c index d95ac9a9d..faa763501 100644 --- a/crypto/base58.c +++ b/crypto/base58.c @@ -46,6 +46,9 @@ typedef uint32_t b58_almostmaxint_t; static const b58_almostmaxint_t b58_almostmaxint_mask = ((((b58_maxint_t)1) << b58_almostmaxint_bits) - 1); +// Decodes a null-terminated Base58 string `b58` to binary and writes the result +// at the end of the buffer `bin` of size `*binszp`. On success `*binszp` is set +// to the number of valid bytes at the end of the buffer. bool b58tobin(void *bin, size_t *binszp, const char *b58) { size_t binsz = *binszp; @@ -108,20 +111,18 @@ bool b58tobin(void *bin, size_t *binszp, const char *b58) { } } - // Count canonical base58 byte count + // locate the most significant byte binu = bin; for (i = 0; i < binsz; ++i) { - if (binu[i]) { - if (zerocount > i) { - /* result too large */ - return false; - } + if (binu[i]) break; + } - break; - } - --*binszp; + // prepend the correct number of null-bytes + if (zerocount > i) { + /* result too large */ + return false; } - *binszp += zerocount; + *binszp = binsz - i + zerocount; return true; }