Back to Blog
Cloud IAM Security

Bypassing Endpoint Detection and Response (EDR) with Sleep Obfuscation

OffSec Research Team
10 June 2026 • 09:00 AM13 min
Bypassing Endpoint Detection and Response (EDR) with Sleep Obfuscation
TL;DR — Modern EDRs perform periodic memory scans of running processes to detect implants during their idle (sleep) intervals. Sleep obfuscation counters this by encrypting or unmapping the beacon's in-memory footprint while it sleeps, restoring to an executable state only when a callback timer fires. This article covers the threat model that makes sleep obfuscation necessary, the principal techniques (Ekko, Foliage, Gargoyle, Nightmangle, and custom implementations), the APC and timer primitives they rely on, call stack artefacts during the sleep phase, advanced combinations with call stack spoofing, and the comprehensive detection strategy that catches even sophisticated implementations.

Executive Summary

Sleep obfuscation has become a defining capability in mature C2 frameworks since roughly 2021, when the offensive security community began systematically addressing the observation that well-configured EDRs routinely detect Cobalt Strike and similar beacons not during their check-in moments but during the long idle intervals between check-ins. Tools like Cobalt Strike (which accounts for a disproportionate share of real-world intrusion tooling), Sliver, and custom C frameworks all now support some variant of sleep obfuscation.

From the red team perspective, sleep obfuscation extends dwell time by defeating the periodic memory scanning that constitutes an EDR's "background intelligence" — the continuous scrutiny of process memory even when nothing interesting is happening. From the blue team perspective, sleep obfuscation means that memory scanning alone is no longer sufficient: detection must also address the obfuscation mechanics themselves (VirtualProtect patterns, APC queue behaviour, timer creation) and the structural invariants (thread origin, process anomaly, network periodicity) that survive even encrypted sleep.

The Threat Model: Why Sleep Windows Are Dangerous

A typical C2 beacon operates on a heartbeat cycle: sleep for a configured interval, wake up, check in with the C2 server, process tasks if any, then sleep again. Common sleep intervals range from 30 seconds (interactive operations) to 60 minutes (long-term persistence). During the sleep interval, the beacon sits completely idle in memory.

EDRs exploit this idle window in two ways:

Scheduled memory scanning: EDR agents schedule periodic scans of all process memory regions. During a scan, the EDR reads every executable page of every process and compares the content against known-bad signatures. A sleeping beacon is the ideal scan target: it is not executing, its pages are stable, and its content is plaintext.

Thread call stack scanning: EDR products enumerate all threads in all processes and walk their call stacks. A sleeping beacon thread typically has a return address chain that terminates in the beacon's allocation — an anonymous, non-module-backed region. This is a reliable structural tell.

shell
Beacon lifecycle WITHOUT sleep obfuscation:┌──────────────────────────────────────────────────────┐│  [SLEEP 60s]                              [CALLBACK]  ││      ↑                                               ││   EDR memory scan fires: finds plaintext beacon      ││   EDR call stack scan:   return addr in anonymous RWX│└──────────────────────────────────────────────────────┘

Sleep obfuscation inserts encrypt–decrypt wrappers around the sleep interval:

shell
Beacon lifecycle WITH sleep obfuscation:┌──────────────────────────────────────────────────────────────────┐│  [ENCRYPT self] → [SLEEP] → [DECRYPT self] → [CALLBACK]         ││                      ↑                                           ││  EDR memory scan: encrypted garbage — no signature match         ││  EDR call stack:  thread in alertable wait — may be spoofed      │└──────────────────────────────────────────────────────────────────┘

Primitive: Windows Timer Queues and APCs

Sleep obfuscation relies on two Windows mechanisms for scheduling the encrypt/decrypt operations around the sleep interval:

Timer Queue Timers (CreateTimerQueueTimer): Create a one-shot or repeating timer. When the timer fires, a callback function executes on a thread pool thread. Timers can be configured to fire after a specific delay.

Asynchronous Procedure Calls (APCs): APCs are functions queued to a thread's APC queue that execute when the thread enters an "alertable" wait state. The key API is QueueUserAPC(callback, thread_handle, parameter). SleepEx(INFINITE, TRUE) puts a thread into an alertable wait, processing any queued APCs before returning.

The combination enables the encrypt-sleep-decrypt cycle without creating new threads:

c
// Conceptual flow: self-encrypting sleepQueueUserAPC(EncryptBeaconMemory, GetCurrentThread(), 0);  // fires immediately on SleepExCreateTimerQueueTimer(&hTimer, NULL, DecryptAndWakeCallback, NULL, sleep_ms, 0, WT_EXECUTEINTIMERTHREAD);SleepEx(INFINITE, TRUE);  // processes EncryptBeaconMemory APC first, then waits// Timer fires after sleep_ms: DecryptAndWakeCallback queues another APC// Second APC fires: DecryptBeaconMemory → execution resumes

Technique 1: Ekko (APC-Based RC4 Encryption)

Ekko (released by C5pider/RTO) is the most widely referenced sleep obfuscation implementation. It uses Windows timer queues and APCs to orchestrate the encrypt-sleep-decrypt sequence with RC4 encryption.

diagram — rendering…
sequenceDiagram
    participant B as Beacon Thread
    participant Q as APC Queue
    participant T as Timer Queue
    participant K as RC4 Encrypt/Decrypt
    B->>Q: QueueUserAPC(EncryptSelf, currentThread, 0)
    B->>T: CreateTimerQueueTimer(DecryptAndWake, sleep_ms)
    B->>B: SleepEx(INFINITE, TRUE) — alertable wait
    Q->>K: EncryptSelf() fires: RC4-encrypt beacon .text
    T->>Q: Timer fires: QueueUserAPC(DecryptSelf)
    Q->>K: DecryptSelf() fires: RC4-decrypt .text
    K->>B: Execution resumes: continue beacon loop

Key implementation details:

c
typedef struct {    PVOID  beacon_base;    SIZE_T beacon_size;    BYTE   rc4_key[16];} EKKO_ARGS; // RC4 encrypt/decrypt of beacon .text sectionvoid EncryptBeaconSection(ULONG_PTR param) {    EKKO_ARGS* args = (EKKO_ARGS*)param;    DWORD old_prot;    VirtualProtect(args->beacon_base, args->beacon_size, PAGE_READWRITE, &old_prot);    RC4(args->beacon_base, args->beacon_size, args->rc4_key, 16);    VirtualProtect(args->beacon_base, args->beacon_size, old_prot, &old_prot);} void DecryptBeaconSection(ULONG_PTR param) {    // Identical to encrypt — RC4 is symmetric    EncryptBeaconSection(param);}

The encryption routine changes .text to PAGE_READWRITE, XOR-encrypts the bytes, restores to PAGE_EXECUTE_READ. When the timer fires, the process reverses.

Critical edge case: The EncryptSelf routine must encrypt itself last — if it encrypts its own code before finishing, it crashes. Ekko handles this by encrypting everything except the encryption stub, then encrypting the stub in the final step.

Technique 2: Foliage (Page Permission Flipping)

Foliage takes a different approach: instead of encrypting the beacon, it changes the memory page permissions to PAGE_NOACCESS during sleep. An EDR memory scanner that tries to read the beacon's pages during the sleep window gets an access violation — the scan silently fails, and the region appears empty.

c
void FoliageSleep(PVOID beacon_base, SIZE_T beacon_size, DWORD sleep_ms) {    DWORD old_prot;        // Set beacon pages inaccessible    VirtualProtect(beacon_base, beacon_size, PAGE_NOACCESS, &old_prot);        // Sleep (beacon is now completely inaccessible — scanner gets AV on read)    Sleep(sleep_ms);        // Restore access    VirtualProtect(beacon_base, beacon_size, old_prot, &old_prot);}

Detection artefact: A memory region that was previously executable becoming PAGE_NOACCESS and then reverting to executable is an unusual permission sequence. EDRs track permission history per region.

Technique 3: Gargoyle (ROP + Timer-Based Re-Execution)

Gargoyle (by itm4n) is the original sleep obfuscation concept from 2017. It uses return-oriented programming (ROP) gadgets to make the beacon code non-executable and establishes a timer that re-executes the beacon via a ROP-constructed return frame:

diagram — rendering…
flowchart TD
    A["Beacon runs"] --> B["Set beacon .text → PAGE_NOACCESS via ROP gadgets"]
    B --> C["SetTimer(WakeUpRoutine, sleep_ms)"]
    C --> D["Beacon 'exits' — no longer in thread call stack"]
    D --> E["EDR: no beacon in memory or call stack"]
    E --> F["Timer fires: WakeUpRoutine via ROP chain"]
    F --> G["Beacon .text → PAGE_EXECUTE_READ again"]
    G --> H["Jump back to beacon entry → resumes"]
    style E fill:#0c2a22,stroke:#21d48e,color:#d1fae5

Gargoyle was groundbreaking in 2017; modern variants combine its page-flip approach with real encryption for defense-in-depth.

Technique 4: Nightmangle / Heap Encryption

Heap-based implementations encrypt the beacon's heap allocations (where configuration, task buffers, and C2 connection state reside) in addition to or instead of the code section.

c
// Encrypt all heap allocations belonging to the beaconHANDLE hHeap = GetProcessHeap();HeapLock(hHeap);PROCESS_HEAP_ENTRY entry = {0};while (HeapWalk(hHeap, &entry)) {    if (entry.wFlags & PROCESS_HEAP_ENTRY_BUSY) {        RC4((BYTE*)entry.lpData, entry.cbData, key, sizeof(key));    }}HeapUnlock(hHeap);

This extends the obfuscation coverage from code pages to data pages, defeating scans that search for known configuration structures (C2 URLs, sleep timers, shellcode patterns in heap data).

Advanced: Sleep Obfuscation + Call Stack Spoofing

High-sophistication implants combine sleep obfuscation with call stack spoofing. Before executing the encrypt+sleep sequence, the beacon overwrites its thread's stack with a fake call chain, making the sleeping thread appear to be a normal Windows API wait:

c
void ObfuscatedSleep(DWORD sleep_ms) {    // Step 1: Build a fake call stack (looks like a thread pool worker)    SpoofCallStack(g_fake_frames, g_frame_count);        // Step 2: Queue APC to encrypt beacon    QueueUserAPC(EncryptBeacon, GetCurrentThread(), (ULONG_PTR)&g_beacon_info);        // Step 3: Queue timer to decrypt and wake    CreateTimerQueueTimer(&g_timer, NULL, DecryptAndWakeAPC, &g_beacon_info, sleep_ms, 0, WT_EXECUTEINTIMERTHREAD);        // Step 4: Alertable wait — encrypt APC fires first, then we wait    SleepEx(INFINITE, TRUE);        // Step 5: On wake, restore real call stack    RestoreCallStack(g_saved_frames, g_frame_count);}

During the encrypted sleep window:

  • The beacon's code pages are encrypted or inaccessible
  • The thread's call stack shows a spoofed chain pointing to ntdll!ZwWaitForSingleObject and kernel32!SleepEx with return addresses inside ntdll
  • Memory scanning finds encrypted garbage
  • Call stack analysis finds a normal-looking alertable wait thread

This combination defeats both primary EDR runtime detection mechanisms simultaneously.

Call Stack During Sleep Phase

The call stack of an unprotected sleeping beacon thread typically shows:

shell
ntdll!ZwWaitForSingleObject+0xcntdll!NtWaitForSingleObject+0x15KernelBase!SleepEx+0xab[BEACON_BASE + 0x1337]     ← return addr in anonymous region — FLAGGED0x0000000000000000

With call stack spoofing active:

shell
ntdll!ZwWaitForSingleObject+0xcntdll!NtWaitForSingleObject+0x15KernelBase!SleepEx+0xabntdll!RtlpTpWorkCallback+0x8d   ← spoofed frame — looks like thread poolntdll!TppWorkerThread+0x2c5     ← spoofed frame — normal worker threadkernel32!BaseThreadInitThunk    ← legitimate thread start0x0000000000000000

Tools like Hunt-Sleeping-Beacons specifically look for the beacon_base + offset return address pattern. Spoofing removes the obvious signal, but introduces subtler inconsistencies (RSP deltas not matching unwind records) that more sophisticated analysis can detect.

Detection Strategy

diagram — rendering…
flowchart TD
    A["Sleep Obfuscation Detection"] --> B["Hunt-Sleeping-Beacons: call stack analysis<br/>for threads in alertable wait with suspicious return addrs"]
    A --> C["VirtualProtect oscillation: .text→RW→NOACCESS→RX<br/>unusual permission sequence on code pages"]
    A --> D["QueueUserAPC self-target: APC queued<br/>where source == target thread"]
    A --> E["CreateTimerQueueTimer from non-timer code path<br/>+ SleepEx(INFINITE, TRUE) combination"]
    A --> F["Periodic memory snapshot diff:<br/>encrypted region content changes between scans"]
    A --> G["ETW gaps: beacon thread active, then goes silent<br/>while kernel callbacks show continued activity"]
    style A fill:#0c2a22,stroke:#21d48e,color:#d1fae5
ToolTechniqueFree/Commercial
Hunt-Sleeping-BeaconsThread call stack analysis for sleeping implantsFree (GitHub)
MonetaEnumerates executable memory regions not backed by filesFree (GitHub)
BeaconHunterAutomated Cobalt Strike beacon detectionFree (GitHub)
PE-sievePer-process in-memory vs on-disk comparisonFree (GitHub)
Hollows HunterComprehensive memory injection detectionFree (GitHub)
YARA + memory dumpPattern matching on memory snapshotsFree

Invariant Signal: VirtualProtect on Code Pages

Even the most sophisticated sleep obfuscation requires at least one VirtualProtect call to change the beacon's .text section from executable to writable (for encryption) and back to executable (for decryption). This permission change sequence on a code page is:

  • Extremely rare in legitimate processes (JIT compilers are the primary exception)
  • Observable via ETW Microsoft-Windows-Kernel-Audit-API-Calls
  • Correlated with the executing process identity and time

An alert on PAGE_EXECUTE_READ → PAGE_READWRITE → PAGE_EXECUTE_READ transitions in non-JIT processes provides high-fidelity coverage for all encryption-based sleep obfuscation variants.

Performance and Stability Trade-offs

Sleep obfuscation is not free. It imposes measurable overhead and introduces stability risks:

Encryption overhead: RC4 on a 500KB beacon .text section takes roughly 0.5–2ms on modern hardware. This is negligible for long sleep intervals (minutes to hours) but adds latency on short-interval (sub-second) callbacks.

Stability risks:

  • If the timer fires before the APC is done encrypting, the decrypt callback may run against partially-encrypted bytes — causing a crash
  • Exception handlers that reference beacon code addresses may trigger on the encrypted region if an exception occurs during the transition window
  • Anti-debugging checks built into the beacon may misfire if the code bytes change temporarily

Mitigation patterns:

c
// Use a synchronisation event to prevent timer/APC raceHANDLE g_encrypt_complete = CreateEventW(NULL, TRUE, FALSE, NULL); void EncryptBeaconAPC(ULONG_PTR param) {    EncryptBeaconSection((EKKO_ARGS*)param);    SetEvent(g_encrypt_complete);  // signal: safe for timer to proceed} void WakeTimerCallback(PVOID param, BOOLEAN fired) {    WaitForSingleObject(g_encrypt_complete, INFINITE);  // wait for encrypt completion    ResetEvent(g_encrypt_complete);    QueueUserAPC(DecryptBeaconAPC, g_beacon_thread, (ULONG_PTR)param);}

Sleep Obfuscation in Commercial C2 Frameworks

Cobalt Strike 4.5+ (Talon / `sleep_mask`): Cobalt Strike introduced the sleep_mask BOF hook in version 4.5, allowing operators to replace the default sleep function with a custom implementation. Operators can load sleep obfuscation BOFs (Ekko, Foliage, AceLdr) as sleep_mask implementations.

Sliver C2 (open source): Sliver added native sleep obfuscation support in version 1.5, implementing a variant of heap and stack obfuscation in its Go-based agent.

Brute Ratel C4 (commercial): Built-in sleep obfuscation using custom page permission manipulation and XOR-based text encryption.

Havoc C2 (open source): Implements an ObfuscateSleep technique combining APC-based encryption with stack encryption.

The commoditisation of sleep obfuscation across these platforms means defenders cannot treat it as a novel, rare technique — it is baseline expected behaviour for mature implants.

Production Implementation Checklist for Red Teams

Before deploying sleep obfuscation in a live engagement, thorough testing is essential. Crashes during the encrypt/decrypt transition leave a forensic artefact (minidump or Watson report) that alerts defenders and terminates the implant. Budget significant lab time on the specific target OS build and EDR product before going operational.

  • [ ] Verify the beacon's base address and section size are correctly identified
  • [ ] Test encrypt/decrypt symmetric property (double-encrypt = original bytes)
  • [ ] Verify the encryption routine handles its own code region last
  • [ ] Confirm call stack appears benign in Hunt-Sleeping-Beacons during sleep
  • [ ] Test that C2 reconnection succeeds after multiple sleep/wake cycles
  • [ ] Verify no memory corruption after 24+ hours of sleep cycles
  • [ ] Confirm exception handlers remain functional after code section encryption

The Future: Hardware-Enforced Countermeasures

Intel CET (Control-flow Enforcement Technology) and the Windows Shadow Stack feature pose a future challenge for sleep obfuscation techniques that also spoof the call stack. CET maintains a shadow copy of the return address stack in a supervisor-protected memory region. When a RET instruction executes, the processor compares the return address against the shadow stack entry. A mismatch causes a #CP (Control Protection) exception.

Call stack spoofing during sleep overwrites the user-mode stack with fake frames, but it cannot overwrite the shadow stack (which is protected from user-mode writes). When the sleeping thread wakes and begins unwinding through the spoofed frames, the first RET that encounters a shadow-stack mismatch kills the process.

This means that on hardware with CET enabled (Windows 11 on compatible processors), the combination of sleep obfuscation + call stack spoofing becomes unstable. Red teams must either:

  • Avoid call stack spoofing on CET-enabled targets
  • Use indirect execution paths that do not require return address manipulation
  • Target the gaps in CET coverage (it is not enabled for all processes by default on most enterprise deployments as of 2024)

Conclusion

Sleep obfuscation represents the current operational standard for long-dwell C2 beacon deployments in mature EDR environments. By hiding the beacon's plaintext footprint during idle intervals, it defeats the most efficient EDR detection opportunity — memory scanning against a stationary, non-executing target. The technique is not a silver bullet: it requires precise implementation (incorrect encryption order crashes the beacon), it leaves structural artefacts (VirtualProtect on code pages, APC queue patterns), and it cannot defeat the kernel-level visibility layer. Defenders who combine periodic memory scanning with call stack inspection of sleeping threads, and who monitor for the triple signal of VirtualProtect + APC queue + SleepEx(INFINITE, TRUE), can reliably detect even sophisticated sleep obfuscation before the beacon wakes to complete its next objective.