Malware Development
Evasion Concepts
Technically speaking, AV/EDR evasion process can be broken down to 3 stages:
Stage 1 : Code wrapper (dropper, loader or stager) that is going to land on disk or get executed as a script, a macro or a one-liner command.
Stage 2 : The malicious payload that is going to be executed by the wrapper and is usually a c2 implant.
Stage 3 : Any post-exploitation action that the c2 agent or malicious code is going to take after infecting the target (EDRs are focusing more on this stage).
As a red team operator, we should consider OPSEC and evasion concepts in all 3 stages of infecting the victim's system. so we have to be familiar with detection/evasion techniques which are:
Static Analysis : just looking at the file and its properties without actually running it.
Dynamic Analysis : running the code in an isolated environment (Emulator / Sandbox) to observe its behavior and see what it would do if it got executed on the machine.
Behavioral Analysis : if the detection system could not find anything during static and dynamic phases, it would let the code run on the machine but closely monitor every action and changes that it makes in the system. this is the feature that EDR products offer.
Detection vs. Evasion
Static Tradecraft
Signature-based Detection String Detection
Payload Encryption / Obfuscation String Encryption / Obfuscation Packing / Compressing
Metadata Analysis
Metadata Modification Binary Properties Certificate Spoofing
File Compression and Encryption Detection
Entropy Reduction Code Cave
Dependency Analysis Function Call Analysis Import/Export Table Examination
IAT/EAT Spoofing Dynamic (Run-time) Imports Custom Libraries/APIs
Disassembly Analysis
Opaque Predicate
Control Flow Analysis
Polymorphism Control Flow Obfuscation Compiler Options Dead Code Insertion
Machine Learning
Be predictable and act normal :)
Dynamic & Behavioral Tradecraft
Sandbox / Emulator
Environment Checks Execution Guardrails Sleep Timer
Memory Scanners
Sleep Mask Self-Mutating Shellcode
Network Traffic Analysis
C2 Redirectors Decoy Domains (DGA) Domain Fronting Traffic Encryption
File & Registry Monitoring
Avoid Sensitive File & Registry Modification
Anti-Debugger / Anti-Sandbox Techniques Detection
Don't use too many execution guards
API Hooking
Ntdll Unhooking Direct Syscalls Indirect Syscalls
Parent-Child Relationship Analysis
PPID Spoofing
Command-Line Argument Analysis
Command-Line Argument Spoofing
Static Analysis
static analysis means analyzing the program or file without executing or opening it. this is the first, oldest and easiest technique that is steal widely used in all endpoint security products since the early ages of anti-virus software. some of the techniques used in this phase are repeated in the next two stages afterwards (such as signature detection that is used by memory scanners during dynamic and behavioral analysis phases). usually when the file touches the disk or the script runs in cmd / powershell console, the static analysis is the first thing that security products do. this technique works best against known-bads and malware that doesn't take any effort to hide its intentions.
Detection Techniques
Signature-based Detection: This is the most basic form of detection. It involves comparing the digital signature (hash) of the malware's file against a database of known malicious signatures. If a match is found, the file is flagged as malware.
String Analysis: Malware often contains characteristic strings or keywords (mostly printable strings and characters) that can indicate its malicious intent. AV/EDR solutions scan the file for these strings, which might include network-related commands, suspicious file paths, or certain function names.
Metadata Analysis: File metadata, such as the compiler used, timestamps, and digital signatures, can provide insights into the malware's origin and authenticity. Metadata that doesn't match legitimate software can be an indicator of malicious activity.
PE (Portable Executable) Header Analysis: For Windows executables, the PE header contains information about the file's structure and properties. Analysis of this header can reveal anomalies, such as missing or tampered sections.
File Compression and Encryption Detection: Malware might be compressed or encrypted to avoid detection. Static analysis can identify patterns associated with common compression or encryption algorithms.
Dependency Analysis: Malware often relies on specific libraries, APIs, or resources. Identifying these dependencies can help in understanding the malware's capabilities and potential impact.
Code Obfuscation and Packing Detection: Malware authors often obfuscate or "pack" their code to evade detection. Static analysis attempts to reverse these techniques to reveal the actual code and behavior.
File Entropy Analysis: Entropy refers to the randomness or unpredictability of data within a file. In the context of malware analysis, this technique involves measuring the entropy of the bytes in a file to determine whether the file's contents appear to be highly structured (low entropy) or more random (high entropy).
Control Flow Analysis: Analyzing the flow of instructions within the malware's code can reveal loops, conditionals, and potential points of interest. This helps in understanding how the malware operates.
Function Call Analysis: Studying the functions called by the malware can provide insights into its behavior, such as whether it attempts to spread, establish persistence, or communicate with a command and control server.
Import/Export Table Examination: Looking at the functions imported and exported by the malware can indicate its capabilities and potential interaction with the operating system or other software.
Behavioral Patterns: Certain types of malware exhibit characteristic behaviors. Static analysis can help identify these patterns, such as the creation of auto-run entries, modification of system files, or attempts to escalate privileges.
Machine Learning and Heuristics: Some AV/EDR solutions use machine learning models and heuristics to identify suspicious files based on patterns and anomalies found in the code.
Evasion Techniques
Code Obfuscation: Malware authors obfuscate their code by applying transformations that alter the code's structure and appearance while preserving its functionality. This makes it harder for signature-based detection and string analysis to identify known patterns.
Packing/Compression: Malware can be packed or compressed using custom algorithms to make the file size smaller and obfuscate the original code. This makes it more difficult for static analysis to access and understand the actual malicious code.
Encryption: Malware might encrypt its payload using encryption algorithms. This results in a file with high entropy and appears as random data, making it challenging for static analysis to determine the file's true nature.
Anti-Debugging Techniques: Malware can include code that detects whether it's being analyzed in a debugger environment. If it detects analysis, it might behave differently or avoid revealing its malicious behavior.
Dead Code Insertion: Adding sections of seemingly unused or irrelevant code can confuse static analysis tools and distract analysts from identifying the actual malicious functions.
Dynamic Code Generation: Malware can generate its code dynamically during execution, making it harder to analyze statically. This technique requires dynamic analysis to observe the actual behavior.
Conditional Execution: Malware might use complex conditional statements to execute certain parts of its code only under specific circumstances, making it harder to predict its behavior statically.
Polymorphism: Polymorphic malware changes its appearance each time it infects a new system, altering its code while maintaining functionality. This makes it difficult to create static signatures for detection.
Environment Detection: Malware can detect if it's running in a virtual or sandbox environment and alter its behavior to avoid detection, making sandbox analysis less effective.
String Encryption: Malicious strings used in the code can be encrypted to avoid straightforward string-based detection. The decryption process happens during execution.
Time Delays: Some malware employs time-based triggers that delay their malicious activities to avoid immediate detection by security solutions.
File Manipulation: Malware might alter file metadata, such as timestamps and digital signatures, to appear more legitimate and bypass metadata-based checks.
Steganography: Malware can be hidden within innocent-looking files, such as images or documents, using steganography techniques to evade static analysis.
Multi-Stage Malware: Malware can be designed to operate in multiple stages, with later stages being downloaded or generated dynamically. This makes it harder to analyze the entire malicious behavior statically.
Dynamic Analysis
As mentioned, dynamic analysis means simulating a test environment to observe the program behavior when it gets executed. generally, this analysis phase happens when a user tries to open or execute the file. and the emulation process is done very fast since AV/EDR products have a very limited time for simulating the execution process. this is because of system performance considerations and user experience improvement which is a key factor for customers when choosing a security product. the complexity of the emulation process depends on the analysis context. if dynamic analysis is done by a malware analyst, the emulation environment can be very realistic and close to a normal (even physical !!!) computer system that a normal user would use. the analysis time is of course loner. but if malware is being simulated by an automated security product, chances are that the emulation time is very short (under 30 seconds) and the emulation environment is not capable of mimicking the possible target of the malware. so in general, our job get much harder if we are dealing with a human analyst compared to a security product. here are some of dynamic analysis techniques used by security products and malware analysts:
Detection Techniques
Sandboxing and Emulation: Executing files or code in a controlled environment to observe behavior.
Signature-based Detection: Identifying known malicious patterns or code signatures in memory after execution.
Heuristic Analysis: Identifying potential malware based on deviations from typical behavior or common patterns.
Network Traffic Analysis: Monitoring network traffic for signs of communication with known malicious IP addresses or domains. Analyzing patterns in network traffic that might indicate command and control (C2) activity.
File and Registry Monitoring: Tracking changes to files and registry entries made by processes, which can help identify unauthorized modifications.
Anti-sandbox Techniques Detection: Detecting multiple environment checks and execution guards used by the malware in order to detect and evade sandbox or emulator software.
Evasion Techniques
Sandbox check and execution guards : put some checks in place to detect the execution environment and stop executing if a sandbox or emulator is detected. Don't use too many sandbox checks, it makes your code look more suspicious.
Behavioral Analysis
This last phase of detection is usually performed by EDR / XDR products. if the security software doesn't find anything bad during static and dynamic analysis, it will let the program run on the target system but keeps monitoring the program and every change or system interaction that it has. during the monitoring process, the security product will collect all the artifacts and decides whether to flag the process as malicious or not. the internals of this detection techniques are not well-known since all vendors tend to keep their product as secret as possible, most of EDR vendors don't even give away a demo or trial version of their product without official request from a customer company. so testing behavioral analysis is a completely black box scenario and very much vendor-specific.
Detection Techniques
Memory Scanners: Scanning memory for the presence of injected or malicious code and detecting suspicious API calls or hooks within a process's memory space.
API Call Monitoring: Tracking API calls made by processes to detect abnormal behavior.
Code Injection Detection: Monitoring for code injection techniques, such as DLL injection, process hollowing, or reflective loading.
Anomaly Detection: Identifying deviations from expected behavior, including user activity, process execution, and system interactions.
Parent-Child Relationship Analysis: Examining the relationships between processes, such as detecting suspicious child processes spawned by a parent process.
Privilege Escalation Detection: Identifying attempts to escalate privileges by exploiting vulnerabilities or abusing system permissions.
Evasion Techniques
Sleep Mask : encrypt the payload in memory or change the memory access rights when the c2 agent goes to sleep.
API unhooking : removing or replacing hooks in API functions used by malware.
Parent Process ID Spoofing: change parent-child process relation in process tree.
Avoid EXE and DLL Files : using uncommon file formats for initial access such as CPL, SCR, etc.
Post-Evasion Tradecraft
some of these actions include:
Remote Process Access:
Shellcode Injection
DLL Injection
PE Injection
Memory Dump
Handle Theft
API Hooking
UAC Bypass
Disk Access:
Infiltration & Exfiltration
Data Corruption & Encryption
Keylogging
Token Impersonation
Local Privilege Escalation
Local & Domain Credential Dumping
Local Persistence
Proxy Tunnel for Pivoting & Lateral Movement
and the list goes on :)
Takeaway
To write an efficient tool, we must consider all these techniques. in addition to that, we need a test environment for trying out different techniques and combining them together against AV/EDR products.
The Lab Environment
We need an offline virtual machine for each security product we want to test. Take snapshots after installation and restore them after testing each sample. Take notes after testing each technique or peace of code, you might need to combine multiple techniques in order to fully evade the product.
NEVER upload your code on VirusTotal or any other similar platforms, even the ones that claim they don't share samples with vendors.
In future sections of this series, we start from basic techniques and make our way to more advanced stuff. bare with me as i get the time to write more posts.
All code snippets from this section are available on GitHub:
Last updated
Was this helpful?