Domain 3Exploit Dev & AV EvasionCORE

Bypassing DEP and ASLR

Complete guide to bypassing DEP and ASLR protections. Covers non-DEP module selection, SETK/SETP flags, heap spraying, information leaks, partial overwrites, and decision trees for protection bypass strategies.

Domain: Domain 3: Exploit Mechanics & AV Evasion•Updated: 2026-09-01
#dep-bypass#aslr-bypass#setk#setp#heap-spray#oscp

Bypassing DEP and ASLR

Chapter 10: Fixing Exploits — Topic 15

When your exploit crashes because of DEP or ASLR, you don’t abandon the vulnerability — you adapt your payload strategy. This guide covers every technique you’ll need to defeat these two critical Windows memory protections.


Table of Contents

  1. DEP Deep Understanding
  2. DEP Bypass Techniques
  3. ASLR Deep Understanding
  4. ASLR Bypass Techniques
  5. Combined DEP + ASLR Bypass
  6. Decision Tree
  7. Mona Commands for DEP/ASLR Analysis
  8. OSCP Relevance
  9. Quick Reference Cheat Sheet

1. DEP Deep Understanding

What is DEP?

DEP (Data Execution Prevention) is a memory protection mechanism that marks certain regions of memory as non-executable. If code attempts to execute from a non-executable region, the CPU raises an exception and the OS terminates the process.

The core idea is simple but powerful: data should not be executable, and executable memory should not contain data. This breaks the fundamental assumption of classic buffer overflow exploits — that you can spray shellcode onto the stack or heap and redirect execution there.

┌─────────────────────────────────────────────┐
│           Classic Buffer Overflow            │
│                                             │
│  Stack:  [Shellcode][NOPs][Return Addr]     │
│          ↑              ↑                   │
│      Executable     Overwritten to point    │
│      (no DEP)         to shellcode          │
└─────────────────────────────────────────────┘

With DEP enabled → Access Violation (STATUS_ACCESS_VIOLATION)

How DEP Works at the OS Level

The NX Bit (No-eXecute)

At the hardware level, DEP relies on the NX bit (No-eXecute), also called the XD bit (eXecute Disable) on AMD processors. This is a single bit in the CPU’s page table entry (PTE):

PTE Bit Name Purpose
Bit 0 Present Page is in memory
Bit 1 Read/Write If 0, page is read-only
Bit 2 User/Supervisor If 0, kernel-only access
Bit 6 NX If 1, page is NON-executable

When the NX bit is set to 1, the CPU’s MMU (Memory Management Unit) will refuse to fetch instructions from that page — even if the page is readable and writable.

Page Table Entry Structure (64-bit):

┌──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┐
│ Bit 0│ Bit 1│ Bit 2│ ...  │ Bit 63│...  │      │      │
│Present│  RW  │  U/S │ ...  │  NX   │...  │      │      │
└──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┘

NX = 0  →  Page is executable
NX = 1  →  Page is NON-executable (DEP active)

Windows Memory Protection Flags

Windows exposes page protection through the VirtualProtect API and the PAGE_* constants:

Flag Value Executable? Writable?
PAGE_READONLY 0x02 No No
PAGE_READWRITE 0x04 No Yes
PAGE_EXECUTE 0x10 Yes No
PAGE_EXECUTE_READ 0x20 Yes No
PAGE_EXECUTE_READWRITE 0x40 Yes Yes
PAGE_EXECUTE_WRITECOPY 0x80 Yes Yes
PAGE_WRITECOPY 0x80 No Yes

The critical insight: DEP is enforced per-page. A single process can have some pages executable and others non-executable. This is why techniques like VirtualProtect calls within shellcode can work — they change the protection of the target page.

Software Execution Prevention (SEP)

On older CPUs that lack hardware NX support, Windows XP SP2/SP3 and Windows Server 2003 implemented Software DEP (also called Software Execution Prevention or SEP). This works by:

  1. Guard pages: The OS places non-executable guard pages around the stack
  2. Page attribute tracking: The OS maintains software page tables that track execution permissions
  3. Exception handling: Attempts to execute from data pages trigger structured exception handling

Software DEP is less reliable than hardware DEP because it can potentially be bypassed through exception handler manipulation. However, on modern systems (Vista and later), hardware DEP is universally available.

Hardware DEP vs Software DEP

Feature Hardware DEP Software DEP (SEP)
CPU requirement NX/XD bit support Any CPU
Enforcement level CPU MMU OS page tables
Reliability Very high Moderate
Bypass difficulty Hard Easier (SEH abuse possible)
Available since Windows XP SP2 (if CPU supports) Windows XP SP2
Bypass via SEH No Potentially yes

Key takeaway for OSCP: On any Windows Vista or newer machine, you’re dealing with hardware DEP. The distinction mainly matters for legacy XP targets.

Opt-in vs Opt-out DEP Policies

Windows supports two DEP policies that determine which processes are protected:

Opt-in (Default on older systems)

Only processes that explicitly opt in are protected. A process opts in by:

  • Setting the /DYNAMICBASE linker flag
  • Setting the IMAGE_DLLCHARACTERISTICS_NX_COMPAT flag (0x00010000) in the PE header
PE Optional Header → DllCharacteristics:
  Bit 16 (0x00010000) = IMAGE_DLLCHARACTERISTICS_NX_COMPAT
  If set → Process runs under DEP (opt-in policy)

Opt-out (Default on Windows 8+)

All processes are protected except those explicitly excluded. Exclusions are made via:

  • Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management
  • The EnableExecProtect value
  • Boot configuration: bcdedit /set nx AlwaysOn (all processes), bcdedit /set nx OptIn (opt-in), bcdedit /set nx AlwaysOff (disabled)
BCDEDIT Setting Policy Coverage
AlwaysOn Opt-out (strict) ALL processes protected
OptIn Opt-in Only opted-in processes
AlwaysOff Disabled No DEP at all

Checking DEP policy on a target:

# Check current NX setting
bcdedit | findstr /i nx

# Check if a specific process is DEP-protected
# Look at the PE header DllCharacteristics

2. DEP Bypass Techniques

Using Non-DEP Modules

The simplest DEP bypass: Find a module loaded in the target process that is NOT covered by DEP, and redirect execution there.

How to Find Non-DEP Modules

Using Mona in Immunity Debugger:

!mona modules

This outputs a table showing all loaded modules with their protection status:

Name              Path                                    DEP    ASLR  REBASE  Safe
==============    ======================================= =====  ====  ======  =====
mshtml.dll        C:\Windows\System32\mshtml.dll          Yes    Yes   Yes     Yes
url.dll           C:\Windows\System32\url.dll             Yes    No    No      Yes
shdocvw.dll       C:\Windows\System32\shdocvw.dll         No     No    No      Yes    ← TARGET!
jscript.dll       C:\Windows\System32\jscript.dll         Yes    Yes   Yes     Yes

Look for modules where DEP = No. These modules have executable pages that you can redirect to.

Finding Useful Opcodes in Non-DEP Modules

Once you identify a non-DEP module, you need to find instructions within it that can help you:

!mona find -s "\xff\x25" -m shdocvw.dll    # jmp [dword ptr ds:[eax]]
!mona find -s "\x8b\xxx\xc3" -m shdocvw.dll  # mov eax, [xxx]; ret
!mona find -s "\xcd\x20" -m shdocvw.dll      # int 20h (rare but useful)

When This Works

  • The target process loads at least one non-DEP module
  • You can find useful gadget instructions in that module
  • The module’s base address is predictable (not ASLR’d, or you have another way to resolve it)

OSCP Reality Check: On Windows XP targets, many modules lack DEP. On Vista+, this is increasingly rare but still possible with third-party modules.


SETK — SetThreadKernelStackBoundingBoxes

SETK stands for Set Thread Kernel Stack Bounding Boxes. It’s a flag embedded in certain PE modules that, when the module is loaded, causes Windows to mark the thread’s stack as executable.

How SETK Works

Some DLLs have a special entry in their .rdata section that contains the SetThreadKernelStackBoundingBoxes API reference. When Windows loads this DLL, it automatically calls this function, which removes the non-executable protection from the thread stack.

The flag is identified by the presence of a specific API reference in the module’s import table or data directory:

API: SetThreadKernelStackBoundingBoxes
DLL: kernel32.dll (exported, but the reference in the target DLL is what matters)

When this function is called during DLL load:

  1. Windows identifies the current thread’s stack region
  2. The stack pages are changed from PAGE_READWRITE to PAGE_EXECUTE_READWRITE
  3. Shellcode on the stack becomes executable

Finding SETK Modules with Mona

!mona setk

Output:

[*] SETK modules:
    Name: shdocvw.dll
    Path: C:\Windows\System32\shdocvw.dll
    Base: 0x76340000
    Size: 0x001d0000

Using SETK in an Exploit

If a SETK module is loaded, your exploit strategy becomes:

  1. Spray shellcode on the stack (as normal)
  2. Ensure the SETK module is loaded before your overflow triggers
  3. The stack is already executable — no special gadgets needed
  4. Redirect EIP to your shellcode using any available technique
# Example: If SETK module is loaded, standard stack shellcode works
buffer = "\x90" * 16          # NOP sled
buffer += shellcode            # Your shellcode (stack is executable!)
buffer += "\x90" * (offset - len(buffer))  # Padding
buffer += struct.pack("<I", shellcode_addr)  # Return address

SETK Module Examples

Common SETK modules found on OSCP machines:

Module Typical Path Notes
shdocvw.dll C:\Windows\System32\shdocvw.dll Shell Doc Object — very common in IE-based apps
url.dll C:\Windows\System32\url.dll URL MIB — sometimes has SETK
mshtml.dll C:\Windows\System32\mshtml.dll MSHTML — version-dependent

Critical: SETK only works if the module is actually loaded in the target process. Just because it exists on disk doesn’t mean it’s loaded. Verify with !mona modules or !mona setk in the debugger.


SETP — NtSetInformationThread

SETP (Set Execution Prevention) uses the NtSetInformationThread API with the ThreadHideFromDebugger class to disable DEP for the current thread.

How SETP Works

The NtSetInformationThread function from ntdll.dll can modify thread information. When called with specific parameters, it disables DEP for the calling thread:

NTSTATUS NtSetInformationThread(
    HANDLE ThreadHandle,
    THREADINFOCLASS ThreadInformationClass,
    PVOID ThreadInformation,
    ULONG ThreadInformationLength
);

The magic call:

NtSetInformationThread(
    NtCurrentThread(),    // ThreadHandle = -2 (current thread)
    0x11,                 // ThreadInformationClass = ThreadWow64Context
    NULL,                 // ThreadInformation = NULL
    0                     // ThreadInformationLength = 0
);

When called with ThreadInformationClass = 0x11 (or sometimes 0x17 on newer systems), NULL info, and 0 length, this call disables DEP for the current thread.

Finding SETP Gadgets with Mona

!mona setp

Output:

[*] SETP gadgets:
    Address: 0x7753b1a0
    Module: ntdll.dll
    Opcode: ff15a0b15377 (call dword ptr [ntdll.NtSetInformationThread])
    Arguments: NULL, 0x11, NULL, 0

Mona also provides ready-to-use SEH records:

!mona setp -cpb "\x00"

This generates a SEH record that calls NtSetInformationThread to disable DEP, then pops execution to the next SEH record.

Using SETP with SEH Overwrites

SETP is most commonly used in conjunction with SEH (Structured Exception Handler) overwrites:

SEH Record Layout:
┌─────────────┬─────────────┐
│ Next SEH Ptr │ SE Handler  │
│  (4 bytes)   │  (4 bytes)  │
└─────────────┴─────────────┘

Exploit Strategy:
1. Overwrite SE Handler with pointer to SETP gadget
2. The gadget calls NtSetInformationThread to disable DEP
3. Use "pop pop ret" to slide to next instruction
4. Next SEH points to shellcode on stack (now executable!)
# SETP + SEH exploit structure
nseh = "\x90\x90\x90\x90"                    # NOPs in next SEH
seh = struct.pack("<I", setp_gadget_addr)     # Points to SETP gadget
# ... padding ...
buffer += nseh + seh                           # Overwrite SEH record
buffer += shellcode                            # Shellcode on stack

SETP Gadget Opcodes to Look For

Opcode Pattern Description
FF 15 xx xx xx xx call dword ptr [NtSetInformationThread]
6A 11 push 0x11 (ThreadInformationClass)
6A 00 push 0
50 / 51 push eax / push ecx (NULL args)
FF 15 call [function_ptr]

Finding the exact gadget:

!mona find -s "\x6a\x11\x6a\x00\x50\x51\xff\x15" -m ntdll.dll

SETP vs SETK Comparison

Feature SETK SETP
Mechanism DLL load-time stack marking Runtime API call
Requires SEH No Typically yes
Module requirement SETK module must be loaded ntdll.dll (always loaded)
Reliability High (if module loaded) High (ntdll always present)
Windows version XP through 7 XP through 8+
Mona command !mona setk !mona setp

Recommendation: SETP is generally more reliable because ntdll.dll is always loaded in every Windows process. SETK depends on a specific module being loaded.


Heap Spray Technique

Heap spraying is a technique primarily used in browser-based exploits (Flash, JavaScript, PDF readers) to reliably place shellcode at a predictable memory location.

The Problem Heap Spray Solves

In classic stack buffer overflows, you control the stack and know where your shellcode lives. In browser exploits:

  1. You don’t directly control the stack
  2. Memory layout is less predictable
  3. You need a reliable way to place shellcode at a known address

Heap spray solves this by flooding the heap with copies of your payload, making it statistically certain that some memory region contains your shellcode.

How Heap Spray Works

┌─────────────────────────────────────────────────────┐
│                    Heap Layout                      │
│                                                     │
│  [Spray][Spray][Spray][Spray][Spray][Spray][Spray] │
│   ↑NOP     ↑NOP     ↑NOP     ↑NOP     ↑NOP     ↑NOP │
│   ↓Shellcode at predictable address                 │
│                                                     │
│  Target address: 0x0C0C0C0C (or 0x0F0F0F0F, etc.)  │
└─────────────────────────────────────────────────────┘

JavaScript Heap Spray (Classic)

The most common form uses JavaScript’s Array object and unescape():

// Classic JS Heap Spray
function spray() {
    // Create a huge block of NOPs (0x0C0C0C0C = slide byte)
    var nopSled = unescape(
        "%u0C0C%u0C0C" +           // Single NOP slide unit
        "%u0C0C%u0C0C".repeat(0x10000)  // ~64KB of NOPs
    );

    // Append shellcode (encoded as Unicode pairs)
    var shellcode = unescape(
        "%u9090%u9090%u9090%u9090" +  // More NOPs
        "%uXXXX%uXXXX%uXXXX%uXXXX"    // Your shellcode
    );

    // Full block: NOP sled + shellcode
    var block = nopSled + shellcode;

    // Spray the heap with many copies
    var sprayArray = new Array();
    for (var i = 0; i < 200; i++) {
        sprayArray[i] = block.substring(0, 0x40000);  // ~256KB each
    }
}

Key Addresses in Heap Spraying

Address Byte Value Use Case
0x0C0C0C0C 0x0C (slide) Most common, works on most systems
0x0F0F0F0F 0x0F (invalid x86 opcode → slide) Alternative when 0x0C is blocked
0x10101010 0x10 Less common, for specific targets
0xDEADBEEF — Debugging/identification

The 0x0C byte is special: it’s OR AH, CH in x86 — a valid but harmless instruction that doesn’t crash and doesn’t change EIP. It acts as a NOP slide in Unicode memory.

Flash Heap Spray

Flash (ActionScript) heap spray was extremely common in OSCP-era browser exploits:

// ActionScript 3 Heap Spray
function spray() {
    var coder:ByteArray = new ByteArray();
    var i:uint = 0;

    // NOP sled (0x0C0C0C0C)
    while (i < 0x200000) {
        coder.writeByte(0x0C);
        i++;
    }

    // Shellcode
    coder.writeByte(0x90); // NOP
    coder.writeByte(0x90);
    // ... rest of shellcode ...

    var blocks:uint = 200;
    var spray:Array = new Array();
    for (var j:uint = 0; j < blocks; j++) {
        spray[j] = coder.clone();
    }
}

Modern Heap Spray Considerations

Modern browsers have mitigations:

  • EGE (Executable Gap Enforcement): Prevents allocation in executable regions
  • ASLR in JavaScript engines: Randomizes heap layout
  • Safe Arrays: Prevent predictable array allocation

For OSCP, you’ll mostly encounter heap spray in:

  • Old Flash-based vulnerabilities
  • Legacy browser exploits (IE8 and below)
  • PDF reader exploits

3. ASLR Deep Understanding

What is ASLR?

ASLR (Address Space Layout Randomization) randomizes the memory addresses where key components of a process are loaded. This defeats exploits that rely on knowing the exact address of:

  • Return addresses on the stack
  • Function addresses in DLLs
  • SEH records
  • Heap allocations

Without ASLR, kernel32.dll might always load at 0x76000000. With ASLR, it could load at 0x74A20000, 0x76F10000, 0x73C80000, etc. — different every time.

How ASLR Randomizes Addresses

The Randomization Process

When Windows loads a module with ASLR enabled:

  1. The loader checks the PE header for the IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE flag (0x0040)
  2. If set, the loader generates a random offset
  3. The module is loaded at base_address + random_offset
  4. The random offset is aligned to 64KB (the page table granularity)
PE Optional Header → DllCharacteristics:
  Bit 13 (0x00002000) = IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY
  Bit 14 (0x00004000) = IMAGE_DLLCHARACTERISTICS_NX_COMPAT (DEP opt-in)
  Bit 15 (0x00008000) = IMAGE_DLLCHARACTERISTICS_NO_ISOLATION
  Bit 16 (0x00010000) = IMAGE_DLLCHARACTERISTICS_NO_SEH
  Bit 22 (0x00400000) = IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE
  Bit  7 (0x00000040) = IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE (ASLR)

Address Randomization Ranges

Component Randomization Range Entropy (bits)
PE Image Base ±256MB (32-bit) ~15-20 bits
Stack Base Random offset per process ~8-10 bits
Heap Base Random offset per process ~8-10 bits
PEB Address Random per process ~8 bits
DLL Load Order Can vary Low

Entropy and Predictability

Entropy measures the unpredictability of the randomization. Higher entropy = harder to guess.

32-bit ASLR Entropy Analysis:

Module Base Address:
┌──────────────────────────────────────────────┐
│  0x70000000 ─────────────────────────────────│
│         │                                    │
│         ├─ Random offset (up to 0x40000000)  │
│         │                                    │
│  0x7FFFFFFF ─────────────────────────────────│
│                                              │
│  ~1 GB range = ~30 bits of theoretical space │
│  But actual alignment reduces to ~15-20 bits  │
└──────────────────────────────────────────────┘

64-bit ASLR Entropy:
┌──────────────────────────────────────────────┐
│  Much larger address space                    │
│  ~28 bits of entropy for image base           │
│  Significantly harder to brute force          │
└──────────────────────────────────────────────┘

Entropy by Windows Version

Windows Version 32-bit Entropy 64-bit Entropy
Windows XP 0 (no ASLR) N/A
Windows Vista ~8 bits ~18 bits
Windows 7 ~15 bits ~28 bits
Windows 8+ ~15 bits ~28 bits
Windows 10+ ~15 bits ~28 bits

For OSCP: Most targets are 32-bit Windows XP/7. The 15-bit entropy means ~32,768 possible positions — too many for brute force in a single connection, but feasible with retry mechanisms.

Module-level vs System-level ASLR

Module-level ASLR

Each DLL/EXE can independently enable or disable ASLR through its PE header:

!mona modules
Name              DEP    ASLR  REBASE  Safe
==============    =====  ====  ======  =====
kernel32.dll      Yes    Yes   Yes     Yes
ntdll.dll         Yes    Yes   Yes     Yes
user32.dll        Yes    Yes   Yes     Yes
custom.dll        Yes    No    No      No    ← Not ASLR'd!

A module without ASLR loads at the same address every time — a goldmine for exploit development.

System-level ASLR

Windows also randomizes:

  • The PEB (Process Environment Block) address
  • Stack cookie (return address guard)
  • Heap base address

Even if individual modules aren’t ASLR’d, the system-level randomization adds some unpredictability.

The REBASE Flag

The REBASE column in Mona’s output indicates whether the module can be relocated:

REBASE Meaning
Yes Module has a relocation table and CAN be ASLR’d
No Module lacks relocation table — CANNOT be relocated

Critical insight: If REBASE = No, the module cannot use ASLR even if the system tries. It will always load at its preferred base address. These are your targets.


4. ASLR Bypass Techniques

Using Non-ASLR Modules

The simplest ASLR bypass: Find a module that doesn’t use ASLR and use addresses from it.

Finding Non-ASLR Modules

!mona modules

Look for modules where ASLR = No:

Name              Path                                    DEP    ASLR  REBASE
==============    ======================================= =====  ====  ======
kernel32.dll      C:\Windows\System32\kernel32.dll        Yes    Yes   Yes
ntdll.dll         C:\Windows\System32\ntdll.dll           Yes    Yes   Yes
urlmon.dll        C:\Windows\System32\urlmon.dll          Yes    No    No     ← TARGET
shdocvw.dll       C:\Windows\System32\shdocvw.dll         No     No    No     ← TARGET

Why Some Modules Lack ASLR

  1. Old modules: Written before ASLR was common
  2. Third-party modules: Developers didn’t enable /DYNAMICBASE
  3. Compatibility: Some modules can’t handle relocation
  4. No relocation table: The linker didn’t generate one

Using Non-ASLR Module Addresses

Once you find a non-ASLR module:

!mona find -s "\xff\x25" -m urlmon.dll
[+] Results saved to find.txt
    0x771b2a3c : jmp [ebp-0x4]
    0x771b5e10 : jmp [eax]

These addresses are stable across reboots — you can hardcode them in your exploit.

Common Non-ASLR Modules on OSCP Machines

Module Typical Base Notes
shdocvw.dll 0x76340000 Very common, often no DEP either
urlmon.dll Varies Check per target
msvcrt.dll Varies Sometimes non-ASLR on older systems
Custom DLLs Preferred base Third-party modules often lack ASLR

Information Leak Exploitation

When all modules use ASLR, you can leak an address from the target process and calculate other addresses.

How Information Leaks Work

┌─────────────────────────────────────────────────────┐
│  Step 1: Trigger the vulnerability                   │
│         ↓                                            │
│  Step 2: The bug leaks a memory address              │
│         (e.g., error message, crafted response)      │
│         ↓                                            │
│  Step 3: Extract the leaked address                  │
│         (e.g., 0x7753b1a0 is in ntdll.dll)           │
│         ↓                                            │
│  Step 4: Calculate the module base                   │
│         leaked_addr - offset = module_base           │
│         ↓                                            │
│  Step 5: Calculate other addresses                   │
│         module_base + target_offset = target_addr    │
│         ↓                                            │
│  Step 6: Use the calculated address in your exploit  │
└─────────────────────────────────────────────────────┘

Common Leak Sources

Source How It Leaks Example
Error messages Exception handler prints address “Exception at 0x7753b1a0”
Crafted responses Application echoes memory Debug output, logging
SEH records Exception record contains addresses SEH chain traversal
Format strings %x reads stack values printf(user_input)
Use-after-free Dangling pointer reveals address Heap metadata exposure

Example: Leaking from an Error Message

# First request: Trigger a controlled crash that leaks an address
# The error response contains: "Exception at 0x7753b1a0 in ntdll.dll"

leaked_address = 0x7753b1a0
ntdll_offset = 0x53b1a0  # Known offset within ntdll
ntdll_base = leaked_address - ntdll_offset  # = 0x77000000

# Now calculate the address of your target function
target_function_offset = 0x123456
target_address = ntdll_base + target_function_offset

Mona’s Leak Analysis

!mona compare -f <filename> -a <address>

This helps you find the offset of a leaked address within a module.

Multi-Stage Exploit with Info Leak

For vulnerabilities that allow multiple requests:

import struct

# Stage 1: Leak an address
leak_request = create_leak_payload()
response = send_request(leak_request)
leaked_addr = parse_address_from_response(response)

# Calculate module base
module_base = leaked_addr - known_offset

# Stage 2: Exploit with calculated addresses
exploit_addr = module_base + gadget_offset
exploit_request = create_exploit_payload(exploit_addr)
send_request(exploit_request)

Partial Overwrite with Brute Force

When you can only overwrite part of an address, you can brute-force the unknown bytes.

The Concept

Full address:    0x7753b1a0
                 └────┬────┘
                 Known part (you control)

If you can only overwrite the LOW 2 bytes:
                 0x7753____
                 Unknown   ← Brute force these 16 bits (65,536 possibilities)

If you can only overwrite the LOW 1 byte:
                 0x7753b1__
                 Unknown   ← Brute force these 8 bits (256 possibilities)

Partial Overwrite Scenarios

Controllable Bytes Possibilities Feasibility
1 byte (8 bits) 256 Easy — single connection often works
2 bytes (16 bits) 65,536 Feasible with retry loop
3 bytes (24 bits) 16,777,216 Difficult — needs many retries
4 bytes (32 bits) 4,294,967,296 Impractical

When Partial Overwrite Works

  1. You control the lower bytes of a pointer (common in 32-bit little-endian overwrites)
  2. The target module loads in a predictable high-range (e.g., always 0x77xxxxxx)
  3. You can retry the exploit multiple times (reconnectable service)

Example: 2-Byte Partial Overwrite

import struct
import socket
import time

target = "192.168.1.100"
port = 80

# We know the high 2 bytes of our target address
high_bytes = 0x7753  # ntdll.dll base (known from prior research)

# Brute force the low 2 bytes
for low_bytes in range(0x0000, 0xFFFF):
    addr = (high_bytes << 16) | low_bytes

    payload = b"A" * offset
    payload += struct.pack("<I", addr)  # Little-endian overwrite

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((target, port))
        s.send(payload)
        s.close()
        time.sleep(0.1)

        # Check if we got a shell (or different crash behavior)
        if check_success():
            print(f"Success at address: {hex(addr)}")
            break
    except:
        continue

Mona’s Partial Overwrite Help

!mona suggest

This command suggests exploit strategies based on the current crash analysis, including partial overwrite opportunities.


5. Combined DEP + ASLR Bypass

When both DEP and ASLR are active, you need a two-pronged approach.

Strategy Matrix

DEP Status ASLR Status Strategy
Off Off Standard shellcode on stack — no bypass needed
On Off SETP/SETK + non-ASLR module addresses
Off On Info leak or non-ASLR module + standard shellcode
On On SETP/SETK + info leak / non-ASLR module

The Combined Approach

┌─────────────────────────────────────────────────────────┐
│           Combined DEP + ASLR Bypass                     │
│                                                          │
│  1. Find non-DEP, non-ASLR module                       │
│     → Best case: one module solves both problems        │
│                                                          │
│  2. If no such module exists:                           │
│     a. Use SETP to disable DEP                           │
│     b. Use info leak to defeat ASLR                      │
│     c. Or: partial overwrite + retry for ASLR            │
│                                                          │
│  3. Alternative: ROP chain                              │
│     a. Find gadgets in ASLR'd modules                    │
│     b. Chain: VirtualProtect → execute shellcode         │
│     c. Requires reliable address resolution              │
└─────────────────────────────────────────────────────────┘

ROP-Based Bypass (Advanced)

When both protections are active and no easy bypass exists, Return-Oriented Programming (ROP) is the nuclear option:

ROP Chain for DEP Bypass:
┌─────────────────────────────────────┐
│ 1. pop eax; ret                     │  ← Load address of stack
│ 2. pop ebx; ret                     │  ← Load PAGE_EXECUTE_READWRITE
│ 3. pop ecx; ret                     │  ← Load page size
│ 4. pop edx; ret                     │  ← Load dummy
│ 5. call VirtualProtect              │  ← Change stack to executable
│ 6. jmp [stack]                      │  ← Jump to shellcode
└─────────────────────────────────────┘

Mona can generate ROP chains:

!mona rop -cm call -cpb \x00 -ci dword -cpb \x00,\x0a,\x0d

For OSCP: ROP is rarely required. Focus on SETP + non-ASLR modules first.


6. Decision Tree

flowchart TD
    A[Start: Vulnerability Found] --> B{Check DEP Status}
    B -->|DEP Off| C{Check ASLR Status}
    B -->|DEP On| D{SETK Module Loaded?}

    C -->|ASLR Off| E["✅ Standard Exploit<br/>Shellcode on stack, known addresses"]
    C -->|ASLR On| F{Non-ASLR Module?}
    F -->|Yes| G["✅ Use Non-ASLR Module<br/>Gadgets from fixed-address module"]
    F -->|No| H{Info Leak Possible?}
    H -->|Yes| I["✅ Info Leak + Calculation<br/>Leak address, compute others"]
    H -->|No| J{Retryable Target?}
    J -->|Yes| K["⚠️ Partial Overwrite + Brute Force<br/>Retry with different low bytes"]
    J -->|No| L["❌ Very Difficult<br/>Consider ROP or alternative vuln"]

    D -->|Yes| M["✅ SETK Bypass<br/>Stack is executable<br/>Check ASLR next"]
    D -->|No| N{Use SETP?}

    N -->|Yes| O["✅ SETP via SEH Overwrite<br/>NtSetInformationThread disables DEP"]
    N -->|No| P{Non-DEP Module?}

    P -->|Yes| Q["✅ Redirect to Non-DEP Module<br/>Find gadgets in executable module"]
    P -->|No| R{Heap Spray Feasible?}

    R -->|Yes| S["⚠️ Heap Spray<br/>Browser/Flash exploit context"]
    R -->|No| T["❌ Hard Bypass Needed<br/>Consider ROP chain"]

    M --> C
    O --> C
    Q --> C
    S --> C

Quick Decision Flow

1. Run: !mona modules
   ↓
2. Any module with DEP=No AND ASLR=No?
   → YES: Use it. Problem solved.
   → NO: Continue...
   ↓
3. Any module with DEP=No?
   → YES: Use for code execution, solve ASLR separately
   → NO: Continue...
   ↓
4. Run: !mona setk
   → Found? Use SETK, stack becomes executable
   → Not found? Continue...
   ↓
5. Run: !mona setp
   → Found? Use SETP with SEH overwrite
   → Not found? Consider ROP
   ↓
6. For ASLR: Any module with ASLR=No?
   → YES: Use its addresses
   → NO: Need info leak or partial overwrite

7. Mona Commands for DEP/ASLR Analysis

Essential Commands

Command Purpose
!mona modules List all modules with DEP/ASLR/REBASE status
!mona config -set workingfolder c:\mona\%p Set up Mona workspace
!mona suggest Suggest exploit strategies based on crash
!mona Seth Show SEH chain

DEP-Specific Commands

Command Purpose
!mona setk Find modules with SETK flag
!mona setp Find SETP gadgets in ntdll
!mona setp -cpb "\x00" SETP gadgets without null bytes
!mona find -s "\xff\x25" -m <module> Find JMP [REG] in module

ASLR-Specific Commands

Command Purpose
!mona modules Check ASLR column
!mona find -s "<opcode>" -m <non-aslr-module> Find stable addresses
!mona compare -f <file> -a <addr> Calculate offset from leaked addr

ROP Chain Generation

Command Purpose
!mona rop -cm call Find ROP gadgets with call instructions
!mona rop -cm pop Find ROP gadgets with pop instructions
!mona rop -ci dword Only use dword pointers
!mona rop -cpb \x00,\x0a,\x0d Exclude bad characters

Finding Useful Gadgets

# Find JMP instructions
!mona find -s "\xff\x25" -m <module>    # JMP [dword ptr ds:[eax]]
!mona find -s "\xff\x23" -m <module>    # JMP [ebx]
!mona find -s "\xff\x15" -m <module>    # CALL [dword ptr ds:[xxx]]

# Find POP/RET for ROP
!mona find -s "\x58\x59\x5a\x5b\x5a\x59\x58\xc3" -m <module>

# Find specific API references
!mona find -s "VirtualProtect" -m <module> -type import

8. OSCP Relevance

How Often Do You Encounter These?

Protection Frequency on OSCP Typical Targets
DEP only Common Windows XP/7 services, browser vulns
ASLR only Uncommon Some Windows 7+ targets
Both DEP + ASLR Rare Hardened Windows targets
Neither Very Common Windows XP, poorly configured services

Typical OSCP Scenarios

Scenario 1: Windows XP Service (Most Common)

Target: Windows XP SP3
Service: Custom vulnerability
DEP: Off (or opt-in, service didn't opt in)
ASLR: Off (XP has minimal ASLR)

Strategy: Standard stack buffer overflow with shellcode

Scenario 2: Windows 7 Browser Exploit

Target: Windows 7 + IE8/IE9
Vuln: Memory corruption in browser component
DEP: On (hardware DEP)
ASLR: Partial (some modules ASLR'd, some not)

Strategy:
1. !mona modules → find non-DEP, non-ASLR module
2. Use SETP if needed
3. Heap spray for reliable code placement

Scenario 3: Windows 7 Service with SEH Overwrite

Target: Windows 7 SP1
Vuln: SEH overwrite in service
DEP: On
ASLR: On for system modules

Strategy:
1. !mona setp → get SETP gadget
2. Overwrite SEH with SETP gadget
3. Next SEH points to shellcode
4. DEP disabled, shellcode executes

Exam Tips

  1. Always run !mona modules first — it tells you everything about DEP/ASLR status
  2. Prefer SETP over SETK — ntdll is always loaded, SETK modules may not be
  3. Non-ASLR modules are your best friend — addresses are stable and reusable
  4. Don’t overthink ROP — OSCP rarely requires full ROP chains
  5. Document your bypass strategy — examiners want to see your reasoning

Common OSCP Targets and Their Protections

Target OS DEP ASLR Recommended Bypass
SickOS services Windows XP Off Off Standard exploit
WPAD Windows 7 On Partial SETP + non-ASLR module
DNS SRV Windows 7 On Partial SETP + SEH overwrite
HTTPD Windows XP Off Off Standard exploit
Various browser vulns Windows 7 On On Heap spray + SETP

9. Quick Reference Cheat Sheet

DEP Bypass Quick Reference

┌──────────────────────────────────────────────────────────┐
│  DEP BYPASS DECISION TREE (Simplified)                    │
│                                                           │
│  !mona modules → Any DEP=No?                             │
│    YES → Use that module for code execution              │
│    NO  → !mona setk → SETK module loaded?               │
│      YES → Stack is executable, use standard shellcode   │
│      NO  → !mona setp → Use SETP gadget with SEH        │
│                                                           │
│  SETP Gadget Pattern:                                    │
│    push 0x11  (ThreadInformationClass)                    │
│    push 0     (ThreadInformationLength)                   │
│    push 0     (ThreadInformation)                         │
│    push -2    (ThreadHandle = current thread)            │
│    call NtSetInformationThread                            │
└──────────────────────────────────────────────────────────┘

ASLR Bypass Quick Reference

┌──────────────────────────────────────────────────────────┐
│  ASLR BYPASS DECISION TREE (Simplified)                   │
│                                                           │
│  !mona modules → Any ASLR=No?                            │
│    YES → Use addresses from that module (stable!)        │
│    NO  → Can you leak an address?                        │
│      YES → Calculate base, derive other addresses        │
│      NO  → Can you retry multiple times?                 │
│        YES → Partial overwrite + brute force             │
│        NO  → Consider ROP or alternative vulnerability   │
│                                                           │
│  Stable Address Sources:                                  │
│    - Modules with ASLR=No and REBASE=No                  │
│    - Calculated from info leaks                           │
│    - Hardcoded for well-known modules on specific OS     │
└──────────────────────────────────────────────────────────┘

Mona Command Quick Reference

# Setup
!mona config -set workingfolder c:\mona\%p

# Analysis
!mona modules              # DEP/ASLR status of all modules
!mona suggest              # Suggested exploit strategies
!mona Seth                 # SEH chain analysis

# DEP Bypass
!mona setk                 # SETK modules
!mona setp                 # SETP gadgets
!mona setp -cpb "\x00"    # SETP without null bytes

# ASLR Bypass
!mona find -s "<bytes>" -m <module>  # Find opcodes in module
!mona compare -f <file> -a <addr>    # Offset calculation

# ROP
!mona rop -cm call -cpb \x00         # ROP gadgets

Bad Characters to Always Consider

Common bad characters: \x00, \x0a, \x0d

When using SETP/SEH:
- \x00 (null) — string terminator
- \x0a (LF) — line terminator
- \x0d (CR) — carriage return

Always verify with:
!mona compare -f <before> -a <addr>
!mona compare -f <after>  -a <addr>

Summary

Bypassing DEP and ASLR is about finding the path of least resistance:

  1. Check for easy wins first: Non-DEP + non-ASLR modules solve both problems at once
  2. SETP is your most reliable DEP bypass: ntdll.dll is always loaded, SETP gadgets are always available
  3. Non-ASLR modules are gold: Stable addresses mean no calculation needed
  4. Info leaks unlock everything: One leaked address can reveal the entire memory layout
  5. ROP is a last resort: Powerful but complex — save it for when simpler methods fail

On the OSCP exam, most Windows targets will have at least one protection weakness you can exploit. The key is systematic analysis with Mona and knowing which technique to apply in each situation.


Last updated: 2026-09-01 | OSCP Fixing Exploits — Module 10, Topic 15