From b2aaa95cb617b29c099c13a7604189e0de4d5f0c Mon Sep 17 00:00:00 2001 From: Sameeh Date: Fri, 23 Oct 2026 13:25:17 +0300 Subject: [PATCH 1/6] Keep CA restrictions when restoring the persisted cert cache The PERSIST_CERT_CACHE save/restore of the CA table only stored the public key, key OID, common name and name hashes of each Signer. Everything else FillSigner takes from the certificate (key usage, extended key usage, path length, self-signed flag, name constraints, AKID, issuer and serial hashes, ...) came back zeroed after a restore, so a restored CA table did not behave like the one that was saved. Store the DER encoding and type of each CA instead and rebuild the Signer with ParseCert/FillSigner on restore, so new Signer fields are picked up without having to change the cache layout again. PERSIST_CERT_CACHE now enables WOLFSSL_SIGNER_DER_CERT so the CA table keeps the DER. The restored signers are built into a separate table and swapped in under the CA lock, so a failed restore leaves the existing CA table in place. Bump WOLFSSL_CACHE_CERT_VERSION to 2 so caches in the old layout are rejected with CACHE_MATCH_ERROR. Add a test that saves and restores a cache holding a name-constrained CA chain and checks a leaf outside the permitted subtree is still rejected. --- src/ssl_certman.c | 302 +++++++++++++++++++---------------- tests/api/test_certman.c | 68 ++++++++ tests/api/test_certman.h | 3 + wolfssl/wolfcrypt/settings.h | 7 + 4 files changed, 240 insertions(+), 140 deletions(-) diff --git a/src/ssl_certman.c b/src/ssl_certman.c index 0946251320b..99169c4a096 100644 --- a/src/ssl_certman.c +++ b/src/ssl_certman.c @@ -1256,7 +1256,7 @@ int wolfSSL_CertManagerLoadCA(WOLFSSL_CERT_MANAGER* cm, const char* file, #if defined(PERSIST_CERT_CACHE) /* Version of layout of cache of CA certificates. */ -#define WOLFSSL_CACHE_CERT_VERSION 1 +#define WOLFSSL_CACHE_CERT_VERSION 2 /* CA certificates cache information. */ typedef struct { @@ -1273,12 +1273,21 @@ typedef struct { /* current cert persistence layout is: 1) CertCacheHeader - 2) caTable + 2) caTable, each Signer stored as: + a) DER length (word32) + b) Signer type (byte) + c) DER encoding of CA certificate - update WOLFSSL_CERT_CACHE_VERSION if change layout for the following + The Signer is rebuilt from the DER on restore so that everything FillSigner + takes from the certificate (key usage, path length, name constraints, ...) + is restored, not only the public key and name hashes. + + update WOLFSSL_CACHE_CERT_VERSION if change layout for the following PERSIST_CERT_CACHE functions */ +static WC_INLINE word32 HashSigner(const byte* hash); + /* Return number of bytes of memory needed to persist this signer. * @@ -1289,16 +1298,13 @@ typedef struct { */ static WC_INLINE int cm_get_signer_memory(Signer* signer) { - int sz = sizeof(signer->pubKeySize) + sizeof(signer->keyOID) - + sizeof(signer->nameLen) + sizeof(signer->subjectNameHash); - -#if !defined(NO_SKID) - sz += (int)sizeof(signer->subjectKeyIdHash); -#endif + int sz = 0; - /* Add dynamic bytes needed. */ - sz += (int)signer->pubKeySize; - sz += signer->nameLen; + /* Signers without a DER copy can't be rebuilt and are not stored. + * FillSigner always keeps one when PERSIST_CERT_CACHE is defined. */ + if ((signer->derCert != NULL) && (signer->derCert->buffer != NULL)) { + sz = (int)sizeof(word32) + 1 + (int)signer->derCert->length; + } return sz; } @@ -1371,8 +1377,10 @@ static WC_INLINE void cm_set_cert_header_Columns(WOLFSSL_CERT_MANAGER* cm, row = cm->caTable[i]; /* Each entry in row. */ while (row != NULL) { - /* Update count. */ - ++count; + /* Update count when this entry is stored. */ + if (cm_get_signer_memory(row) > 0) { + ++count; + } row = row->next; } /* Store row count. */ @@ -1381,15 +1389,73 @@ static WC_INLINE void cm_set_cert_header_Columns(WOLFSSL_CERT_MANAGER* cm, } -/* Restore whole cert row from memory, +/* Rebuild a Signer from the DER encoding of a CA certificate. * - * Assumes we have locked CA table. + * Does not lock the CA table: parsing a certificate may look up its issuer. + * The certificate was checked when it was first added, so it is not verified + * again here. * - * @param [in] cm Certificate manager. - * @param [in] current Buffer containing rows. - * @param [in] row Row number being restored. - * @param [in] listSz Number of entries in row. - * @param [in] end End of data in buffer. + * @param [in] cm Certificate manager. + * @param [in] derBuf DER encoding of certificate. + * @param [in] derSz Size of DER encoding in bytes. + * @param [in] type Type of Signer. + * @param [out] pSigner New Signer. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + * @return Negative value on parse error. + */ +static int cm_restore_signer(WOLFSSL_CERT_MANAGER* cm, const byte* derBuf, + word32 derSz, byte type, Signer** pSigner) +{ + int ret; + Signer* signer = NULL; + DerBuffer* der = NULL; + WC_DECLARE_VAR(cert, DecodedCert, 1, 0); + + WC_ALLOC_VAR_EX(cert, DecodedCert, 1, cm->heap, DYNAMIC_TYPE_DCERT, + return MEMORY_E); + + ret = AllocDer(&der, derSz, CA_TYPE, cm->heap); + if (ret == 0) { + XMEMCPY(der->buffer, derBuf, derSz); + + InitDecodedCert(cert, der->buffer, der->length, cm->heap); + #ifdef WC_ASN_UNKNOWN_EXT_CB + if (cm->unknownExtCallback != NULL) { + wc_SetUnknownExtCallback(cert, cm->unknownExtCallback); + } + #endif + ret = ParseCert(cert, CA_TYPE, NO_VERIFY, cm); + if ((ret == 0) && ((signer = MakeSigner(cm->heap)) == NULL)) { + ret = MEMORY_E; + } + if (ret == 0) { + ret = FillSigner(signer, cert, type, der); + } + FreeDecodedCert(cert); + } + + if ((ret != 0) && (signer != NULL)) { + FreeSigner(signer, cm->heap); + signer = NULL; + } + FreeDer(&der); + WC_FREE_VAR_EX(cert, cm->heap, DYNAMIC_TYPE_DCERT); + + *pSigner = signer; + return ret; +} + + +/* Restore whole cert row from memory into a table. + * + * Does not lock the CA table - signers are added to table passed in. + * + * @param [in] cm Certificate manager. + * @param [in] current Buffer containing rows. + * @param [in] listSz Number of entries in row. + * @param [in] end End of data in buffer. + * @param [in, out] table Table of signers to add restored signers to. * @return Number of bytes consumed on success. * @return PARSE_ERROR when listSz is less than zero. * @return BUFFER_E when buffer is too small. @@ -1397,7 +1463,7 @@ static WC_INLINE void cm_set_cert_header_Columns(WOLFSSL_CERT_MANAGER* cm, * @return Negative value on error. */ static WC_INLINE int cm_restore_cert_row(WOLFSSL_CERT_MANAGER* cm, - byte* current, int row, int listSz, const byte* end) + const byte* current, int listSz, const byte* end, Signer** table) { int ret = 0; int idx = 0; @@ -1411,104 +1477,50 @@ static WC_INLINE int cm_restore_cert_row(WOLFSSL_CERT_MANAGER* cm, /* Process all entries. */ while ((ret == 0) && (listSz > 0)) { Signer* signer = NULL; - byte* publicKey; - byte* start = current + idx; /* for end checks on this signer */ - int minSz = sizeof(signer->pubKeySize) + sizeof(signer->keyOID) + - sizeof(signer->nameLen) + sizeof(signer->subjectNameHash); - #ifndef NO_SKID - minSz += (int)sizeof(signer->subjectKeyIdHash); - #endif + word32 derSz; + byte type; - /* Check minimal size of bytes available. */ - if (start + minSz > end) { + /* Check bytes available for DER length and Signer type. */ + if ((word32)(end - (current + idx)) < (word32)sizeof(word32) + 1) { WOLFSSL_MSG("Would overread restore buffer"); ret = BUFFER_E; } - /* Make a new signer. */ - if ((ret == 0) && ((signer = MakeSigner(cm->heap)) == NULL)) { - ret = MEMORY_E; - } - - if (ret == 0) { - /* Copy in public key size. */ - XMEMCPY(&signer->pubKeySize, current + idx, - sizeof(signer->pubKeySize)); - idx += (int)sizeof(signer->pubKeySize); - - /* Copy in public key OID. */ - XMEMCPY(&signer->keyOID, current + idx, sizeof(signer->keyOID)); - idx += (int)sizeof(signer->keyOID); - - /* Check bytes available for public key. */ - if (start + minSz + signer->pubKeySize > end) { - WOLFSSL_MSG("Would overread restore buffer"); - ret = BUFFER_E; - } - } - if (ret == 0) { - /* Allocate memory for public key to be stored in. */ - publicKey = (byte*)XMALLOC(signer->pubKeySize, cm->heap, - DYNAMIC_TYPE_KEY); - if (publicKey == NULL) { - ret = MEMORY_E; - } - } - if (ret == 0) { - /* Copy in public key. */ - XMEMCPY(publicKey, current + idx, signer->pubKeySize); - signer->publicKey = publicKey; - idx += (int)signer->pubKeySize; - - /* Copy in certificate name length. */ - XMEMCPY(&signer->nameLen, current + idx, sizeof(signer->nameLen)); - idx += (int)sizeof(signer->nameLen); - - /* Check bytes available for certificate name. */ - if (start + minSz + signer->pubKeySize + signer->nameLen > end) { + /* Copy in DER length. */ + XMEMCPY(&derSz, current + idx, sizeof(derSz)); + idx += (int)sizeof(derSz); + /* Copy in Signer type. */ + type = current[idx]; + idx += 1; + + /* Check bytes available for DER. */ + if ((derSz == 0) || ((word32)(end - (current + idx)) < derSz)) { WOLFSSL_MSG("Would overread restore buffer"); ret = BUFFER_E; } } if (ret == 0) { - /* Allocate memory for public key to be stored in. */ - signer->name = (char*)XMALLOC((size_t)signer->nameLen, cm->heap, - DYNAMIC_TYPE_SUBJECT_CN); - if (signer->name == NULL) { - ret = MEMORY_E; - } + /* Rebuild Signer from certificate. */ + ret = cm_restore_signer(cm, current + idx, derSz, type, &signer); } - if (ret == 0) { - /* Copy in certificate name. */ - /* safe cast -- allocated by above XMALLOC(). */ - XMEMCPY((void *)(wc_ptr_t)signer->name, current + idx, - (size_t)signer->nameLen); - idx += signer->nameLen; - - /* Copy in hash of subject name. */ - XMEMCPY(signer->subjectNameHash, current + idx, SIGNER_DIGEST_SIZE); - idx += SIGNER_DIGEST_SIZE; + Signer** last; + idx += (int)derSz; + /* Append to row of table, keeping the order it was stored in. */ #ifndef NO_SKID - /* Copy in hash of subject key. */ - XMEMCPY(signer->subjectKeyIdHash, current + idx,SIGNER_DIGEST_SIZE); - idx += SIGNER_DIGEST_SIZE; + last = &table[HashSigner(signer->subjectKeyIdHash)]; + #else + last = &table[HashSigner(signer->subjectNameHash)]; #endif - - /* Make next Signer the head of the row. */ - signer->next = cm->caTable[row]; - /* Add Signer to start of row. */ - cm->caTable[row] = signer; + while (*last != NULL) { + last = &(*last)->next; + } + *last = signer; /* Done one more Signer. */ --listSz; } - - if ((ret != 0) && (signer != NULL)) { - /* Dispose of allocated signer. */ - FreeSigner(signer, cm->heap); - } } if (ret == 0) { @@ -1538,35 +1550,21 @@ static WC_INLINE int cm_store_cert_row(WOLFSSL_CERT_MANAGER* cm, byte* current, list = cm->caTable[row]; /* Each certificate in row. */ while (list != NULL) { - /* Public key size. */ - XMEMCPY(current + added, &list->pubKeySize, sizeof(list->pubKeySize)); - added += (int)sizeof(list->pubKeySize); - - /* Public key OID. */ - XMEMCPY(current + added, &list->keyOID, sizeof(list->keyOID)); - added += (int)sizeof(list->keyOID); + if (cm_get_signer_memory(list) > 0) { + word32 derSz = list->derCert->length; - /* Public key. */ - XMEMCPY(current + added, list->publicKey, (size_t)list->pubKeySize); - added += (int)list->pubKeySize; + /* DER length. */ + XMEMCPY(current + added, &derSz, sizeof(derSz)); + added += (int)sizeof(derSz); - /* Certificate name length. */ - XMEMCPY(current + added, &list->nameLen, sizeof(list->nameLen)); - added += (int)sizeof(list->nameLen); + /* Signer type. */ + current[added] = list->type; + added += 1; - /* Certificate name. */ - XMEMCPY(current + added, list->name, (size_t)list->nameLen); - added += list->nameLen; - - /* Hash of subject name. */ - XMEMCPY(current + added, list->subjectNameHash, SIGNER_DIGEST_SIZE); - added += SIGNER_DIGEST_SIZE; - - #ifndef NO_SKID - /* Hash of public key. */ - XMEMCPY(current + added, list->subjectKeyIdHash,SIGNER_DIGEST_SIZE); - added += SIGNER_DIGEST_SIZE; - #endif + /* DER encoding of certificate. */ + XMEMCPY(current + added, list->derCert->buffer, derSz); + added += (int)derSz; + } /* Next certificate in row. */ list = list->next; @@ -1803,9 +1801,10 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) { int ret = WOLFSSL_SUCCESS; int i; - CertCacheHeader* hdr = (CertCacheHeader*)mem; - byte* current = (byte*)mem + sizeof(CertCacheHeader); - byte* end = (byte*)mem + sz; /* don't go over */ + const CertCacheHeader* hdr = (const CertCacheHeader*)mem; + const byte* current = (const byte*)mem + sizeof(CertCacheHeader); + const byte* end = (const byte*)mem + sz; /* don't go over */ + Signer** table = NULL; WOLFSSL_ENTER("CM_MemRestoreCertCache"); @@ -1824,21 +1823,24 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) ret = CACHE_MATCH_ERROR; } - /* Lock CA table. */ - if ((ret == WOLFSSL_SUCCESS) && (wc_LockMutex(&cm->caLock) != 0)) { - WOLFSSL_MSG("wc_LockMutex on caLock failed"); - ret = BAD_MUTEX_E; + if (ret == WOLFSSL_SUCCESS) { + /* Signers are rebuilt into a new table without the CA table locked as + * parsing a certificate may look up its issuer. */ + table = (Signer**)XMALLOC(sizeof(Signer*) * CA_TABLE_SIZE, cm->heap, + DYNAMIC_TYPE_TMP_BUFFER); + if (table == NULL) { + ret = MEMORY_E; + } + else { + XMEMSET(table, 0, sizeof(Signer*) * CA_TABLE_SIZE); + } } - if (ret == WOLFSSL_SUCCESS) { - /* Dispose of current CA certificate table. */ - FreeSignerTable(cm->caTable, CA_TABLE_SIZE, cm->heap); - /* Each row. */ for (i = 0; i < CA_TABLE_SIZE; ++i) { /* Restore a row from memory. */ - int added = cm_restore_cert_row(cm, current, i, hdr->columns[i], - end); + int added = cm_restore_cert_row(cm, current, hdr->columns[i], end, + table); /* Bail on error. */ if (added < 0) { WOLFSSL_MSG("cm_restore_cert_row error"); @@ -1848,11 +1850,31 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) /* Update pointer to data of next row. */ current += added; } + } + + /* Lock CA table. */ + if ((ret == WOLFSSL_SUCCESS) && (wc_LockMutex(&cm->caLock) != 0)) { + WOLFSSL_MSG("wc_LockMutex on caLock failed"); + ret = BAD_MUTEX_E; + } + + if (ret == WOLFSSL_SUCCESS) { + /* Dispose of current CA certificate table. */ + FreeSignerTable(cm->caTable, CA_TABLE_SIZE, cm->heap); + /* Move in restored signers. */ + XMEMCPY(cm->caTable, table, sizeof(Signer*) * CA_TABLE_SIZE); + XMEMSET(table, 0, sizeof(Signer*) * CA_TABLE_SIZE); /* Unlock CA table. */ wc_UnLockMutex(&cm->caLock); } + if (table != NULL) { + /* Dispose of any signers restored before a failure. */ + FreeSignerTable(table, CA_TABLE_SIZE, cm->heap); + XFREE(table, cm->heap, DYNAMIC_TYPE_TMP_BUFFER); + } + return ret; } diff --git a/tests/api/test_certman.c b/tests/api/test_certman.c index 2b8f2064c34..43fda0ef233 100644 --- a/tests/api/test_certman.c +++ b/tests/api/test_certman.c @@ -5303,6 +5303,74 @@ int test_wolfSSL_CertManagerNameConstraint_skid_disambiguates(void) return EXPECT_RESULT(); } +/* CA certificates restored from a persisted cache keep their name + * constraints: the restored chain still rejects a leaf outside the permitted + * subtree of the intermediate's issuer. */ +int test_wolfSSL_CertManagerNameConstraint_cert_cache(void) +{ + EXPECT_DECLS; +#if defined(PERSIST_CERT_CACHE) && !defined(NO_FILESYSTEM) && \ + !defined(NO_CERTS) && !defined(NO_TLS) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_CM_VERIFY) && defined(HAVE_ECC) && \ + !defined(IGNORE_NAME_CONSTRAINTS) && !defined(NO_SHA256) && \ + defined(WOLFSSL_ALT_NAMES) && \ + (defined(WOLFSSL_PEM_TO_DER) || defined(OPENSSL_EXTRA)) + WOLFSSL_CTX* ctx = NULL; + WOLFSSL_CERT_MANAGER* cm = NULL; + byte* cache = NULL; + int cacheSz = 0; + int used = 0; + const char* root_cert = + "./certs/test/nc-ancestor/00-root-cert.pem"; + const char* uri_permit_ca_cert = + "./certs/test/nc-ancestor/01-uri-permit-ca-cert.pem"; + const char* benign_sub_ca_cert = + "./certs/test/nc-ancestor/02-benign-sub-ca-cert.pem"; + const char* valid_leaf_cert = + "./certs/test/nc-ancestor/03-valid-leaf-cert.pem"; + const char* attacker_leaf_chain = + "./certs/test/nc-ancestor/03-leaf-chain.pem"; + + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, root_cert, NULL), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, uri_permit_ca_cert, + NULL), WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, benign_sub_ca_cert, + NULL), WOLFSSL_SUCCESS); + + ExpectIntGT(cacheSz = wolfSSL_CTX_get_cert_cache_memsize(ctx), 0); + ExpectNotNull(cache = (byte*)XMALLOC((size_t)cacheSz, NULL, + DYNAMIC_TYPE_TMP_BUFFER)); + ExpectIntEQ(wolfSSL_CTX_memsave_cert_cache(ctx, cache, cacheSz, &used), + WOLFSSL_SUCCESS); + ExpectIntEQ(used, cacheSz); + wolfSSL_CTX_free(ctx); + ctx = NULL; + + /* Restore into a context that has never loaded the CAs. */ + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(wolfSSL_CTX_memrestore_cert_cache(ctx, cache, used), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_get_cert_cache_memsize(ctx), used); + ExpectNotNull(cm = wolfSSL_CTX_GetCertManager(ctx)); + + /* Positive: leaf satisfies the grandparent permit. */ + ExpectIntEQ(wolfSSL_CertManagerVerify(cm, valid_leaf_cert, + WOLFSSL_FILETYPE_PEM), + WOLFSSL_SUCCESS); + + /* Negative: leaf violates the grandparent permit. */ + ExpectIntEQ(wolfSSL_CertManagerVerify(cm, attacker_leaf_chain, + WOLFSSL_FILETYPE_PEM), + WC_NO_ERR_TRACE(ASN_NAME_INVALID_E)); + + wolfSSL_CTX_free(ctx); + XFREE(cache, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return EXPECT_RESULT(); +} + #if defined(WOLFSSL_TRUST_PEER_CERT) && !defined(NO_ASN_TIME_CHECK) && \ defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) /* Before the validity period of certs/test/expired/expired-cert.pem */ diff --git a/tests/api/test_certman.h b/tests/api/test_certman.h index feb9cb687fa..32baff7b3b1 100644 --- a/tests/api/test_certman.h +++ b/tests/api/test_certman.h @@ -68,6 +68,7 @@ int test_wolfSSL_CertManagerRejectRPK(void); int test_wolfSSL_X509_V_ERR_strings(void); int test_wolfSSL_CertManagerNameConstraint_valid_chain(void); int test_wolfSSL_CertManagerNameConstraint_skid_disambiguates(void); +int test_wolfSSL_CertManagerNameConstraint_cert_cache(void); int test_wolfSSL_trust_peer_cert_dates(void); #define TEST_CERTMAN_DECLS \ @@ -120,6 +121,8 @@ int test_wolfSSL_trust_peer_cert_dates(void); test_wolfSSL_CertManagerNameConstraint_valid_chain), \ TEST_DECL_GROUP("certman", \ test_wolfSSL_CertManagerNameConstraint_skid_disambiguates), \ + TEST_DECL_GROUP("certman", \ + test_wolfSSL_CertManagerNameConstraint_cert_cache), \ TEST_DECL_GROUP("certman", test_wolfSSL_trust_peer_cert_dates), \ TEST_DECL_GROUP("certman", \ test_wolfSSL_CertManagerCheckCRL_out_of_date), \ diff --git a/wolfssl/wolfcrypt/settings.h b/wolfssl/wolfcrypt/settings.h index d8b413eeb43..970a4adf628 100644 --- a/wolfssl/wolfcrypt/settings.h +++ b/wolfssl/wolfcrypt/settings.h @@ -5275,6 +5275,13 @@ blinding by defining WC_BLINDING_NO_RNG_ACKNOWLEDGE_WEAKNESS." #define WOLFSSL_SIGNER_DER_CERT #endif +/* The persistent CA cache stores each CA's DER and rebuilds the CA table from + * it, so the CA table must keep the DER. */ +#if defined(PERSIST_CERT_CACHE) + #undef WOLFSSL_SIGNER_DER_CERT + #define WOLFSSL_SIGNER_DER_CERT +#endif + /* * Keeps the "Finished" messages after a TLS handshake for use as the so-called * "tls-unique" channel binding. See comment in internal.h around clientFinished From 00f291a7ee055b79d3ecf2bc90e4f20560651435 Mon Sep 17 00:00:00 2001 From: Sameeh Date: Fri, 23 Oct 2026 18:04:02 +0300 Subject: [PATCH 2/6] Restore the issuer path length when loading a persisted CA cache Rebuilding each CA from its DER recovers the path length stored in that certificate. It does not recover the tighter limit ParseCert copies from the issuer, because restore parses each CA before the new table is installed. After every CA is rebuilt, apply that inherited limit from the restored table before swapping it in. Add a test that saves and restores the chainJ CA set and checks that a further CA under an issuer whose effective path length is 0 is still rejected. --- src/ssl_certman.c | 249 ++++++++++++++++++++++++++++++++++++++- tests/api/test_certman.c | 74 ++++++++++++ tests/api/test_certman.h | 2 + 3 files changed, 324 insertions(+), 1 deletion(-) diff --git a/src/ssl_certman.c b/src/ssl_certman.c index 99169c4a096..6f2611b3f5b 100644 --- a/src/ssl_certman.c +++ b/src/ssl_certman.c @@ -1280,7 +1280,9 @@ typedef struct { The Signer is rebuilt from the DER on restore so that everything FillSigner takes from the certificate (key usage, path length, name constraints, ...) - is restored, not only the public key and name hashes. + is restored, not only the public key and name hashes. The path length a CA + inherits from its issuer is not in the certificate. After every CA is + rebuilt, that limit is applied from the new table. update WOLFSSL_CACHE_CERT_VERSION if change layout for the following PERSIST_CERT_CACHE functions @@ -1430,6 +1432,16 @@ static int cm_restore_signer(WOLFSSL_CERT_MANAGER* cm, const byte* derBuf, ret = MEMORY_E; } if (ret == 0) { + /* ParseCert can tighten maxPathLen from an issuer already in the + * live table. That table is replaced by this restore, so keep + * only the path length stored in this certificate. The inherited + * limit is applied once every restored CA is present. */ + if (cert->pathLengthSet) { + cert->maxPathLen = cert->pathLength; + } + else { + cert->maxPathLen = (word16)WOLFSSL_MAX_PATH_LEN; + } ret = FillSigner(signer, cert, type, der); } FreeDecodedCert(cert); @@ -1785,6 +1797,232 @@ int CM_MemSaveCertCache(WOLFSSL_CERT_MANAGER* cm, void* mem, int sz, int* used) } +/* Issuer name hash is present on Signer when any of these are enabled. + * The same condition gates issuerNameHash in wolfcrypt/asn.h. */ +#if defined(HAVE_OCSP) || defined(HAVE_CRL) || defined(WOLFSSL_AKID_NAME) || \ + !defined(IGNORE_NAME_CONSTRAINTS) + #define CM_SIGNER_HAS_ISSUER_HASH +#endif + +#if !defined(NO_SKID) && !defined(IGNORE_NAME_CONSTRAINTS) +/* Find a signer in table by subject key identifier. + * + * Does not lock. table is private to the restore. + * + * @param [in] table CA table to search. + * @param [in] skid Subject key identifier hash. + * @return Matching signer, or NULL. + */ +static Signer* cm_table_find_skid(Signer** table, const byte* skid) +{ + Signer* s = table[HashSigner(skid)]; + + while (s != NULL) { + if (XMEMCMP(skid, s->subjectKeyIdHash, SIGNER_DIGEST_SIZE) == 0) { + return s; + } + s = s->next; + } + + return NULL; +} +#endif /* !NO_SKID && !IGNORE_NAME_CONSTRAINTS */ + +#ifdef CM_SIGNER_HAS_ISSUER_HASH +/* Find a signer in table by subject name hash. + * + * The row is selected by the subject key identifier when SKID is enabled, + * so the name hash can sit in any row. + * + * Does not lock. table is private to the restore. + * + * @param [in] table CA table to search. + * @param [in] nameHash Subject name hash. + * @return Matching signer, or NULL. + */ +static Signer* cm_table_find_name(Signer** table, const byte* nameHash) +{ + int row; + + for (row = 0; row < CA_TABLE_SIZE; row++) { + Signer* s = table[row]; + + while (s != NULL) { + if (XMEMCMP(nameHash, s->subjectNameHash, SIGNER_DIGEST_SIZE) == 0) { + return s; + } + s = s->next; + } + } + + return NULL; +} +#endif + +/* Return 1 when the signer is self-issued. + * + * A self-issued CA loaded as CA_TYPE does not inherit a path length. + * ParseCert skips the issuer lookup for that case. + * + * @param [in] s Signer to test. + * @return 1 when self-issued. + * @return 0 otherwise. + */ +static int cm_signer_is_self_issued(Signer* s) +{ +#ifdef CM_SIGNER_HAS_ISSUER_HASH + return XMEMCMP(s->subjectNameHash, s->issuerNameHash, + SIGNER_DIGEST_SIZE) == 0; +#else + return s->selfSigned; +#endif +} + +/* Find the issuer of s in table. + * + * Matches the CA_TYPE lookup in ParseCert: an authority key identifier is + * authoritative, and the name is used only when that identifier is absent. + * Does not lock. + * + * @param [in] table CA table to search. + * @param [in] s Signer whose issuer is required. + * @return Issuer signer, or NULL. + */ +static Signer* cm_table_find_issuer(Signer** table, Signer* s) +{ + Signer* issuer = NULL; + +#if !defined(NO_SKID) && !defined(IGNORE_NAME_CONSTRAINTS) + if (s->authKeyIdSet) { + issuer = cm_table_find_skid(table, s->authKeyIdHash); +#ifdef CM_SIGNER_HAS_ISSUER_HASH + if ((issuer != NULL) && + (XMEMCMP(issuer->subjectNameHash, s->issuerNameHash, + SIGNER_DIGEST_SIZE) != 0)) { + issuer = NULL; + } +#endif + /* AKID is authoritative. Do not fall back to the name. */ + return issuer; + } +#endif + +#ifdef CM_SIGNER_HAS_ISSUER_HASH + issuer = cm_table_find_name(table, s->issuerNameHash); +#else + (void)table; + (void)s; +#endif + + return issuer; +} + +/* Apply each restored CA's inherited path length. + * + * ParseCert records the issuer's path length on the signer when the issuer + * is already in the live table. Restore parses every CA before that table + * is installed, so each signer still has only its own path length. Recompute + * the RFC 5280 limit from the restored signers. A path length of 0 is stored + * and not rejected, matching ParseCert with NO_VERIFY. + * + * Repeat until the values stop changing so a child is limited by its + * issuer's final value, independent of hash-bucket order. + * + * Does not lock. + * + * @param [in, out] table Restored CA table. + * @param [in] heap Dynamic memory hint. + * @return 0 on success. + * @return MEMORY_E when dynamic memory allocation fails. + */ +static int cm_restore_apply_pathlen(Signer** table, void* heap) +{ + int count = 0; + int i; + int row; + int guard; + int changed; + struct { + Signer* signer; + word16 base; + }* refs; + + for (row = 0; row < CA_TABLE_SIZE; row++) { + Signer* s = table[row]; + + while (s != NULL) { + count++; + s = s->next; + } + } + if (count == 0) { + return 0; + } + + refs = XMALLOC(sizeof(*refs) * (size_t)count, heap, DYNAMIC_TYPE_TMP_BUFFER); + if (refs == NULL) { + return MEMORY_E; + } + + i = 0; + for (row = 0; row < CA_TABLE_SIZE; row++) { + Signer* s = table[row]; + + while (s != NULL) { + refs[i].signer = s; + refs[i].base = s->maxPathLen; + i++; + s = s->next; + } + } + + for (guard = 0; guard < count; guard++) { + changed = 0; + for (i = 0; i < count; i++) { + Signer* s = refs[i].signer; + Signer* issuer; + word16 next; + + /* Absent key usage is stored as all uses, including keyCertSign. + * ParseCert skips the path length check when that bit is clear. */ + if ((s->keyUsage & KEYUSE_KEY_CERT_SIGN) == 0) { + continue; + } + if (cm_signer_is_self_issued(s)) { + continue; + } + + issuer = cm_table_find_issuer(table, s); + if ((issuer == NULL) || (issuer == s)) { + continue; + } + + if (issuer->maxPathLen == 0) { + next = 0; + } + else { + next = (word16)((word32)issuer->maxPathLen - 1U); + if (next > refs[i].base) { + next = refs[i].base; + } + } + if (next != s->maxPathLen) { + s->maxPathLen = next; + changed = 1; + } + } + if (!changed) { + break; + } + } + + XFREE(refs, heap, DYNAMIC_TYPE_TMP_BUFFER); + return 0; +} + +#undef CM_SIGNER_HAS_ISSUER_HASH + + /* Restore CA certificate table from memory, * * Locks CA table. @@ -1852,6 +2090,15 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) } } + if (ret == WOLFSSL_SUCCESS) { + /* Inherited path length needs every issuer in the new table. */ + int pathRet = cm_restore_apply_pathlen(table, cm->heap); + + if (pathRet != 0) { + ret = pathRet; + } + } + /* Lock CA table. */ if ((ret == WOLFSSL_SUCCESS) && (wc_LockMutex(&cm->caLock) != 0)) { WOLFSSL_MSG("wc_LockMutex on caLock failed"); diff --git a/tests/api/test_certman.c b/tests/api/test_certman.c index 43fda0ef233..2c7c140ac04 100644 --- a/tests/api/test_certman.c +++ b/tests/api/test_certman.c @@ -5371,6 +5371,80 @@ int test_wolfSSL_CertManagerNameConstraint_cert_cache(void) return EXPECT_RESULT(); } +/* A CA restored from the cache keeps the path length it inherited from its + * issuer. chainJ-ICA4 allows two CA certificates below it. ICA3 and ICA2 + * have no path length of their own, so ICA2's effective limit becomes 0. + * A further CA (ICA1) is rejected before the save and after the restore. */ +int test_wolfSSL_CertManagerPathLen_cert_cache(void) +{ + EXPECT_DECLS; +#if defined(PERSIST_CERT_CACHE) && !defined(NO_FILESYSTEM) && \ + !defined(NO_CERTS) && !defined(NO_TLS) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_CM_VERIFY) && !defined(NO_RSA) && \ + !defined(NO_SHA256) && \ + (defined(WOLFSSL_PEM_TO_DER) || defined(OPENSSL_EXTRA)) && \ + (!defined(IGNORE_NAME_CONSTRAINTS) || defined(HAVE_OCSP) || \ + defined(HAVE_CRL) || defined(WOLFSSL_AKID_NAME)) + WOLFSSL_CTX* ctx = NULL; + WOLFSSL_CERT_MANAGER* cm = NULL; + byte* cache = NULL; + int cacheSz = 0; + int used = 0; + const char* root_cert = "./certs/ca-cert.pem"; + const char* ica4_cert = + "./certs/test-pathlen/chainJ-ICA4-pathlen2.pem"; + const char* ica3_cert = + "./certs/test-pathlen/chainJ-ICA3-no_pathlen.pem"; + const char* ica2_cert = + "./certs/test-pathlen/chainJ-ICA2-no_pathlen.pem"; + const char* ica1_cert = + "./certs/test-pathlen/chainJ-ICA1-no_pathlen.pem"; + + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, root_cert, NULL), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, ica4_cert, NULL), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, ica3_cert, NULL), + WOLFSSL_SUCCESS); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, ica2_cert, NULL), + WOLFSSL_SUCCESS); + + /* ICA2 can sign only an end entity. Loading the next CA fails. */ + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, ica1_cert, NULL), + WS_RETURN_CODE(WC_NO_ERR_TRACE(ASN_PATHLEN_INV_E), + WC_NO_ERR_TRACE(WOLFSSL_FAILURE))); + + ExpectIntGT(cacheSz = wolfSSL_CTX_get_cert_cache_memsize(ctx), 0); + ExpectNotNull(cache = (byte*)XMALLOC((size_t)cacheSz, NULL, + DYNAMIC_TYPE_TMP_BUFFER)); + ExpectIntEQ(wolfSSL_CTX_memsave_cert_cache(ctx, cache, cacheSz, &used), + WOLFSSL_SUCCESS); + ExpectIntEQ(used, cacheSz); + wolfSSL_CTX_free(ctx); + ctx = NULL; + + /* Restore into a context that has never loaded the CAs. */ + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(wolfSSL_CTX_memrestore_cert_cache(ctx, cache, used), + WOLFSSL_SUCCESS); + ExpectNotNull(cm = wolfSSL_CTX_GetCertManager(ctx)); + + /* Positive: ICA2 still chains to the restored issuer. */ + ExpectIntEQ(wolfSSL_CertManagerVerify(cm, ica2_cert, WOLFSSL_FILETYPE_PEM), + WOLFSSL_SUCCESS); + + /* Negative: the inherited path length of 0 still rejects ICA1. */ + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, ica1_cert, NULL), + WS_RETURN_CODE(WC_NO_ERR_TRACE(ASN_PATHLEN_INV_E), + WC_NO_ERR_TRACE(WOLFSSL_FAILURE))); + + wolfSSL_CTX_free(ctx); + XFREE(cache, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return EXPECT_RESULT(); +} + #if defined(WOLFSSL_TRUST_PEER_CERT) && !defined(NO_ASN_TIME_CHECK) && \ defined(HAVE_SSL_MEMIO_TESTS_DEPENDENCIES) /* Before the validity period of certs/test/expired/expired-cert.pem */ diff --git a/tests/api/test_certman.h b/tests/api/test_certman.h index 32baff7b3b1..7662de280d5 100644 --- a/tests/api/test_certman.h +++ b/tests/api/test_certman.h @@ -69,6 +69,7 @@ int test_wolfSSL_X509_V_ERR_strings(void); int test_wolfSSL_CertManagerNameConstraint_valid_chain(void); int test_wolfSSL_CertManagerNameConstraint_skid_disambiguates(void); int test_wolfSSL_CertManagerNameConstraint_cert_cache(void); +int test_wolfSSL_CertManagerPathLen_cert_cache(void); int test_wolfSSL_trust_peer_cert_dates(void); #define TEST_CERTMAN_DECLS \ @@ -123,6 +124,7 @@ int test_wolfSSL_trust_peer_cert_dates(void); test_wolfSSL_CertManagerNameConstraint_skid_disambiguates), \ TEST_DECL_GROUP("certman", \ test_wolfSSL_CertManagerNameConstraint_cert_cache), \ + TEST_DECL_GROUP("certman", test_wolfSSL_CertManagerPathLen_cert_cache), \ TEST_DECL_GROUP("certman", test_wolfSSL_trust_peer_cert_dates), \ TEST_DECL_GROUP("certman", \ test_wolfSSL_CertManagerCheckCRL_out_of_date), \ From 42216e8dd824d851f83e8d517fc05678aa2ad47e Mon Sep 17 00:00:00 2001 From: Sameeh Date: Fri, 23 Oct 2026 18:52:48 +0300 Subject: [PATCH 3/6] Turn verification on in the persisted path-length test A new context can load CAs with verification off. A path length of 0 is then stored and the load still succeeds, so the test accepted ICA1. Set the default verify mode before the load, which is what CertManagerLoadCA does, so that CA is rejected again. --- tests/api/test_certman.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/api/test_certman.c b/tests/api/test_certman.c index 2c7c140ac04..954307ae449 100644 --- a/tests/api/test_certman.c +++ b/tests/api/test_certman.c @@ -5401,6 +5401,10 @@ int test_wolfSSL_CertManagerPathLen_cert_cache(void) "./certs/test-pathlen/chainJ-ICA1-no_pathlen.pem"; ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + /* A new context can have verification off. Path length is then stored + * and the load still succeeds. Turn verification on so a path length + * of 0 is rejected, as CertManagerLoadCA does. */ + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_DEFAULT, NULL); ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, root_cert, NULL), WOLFSSL_SUCCESS); ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, ica4_cert, NULL), @@ -5426,6 +5430,7 @@ int test_wolfSSL_CertManagerPathLen_cert_cache(void) /* Restore into a context that has never loaded the CAs. */ ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_DEFAULT, NULL); ExpectIntEQ(wolfSSL_CTX_memrestore_cert_cache(ctx, cache, used), WOLFSSL_SUCCESS); ExpectNotNull(cm = wolfSSL_CTX_GetCertManager(ctx)); From e8fa94b3948aba51f27ec306bfbd432b70219ae8 Mon Sep 17 00:00:00 2001 From: Sameeh Date: Fri, 23 Oct 2026 19:10:47 +0300 Subject: [PATCH 4/6] Keep saved CA limits when the issuer is missing from the cache Restore can raise a path length to the certificate's own limit when the issuer is not in the restored table. Store the path length in use and do not raise it above that value. Store the OCSP issuer key hash as well, and copy the issuer's subject key hash when that issuer is restored. Pass the certificate heap to the CA DER allocation so a context memory pool is used. Bump the cache version to 3 so an older layout is rejected. The path length test now drops the CA that carries the path length extension before a second save and checks the descendant is still rejected. --- src/ssl_certman.c | 164 ++++++++++++++++++++++++++++++++++++--- tests/api/test_certman.c | 103 +++++++++++++++++++++++- wolfcrypt/src/asn.c | 2 +- 3 files changed, 256 insertions(+), 13 deletions(-) diff --git a/src/ssl_certman.c b/src/ssl_certman.c index 6f2611b3f5b..476445ac502 100644 --- a/src/ssl_certman.c +++ b/src/ssl_certman.c @@ -1256,7 +1256,7 @@ int wolfSSL_CertManagerLoadCA(WOLFSSL_CERT_MANAGER* cm, const char* file, #if defined(PERSIST_CERT_CACHE) /* Version of layout of cache of CA certificates. */ -#define WOLFSSL_CACHE_CERT_VERSION 2 +#define WOLFSSL_CACHE_CERT_VERSION 3 /* CA certificates cache information. */ typedef struct { @@ -1275,14 +1275,19 @@ typedef struct { 1) CertCacheHeader 2) caTable, each Signer stored as: a) DER length (word32) - b) Signer type (byte) - c) DER encoding of CA certificate + b) effective path length (word16) + c) Signer type (byte) + d) issuer key hash (KEYID_SIZE bytes, only when HAVE_OCSP is set) + e) DER encoding of CA certificate The Signer is rebuilt from the DER on restore so that everything FillSigner takes from the certificate (key usage, path length, name constraints, ...) is restored, not only the public key and name hashes. The path length a CA inherits from its issuer is not in the certificate. After every CA is - rebuilt, that limit is applied from the new table. + rebuilt, that limit is applied from the new table. The saved path length + is then applied as a ceiling, so a missing issuer cannot raise the limit. + When HAVE_OCSP is set, the issuer key hash is copied from the restored + issuer. If that issuer is not in the cache, the saved hash is kept. update WOLFSSL_CACHE_CERT_VERSION if change layout for the following PERSIST_CERT_CACHE functions @@ -1291,6 +1296,18 @@ typedef struct { static WC_INLINE word32 HashSigner(const byte* hash); +/* Bytes stored before the DER in one cache entry. */ +static WC_INLINE int cm_cache_entry_prefix(void) +{ + int sz = (int)sizeof(word32) + (int)sizeof(word16) + 1; + +#ifdef HAVE_OCSP + sz += KEYID_SIZE; +#endif + return sz; +} + + /* Return number of bytes of memory needed to persist this signer. * * Assumes we have locked CA table. @@ -1305,7 +1322,7 @@ static WC_INLINE int cm_get_signer_memory(Signer* signer) /* Signers without a DER copy can't be rebuilt and are not stored. * FillSigner always keeps one when PERSIST_CERT_CACHE is defined. */ if ((signer->derCert != NULL) && (signer->derCert->buffer != NULL)) { - sz = (int)sizeof(word32) + 1 + (int)signer->derCert->length; + sz = cm_cache_entry_prefix() + (int)signer->derCert->length; } return sz; @@ -1467,7 +1484,9 @@ static int cm_restore_signer(WOLFSSL_CERT_MANAGER* cm, const byte* derBuf, * @param [in] current Buffer containing rows. * @param [in] listSz Number of entries in row. * @param [in] end End of data in buffer. - * @param [in, out] table Table of signers to add restored signers to. + * @param [in, out] table Table of signers to add restored signers to. + * @param [out] savedPath Effective path length of each restored signer. + * @param [in, out] savedCount Number of path lengths written. * @return Number of bytes consumed on success. * @return PARSE_ERROR when listSz is less than zero. * @return BUFFER_E when buffer is too small. @@ -1475,7 +1494,8 @@ static int cm_restore_signer(WOLFSSL_CERT_MANAGER* cm, const byte* derBuf, * @return Negative value on error. */ static WC_INLINE int cm_restore_cert_row(WOLFSSL_CERT_MANAGER* cm, - const byte* current, int listSz, const byte* end, Signer** table) + const byte* current, int listSz, const byte* end, Signer** table, + word16* savedPath, int* savedCount) { int ret = 0; int idx = 0; @@ -1490,10 +1510,14 @@ static WC_INLINE int cm_restore_cert_row(WOLFSSL_CERT_MANAGER* cm, while ((ret == 0) && (listSz > 0)) { Signer* signer = NULL; word32 derSz; + word16 pathLen; byte type; + #ifdef HAVE_OCSP + byte issuerKeyHash[KEYID_SIZE]; + #endif - /* Check bytes available for DER length and Signer type. */ - if ((word32)(end - (current + idx)) < (word32)sizeof(word32) + 1) { + /* Check bytes available for the fields that precede the DER. */ + if ((word32)(end - (current + idx)) < (word32)cm_cache_entry_prefix()) { WOLFSSL_MSG("Would overread restore buffer"); ret = BUFFER_E; } @@ -1501,9 +1525,16 @@ static WC_INLINE int cm_restore_cert_row(WOLFSSL_CERT_MANAGER* cm, /* Copy in DER length. */ XMEMCPY(&derSz, current + idx, sizeof(derSz)); idx += (int)sizeof(derSz); + /* Copy in the path length that was in use at save time. */ + XMEMCPY(&pathLen, current + idx, sizeof(pathLen)); + idx += (int)sizeof(pathLen); /* Copy in Signer type. */ type = current[idx]; idx += 1; + #ifdef HAVE_OCSP + XMEMCPY(issuerKeyHash, current + idx, KEYID_SIZE); + idx += KEYID_SIZE; + #endif /* Check bytes available for DER. */ if ((derSz == 0) || ((word32)(end - (current + idx)) < derSz)) { @@ -1516,9 +1547,23 @@ static WC_INLINE int cm_restore_cert_row(WOLFSSL_CERT_MANAGER* cm, ret = cm_restore_signer(cm, current + idx, derSz, type, &signer); } if (ret == 0) { - Signer** last; idx += (int)derSz; + if (savedPath == NULL) { + ret = MEMORY_E; + } + else { + savedPath[*savedCount] = pathLen; + (*savedCount)++; + #ifdef HAVE_OCSP + /* Keep the saved hash when the issuer is not restored. */ + XMEMCPY(signer->issuerKeyHash, issuerKeyHash, KEYID_SIZE); + #endif + } + } + if (ret == 0) { + Signer** last; + /* Append to row of table, keeping the order it was stored in. */ #ifndef NO_SKID last = &table[HashSigner(signer->subjectKeyIdHash)]; @@ -1529,10 +1574,14 @@ static WC_INLINE int cm_restore_cert_row(WOLFSSL_CERT_MANAGER* cm, last = &(*last)->next; } *last = signer; + signer = NULL; /* Done one more Signer. */ --listSz; } + if (signer != NULL) { + FreeSigner(signer, cm->heap); + } } if (ret == 0) { @@ -1564,15 +1613,25 @@ static WC_INLINE int cm_store_cert_row(WOLFSSL_CERT_MANAGER* cm, byte* current, while (list != NULL) { if (cm_get_signer_memory(list) > 0) { word32 derSz = list->derCert->length; + word16 pathLen = list->maxPathLen; /* DER length. */ XMEMCPY(current + added, &derSz, sizeof(derSz)); added += (int)sizeof(derSz); + /* Path length in use. Restore must not raise this value. */ + XMEMCPY(current + added, &pathLen, sizeof(pathLen)); + added += (int)sizeof(pathLen); + /* Signer type. */ current[added] = list->type; added += 1; + #ifdef HAVE_OCSP + XMEMCPY(current + added, list->issuerKeyHash, KEYID_SIZE); + added += KEYID_SIZE; + #endif + /* DER encoding of certificate. */ XMEMCPY(current + added, list->derCert->buffer, derSz); added += (int)derSz; @@ -2020,6 +2079,55 @@ static int cm_restore_apply_pathlen(Signer** table, void* heap) return 0; } + +/* Do not let restore raise a path length above the value saved with the CA. + * The issuer that produced the saved value may be absent from this cache. */ +static void cm_restore_clamp_pathlen(Signer** table, const word16* saved) +{ + int i = 0; + int row; + + for (row = 0; row < CA_TABLE_SIZE; row++) { + Signer* s = table[row]; + + while (s != NULL) { + if (s->maxPathLen > saved[i]) { + s->maxPathLen = saved[i]; + } + i++; + s = s->next; + } + } +} + + +#ifdef HAVE_OCSP +/* A non-self-issued CA takes its issuer key hash from the restored issuer. + * The hash saved in the cache stays when that issuer is not in the table. */ +static void cm_restore_apply_issuer_key_hash(Signer** table) +{ + int row; + + for (row = 0; row < CA_TABLE_SIZE; row++) { + Signer* s = table[row]; + + while (s != NULL) { + Signer* issuer; + + if (!cm_signer_is_self_issued(s)) { + issuer = cm_table_find_issuer(table, s); + if ((issuer != NULL) && (issuer != s)) { + XMEMCPY(s->issuerKeyHash, issuer->subjectKeyHash, + KEYID_SIZE); + } + } + s = s->next; + } + } +} +#endif + + #undef CM_SIGNER_HAS_ISSUER_HASH @@ -2043,6 +2151,9 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) const byte* current = (const byte*)mem + sizeof(CertCacheHeader); const byte* end = (const byte*)mem + sz; /* don't go over */ Signer** table = NULL; + word16* savedPath = NULL; + int savedCount = 0; + int signerCount = 0; WOLFSSL_ENTER("CM_MemRestoreCertCache"); @@ -2073,12 +2184,29 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) XMEMSET(table, 0, sizeof(Signer*) * CA_TABLE_SIZE); } } + if (ret == WOLFSSL_SUCCESS) { + for (i = 0; i < CA_TABLE_SIZE; ++i) { + if (hdr->columns[i] < 0) { + WOLFSSL_MSG("Row header corrupted, negative value"); + ret = PARSE_ERROR; + break; + } + signerCount += hdr->columns[i]; + } + } + if ((ret == WOLFSSL_SUCCESS) && (signerCount > 0)) { + savedPath = (word16*)XMALLOC(sizeof(word16) * (size_t)signerCount, + cm->heap, DYNAMIC_TYPE_TMP_BUFFER); + if (savedPath == NULL) { + ret = MEMORY_E; + } + } if (ret == WOLFSSL_SUCCESS) { /* Each row. */ for (i = 0; i < CA_TABLE_SIZE; ++i) { /* Restore a row from memory. */ int added = cm_restore_cert_row(cm, current, hdr->columns[i], end, - table); + table, savedPath, &savedCount); /* Bail on error. */ if (added < 0) { WOLFSSL_MSG("cm_restore_cert_row error"); @@ -2090,6 +2218,11 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) } } + if ((ret == WOLFSSL_SUCCESS) && (savedCount != signerCount)) { + WOLFSSL_MSG("Restored CA count does not match the cache header"); + ret = PARSE_ERROR; + } + if (ret == WOLFSSL_SUCCESS) { /* Inherited path length needs every issuer in the new table. */ int pathRet = cm_restore_apply_pathlen(table, cm->heap); @@ -2098,6 +2231,14 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) ret = pathRet; } } +#ifdef HAVE_OCSP + if (ret == WOLFSSL_SUCCESS) { + cm_restore_apply_issuer_key_hash(table); + } +#endif + if ((ret == WOLFSSL_SUCCESS) && (savedPath != NULL)) { + cm_restore_clamp_pathlen(table, savedPath); + } /* Lock CA table. */ if ((ret == WOLFSSL_SUCCESS) && (wc_LockMutex(&cm->caLock) != 0)) { @@ -2121,6 +2262,7 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) FreeSignerTable(table, CA_TABLE_SIZE, cm->heap); XFREE(table, cm->heap, DYNAMIC_TYPE_TMP_BUFFER); } + XFREE(savedPath, cm->heap, DYNAMIC_TYPE_TMP_BUFFER); return ret; } diff --git a/tests/api/test_certman.c b/tests/api/test_certman.c index 954307ae449..180f3e1f78c 100644 --- a/tests/api/test_certman.c +++ b/tests/api/test_certman.c @@ -5371,10 +5371,43 @@ int test_wolfSSL_CertManagerNameConstraint_cert_cache(void) return EXPECT_RESULT(); } +#if defined(PERSIST_CERT_CACHE) && !defined(NO_FILESYSTEM) && \ + !defined(NO_CERTS) && !defined(NO_TLS) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_WOLFSSL_CM_VERIFY) && !defined(NO_RSA) && \ + !defined(NO_SHA256) && \ + (defined(WOLFSSL_PEM_TO_DER) || defined(OPENSSL_EXTRA)) && \ + (!defined(IGNORE_NAME_CONSTRAINTS) || defined(HAVE_OCSP) || \ + defined(HAVE_CRL) || defined(WOLFSSL_AKID_NAME)) +/* Find a loaded CA by its common name. */ +static Signer* test_cm_find_signer(WOLFSSL_CERT_MANAGER* cm, const char* cn) +{ + int row; + int cnLen = (int)XSTRLEN(cn); + + if (cm == NULL) { + return NULL; + } + for (row = 0; row < CA_TABLE_SIZE; row++) { + Signer* s = cm->caTable[row]; + + while (s != NULL) { + if ((s->name != NULL) && (s->nameLen == cnLen) && + (XMEMCMP(s->name, cn, (size_t)cnLen) == 0)) { + return s; + } + s = s->next; + } + } + return NULL; +} +#endif + /* A CA restored from the cache keeps the path length it inherited from its * issuer. chainJ-ICA4 allows two CA certificates below it. ICA3 and ICA2 * have no path length of their own, so ICA2's effective limit becomes 0. - * A further CA (ICA1) is rejected before the save and after the restore. */ + * A further CA (ICA1) is rejected before the save and after the restore. + * A second save drops ICA4. The limit already inherited by ICA2, and the + * OCSP issuer key hash of ICA3, must still be present after that restore. */ int test_wolfSSL_CertManagerPathLen_cert_cache(void) { EXPECT_DECLS; @@ -5388,8 +5421,15 @@ int test_wolfSSL_CertManagerPathLen_cert_cache(void) WOLFSSL_CTX* ctx = NULL; WOLFSSL_CERT_MANAGER* cm = NULL; byte* cache = NULL; + byte* cache2 = NULL; int cacheSz = 0; + int cacheSz2 = 0; int used = 0; + int used2 = 0; +#ifdef HAVE_OCSP + byte ica4Key[KEYID_SIZE]; + byte ica3Key[KEYID_SIZE]; +#endif const char* root_cert = "./certs/ca-cert.pem"; const char* ica4_cert = "./certs/test-pathlen/chainJ-ICA4-pathlen2.pem"; @@ -5425,6 +5465,35 @@ int test_wolfSSL_CertManagerPathLen_cert_cache(void) ExpectIntEQ(wolfSSL_CTX_memsave_cert_cache(ctx, cache, cacheSz, &used), WOLFSSL_SUCCESS); ExpectIntEQ(used, cacheSz); + + /* Remove the CA that carries the path length extension. Descendants + * keep the limit they already inherited. That limit is what the cache + * must restore when the issuer itself is not stored. */ + ExpectNotNull(cm = wolfSSL_CTX_GetCertManager(ctx)); + if (cm != NULL) { + Signer* ica4 = test_cm_find_signer(cm, "chainJ-ICA4-pathlen2"); + Signer* ica3 = test_cm_find_signer(cm, "chainJ-ICA3-no_pathlen"); + + ExpectNotNull(ica4); + ExpectNotNull(ica3); + if ((ica4 != NULL) && (ica3 != NULL)) { + ica4->type = WOLFSSL_CHAIN_CA; +#ifdef HAVE_OCSP + XMEMCPY(ica4Key, ica4->subjectKeyHash, KEYID_SIZE); + XMEMCPY(ica3Key, ica3->subjectKeyHash, KEYID_SIZE); + ExpectIntEQ(XMEMCMP(ica3->issuerKeyHash, ica4Key, KEYID_SIZE), 0); +#endif + } + ExpectIntEQ(wolfSSL_CertManagerUnloadIntermediateCerts(cm), + WOLFSSL_SUCCESS); + ExpectNull(test_cm_find_signer(cm, "chainJ-ICA4-pathlen2")); + } + ExpectIntGT(cacheSz2 = wolfSSL_CTX_get_cert_cache_memsize(ctx), 0); + ExpectNotNull(cache2 = (byte*)XMALLOC((size_t)cacheSz2, NULL, + DYNAMIC_TYPE_TMP_BUFFER)); + ExpectIntEQ(wolfSSL_CTX_memsave_cert_cache(ctx, cache2, cacheSz2, &used2), + WOLFSSL_SUCCESS); + ExpectIntEQ(used2, cacheSz2); wolfSSL_CTX_free(ctx); ctx = NULL; @@ -5444,8 +5513,40 @@ int test_wolfSSL_CertManagerPathLen_cert_cache(void) WS_RETURN_CODE(WC_NO_ERR_TRACE(ASN_PATHLEN_INV_E), WC_NO_ERR_TRACE(WOLFSSL_FAILURE))); + wolfSSL_CTX_free(ctx); + ctx = NULL; + + /* Restore the cache that no longer contains ICA4. */ + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_DEFAULT, NULL); + ExpectIntEQ(wolfSSL_CTX_memrestore_cert_cache(ctx, cache2, used2), + WOLFSSL_SUCCESS); + ExpectNotNull(cm = wolfSSL_CTX_GetCertManager(ctx)); + ExpectNull(test_cm_find_signer(cm, "chainJ-ICA4-pathlen2")); +#ifdef HAVE_OCSP + if (cm != NULL) { + Signer* ica3 = test_cm_find_signer(cm, "chainJ-ICA3-no_pathlen"); + Signer* ica2 = test_cm_find_signer(cm, "chainJ-ICA2-no_pathlen"); + + /* ICA4 is absent, so ICA3 keeps the issuer key hash from the save. */ + ExpectNotNull(ica3); + if (ica3 != NULL) { + ExpectIntEQ(XMEMCMP(ica3->issuerKeyHash, ica4Key, KEYID_SIZE), 0); + } + /* ICA3 is present, so ICA2 takes that issuer's subject key hash. */ + ExpectNotNull(ica2); + if (ica2 != NULL) { + ExpectIntEQ(XMEMCMP(ica2->issuerKeyHash, ica3Key, KEYID_SIZE), 0); + } + } +#endif + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, ica1_cert, NULL), + WS_RETURN_CODE(WC_NO_ERR_TRACE(ASN_PATHLEN_INV_E), + WC_NO_ERR_TRACE(WOLFSSL_FAILURE))); + wolfSSL_CTX_free(ctx); XFREE(cache, NULL, DYNAMIC_TYPE_TMP_BUFFER); + XFREE(cache2, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return EXPECT_RESULT(); } diff --git a/wolfcrypt/src/asn.c b/wolfcrypt/src/asn.c index a66b07d1497..3820b718b5e 100644 --- a/wolfcrypt/src/asn.c +++ b/wolfcrypt/src/asn.c @@ -27040,7 +27040,7 @@ int FillSigner(Signer* signer, DecodedCert* cert, int type, DerBuffer *der) #endif if (ret == 0 && signer != NULL) { #ifdef WOLFSSL_SIGNER_DER_CERT - ret = AllocDer(&signer->derCert, der->length, der->type, NULL); + ret = AllocDer(&signer->derCert, der->length, der->type, cert->heap); } if (ret == 0 && signer != NULL) { XMEMCPY(signer->derCert->buffer, der->buffer, der->length); From 122325cab94cc98860d0e71af8bd0b98db2ce730 Mon Sep 17 00:00:00 2001 From: Sameeh Date: Mon, 26 Oct 2026 09:32:39 +0200 Subject: [PATCH 5/6] Fix the C++ cast and -Og warnings in cert-cache restore cm_restore_apply_pathlen() assigns the result of XMALLOC to a struct pointer. A C++ build rejects that conversion. Name the struct and cast the result. Initialize the restore fields so an -Og build does not treat them as uninitialized. The values are set before use when the row header is valid. --- src/ssl_certman.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/ssl_certman.c b/src/ssl_certman.c index 476445ac502..bbdeeffa97e 100644 --- a/src/ssl_certman.c +++ b/src/ssl_certman.c @@ -1509,9 +1509,9 @@ static WC_INLINE int cm_restore_cert_row(WOLFSSL_CERT_MANAGER* cm, /* Process all entries. */ while ((ret == 0) && (listSz > 0)) { Signer* signer = NULL; - word32 derSz; - word16 pathLen; - byte type; + word32 derSz = 0; + word16 pathLen = 0; + byte type = 0; #ifdef HAVE_OCSP byte issuerKeyHash[KEYID_SIZE]; #endif @@ -2001,7 +2001,7 @@ static int cm_restore_apply_pathlen(Signer** table, void* heap) int row; int guard; int changed; - struct { + struct CmRestorePathRef { Signer* signer; word16 base; }* refs; @@ -2018,7 +2018,8 @@ static int cm_restore_apply_pathlen(Signer** table, void* heap) return 0; } - refs = XMALLOC(sizeof(*refs) * (size_t)count, heap, DYNAMIC_TYPE_TMP_BUFFER); + refs = (struct CmRestorePathRef*)XMALLOC(sizeof(*refs) * (size_t)count, + heap, DYNAMIC_TYPE_TMP_BUFFER); if (refs == NULL) { return MEMORY_E; } From 58b2aa90c8d2ebd4ba24f635a6dfaf0e93e9d33c Mon Sep 17 00:00:00 2001 From: Sameeh Jubran Date: Tue, 17 Nov 2026 10:11:10 +0200 Subject: [PATCH 6/6] Address review findings on the persisted cert cache - Decode the pending CA with the certificate manager heap. FillSigner() moves buffers of the decoded cert into the signer, which the manager keeps after the connection is freed. - Bound each row count in the cache header by the buffer size, so the sum of the counts cannot overflow and undersize the saved path array. - Set the 32-bit unknown extension callback when a signer is restored, as AddCA() does. - Add test_wolfSSL_CertManager_cert_cache_bad_count. --- src/internal.c | 4 ++- src/ssl_certman.c | 13 ++++++++++ tests/api/test_certman.c | 56 ++++++++++++++++++++++++++++++++++++++++ tests/api/test_certman.h | 3 +++ 4 files changed, 75 insertions(+), 1 deletion(-) diff --git a/src/internal.c b/src/internal.c index 5a8af6ee8e1..7eb7e843e4a 100644 --- a/src/internal.c +++ b/src/internal.c @@ -18797,8 +18797,10 @@ static int ProcessPeerCertAddPendingCA(WOLFSSL* ssl, buffer* cert) ret=MEMORY_E; goto exit_req_v2; }); + /* FillSigner() moves buffers of the decoded cert into the signer, which + * the certificate manager keeps after this connection is freed. */ InitDecodedCert(dCertAdd, cert->buffer, cert->length, - ssl->heap); + SSL_CM(ssl)->heap); #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) /* A signer doesn't keep the X509_NAMEs, don't build them. */ dCertAdd->noX509Name = 1; diff --git a/src/ssl_certman.c b/src/ssl_certman.c index bbdeeffa97e..4eadb44a368 100644 --- a/src/ssl_certman.c +++ b/src/ssl_certman.c @@ -1440,6 +1440,10 @@ static int cm_restore_signer(WOLFSSL_CERT_MANAGER* cm, const byte* derBuf, InitDecodedCert(cert, der->buffer, der->length, cm->heap); #ifdef WC_ASN_UNKNOWN_EXT_CB + /* Parse it like AddCA() did. */ + if (cm->unknownExtCallback32 != NULL) { + wc_SetUnknownExtCallback32(cert, cm->unknownExtCallback32); + } if (cm->unknownExtCallback != NULL) { wc_SetUnknownExtCallback(cert, cm->unknownExtCallback); } @@ -2186,12 +2190,21 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) } } if (ret == WOLFSSL_SUCCESS) { + /* Each entry holds its prefix and at least one byte of DER, so the + * buffer bounds the count and the sum cannot overflow. */ + int maxSigners = (int)(end - current) / (cm_cache_entry_prefix() + 1); + for (i = 0; i < CA_TABLE_SIZE; ++i) { if (hdr->columns[i] < 0) { WOLFSSL_MSG("Row header corrupted, negative value"); ret = PARSE_ERROR; break; } + if (hdr->columns[i] > maxSigners - signerCount) { + WOLFSSL_MSG("Row header corrupted, too many entries"); + ret = BUFFER_E; + break; + } signerCount += hdr->columns[i]; } } diff --git a/tests/api/test_certman.c b/tests/api/test_certman.c index 180f3e1f78c..44b343e3b97 100644 --- a/tests/api/test_certman.c +++ b/tests/api/test_certman.c @@ -5371,6 +5371,62 @@ int test_wolfSSL_CertManagerNameConstraint_cert_cache(void) return EXPECT_RESULT(); } +/* A cache header whose row counts add up past INT_MAX is rejected. Without the + * bound the sum wraps below the real count, the array of saved path lengths + * is undersized, and restoring the real entry writes past it. */ +int test_wolfSSL_CertManager_cert_cache_bad_count(void) +{ + EXPECT_DECLS; +#if defined(PERSIST_CERT_CACHE) && !defined(NO_FILESYSTEM) && \ + !defined(NO_CERTS) && !defined(NO_TLS) && !defined(NO_WOLFSSL_CLIENT) && \ + !defined(NO_RSA) && (defined(WOLFSSL_PEM_TO_DER) || defined(OPENSSL_EXTRA)) + WOLFSSL_CTX* ctx = NULL; + byte* cache = NULL; + int cacheSz = 0; + int used = 0; + int emptySz = 0; + int* columns; + int row; + + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntGT(emptySz = wolfSSL_CTX_get_cert_cache_memsize(ctx), 0); + ExpectIntEQ(wolfSSL_CTX_load_verify_locations(ctx, "./certs/ca-cert.pem", + NULL), WOLFSSL_SUCCESS); + ExpectIntGT(cacheSz = wolfSSL_CTX_get_cert_cache_memsize(ctx), 0); + ExpectNotNull(cache = (byte*)XMALLOC((size_t)cacheSz, NULL, + DYNAMIC_TYPE_TMP_BUFFER)); + ExpectIntEQ(wolfSSL_CTX_memsave_cert_cache(ctx, cache, cacheSz, &used), + WOLFSSL_SUCCESS); + wolfSSL_CTX_free(ctx); + ctx = NULL; + + if (EXPECT_SUCCESS()) { + /* The header is the version, the row count, then one count per row. + * Entries are stored in row order, so moving the one real entry to + * row 0 restores it first. 1 + INT_MAX + INT_MAX + 1 wraps to 0. */ + ExpectIntGE(CA_TABLE_SIZE, 4); + columns = (int*)(cache + 2 * sizeof(int)); + for (row = 0; row < CA_TABLE_SIZE; row++) { + columns[row] = 0; + } + columns[0] = 1; + columns[1] = INT_MAX; + columns[2] = INT_MAX; + columns[3] = 1; + } + + ExpectNotNull(ctx = wolfSSL_CTX_new(wolfSSLv23_client_method())); + ExpectIntEQ(wolfSSL_CTX_memrestore_cert_cache(ctx, cache, used), + WC_NO_ERR_TRACE(BUFFER_E)); + /* Nothing was restored. */ + ExpectIntEQ(wolfSSL_CTX_get_cert_cache_memsize(ctx), emptySz); + + wolfSSL_CTX_free(ctx); + XFREE(cache, NULL, DYNAMIC_TYPE_TMP_BUFFER); +#endif + return EXPECT_RESULT(); +} + #if defined(PERSIST_CERT_CACHE) && !defined(NO_FILESYSTEM) && \ !defined(NO_CERTS) && !defined(NO_TLS) && !defined(NO_WOLFSSL_CLIENT) && \ !defined(NO_WOLFSSL_CM_VERIFY) && !defined(NO_RSA) && \ diff --git a/tests/api/test_certman.h b/tests/api/test_certman.h index 7662de280d5..f94c1475eb7 100644 --- a/tests/api/test_certman.h +++ b/tests/api/test_certman.h @@ -70,6 +70,7 @@ int test_wolfSSL_CertManagerNameConstraint_valid_chain(void); int test_wolfSSL_CertManagerNameConstraint_skid_disambiguates(void); int test_wolfSSL_CertManagerNameConstraint_cert_cache(void); int test_wolfSSL_CertManagerPathLen_cert_cache(void); +int test_wolfSSL_CertManager_cert_cache_bad_count(void); int test_wolfSSL_trust_peer_cert_dates(void); #define TEST_CERTMAN_DECLS \ @@ -125,6 +126,8 @@ int test_wolfSSL_trust_peer_cert_dates(void); TEST_DECL_GROUP("certman", \ test_wolfSSL_CertManagerNameConstraint_cert_cache), \ TEST_DECL_GROUP("certman", test_wolfSSL_CertManagerPathLen_cert_cache), \ + TEST_DECL_GROUP("certman", \ + test_wolfSSL_CertManager_cert_cache_bad_count), \ TEST_DECL_GROUP("certman", test_wolfSSL_trust_peer_cert_dates), \ TEST_DECL_GROUP("certman", \ test_wolfSSL_CertManagerCheckCRL_out_of_date), \