injecting custom payload into signed windows executables! title igor glücksmann...
TRANSCRIPT
Injecting custom payload into signed Windows executables!TitleIgor Glü[email protected]
www.avast.com
REcon 2012
Credits
• Robert Žáček, AVAST Software
Overview
• Signed executable files & Windows• Format of signed PE files (Authenticode)• Modification method 1: limited targets• Modification method 2: more targets• Modification method 3: any executables• Fixing the vulnerability• Suggestions to developers
Signatures
Signed executables & Windows
• Subject: executable (PE) files – EXE, DLL, SYS• Both 32- and 64-bit
• Executables with an embedded digital signature• Microsoft Authenticode specification
– Sig: signer name, optional product name, URL, timestamp
The signature asserts that:
• The file originates from a specific software publisher• The file has not been altered since it was signed
• Signing via Windows catalogs
PE files
Format of a PE fileDOS headerDOS header
DOS stubDOS stub
NT headersNT headers
SectionsSections
OverlayOverlay
Section headersSection headers
e_lfanew
Format of a signed PE file
• The signature contains the hash of the “blue” area
DOS headerDOS header
DOS stubDOS stub
NT headersNT headers
SectionsSections
OverlayOverlay
Section headersSection headers
File headerFile header
SignatureSignature
Optional headerOptional header
Data directoriesData directories
SignatureSignature
Security directorySecurity directory
ChecksumChecksum
PE file signature
• Signature is in PKCS#7 format• Uses X.509 v3 certificates• SignedData structure contains the hash of the file• Hash: SHA-1, SHA-256, MD5• Hash covers the whole file excluding the 3
regions• The chain of certificates should end in a trusted
root
• The user-mode API to validate signatures resides in wintrust.dll & imagehlp.dll
Modifying a signed executable
Story of a modification
• Forum at http://reboot.pro/15889– Modify a signed executable without invalidating its digital
signature!
• Appending arbitrary data to a signed file• Aymeric on software – February 22nd, 2009• Including tools to perform the modification easily
PayloadPayload
Appending arbitrary data1. Append the payload2. Go to the security directory table
and adjust the size accordingly3. Update the first DWORD of the
signature accordingly4. Update the checksum
• Hash unchanged sig valid• Payload not in the address space• Steganography?
– We can do better!
DOS headerDOS header
DOS stubDOS stub
NT headersNT headers
SectionsSections
OverlayOverlay
Section headersSection headers
SignatureSignatureSignature
Payload
Signature
Payload
Installers / SFX archives
• Unpacker stub + archive• Stub usually fixed, pre-built• Archive often in overlay
• Finding the archive– Hardcoded offset– Parsing PE structures– Scanning for archive signature
• What if the stub scans for the signature backwards?
DOS headerDOS headerDOS stubDOS stub
NT headersNT headers
SectionsSections
ArchiveArchive
Section headersSection headers
SignatureSignature
Payload archivePayload archive
ZIP archive
• The main header is at the end of the file
• The exact behavior depends on the particular stub, but backward scan is common
• Any interesting signed targets out there?
Local file header 1Local file header 1
File data 1File data 1
Local file header 2Local file header 2
File data 2File data 2
Local file header NLocal file header N
File data NFile data N
Central file header 1Central file header 1
Central file header 2Central file header 2
Central file header NCentral file header N
End headerEnd header
…
…
Adobe Flash installer
• Demo…
• High-profile target, almost everybody has it• Great for social engineering
• A bit harder than just replacing a file in the archive (the installer is actually a downloader, encrypted files)
• Handy: the installer runs elevated• Calls WinVerifyTrust to check its integrity…
Common SFX stubs
• Not just plain SFX, they can also run extracted files
Archive Archiver Behavior
ZIP WinRAR Scans backwards
ZIP WinZIP Hardcoded offset, data in last section
ZIP Xceed Scans backwards
ZIP IZArc Scans backwards
ZIP HP Scans backwards
RAR WinRAR Scans forwards
CAB MS SFX Data in resources
7ZIP 7-Zip Scans forwards
7ZIP 7zsfx Scans forwards in the first 2MB
7zsfx• http://7zsfx.info• Extended 7-Zip SFX stub with added installer features• Used by NVIDIA, Symantec, Comodo, TI, …
• Stub + script + archive (+ signature)– Stub scans forwards, 2MB limit for archive, 1MB for script
• Internationalization features (undocumented)– Searches for a localized script marker first (user locale
based)– If not found, searches for the generic script marker Having a small signed archive, we can append a fake
localized script (or more…)
• Demo…
Real-world use
• Any malicious use?– No evidence about malware so far– But there is a non-malicious use! (to avoid repetitive
signing?)• Microgaming (CAB), Support.com (ZIP), …
• With a huge file set, you can find interesting carriers– ZIP (WinRAR) by Microsoft– ZIP (Custom) by HP, ZIP (Xceed) by Dell– Adobe installers– Acronis driver (x86/x64) with a ZIP in overlay
Method 1 overview
• We can append any data to the file overlay• The content is not mapped into the address space• We can exploit vulnerable application that
process their files backwards, or don’t check the order of sigs
• Limited scope• Design problem, hard to fix
Content beyond the signature• Can there by any content after,
but outside the signature?
• Authenticode spec: yes• Windows XP SP2: no• Windows Vista/7/8… yes
• Restrictions (no sig inside image)
• The sig can be anywhere in the overlay, however
DOS headerDOS header
DOS stubDOS stub
NT headersNT headers
SectionsSections
OverlayOverlay
Section headersSection headers
SignatureSignature
Overlay 2Overlay 2
Moving the signature
• We can append an archive and merge it into the signature
• Now, we can swap positions of those two blocks
• And of course correct the offset
• The hashed part has been split, but the whole “stream” remains the same Signature is still valid
DOS headerDOS header
DOS stubDOS stub
NT headersNT headers
SectionsSections
ArchiveArchive
Section headersSection headers
SignatureSignature
Payload archivePayload archive
Signature
Payload archive
Signature
Payload archive
Common installersInstaller Behavior
NSIS Scans forwards for signature (by aligned blocks), CRC DWORD
Inno Setup Offsets in PE header or resources – but point far into the overlay
Wise (old) Hardcoded offset in data section, pointing to the beginning of overlay
Setup Factory Scans forwards for a signature, only in a small block (img + overlay)
InstallShield Parses DOS/NE header – skips sections to get to the overlay
Real-world use
• We can now replace the extracted archive for many common SFX files (WinRAR, 7-Zip, …)
• Additional installers affected (Nullsoft, Inno)
• Doesn’t work on Windows XP SP2/SP3• Doesn’t work for drivers
• Seems not to be used in the wild, just a few files:– With trailing zeros– Double signed (Borland)– NB10 record with link to PDB (Microsoft)
Method 2 overview
• We can insert any data into the file overlay, provided the signature is moved before the insert point
• The content is not mapped into the address space• We can exploit application that search for their
signatures in the overlay, or use offsets into the middle of the overlay
• Broader scope – many SFX archives and installers• Restricted to Vista+ OS, no drivers• Unless there’s a reason to allow data after the
signature, easy to fix
Getting out of the overlay
• Can we change the real image, not just the overlay?
• The verification code checks that:– The signature doesn’t start before the end of any non-
empty section (non-empty == PointerToRawData != 0)– There is at least one section– Overflows of section sizes etc.– MajorLinkerVersion >= 3 || MinorLinkerVersion >= 5 ?!
• It seems we can’t get into the image because the file’s headers prevent that (by containing non-empty sections)
Inserting a new PE header• Move the whole content,
starting with DOS header’s e_lfanew field
• Move the signature, so that its first DWORD (size) actually is the new e_lfanew field
• Insert custom NT headers• Extend the signature to
cover the whole new block, incl. the e_lfanew field
• Remove checksum and sec. dir. record from the old image
DOS headerDOS header
DOS stubDOS stub
NT headersNT headers
SectionsSections
OverlayOverlay
Section headersSection headers
SignatureSignature
New NT headersNew NT headersNew NT headersNew NT headers
Final layout of the twisted file• The signature now hides:
– e_lfanew field (offset of NT header)– the signature itself– the new NT headers– anything else that may be in that
block
• The rest is not used, it’s there as an overlay to match the hash
• What about our payload?
DOS headerDOS header
DOS stubDOS stub
SectionsSections
OverlayOverlay
Section headersSection headers
SignatureSignature
New NT headersNew NT headers
NT headersNT headers
Including a payload
• Checks we need to pass:– There has to be at least one section– There can’t be any non-empty sections before the signature We can have only empty sections
• So, the payload has to be inside the header• Inconvenient, but there are options
– The header can contain code, unless• the header has the NX bit enabled• the system has DEP enforced for all processes
– We can point imports to a UNC path (WebDAV)
• Demo…
Method 3 overview
• We can twist any signed executable to insert our own NT headers
• No sections – all code has to be in headers– Possible issues with DEP enforcement
• Restricted to Vista+ OS, no drivers• Easy to fix, the files are just “wrong”
Affected
• Faking the data shown in– file’s properties page– UAC prompt– IE-downloaded file warning
• Bypassing program’s self-checking if done on EXEs– Interesting for auto-updates if the product
communication with its servers is not secured properly and can be tampered with• Evilgrade framework (www.infobytesec.com) – DNS attacks
• AppLocker / Software Restriction Policies
AppLocker
• Rules for executable modules, MSIs, scripts• Allow/deny for a user or group, based on:
– Path– Publisher (extracted from the digital signature)
• Any• Specific one• Specific publisher plus specific VersionInfo (product, file,
version)
– File hash• SHA256• Same excluded areas as the Authenticode hash!
Mitigation
• If Authenticode specs could be updated (i.e. all the existing signed executables invalidated)…– Include the final size (file / signature) into the hashed part
• chicken-egg problem, probably solvable (harder to sign though)
– Restrict allowed items in PKCS#7/X.509 part to the bare minimum, check that the sig doesn’t contain anything else• Might be hard – additional “certs” in PKCS#7, optional
attributes, BER encoding, Authenticode extensions (page-hashes)
– Store the signature in a separate file, as a full-file hash• Slightly inconvenient to transfer• Signing via catalogs… doesn’t really help
– File hash (SHA-1) stored in a separate file (signed itself)– Windows doesn’t check catalogs for all operations– Same excluded areas as the Authenticode hash!
Offical hotfix
• MS12-024 – April 10, 2012• Updated imagehlp.dll
1. Reintroduced check – signature ends at the end of file• If not, the Properties page doesn’t even show the sig tab• Fixes methods 2 & 3
2. Added scanner for banned markers within signature• Prevents method 1 for common SFX archives / installers• Again, the signature tab doesn’t show if a marker is present
Forbidden markers
• 50 markers• Cover known vulnerable SFX archives and installers
– ZIP, CAB, 7zsfx, …
• The list is extensible via registry• Some of the markers are just 4 bytes long…
• Signatures of abused stubs don’t validate anymore
• There probably are other vulnerable installers out there, and new ones may appear
For developers
• If you really need to write your own installer…– Remember a signature may be appended to your
archive, and there may be something fishy inside• If looking for signatures, scan forwards, if multiples, use the
1st• Parse PE header and avoid the signature block
– Read DOS header (IMAGE_DOS_HEADER), extract offset of PE header, seek
– Read PE header (IMAGE_NT_HEADERS32/64), extract DataDirectory[ 4 ]
• Use a hardcoded offset• You can put the content inside of the image, but…
• Integrity checking by verifying your own signature via OS API may not be reliable
For developers 2
• If you need to verify other files’ signatures– If using API, make sure the OS is up-to-date– If using own code
• Validate the PE structure properly– No need to be too clever (sorting the excluded regions, …)– The file can’t be too twisted because the existing sign tools wouldn’t
sign it
• Make sure the signature is at the end of the file• Employ additional checks
– Markers?– Size is not a good heuristics
» Most signatures are below 10KB, but you can find some over 100KB
Conclusion
• We cannot really trust that a signed file hasn’t been tampered with
• For some files it matters, for some files it doesn’t
• The major part has been fixed• Be careful not to add another vulnerable
application to the list
References
• Microsoft Portable Executable and Common Object File Format Specificationhttp://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
• Windows Authenticode Portable Executable Signature Formathttp://www.microsoft.com/whdc/winlogo/drvsign/Authenticode_PE.mspx
• Microsoft Security Bulletin MS12-024http://technet.microsoft.com/en-us/security/bulletin/ms12-024
Q&A
• Questions?