This post continues my series dedicated to the exploitation of the Source Engine 1.
If you haven’t already, I recommend reading my first post on the Source Engine where I break down the engine’s network protocol and exploit an infoleak vulnerability.

Now we’re finally jumping in at the deep end. In this post, I’ll walk through the first deadly bug I found in the protocol implementation and show how, with a bit of exploit engineering and heap massaging, it can ultimately lead to remote code execution.

Let’s dive in!

The Bug

Let’s take another look at the function responsible for parsing incoming fragments, that we first reviewed in my previous post:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
bool CNetChan::ReadSubChannelData(bf_read &received, int stream_idx) {
    data_fragments* data = &this->stream_data[stream_idx]; 

    bool is_single_block = received.ReadOneBit() == 0; // is that a single block?
    if(!is_single_block) {
        start_fragment = received.ReadUBitLong(...);
        fragments_num = received.ReadUBitLong(3); 
        offset = startFragment * FRAGMENT_SIZE;
        len = numFragments * FRAGMENT_SIZE;
    }

    if(offset == 0) { // if first fragment then allocate buffer & read metadata
        <...>
        data->byte_count = received.ReadUBitLong(...);
        data->buffer = malloc(data->byte_count);
        data->total_fragments = bytesize_to_fragments(data->byte_count);
        data->acked_fragments = 0;
        <...>
    } else {
        if (!data->buffer) {
            <raise error> // trying to receive fragment but no buffer allocated
        }
    }

    <...> // some checks

    received.ReadBytes(data->buffer+offset, len); // read block data
    data->acked_fragments += fragments_num; 

    return true;
}

When receiving a data fragment, the engine must determine whether a transfer is already ongoing, there are two cases:

  • The fragment’s offset is null (offset == 0 @ line 12). In this case, it considers that a new transfer is initiated (this is the first fragment after all…): it allocates a buffer large enough to hold the transfer, based on the metadata contained in the fragment header – see line 14 – and derives the expected number of fragments based on these values.

  • The fragment’s offset is not null (offset != 0 @ line 19). In this case, it checks whether data->buffer is non-null – see line 19. Note that the only flag indicating an active transfer is whether data->buffer is null or not. As long as data->buffer remains a valid pointer, ReadSubChannelData will continue copying incoming fragments into it, as long as the fragment’s offset is in-bounds.

Later, once all fragments have supposedly been received, the engine processes the message:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool CNetChan::CheckReceivingList(int stream_idx) {
    data_fragments* data = &this->stream_data[stream_idx];

    <check fragments received>

    if (data->is_compressed)
        UncompressFragments(sdata);

    <...>

    if (!ProcessMessages(data->buffer))
        return false; // when message processing failed
    <...>

    if (data->buffer) {
        delete [] data->buffer;
        data->buffer = NULL;
    }

    return true;
}

This function eventually frees the buffer and nullifies the pointer at lines 16–17.
This nullification is critical, because it marks the end of the transfer. Once data->buffer becomes null, CNetChan::ReadSubChannelData will refuse additional fragments.

However, if ProcessMessages fails (line 11-12), the function returns early before freeing and nullifying data->buffer. Then, from the engine’s perspective, the transfer is still in progress because data->buffer remains non-null. So, in theory, we can keep sending fragments and CNetChan::ReadSubChannelData will gently copy them to the transfer buffer. However, at that point it’s merely just a bug, not a vulnerability. Even though we can keep sending fragments when we shouldn’t be, CNetChan::ReadSubChannelData is still checking the fragment IDs/offsets, so it won’t write out of bounds.

At least, it won’t write out of bounds as long as data->buffer remains unchanged. The situation changes if data->buffer is ever reallocated to a different size during processing. And… this is exactly what happens inside UncompressFragments, which is called just before ProcessMessages:

1
2
3
4
5
6
7
8
9
10
11
12
void CNetChan::UncompressFragments(stream_data_t *sdata) {
    void* new_buf = new char[data->uncompressed_size];

    bool success = <safe decompression>

    if(success) {
        delete [] data->buffer;
        data->buffer = new_buf;
        data->is_compressed = false;
        <...>
    } 
}

If the transfer is marked as compressed (via metadata in the first fragment), then UncompressFragments will decompress the content, free the old data->buffer, allocate a new buffer for the decompressed content, and eventually make data->buffer points to the newly allocated buffer.

Let’s call compressed_size the compressed size announced in the first fragment, and uncompressed_size the uncompressed size. If ProcessMessages subsequently fails after decompression, the transfer state is not reset, and we can continue transmitting fragments. In other words, at that point, the engine still believes it is receiving a transfer of size compressed_size, while data->buffer now references a buffer of size uncompressed_size.

You might assume this is “safe” anyway (right?) because decompression usually increases size… However, nothing actually enforces that compressed_size <= uncompressed_size! The source engine uses its own compression algorithm (I’m not going into details, it does not matter that much), and we can totally craft a “compressed” content whose uncompressed size is significantly lower than its compressed size.

Since the number of expected fragments is derived from compressed_size, and the new allocation size is uncompressed_size, if we craft a compressed content such that uncompressed_size < compressed_size, we now have a size mismatch: the engine believes it is still receiving a transfer of size compressed_size, allowing up to compressed_size / FRAGMENT_SIZE fragments. However, the backing buffer is now only uncompressed_size bytes long. So, in the end, we can send fragments that are written past the end of the newly allocated buffer, resulting in a heap overflow.


Heap Exploitation

At the time, the Source Engine was using tcmalloc for managing the heap (at least on Linux). The structure of the heap is fairly easy to understand, nothing fancy, nothing complex, nothing secure… I found these quite interesting presentation slides by Agustin Gianni & Sean Heelan [1] that detail the functioning of tcmalloc and appropriate exploitation techniques – I encourage you to take a look at it!

Generally exploiting a heap-overflow can be done in two ways:

  • overwrite heap metadata and use the heap internals as exploitation primitives
  • overwrite whatever data is stored (like C++ objects) to craft exploitation primitives (arbitrary read/write, arbitrary function call…)

In this case, I’ve chosen to take advantage of the insecure heap structures and internals.

Heap Internals

In tcmalloc, the heap is organized into size classes. Each size class corresponds to a fixed allocation size, and allocations are rounded up to the nearest matching class. Internally, each size class maintains a free list containing available chunks of that exact size. These chunks are picked from larger contiguous memory regions called spans. A span is a run of memory pages that is subdivided into equally sized objects belonging to a single size class.

When a memory allocation is requested, tcmalloc selects the appropriate size class at runtime based on the requested size, rounds it up if necessary, and returns a chunk from that class’ free-list. The free list itself is implemented as a classic singly linked-list. When a chunk is freed, it is pushed onto the head of the list, and the pointer to the next free chunk is stored directly at offset zero inside the freed chunk’s memory – i.e. the freed memory region is reused to store heap metadata.

So initially, before any allocations, a span assigned to a specific size class has been split into fixed-size free chunks. The allocator sequentially links those chunks together to form the free list:

Figure 1: Initial structure of a heap span before any allocation.

Note that initially, because chunks are sequential linked together, the free-list has a fully deterministic order. Within a freshly initialized span, each free chunk simply points to its immediate left-neighbor in memory.

This might seem like a minor detail, but it becomes crucial later when it comes to massaging the heap. Also note that, when a size class runs out of free chunks, tcmalloc allocates a new span for that class, and the free-list is repopulated just like in figure 1.

Exploitation Strategy

Since we have a heap buffer overflow primitive, we can overwrite the metadata of the chunk immediately adjacent to our allocation. Especially, if the right-adjacent chunk within the same span is currently free, we can overwrite its next pointer:

Figure 2: Overwriting the next pointer.

Because tcmalloc implements free lists as singly linked-lists, allocating that adjacent chunk – chunk B in figure 2 – will pop it from the free list and set the free-list head to the value stored in B’s next pointer. If we have corrupted that pointer, the allocator will blindly trust it.

As a result, the next allocation from that same size class will return a chunk located at an address we control (0xAAAAAAAA… in the example):

Figure 3: Getting control of the free-list head.

Massaging the Heap

Now we have an exploitation strategy, good. However, its success depends on two conditions:

  • the fragment-receiving buffer must be located just before a free-chunk
  • ideally, this free-chunk must be a free-list head

Obviously, the heap is a mess and these conditions are really unlikely to be fulfilled without any heap manipulation from our side. Ideally, we want to put the heap in a standard and known state, that we can subsequently alter and shape to fulfill our requirements. In [1], Agustin and Sean give us insight on how to do that.

At that point, having a way to inspect the heap internals with a debugger is a must. There wasn’t really anything designed to do that for tcmalloc – at least in the way I wanted it. So I ended up creating my own GEF plugin to pretty print the size-classes, free-lists, allocated chunks…

Free-List Exhaustion

First, we must exhaust the free-list of a chosen class-size, such that it is repopulated with a new span whose shape is known – see figure 1. To do this, we need a way to allocate a bunch of same-sized chunks, which is exactly what we can do with CSVCMsg_CreateStringTable messages:

message CSVCMsg_CreateStringTable
{
	optional string name = 1;
	optional int32 max_entries = 2;
	optional int32 num_entries = 3;
	optional bool user_data_fixed_size = 4;
	optional int32 user_data_size = 5;
	optional int32 user_data_size_bits = 6;
	optional int32 flags = 7;
	optional bytes string_data = 8;
}

This message creates a so-called string table, whose content is just a list of strings to copy locally. Each string is copied to its own allocated memory chunk, which gives us exactly what we were searching for: we can allocate a bunch of chunks of arbitrary sizes to exhaust a free-list.

Reversing the Free-List Order

Now that we can trigger a free-list exhaustion and repopulation, we need a way to reverse the free-list order. If you take a look at figure 1, after repopulating, the free-chunks are stored in descending order in the free-list. This means that for a given free-chunk, the next free-chunk in the free-list is its left-neighbor in memory. This is exactly the opposite of what we’re aiming for! For our exploitation, we want the next free-chunk to be the right-neighbor in order to overflow its next pointer. So, in the end, we would like something like this instead:

Figure 4: Ideal free-list structure for exploitation.

To achieve this, we can once again leverage CSVCMsg_CreateStringTable messages. When creating a table, the engine sequentially allocate a new chunk for each string in the message. Each table is named, and when you send a new table with the same name, the previous table is deleted. At this moment, the engine will sequentially free each allocated chunk in the table. So, if we start from a newly populated free-list after exhaustion, this is what happens:

Figure 5: Free-list order reversing using string tables.

Eventually, we end up with a fully reversed free-list!

Write-What-Where?

So now we can massage the heap, such that the exploitation strategy introduced in figure 2 & figure 3 is achievable. We take control of a free-list head pointer, such that the next malloc call will return our controlled pointer, and the engine will gently write data at that location.
From there, we must determine:

  • a good target to redirect the allocation
  • whether we can control the content written at that location

The second point is trivial, we can just start a new data transfer with a carefully chosen size, such that the buffer allocated for the transfer uses our poisoned free-list. We can then send fragments that the engine will copy to the targeted location.

In the end, we have built a write-what-where primitive, we can write arbitrary data at an arbitrary location, but we still need to find where to write.
Since ASLR is enabled, we must leak the address of our target before triggering the exploit. Fortunately, in my previous post, I’ve detailed a nice infoleak vulnerability that we can leverage to leak the base address of the engine_client.so shared library. So ideally, our target must be inside the engine_client.so address space.

Arbitrary Vtable Function Call

Generally, in C++ applications, one of the go-in target is C++ objects vtable. Even though C++ objects are generally dynamically allocated and stored on the heap, you can find some of them stored elsewhere. Typically, global variables that are initialized at the program start are stored in the .data section. All that remains is to find a specific global C++ object, in the engine_client.so library, and that exposes a vtable.

In my previous post, we leveraged so-called ConVar to get the infoleak working. When it comes to manipulating C++ objects in the Source Engine, ConVar are a good target because a remote peer can easily interact with them. Once again, ConVar are perfect for our purposes, because they have a vtable, and we can remotely trigger virtual function calls for a specific ConVar object.

After a bit of reversing, I finally found the perfect ConVar: timerefresh. This ConVar is stored in the .data section of engine_client.so, and can be queried by the server – thus triggering virtual function calls. All we have to do is:

  1. trigger the exploit to take control of the free-list
  2. redirect the free-list head to the .data section of engine_client.so, make it point somewhere near timerefresh
  3. initiate a new transfer to trigger the poisoned allocation
  4. send fragments to overwrite the timerefresh vtable and redirect it to our own fake vtable
  5. trigger a virtual function call, which use the fake vtable and jump to our desired location

So in the end, this is what happens:

Figure 6: Overwriting timerefresh vtable.

In the end, we can trigger a virtual function call by sending e.g. a CNETMsg_SetConVar message:

message CMsg_CVars
{
	message CVar
	{
		optional string name = 1;
		optional string value = 2;
        ...
	}

	repeated CVar cvars = 1;
}

message CNETMsg_SetConVar
{
	optional CMsg_CVars convars = 1;
}

This message will trigger a virtual function call to ConVar::InternalSetValue to set the value of each ConVar in its list. So all we need to do is put timerefresh in that list, and this will trigger an arbitrary function call using our fake vtable!

Getting RCE

From there, getting RCE is a piece of cake. We already have full control over a vtable, and can trigger a vtable function call. All that’s left is to build a code-reuse gadget chain that spawns a shell. There’s just one little catch: we don’t control the stack. This means we cannot simply jump to a conventional ROP chain.

Let’s take a look at the context of this virtual function call. When ConVar::InternalSetValue is called, our poisoned vtable determines the address the program jumps to. Since InternalSetValue is a C++ instance method, its first argument is the this pointer – our poisoned ConVar object – while its second argument is the new ConVar value – the value field from the CMsg_CVars network message. Following the Linux x86-64 System V ABI, these arguments are passed in rdi and rsi, respectively. Consequently, when execution reaches our chosen gadget, rdi points to our poisoned object and rsi points to the data we supplied in CMsg_CVars.

After looking through the available gadgets using Ropper, I found a very promising gadget:

xchg rsp, rsi; dec dword ptr [rax - 0x77]; ret 0x8d48;

This gadget is almost perfect, the xchg instruction swaps rsp and rsi, allowing us to pivot the stack to the data we control – the value field of CMsg_CVars.

The only issue with it was this dec instruction writing at the address rax - 0x77. Unfortunately, rax does not naturally point to a writable memory location when calling ConVar::InternalSetValue. We therefore need a helper gadget to initialize rax before reaching the pivot. Fortunately, I found exactly what we need:

mov rax, qword ptr [rdi]; call qword ptr [rax + 0x98];

Since rdi points to our poisoned object, we take control of rax with the first mov instruction. We can then arrange for the indirect call to reach our pivot gadget.

By chaining these two gadgets, we can finally take control of rsp. From there, we can execute a ROP-chain using the data we supplied through the ConVar message.

And that’s it! With the stack pivot in place, we can execute our ROP chain (automatically generated with Ropper), ultimately spawning a shell… voilà!

Demo Video

Conclusion

And that’s it for this one!
I had quite a bit of fun digging into this bug. What started as a rather subtle issue in the fragment handling code eventually turned into a full RCE, after quite a bit of heap massaging… It’s also a nice illustration of how much you can get out of a bug once you understand the internals of the engine. And it would have been way harder without the decompression routine rewriting the data->buffer pointer!

Remember… sometimes decompression makes your data smaller… hehe! I’ll leave it here for now. The next posts in this series will focus on other deadly bugs I’ve found in the engine!


Responsible Disclosure

Just like the previous bug, I reported this vulnerability to Valve in November 2022 via Hackerone. Again, with the planned release of CS2 a few months after the report, it seems Valve deprioritized fixing issues in their legacy engine. That said, Valve did respond fairly quickly this time – in January 2023, if I remember correctly. Since then, several games have been updated to use Valve’s newer networking stack: GameNetworkingSockets, which obviously does not share the vulnerable code described in this post.


References

  1. [1]
    S. Heelan and A. Gianni, “Attacking the Webkit Heap,” Sean Heelan’s Website. [Online]. Available: https://sean.heelan.io/wp-content/uploads/2017/12/attacking_the_webkit_heap.pdf