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 0946251320b..4eadb44a368 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 3 /* CA certificates cache information. */ typedef struct { @@ -1273,12 +1273,40 @@ typedef struct { /* current cert persistence layout is: 1) CertCacheHeader - 2) caTable - - update WOLFSSL_CERT_CACHE_VERSION if change layout for the following + 2) caTable, each Signer stored as: + a) DER length (word32) + 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. 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 */ +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. * @@ -1289,16 +1317,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 = cm_cache_entry_prefix() + (int)signer->derCert->length; + } return sz; } @@ -1371,8 +1396,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 +1408,89 @@ 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 + /* Parse it like AddCA() did. */ + if (cm->unknownExtCallback32 != NULL) { + wc_SetUnknownExtCallback32(cert, cm->unknownExtCallback32); + } + 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) { + /* 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); + } + + 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. + * @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. @@ -1397,7 +1498,8 @@ 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, + word16* savedPath, int* savedCount) { int ret = 0; int idx = 0; @@ -1411,102 +1513,77 @@ 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 = 0; + word16 pathLen = 0; + byte type = 0; + #ifdef HAVE_OCSP + byte issuerKeyHash[KEYID_SIZE]; + #endif - /* Check minimal size of bytes available. */ - if (start + minSz > end) { + /* 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; } - /* 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); + /* 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 public key. */ - if (start + minSz + signer->pubKeySize > end) { + /* 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. */ - publicKey = (byte*)XMALLOC(signer->pubKeySize, cm->heap, - DYNAMIC_TYPE_KEY); - if (publicKey == NULL) { - ret = MEMORY_E; - } + /* Rebuild Signer from certificate. */ + ret = cm_restore_signer(cm, current + idx, derSz, type, &signer); } - if (ret == 0) { - /* Copy in public key. */ - XMEMCPY(publicKey, current + idx, signer->pubKeySize); - signer->publicKey = publicKey; - idx += (int)signer->pubKeySize; + idx += (int)derSz; - /* 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) { - 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) { + 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) { - /* 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; + /* 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; + signer = NULL; /* Done one more Signer. */ --listSz; } - - if ((ret != 0) && (signer != NULL)) { - /* Dispose of allocated signer. */ + if (signer != NULL) { FreeSigner(signer, cm->heap); } } @@ -1538,35 +1615,31 @@ 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; + word16 pathLen = list->maxPathLen; - /* 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); + /* Path length in use. Restore must not raise this value. */ + XMEMCPY(current + added, &pathLen, sizeof(pathLen)); + added += (int)sizeof(pathLen); - /* Certificate name. */ - XMEMCPY(current + added, list->name, (size_t)list->nameLen); - added += list->nameLen; + /* Signer type. */ + current[added] = list->type; + added += 1; - /* Hash of subject name. */ - XMEMCPY(current + added, list->subjectNameHash, SIGNER_DIGEST_SIZE); - added += SIGNER_DIGEST_SIZE; + #ifdef HAVE_OCSP + XMEMCPY(current + added, list->issuerKeyHash, KEYID_SIZE); + added += KEYID_SIZE; + #endif - #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; @@ -1787,6 +1860,282 @@ 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 CmRestorePathRef { + 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 = (struct CmRestorePathRef*)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; +} + + +/* 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 + + /* Restore CA certificate table from memory, * * Locks CA table. @@ -1803,9 +2152,13 @@ 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; + word16* savedPath = NULL; + int savedCount = 0; + int signerCount = 0; WOLFSSL_ENTER("CM_MemRestoreCertCache"); @@ -1824,21 +2177,50 @@ 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 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]; + } + } + 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, i, hdr->columns[i], - end); + int added = cm_restore_cert_row(cm, current, hdr->columns[i], end, + table, savedPath, &savedCount); /* Bail on error. */ if (added < 0) { WOLFSSL_MSG("cm_restore_cert_row error"); @@ -1848,11 +2230,54 @@ int CM_MemRestoreCertCache(WOLFSSL_CERT_MANAGER* cm, const void* mem, int sz) /* Update pointer to data of next row. */ current += added; } + } + + 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); + + if (pathRet != 0) { + 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)) { + 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); + } + 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 2b8f2064c34..44b343e3b97 100644 --- a/tests/api/test_certman.c +++ b/tests/api/test_certman.c @@ -5303,6 +5303,310 @@ 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(); +} + +/* 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) && \ + !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 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; +#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; + 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"; + 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())); + /* 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), + 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); + + /* 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; + + /* 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)); + + /* 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); + 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(); +} + #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..f94c1475eb7 100644 --- a/tests/api/test_certman.h +++ b/tests/api/test_certman.h @@ -68,6 +68,9 @@ 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_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 \ @@ -120,6 +123,11 @@ 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_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), \ 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); 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