From 69749e8f994b42c8af835d55b3a8be757df7fab9 Mon Sep 17 00:00:00 2001 From: Takashi Kojo Date: Thu, 30 Jul 2026 16:20:47 +0900 Subject: [PATCH] Reset MlDsaKey between decode attempts in X509_set_pubkey --- src/x509.c | 10 ++++++++++ tests/api/test_ossl_x509_pk.c | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/x509.c b/src/x509.c index e481f490d9..1c3109e02c 100644 --- a/src/x509.c +++ b/src/x509.c @@ -16600,6 +16600,16 @@ int wolfSSL_X509_set_pubkey(WOLFSSL_X509 *cert, WOLFSSL_EVP_PKEY *pkey) PRIVATE_KEY_LOCK(); #endif if (!decodeOk) { + #ifdef WOLFSSL_MLDSA_PRIVATE_KEY + /* A failed PrivateKeyDecode may leave the level pinned; + * reset the key so PublicKeyDecode auto-detects it from + * the SPKI OID. */ + wc_MlDsaKey_Free(mldsa); + if (wc_MlDsaKey_Init(mldsa, NULL, INVALID_DEVID) != 0) { + XFREE(mldsa, cert->heap, DYNAMIC_TYPE_MLDSA); + return WOLFSSL_FAILURE; + } + #endif idx = 0; if (wc_MlDsaKey_PublicKeyDecode(mldsa, (const byte*)pkey->pkey.ptr, (word32)pkey->pkey_sz, diff --git a/tests/api/test_ossl_x509_pk.c b/tests/api/test_ossl_x509_pk.c index 6c5daffc1d..6f65337403 100644 --- a/tests/api/test_ossl_x509_pk.c +++ b/tests/api/test_ossl_x509_pk.c @@ -405,6 +405,30 @@ int test_wolfSSL_X509_set_pubkey(void) pubkey = NULL; } #endif + + /* Public-only EVP_PKEY holding an SPKI: the private-key decode + * fails and the fallback public decode must work on a reset key. */ + { + WOLFSSL_EVP_PKEY* spki = NULL; + unsigned char der[2048]; + int derSz = 0; + const unsigned char* pp = der; + XFILE f = XBADFILE; + + ExpectTrue((f = XFOPEN("./certs/mldsa/mldsa44_pub-spki.der", + "rb")) != XBADFILE); + ExpectIntGT(derSz = (int)XFREAD(der, 1, sizeof(der), f), 0); + if (f != XBADFILE) + XFCLOSE(f); + ExpectNotNull(spki = wolfSSL_d2i_PUBKEY(NULL, &pp, (long)derSz)); + ExpectIntEQ(wolfSSL_X509_set_pubkey(x509, spki), WOLFSSL_SUCCESS); + ExpectNotNull(pubkey = wolfSSL_X509_get_pubkey(x509)); + ExpectIntEQ(wolfSSL_EVP_PKEY_id(pubkey), WC_EVP_PKEY_DILITHIUM); + wolfSSL_EVP_PKEY_free(pubkey); + pubkey = NULL; + wolfSSL_EVP_PKEY_free(spki); + } + wolfSSL_EVP_PKEY_free(pkey); pkey = NULL; }