@@ -16339,6 +16339,9 @@ int wolfSSL_X509_set_subject_key_id_ex(WOLFSSL_X509* x509)
1633916339#endif /* !NO_SHA */
1634016340
1634116341/* Set Authority Key Identifier from raw bytes.
16342+ * The bytes passed in are the keyIdentifier OCTET STRING contents only,
16343+ * they must not be a pre-encoded AuthorityKeyIdentifier SEQUENCE.
16344+ * The cert encoder wraps them in SEQUENCE { [0] keyIdentifier } at sign time.
1634216345 *
1634316346 * x509 - Certificate to modify
1634416347 * akid - Raw AKID bytes
@@ -16349,27 +16352,38 @@ int wolfSSL_X509_set_subject_key_id_ex(WOLFSSL_X509* x509)
1634916352int wolfSSL_X509_set_authority_key_id(WOLFSSL_X509* x509,
1635016353 const unsigned char* akid, int akidSz)
1635116354{
16355+ byte* newAkid = NULL;
16356+
1635216357 WOLFSSL_ENTER("wolfSSL_X509_set_authority_key_id");
1635316358
1635416359 if (x509 == NULL || akid == NULL || akidSz <= 0) {
1635516360 return WOLFSSL_FAILURE;
1635616361 }
1635716362
16358- /* Allocate/reallocate memory for authKeyIdSrc */
16359- if (x509->authKeyIdSrc == NULL || (int)x509->authKeyIdSrcSz < akidSz) {
16360- if (x509->authKeyIdSrc != NULL) {
16361- XFREE(x509->authKeyIdSrc, x509->heap, DYNAMIC_TYPE_X509_EXT);
16362- }
16363- x509->authKeyIdSrc = (byte*)XMALLOC((word32)akidSz, x509->heap,
16364- DYNAMIC_TYPE_X509_EXT);
16365- if (x509->authKeyIdSrc == NULL) {
16366- return WOLFSSL_FAILURE;
16367- }
16363+ /* Allocate new buffer up front so failure leaves prior state intact */
16364+ newAkid = (byte*)XMALLOC((word32)akidSz, x509->heap, DYNAMIC_TYPE_X509_EXT);
16365+ if (newAkid == NULL) {
16366+ return WOLFSSL_FAILURE;
16367+ }
16368+ XMEMCPY(newAkid, akid, (word32)akidSz);
16369+
16370+ /* Free any prior storage. authKeyIdSrc may be populated from a prior
16371+ * parse cert operation. authKeyId aliases inside that buffer, so
16372+ * authKeyIdSrc must be freed first to avoid a dangling authKeyId. */
16373+ if (x509->authKeyIdSrc != NULL) {
16374+ XFREE(x509->authKeyIdSrc, x509->heap, DYNAMIC_TYPE_X509_EXT);
16375+ x509->authKeyIdSrc = NULL;
16376+ x509->authKeyIdSrcSz = 0;
16377+ }
16378+ else if (x509->authKeyId != NULL) {
16379+ XFREE(x509->authKeyId, x509->heap, DYNAMIC_TYPE_X509_EXT);
1636816380 }
1636916381
16370- XMEMCPY(x509->authKeyIdSrc, akid, (word32)akidSz);
16371- x509->authKeyIdSrcSz = (word32)akidSz;
16372- x509->authKeyId = x509->authKeyIdSrc;
16382+ /* Store newAkid as authKeyId only, do not populate authKeyIdSrc.
16383+ * When authKeyIdSrc is non-NULL, the encoder writes those bytes without
16384+ * SEQUENCE/[0] wrapper. authKeyIdSrc must be NULL here so encoder does
16385+ * wrap them. */
16386+ x509->authKeyId = newAkid;
1637316387 x509->authKeyIdSz = (word32)akidSz;
1637416388 x509->authKeyIdSet = 1;
1637516389
0 commit comments