diff --git a/NEWS.md b/NEWS.md index 9711a5c..8e1b946 100644 --- a/NEWS.md +++ b/NEWS.md @@ -4,6 +4,16 @@ **Other user-visible changes** +- match SignTool's Authenticode attributes: omit primary signingTime and always + include SpcSpOpusInfo, even without description or URL +- accept `-st` and `-time` as deprecated no-ops when signing, with a warning; + `verify -time` and its compatibility alias `verify -st` continue to select + the verification time +- use empty PE image flags and an empty Unicode file link when not generating + page hashes, matching the PE SIP's default encoding +- generate SHA-384 and SHA-512 PE page hashes with the selected signing digest, + matching SignTool; verify these and legacy SHA-256 page-hash tables +- match the CAB SIP's v2 subject OID and serialized cabinet-size hash - fixed memory leaks in signature processing, built-in timestamping and private key loading, and incorrect success reports when TSA parameters cannot be loaded diff --git a/cab.c b/cab.c index 8ac93dd..9662913 100644 --- a/cab.c +++ b/cab.c @@ -42,7 +42,7 @@ struct cab_ctx_st { /* FILE_FORMAT method prototypes */ static FILE_FORMAT_CTX *cab_ctx_new(GLOBAL_OPTIONS *options, BIO *hash, BIO *outdata); -static ASN1_OBJECT *cab_obsolete_link_get(u_char **p, int *plen, FILE_FORMAT_CTX *ctx); +static ASN1_OBJECT *cab_link_get(u_char **p, int *plen, FILE_FORMAT_CTX *ctx); static PKCS7 *cab_pkcs7_contents_get(FILE_FORMAT_CTX *ctx, BIO *hash, const EVP_MD *md); static int cab_hash_length_get(FILE_FORMAT_CTX *ctx); static u_char *cab_digest_calc(FILE_FORMAT_CTX *ctx, const EVP_MD *md); @@ -60,7 +60,7 @@ static int cab_is_detaching_supported(void); FILE_FORMAT file_format_cab = { .ctx_new = cab_ctx_new, - .data_blob_get = cab_obsolete_link_get, + .data_blob_get = cab_link_get, .pkcs7_contents_get = cab_pkcs7_contents_get, .hash_length_get = cab_hash_length_get, .digest_calc = cab_digest_calc, @@ -134,24 +134,71 @@ static FILE_FORMAT_CTX *cab_ctx_new(GLOBAL_OPTIONS *options, BIO *hash, BIO *out * Allocate and return SpcLink object. * [out] p: SpcLink data * [out] plen: SpcLink data length - * [in] ctx: structure holds input and output data (unused) - * [returns] pointer to ASN1_OBJECT structure corresponding to SPC_CAB_DATA_OBJID + * [in] ctx: structure holds input and output data + * [returns] CAB SIP version 2 subject OID, or NULL on failure */ -static ASN1_OBJECT *cab_obsolete_link_get(u_char **p, int *plen, FILE_FORMAT_CTX *ctx) +static ASN1_OBJECT *cab_link_get(u_char **p, int *plen, FILE_FORMAT_CTX *ctx) { - ASN1_OBJECT *dtype; - SpcLink *link = spc_link_obsolete_get(); - - /* squash the unused parameter warning */ - (void)ctx; - - *plen = i2d_SpcLink(link, NULL); - *p = OPENSSL_malloc((size_t)*plen); - i2d_SpcLink(link, p); - *p -= *plen; + static const u_char classid[] = { + 0xa6, 0xb5, 0x86, 0xd5, 0xb4, 0xa1, 0x24, 0x66, + 0xae, 0x05, 0xa2, 0x17, 0xda, 0x8e, 0x60, 0xd6 + }; + u_char size[4], digest[EVP_MAX_MD_SIZE], *serialized = NULL, *q; + unsigned int digest_len; + uint32_t cabinet_size = GET_UINT32_LE(ctx->options->indata + 8); + ASN1_OBJECT *oid = NULL, *dtype = NULL; + X509_ATTRIBUTE *attribute = NULL; + SpcLink *link = NULL; + int len, serialized_len; + + /* The SIP hashes cbCabinet after reserving the signature header, not + * the total file length including the PKCS#7. Re-signing keeps it. */ + if (!(ctx->cab_ctx->flags & FLAG_RESERVE_PRESENT)) { + if (cabinet_size > UINT32_MAX - 24) + goto cleanup; + cabinet_size += 24; + } + PUT_UINT32_LE(cabinet_size, size); + if (!EVP_Digest(size, sizeof size, digest, &digest_len, ctx->options->md, NULL)) + goto cleanup; + oid = OBJ_txt2obj("1.3.6.1.4.1.311.2.5.1", 1); + if (!oid) + goto cleanup; + attribute = X509_ATTRIBUTE_create_by_OBJ(NULL, oid, V_ASN1_OCTET_STRING, + digest, (int)digest_len); + if (!attribute || (len = i2d_X509_ATTRIBUTE(attribute, NULL)) <= 0) + goto cleanup; + /* serializedData is a SET OF attributes, containing the size hash. */ + serialized_len = ASN1_object_size(1, len, V_ASN1_SET); + serialized = OPENSSL_malloc((size_t)serialized_len); + link = SpcLink_new(); + if (!serialized || !link) + goto cleanup; + q = serialized; + ASN1_put_object(&q, 1, len, V_ASN1_SET, V_ASN1_UNIVERSAL); + if (i2d_X509_ATTRIBUTE(attribute, &q) != len) + goto cleanup; + link->type = 1; + link->value.moniker = SpcSerializedObject_new(); + if (!link->value.moniker + || !ASN1_OCTET_STRING_set(link->value.moniker->classId, classid, sizeof classid) + || !ASN1_OCTET_STRING_set(link->value.moniker->serializedData, serialized, serialized_len)) + goto cleanup; dtype = OBJ_txt2obj(SPC_CAB_DATA_OBJID, 1); + if (!dtype) + goto cleanup; + *p = NULL; + *plen = i2d_SpcLink(link, p); + if (*plen <= 0) { + ASN1_OBJECT_free(dtype); + dtype = NULL; + } +cleanup: SpcLink_free(link); - return dtype; /* OK */ + X509_ATTRIBUTE_free(attribute); + ASN1_OBJECT_free(oid); + OPENSSL_free(serialized); + return dtype; } /* diff --git a/cmake/CMakeTest.cmake b/cmake/CMakeTest.cmake index 5ffe542..0a62736 100644 --- a/cmake/CMakeTest.cmake +++ b/cmake/CMakeTest.cmake @@ -47,6 +47,9 @@ if(Python3_FOUND) "${CMAKE_CURRENT_SOURCE_DIR}/tests/make_large_pe.py" "${CMAKE_CURRENT_SOURCE_DIR}/tests/make_crafted_timestamps.py" "${CMAKE_CURRENT_SOURCE_DIR}/tests/check_pe_checksum.py" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/check_pe_page_hashes.py" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/check_signtool_compat.py" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/check_sip_formats.py" "${CMAKE_CURRENT_SOURCE_DIR}/tests/check_msi_tree.py" "${CMAKE_CURRENT_SOURCE_DIR}/tests/start_server.py" "${CMAKE_CURRENT_SOURCE_DIR}/tests/exec.py" @@ -117,14 +120,12 @@ if(Python3_FOUND AND NOT cryptography_error) ### Sign ### # Sign with PKCS#12 container with private key and certificate encryption algorithm - # Signing time: May 1 00:00:00 2019 GMT (1556668800) foreach(ext ${extensions_all}) add_test(NAME "signed_${ext}" COMMAND ${Python3_EXECUTABLE} ${EXEC} ${OSSLSIGNCODE} "sign" "-pkcs12" "${CERTS}/cert.p12" "-readpass" "${CERTS}/password.txt" "-ac" "${CERTS}/CAcross.pem" - "-time" "1556668800" "-add-msi-dse" "-comm" "-ph" @@ -146,7 +147,6 @@ if(Python3_FOUND AND NOT cryptography_error) "-key" "${CERTS}/keyp.pem" "-readpass" "${CERTS}/password.txt" "-ac" "${CERTS}/CAcross.pem" - "-time" "1556668800" # Signing time: May 1 00:00:00 2019 GMT "-add-msi-dse" "-comm" "-ph" @@ -237,7 +237,6 @@ if(Python3_FOUND AND NOT cryptography_error) "-key" "${CERTS}/key.der" "-pass" "passme" "-ac" "${CERTS}/CAcross.pem" - "-time" "1556755200" # Signing time: May 2 00:00:00 2019 GMT "-add-msi-dse" "-comm" "-ph" @@ -253,6 +252,22 @@ if(Python3_FOUND AND NOT cryptography_error) endforeach(ext ${extensions_all}) +### SignTool-compatible default attributes (all supported OpenSSL versions) ### + + add_test(NAME "signtool_compat" + COMMAND ${Python3_EXECUTABLE} "${TEST_DIR}/check_signtool_compat.py" + ${OSSLSIGNCODE} ${FILES}) + list(APPEND ALL_TESTS "signtool_compat") + add_test(NAME "sip_formats" + COMMAND ${Python3_EXECUTABLE} "${TEST_DIR}/check_sip_formats.py" + ${OSSLSIGNCODE} "${FILES}") + list(APPEND ALL_TESTS "sip_formats") + add_test(NAME "pe_page_hashes" + COMMAND ${Python3_EXECUTABLE} "${TEST_DIR}/check_pe_page_hashes.py" + ${OSSLSIGNCODE} "${FILES}") + list(APPEND ALL_TESTS "pe_page_hashes") + + ### PE checksum ### # The CheckSum field of a signed PE file is compared with an independent @@ -496,7 +511,6 @@ if(Python3_FOUND AND NOT cryptography_error) "-pkcs12" "${CERTS}/cert.p12" "-readpass" "${CERTS}/password.txt" "-ac" "${CERTS}/CAcross.pem" - "-time" "1556668800" # Signing time: May 1 00:00:00 2019 GMT "-add-msi-dse" "-comm" "-ph" @@ -518,7 +532,6 @@ if(Python3_FOUND AND NOT cryptography_error) "-pkcs12" "${CERTS}/cert.p12" "-readpass" "${CERTS}/password.txt" "-ac" "${CERTS}/CAcross.pem" - "-time" "1556668800" # Signing time: May 1 00:00:00 2019 GMT "-add-msi-dse" "-comm" "-ph" @@ -615,7 +628,6 @@ if(Python3_FOUND AND NOT cryptography_error) "-h" "sha384" "-i" "https://www.osslsigncode.com/" "-n" "osslsigncode" - "-time" "1556668800" # Signing time: May 1 00:00:00 2019 GMT "-ts" "FILE ${LOGS}/url.log" "-in" "${FILES}/unsigned.${ext}" "-out" "${FILES}/ts_${cert}.${ext}") diff --git a/helpers.c b/helpers.c index 0b47ffe..3abdec7 100644 --- a/helpers.c +++ b/helpers.c @@ -12,7 +12,6 @@ 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); static int pkcs7_signer_info_add_spc_sp_opus_info(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx); -static int pkcs7_signer_info_add_signing_time(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx); static int pkcs7_signer_info_add_purpose(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx); static int pkcs7_signer_info_add_sequence_number(PKCS7_SIGNER_INFO *si, FILE_FORMAT_CTX *ctx); static STACK_OF(X509) *X509_chain_get_sorted(FILE_FORMAT_CTX *ctx, int signer); @@ -200,14 +199,13 @@ PKCS7 *pkcs7_create(FILE_FORMAT_CTX *ctx) goto err; } - if (!pkcs7_signer_info_add_signing_time(si, ctx)) { - goto err; - } if (!pkcs7_signer_info_add_purpose(si, ctx)) { goto err; } - if ((ctx->options->desc || ctx->options->url) && - !pkcs7_signer_info_add_spc_sp_opus_info(si, ctx)) { + /* SignTool's shared I_CreateAuthCodeAttrs/CreateOpusInfo path emits OpusInfo, + * including an empty SEQUENCE when neither -n nor -i was supplied. This + * applies to all SIP formats, not just PE files. */ + if (!pkcs7_signer_info_add_spc_sp_opus_info(si, ctx)) { fprintf(stderr, "Couldn't allocate memory for opus info\n"); goto err; } @@ -501,27 +499,50 @@ ASN1_OCTET_STRING *spc_indirect_data_content_get(BIO *hash, FILE_FORMAT_CTX *ctx } /* - * Signs the data and place the signature in p7 - * [in, out] p7: new PKCS#7 signature + * Sign the prepared Authenticode content, without synthesizing signingTime. + * Both callers embed the content separately after this function returns; + * data contains the SEQUENCE contents, not its ASN.1 tag and length. + * [in, out] p7: new signedData with signed attributes and signing keys * [in] data: content data * [in] len: content length + * [returns] 0 on error or 1 on success */ int pkcs7_sign_content(PKCS7 *p7, const u_char *data, int len) { - BIO *p7bio; + STACK_OF(PKCS7_SIGNER_INFO) *signers = PKCS7_get_signer_info(p7); + int i; - if ((p7bio = PKCS7_dataInit(p7, NULL)) == NULL) { - fprintf(stderr, "PKCS7_dataInit failed\n"); - return 0; /* FAILED */ - } - BIO_write(p7bio, data, len); - (void)BIO_flush(p7bio); - if (!PKCS7_dataFinal(p7, p7bio)) { - fprintf(stderr, "PKCS7_dataFinal failed\n"); - BIO_free_all(p7bio); + /* PKCS7_dataFinal() inserts a missing signingTime by default, unlike + * SignTool. Use the public signer-level API on every supported OpenSSL + * version (including 1.1.1): supply the content digest, then sign the + * existing attributes once. PKCS7_SIGNER_INFO_sign() does not add a time. + * This uses the supplied key and attributes directly, without adding a + * temporary time or signing twice. + * + * This helper only handles newly constructed Authenticode signedData: + * contentType and the other signed attributes are already present, and + * its callers install the encapsulated content. It is not a general + * replacement for PKCS7_dataFinal() (encryption, streaming, no-attrs). */ + if (len < 0 || !signers || sk_PKCS7_SIGNER_INFO_num(signers) <= 0) return 0; /* FAILED */ + for (i = 0; i < sk_PKCS7_SIGNER_INFO_num(signers); i++) { + PKCS7_SIGNER_INFO *si = sk_PKCS7_SIGNER_INFO_value(signers, i); + X509_ALGOR *alg; + EVP_PKEY *key; + const EVP_MD *md; + unsigned char digest[EVP_MAX_MD_SIZE]; + unsigned int digest_len; + + PKCS7_SIGNER_INFO_get0_algs(si, &key, &alg, NULL); + md = EVP_get_digestbyobj(alg->algorithm); + if (!key || !md || sk_X509_ATTRIBUTE_num(PKCS7_get_signed_attributes(si)) <= 0 || + !EVP_Digest(data, (size_t)len, digest, &digest_len, md, NULL) || + !PKCS7_add1_attrib_digest(si, digest, (int)digest_len) || + !PKCS7_SIGNER_INFO_sign(si)) { + fprintf(stderr, "Failed to sign Authenticode attributes\n"); + return 0; /* FAILED */ + } } - BIO_free_all(p7bio); return 1; /* OK */ } @@ -658,25 +679,27 @@ ASN1_TYPE *catalog_content_get(CatalogAuthAttr *attribute) } /* - * PE and CAB format specific - * [in] none - * [returns] pointer to SpcLink + * Build the empty Unicode file link used by the PE SIP. + * [returns] pointer to SpcLink, or NULL on allocation failure */ -SpcLink *spc_link_obsolete_get(void) +SpcLink *spc_link_file_get(void) { - const u_char obsolete[] = { - 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x4f, - 0x00, 0x62, 0x00, 0x73, 0x00, 0x6f, 0x00, 0x6c, - 0x00, 0x65, 0x00, 0x74, 0x00, 0x65, 0x00, 0x3e, - 0x00, 0x3e, 0x00, 0x3e - }; SpcLink *link = SpcLink_new(); + + if (!link) + return NULL; link->type = 2; link->value.file = SpcString_new(); + if (!link->value.file) + goto err; link->value.file->type = 0; link->value.file->value.unicode = ASN1_BMPSTRING_new(); - ASN1_STRING_set(link->value.file->value.unicode, obsolete, sizeof obsolete); + if (!link->value.file->value.unicode) + goto err; return link; +err: + SpcLink_free(link); + return NULL; } /* @@ -884,32 +907,6 @@ static int pkcs7_signer_info_add_spc_sp_opus_info(PKCS7_SIGNER_INFO *si, FILE_FO return 1; /* OK */ } -/* - * Add a custom, non-trusted time to the PKCS7 structure to prevent OpenSSL - * adding the _current_ time. This allows to create a deterministic signature - * when no trusted timestamp server was specified, making osslsigncode - * behaviour closer to signtool.exe (which doesn't include any non-trusted - * time in this case.) - * [in, out] si: PKCS7_SIGNER_INFO structure - * [in] ctx: structure holds input and output data - * [returns] 0 on error or 1 on success - */ -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 */ - 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 */ -} - /* * [in, out] si: PKCS7_SIGNER_INFO structure * [in] ctx: structure holds input and output data diff --git a/helpers.h b/helpers.h index 8d8861d..e87bce3 100644 --- a/helpers.h +++ b/helpers.h @@ -31,7 +31,7 @@ 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); +SpcLink *spc_link_file_get(void); int compare_digests(u_char *mdbuf, u_char *cmdbuf, int mdtype); int spc_indirect_data_content_get_digest(SpcIndirectDataContent *idc, u_char *mdbuf, int *mdtype); diff --git a/osslsigncode.c b/osslsigncode.c index d2da58f..8c7b429 100644 --- a/osslsigncode.c +++ b/osslsigncode.c @@ -3758,7 +3758,6 @@ static void usage(const char *argv0, const char *cmd) printf("%12s[ -TSA-time ]\n", ""); printf("%12s[ -HTTPS-CAfile ]\n", ""); printf("%12s[ -HTTPS-CRLfile ]\n", ""); - printf("%12s[ -time ]\n", ""); printf("%12s[ -addUnauthenticatedBlob [ -blobFile ] ]\n", ""); printf("%12s[ -nest ]\n", ""); printf("%12s[ -verbose ]\n", ""); @@ -3882,7 +3881,7 @@ static void help_for(const char *argv0, const char *cmd) const char *cmds_readpass[] = {"sign", NULL}; const char *cmds_require_leaf_hash[] = {"verify", NULL}; const char *cmds_sigin[] = {"attach-signature", NULL}; - const char *cmds_time[] = {"sign", "verify", NULL}; + const char *cmds_time[] = {"verify", NULL}; const char *cmds_ignore_timestamp[] = {"verify", NULL}; const char *cmds_ignore_cdp[] = {"verify", NULL}; const char *cmds_ignore_crl[] = {"verify", NULL}; @@ -4056,7 +4055,7 @@ static void help_for(const char *argv0, const char *cmd) printf("%26sthis option cannot be used with the -t option\n", ""); } if (on_list(cmd, cmds_time)) - printf("%-24s= the unix-time to set the signing and/or verifying time\n", "-time"); + printf("%-24s= the unix-time to use for certificate verification\n", "-time, -st"); if (on_list(cmd, cmds_CAfileHTTPS)) printf("%-24s= the file containing one or more HTTPS certificates in PEM format\n", "-HTTPS-CAfile"); if (on_list(cmd, cmds_CRLfileHTTPS)) @@ -4966,13 +4965,39 @@ static int main_configure(int argc, char **argv, GLOBAL_OPTIONS *options) return 0; /* FAILED */ } options->url = *(++argv); - } else if ((cmd == CMD_SIGN || cmd == CMD_VERIFY) - && (!strcmp(*argv, "-time") || !strcmp(*argv, "-st"))) { + } else if (cmd == CMD_SIGN && (!strcmp(*argv, "-st") || !strcmp(*argv, "-time"))) { + const char *option = *argv; + if (--argc < 1) { usage(argv0, "all"); return 0; /* FAILED */ } - options->time = (time_t)strtoull(*(++argv), NULL, 10); + /* Keep old signing scripts working; do not parse or encode a time. */ + ++argv; + fprintf(stderr, "Warning: %s is deprecated and ignored when signing\n", option); + } else if (!strcmp(*argv, "-time") || !strcmp(*argv, "-st")) { + char *end; + long long value; + + if (cmd != CMD_VERIFY) { + fprintf(stderr, "%s is only supported by verify\n", *argv); + return 0; /* FAILED */ + } + if (--argc < 1) { + usage(argv0, "all"); + return 0; /* FAILED */ + } + ++argv; + errno = 0; + value = strtoll(*argv, &end, 10); + options->time = (time_t)value; + /* Reject malformed/overflowing input, narrowing to time_t, and + * the internal 'unspecified' sentinel. */ + if (errno == ERANGE || end == *argv || *end != '\0' || + (long long)options->time != value || options->time == INVALID_TIME) { + fprintf(stderr, "Invalid verification time: %s\n", *argv); + return 0; /* FAILED */ + } } else if ((cmd == CMD_SIGN || cmd == CMD_ADD) && !strcmp(*argv, "-t")) { if (--argc < 1) { usage(argv0, "all"); diff --git a/osslsigncode.h b/osslsigncode.h index bb90ece..80fb64f 100644 --- a/osslsigncode.h +++ b/osslsigncode.h @@ -183,10 +183,10 @@ #define SPC_STATEMENT_TYPE_OBJID "1.3.6.1.4.1.311.2.1.11" #define SPC_SP_OPUS_INFO_OBJID "1.3.6.1.4.1.311.2.1.12" #define SPC_PE_IMAGE_DATA_OBJID "1.3.6.1.4.1.311.2.1.15" -#define SPC_CAB_DATA_OBJID "1.3.6.1.4.1.311.2.1.25" +#define SPC_CAB_DATA_OBJID "1.3.6.1.4.1.311.2.1.28" #define SPC_SIPINFO_OBJID "1.3.6.1.4.1.311.2.1.30" #define SPC_PE_IMAGE_PAGE_HASHES_V1 "1.3.6.1.4.1.311.2.3.1" /* SHA1 */ -#define SPC_PE_IMAGE_PAGE_HASHES_V2 "1.3.6.1.4.1.311.2.3.2" /* SHA256 */ +#define SPC_PE_IMAGE_PAGE_HASHES_V2 "1.3.6.1.4.1.311.2.3.2" /* SHA256, SHA384, SHA512 */ #define SPC_NESTED_SIGNATURE_OBJID "1.3.6.1.4.1.311.2.4.1" /* Microsoft OID Time Stamping */ #define SPC_TIME_STAMP_REQUEST_OBJID "1.3.6.1.4.1.311.3.2.1" diff --git a/osslsigncode.md b/osslsigncode.md index 4d923ec..579c02d 100644 --- a/osslsigncode.md +++ b/osslsigncode.md @@ -25,7 +25,6 @@ osslsigncode - Authenticode signing, timestamping, extraction, attachment, remov [`-t` *URL* ... | `-ts` *URL* ...] [`-TSA-certs` *file* `-TSA-key` *file-or-URI* [`-TSA-time` *unix-time*]] [`-HTTPS-CAfile` *file*] [`-HTTPS-CRLfile` *file*] -[`-time` *unix-time*] [`-addUnauthenticatedBlob` [`-blobFile` *file*]] [`-nest`] [`-add-msi-dse`] [`-verbose`] [`-pem`] `-in` *input* `-out` *output* @@ -253,7 +252,12 @@ build. : Add the Java CAB permission attribute. Only `low` is currently supported. `-ph` -: Generate page hashes for executable files. +: Generate page hashes for executable files. SHA-256, SHA-384 and SHA-512 + signatures use the selected digest for page hashes; MD5 and SHA-1 signatures + use SHA-1 page hashes. + +`-st`, `-time` *unix-time*\ +: Deprecated when signing; accepted and ignored with a warning. `-add-msi-dse` : For MSI files, enable the `MsiDigitalSignatureEx` signing mode. In this @@ -343,9 +347,10 @@ The following timestamping modes are **mutually exclusive** within a single `-TSA-CRLfile`, `-CRLuntrusted` *file* : PEM file containing CRLs for timestamp validation. -`-time`, `-st` *unix-time* -: Verification time. If a valid timestamp is present and used, chain - validation is normally performed at the timestamp time. +`-time`, `-st` *unix-time*\ +: Select the verification time (`-1` is reserved). `-st` is a compatibility + alias for `-time`. If a valid timestamp is used, chain validation is normally + performed at the timestamp time. `-ignore-timestamp` : Skip verification of the timestamp signature. diff --git a/pe.c b/pe.c index 856fd49..c5027b3 100644 --- a/pe.c +++ b/pe.c @@ -92,7 +92,7 @@ static int pe_modify_header(FILE_FORMAT_CTX *ctx, BIO *hash, BIO *outdata); static BIO *pe_digest_calc_bio(FILE_FORMAT_CTX *ctx, const EVP_MD *md); static int pkcs7_get_page_hash(PKCS7 *p7, u_char **ph, int *phlen, int *phtype); static int pe_page_hash_get(u_char **ph, int *phlen, int *phtype, SpcAttributeTypeAndOptionalValue *obj); -static u_char *pe_page_hash_calc(int *rphlen, FILE_FORMAT_CTX *ctx, int phtype); +static u_char *pe_page_hash_calc(int *rphlen, FILE_FORMAT_CTX *ctx, int *phtype, int expected_phlen); static int pe_verify_page_hash(FILE_FORMAT_CTX *ctx, u_char *ph, int phlen, int phtype); static SpcLink *pe_page_hash_link_get(FILE_FORMAT_CTX *ctx, int phtype); static int pe_check_file(FILE_FORMAT_CTX *ctx); @@ -156,12 +156,17 @@ static ASN1_OBJECT *pe_spc_image_data_get(u_char **p, int *plen, FILE_FORMAT_CTX ASN1_OBJECT *dtype; SpcPeImageData *pid = SpcPeImageData_new(); - ASN1_BIT_STRING_set_bit(pid->flags, 0, 1); + if (!pid) + return NULL; + /* Match the PE SIP: empty image flags, also when page hashes are present. + * This is PE subject data, not a rule for other formats' SIP data. */ if (ctx->options->pagehash) { SpcLink *link; - phtype = NID_sha1; - if (EVP_MD_size(ctx->options->md) > EVP_MD_size(EVP_sha1())) - phtype = NID_sha256; + /* The PE SIP uses the selected SHA-2 algorithm, not always SHA-256. + * Keep SHA-1 page hashes for MD5 and SHA-1 signatures. */ + phtype = EVP_MD_nid(ctx->options->md); + if (EVP_MD_size(ctx->options->md) <= EVP_MD_size(EVP_sha1())) + phtype = NID_sha1; link = pe_page_hash_link_get(ctx, phtype); if (!link) { SpcPeImageData_free(pid); @@ -169,7 +174,11 @@ static ASN1_OBJECT *pe_spc_image_data_get(u_char **p, int *plen, FILE_FORMAT_CTX } pid->file = link; } else { - pid->file = spc_link_obsolete_get(); + pid->file = spc_link_file_get(); + if (!pid->file) { + SpcPeImageData_free(pid); + return NULL; + } } *plen = i2d_SpcPeImageData(pid, NULL); *p = OPENSSL_malloc((size_t)*plen); @@ -942,7 +951,8 @@ static int pe_page_hash_get(u_char **ph, int *phlen, int *phtype, if (!obj) return 0; /* FAILED */ - /* Determine page hash algorithm */ + /* V1 identifies SHA-1. V2 covers SHA-256/384/512; use NID_sha256 as + * its initial type and resolve the digest width during verification. */ *phtype = 0; buf[0] = 0x00; OBJ_obj2txt(buf, sizeof buf, obj->type, 1); @@ -1001,10 +1011,12 @@ static int pe_page_hash_get(u_char **ph, int *phlen, int *phtype, * Calculate page hash for the PE file. * [out] rphlen: page hash length * [in] ctx: structure holds input and output data - * [in] phtype: NID_sha1 or NID_sha256 + * [in, out] phtype: page hash algorithm (NID_sha1 or a SHA-2 NID) + * [in] expected_phlen: serialized table length for verification, or 0 when signing; + * for V2, resolve phtype from this length and the PE's page count * [returns] pointer to calculated page hash */ -static u_char *pe_page_hash_calc(int *rphlen, FILE_FORMAT_CTX *ctx, int phtype) +static u_char *pe_page_hash_calc(int *rphlen, FILE_FORMAT_CTX *ctx, int *phtype, int expected_phlen) { uint16_t nsections, opthdr_size; uint32_t alignment, pagesize, hdrsize; @@ -1014,23 +1026,17 @@ static u_char *pe_page_hash_calc(int *rphlen, FILE_FORMAT_CTX *ctx, int phtype) size_t written, off, sect_off, sect_tbl, need; u_char *res = NULL, *zeroes = NULL; char *sections; - const EVP_MD *md = EVP_get_digestbynid(phtype); + const EVP_MD *md; BIO *bhash = NULL; uint32_t filebound; size_t pphlen_sz, sections_factor; uint64_t pages; - if (rphlen == NULL || ctx == NULL || ctx->options == NULL || ctx->pe_ctx == NULL + if (rphlen == NULL || phtype == NULL || expected_phlen < 0 + || ctx == NULL || ctx->options == NULL || ctx->pe_ctx == NULL || ctx->options->indata == NULL) return NULL; - if (md == NULL) - return NULL; - - mdlen = EVP_MD_size(md); - if (mdlen <= 0) - return NULL; - /* NumberOfSections indicates the size of the section table, * which immediately follows the headers, can be up to 65535 under Vista and later */ nsections = GET_UINT16_LE(ctx->options->indata + ctx->pe_ctx->header_size + 6); @@ -1077,8 +1083,6 @@ static u_char *pe_page_hash_calc(int *rphlen, FILE_FORMAT_CTX *ctx, int phtype) pagesize, hdrsize); return NULL; /* FAILED */ } - pphlen = 4 + mdlen; - /* Determine the file boundary for section data validation */ filebound = ctx->pe_ctx->sigpos ? ctx->pe_ctx->sigpos : ctx->pe_ctx->fileend; @@ -1109,6 +1113,32 @@ static u_char *pe_page_hash_calc(int *rphlen, FILE_FORMAT_CTX *ctx, int phtype) } pages += ((uint64_t)rs + pagesize - 1) / pagesize; } + if (expected_phlen > 0 && *phtype == NID_sha256) { + /* V2 has no separate OIDs for the SHA-2 digest widths. There is one + * record per page, plus the header and terminating records, each + * containing a 4-byte offset and a digest. Resolve the width using + * the actual PE geometry, not the enclosing signature's algorithm: + * older osslsigncode versions always emitted SHA-256 page hashes. + * The caller still compares the entire calculated table. */ + if ((uint64_t)expected_phlen == (pages + 2) * (4 + 32)) + *phtype = NID_sha256; + else if ((uint64_t)expected_phlen == (pages + 2) * (4 + 48)) + *phtype = NID_sha384; + else if ((uint64_t)expected_phlen == (pages + 2) * (4 + 64)) + *phtype = NID_sha512; + else { + fprintf(stderr, "Invalid V2 page hash table length: %d\n", expected_phlen); + return NULL; /* FAILED */ + } + } + md = EVP_get_digestbynid(*phtype); + if (md == NULL) + return NULL; + mdlen = EVP_MD_size(md); + if (mdlen <= 0) + return NULL; + pphlen = 4 + mdlen; + /* Never more than the pages of the whole file, overlapping sections * that would need more are rejected while computing the page hash */ if (pages > (uint64_t)nsections + ctx->pe_ctx->fileend / pagesize) @@ -1116,8 +1146,7 @@ static u_char *pe_page_hash_calc(int *rphlen, FILE_FORMAT_CTX *ctx, int phtype) /* header page + last entry (end of the last section) + 1 spare */ sections_factor = 3 + (size_t)pages; pphlen_sz = (size_t)pphlen; - /* Sanity limit - a PE file is at most 4 GB, so even with 512 byte pages - * the page hash stays below 512 MB */ + /* Bound the allocation even for overlapping sections and wide digests. */ if (sections_factor > SIZE_512M / pphlen_sz) { fprintf(stderr, "Page hash size exceeds limit: %zu\n", sections_factor * pphlen_sz); return NULL; /* FAILED */ @@ -1314,7 +1343,7 @@ static u_char *pe_page_hash_calc(int *rphlen, FILE_FORMAT_CTX *ctx, int phtype) * [in] ctx: structure holds input and output data * [in] ph: page hash * [in] phlen: page hash length - * [in] phtype: NID_sha1 or NID_sha256 + * [in] phtype: NID_sha1 for V1, NID_sha256 for V2 (resolved from the table length) * [returns] 0 on error or 1 on success */ static int pe_verify_page_hash(FILE_FORMAT_CTX *ctx, u_char *ph, int phlen, int phtype) @@ -1324,7 +1353,7 @@ static int pe_verify_page_hash(FILE_FORMAT_CTX *ctx, u_char *ph, int phlen, int if (!ph) return 1; /* OK */ - cph = pe_page_hash_calc(&cphlen, ctx, phtype); + cph = pe_page_hash_calc(&cphlen, ctx, &phtype, phlen); if (!cph) { fprintf(stderr, "Page hash verification failed: could not calculate page hash\n"); return 0; /* FAILED */ @@ -1345,7 +1374,7 @@ static int pe_verify_page_hash(FILE_FORMAT_CTX *ctx, u_char *ph, int phlen, int /* * Create a new SpcLink structure. * [in] ctx: structure holds input and output data - * [in] phtype: NID_sha1 or NID_sha256 + * [in] phtype: NID_sha1, NID_sha256, NID_sha384 or NID_sha512 * [returns] pointer to SpcLink structure */ static SpcLink *pe_page_hash_link_get(FILE_FORMAT_CTX *ctx, int phtype) @@ -1359,7 +1388,7 @@ static SpcLink *pe_page_hash_link_get(FILE_FORMAT_CTX *ctx, int phtype) SpcLink *link; STACK_OF(ASN1_TYPE) *oset, *aset; - ph = pe_page_hash_calc(&phlen, ctx, phtype); + ph = pe_page_hash_calc(&phlen, ctx, &phtype, 0); if (!ph) { fprintf(stderr, "Failed to calculate page hash\n"); return NULL; /* FAILED */ diff --git a/tests/check_pe_page_hashes.py b/tests/check_pe_page_hashes.py new file mode 100644 index 0000000..d9b03ea --- /dev/null +++ b/tests/check_pe_page_hashes.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""Check PE page hashes independently, without Windows or a timestamp service.""" + +import argparse +import hashlib +import struct +import tempfile +from pathlib import Path + +from check_pe_checksum import pe_checksum +from check_signtool_compat import (make_certificate, parse_der, pkcs7_layout, run, + signature_layout) +from check_sip_formats import replace_content, tlv +from make_large_pe import make_pe + + +CLASS_ID = bytes.fromhex("a6b586d5b4a12466ae05a217da8e60d6") +PAGE_HASH_V1 = bytes.fromhex("2b060104018237020301") +PAGE_HASH_V2 = bytes.fromhex("2b060104018237020302") + + +def pe_layout(data): + """Return the optional header, section table, count, and certificate directory.""" + pe = struct.unpack_from(" 2 else blob[1]) + assert not any(blob[header + content_len:]) + attrs, content = pkcs7_layout(blob[:header + content_len], public_key, digest) + image = content.children()[0].children()[1].children() + assert image[0].tag == 3 and image[1].tag == 0xa0 + link = image[1].children()[0] + return attrs, image[0], link + + +def pkcs7_layout(blob, public_key, digest): + """Validate signed attributes and content digest for any Authenticode SIP.""" + pkcs7 = parse_der(blob)[0] + signed = pkcs7.children()[1].children()[0].children() + content = signed[2].children()[1].children()[0] + assert content.tag == 0x30 + signers = signed[-1].children() + assert len(signers) == 1 + signer = signers[0].children() + assert len(signer) == 6 # No unsigned timestamp attributes. + assert signer[3].tag == 0xa0 + attrs = {} + for attr in signer[3].children(): + oid, values = attr.children() + assert oid.body not in attrs + attrs[oid.body] = values + assert CONTENT_TYPE in attrs and MESSAGE_DIGEST in attrs + assert attrs[MESSAGE_DIGEST].children()[0].body == hashlib.new( + digest, content.body).digest() + # Authenticode signs a SET encoding, not the context-specific [0] tag. + public_key.verify(signer[-1].body, b"\x31" + signer[3].encoded[1:], + padding.PKCS1v15(), getattr(hashes, digest.upper())()) + return attrs, content + + +def make_certificate(directory, publisher=None): + """Create an isolated self-signed code-signing certificate and private key.""" + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, + "osslsigncode compatibility test")]) + if publisher is not None: + name = x509.Name.from_rfc4514_string(publisher.replace(", ", ","), + {"E": NameOID.EMAIL_ADDRESS, "S": NameOID.STATE_OR_PROVINCE_NAME}) + now = datetime.datetime.now(datetime.timezone.utc) + cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name) + .public_key(key.public_key()).serial_number(x509.random_serial_number()) + .not_valid_before(now - datetime.timedelta(days=1)) + .not_valid_after(now + datetime.timedelta(days=1)) + .add_extension(x509.BasicConstraints(ca=True, path_length=None), True) + .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CODE_SIGNING]), False) + .sign(key, hashes.SHA256())) + cert_path, key_path = directory / "cert.pem", directory / "key.pem" + cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM)) + key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption())) + return key, cert_path, key_path + + +def run(args, expected_error=None): + """Run osslsigncode and retain diagnostics on failure.""" + result = subprocess.run([str(arg) for arg in args], check=False, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True) + if expected_error is not None: + assert result.returncode != 0 and expected_error in result.stdout, result.stdout + else: + assert result.returncode == 0, result.stdout + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("osslsigncode") + parser.add_argument("files", type=Path) + args = parser.parse_args() + originals = {path: path.read_bytes() for path in args.files.glob("unsigned.*")} + # AppX signing certificates must match the package publisher. Use the same + # disposable certificate for all formats to keep this test self-contained. + with zipfile.ZipFile(args.files / "unsigned.256appx") as archive: + manifest = ET.fromstring(archive.read("AppxManifest.xml")) + publisher = next(child for child in manifest if child.tag.endswith("Identity")).attrib["Publisher"] + with tempfile.TemporaryDirectory(prefix="signtool-compat-") as tmp: + directory = Path(tmp) + key, cert, key_file = make_certificate(directory, publisher) + command = [args.osslsigncode, "sign", "-certs", cert, "-key", key_file] + + def sign(case, extra, digest="sha1", ext="exe"): + output = directory / (case + "." + ext) + result = run(command + ["-h", digest] + extra + ["-in", args.files / ("unsigned." + ext), + "-out", output]) + for option in ("-st", "-time"): + if option in extra: + assert option + " is deprecated and ignored when signing" in result.stdout + if ext == "exe": + layout = signature_layout(output, key.public_key(), digest) + else: + der = directory / (case + ".der") + run([args.osslsigncode, "extract-signature", "-in", output, "-out", der]) + attrs, _ = pkcs7_layout(der.read_bytes(), key.public_key(), digest) + layout = attrs, None, None + run([args.osslsigncode, "verify", "-CAfile", cert, "-in", output]) + return layout + + # The same signer-level path and expectations apply to every supported + # OpenSSL version, without requiring an automatic-time omission API. + for digest in ("sha1", "sha256"): + attrs, flags, link = sign("default-" + digest, [], digest) + assert SIGNING_TIME not in attrs + assert attrs[OPUS_INFO].encoded == bytes.fromhex("31023000") + assert flags.encoded == bytes.fromhex("030100") + assert link.encoded == bytes.fromhex("a2028000") + + attrs, _, _ = sign("metadata", ["-n", "description", "-i", "https://example.test/"]) + opus = attrs[OPUS_INFO].children()[0].children() + assert len(opus) == 2 + assert opus[0].children()[0].tag == 0x81 + assert opus[0].children()[0].body == b"description" + assert opus[1].children()[0].body == b"https://example.test/" + attrs, _, _ = sign("empty-url", ["-i", ""]) + assert attrs[OPUS_INFO].encoded == bytes.fromhex("31063004a1028000") + for option in ("-st", "-time"): + for label, epoch in (("epoch", "0"), ("future", "4294967295"), ("negative", "-1")): + case = option[1:] + "-" + label + attrs, _, _ = sign(case, [option, epoch]) + assert SIGNING_TIME not in attrs + assert (directory / (case + ".exe")).read_bytes() == (directory / "default-sha1.exe").read_bytes() + run(command + [option], "Usage:") + attrs, _, _ = sign("both-options", ["-st", "0", "-time", "-1"]) + assert SIGNING_TIME not in attrs + assert (directory / "both-options.exe").read_bytes() == (directory / "default-sha1.exe").read_bytes() + + verify = [args.osslsigncode, "verify", "-CAfile", cert, + "-in", directory / "default-sha1.exe"] + now = str(int(datetime.datetime.now(datetime.timezone.utc).timestamp())) + for option in ("-time", "-st"): + result = run(verify + [option, now]) + assert "deprecated" not in result.stdout, result.stdout + run(verify + [option, "0"], "certificate is not yet valid") + run(verify + [option], "Usage:") + for value in ("", "abc", "1junk", "-1", "18446744073709551615", "-99999999999999999999"): + run(verify + [option, value], "Invalid verification time") + # Both spellings set the same option; the last value takes precedence. + run(verify + ["-time", "0", "-st", now]) + run(verify + ["-st", "0", "-time", now]) + run(verify + ["-time", now, "-st", "0"], "certificate is not yet valid") + run(verify + ["-st", now, "-time", "0"], "certificate is not yet valid") + attrs, flags, link = sign("pagehash", ["-ph"]) + assert SIGNING_TIME not in attrs and flags.encoded == bytes.fromhex("030100") + assert link.tag == 0xa1 and len(link.body) > 16 # Serialized page-hash object. + for ext in ("ex_", "msi", "cat", "ps1", "psc1", "mof", "js", "256appx", "512appx"): + digest = "sha512" if ext == "512appx" else "sha256" + attrs, _, _ = sign("default-" + ext, [], digest, ext) + assert SIGNING_TIME not in attrs, ext + assert attrs[OPUS_INFO].encoded == bytes.fromhex("31023000"), ext + for option in ("-st", "-time"): + legacy_attrs, _, _ = sign("legacy-" + option[1:] + "-" + ext, [option, "-1"], digest, ext) + assert legacy_attrs == attrs, ext + assert all(path.read_bytes() == data for path, data in originals.items()) + print("No signingTime and legacy -st/-time no-ops verified for all ten formats; " + "verify -time/-st aliases checked; " + "content digests, RSA signatures, PE metadata and checksums verified") + + +if __name__ == "__main__": + main() diff --git a/tests/check_sip_formats.py b/tests/check_sip_formats.py new file mode 100644 index 0000000..6517b5a --- /dev/null +++ b/tests/check_sip_formats.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +"""CAB SIP regressions, with independent digest and RSA checks.""" +import argparse +import hashlib +import struct +import tempfile +from pathlib import Path + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import padding + +from check_signtool_compat import (make_certificate, parse_der, pkcs7_layout, run, + SIGNING_TIME, MESSAGE_DIGEST) + + +def tlv(tag, body): + size = len(body) + length = bytes([size]) if size < 128 else size.to_bytes((size.bit_length() + 7) // 8, "big") + if size >= 128: + length = bytes([0x80 | len(length)]) + length + return bytes([tag]) + length + body + + +def replace_content(blob, content, key, digest): + """Make a legacy test signature with the disposable key, not a patched file signature.""" + outer = parse_der(blob)[0].children() + signed = outer[1].children()[0].children() + old_content = signed[2].children() + new_content = tlv(0x30, old_content[0].encoded + tlv(0xa0, content)) + signer = signed[-1].children()[0].children() + attrs = [] + for attr in signer[3].children(): + oid, values = attr.children() + if oid.body == MESSAGE_DIGEST: + values = parse_der(tlv(0x31, tlv(4, hashlib.new(digest, parse_der(content)[0].body).digest())))[0] + attrs.append(tlv(0x30, oid.encoded + values.encoded)) + attrs = b"".join(sorted(attrs)) + sig = key.sign(tlv(0x31, attrs), padding.PKCS1v15(), getattr(hashes, digest.upper())()) + signer = (b"".join(n.encoded for n in signer[:3]) + tlv(0xa0, attrs) + + signer[4].encoded + tlv(4, sig)) + signed = (b"".join(n.encoded for n in signed[:2]) + new_content + + b"".join(n.encoded for n in signed[3:-1]) + tlv(0x31, tlv(0x30, signer))) + return tlv(0x30, outer[0].encoded + tlv(0xa0, tlv(0x30, signed))) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("osslsigncode") + parser.add_argument("files", type=Path) + args = parser.parse_args() + originals = {p: p.read_bytes() for p in args.files.glob("unsigned.*")} + tool = args.osslsigncode + with tempfile.TemporaryDirectory(prefix="sip-formats-") as tmp: + directory = Path(tmp) + key, cert, key_file = make_certificate(directory) + counter = 0 + + def verify(path): + run([tool, "verify", "-CAfile", cert, "-in", path]) + + def extract(path): + nonlocal counter + counter += 1 + der = directory / (str(counter) + ".der") + run([tool, "extract-signature", "-in", path, "-out", der]) + return der.read_bytes(), der + + def sign(source, digest="sha256", extra=(), error=None): + nonlocal counter + counter += 1 + output = directory / (str(counter) + source.suffix) + run([tool, "sign", "-certs", cert, "-key", key_file, "-h", digest, + *extra, "-in", source, "-out", output], error) + if error is None: + verify(output) + return output + + def detached(source, digest, flags=()): + nonlocal counter + counter += 1 + data = directory / (str(counter) + ".data") + run([tool, "extract-data", "-h", digest, *flags, "-in", source, "-out", data]) + signature = sign(data, digest) + output = directory / (str(counter) + "-detached" + source.suffix) + run([tool, "attach-signature", "-h", digest, *flags, "-sigin", signature, + "-in", source, "-out", output]) + verify(output) + return output + + def content(path, digest): + blob, _ = extract(path) + attrs, value = pkcs7_layout(blob, key.public_key(), digest) + assert SIGNING_TIME not in attrs + return blob, value.children() + + # CAB v2: the auxiliary hash covers four little-endian cbCabinet bytes. + for digest in ("sha1", "sha256", "sha512"): + source = args.files / "unsigned.ex_" + output = sign(source, digest) + blob, value = content(output, digest) + subject, main_digest = value + assert subject.children()[0].body.hex() == "2b06010401823702011c" + link = subject.children()[1] + assert link.tag == 0xa1 + clsid, serialized = link.children() + assert clsid.body.hex() == "a6b586d5b4a12466ae05a217da8e60d6" + attribute = parse_der(serialized.body)[0].children()[0].children() + assert attribute[0].body.hex() == "2b060104018237020501" + data = output.read_bytes() + assert attribute[1].children()[0].body == hashlib.new(digest, data[8:12]).digest() + sigpos = struct.unpack_from(">>'.encode('utf-16-be')))) + legacy_blob = replace_content(blob, tlv(0x30, legacy_subject + main_digest.encoded), key, digest) + legacy_blob += bytes((-len(legacy_blob)) % 8) + header = bytearray(data[:sigpos]) + struct.pack_into('