@@ -16338,6 +16338,9 @@ int wolfSSL_X509_set_subject_key_id_ex(WOLFSSL_X509* x509)
1633816338#endif /* !NO_SHA */
1633916339
1634016340/* Set Authority Key Identifier from raw bytes.
16341+ * The bytes passed in are the keyIdentifier OCTET STRING contents only,
16342+ * they must not be a pre-encoded AuthorityKeyIdentifier SEQUENCE.
16343+ * The cert encoder wraps them in SEQUENCE { [0] keyIdentifier } at sign time.
1634116344 *
1634216345 * x509 - Certificate to modify
1634316346 * akid - Raw AKID bytes
@@ -16348,27 +16351,37 @@ int wolfSSL_X509_set_subject_key_id_ex(WOLFSSL_X509* x509)
1634816351int wolfSSL_X509_set_authority_key_id(WOLFSSL_X509* x509,
1634916352 const unsigned char* akid, int akidSz)
1635016353{
16354+ byte* newAkid = NULL;
16355+
1635116356 WOLFSSL_ENTER("wolfSSL_X509_set_authority_key_id");
1635216357
1635316358 if (x509 == NULL || akid == NULL || akidSz <= 0) {
1635416359 return WOLFSSL_FAILURE;
1635516360 }
1635616361
16357- /* Allocate/reallocate memory for authKeyIdSrc */
16358- if (x509->authKeyIdSrc == NULL || (int)x509->authKeyIdSrcSz < akidSz) {
16359- if (x509->authKeyIdSrc != NULL) {
16360- XFREE(x509->authKeyIdSrc, x509->heap, DYNAMIC_TYPE_X509_EXT);
16361- }
16362- x509->authKeyIdSrc = (byte*)XMALLOC((word32)akidSz, x509->heap,
16363- DYNAMIC_TYPE_X509_EXT);
16364- if (x509->authKeyIdSrc == NULL) {
16365- return WOLFSSL_FAILURE;
16366- }
16362+ /* Allocate new buffer up front so failure leaves prior state intact */
16363+ newAkid = (byte*)XMALLOC((word32)akidSz, x509->heap, DYNAMIC_TYPE_X509_EXT);
16364+ if (newAkid == NULL) {
16365+ return WOLFSSL_FAILURE;
16366+ }
16367+ XMEMCPY(newAkid, akid, (word32)akidSz);
16368+
16369+ /* Free any prior storage. authKeyIdSrc may be populated from a prior
16370+ * parse cert operation. authKeyId aliases inside that buffer, so
16371+ * authKeyIdSrc must be freed first to avoid a dangling authKeyId. */
16372+ if (x509->authKeyIdSrc != NULL) {
16373+ XFREE(x509->authKeyIdSrc, x509->heap, DYNAMIC_TYPE_X509_EXT);
16374+ x509->authKeyIdSrc = NULL;
16375+ x509->authKeyIdSrcSz = 0;
16376+ }
16377+ else if (x509->authKeyId != NULL) {
16378+ XFREE(x509->authKeyId, x509->heap, DYNAMIC_TYPE_X509_EXT);
1636716379 }
1636816380
16369- XMEMCPY(x509->authKeyIdSrc, akid, (word32)akidSz);
16370- x509->authKeyIdSrcSz = (word32)akidSz;
16371- x509->authKeyId = x509->authKeyIdSrc;
16381+ /* Store newAkid as authKeyId only, do not populate authKeyIdSrc. When
16382+ * authKeyIdSrc is non-NULL, encoder writes bytes verbatim with no
16383+ * SEQUENCE/[0] wrapper, but we want that. */
16384+ x509->authKeyId = newAkid;
1637216385 x509->authKeyIdSz = (word32)akidSz;
1637316386 x509->authKeyIdSet = 1;
1637416387
0 commit comments