Safe First Look at a Suspicious File
Build a harmless sample set from a pinned package and the official UPX release, then triage it statically: hashes, PE metadata, section entropy, imports and strings with pefile, unpacking, and a YARA rule tested against benign files. Finish with how sandbox behaviour and clear criteria decide when to escalate to a reverse engineer.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create the environment
- Step 2: Download the source files and check them
- Step 3: Build the sample set
- Step 4: Read the PE metadata
- Step 5: Compare the strings
- Step 6: Unpack and look again
- Step 7: Write a first YARA rule and test it
- Step 8: Tighten the rule
- Step 9: Sandbox behaviour and the escalation decision
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of Threat Intel & Malware Triage
- From Threat Reports to Defensive Action Concept · 20 min
- Working a Reported Phishing Email Lab · 30 min
- Safe First Look at a Suspicious File Lab · 30 min
- Email Authentication from Monitor to Reject Worked example · 20 min
- Sharing and Operationalising Indicators Worked example · 20 min
- Threat Intel & Malware Triage Check Knowledge check · 8 questions
What you will learn
- Triage a suspicious file in an isolated environment with static checks (hashes, strings, file metadata, YARA) and sandbox behaviour, recognise obfuscation or packing, and decide when to escalate to a reverse engineer.
01. Goal and setup
Your endpoint agent quarantined invoice.exe from a user's Downloads folder, and statement.exe turned up on another computer. Before anyone spends a day reverse engineering it, you need a first look: what is it, has it been seen before, is it hiding something, does it need an expert?
This lab uses no real malware. The two "suspicious" files are a harmless program, a small launcher shipped inside the Python package distlib, compressed with the open-source packer UPX. That is enough to see everything a packed sample shows in static triage, and the unpacked originals give you known-good files for the negative test. Static triage examines a file without running it. It is still not risk-free, because a parser can have bugs, so with real samples you work in an isolated virtual machine without network access or shared folders, and you revert it to a clean snapshot afterwards.
You need: Linux on x86-64 (for the UPX build used here; other systems use the matching asset from the same release), Python 3.10 or later, curl and unzip. Tested with Python 3.12.13, pefile 2024.8.26, yara-python 4.5.4 (YARA 4.5.4), UPX 5.3.0 (released 28 October 2026) and distlib 0.4.4.
file-lab/
├── .venv/ step 1: pefile and yara-python
├── dl/, upx-5.3.0-amd64_linux/ step 2: the distlib wheel and UPX
├── make_samples.sh, pe/, samples/ step 3
├── triage.py, strings.py, unpacked/ steps 4-6
├── rules/v1_naive.yar, rules/v2_family.yar, test_rules.py steps 7-8
└── escalate.py step 902. Step 1: Create the environment
pefile parses Windows executables (the PE, Portable Executable, format) in pure Python. yara-python is the official Python binding for YARA, the pattern-matching engine used to describe malware families.
mkdir file-lab && cd file-lab
export PIP_DISABLE_PIP_VERSION_CHECK=1
python3 -m venv .venv
.venv/bin/pip install -q pefile==2024.8.26 yara-python==4.5.4
.venv/bin/python -c "import pefile, yara; print(pefile.__version__, yara.__version__)"2024.8.26 4.5.403. Step 2: Download the source files and check them
Download only from official sources, the wheel from PyPI and UPX from its GitHub release, and compare each SHA-256 with the value the publisher shows. Stop if they differ.
.venv/bin/pip download -q --no-deps distlib==0.4.4 -d dl
sha256sum dl/distlib-0.4.4-py2.py3-none-any.whl | cut -c1-64
REL=https://github.com/upx/upx/releases/download/v5.3.0
curl -fsSLO "$REL/upx-5.3.0-amd64_linux.tar.xz"
SUM=79cea8a50b6fa102d10c7b79a419cd77dead3cc2d78661de2dc5e5815dc505c1
echo "$SUM upx-5.3.0-amd64_linux.tar.xz" | sha256sum -c
tar -xJf upx-5.3.0-amd64_linux.tar.xz
./upx-5.3.0-amd64_linux/upx --version | head -1cf09d55b1e85a89576b036aeb71550bfd68320f3f21761ca329eadadad918638
upx-5.3.0-amd64_linux.tar.xz: OK
upx 5.3.004. Step 3: Build the sample set
The script copies two launchers out of the wheel as known-good files, packs the same two with UPX to make the "suspicious" pair, and adds two benign non-PE files. notes.txt deliberately mentions UPX's section names; it is the trap for a careless rule.
#!/bin/sh
# Build the lab sample set from known-good files. No real malware is involved.
set -e
UPX=./upx-5.3.0-amd64_linux/upx
mkdir -p pe samples
unzip -o -q -j dl/distlib-0.4.4-py2.py3-none-any.whl \
distlib/t64.exe distlib/w64.exe -d pe
cp pe/t64.exe samples/launcher.exe # known-good console launcher
cp pe/w64.exe samples/gui-launcher.exe # known-good GUI launcher
$UPX -qqq --best -o samples/invoice.exe pe/t64.exe # "suspicious" 1
$UPX -qqq --best -o samples/statement.exe pe/w64.exe # "suspicious" 2
printf 'Notes: UPX0 and UPX1 are the section names UPX writes.\n' > samples/notes.txt
printf '#!/bin/sh\necho "backup done"\n' > samples/backup.sh
chmod a-x samples/*
cd samples && sha256sum * | sort -k2sh make_samples.sh7661fbb5b46f615bfd4aea11ad41e999b8bb930ce7fef7b1e28d9aa0772c96f5 backup.sh
7a319ffaba23a017d7b1e18ba726ba6c54c53d6446db55f92af53c279894f8ad gui-launcher.exe
0223b2ebb54146df49c25fec58e48b156efbe7067b45f126876aeec36f0b1908 invoice.exe
81a618f21cb87db9076134e70388b6e9cb7c2106739011b6a51772d22cae06b7 launcher.exe
ba6018b3edda12281f18a7f1f8963efea6abaa9733a1981e25c551f4a1d97c62 notes.txt
2210a02b2b5b3ab41f753d350e5306410d4ace960239431886af06482bdbe8e2 statement.exeThe SHA-256 is the first thing to record and to look up. It identifies the exact bytes, so a match in your own EDR telemetry or a reputation service tells you quickly whether this file has been seen before. Looking up a hash does not upload the file, but uploading a sample to a public service can share it with that service's other users. An unknown hash does not mean the file is safe: one changed byte, or a new build, gives a new hash.
05. Step 4: Read the PE metadata
triage.py prints three hashes, the type, the entropy and, for PE files, the header data. Entropy measures how unpredictable the bytes are, from 0 bits per byte (one repeated value) to 8 (random). Code and text usually sit between 4 and 6.5. Compressed or encrypted data comes close to 8.
"""Static triage of one file: hashes, type, entropy and, for PE files, metadata."""
import hashlib
import math
import sys
from collections import Counter
from datetime import datetime, timezone
import pefile
def entropy(data):
"""Shannon entropy in bits per byte: 0 = one repeated byte, 8 = random."""
if not data:
return 0.0
counts = Counter(data)
return -sum(c / len(data) * math.log2(c / len(data)) for c in counts.values())
path = sys.argv[1]
data = open(path, "rb").read()
print(f"file {path} ({len(data)} bytes)")
for algo in ("md5", "sha1", "sha256"):
print(f"{algo:<7} {hashlib.new(algo, data).hexdigest()}")
print(f"entropy {entropy(data):.2f} for the whole file")
if data[:2] != b"MZ":
print("type not a PE file (no MZ header):", data[:16])
sys.exit()
pe = pefile.PE(data=data)
built = datetime.fromtimestamp(pe.FILE_HEADER.TimeDateStamp, timezone.utc)
machine = pefile.MACHINE_TYPE[pe.FILE_HEADER.Machine].split("_")[-1]
subsystem = pefile.SUBSYSTEM_TYPE[pe.OPTIONAL_HEADER.Subsystem][16:]
print(f"type PE, machine {machine}, subsystem {subsystem}")
print(f"built {built:%Y-%m-%d %H:%M} UTC (header value, easy to fake)")
info = {}
for group in getattr(pe, "FileInfo", []):
for entry in group:
for table in getattr(entry, "StringTable", []):
info.update({k.decode(): v.decode() for k, v in table.entries.items()})
print(f"version {info.get('ProductName')!r}, original name "
f"{info.get('OriginalFilename')!r}")
print("section raw size virt size entropy")
for s in pe.sections:
name = s.Name.rstrip(b"\0").decode(errors="replace")
print(f"{name:<9} {s.SizeOfRawData:>9} {s.Misc_VirtualSize:>10} "
f"{entropy(s.get_data()):>8.2f}")
imports = getattr(pe, "DIRECTORY_ENTRY_IMPORT", [])
total = sum(len(dll.imports) for dll in imports)
print(f"imports {total} functions from {len(imports)} DLLs, imphash {pe.get_imphash()}")
for dll in imports:
names = [i.name.decode() for i in dll.imports if i.name]
if len(names) > 4:
names = names[:3] + [f"and {len(names) - 3} more"]
print(f" {dll.dll.decode()}: {', '.join(names)}").venv/bin/python triage.py samples/invoice.exefile samples/invoice.exe (62464 bytes)
md5 3dada4d575bb78d37d3fba5fa5eb3c62
sha1 f44131544e9b17af5f838157b493829eade4a566
sha256 0223b2ebb54146df49c25fec58e48b156efbe7067b45f126876aeec36f0b1908
entropy 7.27 for the whole file
type PE, machine AMD64, subsystem WINDOWS_CUI
built 2022-08-06 06:41 UTC (header value, easy to fake)
version 'Simple Launcher', original name 't64.exe'
section raw size virt size entropy
UPX0 0 98304 0.00
UPX1 39424 40960 7.89
.rsrc 22016 24576 5.44
imports 5 functions from 2 DLLs, imphash 0e506c9758cb80305cfb7fe11c6b81a5
KERNEL32.DLL: LoadLibraryA, ExitProcess, GetProcAddress, VirtualProtect
SHLWAPI.dll: StrStrIW.venv/bin/python triage.py samples/launcher.exefile samples/launcher.exe (108032 bytes)
md5 19d621a4b2d26d8fa8002548a1b04a32
sha1 0d0c5e3b06f56ad12a77da46ab3fdab81acda628
sha256 81a618f21cb87db9076134e70388b6e9cb7c2106739011b6a51772d22cae06b7
entropy 6.09 for the whole file
type PE, machine AMD64, subsystem WINDOWS_CUI
built 2022-08-06 06:41 UTC (header value, easy to fake)
version 'Simple Launcher', original name 't64.exe'
section raw size virt size entropy
.text 61440 60961 6.39
.rdata 14848 14404 4.84
.data 5120 16708 1.98
.pdata 3072 2880 4.62
.rsrc 21504 21492 5.48
.reloc 1024 852 2.55
imports 86 functions from 2 DLLs, imphash c51d659b4b1142d4af3795d09f1d63f7
KERNEL32.dll: ExitProcess, GetCommandLineW, SearchPathW, and 80 more
SHLWAPI.dll: StrStrIW, PathRemoveFileSpecW, PathCombineWCompare the two. The known-good launcher has the usual sections (.text for code, .rdata, .data and others) and imports 86 functions. invoice.exe shows the classic signs of packing. UPX0 has a raw size of 0 on disk but reserves 98,304 bytes in memory: empty space for the real program, filled in at run time. UPX1 holds the compressed original, with entropy 7.89. The import table is nearly empty: LoadLibraryA and GetProcAddress let the unpacking stub load the real imports later, and VirtualProtect changes memory permissions so that the unpacked code can run.
Two more fields matter. The build timestamp can be set to anything, so treat it as a hint. The version information still names the original file t64.exe. A file renamed to look like an invoice is a common lure, and the mismatch is a useful note for the case.
06. Step 5: Compare the strings
Readable strings often give away what a program does: error messages, URLs, commands, file paths. strings.py counts ASCII and UTF-16 strings of eight or more characters and shows those that read like messages.
"""Count printable strings and show the ones that read like messages."""
import re
import sys
data = open(sys.argv[1], "rb").read()
ascii_ = [m.decode() for m in re.findall(rb"[\x20-\x7e]{8,}", data)]
wide = [m.decode("utf-16le") for m in re.findall(rb"(?:[\x20-\x7e]\x00){8,}", data)]
# A "message" has four or more words, like an error text or a command line.
MESSAGE = re.compile(r"[A-Za-z]{3,}(?: [\w'%]{2,}){3,}")
messages = [s for s in ascii_ + wide if MESSAGE.search(s)]
print(f"{sys.argv[1]}: {len(ascii_)} ASCII + {len(wide)} UTF-16 strings (8+ chars); "
f"{len(messages)} message-like")
for s in messages[:5]:
print(" ", s[:76]).venv/bin/python strings.py samples/launcher.exe
.venv/bin/python strings.py samples/invoice.exesamples/launcher.exe: 260 ASCII + 67 UTF-16 strings (8+ chars); 41 message-like
!This program cannot be run in DOS mode.
Fatal error in launcher: %s
Failed to open executable
Unable to find an appended archive.
Unable to read from file
samples/invoice.exe: 107 ASCII + 19 UTF-16 strings (8+ chars); 1 message-like
!This program cannot be run in DOS mode.The launcher's error messages describe what it does. In the packed copy they are compressed away; only the DOS stub message remains. When static checks reveal this little, a sandbox or an unpacked copy must tell you the rest.
07. Step 6: Unpack and look again
UPX can reverse its own packing with -d. Unpack into a separate folder so that the original sample stays untouched as evidence.
mkdir -p unpacked
./upx-5.3.0-amd64_linux/upx -qqq -d -o unpacked/invoice.exe samples/invoice.exe
.venv/bin/python triage.py unpacked/invoice.exe | grep -E 'sha256|^\.text|imports'
.venv/bin/python strings.py unpacked/invoice.exe | head -1sha256 1f898e2a7ddcb6897dc5b1bb964a131adc0b21796404cd1977d14f7cf87b81ec
.text 61440 60961 6.39
imports 86 functions from 2 DLLs, imphash c51d659b4b1142d4af3795d09f1d63f7
unpacked/invoice.exe: 260 ASCII + 67 UTF-16 strings (8+ chars); 41 message-likeAfter unpacking, the sections, imports and strings are back. The SHA-256 differs from launcher.exe, because unpacking does not rebuild the file byte for byte. The imphash, an MD5 of the normalised import list, is identical: the same functions from the same DLLs in the same order, a strong hint that this is the same program. That is how a pivot on imphash finds relatives that a file hash misses. Malware authors often modify UPX or use custom packers so that upx -d fails; then you need a sandbox memory dump or a reverse engineer.
08. Step 7: Write a first YARA rule and test it
A YARA rule describes a family of files: strings to look for and a condition that combines them. test_rules.py runs a rule over the whole sample set and compares each result with what you expect: the two packed files must match, the four benign files must not. A rule without a negative test is untested. Start with the obvious rule on the section names.
rule lab_upx_strings_only
{
strings:
$upx0 = "UPX0"
$upx1 = "UPX1"
condition:
all of them
}"""Run a YARA rule file over the sample set and compare with what we expect."""
import sys
import yara
EXPECT = { # file name -> should the rule match?
"invoice.exe": True, "statement.exe": True, # the family
"launcher.exe": False, "gui-launcher.exe": False, # known-good, unpacked
"notes.txt": False, "backup.sh": False, # known-good, not PE
}
rules = yara.compile(filepath=sys.argv[1])
wrong = 0
for name, want in EXPECT.items():
got = bool(rules.match(f"samples/{name}"))
wrong += got != want
print(f"{'ok' if got == want else 'WRONG':<5} {name:<16} match={got!s:<5} "
f"expected={want}")
print(f"{wrong} wrong")
sys.exit(1 if wrong else 0).venv/bin/python test_rules.py rules/v1_naive.yar; echo "exit=$?"ok invoice.exe match=True expected=True
ok statement.exe match=True expected=True
ok launcher.exe match=False expected=False
ok gui-launcher.exe match=False expected=False
WRONG notes.txt match=True expected=False
ok backup.sh match=False expected=False
1 wrong
exit=109. Step 8: Tighten the rule
The text file matched because the rule looks for bytes anywhere. The second version uses YARA's pe and math modules to describe structure: the file must start with MZ (uint16(0) == 0x5A4D), its version information must name the product, UPX0 must be empty on disk, and UPX1 must have high entropy.
import "pe"
import "math"
rule lab_packed_simple_launcher
{
meta:
description = "Simple Launcher builds packed with UPX (lab family)"
author = "file-lab"
date = "2026-11-16"
reference = "samples/invoice.exe, samples/statement.exe"
condition:
uint16(0) == 0x5A4D and
pe.version_info["ProductName"] == "Simple Launcher" and
for any s in pe.sections : (s.name == "UPX0" and s.raw_data_size == 0) and
for any s in pe.sections : (
s.name == "UPX1" and
math.entropy(s.raw_data_offset, s.raw_data_size) > 7.0
)
}.venv/bin/python test_rules.py rules/v2_family.yar; echo "exit=$?"ok invoice.exe match=True expected=True
ok statement.exe match=True expected=True
ok launcher.exe match=False expected=False
ok gui-launcher.exe match=False expected=False
ok notes.txt match=False expected=False
ok backup.sh match=False expected=False
0 wrong
exit=0Both packed launchers match and none of the benign set does. Be honest about what this means: here, packing is the only difference between the "family" and the known-good copies. For real families, analysts add traits that survive rebuilds: unique strings or code from the unpacked payload, configuration formats, or structure such as the import hash. A rule on packer traits alone also matches legitimate software packed with UPX, so test any rule against a large set of known-good files before it goes into production, and expect a packer rule to miss the payload once it is unpacked in memory.
10. Step 9: Sandbox behaviour and the escalation decision
Static triage says what a file is. A sandbox shows what it does: an instrumented, isolated virtual machine runs the sample and records the processes it starts, the files and registry keys it writes, its DNS and network traffic, and often a memory dump in which packed code appears unpacked. This step is not reproducible in this lab: the samples are Windows programs and this host has no Windows sandbox. Open-source CAPE Sandbox or a commercial service with private analysis do this job; the free tiers of public sandboxes can make what you submit visible to other users.
Sandbox results have limits too. Samples can check for virtual machines, sleep for an hour, or wait for a mouse click before doing anything, so "nothing happened" is weak evidence. Most samples do not need a reverse engineer, whose time is scarce. Escalate when the response depends on a question that triage and the sandbox could not answer, or when the sample hides its behaviour from both. escalate.py writes these criteria as code and applies them to this lab's file and three imagined cases.
"""Apply escalation criteria to triage findings: who works each sample next?"""
CASES = [ # what triage and the sandbox established, and what the response still needs
{"name": "invoice.exe (this lab)", "unpacked": True, "evades_sandbox": False,
"open_questions": []},
{"name": "stealer.exe", "unpacked": True, "evades_sandbox": False,
"open_questions": []}, # sandbox extracted its C2 and matched a known family
{"name": "loader-b.bin", "unpacked": False, "evades_sandbox": True,
"open_questions": ["what the second stage does"]},
{"name": "locker.exe", "unpacked": True, "evades_sandbox": False,
"open_questions": ["whether files can be decrypted"]},
]
def decide(case):
if case["open_questions"]:
return f"escalate (open question: {case['open_questions'][0]})"
if case["evades_sandbox"] or not case["unpacked"]:
return "escalate (triage cannot see what it does)"
return "triage is enough: act on the indicators and behaviour"
for case in CASES:
print(f"{case['name']:<23} {decide(case)}").venv/bin/python escalate.pyinvoice.exe (this lab) triage is enough: act on the indicators and behaviour
stealer.exe triage is enough: act on the indicators and behaviour
loader-b.bin escalate (open question: what the second stage does)
locker.exe escalate (open question: whether files can be decrypted)An unknown hash and a YARA match are evidence, not conclusions; neither alone is a reason to escalate. For the ransomware case, whether files can be decrypted changes the recovery plan, so an expert answer is worth the cost.
11. Troubleshooting
12. Check your understanding
13. Apply it
Extend the lab towards the skill project:
- Add a branch to
v2_family.yarthat also matches the unpacked launcher by two of its error strings, and keeplauncher.exeout by adding a condition. Rerun the test withinvoice-unpacked.exeadded toEXPECT. Explain whether the condition you used would survive a rebuild. - Write a short triage note for
invoice.exe: hashes, packing evidence, what unpacking showed, the YARA result and your escalation decision with its reason. - Map what you found to ATT&CK: T1027.002 (Obfuscated Files or Information: Software Packing) and T1036 (Masquerading) for the invoice name.
14. Review prompt
Without looking back:
- Name three static signs that a PE file is packed, and say why each one appears.
- What does an unknown SHA-256 tell you, and what does it not?
- Why does a YARA rule need a set of benign files, and what did the text file catch?
- Give two situations in which you would escalate a sample to a reverse engineer, and one in which you would not.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.