From ae8b8c4164705046aa9cce1e7e4f2e4766e2b71f Mon Sep 17 00:00:00 2001 From: Sean Parkinson Date: Fri, 7 Feb 2025 08:28:56 +1000 Subject: [PATCH] Read DER BIO: fix for when BIO data is less than seq buffer size wolfssl_read_der_bio did not not handle the length to be read from the BIO being less than the size of the sequence buffer. --- src/pk.c | 6 +++++- tests/api.c | 5 +++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/pk.c b/src/pk.c index 3cbfc7752..4466c0a1e 100644 --- a/src/pk.c +++ b/src/pk.c @@ -1558,7 +1558,11 @@ static int wolfssl_read_der_bio(WOLFSSL_BIO* bio, unsigned char** out) WOLFSSL_ERROR_MSG("Malloc failure"); err = 1; } - if (!err) { + if ((!err) && (derLen <= (int)sizeof(seq))) { + /* Copy the previously read data into the buffer. */ + XMEMCPY(der, seq, derLen); + } + else if (!err) { /* Calculate the unread amount. */ int len = derLen - (int)sizeof(seq); /* Copy the previously read data into the buffer. */ diff --git a/tests/api.c b/tests/api.c index 410ea272a..1f3b72fc7 100644 --- a/tests/api.c +++ b/tests/api.c @@ -72654,10 +72654,15 @@ static int test_wolfSSL_d2i_PrivateKeys_bio(void) #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) { + const unsigned char seqOnly[] = { 0x30, 0x00, 0x00, 0x00, 0x00, 0x00 }; RSA* rsa = NULL; /* Tests bad parameters */ ExpectNull(d2i_RSAPrivateKey_bio(NULL, NULL)); + /* Test using bad data. */ + ExpectIntGT(BIO_write(bio, seqOnly, sizeof(seqOnly)), 0); + ExpectNull(d2i_RSAPrivateKey_bio(bio, NULL)); + /* RSA not set yet, expecting to fail*/ rsa = wolfSSL_RSA_new(); ExpectIntEQ(SSL_CTX_use_RSAPrivateKey(ctx, rsa), WC_NO_ERR_TRACE(WOLFSSL_FAILURE));