Skip to content

Compute the PE checksum while writing the output file - #540

Open
francoisgirinon-netizen wants to merge 1 commit into
mtrojnar:masterfrom
francoisgirinon-netizen:perf/pe-checksum-while-writing
Open

francoisgirinon-netizen wants to merge 1 commit into
mtrojnar:masterfrom
francoisgirinon-netizen:perf/pe-checksum-while-writing

Conversation

@francoisgirinon-netizen

@francoisgirinon-netizen francoisgirinon-netizen commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Pull Request Type

  • Bug fix
  • New feature
  • Code style / formatting / renaming
  • Refactoring (no functional or API changes)
  • Build / CI related changes
  • Documentation
  • Other (please describe): Performance

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 to
the start of the output and reads the whole file again through the BIO, 64 KB at a
time, only to compute the CheckSum field (pe_calc_checksum()). On large files
this read back is a large part of the time of sign and remove-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. sign on a 1 GB PE file takes 1.9 s instead of 12.9 s, remove-signature
2.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 right
      after it is written. The zeroed CheckSum field and Certificate Table entry,
      and the zero padding, add nothing.
    • pe_append_pkcs7() sums the WIN_CERTIFICATE header and the signature.
    • pe_update_data_size() sums the new Certificate Table entry, then folds the sum
      with pe_checksum_fold() and the output size.
    • pe_checksum_add() wraps pe_checksum_sum() for data at any file offset: a
      byte 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 by verify) is
      unchanged.
  • No value stored in the input file is trusted.

Testing

  • Existing tests

  • New tests added

  • Manual testing

  • ctest: 424/424 passed on Windows x86-64 (MSVC 2019, OpenSSL 3.5.9), without
    LARGE_FILE_TESTS. This includes the checksum_* tests from Speed up PE checksum calculation #513, which compare
    the CheckSum field with an independent implementation.

  • The output of this branch and of master were compared byte for byte on 266
    cases: 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-signature and attach-signature -nest. All
    identical.

  • Timings (median of 7 alternating runs, same build options, 1 GB PE file with a
    random overlay, in the page cache):

    command master this branch
    sign 12.9 s 1.9 s
    remove-signature 7.4 s 2.6 s
    attach-signature 11.2 s 12.0 s

    attach-signature does not change: check_attached_data() still reads back and
    hashes the whole output file, and that dominates its time.

Additional Notes

  • pe_update_data_size() now relies on pe_modify_header(), and on
    pe_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

  • I hereby agree to license my contribution under the project's license.

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 olszomal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 + siglen in pe_ctx_get().
  • fileend += len when aligning the output file.
  • len + 8 + padlen when 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants