KawaiiconCTF 2026 - professors-hash

How can something as simple as a dictionary get your computer hacked?

professors-hash was an advanced pwn challenge that I wrote for Kawaiicon CTF, organized by my friends at VuwCTF in New Zealand. During the event, players were tasked with exploiting a custom templated hashmap library written in C. Players were provided the C source code for the hash table as well as the compiled executable binary and libc used on the server, and were tasked to obtain a remote shell through the program and read the flag on the filesystem. This was my first time really playing with glibc internals in a pwn context, and I recieved a lot of great advice from my friend cbass, who taught me about the interesting libc details that made the solution path possible. In this author writeup, I will explain the inspiration and mechanisms surrounding this binary exploitation challenge.

The Inspiration

This challenge was inspired by my continued musings about hash tables, one of my favorite data structures. Several months ago, I took a look at a hashmap implementation from my friend’s CS lecture, and noticed a some of really cursed bugs in the code, and wanted to turn the concept into a CTF challenge. So, as an exercise, I implemented a custom hashmap library in C, and carefully analyzed how a simple bug could result in a complete takeover by an attacker. My favorite finding ended up being a pwn challenge at Kawaiicon CTF. In order to solve this challenge, we need to first understand how a hash table works.

What Is a Hash Table?

A hash table is a data structure that implements an associative key-value store (otherwise known as a dictionary or a map). Essentially, a hash table uses a special technique called hashing to look up, insert, and remove key-value pairs quickly. Instead of searching through the entire list of entries for the requested key, a hash table first passes the key through a hash function to compute an integer index into an array of slots or buckets. From there, the algorithm can directly search the exact slot where the data lives, improving up lookup time. The hash function should deterministically map keys to a uniform distribution of integers, so that different keys will get distributed to different buckets, maintaining an even load on the data structure. Internally, my implementation uses a separately-managed array list of keys and values behind each slot index1.

How Did I Design It in C?

I wanted to make a hashmap library that could be customized to operate over a variety of keys and values, abstracting away the core search algorithms from the specifics of the data behing handled. In C, there are two common approaches to writing type-generic code.

The first approach is to make the core functions completely type-agnostic using void pointers, requiring the user to fully specify how to manipulate the data at runtime (through parameters such as the data size, hash/comparison functions pointers, etc.). This void * pattern is ubiquitous in the C standard library: some examples that come to mind are the memmem, qsort, and malloc functions (don’t ask me why). The second approach uses preprocessor macros to generate a concrete implementation of the data structure at compile-time. This results in native functions and types tailored for the specific use case, which do not require constantly juggling metadata about the data being passed around. This is the approach I decided to go with.2

I created a special template C file which would generate the types and functions for the hashmap based on provided preprocessor macros: including hashmap.c would define struct types and functions based on the provided HASHMAP_KEY_TYPE, HASHMAP_VALUE_TYPE, and so on.

The C Implementation

Finally, we’re ready to take a look at the actual code. The template creates a custom heap-allocated struct for our hashmap, which contains slot pointers. Here is the struct layout for our hashmap:

typedef struct HASHMAP_LABEL(_hashmap) HASHMAP_LABEL(_hashmap_t);

struct HASHMAP_LABEL(_hashmap) {
    HASHMAP_VALUE_TYPE *value_slots[HASHMAP_NUM_SLOTS];
    HASHMAP_KEY_TYPE *key_slots[HASHMAP_NUM_SLOTS];
    size_t slot_capacities[HASHMAP_NUM_SLOTS];
    size_t slot_sizes[HASHMAP_NUM_SLOTS];
};

To determine the slot that a given key belongs to, we run our hash function, and mod it to fit within the number of slots we have. Once we know the slot index, we use our equality comparator to check if we have a match in the key array.

static size_t
HASHMAP_INTERNAL_LABEL(_hashmap_slot_index)(HASHMAP_KEY_TYPE const *key) {
    return (size_t)(HASHMAP_HASH_FUNC(key) % HASHMAP_NUM_SLOTS);
}

static size_t
HASHMAP_INTERNAL_LABEL(_hashmap_slot_find_index)(HASHMAP_LABEL(_hashmap_t) const *map,
                                                  size_t slot_index,
                                                  HASHMAP_KEY_TYPE const *key) {
    for (size_t i = 0; i < map->slot_sizes[slot_index]; i++) {
        if (HASHMAP_KEY_CMP_FUNC(&map->key_slots[slot_index][i], key) == 0) {
            return i;
        }
    }
    return SIZE_MAX; // entry not found
}

With these primitives, we can easily implement our core map operations. It’s fairly straightforward, and the exact details aren’t necessary for the challenge, so I won’t show all of the source code here. Here’s a taste of what the code looks like for the get operation:

int
HASHMAP_LABEL(_hashmap_get)(HASHMAP_LABEL(_hashmap_t) const *map,
                           HASHMAP_KEY_TYPE const *key,
                           HASHMAP_VALUE_TYPE *value_out) {
    size_t slot_index;
    size_t entry_index;

    if (!map || !key || !value_out) return 0;

    slot_index = HASHMAP_INTERNAL_LABEL(_hashmap_slot_index)(key);
    entry_index = HASHMAP_INTERNAL_LABEL(_hashmap_slot_find_index)(map,
                                                                   slot_index,
                                                                   key);
    if (entry_index == SIZE_MAX) return 0; // not found

    *value_out = map->value_slots[slot_index][entry_index];
    return 1; // success
}

Just to recap, this is what the memory looks like when we retrieve a value associated with a given key:

getting a value from a hash table.

And there we have it! Using this library, we can generate concrete hashmap implementations. Since the key and value types are provided to the template, the generated code should be type-aware, and reject any code that doesn’t pass in the correct data types at compile-time. Our library doesn’t have any glaringly obvious bugs, so what could possibly be wrong?

The Professor’s Hash Table

The main entrypoint of the challenge runs a simple demo of the hash table library, allowing users to insert and query entries in a table. Our professor’s demo defines two datatypes: a str255 pascal string, as well as a bin256 data type, each with a fixed size of 256 bytes. These structs are used as the key and value types of the system, respectively.

typedef struct str255 {
    uint8_t size; // the string's length, from 0-255
    char data[255]; // the data
} str255_t;

typedef struct bin256 {
    uint8_t data[256];
} bin256_t;

Then, we invoke the template in the preprocessor to generate our str255-to-bin256 mapping.

#define HASHMAP_TYPENAME professors_map
#define HASHMAP_NUM_SLOTS 256
#define HASHMAP_KEY_TYPE str255_t
#define HASHMAP_VALUE_TYPE bin256_t
#define HASHMAP_HASH_FUNC professors_hash_string
#define HASHMAP_KEY_CMP_FUNC professors_key_cmp
#include "hashmap.c"
#undef HASHMAP_KEY_CMP_FUNC
#undef HASHMAP_HASH_FUNC
#undef HASHMAP_VALUE_TYPE
#undef HASHMAP_KEY_TYPE
#undef HASHMAP_NUM_SLOTS
#undef HASHMAP_TYPENAME

These data types are quite innocuous, the code compiles and runs, so what could possibly go wrong? Well, as the challenge name hints, everything falls apart when we look at the professor’s hash function.

const double HASH_BASE = 257.0;
const double HASH_MOD = 1000000009.0;

/**
 * Uses the professor's original floating-point polynomial hash.
 */
int
professors_hash_string(str255_t const *key) {
    str255_t const *string = key;

    // dear professor... why?
    double h = 0.0;
    int len = string->size;
    for (int i = 0; i < len; i++) {
        char c = string->data[i];
        h = fmod(h * HASH_BASE + (double)c, HASH_MOD);
    }

    return (int)h;
}

This code is extremely scuffed with its use of floating-point numbers to calculate hashes. This is a big indicator of code smell, but, contrary to popular belief, the use of doubles here doesn’t actually impact the determinism of the hash function[3]. This code falls apart for a different reason: signedness. The chars in the string are treated as signed integers, which could be negative if their byte values exceed 127. This case would never be encountered with normal ASCII input, which is why the code didn’t fail during basic testing.

Additionally, I’ve been kinda lying to you. The C math library’s fmod function, as well as the % operator, don’t actually calculate the mathematical modulo; they calculate the remainder of the division3. The remainder x % y will always have the same sign as the dividend x, meaning we can obtain negative indices through this computation. As a final blow, the HASHMAP_NUM_SLOTS parameter is is defined with the raw integer literal 256, which is also signed; this means that C will never promote the slot index HASHMAP_HASH_FUNC(key) % HASHMAP_NUM_SLOTS to an unsigned integer until it is too late. The array requires indices on the range [0, 256), but due to the signed integer bug, we’re actually able to access negative indices too, on the range (-256, 256). This means that an attacker can trigger out of bounds (negative) access on the hash table slot array.

Exploiting the Hash Table

Okay, we’ve identified an out of bounds bug in the hash map: malicious key strings can hash into negative slot indices. But how is this exploitable, exactly? The pointer topology of the hash table is actually quite awkward; we aren’t actually able to directly read or write out of bounds using this negative hash index. Recall that the hash table struct stores an array of pointers to slot arrays: in the put function, we can only write to a specific index map->value_slots[slot_index][entry_index] once we identify a matching index for our key in map->key_slots[slot_index]. If slot array pointers map->key_slots[slot_index] or map->value_slots[slot_index] aren’t valid memory addresses, the program will segfault before we can even perform our relative read or write!

todo diagram of us doing a negative oob on the hash table and dereferencing unknown values ??

Not only does the slot array address need to be valid, the pointer location needs to be useful for us to build an exploit chain. In order to make the most out of our undefined behavior, we’re going to need to know exactly where we’re dereferencing into when we use a negative hash index.

The first thing that the code does with our slot is that it tries to find the matching key in the array: the code searches for the index i where map->key_slots[-idx][i] matches our query’s key. Because the key_slots array is placed after the value_slots array in the hashmap struct, an out of bound access map->key_slots[-idx] is semantically equivalent to map->value_slots[256-idx]. This is good news! When we use a negative slot index, map->key_slots[-idx] still points to valid memory. In fact, it’s memory we can already control! With a clever setup of type confusion between keys and values, we can successfully navigate the key scan to land at whatever index i we want, by planting values in the victim slot that match the keys we will use in the future.

The next part is harder: how do we steer our read/write primitive on the value slot of the hashmap to obtain RCE? We can control both values -idx and i using a careful setup, but we still don’t know where map->value_slots[-idx][i] will access. Because the hashmap struct is allocated on the heap, accessing map->value_slots[-idx] will result in a heap underflow. Is there any way we can coerce map->value_slots[-idx] into returning a useful pointer that lets us craft an exploit?

Exploiting the GLIBC Heap

It turns out, we can get a very useful pointer leak if the previous chunk is free. When a chunk is free, the user data section is repurposed as metadata, containing fd and bk pointers to link the chunk into a bin. If this is the first chunk of the given size to have been freed in the program, the fd pointer will point to the large bin’s head in the libc malloc_state structure.

todo the same diagram but now revealed whats before the heap

bleh libc malloc_state

blehhhhhh stop

The Mistakes

My challenge had several quality control problems. The code wasn’t very well-structured, so it had a bunch of unnecessary overcomplications (such as the struct sized_object). Additionally, the alloc_off_heap function had a silly logic error which miscalculated the on-heap size of an off-heap object, allowing users to corrupt the heap using integer overflow directly. In the future, I’ll need to make sure to get proofreading on my challenges and ensure that there aren’t any unintended solutions in the challenge.

The Conclusion

Overall, 85 out of 400 teams solved the challenge within the first 24 hours. Despite the technical problems, I think that pwn/garden was a very fun challenge. garden provides a look into how custom heaps, garbage collection, and mitigations interact in a realistic environment, similar to that of a real-world JVM implementation. I hope to create more unique and advanced challenges in the future. Also, the flag contains a mandatory sponsored message by FizzBuzz101:

dice{m1tig4ti0ns_nev3r_w0rk_y0u_escap3d_th3_w4ll3d_g4Rd3n}

IMPORTANT DONT DELETE MY FOOTNOTES

  1. There are many different layouts for storing entries in a hashmap: OpenJDK’s HashMap manages a linked list of entries for each slot, and CPython’s dict implementation stores all entries in a single array, with a custom open addressing algorithm to resolve collisions. Eclipse Collections’ UnifiedMap implementation here actually does resemble the layout used in this challenge, with a contiguous array of entries for each slot in the table. ↩

  2. I decided to use templates after my experience with the extremely scuffed Firedancer CPI implementation, which uses preprocessor templates to reuse common code while inlining custom functionality. Everyone must endure the wrath of scuffed preprocessor hacks. ↩

  3. In the C spec, the division and remainder operators are the results obtained when the dividend is truncated towards zero by the diviso; this pairs cleanly, enforcing the property (a / b) * b + (a % b) == a (given the quotient is representable). The natermsmes “remainder” and “modulo” are often used interchangeably, but strictly speaking, the % operator in C computes the remainder, whereas in Python, it computes the modulo. ↩