TExcelTAD
Home › Reverse Engineering & Binary Analysis › Code Signing and Integrity Checks

Code Signing and Integrity Checks

Everything in this section so far (packing, anti-debugging, obfuscation) tries to hide what a program does. Code signing solves a different and more useful problem: proving who published a program and that nobody changed it since. It doesn't stop reverse engineering (a signed binary is as readable as an unsigned one), but it is what lets an operating system refuse a modified binary, and it is the first thing an analyst checks on an unknown file: signed by whom, valid or broken, and does the signer make sense for this file? This lesson shows what a signature covers, verifies and breaks one on files the examples create, and surveys how each platform uses signatures.

Definitions

  • Code signature: a digital signature over a hash of the program, made with the publisher's private key, plus a certificate chain linking the public key to a trusted certificate authority (see X.509 and PKI in the cryptography course).
  • Authenticode (Windows PE): a PKCS#7 SignedData structure stored in the PE's certificate table (data directory 4, the security directory). The signed hash covers the whole file except the optional header's CheckSum field, the security directory entry itself, and the certificate table, since those must change when the signature is added. Verified with signtool verify /pa or PowerShell Get-AuthenticodeSignature.
  • macOS: codesign writes a signature blob pointed to by LC_CODE_SIGNATURE; its CodeDirectory holds a hash of every page, so the kernel can check pages as they are loaded. Notarization adds Apple's scan and ticket; Gatekeeper enforces both for downloaded apps.
  • Linux: no per-binary signature in the ELF format by default; integrity comes from signed packages (APT's signed Release files, RPM's GPG signatures), kernel module signing, IMA/EVM (file hashes and signatures in extended attributes, checked by the kernel), and Sigstore signatures for containers and artefacts (Supply-Chain Security).
  • Timestamping: a trusted time-stamp authority countersigns the signature, so it stays valid after the certificate expires (but not after it is revoked for compromise).

What a signature covers, modelled in Python

The example builds a synthetic "image" with a header containing a checksum field, a code area, and a slot for the signature, then signs it the way Authenticode does: hash everything except the checksum and the signature slot. It uses an Ed25519 key derived from a fixed seed so the output is stable (a real key is generated randomly and kept in a hardware security module). Then it checks three modifications.

python · try it yourself
import hashlib, struct
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.exceptions import InvalidSignature

key = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(b"lab-only signing seed").digest())
pub = key.public_key()

CHECKSUM = slice(8, 12)              # excluded from the hash (like the PE CheckSum field)
SIG = slice(64, 128)                 # signature slot (like the certificate table)
def build():
    img = bytearray(256)
    img[0:4] = b"TOY1"
    img[128:140] = bytes.fromhex("554889e531c05dc3") + b"\0" * 4     # "code"
    img[140:160] = b"lab tool v1.0\0".ljust(20, b"\0")
    return img

def signed_digest(img):
    h = hashlib.sha256()
    h.update(img[:CHECKSUM.start]); h.update(img[CHECKSUM.stop:SIG.start]); h.update(img[SIG.stop:])
    return h.digest()

def sign(img):
    img[SIG] = key.sign(signed_digest(img))

def verify(img, label):
    try:
        pub.verify(bytes(img[SIG]), signed_digest(img))
        print(f"{label:<38} signature VALID")
    except InvalidSignature:
        print(f"{label:<38} signature INVALID")

img = build(); sign(img)
verify(img, "as published")
a = bytearray(img); struct.pack_into("<I", a, 8, 0xDEADBEEF)
verify(a, "checksum field rewritten (excluded)")
b = bytearray(img); b[133] = 0x90                                   # patch one code byte
verify(b, "one code byte patched")
c = bytearray(img); c[140:153] = b"lab tool v6.6"
verify(c, "version string edited")
as published                           signature VALID
checksum field rewritten (excluded)    signature VALID
one code byte patched                  signature INVALID
version string edited                  signature INVALID

The checksum can change freely because it is excluded, exactly as Windows lets a tool recompute a PE checksum without breaking Authenticode. Any change to code or data breaks the signature. This is also why exclusions matter to attackers: bugs in what a signature format excludes or how a parser reads it have allowed appending data to signed files without invalidating them, and Microsoft later tightened Authenticode verification for that reason (MS13-098, CVE-2013-3900; the stricter check is still opt-in, through the EnableCertPaddingCheck registry value).

Signing and verifying a binary with OpenSSL

The session signs a compiled toy with the lab's RSA key and verifies it with the public key from the lab certificate (both are lab-only sample files with a key derived from a fixed seed). Then it patches one byte of the binary and verifies again. Real code signing wraps the same operation in a format (Authenticode, CMS, Sigstore bundle) with the certificate chain and a timestamp.

bash · try it yourself
printf '#include <stdio.h>\nint main(void){puts("signed lab tool");return 0;}\n' > tool.c
gcc -O2 tool.c -o tool
openssl dgst -sha256 -sign $SAMPLES/pki/lab.test.key -out tool.sig tool
openssl x509 -in $SAMPLES/pki/lab.test.crt -pubkey -noout > lab.pub
echo "signature: $(stat -c %s tool.sig) bytes (RSA 2048)"
openssl dgst -sha256 -verify lab.pub -signature tool.sig tool
cp tool tool-patched
off=$(grep -obUaP 'signed lab tool' tool-patched | cut -d: -f1)
printf 'S' | dd of=tool-patched bs=1 seek="$off" conv=notrunc status=none
./tool-patched
openssl dgst -sha256 -verify lab.pub -signature tool.sig tool-patched 2>/dev/null || echo "exit code: $?"
signature: 256 bytes (RSA 2048)
Verified OK
Signed lab tool
Verification failure
exit code: 1

One changed byte in the string (s → S) and the verification fails. The patched program still runs, of course: a signature only helps if something checks it before running the file, which is the operating system's job (Windows WDAC / Smart App Control, macOS Gatekeeper, Linux IMA appraisal, a package manager, or an update client).

How analysts use signatures in triage, and how abuse is detected

  • Unsigned where the vendor always signs, or signature invalid (the file was modified after signing): strong signals; a patched or trojanised copy of legitimate software looks exactly like this.
  • Valid signature, wrong signer: a "Microsoft" tool signed by an unknown company, or a signer that has nothing to do with the product name in the version resource.
  • Valid signature, bad certificate: certificates stolen from real companies have been used to sign malware (Stuxnet's drivers were signed with two stolen certificates, Realtek's and JMicron's); CAs revoke them, so check revocation and threat-intelligence feeds, not only validity.
  • Signed but vulnerable: attackers load old, legitimately signed drivers with known bugs ("bring your own vulnerable driver"); Microsoft's vulnerable driver blocklist (on by default in recent Windows 11 releases) and WDAC policies address this.

How to sign software properly

  • Sign every release artefact in CI with a key kept in an HSM or a cloud signing service, never on a developer laptop; timestamp every signature.
  • Verify signatures on install and update (an updater that downloads over HTTPS but doesn't check the signature is a classic finding).
  • Publish your signer identity and certificate fingerprints so users and analysts can check them; for containers and open-source artefacts, use Sigstore and record signatures in a transparency log.

Pitfalls

  • A signature says who, not what: signed malware exists. It also says nothing about vulnerabilities.
  • Hashes are not signatures: a SHA-256 published next to a download proves integrity only if the page itself is trustworthy.
  • Build ids and checksums (ELF build id, PE CheckSum) are not security features; anyone can recompute them.
  • Expired vs revoked: a timestamped signature from an expired certificate is fine; any signature from a certificate revoked for key compromise is not.

Practice

1. Why does Authenticode exclude the CheckSum field from the signed hash?

Adding the certificate table changes the file, and the checksum is recomputed afterwards; if it were covered, signing would invalidate itself.

2. A file claims to be a common vendor's utility; its signature is valid, and the signer is "Lab Example Trading Ltd". What do you do?

Treat it as suspicious: the signer doesn't match the product. Compare with the vendor's genuine file (hash, signer), check the certificate's issue date and revocation status, and analyse it.

3. In the Python model, which other field would a real format also have to exclude, and why?

The pointer and size of the signature itself (the PE security directory entry), because they are written after signing.

Test yourself

What does a valid code signature prove?

  1. The program is not malware
  2. Who signed it, and that it hasn't changed since signing
  3. That the code has no bugs
  4. That the program is packed

Where is an Authenticode signature stored in a PE file?

  1. In .text
  2. In the certificate table pointed to by data directory 4 (the security directory)
  3. In the DOS stub
  4. In the import table

The patched tool still ran after its signature broke. Why?

  1. The signature was wrong
  2. Nothing checked the signature before running it; enforcement is the job of the OS or installer
  3. Linux ignores bytes in strings
  4. RSA is weak

Which situation should make an analyst most suspicious?

  1. A Microsoft tool signed by Microsoft
  2. An unsigned build of your own toy
  3. A copy of a well-known vendor's tool signed by an unrelated company
  4. A timestamped signature from an expired certificate