
What Is a PE File Overlay? A Complete Guide to Detecting and Analyzing Hidden Data in Windows Executables
Imagine examining a Windows executable with a PE analysis tool.
You inspect the DOS header, review the PE header, examine the imported functions, calculate section entropy, and identify the program’s entry point.

Everything appears relatively normal.
But then you notice something interesting.
The final PE section ends at file offset 0x28000, while the executable itself is considerably larger.
What occupies the remaining space?
Is it a digital signature? An embedded archive? Configuration data? An installer payload? Unused padding? Or something that deserves further investigation?
This is where PE file overlay analysis becomes particularly useful.
A Portable Executable file can contain information beyond the raw data of its declared sections. Depending on the executable, these additional bytes may serve legitimate purposes or contain information relevant to a cybersecurity investigation.
Understanding how to identify and interpret this data is a valuable skill for software developers, reverse engineers, digital forensic investigators and malware researchers.
In this guide, we will explore what a PE file overlay is, how it relates to the Windows executable format, how to calculate its location, and how to distinguish certificate-related data from other trailing bytes.
We will also build a small, read-only Python PE overlay analyzer.
You do not need to execute the files you investigate.
Let’s look beyond the last section.
1. What Is a PE File?
PE stands for Portable Executable.
It is the file format used by Windows for several types of executable images, including:
- EXE executable programs.
- DLL dynamic-link libraries.
- SYS device drivers.
- SCR screensaver executables.
- Certain EFI applications.
The PE format contains information that helps the operating system load and prepare an executable image.
A typical PE file includes several important structures.
| Structure | Purpose |
|---|---|
| DOS Header | Contains the traditional MZ signature and location of the PE header |
| DOS Stub | Legacy DOS-compatible stub or related data |
| PE Signature | Identifies the Portable Executable format |
| COFF File Header | Describes architecture and general file characteristics |
| Optional Header | Contains information required for loading executable images |
| Data Directories | Identify important structures such as imports and certificates |
| Section Table | Describes the executable’s sections |
| Section Raw Data | Contains section contents stored on disk |
Common section names include .text, .data, .rdata, .rsrc, and .reloc.
These names are conventions rather than strict guarantees of their contents.
For example, a section named .text commonly contains executable code, but a section name alone does not determine how its contents are used.
The PE format is more flexible than it might initially appear.
That flexibility is one of the reasons executable analysis remains such an interesting subject.
2. What Is a PE File Overlay?
A PE file overlay commonly refers to data located after the raw data of the executable’s last section on disk.
Consider this simplified file layout:
+---------------------------------+
| DOS Header and DOS Stub |
+---------------------------------+
| PE Signature |
+---------------------------------+
| COFF Header |
+---------------------------------+
| Optional Header |
+---------------------------------+
| Section Table |
+---------------------------------+
| .text Section |
+---------------------------------+
| .rdata Section |
+---------------------------------+
| .data Section |
+---------------------------------+
| .rsrc Section |
+---------------------------------+
| End of Declared Section Data |
+---------------------------------+
| Additional Data |
| |
| Possible Overlay |
+---------------------------------+
| End of File |
+---------------------------------+
The additional data is physically present inside the file, but it is not necessarily part of an ordinary PE section.
Different analysis tools use slightly different definitions when reporting overlays.
Some calculate everything following the last section’s raw data. Others exclude recognized structures, particularly the attribute certificate table.
Throughout this article, we will distinguish between:
- Trailing region: All bytes after the calculated end of the headers and section raw data.
- Declared certificate-table region: Bytes identified by the PE Security Directory.
- Other trailing data: Remaining bytes not covered by the declared certificate-table region.
This terminology helps avoid treating every additional byte as unexplained or suspicious.
3. Is a PE Overlay an Official PE Section?
No.
An overlay is not a section described by an additional entry in the PE section table.
Each ordinary PE section has an associated section header containing information such as:
- Section name.
- Virtual address.
- Virtual size.
- Raw data offset.
- Raw data size.
- Section characteristics.
Overlay data, as commonly defined, does not have its own corresponding section header.
This is one of the most important distinctions in PE analysis.
| PE Section | PE Overlay |
|---|---|
| Described in the section table | Not an ordinary section-table entry |
| Has defined section characteristics | Does not have ordinary section characteristics |
| Contains declared raw or virtual data | Contains additional file data |
| May contribute to the mapped executable image | Not automatically mapped as an ordinary section |
| Often referenced by executable structures | May be accessed through separate application logic |
An application can still use additional file data by deliberately reading its executable file or accessing related file structures.
However, the mere presence of that data does not mean it becomes executable code when Windows loads the image.
4. Why Do PE Files Contain Overlays?
There are several legitimate reasons why a Windows executable might contain additional data.
Self-extracting archives
A self-extracting archive may combine an executable extraction program with archived files.
The executable component provides the interface and extraction functionality, while additional file data contains the archive or associated information.
The complete package can be distributed as a single executable.
Software installers
Installation programs may contain compressed application files, installation scripts, configuration information, or other resources beyond their ordinary section data.
The installer can retrieve the necessary information when performing an authorized installation.
Application packaging
Some applications package configuration files, runtime components, media, or other resources into a single distributable executable.
Depending on the packaging format, some of this information may reside outside ordinary PE sections.
Digital signatures
Digitally signed Windows executables may contain an attribute certificate table.
This table is commonly located beyond ordinary section data and requires special treatment during overlay analysis.
We will examine this structure in more detail shortly.
Debugging and development information
Certain executables may contain additional information associated with their build or debugging process.
Not every byte outside section data is necessarily an unidentified payload.
Padding and alignment
Additional bytes may exist for alignment, packaging, or other implementation-specific reasons.
Malware-related data
During defensive malware analysis, researchers may encounter executables containing additional encoded, encrypted, compressed or otherwise packaged data.
Such observations can be relevant to an investigation.
However, legitimate installers and application packages can exhibit similar characteristics.
A PE file overlay is a structural observation, not a malware verdict.
5. Understanding File Offsets, RVAs and Virtual Addresses
Before calculating an overlay, we need to understand three important concepts.
File offset
A file offset represents a byte position inside a file stored on disk.
For example:
File offset: 0x400
This identifies a position 1,024 bytes from the beginning of the file.
Relative Virtual Address — RVA
An RVA represents an address relative to the executable image’s base address when mapped into memory.
For example:
RVA: 0x1000
This represents a position relative to the image base.
Virtual Address — VA
A virtual address represents an address in the process’s virtual address space.
A simplified relationship is:
VA = ImageBase + RVA
For an image base of 0x140000000 and an RVA of 0x1000:
VA = 0x140001000
Actual runtime addresses may differ due to relocation and address space layout randomization.
Why this matters for overlays
A PE overlay exists as bytes within the physical file.
Calculating its location requires file offsets and raw data sizes, not section RVAs or virtual sizes.
Using virtual addresses to calculate a physical file boundary can produce incorrect results.
This distinction is especially important when analyzing malformed or unusually structured executables.
6. How to Calculate a PE File Overlay
Two fields in each section header are particularly useful.
PointerToRawData
This field identifies the section’s raw data location inside the file.
SizeOfRawData
This field describes the declared size of that raw data.
The end of a section’s raw data can be calculated as:
SectionRawEnd = PointerToRawData + SizeOfRawData
To determine the end of the declared section data, examine all relevant section headers and select the highest valid raw-data end.
For a conservative trailing-region calculation, also consider the declared header size.
TrailingRegionStart = max(
SizeOfHeaders,
ValidSectionRawEnds
)
Then:
TrailingRegionSize = FileSize - TrailingRegionStart
If the calculated boundary equals the file size, there is no trailing region under this definition.
If the calculated boundary exceeds the file size, the executable may be truncated, malformed, or otherwise inconsistent. Do not calculate a negative overlay size or assume that the file is normal.
Practical example
Consider this hypothetical PE file:
| Section | PointerToRawData | SizeOfRawData | Raw Data End |
|---|---|---|---|
| .text | 0x0400 | 0x6000 | 0x6400 |
| .rdata | 0x6400 | 0x2000 | 0x8400 |
| .data | 0x8400 | 0x1000 | 0x9400 |
| .rsrc | 0x9400 | 0x3000 | 0xC400 |
Assume the file size is:
0x10000
The highest section raw-data end is:
0xC400
Assuming the declared header region ends earlier, the trailing region begins at 0xC400.
Its size is:
0x10000 - 0xC400 = 0x3C00
That equals 15,360 bytes.
We have established that 15,360 bytes exist beyond the declared section-data boundary.
We have not yet established what those bytes represent.
7. Why You Should Examine Every Section Header
It may be tempting to calculate the overlay using only the final section-table entry.
However, the final entry in the table is not necessarily the section with the highest raw-data end.
Unusual, malformed or deliberately constructed executable files may contain sections whose physical ordering differs from their section-table ordering.
For example:
| Section-table entry | Raw offset | Raw size |
|---|---|---|
| First | 0x400 | 0x1000 |
| Second | 0x5000 | 0x2000 |
| Third | 0x1400 | 0x1000 |
The third entry appears last in the table, but the second entry extends furthest into the file.
Calculating the boundary from the third entry would incorrectly classify some declared section data as overlay.
A more reliable approach is to examine all applicable section entries.
You should also check for:
- Raw data ranges extending beyond the file.
- Overlapping section ranges.
- Unexpected zero raw-data pointers.
- Inconsistent header sizes.
- Truncated section headers.
- Unusual alignment.
These observations should be recorded rather than silently ignored.
An overlay calculation is only as reliable as the structural information on which it depends.
8. The PE Security Directory: An Important Exception
The Optional Header of a PE file contains an array of data directories.
These directories identify important executable structures, including imports, exports, resources, relocations and security-related data.
Most data-directory addresses are expressed as RVAs.
However, the Security Directory is an important exception.
The VirtualAddress member of the IMAGE_DIRECTORY_ENTRY_SECURITY entry contains a file offset, not an RVA.
This may appear counterintuitive because the field is named VirtualAddress.
In this particular directory, the field identifies the physical location of the attribute certificate table inside the file.
The accompanying Size member describes its declared size.
A simplified example:
Security Directory:
VirtualAddress = 0xE000
Size = 0x1000
The declared certificate-table interval is:
Start: 0xE000
End: 0xF000
The end offset is exclusive.
This distinction is essential when developing PE analysis tools.
A parser that incorrectly converts this value from an RVA to a file offset may inspect the wrong location.
9. Digital Signatures Are Not Automatically Suspicious Overlays
Imagine analyzing an executable whose sections end at:
0xC400
The complete file ends at:
0x10000
The Security Directory identifies a certificate-table interval:
0xE000 to 0xF000
The complete trailing region contains:
0x3C00 bytes
The declared certificate table occupies:
0x1000 bytes
The remaining trailing bytes total:
0x3C00 - 0x1000 = 0x2C00
This gives us a more informative picture.
| Region | Start | End | Size |
|---|---|---|---|
| Other trailing data | 0xC400 | 0xE000 | 7,168 bytes |
| Declared certificate table | 0xE000 | 0xF000 | 4,096 bytes |
| Other trailing data | 0xF000 | 0x10000 | 4,096 bytes |
This is an illustrative layout, not a claim that every such certificate placement represents a validly signed executable.
The important lesson is that the declared certificate region and other trailing bytes should be evaluated separately.
Certificate presence does not establish signature validity
A Security Directory entry does not prove that:
- Its contents form a valid certificate table.
- The Authenticode signature is valid.
- The executable has not been modified.
- The signer is trusted.
- The executable is safe.
Signature verification is a separate operation.
Our Python analyzer will identify the declared certificate-table interval, but it will not perform cryptographic Authenticode verification.
10. How to Check an Executable’s Digital Signature on Windows
Windows PowerShell provides a convenient way to inspect Authenticode signature information.
For example:
Get-AuthenticodeSignature `
-FilePath "C:\Analysis\sample.exe" |
Format-List
Replace the path with the executable you want to examine.
To display selected information:
Get-AuthenticodeSignature `
-FilePath "C:\Analysis\sample.exe" |
Select-Object Status,
StatusMessage,
SignerCertificate
Possible status values include Valid, NotSigned, and other verification results.
Interpret these results within the context of Windows trust policies, certificate validation and available verification information.
Some Windows files may be signed through a catalog rather than an embedded certificate table.
Consequently, the absence of an embedded certificate-table region does not necessarily mean that Windows cannot establish a signature through another supported mechanism.
Remember that signature verification answers a different question from overlay detection.
11. What Can a PE Overlay Contain?
Once an additional data region has been identified, the next question is what that region contains.
Possible contents include:
| Content | Possible interpretation |
|---|---|
| Text strings | Configuration, documentation or metadata |
| ZIP archive signatures | Possible embedded archive |
| Cabinet archive signatures | Possible installation-related content |
| Image signatures | Possible bundled graphical resources |
| Repeated zero bytes | Possible padding or unused space |
| High-entropy bytes | Possible compression, encryption or other complex data |
| Executable-like headers | Possible embedded executable data or coincidental patterns |
| Structured binary records | Application-specific information |
These observations are preliminary clues.
For example, finding the bytes associated with a ZIP file signature does not prove that a complete, valid ZIP archive exists at that location.
Additional structural validation would be necessary.
Likewise, finding an MZ signature does not establish that the remaining data forms a complete Portable Executable file.
Many byte sequences occur naturally or coincidentally inside larger binary files.
12. Understanding PE Overlay Entropy
Entropy is a mathematical measure that describes the distribution of values within a dataset.
In executable analysis, Shannon entropy is often calculated over the bytes of a file or section.
For byte-oriented Shannon entropy, the theoretical range is from 0 to 8 bits per byte.
A sequence consisting entirely of identical bytes has an entropy of zero.
A sufficiently large dataset with all byte values occurring at approximately equal frequencies approaches eight bits per byte.
The formula is:
H = -sum(p(x) × log2(p(x)))
Where p(x) represents the observed probability of a particular byte value.
Why entropy can help
Entropy provides a useful statistical characteristic of an overlay.
| Data characteristics | Possible entropy behavior |
|---|---|
| Repeated padding bytes | Very low |
| Ordinary text | Often relatively low or moderate |
| Mixed application data | Variable |
| Compressed data | Often high |
| Encrypted data | Often high |
| Random-like data | Often high |
These are general tendencies, not reliable classification rules.
A high-entropy overlay is not automatically malicious.
Legitimate compressed installers can contain large amounts of high-entropy data.
A low-entropy overlay is not automatically harmless either.
The size of the region also matters. Entropy calculated over a very small dataset may be misleading because there are too few observations to characterize the underlying distribution.
For more information about entropy, see our existing guide: What Is File Entropy?.
13. Why Overlay Size Alone Is Not Enough
An executable containing a large overlay may initially appear unusual.
But size requires context.
Consider three hypothetical examples.
Example A: Ordinary desktop utility
- File size: 500 KB.
- Trailing data: 2 KB.
- Declared certificate data: present.
The additional data may be associated with signing or packaging.
Example B: Software installer
- File size: 200 MB.
- Trailing data: 180 MB.
- Entropy: relatively high.
The size may be consistent with a compressed installation package.
Example C: Unknown small executable
- File size: 100 KB.
- Trailing data: 70 KB.
- Format: unidentified.
This may justify further analysis, particularly if the additional data does not match the application’s documented purpose.
However, none of these hypothetical observations establishes malicious behavior.
Overlay size becomes more useful when combined with file type, section information, certificate verification, provenance and other evidence.
14. The PEFile Overlay Evidence Model
To make overlay analysis more systematic, we suggest using a five-stage investigation model.
Stage 1: Location
Determine where the trailing region begins.
Record:
- Complete file size.
- Declared header size.
- Highest valid section raw-data end.
- Trailing-region start.
- Trailing-region size.
At this stage, focus on establishing physical boundaries.
Stage 2: Structure
Determine whether known PE structures occupy any part of the trailing region.
Review:
- Security Directory location.
- Declared certificate-table size.
- Whether the declared region is within file boundaries.
- Whether it overlaps section data.
- Relevant structural warnings.
A correctly bounded region is not necessarily a valid certificate table, but it gives you a starting point.
Stage 3: Content
Inspect descriptive characteristics of the remaining data.
Useful measurements include:
- Region size.
- SHA-256 hash.
- Shannon entropy.
- Leading byte sequences.
- Recognizable file signatures.
- Repeated byte patterns.
These observations describe content without assuming its purpose.
Stage 4: Context
Consider what the executable is expected to do.
Is it an installer? A signed Windows utility? A driver? A self-contained application? A software development artifact?
Is its origin known?
Do similar legitimate files contain comparable structures?
Stage 5: Conclusion
Document what the evidence establishes.
For example:
The executable contains 15,360 bytes after its declared section data. Of these, 4,096 bytes overlap its declared Security Directory interval. The remaining bytes have an unidentified format and require further investigation.
This conclusion is more useful than simply reporting that an overlay exists.
It distinguishes established observations from unanswered questions.
15. How to Analyze a PE Overlay Using Python
Python provides a convenient environment for building small executable-analysis utilities.
One useful library is pefile, which supports parsing the Windows Portable Executable format.
The Python pefile package is a separate project from the PEFile.net command-line utility.
In this tutorial, we will use Python’s pefile library to inspect the executable structure and implement our own conservative trailing-region calculation.
Our utility will be called PEFile Overlay Inspector.
It will:
- Open a PE file without executing it.
- Inspect the declared headers and sections.
- Calculate the highest declared raw-data boundary.
- Detect a trailing region.
- Inspect the Security Directory.
- Separate its declared certificate-table interval from other trailing bytes.
- Calculate SHA-256 hashes.
- Calculate Shannon entropy.
- Display leading bytes.
- Report structural warnings.
- Optionally save a JSON report.
The utility will not modify the analyzed executable.
It will not load executable code, run the file, extract or execute embedded content, or determine whether the file is malware.
16. Preparing the Python Environment
You will need Python 3.10 or newer.
Create a project directory:
mkdir pefile-overlay-inspector
cd pefile-overlay-inspector
Create a virtual environment:
python -m venv .venv
On Windows PowerShell:
.\.venv\Scripts\Activate.ps1
On Linux or macOS:
source .venv/bin/activate
Install the Python pefile package:
python -m pip install pefile
You can find additional information about the library in its official documentation.
17. Complete PEFile Overlay Inspector Source Code
Create a file named:
pe_overlay_inspector.py
Copy the following implementation.
import argparse
import hashlib
import json
import math
import sys
from collections import Counter
from pathlib import Path
import pefile
MAX_FILE_SIZE = 256 * 1024 * 1024
SECURITY_DIRECTORY_INDEX = 4
def sha256(data):
"""Calculate the SHA-256 hash of a byte sequence."""
return hashlib.sha256(data).hexdigest()
def calculate_entropy(data):
"""Calculate byte-oriented Shannon entropy."""
if not data:
return 0.0
counts = Counter(data)
total = len(data)
return -sum(
(count / total) *
math.log2(count / total)
for count in counts.values()
)
def identify_leading_bytes(data):
"""Identify possible formats from leading bytes."""
signatures = (
(b"PK\x03\x04", "Possible ZIP archive"),
(b"PK\x05\x06", "Possible empty ZIP archive"),
(b"MSCF", "Possible Cabinet archive"),
(b"MZ", "Possible DOS/PE-related header"),
(
b"\x89PNG\r\n\x1a\n",
"Possible PNG image"
),
(b"%PDF-", "Possible PDF document"),
(
b"\x1f\x8b",
"Possible GZIP data"
),
(
b"7z\xbc\xaf\x27\x1c",
"Possible 7-Zip archive"
),
)
for signature, description in signatures:
if data[:len(signature)] == signature:
return description
if data and not any(data):
return "All-zero data"
return "Unidentified leading bytes"
def summarize_region(raw, start, end, label):
"""Return descriptive information about a region."""
data = memoryview(raw)[start:end]
return {
"label": label,
"start_offset": start,
"end_offset_exclusive": end,
"size": len(data),
"sha256": sha256(data),
"entropy": round(
calculate_entropy(data), 4
),
"first_32_bytes_hex": data[:32].hex(" "),
"leading_byte_hint": (
identify_leading_bytes(data)
),
}
def get_section_name(section):
return (
section.Name
.rstrip(b"\x00")
.decode("ascii", errors="replace")
)
def read_file(path):
"""Read a bounded amount of data."""
with path.open("rb") as source:
raw = source.read(MAX_FILE_SIZE + 1)
if len(raw) > MAX_FILE_SIZE:
raise ValueError(
"File exceeds the 256 MiB analysis limit."
)
if not raw:
raise ValueError("The file is empty.")
return raw
def calculate_image_boundary(pe, file_size):
"""Calculate a conservative raw-data boundary."""
warnings = []
sections = []
valid_ranges = []
boundary_reliable = True
header_end = int(
pe.OPTIONAL_HEADER.SizeOfHeaders
)
declared_sections = int(
pe.FILE_HEADER.NumberOfSections
)
if declared_sections != len(pe.sections):
warnings.append(
"Declared and parsed section counts differ."
)
boundary_reliable = False
if header_end <= 0 or header_end > file_size:
warnings.append(
"Declared header size is outside "
"the expected file range."
)
boundary_reliable = False
boundary = min(
max(header_end, 0),
file_size
)
for section in pe.sections:
name = get_section_name(section)
start = int(section.PointerToRawData)
size = int(section.SizeOfRawData)
end = start + size
valid = True
if size:
if start == 0:
valid = False
warnings.append(
f"{name}: non-empty section "
"has a zero raw-data pointer."
)
if start > file_size or end > file_size:
valid = False
warnings.append(
f"{name}: declared raw-data "
"range exceeds file boundaries."
)
if valid:
valid_ranges.append(
(start, end, name)
)
boundary = max(boundary, end)
else:
boundary_reliable = False
sections.append({
"name": name,
"raw_offset": start,
"raw_size": size,
"raw_end_exclusive": end,
"valid_raw_range": valid,
})
valid_ranges.sort()
highest_end = 0
highest_name = None
for start, end, name in valid_ranges:
if start < header_end:
warnings.append(
f"{name}: raw data overlaps "
"the declared header region."
)
boundary_reliable = False
if start < highest_end:
warnings.append(
f"{name}: raw data overlaps "
f"section {highest_name}."
)
boundary_reliable = False
if end > highest_end:
highest_end = end
highest_name = name
return {
"boundary": boundary,
"boundary_reliable": boundary_reliable,
"declared_header_size": header_end,
"sections": sections,
"warnings": warnings,
}
def get_certificate_interval(pe, file_size):
"""Read the Security Directory as a file interval."""
directories = pe.OPTIONAL_HEADER.DATA_DIRECTORY
result = {
"present": False,
"range_valid": False,
"offset": None,
"size": 0,
"end_offset_exclusive": None,
"warnings": [],
}
if len(directories) <= SECURITY_DIRECTORY_INDEX:
return result
directory = directories[
SECURITY_DIRECTORY_INDEX
]
offset = int(directory.VirtualAddress)
size = int(directory.Size)
result["offset"] = offset
result["size"] = size
result["present"] = bool(offset or size)
if not result["present"]:
return result
end = offset + size
result["end_offset_exclusive"] = end
if offset <= 0 or size < 8:
result["warnings"].append(
"Security Directory has an "
"unexpected offset or size."
)
return result
if end > file_size:
result["warnings"].append(
"Declared certificate-table range "
"extends beyond the file."
)
return result
result["range_valid"] = True
if offset % 8 != 0:
result["warnings"].append(
"Certificate-table offset is not "
"aligned to an 8-byte boundary."
)
if size % 8 != 0:
result["warnings"].append(
"Declared certificate-table size "
"is not a multiple of 8 bytes."
)
return result
def analyze_trailing_regions(
raw,
boundary,
certificate,
):
"""Partition trailing bytes using declared intervals."""
file_size = len(raw)
regions = []
if boundary >= file_size:
return regions
if not certificate["range_valid"]:
return [
summarize_region(
raw,
boundary,
file_size,
"Unclassified trailing data"
)
]
cert_start = certificate["offset"]
cert_end = certificate["end_offset_exclusive"]
overlap_start = max(boundary, cert_start)
overlap_end = min(file_size, cert_end)
if overlap_start >= overlap_end:
return [
summarize_region(
raw,
boundary,
file_size,
"Other trailing data"
)
]
if boundary < overlap_start:
regions.append(
summarize_region(
raw,
boundary,
overlap_start,
"Other trailing data"
)
)
regions.append(
summarize_region(
raw,
overlap_start,
overlap_end,
"Declared certificate-table overlap"
)
)
if overlap_end < file_size:
regions.append(
summarize_region(
raw,
overlap_end,
file_size,
"Other trailing data"
)
)
return regions
def analyze_file(path):
raw = read_file(path)
pe = pefile.PE(
data=raw,
fast_load=True
)
try:
layout = calculate_image_boundary(
pe,
len(raw)
)
certificate = get_certificate_interval(
pe,
len(raw)
)
boundary = layout["boundary"]
warnings = (
layout["warnings"]
+ certificate["warnings"]
+ pe.get_warnings()
)
if (
certificate["range_valid"]
and certificate["offset"] < boundary
):
warnings.append(
"Declared certificate-table interval "
"begins inside the calculated "
"header/section region."
)
regions = []
if layout["boundary_reliable"]:
regions = analyze_trailing_regions(
raw,
boundary,
certificate,
)
trailing_size = len(raw) - boundary
else:
trailing_size = None
warnings.append(
"Trailing-region classification "
"withheld because the calculated "
"boundary is unreliable."
)
return {
"tool": "PEFile Overlay Inspector",
"file": path.name,
"file_size": len(raw),
"file_sha256": sha256(raw),
"machine": hex(
pe.FILE_HEADER.Machine
),
"optional_header_magic": hex(
pe.OPTIONAL_HEADER.Magic
),
"declared_header_size": (
layout["declared_header_size"]
),
"section_count": len(
layout["sections"]
),
"sections": layout["sections"],
"candidate_raw_data_end": boundary,
"boundary_reliable": (
layout["boundary_reliable"]
),
"trailing_region_size": trailing_size,
"security_directory": certificate,
"trailing_regions": regions,
"warnings": warnings,
"limitations": [
"Read-only structural inspection.",
"Leading byte matches are heuristic.",
"Certificate bounds do not establish "
"certificate validity.",
"Authenticode signatures are not "
"cryptographically verified.",
"The analyzer does not identify every "
"possible non-section PE structure.",
"No malware verdict is produced.",
],
}
finally:
pe.close()
def display_report(report):
print("=" * 65)
print("PEFile Overlay Inspector")
print("Read-only Portable Executable analysis")
print("=" * 65)
print("File:", report["file"])
print("File size:", report["file_size"], "bytes")
print("SHA-256:", report["file_sha256"])
print("Machine:", report["machine"])
print(
"Optional Header Magic:",
report["optional_header_magic"]
)
print("\nSECTIONS")
for section in report["sections"]:
print(
f" {section['name']!r:12} "
f"Offset={section['raw_offset']:#x} "
f"Size={section['raw_size']:#x} "
f"End={section['raw_end_exclusive']:#x}"
)
print("\nTRAILING REGION")
print(
"Candidate boundary:",
hex(report["candidate_raw_data_end"])
)
print(
"Boundary reliable:",
report["boundary_reliable"]
)
print(
"Trailing size:",
report["trailing_region_size"]
)
certificate = report["security_directory"]
print("\nSECURITY DIRECTORY")
print("Declared:", certificate["present"])
print(
"Range within file:",
certificate["range_valid"]
)
if certificate["offset"] is not None:
print(
"Offset:",
hex(certificate["offset"])
)
print("Size:", certificate["size"])
print("\nTRAILING DATA REGIONS")
if not report["trailing_regions"]:
print("No regions reported.")
for region in report["trailing_regions"]:
print("-" * 65)
print("Type:", region["label"])
print(
"Start:",
hex(region["start_offset"])
)
print(
"End:",
hex(region["end_offset_exclusive"])
)
print("Size:", region["size"], "bytes")
print("Entropy:", region["entropy"])
print("SHA-256:", region["sha256"])
print(
"Leading bytes:",
region["first_32_bytes_hex"]
)
print(
"Content hint:",
region["leading_byte_hint"]
)
print("\nSTRUCTURAL WARNINGS")
if not report["warnings"]:
print("No warnings generated.")
for warning in report["warnings"]:
print("-", repr(warning))
print("\nLIMITATIONS")
for limitation in report["limitations"]:
print("-", limitation)
def main():
parser = argparse.ArgumentParser(
description=(
"Inspect trailing data in "
"Windows Portable Executable files."
)
)
parser.add_argument(
"file",
help="Path to a PE file."
)
parser.add_argument(
"--json",
metavar="FILE",
help="Save report to a new JSON file."
)
args = parser.parse_args()
try:
report = analyze_file(
Path(args.file)
)
display_report(report)
if args.json:
output = Path(args.json)
with output.open(
"x",
encoding="utf-8"
) as destination:
json.dump(
report,
destination,
indent=2,
ensure_ascii=True
)
print("\nReport saved:", output)
except pefile.PEFormatError as exc:
print(
"PE parsing failed:",
str(exc),
file=sys.stderr
)
return 1
except FileExistsError:
print(
"Report already exists. "
"Choose another filename.",
file=sys.stderr
)
return 1
except (OSError, ValueError) as exc:
print(
"Analysis failed:",
str(exc),
file=sys.stderr
)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
18. Running PEFile Overlay Inspector
To analyze an executable:
python pe_overlay_inspector.py `
"C:\Analysis\sample.exe"
To save a JSON report:
python pe_overlay_inspector.py `
"C:\Analysis\sample.exe" `
--json sample_report.json
On Linux or macOS:
python pe_overlay_inspector.py sample.exe \
--json sample_report.json
The analyzed file is opened for reading.
The JSON report is created separately, and the utility refuses to overwrite an existing report.
The implementation deliberately limits input files to 256 MiB because it reads the complete executable into memory.
Large installers may exceed this limit. A more advanced implementation could use memory-mapped files or streaming analysis.
19. Understanding the Analyzer’s Output
Consider this simplified, illustrative output:
PEFile Overlay Inspector
File: example.exe
File size: 65536 bytes
SECTIONS
.text Offset=0x400
Size=0x6000
End=0x6400
.rdata Offset=0x6400
Size=0x2000
End=0x8400
.data Offset=0x8400
Size=0x1000
End=0x9400
.rsrc Offset=0x9400
Size=0x3000
End=0xc400
TRAILING REGION
Candidate boundary: 0xc400
Boundary reliable: True
Trailing size: 15360
SECURITY DIRECTORY
Declared: True
Range within file: True
Offset: 0xe000
Size: 4096
TRAILING DATA REGIONS
Type: Other trailing data
Start: 0xc400
End: 0xe000
Size: 7168 bytes
Type: Declared certificate-table overlap
Start: 0xe000
End: 0xf000
Size: 4096 bytes
Type: Other trailing data
Start: 0xf000
End: 0x10000
Size: 4096 bytes
The important information is that the trailing region has been divided into meaningful intervals.
We can now investigate the non-certificate regions separately.
The analyzer also reports hashes and entropy values for individual regions, allowing us to compare their content characteristics.
This can be considerably more useful than calculating one entropy value across the entire trailing region.
What does Boundary reliable mean?
In this utility, a reliable boundary means the implemented structural checks did not encounter certain conditions that would make the boundary calculation ambiguous.
It does not mean the file has passed every possible PE-format validation.
PE files can contain additional structures and unusual relationships that this educational implementation does not inspect.
What does Range within file mean?
It means the declared certificate-table interval satisfies the basic bounds checks implemented by the utility.
It does not mean that the certificate table contains valid certificate records or a valid Authenticode signature.
20. Conduct Your Own PE Overlay Research Experiment
One of the best ways to understand overlays is to compare different types of legitimate Windows executables.
You do not need malware samples to begin learning.
Create a dedicated analysis directory and select several files from trusted sources.
Possible examples include:
- A small executable you compiled yourself.
- A digitally signed Windows application.
- A legitimate software installer.
- A self-contained application.
- A trusted self-extracting archive.
- A DLL from one of your own software projects.
Do not execute files simply to determine whether they contain an overlay.
Step 1: Record file identity
Calculate each file’s SHA-256 hash.
On Windows:
Get-FileHash `
-Algorithm SHA256 `
-Path "C:\Analysis\sample.exe"
This identifies the exact file being examined.
Step 2: Run the analyzer
Generate a separate JSON report for each file.
python pe_overlay_inspector.py `
"C:\Analysis\sample.exe" `
--json sample_report.json
Step 3: Verify available signatures
Use Windows Authenticode verification where appropriate.
Get-AuthenticodeSignature `
-FilePath "C:\Analysis\sample.exe"
Record the result separately from the overlay observations.
Step 4: Compare the findings
Use a table like the following:
| File type | File size | Trailing bytes | Certificate region | Other trailing bytes | Observations |
|---|---|---|---|---|---|
| Self-compiled EXE | |||||
| Signed application | |||||
| Installer | |||||
| Self-contained application | |||||
| Self-extracting archive | |||||
| DLL |
You may discover that legitimate executables exhibit substantially different file layouts.
Some may contain no trailing region. Others may include certificate data or large amounts of application-specific information.
Step 5: Document what you actually learned
A good analysis report should distinguish observations from explanations.
For example:
The installer contains a substantial trailing region with relatively high entropy. Its expected role as an installation package provides a plausible explanation, but the content format was not independently validated.
This is a more defensible conclusion than labeling the file suspicious based on entropy alone.
21. PE Overlay Analysis and Malware Research
Overlay analysis is one component of static malware analysis.
Static analysis examines a file without executing its intended program logic.
When analyzing an unknown executable, researchers may consider:
- File hashes.
- PE header consistency.
- Imported functions.
- Section characteristics.
- Section entropy.
- Entry-point location.
- Digital signature information.
- Embedded resources.
- Printable strings.
- Additional file data.
Overlay observations can help identify regions requiring deeper investigation.
However, malware classification should be based on multiple sources of evidence.
A legitimate installer may contain high-entropy additional data. A malicious executable may contain no overlay at all.
Overlay presence is neither a necessary nor a sufficient condition for malware.
Treat unknown files carefully
Even static analysis tools can contain vulnerabilities in their file parsers.
When investigating files from untrusted sources:
- Keep your analysis tools updated.
- Avoid unnecessary administrative privileges.
- Use an isolated analysis environment where appropriate.
- Do not execute unknown samples on your everyday computer.
- Protect confidential file contents and reports.
Do not upload proprietary executables to public analysis services without understanding their data-sharing policies and obtaining appropriate authorization.
22. Is Overlay Data Loaded Into Memory?
The Windows loader maps executable images according to their defined structures and section information.
Trailing bytes are not automatically mapped as an additional ordinary executable section merely because they exist inside the file.
The attribute certificate table is a particularly important example of file-resident information that is not mapped as an ordinary image section.
Applications may nevertheless access additional file information through their own logic.
For example, a legitimate installer might need to read packaged application data stored in its executable file.
This explains why the following values can differ substantially:
- Physical executable file size.
- Declared raw section data size.
- Optional Header
SizeOfImage. - Memory consumption of the running process.
These measurements describe different aspects of an executable.
SizeOfImage is not an overlay boundary.
23. Does Removing an Overlay Change the Executable?
Potentially, yes.
Additional executable data may be necessary for the application to function.
Removing or changing bytes can affect:
- Installation packages.
- Embedded archives.
- Application configuration.
- Digital signatures.
- File hashes.
- Application-specific integrity checks.
- Software distribution mechanisms.
Even when Windows can map an executable’s ordinary sections, the application may depend on additional file data later.
For this reason, our inspector is intentionally read-only.
During forensic or security analysis, preserving the original file is particularly important.
If experimentation involving file modification is necessary, it should be performed separately on an authorized laboratory copy, with the original preserved.
24. PE Overlay vs. PE Resources
PE resources and overlays are sometimes confused because both may contain information beyond executable machine instructions.
However, they are structurally different.
| Feature | PE Resources | PE Overlay |
|---|---|---|
| Ordinary PE structure | Resource directory and related data | Additional trailing file bytes |
| Common location | Often associated with .rsrc |
Beyond the calculated raw-data boundary |
| Windows resource APIs | Supported for appropriately structured resources | Not automatically exposed as ordinary resources |
| Typical contents | Icons, dialogs, strings, version information | Archives, packaging data, certificates, other information |
| Format | Defined resource-directory structures | Application-dependent |
A resource can contain arbitrary application data while remaining part of the declared executable image.
An overlay may contain similar information without being part of the resource directory.
The distinction concerns where and how the data is represented.
25. PE Overlay vs. Packed Executables
A packed executable uses some form of packing or transformation to represent executable content differently from an ordinary uncompressed build.
Packed executables can exhibit characteristics such as:
- Unusual section layouts.
- High-entropy sections.
- Different import patterns.
- Additional application-specific data.
However, packing does not necessarily imply the presence of an overlay.
Similarly, an executable with an overlay is not necessarily packed.
| Observation | Does it prove packing? |
|---|---|
| High section entropy | No |
| Large trailing region | No |
| Unusual section name | No |
| Embedded archive signature | No |
| Presence of a certificate table | No |
These are potential indicators or structural characteristics requiring context.
It is important not to turn individual static features into unsupported conclusions.
26. Common Mistakes in PE Overlay Analysis
Mistake 1: Using VirtualSize instead of SizeOfRawData
Virtual size describes section information in the mapped image.
Overlay calculations concern physical file boundaries.
Use the appropriate raw-data fields.
Mistake 2: Using the final section-table entry
The last listed section may not have the highest raw-data end.
Review all relevant section headers.
Mistake 3: Ignoring malformed section boundaries
A section that extends beyond the end of the file may indicate invalid or inconsistent structure.
Report the condition rather than calculating a misleading overlay.
Mistake 4: Treating the Security Directory address as an RVA
The Security Directory uses a file offset.
This exception is important when interpreting certificate-table placement.
Mistake 5: Assuming every trailing byte is malicious
Legitimate executables frequently contain additional file data.
Interpret the content in context.
Mistake 6: Assuming every declared certificate is valid
A certificate-table entry only describes a location and size.
Perform signature verification separately.
Mistake 7: Treating entropy as a malware detector
Entropy describes byte distribution.
It does not independently establish malicious intent.
Mistake 8: Trusting file signatures without validation
A recognizable leading byte pattern is an initial clue, not proof of a complete embedded file.
Mistake 9: Ignoring non-section file structures
Debug information and other structures may occupy additional file space.
A complete PE forensic parser requires more than section and certificate calculations.
Mistake 10: Modifying the original sample
Preserve the analyzed file.
Use separate reports and authorized laboratory copies when appropriate.
27. PE File Overlay Analysis Checklist
Use this checklist when examining an executable.
File identity
-
Record the file name and size.
-
Calculate the SHA-256 hash.
-
Document the file’s known origin.
-
Preserve the original file.
PE structure
-
Verify that the file can be parsed as PE.
-
Inspect the declared header size.
-
Review all section headers.
-
Examine raw offsets and raw sizes.
-
Check for out-of-bounds section data.
-
Review overlapping section ranges.
-
Calculate the highest declared raw-data end.
Trailing region
-
Calculate the trailing-region start.
-
Calculate its size.
-
Review the Security Directory.
-
Validate the declared certificate-table bounds.
-
Distinguish certificate-related bytes from other trailing data.
-
Record structural inconsistencies.
Content analysis
-
Calculate hashes of relevant regions.
-
Calculate entropy.
-
Inspect leading byte patterns.
-
Consider the limitations of format identification.
-
Avoid executing unknown content.
Interpretation
-
Consider the executable’s expected purpose.
-
Verify available digital signatures separately.
-
Compare observations with known legitimate files.
-
Distinguish observations from hypotheses.
-
Avoid unsupported malware conclusions.
28. Frequently Asked Questions
What is an overlay in an EXE file?
An overlay commonly refers to additional bytes located after the raw data of the executable’s declared PE sections.
Different tools may handle recognized non-section structures differently when reporting overlays.
Are PE overlays part of the Windows executable format?
The term overlay describes additional file data rather than an ordinary PE section.
Some recognized PE structures, including the attribute certificate table, may exist outside ordinary section data.
Do all executable files have overlays?
No.
Many executables end at their declared raw-data boundary, while others contain additional information.
Are PE overlays dangerous?
Not inherently.
They may contain legitimate installation files, application data, certificates or other information.
Their security significance depends on the complete context.
Can a digitally signed executable contain an overlay?
Yes.
Signed executables may contain certificate-related data outside ordinary PE sections.
This is one reason overlay analysis should consider the Security Directory.
Is the PE Security Directory address an RVA?
No.
The Security Directory’s VirtualAddress field represents a file offset to the attribute certificate table.
Can I calculate overlay size using SizeOfImage?
No.
SizeOfImage describes the size of the mapped executable image, subject to PE layout requirements.
It is not the physical end of section data on disk.
Can I detect a PE overlay with Python?
Yes.
Libraries such as pefile provide access to executable structures and overlay-related functionality.
You can also calculate a trailing-region boundary using declared header sizes and section raw-data fields.
Does high overlay entropy indicate malware?
No.
High entropy may be consistent with compressed, encrypted or other statistically complex data.
Additional investigation is required to determine its meaning.
Can I analyze an executable without running it?
Yes.
Static analysis tools can inspect executable structures, hashes, strings, imports and additional file data without executing the program.
Use updated tools and appropriate isolation when analyzing untrusted files.
Can an executable contain another executable?
A Windows executable can contain additional executable-like information within resources, sections or other file regions.
A matching header signature alone does not prove that a complete, valid embedded executable exists.
Does a valid digital signature mean an executable is safe?
No.
A valid signature provides information about integrity and signing identity under the applicable verification policy.
It does not guarantee that the executable is free from vulnerabilities or malicious behavior.
Is PEFile Overlay Inspector a malware scanner?
No.
It is an educational, read-only structural analysis utility.
It provides descriptive observations about executable file layout and trailing data without producing a malware classification.
29. What Could We Add to a More Advanced PE Overlay Analyzer?
Our educational implementation provides a starting point.
A more comprehensive executable-analysis utility could include:
- Streaming analysis for very large files.
- Detailed certificate-table record validation.
- Authenticode verification integration.
- Additional non-section structure identification.
- Entropy measurements across smaller file regions.
- Better PE-format consistency checks.
- Comparison between multiple executable versions.
- Visual representation of physical file intervals.
- Structured evidence reports.
- Integration with defensive executable-analysis workflows.
One particularly interesting direction is comparing different versions of the same application.
For example, a researcher could investigate whether an application update introduced changes to its trailing data, certificate-table placement or packaging structure.
Such comparisons can provide useful evidence when investigating software distribution and build changes.
Conclusion: Look Beyond the Last Section
Portable Executable analysis does not have to stop at the entry point, import table or last declared section.
A Windows executable may contain additional information that helps explain how it was built, signed, packaged or distributed.
PE file overlay analysis provides a way to investigate that information systematically.
The most important principles are straightforward:
- Work with physical file offsets.
- Examine every relevant section.
- Validate declared file boundaries.
- Account for the Security Directory.
- Separate certificate-related information from other trailing bytes.
- Use entropy and file signatures as observations rather than verdicts.
- Preserve the original executable.
- Document what your evidence actually establishes.
The next time you analyze a Windows executable, consider asking one additional question:
What exists beyond the end of its last declared section?
The answer may be more interesting than you expect.
And even when the answer turns out to be something completely ordinary, understanding why those bytes are present makes you a better executable analyst.
Keep exploring, keep questioning, and remember that every byte has a location — but understanding its purpose requires evidence.
References and Further Reading
- Microsoft — PE Format Specification
- Python pefile Documentation
- Microsoft — Get-AuthenticodeSignature
- Microsoft — Get-FileHash
- Python — hashlib Documentation
- PEFile.net — What Is File Entropy?
- PEFile.net — PE File Information Example
- PEFile.net — Portable Executable File Information
This article is intended for educational, software development, digital forensic and defensive cybersecurity purposes. The Python utility is an educational structural analyzer, not a comprehensive PE validator, Authenticode verifier or malware detection product. All hypothetical examples are illustrative.
Last technical review: November 2026.
You must be logged in to post a comment.