From 3c5c0f88d44c16a0e392c4b971b0307714b71f0a Mon Sep 17 00:00:00 2001 From: kaleb-himes Date: Thu, 23 Jul 2020 12:20:41 -0600 Subject: [PATCH] Address buffer underflow, thanks to J.S. for the report on ZD10580 --- wolfcrypt/src/asn.c | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index 54f91d7b8..f9c90a745 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -10555,9 +10555,22 @@ int PemToDer(const unsigned char* buff, long longSz, int type, #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD #ifndef NO_DES3 if (info->cipherType == WC_CIPHER_DES3) { - padVal = der->buffer[der->length-1]; - if (padVal <= DES_BLOCK_SIZE) { - der->length -= padVal; + /* Assuming there is padding: + * (der->length > 0 && + * (der->length % DES_BLOCK_SIZE) != 0) + * and assuming the last value signifies the number of + * padded bytes IE if last value is 0x08 then there are + * 8 bytes of padding: + * padVal = der->buffer[der->length-1]; + * then strip this padding before proceeding: + * der->length -= padVal; + */ + if (der->length > 0 && + (der->length % DES_BLOCK_SIZE) != 0) { + padVal = der->buffer[der->length-1]; + if (padVal <= DES_BLOCK_SIZE) { + der->length -= padVal; + } } } #endif /* !NO_DES3 */