Skip to content

Commit b558383

Browse files
scripts: fix compute_authenticode_hash for unsigned PEs
When the PE has no attached certificate the security data directory fields VirtualAddress and Size are both 0. The previous unconditional slicing: pe_data[certificate_table_offset + 0x08 : 0] # -> empty + pe_data[0 + 0 :] # -> whole file re-appended produced a wrong digest for unsigned images. Add an explicit branch: when VirtualAddress == 0, hash only the bytes that follow the 8-byte cert-dir data-directory entry, which is the correct tail of an unsigned PE image. Signed-off-by: Jeremy Compostella <jeremy.compostella@intel.com>
1 parent 1291637 commit b558383

1 file changed

Lines changed: 11 additions & 4 deletions

File tree

‎scripts/authenticode_transplant.py‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -447,10 +447,17 @@ def compute_authenticode_hash(pe_data: bytes, hash_algorithm: Optional[object] =
447447
hash_data = (
448448
pe_data[:checksum_offset] + pe_data[checksum_offset + 0x04 : certificate_table_offset]
449449
)
450-
hash_data += (
451-
pe_data[certificate_table_offset + 0x08 : certificate_virtual_addr]
452-
+ pe_data[certificate_virtual_addr + certificate_size :]
453-
)
450+
if certificate_virtual_addr == 0:
451+
# Unsigned PE: the security data directory is empty (VirtualAddress == 0,
452+
# Size == 0). The naive slice pe_data[0 + 0:] would re-append the entire
453+
# file, producing a wrong digest. Instead, hash only the bytes that follow
454+
# the 8-byte cert-dir data-directory entry.
455+
hash_data += pe_data[certificate_table_offset + 0x08 :]
456+
else:
457+
hash_data += (
458+
pe_data[certificate_table_offset + 0x08 : certificate_virtual_addr]
459+
+ pe_data[certificate_virtual_addr + certificate_size :]
460+
)
454461

455462
# Map cryptography hash algorithm to hashlib
456463
if isinstance(hash_algorithm, crypto_hashes.SHA256):

0 commit comments

Comments
 (0)