From 26d3e13581bad329d88aec02b298223b1b8b9856 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Trojnara?= Date: Sun, 15 Nov 2026 09:52:29 +0100 Subject: [PATCH 1/2] Fix memory leaks in signature and key handling Release signatures, timestamp credentials and APPX buffers on error, and free unused catalog members. Repeated hashes, private keys and command options must release the values they replace. Finish initialized engines when forced login fails. Handle failed ownership transfers to OpenSSL attributes and stacks, preserve MSI buffers after failed growth, and unmap the complete input when PE or script processing shortens its content length. Check digest BIO allocation before linking sink BIOs. Route built-in TSA loading failures through common cleanup. Preserve the failure result so unreadable or invalid TSA parameters no longer leave an apparently successful output without the requested timestamp. --- NEWS.md | 8 +++ appx.c | 37 ++++++---- cab.c | 10 ++- cat.c | 8 ++- helpers.c | 186 +++++++++++++++++++++++++++++++++++-------------- msi.c | 27 ++++--- osslsigncode.c | 132 ++++++++++++++++++++++++----------- pe.c | 6 +- script.c | 17 ++++- 9 files changed, 308 insertions(+), 123 deletions(-) diff --git a/NEWS.md b/NEWS.md index 20035f9..9711a5c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,14 @@ ### 2.17 (unreleased) +**Other user-visible changes** + +- fixed memory leaks in signature processing, built-in timestamping and + private key loading, and incorrect success reports when TSA parameters + cannot be loaded +- fixed allocation-failure crashes when decoding Base64 script signatures + and timestamp responses, or creating signature content + ### 2.16 (2026.11.13) **Security fixes** diff --git a/appx.c b/appx.c index b7c5e95..df65840 100644 --- a/appx.c +++ b/appx.c @@ -730,13 +730,13 @@ static int appx_append_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7) blob = OPENSSL_malloc((size_t)(len + 4)); memcpy(blob, PKCX_SIGNATURE, 4); memcpy(blob + 4, der, (size_t)len); + OPENSSL_free(der); len += 4; if (!zipAppendSignatureFile(outdata, zip, blob, (uint64_t)len)) { OPENSSL_free(blob); fprintf(stderr, "Failed to append zip file\n"); return 1; /* FAILED */ } - OPENSSL_free(der); OPENSSL_free(blob); if (!get_current_position(outdata, &cdOffset)) { fprintf(stderr, "Unable to get offset\n"); @@ -798,6 +798,11 @@ static BIO *appx_calculate_hashes(FILE_FORMAT_CTX *ctx) { uint64_t cdOffset = 0; + OPENSSL_free(ctx->appx_ctx->calculatedBMHash); + OPENSSL_free(ctx->appx_ctx->calculatedCTHash); + OPENSSL_free(ctx->appx_ctx->calculatedDataHash); + OPENSSL_free(ctx->appx_ctx->calculatedCDHash); + OPENSSL_free(ctx->appx_ctx->calculatedCIHash); ctx->appx_ctx->calculatedBMHash = zipCalcDigest(ctx->appx_ctx->zip, BLOCK_MAP_FILENAME, ctx->appx_ctx->md); ctx->appx_ctx->calculatedCTHash = zipCalcDigest(ctx->appx_ctx->zip, CONTENT_TYPES_FILENAME, ctx->appx_ctx->md); ctx->appx_ctx->calculatedDataHash = appx_calc_zip_data_hash(&cdOffset, ctx->appx_ctx->zip, ctx->appx_ctx->md); @@ -873,6 +878,8 @@ static uint8_t *appx_calc_zip_central_directory_hash(ZIP_FILE *zip, const EVP_MD u_char *mdbuf = NULL; BIO *bhash = BIO_new(BIO_f_md()); + if (!bhash) + return NULL; /* FAILED */ #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" @@ -1007,6 +1014,8 @@ static uint8_t *appx_calc_zip_data_hash(uint64_t *cdOffset, ZIP_FILE *zip, const BIO *bhash = BIO_new(BIO_f_md()); uint64_t noEntries = 0; + if (!bhash) + return NULL; /* FAILED */ #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" @@ -1092,25 +1101,29 @@ static int appx_extract_hashes(FILE_FORMAT_CTX *ctx, SpcIndirectDataContent *con return 0; /* FAILED */ } while (pos + mdlen + 4 <= len) { + u_char **hash; + if (!memcmp(data + pos, AXPC_SIGNATURE, 4)) { - ctx->appx_ctx->existingDataHash = OPENSSL_malloc((size_t)mdlen); - memcpy(ctx->appx_ctx->existingDataHash, data + pos + 4, (size_t)mdlen); + hash = &ctx->appx_ctx->existingDataHash; } else if (!memcmp(data + pos, AXCD_SIGNATURE, 4)) { - ctx->appx_ctx->existingCDHash = OPENSSL_malloc((size_t)mdlen); - memcpy(ctx->appx_ctx->existingCDHash, data + pos + 4, (size_t)mdlen); + hash = &ctx->appx_ctx->existingCDHash; } else if (!memcmp(data + pos, AXCT_SIGNATURE, 4)) { - ctx->appx_ctx->existingCTHash = OPENSSL_malloc((size_t)mdlen); - memcpy(ctx->appx_ctx->existingCTHash, data + pos + 4, (size_t)mdlen); + hash = &ctx->appx_ctx->existingCTHash; } else if (!memcmp(data + pos, AXBM_SIGNATURE, 4)) { - ctx->appx_ctx->existingBMHash = OPENSSL_malloc((size_t)mdlen); - memcpy(ctx->appx_ctx->existingBMHash, data + pos + 4, (size_t)mdlen); + hash = &ctx->appx_ctx->existingBMHash; } else if (!memcmp(data + pos, AXCI_SIGNATURE, 4)) { - ctx->appx_ctx->existingCIHash = OPENSSL_malloc((size_t)mdlen); - memcpy(ctx->appx_ctx->existingCIHash, data + pos + 4, (size_t)mdlen); + hash = &ctx->appx_ctx->existingCIHash; } else { fprintf(stderr, "Invalid hash signature\n"); return 0; /* FAILED */ } + /* The digest size is fixed for this context; reuse buffers for repeated tags. */ + if (!*hash) { + *hash = OPENSSL_malloc((size_t)mdlen); + if (!*hash) + return 0; /* FAILED */ + } + memcpy(*hash, data + pos + 4, (size_t)mdlen); pos += mdlen + 4; } if (!ctx->appx_ctx->existingDataHash) { @@ -1780,7 +1793,7 @@ static u_char *zipCalcDigest(ZIP_FILE *zip, const char *fileName, const EVP_MD * #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif - if (!BIO_set_md(bhash, md)) { + if (!bhash || !BIO_set_md(bhash, md)) { fprintf(stderr, "Unable to set the message digest of BIO\n"); OPENSSL_free(data); BIO_free_all(bhash); diff --git a/cab.c b/cab.c index 76c8507..8ac93dd 100644 --- a/cab.c +++ b/cab.c @@ -205,7 +205,7 @@ static u_char *cab_digest_calc(FILE_FORMAT_CTX *ctx, const EVP_MD *md) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif - if (!BIO_set_md(bhash, md)) { + if (!bhash || !BIO_set_md(bhash, md)) { fprintf(stderr, "Unable to set the message digest of BIO\n"); BIO_free_all(bhash); return 0; /* FAILED */ @@ -493,6 +493,7 @@ static PKCS7 *cab_pkcs7_signature_new(FILE_FORMAT_CTX *ctx, BIO *hash) content = spc_indirect_data_content_get(hash, ctx); if (!content) { fprintf(stderr, "Failed to get spcIndirectDataContent\n"); + PKCS7_free(p7); return NULL; /* FAILED */ } if (!sign_spc_indirect_data_content(p7, content)) { @@ -723,8 +724,11 @@ static int cab_add_jp_attribute(PKCS7 *p7, int jp) if (attrs) { astr = ASN1_STRING_new(); ASN1_STRING_set(astr, attrs, sizeof java_attrs_low); - return PKCS7_add_signed_attribute(si, OBJ_txt2nid(MS_JAVA_SOMETHING), - V_ASN1_SEQUENCE, astr); + if (!PKCS7_add_signed_attribute(si, OBJ_txt2nid(MS_JAVA_SOMETHING), + V_ASN1_SEQUENCE, astr)) { + ASN1_STRING_free(astr); + return 0; /* FAILED */ + } } return 1; /* OK */ } diff --git a/cat.c b/cat.c index 8936c99..242e011 100644 --- a/cat.c +++ b/cat.c @@ -256,6 +256,7 @@ static CAT_CTX *cat_ctx_get(char *indata, uint32_t filesize) static int cat_add_content_type(PKCS7 *p7, PKCS7 *cursig) { const char *content_type; + ASN1_OBJECT *object; STACK_OF(PKCS7_SIGNER_INFO) *signer_info; PKCS7_SIGNER_INFO *si; @@ -275,9 +276,14 @@ static int cat_add_content_type(PKCS7 *p7, PKCS7 *cursig) si = sk_PKCS7_SIGNER_INFO_value(signer_info, 0); if (!si) return 0; /* FAILED */ + object = OBJ_txt2obj(content_type, 1); + if (!object) + return 0; /* FAILED */ if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType, - V_ASN1_OBJECT, OBJ_txt2obj(content_type, 1))) + V_ASN1_OBJECT, object)) { + ASN1_OBJECT_free(object); return 0; /* FAILED */ + } return 1; /* OK */ } diff --git a/helpers.c b/helpers.c index 5fa0840..0b47ffe 100644 --- a/helpers.c +++ b/helpers.c @@ -248,6 +248,7 @@ int add_indirect_data_object(PKCS7 *p7) { STACK_OF(PKCS7_SIGNER_INFO) *signer_info; PKCS7_SIGNER_INFO *si; + ASN1_OBJECT *object; signer_info = PKCS7_get_signer_info(p7); if (!signer_info) @@ -255,9 +256,14 @@ int add_indirect_data_object(PKCS7 *p7) si = sk_PKCS7_SIGNER_INFO_value(signer_info, 0); if (!si) return 0; /* FAILED */ + object = OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, 1); + if (!object) + return 0; /* FAILED */ if (!PKCS7_add_signed_attribute(si, NID_pkcs9_contentType, - V_ASN1_OBJECT, OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, 1))) + V_ASN1_OBJECT, object)) { + ASN1_OBJECT_free(object); return 0; /* FAILED */ + } return 1; /* OK */ } @@ -305,40 +311,40 @@ int sign_spc_indirect_data_content(PKCS7 *p7, ASN1_OCTET_STRING *content) /* * Add encapsulated content to signed PKCS7 structure. - * [in] content: spcIndirectDataContent + * [in] content: spcIndirectDataContent (consumed, also on error) * [returns] new PKCS#7 signature with encapsulated content */ PKCS7 *pkcs7_set_content(ASN1_OCTET_STRING *content) { - PKCS7 *p7, *td7; + PKCS7 *p7 = NULL, *td7 = NULL; - p7 = PKCS7_new(); - if (!p7) { - return NULL; /* FAILED */ - } - if (!PKCS7_set_type(p7, NID_pkcs7_signed)) { - PKCS7_free(p7); - return NULL; /* FAILED */ - } - if (!PKCS7_content_new(p7, NID_pkcs7_data)) { - PKCS7_free(p7); + if (!content) return NULL; /* FAILED */ - } + p7 = PKCS7_new(); + if (!p7 || !PKCS7_set_type(p7, NID_pkcs7_signed) + || !PKCS7_content_new(p7, NID_pkcs7_data)) + goto err; td7 = PKCS7_new(); - if (!td7) { - PKCS7_free(p7); - return NULL; /* FAILED */ - } + if (!td7) + goto err; td7->type = OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, 1); + if (!td7->type) + goto err; td7->d.other = ASN1_TYPE_new(); + if (!td7->d.other) + goto err; td7->d.other->type = V_ASN1_SEQUENCE; td7->d.other->value.sequence = content; - if (!PKCS7_set_content(p7, td7)) { - PKCS7_free(td7); - PKCS7_free(p7); - return NULL; /* FAILED */ - } + content = NULL; /* owned by td7 */ + if (!PKCS7_set_content(p7, td7)) + goto err; return p7; + +err: + ASN1_OCTET_STRING_free(content); + PKCS7_free(td7); + PKCS7_free(p7); + return NULL; /* FAILED */ } /* @@ -458,17 +464,34 @@ ASN1_OCTET_STRING *spc_indirect_data_content_get(BIO *hash, FILE_FORMAT_CTX *ctx return NULL; /* FAILED */ } hashlen = ctx->format->hash_length_get(ctx); + if (hashlen <= 0 || hashlen > (int)sizeof mdbuf) { + fprintf(stderr, "Unsupported message digest length: %d\n", hashlen); + OPENSSL_free(p); + ASN1_OCTET_STRING_free(content); + return NULL; /* FAILED */ + } if (hashlen > EVP_MAX_MD_SIZE) { /* APPX format specific */ mdlen = BIO_read(hash, (char*)mdbuf, hashlen); } else { mdlen = BIO_gets(hash, (char*)mdbuf, EVP_MAX_MD_SIZE); } - data = OPENSSL_malloc((size_t)(len + mdlen)); + if (mdlen != hashlen) { + fprintf(stderr, "Failed to read the message digest\n"); + OPENSSL_free(p); + ASN1_OCTET_STRING_free(content); + return NULL; /* FAILED */ + } + data = OPENSSL_malloc((size_t)(len + hashlen)); + if (!data) { + OPENSSL_free(p); + ASN1_OCTET_STRING_free(content); + return NULL; /* FAILED */ + } memcpy(data, p, (size_t)len); OPENSSL_free(p); - memcpy(data + len, mdbuf, (size_t)mdlen); - if (!ASN1_OCTET_STRING_set(content, data, len + mdlen)) { + memcpy(data + len, mdbuf, (size_t)hashlen); + if (!ASN1_OCTET_STRING_set(content, data, len + hashlen)) { ASN1_OCTET_STRING_free(content); OPENSSL_free(data); return NULL; /* FAILED */ @@ -629,8 +652,8 @@ ASN1_TYPE *catalog_content_get(CatalogAuthAttr *attribute) contents = d2i_ASN1_SET_ANY(NULL, &contents_data, ASN1_STRING_length(value)); if (!contents) return 0; /* FAILED */ - content = sk_ASN1_TYPE_value(contents, 0); - sk_ASN1_TYPE_free(contents); + content = sk_ASN1_TYPE_shift(contents); + sk_ASN1_TYPE_pop_free(contents, ASN1_TYPE_free); return content; } @@ -744,14 +767,24 @@ static SpcSpOpusInfo *spc_sp_opus_info_create(FILE_FORMAT_CTX *ctx) */ static int spc_indirect_data_content_create(u_char **blob, int *len, FILE_FORMAT_CTX *ctx) { - u_char *p = NULL; - int mdtype, hashlen, l = 0; - void *hash; - SpcIndirectDataContent *idc = SpcIndirectDataContent_new(); + u_char *p = NULL, *der; + int mdtype, hashlen, derlen, l = 0; + void *hash = NULL; + SpcIndirectDataContent *idc = NULL; if (!ctx->format->data_blob_get || !ctx->format->hash_length_get) { return 0; /* FAILED */ } + hashlen = ctx->format->hash_length_get(ctx); + if (hashlen <= 0) { + return 0; /* FAILED */ + } + *blob = NULL; + *len = 0; + idc = SpcIndirectDataContent_new(); + if (!idc) { + return 0; /* FAILED */ + } if (ctx->format->md_get) { /* APPX file specific - use a hash algorithm specified in the AppxBlockMap.xml file */ mdtype = EVP_MD_nid(ctx->format->md_get(ctx)); @@ -759,35 +792,64 @@ static int spc_indirect_data_content_create(u_char **blob, int *len, FILE_FORMAT mdtype = EVP_MD_nid(ctx->options->md); } idc->data->value = ASN1_TYPE_new(); + if (!idc->data->value) { + goto err; + } idc->data->value->type = V_ASN1_SEQUENCE; idc->data->value->value.sequence = ASN1_STRING_new(); + if (!idc->data->value->value.sequence) { + goto err; + } idc->data->type = ctx->format->data_blob_get(&p, &l, ctx); if (!idc->data->type) { - SpcIndirectDataContent_free(idc); - return 0; /* FAILED */ + goto err; } if (!ASN1_STRING_set(idc->data->value->value.sequence, p, l)) { - OPENSSL_free(p); - SpcIndirectDataContent_free(idc); - return 0; /* FAILED */ + goto err; } OPENSSL_free(p); + p = NULL; idc->messageDigest->digestAlgorithm->algorithm = OBJ_nid2obj(mdtype); idc->messageDigest->digestAlgorithm->parameters = ASN1_TYPE_new(); + if (!idc->messageDigest->digestAlgorithm->parameters) { + goto err; + } idc->messageDigest->digestAlgorithm->parameters->type = V_ASN1_NULL; - hashlen = ctx->format->hash_length_get(ctx); + /* reserve the message digest appended by the caller */ hash = OPENSSL_zalloc((size_t)hashlen); - ASN1_OCTET_STRING_set(idc->messageDigest->digest, hash, hashlen); + if (!hash) { + goto err; + } + if (!ASN1_OCTET_STRING_set(idc->messageDigest->digest, hash, hashlen)) { + goto err; + } OPENSSL_free(hash); + hash = NULL; - *len = i2d_SpcIndirectDataContent(idc, NULL); - *blob = OPENSSL_malloc((size_t)*len); - p = *blob; - i2d_SpcIndirectDataContent(idc, &p); + derlen = i2d_SpcIndirectDataContent(idc, NULL); + if (derlen <= hashlen) { + goto err; + } + *blob = OPENSSL_malloc((size_t)derlen); + if (!*blob) { + goto err; + } + der = *blob; + if (i2d_SpcIndirectDataContent(idc, &der) != derlen) { + OPENSSL_free(*blob); + *blob = NULL; + goto err; + } SpcIndirectDataContent_free(idc); - *len -= hashlen; + *len = derlen - hashlen; return 1; /* OK */ + +err: + OPENSSL_free(hash); + OPENSSL_free(p); + SpcIndirectDataContent_free(idc); + return 0; /* FAILED */ } /* @@ -814,8 +876,12 @@ static int pkcs7_signer_info_add_spc_sp_opus_info(PKCS7_SIGNER_INFO *si, FILE_FO ASN1_STRING_set(astr, p, len); OPENSSL_free(p); SpcSpOpusInfo_free(opus); - return PKCS7_add_signed_attribute(si, OBJ_txt2nid(SPC_SP_OPUS_INFO_OBJID), - V_ASN1_SEQUENCE, astr); + if (!PKCS7_add_signed_attribute(si, OBJ_txt2nid(SPC_SP_OPUS_INFO_OBJID), + V_ASN1_SEQUENCE, astr)) { + ASN1_STRING_free(astr); + return 0; /* FAILED */ + } + return 1; /* OK */ } /* @@ -830,10 +896,18 @@ static int pkcs7_signer_info_add_spc_sp_opus_info(PKCS7_SIGNER_INFO *si, FILE_FO */ static int pkcs7_signer_info_add_signing_time(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx) { + ASN1_TIME *time; + if (ctx->options->time == INVALID_TIME) /* -time option was not specified */ return 1; /* SUCCESS */ - return PKCS7_add_signed_attribute(si, NID_pkcs9_signingTime, V_ASN1_UTCTIME, - ASN1_TIME_adj(NULL, ctx->options->time, 0, 0)); + time = ASN1_TIME_adj(NULL, ctx->options->time, 0, 0); + if (!time) + return 0; /* FAILED */ + if (!PKCS7_add_signed_attribute(si, NID_pkcs9_signingTime, V_ASN1_UTCTIME, time)) { + ASN1_TIME_free(time); + return 0; /* FAILED */ + } + return 1; /* OK */ } /* @@ -858,8 +932,12 @@ static int pkcs7_signer_info_add_purpose(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX } else { ASN1_STRING_set(purpose, purpose_ind, sizeof purpose_ind); } - return PKCS7_add_signed_attribute(si, OBJ_txt2nid(SPC_STATEMENT_TYPE_OBJID), - V_ASN1_SEQUENCE, purpose); + if (!PKCS7_add_signed_attribute(si, OBJ_txt2nid(SPC_STATEMENT_TYPE_OBJID), + V_ASN1_SEQUENCE, purpose)) { + ASN1_STRING_free(purpose); + return 0; /* FAILED */ + } + return 1; /* OK */ } /* @@ -877,8 +955,12 @@ static int pkcs7_signer_info_add_sequence_number(PKCS7_SIGNER_INFO *si, FILE_FOR ASN1_INTEGER_free(number); return 0; /* FAILED */ } - return PKCS7_add_signed_attribute(si, OBJ_txt2nid(PKCS9_SEQUENCE_NUMBER), - V_ASN1_INTEGER, number); + if (!PKCS7_add_signed_attribute(si, OBJ_txt2nid(PKCS9_SEQUENCE_NUMBER), + V_ASN1_INTEGER, number)) { + ASN1_INTEGER_free(number); + return 0; /* FAILED */ + } + return 1; /* OK */ } /* diff --git a/msi.c b/msi.c index a7dc687..f2bed0e 100644 --- a/msi.c +++ b/msi.c @@ -386,7 +386,7 @@ static u_char *msi_digest_calc(FILE_FORMAT_CTX *ctx, const EVP_MD *md) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif - if (!BIO_set_md(bhash, md)) { + if (!bhash || !BIO_set_md(bhash, md)) { fprintf(stderr, "Unable to set the message digest of BIO\n"); BIO_free_all(bhash); return NULL; /* FAILED */ @@ -434,7 +434,7 @@ static int msi_verify_digests(FILE_FORMAT_CTX *ctx, PKCS7 *p7) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif - if (!BIO_set_md(hash, md)) { + if (!hash || !BIO_set_md(hash, md)) { fprintf(stderr, "Unable to set the message digest of BIO\n"); BIO_free_all(hash); return 0; /* FAILED */ @@ -455,7 +455,7 @@ static int msi_verify_digests(FILE_FORMAT_CTX *ctx, PKCS7 *p7) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif - if (!BIO_set_md(prehash, md)) { + if (!prehash || !BIO_set_md(prehash, md)) { fprintf(stderr, "Unable to set the message digest of BIO\n"); BIO_free_all(hash); BIO_free_all(prehash); @@ -647,6 +647,7 @@ static PKCS7 *msi_pkcs7_signature_new(FILE_FORMAT_CTX *ctx, BIO *hash) content = spc_indirect_data_content_get(hash, ctx); if (!content) { fprintf(stderr, "Failed to get spcIndirectDataContent\n"); + PKCS7_free(p7); return NULL; /* FAILED */ } if (!sign_spc_indirect_data_content(p7, content)) { @@ -1698,11 +1699,12 @@ static int minifat_append(MSI_OUT *out, char *buf, uint32_t len) fprintf(stderr, "Failed to append MiniFAT sector\n"); return 0; /* FAILED */ } - out->minifat = OPENSSL_realloc(out->minifat, (size_t)(out->minifatMemallocCount * out->sectorSize)); - if (!out->minifat) { + char *minifat = OPENSSL_realloc(out->minifat, (size_t)(out->minifatMemallocCount * out->sectorSize)); + if (!minifat) { fprintf(stderr, "Memory allocation failure\n"); return 0; /* FAILED */ } + out->minifat = minifat; } memcpy(out->minifat + out->minifatLen, buf, (size_t)len); out->minifatLen += len; @@ -1717,11 +1719,12 @@ static int fat_append(MSI_OUT *out, char *buf, uint32_t len) fprintf(stderr, "Failed to append FAT sector\n"); return 0; /* FAILED */ } - out->fat = OPENSSL_realloc(out->fat, (size_t)(out->fatMemallocCount * out->sectorSize)); - if (!out->fat) { + char *fat = OPENSSL_realloc(out->fat, (size_t)(out->fatMemallocCount * out->sectorSize)); + if (!fat) { fprintf(stderr, "Memory allocation failure\n"); return 0; /* FAILED */ } + out->fat = fat; } memcpy(out->fat + out->fatLen, buf, (size_t)len); out->fatLen += len; @@ -1736,11 +1739,12 @@ static int difat_append(MSI_OUT *out, char *buf, uint32_t len) fprintf(stderr, "Failed to append DIFAT sector\n"); return 0; /* FAILED */ } - out->difat = OPENSSL_realloc(out->difat, (size_t)(out->difatMemallocCount * out->sectorSize)); - if (!out->difat) { + char *difat = OPENSSL_realloc(out->difat, (size_t)(out->difatMemallocCount * out->sectorSize)); + if (!difat) { fprintf(stderr, "Memory allocation failure\n"); return 0; /* FAILED */ } + out->difat = difat; } memcpy(out->difat + out->difatLen, buf, (size_t)len); out->difatLen += len; @@ -1804,7 +1808,10 @@ static int dirent_insert(MSI_DIRENT *dirent, const u_char *name, uint16_t nameLe } /* create new dirent */ new_dirent = dirent_add(name, nameLen); - sk_MSI_DIRENT_push(dirent->children, new_dirent); + if (!sk_MSI_DIRENT_push(dirent->children, new_dirent)) { + msi_dirent_free(new_dirent); + return 0; /* FAILED */ + } return 1; /* OK */ } diff --git a/osslsigncode.c b/osslsigncode.c index f3a76b1..4761fe4 100644 --- a/osslsigncode.c +++ b/osslsigncode.c @@ -316,7 +316,7 @@ static BIO *bio_encode_rfc3161_request(PKCS7 *p7, const EVP_MD *md) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif - if (!BIO_set_md(bhash, md)) { + if (!bhash || !BIO_set_md(bhash, md)) { fprintf(stderr, "Unable to set the message digest of BIO\n"); goto out; } @@ -687,17 +687,27 @@ static BIO *bio_get_http_curl(long *http_code, char *url, BIO *req, char *proxy, } } if (req) { /* POST */ - if (rfc3161) { - /* RFC3161 Timestamp */ - slist = curl_slist_append(slist, "Content-Type: application/timestamp-query"); - slist = curl_slist_append(slist, "Accept: application/timestamp-reply"); - } else { - /* Authenticode Timestamp */ - slist = curl_slist_append(slist, "Content-Type: application/octet-stream"); - slist = curl_slist_append(slist, "Accept: application/octet-stream"); + const char *headers[] = { + rfc3161 ? "Content-Type: application/timestamp-query" : + "Content-Type: application/octet-stream", + rfc3161 ? "Accept: application/timestamp-reply" : + "Accept: application/octet-stream", + "User-Agent: Transport", + "Cache-Control: no-cache" + }; + size_t i; + + for (i = 0; i < sizeof headers / sizeof headers[0]; i++) { + struct curl_slist *next = curl_slist_append(slist, headers[i]); + + if (!next) { + fprintf(stderr, "CURL failure: unable to allocate HTTP headers\n"); + curl_slist_free_all(slist); + curl_easy_cleanup(curl); + return NULL; /* FAILED */ + } + slist = next; } - slist = curl_slist_append(slist, "User-Agent: Transport"); - slist = curl_slist_append(slist, "Cache-Control: no-cache"); res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist); if (res != CURLE_OK) { fprintf(stderr, "CURL failure: %s %s\n", curl_easy_strerror(res), url); @@ -890,10 +900,21 @@ static void check_authenticode_timestamp(BIO **resp) /* BASE64 encoded Authenticode Timestamp */ BIO *b64 = BIO_new(BIO_f_base64()); + if (!b64) { + BIO_free_all(*resp); + *resp = NULL; + return; + } if (!memchr(ptr, '\n', (size_t)len)) { BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); } else { BIO *bio_mem = BIO_new_mem_buf(ptr, len); + if (!bio_mem) { + BIO_free(b64); + BIO_free_all(*resp); + *resp = NULL; + return; + } BIO_push(b64, bio_mem); } *resp = BIO_push(b64, *resp); @@ -1251,10 +1272,17 @@ static STACK_OF(X509) *X509_chain_read_certs(BIO *bin, char *certpass) { STACK_OF(X509) *certs = sk_X509_new_null(); X509 *x509; + + if (!certs) + return NULL; (void)BIO_seek(bin, 0); x509 = PEM_read_bio_X509(bin, NULL, NULL, certpass); while (x509) { - sk_X509_push(certs, x509); + if (!sk_X509_push(certs, x509)) { + X509_free(x509); + sk_X509_pop_free(certs, X509_free); + return NULL; + } x509 = PEM_read_bio_X509(bin, NULL, NULL, certpass); } ERR_clear_error(); @@ -1273,16 +1301,16 @@ static STACK_OF(X509) *X509_chain_read_certs(BIO *bin, char *certpass) static int add_timestamp_builtin(PKCS7 *p7, FILE_FORMAT_CTX *ctx) { BIO *btmp, *bout; - STACK_OF(X509) *chain; + STACK_OF(X509) *chain = NULL; X509 *signer_cert = NULL; - EVP_PKEY *signer_key; + EVP_PKEY *signer_key = NULL; TS_RESP *response = NULL; int i, res = 1; btmp = bio_new_file(ctx->options->tsa_certfile, "rb"); if (!btmp) { fprintf(stderr, "Failed to read Time-Stamp Authority certificate file: %s\n", ctx->options->tsa_certfile); - return 0; /* FAILED */ + goto out; } /* .pem certificate file */ chain = X509_chain_read_certs(btmp, NULL); @@ -1290,13 +1318,13 @@ static int add_timestamp_builtin(PKCS7 *p7, FILE_FORMAT_CTX *ctx) btmp = bio_new_file(ctx->options->tsa_keyfile, "rb"); if (!btmp) { fprintf(stderr, "Failed to read private key file: %s\n", ctx->options->tsa_keyfile); - return 0; /* FAILED */ + goto out; } signer_key = PEM_read_bio_PrivateKey(btmp, NULL, NULL, NULL); BIO_free(btmp); if(!chain || !signer_key) { fprintf(stderr, "Failed to load Time-Stamp Authority crypto parameters\n"); - return 0; /* FAILED */ + goto out; } /* find the signer's certificate located somewhere in the whole certificate chain */ for (i=0; ilogin && !ENGINE_ctrl_cmd_string(engine, "FORCE_LOGIN", 0, 0)) { fprintf(stderr, "Failed to force a login to the pkcs11 engine\n"); + ENGINE_finish(engine); ENGINE_free(engine); return 0; /* FAILED */ } @@ -4361,8 +4394,11 @@ static int read_token(GLOBAL_OPTIONS *options, ENGINE *engine) fprintf(stderr, "Failed to load certificate %s\n", options->p11cert); ENGINE_finish(engine); return 0; /* FAILED */ - } else - sk_X509_push(options->certs, params.cert); + } else if (!sk_X509_push(options->certs, params.cert)) { + X509_free(params.cert); + ENGINE_finish(engine); + return 0; /* FAILED */ + } } options->pkey = ENGINE_load_private_key(engine, options->keyfile, NULL, NULL); @@ -4561,16 +4597,24 @@ static void load_objects_from_store(const char *url, char *pass, EVP_PKEY **pkey type = OSSL_STORE_INFO_get_type(object); switch (type) { case OSSL_STORE_INFO_PKEY: - if (pkey) + if (pkey) { + EVP_PKEY_free(*pkey); *pkey = OSSL_STORE_INFO_get1_PKEY(object); + } break; case OSSL_STORE_INFO_CERT: - if (certs) - sk_X509_push(certs, OSSL_STORE_INFO_get1_CERT(object)); + if (certs) { + X509 *cert = OSSL_STORE_INFO_get1_CERT(object); + if (!sk_X509_push(certs, cert)) + X509_free(cert); + } break; case OSSL_STORE_INFO_CRL: - if (crls) - sk_X509_CRL_push(crls, OSSL_STORE_INFO_get1_CRL(object)); + if (crls) { + X509_CRL *crl = OSSL_STORE_INFO_get1_CRL(object); + if (!sk_X509_CRL_push(crls, crl)) + X509_CRL_free(crl); + } break; default: break; /* skip any other type */ @@ -4662,6 +4706,7 @@ static int provider_load(const char *pname) providers = sk_OSSL_PROVIDER_new_null(); } if (providers == NULL || !sk_OSSL_PROVIDER_push(providers, prov)) { + OSSL_PROVIDER_unload(prov); providers_cleanup(); return 0; /* FAILED */ } @@ -4861,6 +4906,8 @@ static int main_configure(int argc, char **argv, GLOBAL_OPTIONS *options) usage(argv0, "all"); return 0; /* FAILED */ } + if (options->pass) + OPENSSL_clear_free(options->pass, strlen(options->pass)); options->pass = OPENSSL_strdup(*(++argv)); memset(*argv, 0, strlen(*argv)); #ifdef PROVIDE_ASKPASS @@ -5007,6 +5054,7 @@ static int main_configure(int argc, char **argv, GLOBAL_OPTIONS *options) usage(argv0, "all"); return 0; /* FAILED */ } + OPENSSL_free(options->crlfile); options->crlfile = OPENSSL_strdup(*++argv); } else if ((cmd == CMD_SIGN || cmd == CMD_ADD || cmd == CMD_VERIFY) && !strcmp(*argv, "-HTTPS-CAfile")) { @@ -5022,6 +5070,7 @@ static int main_configure(int argc, char **argv, GLOBAL_OPTIONS *options) usage(argv0, "all"); return 0; /* FAILED */ } + OPENSSL_free(options->https_crlfile); options->https_crlfile = OPENSSL_strdup(*++argv); } else if (cmd == CMD_VERIFY && (!strcmp(*argv, "-untrusted") || !strcmp(*argv, "-TSA-CAfile"))) { if (--argc < 1) { @@ -5035,6 +5084,7 @@ static int main_configure(int argc, char **argv, GLOBAL_OPTIONS *options) usage(argv0, "all"); return 0; /* FAILED */ } + OPENSSL_free(options->tsa_crlfile); options->tsa_crlfile = OPENSSL_strdup(*++argv); } else if (cmd == CMD_VERIFY && !strcmp(*argv, "-require-leaf-hash")) { if (--argc < 1) { @@ -5177,7 +5227,8 @@ static void engine_control_set(GLOBAL_OPTIONS *options, const char *arg) ASN1_STRING_set(engine_ctrl->param, tmp_str, (int)strlen(tmp_str)); } ASN1_STRING_set(engine_ctrl->cmd, arg, (int)strlen(arg)); - sk_EngineControl_push(options->engine_ctrls, engine_ctrl); + if (!sk_EngineControl_push(options->engine_ctrls, engine_ctrl)) + EngineControl_free(engine_ctrl); } #endif /* OPENSSL_NO_ENGINE */ @@ -5228,7 +5279,7 @@ static int main_execute(int argc, char **argv) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif - if (!BIO_set_md(hash, options.md)) { + if (!hash || !BIO_set_md(hash, options.md)) { DO_EXIT_0("Unable to set the message digest of BIO\n"); } #if defined(__GNUC__) @@ -5238,6 +5289,7 @@ static int main_execute(int argc, char **argv) outdata = bio_new_file(options.outfile, "w+b"); if (!outdata) { BIO_free_all(hash); + hash = NULL; DO_EXIT_1("Failed to create file: %s\n", options.outfile); } } @@ -5258,6 +5310,7 @@ static int main_execute(int argc, char **argv) remove_file(options.outfile); } BIO_free_all(hash); + hash = NULL; BIO_free_all(outdata); outdata = NULL; ret = 1; /* FAILED */ @@ -5276,7 +5329,6 @@ static int main_execute(int argc, char **argv) DO_EXIT_0("Unable to extract pkcs7 contents\n"); } ret = data_write_pkcs7(ctx, outdata, p7); - PKCS7_free(p7); goto skip_signing; } else if (options.cmd == CMD_EXTRACT) { if (!ctx->format->pkcs7_extract) { @@ -5287,7 +5339,6 @@ static int main_execute(int argc, char **argv) DO_EXIT_0("Unable to extract existing signature\n"); } ret = data_write_pkcs7(ctx, outdata, p7); - PKCS7_free(p7); goto skip_signing; } else if (options.cmd == CMD_REMOVE) { if (!ctx->format->remove_pkcs7) { @@ -5327,7 +5378,6 @@ static int main_execute(int argc, char **argv) } options.nested_number = nested_signatures_number_get(cursig); if (options.nested_number < 0) { - PKCS7_free(cursig); DO_EXIT_0("Unable to get number of nested signatures\n"); } } @@ -5335,7 +5385,6 @@ static int main_execute(int argc, char **argv) /* Obtain an existing PKCS#7 signature from a "sigin" file */ p7 = pkcs7_get_sigfile(ctx); if (!p7) { - PKCS7_free(cursig); DO_EXIT_0("Unable to extract valid signature\n"); } if (ctx->format->process_data) { @@ -5355,7 +5404,6 @@ static int main_execute(int argc, char **argv) } options.nested_number = nested_signatures_number_get(cursig); if (options.nested_number < 0) { - PKCS7_free(cursig); DO_EXIT_0("Unable to get number of nested signatures\n"); } } @@ -5382,7 +5430,6 @@ static int main_execute(int argc, char **argv) ret = add_timestamp_and_blob(p7, ctx); } if (ret) { - PKCS7_free(p7); DO_EXIT_0("Unable to set unauthenticated attributes\n"); } if (cursig) { @@ -5396,18 +5443,17 @@ static int main_execute(int argc, char **argv) if (ctx->format->append_pkcs7) { ret = ctx->format->append_pkcs7(ctx, outdata, p7); if (ret) { - PKCS7_free(p7); DO_EXIT_0("Append signature to outfile failed\n"); } } if (ctx->format->update_data_size) { ctx->format->update_data_size(ctx, outdata, p7); } - PKCS7_free(p7); skip_signing: if (ctx->format->bio_free) { ctx->format->bio_free(hash, outdata); + hash = NULL; outdata = NULL; } if (!ret && options.cmd == CMD_ATTACH) { @@ -5424,6 +5470,8 @@ static int main_execute(int argc, char **argv) } err_cleanup: + PKCS7_free(p7); + PKCS7_free(cursig); if (outdata) { BIO *head = hash; int outdata_in_hash = 0; @@ -5443,6 +5491,8 @@ static int main_execute(int argc, char **argv) /* unlink outfile */ remove_file(options.outfile); } + } else { + BIO_free_all(hash); } if (ctx && ctx->format->ctx_cleanup) { ctx->format->ctx_cleanup(ctx); diff --git a/pe.c b/pe.c index c52cc0a..7e34832 100644 --- a/pe.c +++ b/pe.c @@ -39,6 +39,7 @@ struct pe_ctx_st { uint32_t sigpos; uint32_t siglen; uint32_t fileend; + uint32_t filesize; /* original mapping length */ }; /* FILE_FORMAT method prototypes */ @@ -500,7 +501,7 @@ static void pe_bio_free(BIO *hash, BIO *outdata) */ static void pe_ctx_cleanup(FILE_FORMAT_CTX *ctx) { - unmap_file(ctx->options->indata, ctx->pe_ctx->fileend); + unmap_file(ctx->options->indata, ctx->pe_ctx->filesize); OPENSSL_free(ctx->pe_ctx); OPENSSL_free(ctx); } @@ -596,6 +597,7 @@ static PE_CTX *pe_ctx_get(char *indata, uint32_t filesize) pe_ctx->sigpos = sigpos; pe_ctx->siglen = siglen; pe_ctx->fileend = filesize; + pe_ctx->filesize = filesize; return pe_ctx; /* OK */ } @@ -782,7 +784,7 @@ static BIO *pe_digest_calc_bio(FILE_FORMAT_CTX *ctx, const EVP_MD *md) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" #endif - if (!BIO_set_md(bhash, md)) { + if (!bhash || !BIO_set_md(bhash, md)) { fprintf(stderr, "Unable to set the message digest of BIO\n"); BIO_free_all(bhash); return 0; /* FAILED */ diff --git a/script.c b/script.c index 539bb9f..a8fb90c 100644 --- a/script.c +++ b/script.c @@ -55,6 +55,7 @@ struct script_ctx_st { int has_signature; uint32_t sigpos; uint32_t fileend; + uint32_t filesize; /* original mapping length */ }; #define LINE_MAX_LEN 100 @@ -247,6 +248,9 @@ static u_char *script_digest_calc(FILE_FORMAT_CTX *ctx, const EVP_MD *md) u_char *mdbuf; BIO *hash = BIO_new(BIO_f_md()); + if (!hash) + return NULL; /* FAILED */ + #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-qual" @@ -405,8 +409,12 @@ static PKCS7 *script_pkcs7_extract(FILE_FORMAT_CTX *ctx) } /* prepare for Base64 decoding */ - bio_mem = BIO_new_mem_buf(clean_base64, (int)clean_base64_len); bio_b64 = BIO_new(BIO_f_base64()); + if (!bio_b64) + goto cleanup; + bio_mem = BIO_new_mem_buf(clean_base64, (int)clean_base64_len); + if (!bio_mem) + goto cleanup; BIO_push(bio_b64, bio_mem); BIO_set_flags(bio_b64, BIO_FLAGS_BASE64_NO_NL); @@ -493,6 +501,7 @@ static PKCS7 *script_pkcs7_signature_new(FILE_FORMAT_CTX *ctx, BIO *hash) content = spc_indirect_data_content_get(hash, ctx); if (!content) { fprintf(stderr, "Failed to get spcIndirectDataContent\n"); + PKCS7_free(p7); return NULL; /* FAILED */ } if (!sign_spc_indirect_data_content(p7, content)) { @@ -587,7 +596,7 @@ static void script_bio_free(BIO *hash, BIO *outdata) */ static void script_ctx_cleanup(FILE_FORMAT_CTX *ctx) { - unmap_file(ctx->options->indata, ctx->script_ctx->fileend); + unmap_file(ctx->options->indata, ctx->script_ctx->filesize); OPENSSL_free(ctx->script_ctx); OPENSSL_free(ctx); } @@ -670,6 +679,7 @@ static SCRIPT_CTX *script_ctx_get(char *indata, uint32_t filesize, const SCRIPT_ script_ctx->utf = utf; script_ctx->has_signature = has_signature; script_ctx->fileend = filesize; + script_ctx->filesize = filesize; script_ctx->sigpos = (uint32_t)sig_pos; return script_ctx; /* OK */ } @@ -834,6 +844,9 @@ static BIO *script_digest_calc_bio(FILE_FORMAT_CTX *ctx, const EVP_MD *md) size_t fileend; BIO *hash = BIO_new(BIO_f_md()); + if (!hash) + return NULL; /* FAILED */ + if (ctx->script_ctx->has_signature) fileend = ctx->script_ctx->sigpos; else From 705c9dcb7a5001fd8728d7fa81c6528ce7f7eb6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Trojnara?= Date: Sun, 15 Nov 2026 15:21:32 +0100 Subject: [PATCH 2/2] Document signature and buffer ownership Make success-only ownership transfers and always-consuming helper contracts explicit at call boundaries. Explain signature cleanup, context-owned APPX buffers and immutable mapping sizes so future changes do not reintroduce leaks or double frees. Comments only; no behavior changes. --- appx.c | 1 + helpers.h | 2 ++ osslsigncode.c | 6 ++++-- pe.c | 4 ++-- script.c | 4 ++-- 5 files changed, 11 insertions(+), 6 deletions(-) diff --git a/appx.c b/appx.c index df65840..9d82e7d 100644 --- a/appx.c +++ b/appx.c @@ -226,6 +226,7 @@ IMPLEMENT_ASN1_FUNCTIONS(AppxSpcSipInfo) struct appx_ctx_st { ZIP_FILE *zip; + /* Hash buffers are owned by this context and freed by appx_ctx_cleanup(). */ u_char *calculatedBMHash; u_char *calculatedCTHash; u_char *calculatedCDHash; diff --git a/helpers.h b/helpers.h index 5d4cb84..8d8861d 100644 --- a/helpers.h +++ b/helpers.h @@ -17,6 +17,7 @@ int data_write_pkcs7(FILE_FORMAT_CTX *ctx, BIO *outdata, PKCS7 *p7); PKCS7 *pkcs7_create(FILE_FORMAT_CTX *ctx); int add_indirect_data_object(PKCS7 *p7); int sign_spc_indirect_data_content(PKCS7 *p7, ASN1_OCTET_STRING *content); +/* Consumes content even on failure; free a non-NULL result with PKCS7_free(). */ PKCS7 *pkcs7_set_content(ASN1_OCTET_STRING *content); int pkcs7_get_content_digest(PKCS7 *p7, u_char *mdbuf, int *mdtype); SpcIndirectDataContent *pkcs7_get_indirect_data_content(PKCS7 *p7); @@ -28,6 +29,7 @@ int bio_hash_data(BIO *hash, char *indata, size_t idx, size_t fileend); void print_hash(const char *descript1, const char *descript2, const u_char *hashbuf, int length); int is_content_type(PKCS7 *p7, const char *objid); MsCtlContent *ms_ctl_content_get(PKCS7 *p7); +/* Borrows attribute; free a non-NULL result with ASN1_TYPE_free(). */ ASN1_TYPE *catalog_content_get(CatalogAuthAttr *attribute); SpcLink *spc_link_obsolete_get(void); int compare_digests(u_char *mdbuf, u_char *cmdbuf, int mdtype); diff --git a/osslsigncode.c b/osslsigncode.c index 4761fe4..d2da58f 100644 --- a/osslsigncode.c +++ b/osslsigncode.c @@ -3386,8 +3386,9 @@ static int verify_signed_file(FILE_FORMAT_CTX *ctx, GLOBAL_OPTIONS *options, /* * Insert PKCS#7 signature and its nested signatures to the sorted signature list - * [in] p7: PKCS#7 signature - * [returns] sorted signature list + * [in] p7: ownership transfers to the returned list only on success + * [returns] owned signature list, or NULL with p7 still owned by the caller + * Free the returned list with sk_PKCS7_pop_free(signatures, PKCS7_free). */ static STACK_OF(PKCS7) *signature_list_create(PKCS7 *p7) { @@ -5253,6 +5254,7 @@ static int main_execute(int argc, char **argv) { FILE_FORMAT_CTX *ctx = NULL; GLOBAL_OPTIONS options; + /* Owned here; every exit path releases the remaining signatures at err_cleanup. */ PKCS7 *p7 = NULL, *cursig = NULL; BIO *outdata = NULL; BIO *hash = NULL; diff --git a/pe.c b/pe.c index 7e34832..856fd49 100644 --- a/pe.c +++ b/pe.c @@ -38,8 +38,8 @@ struct pe_ctx_st { uint32_t nrvas; uint32_t sigpos; uint32_t siglen; - uint32_t fileend; - uint32_t filesize; /* original mapping length */ + uint32_t fileend; /* logical end; may exclude an existing signature */ + uint32_t filesize; /* immutable mapping length, used by ctx_cleanup */ }; /* FILE_FORMAT method prototypes */ diff --git a/script.c b/script.c index a8fb90c..f5d050b 100644 --- a/script.c +++ b/script.c @@ -54,8 +54,8 @@ struct script_ctx_st { int utf; int has_signature; uint32_t sigpos; - uint32_t fileend; - uint32_t filesize; /* original mapping length */ + uint32_t fileend; /* logical end; may exclude an existing signature */ + uint32_t filesize; /* immutable mapping length, used by ctx_cleanup */ }; #define LINE_MAX_LEN 100