Repository navigation
Compute the PE checksum while writing the output file - #540
francoisgirinon-netizen wants to merge 1 commit into
Conversation
After writing a signed or unsigned PE file, pe_update_data_size() read the whole output file back to compute its checksum. On a multi-GB file this is a full extra read of the output. The checksum is a ones' complement sum of 16-bit words plus the file size, so it can be accumulated on the data as it is written: the input bytes copied by pe_modify_header() (each 64 KB chunk is summed right after it is written, while still in the CPU cache), the WIN_CERTIFICATE and signature, and the new Certificate Table entry. The zeroed CheckSum field and the zero padding add nothing. Each byte is summed according to its own file offset, so the result does not depend on the parity of the offsets. No value stored in the input file is trusted. The output files are byte-for-byte identical to the previous ones.
olszomal
left a comment
There was a problem hiding this comment.
The incremental checksum calculation is correct and provides a significant performance improvement. All tests passed on Fedora 43, including LARGE_FILE_TESTS=ON.
During the review, I identified three issues closely related to the modified code that should be addressed within this PR.
1. PE checksum verification with an unaligned CheckSum field
The current pe_checksum_sum() implementation excludes the CheckSum field by subtracting two aligned 16-bit words. However, when e_lfanew is odd, the CheckSum field spans three consecutive 16-bit words, and the alignment condition prevents its exclusion.
As a result, verify may incorrectly report an invalid PE checksum even though the checksum stored in the file is correct.
The solution is to subtract the four individual bytes of the CheckSum field according to their absolute file offsets, regardless of alignment:
static uint64_t pe_checksum_sum(const u_char *data, size_t nwords,
uint32_t offset, uint32_t header_size)
{
uint64_t sum = 0;
uint32_t pos = header_size + 88;
size_t i;
for (i = 0; i < nwords; i++)
sum += (uint32_t)data[2 * i] | ((uint32_t)data[2 * i + 1] << 8);
/* Exclude all four bytes of the CheckSum field, regardless of its alignment. */
for (i = 0; i < 4; i++) {
uint32_t bytepos = pos + (uint32_t)i;
if (bytepos >= offset && (bytepos - offset) / 2 < nwords) {
uint32_t value = data[bytepos - offset];
sum -= value << ((bytepos % 2) * 8);
}
}
return sum;
}I reproduced the issue and successfully tested the proposed fix. All regression tests passed.
2. Output BIO error handling
Several BIO_write() and BIO_seek() return values remain unchecked. This is particularly relevant now that the checksum is accumulated during writing.
Please check all write and seek operations in pe_modify_header(), pe_append_pkcs7() and pe_update_data_size(). This also requires changing the update_data_size() callback to return a status and handling failures in osslsigncode.c.
A broader review of I/O error handling across other file formats can be addressed separately.
3. Integer overflows in PE file size calculations
Several size calculations remain susceptible to integer overflow:
sigpos + sigleninpe_ctx_get().fileend += lenwhen aligning the output file.len + 8 + padlenwhen calculating the certificate table size.outsize += (uint32_t)(len + 8 + padlen)when calculating the final output size.
Use subtraction-based bounds checks where possible (e.g. siglen != filesize - sigpos after validating sigpos) and perform size calculations using uint64_t intermediates where appropriate.
Note that casting len + 8 + padlen to uint32_t does not prevent signed integer overflow, since the addition is performed using int arithmetic. The operands must be promoted before the addition.
Validate both the aligned file size and the final signed file size against UINT32_MAX before performing the corresponding write operations.
The overall approach looks good. Please address the issues outlined above before merging this PR.
Pull Request Type
Related Issue
Issue number: N/A (follow-up to #513)
Current Behavior
After writing a signed or unsigned PE file,
pe_update_data_size()seeks back tothe start of the output and reads the whole file again through the BIO, 64 KB at a
time, only to compute the
CheckSumfield (pe_calc_checksum()). On large filesthis read back is a large part of the time of
signandremove-signature.New Behavior
The checksum is a one's complement sum of 16-bit words plus the file size, so it is
now accumulated on the data as it is written, and the output file is no longer read
back.
signon a 1 GB PE file takes 1.9 s instead of 12.9 s,remove-signature2.6 s instead of 7.4 s. The output files are byte identical.
Scope of Changes
pe.c:pe_modify_header()sums the input bytes it copies, each 64 KB chunk rightafter it is written. The zeroed
CheckSumfield and Certificate Table entry,and the zero padding, add nothing.
pe_append_pkcs7()sums theWIN_CERTIFICATEheader and the signature.pe_update_data_size()sums the new Certificate Table entry, then folds the sumwith
pe_checksum_fold()and the output size.pe_checksum_add()wrapspe_checksum_sum()for data at any file offset: abyte at an odd offset is the high byte of its word, so the result does not
depend on where the data is split.
pe_calc_checksum()is removed.pe_calc_realchecksum()(used byverify) isunchanged.
Testing
Existing tests
New tests added
Manual testing
ctest: 424/424 passed on Windows x86-64 (MSVC 2019, OpenSSL 3.5.9), withoutLARGE_FILE_TESTS. This includes thechecksum_*tests from Speed up PE checksum calculation #513, which comparethe
CheckSumfield with an independent implementation.The output of this branch and of
masterwere compared byte for byte on 266cases: PE32 and PE32+ files, with and without an overlay, with 1 to 7 trailing
bytes, with an odd
e_lfanew, and with a signature table at an odd offset;commands
sign,sign -ph,sign -nest, re-signing,add,remove-signature,attach-signatureandattach-signature -nest. Allidentical.
Timings (median of 7 alternating runs, same build options, 1 GB PE file with a
random overlay, in the page cache):
signremove-signatureattach-signatureattach-signaturedoes not change:check_attached_data()still reads back andhashes the whole output file, and that dominates its time.
Additional Notes
pe_update_data_size()now relies onpe_modify_header(), and onpe_append_pkcs7()with the same signature, having run on the same context.Every caller in
main_execute()does; the function comment says so.License Declaration