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 0c536dbde..3ae51dc92 100644 --- a/tests/api.c +++ b/tests/api.c @@ -72663,10 +72663,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));