Skip to main content
Be Bitwise

From Bug to Exploit

Vulnerability Discovery Case Studies · VR Analysis & Discovery track

9 min read

In this module

Crossing the Line from Discovery to Demonstration

Finding a vulnerability is half the work. To demonstrate real-world impact, assess severity accurately, and give the vendor something actionable, you need a proof-of-concept exploit. This lesson walks through taking a confirmed vulnerability and building a working PoC — navigating constraints, mitigations, and the practical difficulty of exploitation that actually holds together under realistic conditions.

Starting Point: A Confirmed Heap Buffer Overflow

Continuing from Lesson 1's case study, we have a confirmed heap buffer overflow in libimgdec. The ASan report tells us:

  • Bug class: Heap buffer overflow (write)
  • Root cause: Integer overflow in width * height * 4 causes undersized allocation
  • Overflow size: Attacker-controlled (depends on image dimensions and data)
  • Overflow direction: Forward (writing past the end of the allocation)

The first question: what can we achieve with this overflow?

Understanding Constraints

Every vulnerability has constraints that determine exploitability:

What do we control? The overflow writes decompressed image data into the heap. We control:

  • The size of the undersized allocation (via the overflowed dimension calculation)
  • The content of the overflow (the image pixel data, which we craft)
  • The total overflow length (determined by the "real" image dimensions)

What is adjacent in memory? The heap allocator places our undersized buffer among other allocations. What is immediately after our buffer determines what we overwrite. This depends on:

  • The allocator implementation (glibc's ptmalloc2, jemalloc, tcmalloc)
  • The program's allocation pattern (what else is allocated at the same time)
  • The exact size of our undersized allocation (different size classes have different bin layouts)

What mitigations are active? Modern systems have multiple exploit mitigations:

  • ASLR - randomizes library and heap addresses
  • Stack canaries - protect return addresses (not relevant here; this is heap)
  • Heap hardening - modern allocators include metadata checks
  • NX/DEP - heap memory is not executable
Mitigations Are Not Walls, They Are Speed Bumps

Each mitigation increases the difficulty of exploitation but rarely makes it impossible. ASLR requires an information leak to defeat. Heap hardening can sometimes be bypassed by careful heap grooming. NX is bypassed by ROP chains (Return-Oriented Programming). The vulnerability researcher's job is to assess whether the combination of mitigations makes exploitation impractical or merely more complex.

Heap Grooming: Controlling What You Overwrite

Heap grooming (or heap shaping/massaging) is the technique of manipulating the heap layout so that a specific target object is adjacent to the vulnerable buffer. The goal is to place a high-value target (function pointer, vtable pointer, object with security-relevant fields) immediately after the overflowed buffer.

text
// Conceptual heap grooming strategy:
// 1. Allocate many objects of the target size
// 2. Free alternating objects to create "holes"
// 3. Trigger the vulnerable allocation (fills a hole)
// 4. The adjacent occupied slots contain target objects
// 5. Overflow overwrites the adjacent target object
// In our image decoder scenario:
// The library allocates palette structures alongside pixel buffers
// If we can make a palette allocation adjacent to our pixel buffer...
// Craft input that triggers these allocations in sequence:
// [palette chunk] -> malloc(palette_size) -> fills bin
// [image chunk] -> malloc(overflowed_size) -> adjacent to palette
// Overflow image data -> overwrites palette structure

The palette structure might contain a function pointer for colour transformation. Overwriting that pointer with an attacker-controlled value hijacks execution when the library calls the transformation function.

Developing the PoC: Step by Step

Step 1: Achieve controlled crash

First, demonstrate basic control. Craft an image where the overflow writes a recognisable pattern (0x41414141) over adjacent memory:

python
# PoC generator (Python)
import struct
def create_poc():
# File header
data = b'\x89IMGD\r\n\x1a\n' # Magic bytes
# Header chunk: dimensions that cause integer overflow
# width=0x10000, height=0x10001 -> width*height*4 overflows to 0x40000
# But actual data will be much larger
header = struct.pack('<II', 0x10000, 0x10001)
data += make_chunk(b'IHDR', header)
# Image data: decompresses to attacker-controlled content
# This will overflow the undersized allocation
pixel_data = b'\x41' * 0x100000 # Large payload of 'A's
data += make_chunk(b'IDAT', compress(pixel_data))
# End chunk
data += make_chunk(b'IEND', b'')
return data

Run this PoC and check the crash: if the program crashes with RIP/PC pointing to 0x4141414141414141, you have achieved control-flow hijack. If it crashes writing to that address, you have a write-what-where primitive.

Step 2: Information leak (defeat ASLR)

Most modern exploits need to defeat ASLR before they can redirect execution to useful code. Look for ways to leak memory addresses:

  • Heap metadata leak - if the overflow can partially overwrite a data structure that is later sent back to the user (e.g., in error messages or response data), you can leak heap addresses
  • Stack address leak - some libraries store stack pointers in heap objects
  • Separate info-disclosure bug - another vulnerability that leaks addresses

For our case study, suppose the library has a "get image info" function that returns metadata from parsed chunks. If we can overflow into a metadata structure and replace a string pointer with a heap address, the library will read from that address and return the bytes as a string, leaking heap contents.

Step 3: Construct the exploit payload

With ASLR defeated (we know where libc is loaded), construct a payload that achieves code execution. Since the heap is not executable (NX), we use ROP:

python
# Construct exploit payload
libc_base = leaked_address - known_offset
# ROP gadgets in libc
pop_rdi = libc_base + 0x23b6a # pop rdi; ret
bin_sh = libc_base + 0x1b3e1a # "/bin/sh" string
system = libc_base + 0x4f440 # system() function
# Payload that overwrites a function pointer
# When the function pointer is called, it starts our ROP chain
payload = b'\x00' * overflow_offset # Padding to reach target
payload += struct.pack('<Q', pop_rdi)
payload += struct.pack('<Q', bin_sh)
payload += struct.pack('<Q', system)

That payload skips two steps a real exploit can't. First, overwriting a function pointer gives you one jump, not a stack: when the program calls through the pointer, RSP still points at the real stack, so the pop rdi would pop whatever happens to be there. You point the function pointer at a stack pivot gadget instead (something like xchg rax, rsp; ret when RAX holds the address of your heap object), and the chain lives in your heap data. Second, glibc's system() uses SSE instructions that fault if RSP isn't 16-byte aligned at the call, so chains usually start with a lone ret to shift the stack by 8 bytes.

Here's the chain as it sits in the heap after the pivot, using the lesson's offsets on an illustrative libc base of 0x7ffff79e4000. The ret comes free: it's the byte straight after pop rdi in the same gadget.

ROP Chain Layout

Stack (SP →)
1.0x7FFFF7A07B6B→ret (alignment)◄ active
2.0x7FFFF7A07B6A→pop rdi; ret
3.0x7FFFF7B97E1A→/bin/sh string
4.0x7FFFF7A33440→system
Code (Gadgets)
0x7FFFF7A07B6Bret (alignment)
ret
0x7FFFF7A07B6Apop rdi; ret
pop rdi; ret
0x7FFFF7B97E1A/bin/sh string
data: popped into rdi
0x7FFFF7A33440system
system(rdi)
Each RET pops the next address from the stack and jumps to it, chaining gadgets together.

Step 4: Verify reliability

Run the exploit multiple times. A reliable PoC should work consistently under documented conditions (specific OS version, library version, ASLR state). If reliability is low, investigate why:

  • Heap layout may vary between runs (need better heap grooming)
  • Timing-dependent behaviour (if multi-threaded)
  • Partial overwrites that sometimes corrupt metadata (reduce overflow size)

Bypassing Mitigations in Practice

For the PoC, you may need to address specific mitigations:

ASLR bypass - find an information disclosure vulnerability or use a partial overwrite (if the overflow can modify only the low bytes of a pointer, the high bytes from ASLR remain valid).

Heap hardening - modern allocators check metadata integrity. Avoid corrupting heap chunk headers by precisely controlling the overflow length to overwrite only user data in the adjacent allocation, not the allocator's metadata.

Modern glibc Heap Protections

Recent glibc releases closed several classic shortcuts. Safe-linking (2.32) mangles tcache and fastbin next pointers with the address they're stored at, so poisoning one now needs a heap leak first. The __malloc_hook and __free_hook variables were removed in 2.34, taking away the favourite one-write target. Chunk size and double-free checks catch many sloppy overwrites. Overwriting application data in the neighbouring chunk, as this case study does, sidesteps most of them.

CFI (Control Flow Integrity) - if the target uses CFI, indirect calls through corrupted function pointers will be caught. May need to find a different exploitation primitive (data-only attacks that change security-relevant variables without hijacking control flow).

Writing Reliable Exploits

Reliability comes from minimising assumptions:

  • Deterministic heap layout - groom the heap to ensure predictable object placement
  • Handle multiple allocation sizes - test across different allocator size classes
  • Graceful failure - if the exploit detects unexpected conditions (wrong address, wrong layout), abort cleanly rather than crashing the target
  • Document everything - exact OS version, compiler, library version, and ASLR state

Responsible Disclosure Walkthrough

With a working PoC, proceed through coordinated disclosure:

  1. Prepare the report - vulnerability description, affected versions, PoC file, suggested fix
  2. Contact the vendor - use their security contact, encrypt with their PGP key
  3. Include the minimal PoC - the crash PoC (not the full exploit), which is sufficient to demonstrate the bug
  4. Propose a timeline - "We plan to disclose in 90 days or upon patch release"
  5. Collaborate on the fix - review the vendor's proposed patch for completeness
  6. Publish the advisory - after the patch is released, publish details with credit
PoC vs. Full Exploit

For responsible disclosure, you typically provide a crash PoC rather than a full code-execution exploit. The crash PoC proves the vulnerability is real and helps the vendor reproduce it. A full exploit is unnecessary for this purpose and could be misused if the report is intercepted. Save the full exploit analysis for your own notes and conference presentations after the patch is widely deployed.

The Cycle Continues

Finding one vulnerability often leads to more. During this case study, we observed:

  • The same integer overflow pattern likely exists in other image dimension calculations
  • The library's chunk parsing trusts length fields throughout
  • Error handling paths may have resource leaks

Apply variant analysis (Source Code Auditing): write CodeQL queries or Semgrep rules that capture the patterns you found, and run them across the entire codebase. The developer who made one integer overflow mistake likely made others. Each new finding builds your understanding of the codebase's weaknesses and makes subsequent discoveries faster.

That's the cycle: target selection → analysis → discovery → PoC → variant analysis → next target. The techniques from Introduction to Vulnerability Research through Advanced Fuzzing Techniques are what drive it.