From fb4a935429984ac5c60effafdd50febdc949f135 Mon Sep 17 00:00:00 2001 From: ghptc Date: Tue, 27 Oct 2026 15:53:08 -0300 Subject: [PATCH] feat(rcon): add gated asynchronous authenticated mode bridge --- docs/rcon-investigation.md | 4 + docs/rcon-mode-bridge.md | 112 +++++++++++++++++++++ src/hl2rcon.c | 38 +++++-- src/sv_auth.c | 23 ++++- src/sv_auth.h | 1 + src/sv_cmds.c | 4 +- src/sv_main.c | 10 +- src/sv_mode_bridge.c | 189 +++++++++++++++++++++++++++++++++++ src/sv_mode_bridge.h | 10 ++ src/webadmin.c | 16 +-- tests/rcon_harness.c | 14 ++- tests/rcon_harness_main.c | 18 +++- tests/run_btd_integration.py | 4 +- tests/test_auth_hardening.py | 106 ++++++++++++++++++++ tests/test_mode_bridge.c | 72 +++++++++++++ tests/test_mode_bridge.py | 62 ++++++++++++ tests/test_rcon.py | 27 +++++ 17 files changed, 684 insertions(+), 26 deletions(-) create mode 100644 docs/rcon-mode-bridge.md create mode 100644 src/sv_mode_bridge.c create mode 100644 src/sv_mode_bridge.h create mode 100644 tests/test_auth_hardening.py create mode 100644 tests/test_mode_bridge.c create mode 100644 tests/test_mode_bridge.py diff --git a/docs/rcon-investigation.md b/docs/rcon-investigation.md index 8f4aed6a..0cc26588 100644 --- a/docs/rcon-investigation.md +++ b/docs/rcon-investigation.md @@ -1,5 +1,9 @@ # Traditional UDP RCON compatibility investigation +Current authenticated mode-bridge implementation and its disabled activation +gate are documented in [rcon-mode-bridge.md](rcon-mode-bridge.md). The historical +investigations below retain their original evidence and scope. + Investigation date: 2026-10-26. Server baseline: `9e3ce3e17532574bbe25e24cbff0174df94c802d`. No real credential was read or used. No remote runtime was contacted or changed. diff --git a/docs/rcon-mode-bridge.md b/docs/rcon-mode-bridge.md new file mode 100644 index 00000000..d750248c --- /dev/null +++ b/docs/rcon-mode-bridge.md @@ -0,0 +1,112 @@ +# Authenticated RCON mode bridge + +Baseline: protected master `701a7c5df46c5723705dad0408afa44fb89b0ad9`. +The previous `change_mode` preflight remains nonmutating for console, command +buffers and GSC. Authenticated UDP and Source RCON have a separate native ingress +for exactly `change_mode promod`, `change_mode zombies`, or `change_mode` status. +Both registration and ingress require power 100. A command-power metadata change +cannot lower the native floor. No console/GSC invocation inherits an ambient +"authenticated" flag. + +Only the authenticated ingress submits a fixed packet over nonblocking Linux +`SOCK_SEQPACKET` to `/run/cod4-mode-bridge/control.sock`. The engine checks the +host peer is UID zero. No path, executable, image reference, shell, Docker API, +password, account name or arbitrary argv crosses this interface. The host validates +kernel peer credentials against the current production container and executable. +No endpoint is mounted or activated by this change. Windows fails closed. + +UDP framing is checked against the complete original payload, including ignored +newline/NUL suffixes and truncation, before accepting a mode command. Source +requests are checked against their complete packet frame. Modes reject quotes, +comments, separators, controls and extra arguments. Mode request logging omits raw +arguments. The existing UDP password and Source account authentication remain +responsible for authenticating the administrator. + +Authentication hardening found necessary during this investigation: + +- Unregistered commands/cvars no longer bypass low-power Source/Webadmin checks + via `Cmd_GetPower == -1`. Registered command permissions remain unchanged. +- Source login identity comes from the exact record returned by `Auth_Authorize`, + not a second username/SteamID-handle lookup. Zero-ID account logins are rejected; + the authenticated master-console login remains supported. +- Webadmin carries the exact matched session record through dispatch and logout; + numeric or duplicate names cannot select another account. +- Sub-100 password administrators cannot reset equal/higher-ranked accounts; + power-100 recovery remains available. +- Source command early exits restore the old invoker and redirect state. + +## Asynchronous feedback + +Initial output is **submitted**, with an unpredictable operation ID; it is not +acceptance or success. There is no synchronous controller/Docker wait in the game +loop. The frame poll accepts only bounded fixed-enum replies matching that ID. +Embedded NUL, truncated, malformed or mismatched replies are discarded. + +After host preflight accepts a durable operation, the engine queues a fixed player +broadcast and acknowledges on the next normal game frame. The host then recreates +the runtime. An engine that disappears cannot cancel the accepted host job; a +still-running engine that fails notification acknowledgment causes denial before +mutation. Network delivery of the notice is not a guaranteed player receipt. + +The initiating UDP endpoint receives a safe asynchronous update where possible. +Source clients can poll the status command. The host survives process replacement +and the replacement engine refreshes status; after reconnecting, use: + +```text +/rcon change_mode +``` + +Status reports operation ID, mode, phase and a fixed explanation. Accepted/pending +is never completion. Success requires host verification; `rolled_back` means the +transition failed and the previous exact runtime was verified restored. +`recovery_required` requires operator intervention. Availability is the last host +response and is revalidated for every request. + +## Trust and qualification + +The qualified engine, native plugins, installed GSC and private authentication +configuration are trusted code/authority. Direct GSC execution cannot submit a +mode request, but a malicious mod that steals or changes the existing credential +can authenticate normally. The bridge is not a sandbox for a compromised game +process. Host authority is still restricted to the two approved immutable images. +Command-policy managers and credential administrators belong to authentication +TCB; do not delegate that authority to untrusted accounts. + +Classic UDP RCON is plaintext and has no cryptographic packet nonce. Durable host +request IDs prevent host-request replay/duplicates; they do not repair captured +UDP credentials or network-packet replay. Activation requires protected +administrative transport and explicit operator acceptance of the legacy protocol +boundary. No password is forwarded to the host or added to status/logging. + +See workspace `docs/authenticated-mode-bridge.md` for host trust, locking, rollback, +threat model and the gated installation/qualification procedure. Both modes need +independent actual-client qualification, and both images must contain protocol +`C4M1`. No production bridge installation, merge or deployment is automatic. + +## Checks + +```sh +make -j4 +python3 -m unittest discover -s tests -p 'test_*.py' +python3 tests/run_map_rotation.py +python3 tests/run_map_voting.py +``` + +Native policy fixtures execute the actual bridge, framing, authentication, +Source/Web console, role-reset and session-record functions. Loopback RCON tests +execute the production parser/authentication path, including invalid framing, +unauthenticated requests and numeric-name identity binding. Live-game compatibility +uses the existing disposable Promod/BTD/allied runners with the host endpoint +absent; this verifies disabled-bridge compatibility, not an enabled production +transition. Complete real-image RCON round trips and external rollback remain +operator qualification gates after reviewed merges. + +Rollback: retain the host CLI, remove the bridge socket mount/stop the host bridge +only with operator authorization, and revert the focused feature through review. +Do not undo authentication repairs merely to disable switching. Keep production +on its existing approved image until separate activation approval. + +Local review evidence (2026-10-27): engine unit suite 79 tests, one optional +client-checkout skip; map rotation/voting checks passed. Protected baselines: +engine `701a7c5df46c5723705dad0408afa44fb89b0ad9`, workspace `b77684d`, +configuration `9f0fa1a0b0c1483ea20a89fc7beaf26c9b7c2201`. diff --git a/src/hl2rcon.c b/src/hl2rcon.c index 74e9d256..e61eaa67 100644 --- a/src/hl2rcon.c +++ b/src/hl2rcon.c @@ -35,6 +35,7 @@ #include "g_sv_shared.h" #include "sv_auth.h" #include "q_platform.h" +#include "sv_mode_bridge.h" #include "sapi.h" #include @@ -193,6 +194,8 @@ qboolean HL2Rcon_SourceRconAuth(netadr_t *from, msg_t *msg, rconUser_t* user){ char buf[MAX_STRING_CHARS]; char stringlinebuf[MAX_STRING_CHARS]; uint64_t steamid; + int authorized_index; + authData_admin_t *authorized; //packetlen = MSG_ReadLong(msg); @@ -233,15 +236,19 @@ qboolean HL2Rcon_SourceRconAuth(netadr_t *from, msg_t *msg, rconUser_t* user){ goto badrcon; } - if(Auth_Authorize(username, password) < 0) + authorized_index = Auth_Authorize(username, password); + authorized = authorized_index < 0 ? NULL : Auth_GetAdminFromIndex(authorized_index); + if(!authorized || authorized->steamid == 0) { goto badrcon; } + /* Bind identity to the verified record, never parse a login as a handle. */ + steamid = authorized->steamid; + username = authorized->username; Com_Printf(CON_CHANNEL_DONT_FILTER,"Rcon login from: %s Name: %s\n", NET_AdrToString (from), username); Cmd_EndTokenizedString(); - steamid = Auth_GetSteamID(username); }else{ steamid = 0; username = "console"; @@ -490,7 +497,7 @@ void HL2Rcon_ExecuteConsoleCommand(const char* command, uint64_t steamid) while ( command[i] != ' ' && command[i] != '\0' && command[i] != '\n' && i < 32 ){ i++; } - if(i > 29 || i < 3) return; + if(i > 29 || i < 3) goto cleanup; Q_strncpyz(cmd,command,i+1); @@ -502,7 +509,7 @@ void HL2Rcon_ExecuteConsoleCommand(const char* command, uint64_t steamid) // start redirecting all print outputs to the packet powercmd = Cmd_GetPower(cmd); - if(powercmd > power) + if(powercmd < 0 || powercmd > power) { Com_Printf(CON_CHANNEL_DONT_FILTER,"Insufficient permissions! Power: %d Needed: %d\n", power, powercmd); }else{ @@ -519,6 +526,7 @@ void HL2Rcon_ExecuteConsoleCommand(const char* command, uint64_t steamid) } } +cleanup: Com_EndRedirect(); Cmd_SetCurrentInvokerInfo(oldpower, oldinvokerclnum, oldinvokersteamid, oldinvokername); @@ -529,6 +537,7 @@ void HL2Rcon_ExecuteConsoleCommand(const char* command, uint64_t steamid) int HL2Rcon_SourceRconEvent(netadr_t *from, msg_t *msg, int connectionId){ int packettype; + int packetstart, packetlen, commandstart; int type; int8_t team; int8_t clientnum; @@ -560,8 +569,8 @@ int HL2Rcon_SourceRconEvent(netadr_t *from, msg_t *msg, int connectionId){ while(msg->readcount < msg->cursize) { - //packetlen = - MSG_ReadLong(msg); + packetstart = msg->readcount; + packetlen = MSG_ReadLong(msg); user->lastpacketid = MSG_ReadLong(msg); @@ -592,19 +601,32 @@ int HL2Rcon_SourceRconEvent(netadr_t *from, msg_t *msg, int connectionId){ case SERVERDATA_EXECCOMMAND: + commandstart = msg->readcount; command = MSG_ReadString(msg, stringbuf, sizeof(stringbuf)); //Pop the end of body byte MSG_ReadByte(msg); - Com_Printf(CON_CHANNEL_DONT_FILTER,"Rcon from: %s command: %s\n", NET_AdrToString(from), command); + Com_Printf(CON_CHANNEL_DONT_FILTER,"Rcon from: %s command: %s\n", NET_AdrToString(from), + SV_RconModeCommand(command) ? "change_mode request (arguments omitted)" : command); sourceRcon.redirectUser = connectionId+1; sourceRcon.writeerror = 0; if(user->steamid != 0 || strcmp(user->rconUsername, "console") == 0) { - HL2Rcon_ExecuteConsoleCommand(command, user->steamid); + int power = user->steamid ? Auth_GetClPowerBySteamID(user->steamid) : 100; + Com_BeginRedirect(sv_outputbuf, sizeof(sv_outputbuf), HL2Rcon_SourceRconFlushRedirect); + if (SV_RconModeIngress(command, power, NULL, + packetlen >= 10 && packetlen <= msg->cursize-packetstart-4 && + msg->readcount == packetstart+4+packetlen && + msg->data[msg->readcount-1] == 0 && + SV_RconModeFraming(msg->data+commandstart, msg->readcount-commandstart-1))) { + Com_EndRedirect(); + } else { + Com_EndRedirect(); + HL2Rcon_ExecuteConsoleCommand(command, user->steamid); + } } sourceRcon.redirectUser = 0; if(sourceRcon.writeerror) diff --git a/src/sv_auth.c b/src/sv_auth.c index f88fc4f3..be3ee635 100644 --- a/src/sv_auth.c +++ b/src/sv_auth.c @@ -54,27 +54,32 @@ authData_t auth_admins; #define AUTH_DEFAULT_POWER 1 -const char* Auth_FindSessionID(const char* sessionid) +authData_admin_t* Auth_FindSessionAdmin(const char* sessionid) { int i; authData_admin_t *user; - if(strlen(sessionid) != 64) + if(!sessionid || strlen(sessionid) != 64) { return NULL; } for(i = 0, user = auth_admins.admins; i < MAX_AUTH_ADMINS; i++, user++){ - if(!Q_stricmp(user->sessionid, sessionid)) + if(user->steamid && *user->username && !Q_stricmp(user->sessionid, sessionid)) { - return user->username; + return user; } } return NULL; } +const char* Auth_FindSessionID(const char* sessionid) +{ + authData_admin_t *user = Auth_FindSessionAdmin(sessionid); + return user ? user->username : NULL; +} const char* Auth_GetSessionId(const char* username, const char *password) { int handle; @@ -351,7 +356,7 @@ void Auth_ListAdmins_f( void ){ authData_admin_t* Auth_GetAdminFromIndex( int index ) { - if(index >= MAX_AUTH_ADMINS) + if(index < 0 || index >= MAX_AUTH_ADMINS) { return NULL; } @@ -435,6 +440,14 @@ void Auth_ChangePasswordByMasterAdmin_f() Com_Printf(CON_CHANNEL_DONT_FILTER,"Admin %s not found.\n",Cmd_Argv(1)); return; } + /* Password administration cannot take over an equal/higher-ranked account. + * Full-power operators retain account recovery authority. */ + if (Cmd_GetInvokerPower() != 100 && + Auth_GetClPowerBySteamID(id) >= Cmd_GetInvokerPower()) + { + Com_PrintError(CON_CHANNEL_DONT_FILTER, "Cannot reset an account at or above your own permission level.\n"); + return; + } Auth_ChangeAdminPassword( id, Cmd_Argv(2) ); } diff --git a/src/sv_auth.h b/src/sv_auth.h index 284e2922..6bcf2c24 100644 --- a/src/sv_auth.h +++ b/src/sv_auth.h @@ -69,6 +69,7 @@ qboolean Auth_InfoAddAdmin(const char* line); void Auth_WriteAdminConfig(char* buffer, int size); const char* Auth_FindSessionID(const char* sessionid); +authData_admin_t* Auth_FindSessionAdmin(const char* sessionid); const char* Auth_GetSessionId(const char* username, const char *password); void Auth_ApplyUndercoverStatus(client_t* cl); void Auth_StoreUndercoverStatus(client_t* cl); diff --git a/src/sv_cmds.c b/src/sv_cmds.c index 566788be..5c293d3a 100644 --- a/src/sv_cmds.c +++ b/src/sv_cmds.c @@ -2373,8 +2373,8 @@ void SV_LoadMapFromBsp() void SV_DoHostMigration_f(); -/* Artifact selection/recreation belongs to the external operator, never GSC or - * a client-supplied command. Until that boundary is qualified, fail closed. */ +/* Generic console/GSC execution remains a nonmutating preflight. Only the + * authenticated raw RCON ingress may submit to the qualified host controller. */ static void SV_ChangeMode_f(void) { const char *mode; diff --git a/src/sv_main.c b/src/sv_main.c index 6145c466..14606160 100644 --- a/src/sv_main.c +++ b/src/sv_main.c @@ -54,6 +54,7 @@ #include "xac_helper.h" #include "db_load.h" #include "sec_crypto.h" +#include "sv_mode_bridge.h" #include #include @@ -1530,9 +1531,15 @@ __optimize3 __regparm2 static void SVC_RemoteCommand( netadr_t *from, msg_t *msg while(cmd_aux[0] == ' ')//Skipping space after the password cmd_aux++; - Com_Printf (CON_CHANNEL_SERVER,"Rcon from %s: %s\n", NET_AdrToString (from), cmd_aux ); + Com_Printf (CON_CHANNEL_SERVER,"Rcon from %s: %s\n", NET_AdrToString (from), + SV_RconModeCommand(cmd_aux) ? "change_mode request (arguments omitted)" : cmd_aux ); Com_BeginRedirect (sv_outputbuf, SV_OUTPUTBUF_LENGTH, SV_FlushRedirect); + if (SV_RconModeIngress(cmd_aux, 100, from, + SV_RconModeFraming(msg->data + 8, msg->cursize - 8))) { + Com_EndRedirect(); + return; + } #ifdef PUNKBUSTER if(!Q_stricmpn(cmd_aux, "pb_sv_", 6)){ @@ -4107,6 +4114,7 @@ SV_PreFrame */ void SV_PreFrame() { + SV_ModeBridgeFrame(); SV_BotManagerFrame(); SV_UpdateBots(); if ( cvar_modifiedFlags & 0x404 ) diff --git a/src/sv_mode_bridge.c b/src/sv_mode_bridge.c new file mode 100644 index 00000000..1f118078 --- /dev/null +++ b/src/sv_mode_bridge.c @@ -0,0 +1,189 @@ +/* Fixed, nonblocking host mode-control IPC. AGPL-3.0-or-later. + * Only authenticated RCON ingress calls SV_RconModeIngress. Console/GSC never do. + * No shell, credentials, image identifiers or selectable endpoint cross this API. + */ +#include "sv_mode_bridge.h" +#include "qcommon.h" +#include "qcommon_io.h" +#include "server.h" +#include "netchan.h" +#include "sys_main.h" +#include "cvar.h" +#include +#include +#ifndef _WIN32 +#include +#include +#include +#include +#include + +#ifndef BRIDGE_SOCKET +#define BRIDGE_SOCKET "/run/cod4-mode-bridge/control.sock" +#endif +static int channel = -1; +static time_t opened, next_status; +static qboolean notify_peer; +static qboolean ack_pending; +static netadr_t peer; +static char request_id[33]; +static char cached[192] = "Host controller unavailable. Runtime unchanged."; + +static qboolean mode_name(const char *name) { return !strcmp(name,"promod") || !strcmp(name,"zombies"); } +static qboolean identifier(const char *s) +{ + int i; + if (!strcmp(s,"none")) return qtrue; + if (strlen(s) != 32) return qfalse; + for (i=0;i<32;i++) if (!((s[i]>='0' && s[i]<='9') || (s[i]>='a' && s[i]<='f'))) return qfalse; + return qtrue; +} +static qboolean word(const char *s) +{ + const char *values[] = {"idle","pending","accepted","success","rolled_back","recovery_required", + "disabled","denied","invalid","busy","replay","already_active","not_qualified","failed", + "verifying","rolling_back","submitted","unavailable"}; + unsigned i; + for(i=0;i=0) close(channel); channel=-1; notify_peer=qfalse; ack_pending=qfalse; request_id[0]=0; } +static qboolean submit(const char *mode, const netadr_t *reply) +{ + struct sockaddr_un address; + struct ucred credentials; + socklen_t size=sizeof(credentials); + char message[128]; + byte entropy[16]; + int i,n; + if(channel>=0) return qfalse; + channel=socket(AF_UNIX,SOCK_SEQPACKET|SOCK_NONBLOCK|SOCK_CLOEXEC,0); + if(channel<0) return qfalse; + memset(&address,0,sizeof(address)); address.sun_family=AF_UNIX; + memcpy(address.sun_path,BRIDGE_SOCKET,sizeof(BRIDGE_SOCKET)); + if(connect(channel,(struct sockaddr*)&address,sizeof(address))<0 || + getsockopt(channel,SOL_SOCKET,SO_PEERCRED,&credentials,&size)<0 || credentials.uid!=0) { close_channel(); return qfalse; } + if(mode) { + if(!Sys_RandomBytes(entropy,sizeof(entropy))) { close_channel(); return qfalse; } + for(i=0;i<16;i++) snprintf(request_id+i*2,3,"%02x",entropy[i]); + n=snprintf(message,sizeof(message),"C4M1 switch %s %s",request_id,mode); + } else n=snprintf(message,sizeof(message),"C4M1 status"); + if(send(channel,message,n,MSG_DONTWAIT|MSG_NOSIGNAL)!=n) { close_channel(); return qfalse; } + if(reply) { peer=*reply; notify_peer=qtrue; } + opened=time(NULL); + return qtrue; +} +#endif + +qboolean SV_RconModeFraming(const byte *wire, int length) +{ + int i; + if(length<0 || length>=1024) return qfalse; + for(i=0;i126 || wire[i]=='%') return qfalse; + } + return qtrue; +} + +qboolean SV_RconModeCommand(const char *raw) +{ + while(*raw==' ') ++raw; + return !Q_stricmpn(raw,"change_mode",11) && + (!raw[11] || raw[11]==' ' || raw[11]=='\t' || raw[11]=='\n' || raw[11]=='\r' || raw[11]==';'); +} + +qboolean SV_RconModeIngress(const char *raw, int power, const netadr_t *reply, qboolean framing) +{ + const char *argument; + char game[MAX_OSPATH]; + /* Recognize malformed variants too, so they cannot fall through tokenization. */ + while(*raw==' ') ++raw; + if(!SV_RconModeCommand(raw)) return qfalse; + if(power!=100) { Com_Printf(CON_CHANNEL_DONT_FILTER,"Permission denied: change_mode requires power 100.\n"); return qtrue; } + argument=raw+11; + if(!framing || (*argument && *argument!=' ')) { Com_Printf(CON_CHANNEL_DONT_FILTER,"Invalid mode request.\n"); return qtrue; } + while(*argument==' ') ++argument; + if(*argument && strcmp(argument,"promod") && strcmp(argument,"zombies")) { + Com_Printf(CON_CHANNEL_DONT_FILTER,"Unsupported mode. Use exactly change_mode promod or change_mode zombies. Invalid mode request; runtime unchanged.\n"); return qtrue; + } +#ifdef _WIN32 + Com_Printf(CON_CHANNEL_DONT_FILTER,"Host controller unavailable on this platform. Runtime unchanged.\n"); +#else + if(!*argument) { + Cvar_VariableStringBuffer("fs_game",game,sizeof(game)); + Com_Printf(CON_CHANNEL_DONT_FILTER,"Current fs_game: %s\nAvailable switch targets: %s (last host response; every request revalidated).\nMODE_STATUS %s\n",*game?game:"main", + strstr(cached,"result=idle") || strstr(cached,"result=success") || strstr(cached,"result=accepted") || strstr(cached,"result=rolled_back") || strstr(cached,"result=already_active") ? "promod,zombies" : "none",cached); + if(!submit(NULL,reply) && channel<0) + Com_Printf(CON_CHANNEL_DONT_FILTER,"Host controller unavailable; cached status may be stale.\n"); + } else { + if(channel>=0 && !request_id[0]) close_channel(); + if(channel>=0) Com_Printf(CON_CHANNEL_DONT_FILTER,"Transition request already in progress; use change_mode for status.\n"); + else if(submit(argument,reply)) { + snprintf(cached,sizeof(cached),"operation=%s mode=%s result=submitted phase=pending",request_id,argument); + Com_Printf(CON_CHANNEL_DONT_FILTER,"MODE_STATUS %s (not yet accepted). Use change_mode for status after reconnect.\n",cached); + } else Com_Printf(CON_CHANNEL_DONT_FILTER,"Host controller unavailable. Runtime unchanged.\n"); + } +#endif + return qtrue; +} + +void SV_ModeBridgeFrame(void) +{ +#ifndef _WIN32 + char message[256],version[8],code[32],id[40],mode[16],phase[32],canonical[256],announcement[128]; + struct iovec iov={message,sizeof(message)-1}; + struct msghdr header; + int n; + /* Give queued player notices a normal game-frame send before host handoff. */ + if(channel>=0 && ack_pending) { + n=snprintf(message,sizeof(message),"C4M1 notified %s",request_id); + send(channel,message,n,MSG_DONTWAIT|MSG_NOSIGNAL); + close_channel(); + return; + } + if(channel<0) { + if(time(NULL)>=next_status) { next_status=time(NULL)+2; submit(NULL,NULL); } + return; + } + memset(&header,0,sizeof(header)); header.msg_iov=&iov; header.msg_iovlen=1; + n=recvmsg(channel,&header,MSG_DONTWAIT); + if(n<0 && (errno==EAGAIN || errno==EWOULDBLOCK)) { + if(time(NULL)-opened>120) { strcpy(cached,"Host validation timed out; outcome unknown. Query status."); close_channel(); } + return; + } + if(n<=0 || header.msg_flags&MSG_TRUNC || memchr(message,0,n)) { close_channel(); return; } + message[n]=0; + if(sscanf(message,"%7s %31s %39s %15s %31s",version,code,id,mode,phase)!=5) { close_channel(); return; } + snprintf(canonical,sizeof(canonical),"%s %s %s %s %s",version,code,id,mode,phase); + if(strcmp(canonical,message) || strcmp(version,"C4M1") || !word(code) || !word(phase) || + (!mode_name(mode) && strcmp(mode,"none")) || !identifier(id)) { close_channel(); return; } + if(request_id[0] && strcmp(request_id,id)) { close_channel(); return; } + snprintf(cached,sizeof(cached),"operation=%s mode=%s result=%s phase=%s",id,mode,code,phase); + Com_Printf(CON_CHANNEL_SERVER,"MODE_STATUS %s\n%s\n",cached,result_text(code)); + if(notify_peer) NET_OutOfBandPrint(NS_SERVER,&peer,"print\nMODE_STATUS %s\n%s\n",cached,result_text(code)); + if(!strcmp(code,"accepted") && request_id[0]) { + snprintf(announcement,sizeof(announcement),"^3Mode change to %s accepted. Server restarting; reconnect shortly.",mode); + SV_SayToPlayers(-1,-1,announcement); + ack_pending=qtrue; + return; + } + close_channel(); +#endif +} diff --git a/src/sv_mode_bridge.h b/src/sv_mode_bridge.h new file mode 100644 index 00000000..64a4b9ac --- /dev/null +++ b/src/sv_mode_bridge.h @@ -0,0 +1,10 @@ +/* Authenticated ingress only. AGPL-3.0-or-later. */ +#ifndef SV_MODE_BRIDGE_H +#define SV_MODE_BRIDGE_H +#include "q_shared.h" +#include "sys_net.h" +qboolean SV_RconModeIngress(const char *raw, int power, const netadr_t *reply, qboolean framing); +qboolean SV_RconModeFraming(const byte *wire, int length); +qboolean SV_RconModeCommand(const char *raw); +void SV_ModeBridgeFrame(void); +#endif diff --git a/src/webadmin.c b/src/webadmin.c index 5f0f0c63..c32a4cf6 100644 --- a/src/webadmin.c +++ b/src/webadmin.c @@ -559,7 +559,7 @@ void Webadmin_ConsoleCommand(xml_t* xmlobj, const char* command, uint64_t steami // start redirecting all print outputs to the packet powercmd = Cmd_GetPower(cmd); - if(powercmd > power) + if(powercmd < 0 || powercmd > power) { XA(" Insufficient permissions! "); return; @@ -605,8 +605,9 @@ void Webadmin_BuildLoginForm(xml_t* xmlobj, qboolean badtry, const char* banmsg) } -void Webadmin_BuildMessage(msg_t* msg, const char* username, qboolean invalidloginattempt, const char* banmsg, const char* url, httpPostVals_t* values) +void Webadmin_BuildMessage(msg_t* msg, authData_admin_t* authenticated, qboolean invalidloginattempt, const char* banmsg, const char* url, httpPostVals_t* values) { + const char *username = authenticated ? authenticated->username : NULL; xml_t xmlbase; xml_t* xmlobj = &xmlbase; @@ -652,7 +653,7 @@ void Webadmin_BuildMessage(msg_t* msg, const char* username, qboolean invalidlog Webadmin_BuildLoginForm(xmlobj, invalidloginattempt, banmsg); }else { - steamid = Auth_GetSteamID(username); + steamid = authenticated->steamid; if(!Q_strncmp(url +9, "/listadmins", 11)) { Webadmin_BuildAdminList(xmlobj, steamid); @@ -678,7 +679,7 @@ void Webadmin_BuildMessage(msg_t* msg, const char* username, qboolean invalidlog if(Webadmin_GetUrlVal( url, "action", actionval, sizeof(actionval)))//nnjpls { if (strcmp(actionval, "logout") == 0) { - Auth_WipeSessionId(username); + authenticated->sessionid[0] = '\0'; }else{ @@ -802,6 +803,7 @@ qboolean HTTPCreateWebadminMessage(ftRequest_t* request, msg_t* msg, char* sessi qboolean invalidlogin = qfalse; const char* username = NULL; const char* password = NULL; + authData_admin_t *authenticated = NULL; if(SV_PlayerBannedByip(&request->remote, banmsg, sizeof(banmsg))) @@ -810,7 +812,8 @@ qboolean HTTPCreateWebadminMessage(ftRequest_t* request, msg_t* msg, char* sessi return qtrue; } - username = Auth_FindSessionID(sessionkey); + authenticated = Auth_FindSessionAdmin(sessionkey); + username = authenticated ? authenticated->username : NULL; if(username == NULL) { @@ -842,12 +845,13 @@ qboolean HTTPCreateWebadminMessage(ftRequest_t* request, msg_t* msg, char* sessi if(session != NULL) { strcpy(sessionkey, session); + authenticated = Auth_FindSessionAdmin(sessionkey); } }else{ Com_Printf(CON_CHANNEL_SERVER,"Already logged in as: %s\n", username); } - Webadmin_BuildMessage(msg, username, invalidlogin, NULL, request->url, values); + Webadmin_BuildMessage(msg, authenticated, invalidlogin, NULL, request->url, values); return qtrue; } diff --git a/tests/rcon_harness.c b/tests/rcon_harness.c index 8d0412d4..e5638671 100644 --- a/tests/rcon_harness.c +++ b/tests/rcon_harness.c @@ -27,6 +27,11 @@ int cvar_modifiedFlags; static struct { netadr_t redirectAddress; } svs; static struct { int rconBucket; } querylimit; static int executed, ban_seconds, source_id; +qboolean SV_RconModeFraming(const byte *wire, int length); +static qboolean SV_RconModeIngress(const char *raw,int power,const netadr_t *peer,qboolean framing) { + (void)peer; assert(power==100); if(strncmp(raw,"change_mode",11)) return qfalse; + strcpy(response,framing?"INGRESS_ALLOWED":"INGRESS_INVALID"); return qtrue; +} static void Cmd_TokenizeStringInternal(const char *, qboolean, cmdTokenizeParams_t *); static int Cvar_SetVariant(cvar_t *, CvarValue, qboolean); static void Com_Printf(int channel, const char *fmt, ...) { @@ -41,6 +46,7 @@ static void Com_Printf(int channel, const char *fmt, ...) { static void Sys_EnterCriticalSection(int n) { (void)n; } static void Sys_LeaveCriticalSection(int n) { (void)n; } int Q_stricmp(const char *a, const char *b) { return strcasecmp(a,b); } +int Q_stricmpn(const char *a,const char *b,int n) { return strncasecmp(a,b,n); } static void FreeString(const char *s) { free((void *)s); } static char *CopyString(const char *s) { return strdup(s); } void Q_strncpyz(char *d, const char *s, int n) { snprintf(d,n,"%s",s); } @@ -75,7 +81,11 @@ static void Cmd_ExecuteSingleCommand(int a,int b,const char *s) { (void)a;(void)b; executed=1; snprintf(response,sizeof(response),"EXECUTED:%s",s); } static int SV_PlayerBannedByip(netadr_t *a,char *b,int n) { (void)a;(void)b;(void)n;return 0; } -static int Auth_Authorize(const char *u,const char *p) { (void)u;(void)p;return -1; } -static uint64_t Auth_GetSteamID(const char *u) { (void)u;return 0; } +typedef struct { uint64_t steamid; char username[32]; } authData_admin_t; +static int auth_handle=-1, identity_lookups; +static authData_admin_t authorized_record={42,"76561198000000999"}; +static int Auth_Authorize(const char *u,const char *p) { (void)u;(void)p;return auth_handle; } +static authData_admin_t *Auth_GetAdminFromIndex(int index) { return index==0?&authorized_record:NULL; } +static uint64_t Auth_GetSteamID(const char *u) { (void)u;identity_lookups++;return 999; } static int Com_GetRealtime(void) { return 1000; } static void SV_PlayerAddBanByip(netadr_t *a,const char *r,int until) { (void)a;(void)r;ban_seconds=until-1000; } diff --git a/tests/rcon_harness_main.c b/tests/rcon_harness_main.c index e43657ef..eed30f4a 100644 --- a/tests/rcon_harness_main.c +++ b/tests/rcon_harness_main.c @@ -4,12 +4,27 @@ int main(int argc,char **argv) { password_var.string=nullstring; password_var.latchedString=nullstring; if(argc==3) { - assert(!strcmp(argv[1],"--source")); + int bound=!strcmp(argv[1],"--source-bound"); + int zero=!strcmp(argv[1],"--source-zero"); + int console=!strcmp(argv[1],"--source-console"); + assert(bound || zero || console || !strcmp(argv[1],"--source")); + if(bound || zero)auth_handle=0; + if(zero)authorized_record.steamid=0; Cvar_Set2("rcon_password","SyntheticServerPassword",qfalse); byte packet[1024]={0}; msg_t m; MSG_Init(&m,packet,sizeof(packet)); MSG_WriteLong(&m,10+strlen(argv[2])); MSG_WriteLong(&m,7); MSG_WriteLong(&m,3); strcpy((char *)packet+m.cursize,argv[2]); m.cursize+=strlen(argv[2])+2; netadr_t from={0}; rconUser_t user={0}; + if(console) { + assert(HL2Rcon_SourceRconAuth(&from,&m,&user)); + assert(user.steamid==0 && !strcmp(user.rconUsername,"console")); + puts("source_master_console_authenticated=1");return 0; + } + if(bound) { + assert(HL2Rcon_SourceRconAuth(&from,&m,&user)); + assert(user.steamid==42 && identity_lookups==0); + puts("source_bound_to_verified_record=1 steamid=42");return 0; + } assert(!HL2Rcon_SourceRconAuth(&from,&m,&user)); assert(strstr(logs,"Bad rcon from 127.0.0.1\n")); assert(!strstr(logs,argv[2])); @@ -36,6 +51,7 @@ int main(int argc,char **argv) { MSG_ReadLong(&msg); MSG_ReadStringLine(&msg,text,sizeof(text)); Cmd_TokenizeString(text); assert(!strcmp(Cmd_Argv(0),"rcon")); netadr_t from={sock}; SVC_RemoteCommand(&from,&msg); + assert(!strstr(logs,"MODE_SECRET_CANARY")); assert(sendto(sock,response,strlen(response),0,(struct sockaddr *)&client,size)>=0); printf("cfg_length=%zu cfg_equal=%d\n",strlen(password_var.string),!strcmp(password_var.string,expected)); close(sock); FreeString(password_var.string); FreeString(password_var.latchedString); diff --git a/tests/run_btd_integration.py b/tests/run_btd_integration.py index 1a5ba157..9d6d59f0 100644 --- a/tests/run_btd_integration.py +++ b/tests/run_btd_integration.py @@ -77,8 +77,10 @@ def value(name): checks[f'{attempt}_classic_policy'] = value('btd_anticamp') == '0' and value('btd_msg2') == 'Server admins are pitta' checks[f'{attempt}_bad_password'] = 'Bad rcon' in rcon('change_mode zombies', 'invalid-fixture') checks[f'{attempt}_status'] = fs_game in rcon('change_mode') and 'targets: none' in rcon('change_mode') - for requested in ('zombies', 'promod', 'hardcore', 'unknown'): + for requested in ('zombies', 'promod'): checks[f'{attempt}_unavailable_{requested}'] = 'Runtime unchanged' in rcon('change_mode ' + requested) + for requested in ('hardcore', 'unknown'): + checks[f'{attempt}_unsupported_{requested}'] = 'Unsupported mode' in rcon('change_mode ' + requested) for invalid in ('../zombies', 'mods/btd_alpha_001', 'https://example.invalid', 'zombies;quit'): checks[f'{attempt}_invalid_{invalid}'] = 'Invalid mode' in rcon('change_mode ' + invalid) with ThreadPoolExecutor(max_workers=2) as executor: diff --git a/tests/test_auth_hardening.py b/tests/test_auth_hardening.py new file mode 100644 index 00000000..44816cb1 --- /dev/null +++ b/tests/test_auth_hardening.py @@ -0,0 +1,106 @@ +"""Execute production authorization functions at privilege and identity boundaries.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +from test_rcon import function +ROOT=Path(__file__).resolve().parents[1] + +def execute(source): + with tempfile.TemporaryDirectory() as d: + path=Path(d)/'auth.c';binary=Path(d)/'auth';path.write_text(source) + subprocess.run(['gcc',str(path),'-o',str(binary)],check=True) + subprocess.run([str(binary)],check=True) + +class AuthHardening(unittest.TestCase): + def test_password_reset_cannot_take_over_higher_or_equal_role(self): + source=r''' +#include +#include +#include +#include +#include +#define CON_CHANNEL_DONT_FILTER 0 +static int invoker=95,target=100,changed,argc=3;static char output[1024]; +int Cmd_Argc(void){return argc;} +char *Cmd_Argv(int n){return n==1?"owner":"NEW_SECRET_CANARY";} +int Cmd_GetInvokerPower(void){return invoker;} +uint64_t Auth_GetSteamID(const char *name){return 42;} +int Auth_GetClPowerBySteamID(uint64_t id){return target;} +void Auth_ChangeAdminPassword(uint64_t id,const char *password){assert(id==42);changed++;} +void Com_Printf(int channel,const char *fmt,...){va_list ap;va_start(ap,fmt);vsnprintf(output,sizeof(output),fmt,ap);va_end(ap);} +#define Com_PrintError Com_Printf +''' + source+=function('src/sv_auth.c','void Auth_ChangePasswordByMasterAdmin_f(') + source+=r''' +int main(void){ + Auth_ChangePasswordByMasterAdmin_f();assert(!changed && !strstr(output,"NEW_SECRET_CANARY")); + target=95;Auth_ChangePasswordByMasterAdmin_f();assert(!changed); + target=50;Auth_ChangePasswordByMasterAdmin_f();assert(changed==1); + invoker=100;target=100;Auth_ChangePasswordByMasterAdmin_f();assert(changed==2); + invoker=20;target=100;Auth_ChangePasswordByMasterAdmin_f();assert(changed==2); + return 0; +} +''' + execute(source) + + def test_web_console_denies_unregistered_cvars_and_keeps_registered_permissions(self): + source=r''' +#include +#include +#include +#include +#define SV_OUTPUTBUF_LENGTH 4096 +#define XA(text) (++denied) +typedef int qboolean;typedef struct{int x;}xml_t; +static xml_t *xmlobjFlush;static int power=20,executed,denied; +int Cmd_GetInvokerPower(void){return power;} +int Cmd_GetPower(const char *name){return !strcmp(name,"bot_status")?20:-1;} +void Q_strncpyz(char *out,const char *s,int n){snprintf(out,n,"%s",s);} +void Q_strchrrepl(char *s,char a,char b){for(;*s;s++)if(*s==a){*s=b;break;}} +void Webadmin_FlushRedirect(char *s,qboolean last){} +void Com_BeginRedirect(char*b,int n,void(*f)(char*,qboolean)){} +void Com_EndRedirect(void){} +void Cmd_ExecuteSingleCommand(int a,int b,const char *text){executed++;} +''' + source+=function('src/webadmin.c','void Webadmin_ConsoleCommand(') + source+=r''' +int main(void){ + xml_t xml; + Webadmin_ConsoleCommand(&xml,"rcon_password",42);assert(!executed && denied==1); + Webadmin_ConsoleCommand(&xml,"rcon_password attacker",42);assert(!executed && denied==2); + Webadmin_ConsoleCommand(&xml,"bot_status",42);assert(executed==1); + power=100;Webadmin_ConsoleCommand(&xml,"rcon_password",42);assert(executed==2); + return 0; +} +''' + execute(source) + + def test_web_session_binds_record_despite_numeric_or_duplicate_names(self): + source=r''' +#include +#include +#include +#include +#define MAX_AUTH_ADMINS 4 +typedef struct {char username[32],sessionid[65];uint64_t steamid;}authData_admin_t; +static struct {authData_admin_t admins[MAX_AUTH_ADMINS];}auth_admins; +int Q_stricmp(const char *a,const char *b){return strcasecmp(a,b);} +''' + source+=function('src/sv_auth.c','authData_admin_t* Auth_FindSessionAdmin(') + source+=function('src/sv_auth.c','authData_admin_t* Auth_GetAdminFromIndex(') + source+=r''' +int main(void){ + authData_admin_t *low=&auth_admins.admins[0],*high=&auth_admins.admins[1]; + strcpy(low->username,"76561198000000999");low->steamid=42;memset(low->sessionid,'a',64); + strcpy(high->username,low->username);high->steamid=999;memset(high->sessionid,'b',64); + assert(Auth_FindSessionAdmin(low->sessionid)==low && Auth_FindSessionAdmin(high->sessionid)==high); + strcpy(low->username,"renamed");assert(Auth_FindSessionAdmin(low->sessionid)==low); + assert(!Auth_FindSessionAdmin(0) && !Auth_FindSessionAdmin("short")); + low->sessionid[0]=0;assert(!Auth_FindSessionAdmin("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")); + assert(!Auth_GetAdminFromIndex(-1) && !Auth_GetAdminFromIndex(MAX_AUTH_ADMINS)); + assert(Auth_GetAdminFromIndex(0)==low); + return 0; +} +''' + execute(source) diff --git a/tests/test_mode_bridge.c b/tests/test_mode_bridge.c new file mode 100644 index 00000000..390fca28 --- /dev/null +++ b/tests/test_mode_bridge.c @@ -0,0 +1,72 @@ +/* Execute the actual bridge with controlled IPC boundaries; no host actions. */ +#define socket test_socket +#define connect test_connect +#define getsockopt test_getsockopt +#define send test_send +#define recvmsg test_recvmsg +#define close test_close +#define time test_time +#include "../src/sv_mode_bridge.c" +#undef assert +#include +#include +static int sockets, sends, broadcasts, root_peer=1, nonce; +static unsigned char incoming[512]; +static int incoming_size, incoming_flags; +static char output[2048], sent[256]; +time_t test_time(time_t *p) { if(p) *p=1000; return 1000; } +int test_socket(int domain,int type,int protocol) { assert(domain==AF_UNIX && type&SOCK_NONBLOCK); sockets++; return 42; } +int test_connect(int fd,const struct sockaddr *a,socklen_t n) { assert(fd==42); return 0; } +int test_getsockopt(int fd,int level,int option,void *data,socklen_t *size) { + assert(option==SO_PEERCRED); ((struct ucred*)data)->uid=root_peer?0:1000; return 0; +} +ssize_t test_send(int fd,const void *data,size_t size,int flags) { + assert(fd==42 && flags&MSG_DONTWAIT); assert(sizemsg_iov[0].iov_base,incoming,incoming_size); + header->msg_flags=incoming_flags;int n=incoming_size;incoming_size=0;return n; +} +int test_close(int fd) { assert(fd==42); return 0; } +qboolean Sys_RandomBytes(byte *data,int n) { memset(data,++nonce,n); return qtrue; } +void Com_Printf(conChannel_t channel,const char *fmt,...) { + va_list ap;va_start(ap,fmt);vsnprintf(output,sizeof(output),fmt,ap);va_end(ap); +} +int Q_stricmpn(const char*a,const char*b,int n) { return strncasecmp(a,b,n); } +void SV_SayToPlayers(int cl,int team,char *text) { broadcasts++;assert(strstr(text,"accepted")); } +void NET_OutOfBandPrint(netsrc_t sock,netadr_t *adr,const char *fmt,...) { } +const char *Cvar_VariableStringBuffer(const char *name,char *buffer,int n) { snprintf(buffer,n,"mods/pml220");return buffer; } +static void reset(void) { close_channel();sockets=sends=broadcasts=0;output[0]=0;incoming_size=incoming_flags=0;root_peer=1; } +static void receive(const char *code,const char *id,const char *mode,const char *phase) { + incoming_size=snprintf((char*)incoming,sizeof(incoming),"C4M1 %s %s %s %s",code,id,mode,phase); +} +int main(void) { + const char *bad[]={"hardcore","Zombies","promod;quit","promod //comment","\"promod\"","promod extra","promod\nquit","../zombies","$(id)","promod\t"}; + reset(); + for(int p=0;p<100;p++) {assert(SV_RconModeIngress("change_mode zombies",p,NULL,qtrue));assert(!sockets);assert(strstr(output,"Permission denied"));} + for(unsigned i=0;i=0 && !strstr(sent,"C4M1 notified")); + SV_ModeBridgeFrame();assert(strstr(sent,"C4M1 notified") && channel<0); + reset();SV_RconModeIngress("change_mode promod",100,NULL,qtrue); + receive("accepted","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","promod","pending");SV_ModeBridgeFrame();assert(!broadcasts); + reset();assert(submit(NULL,NULL));receive("rolled_back","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","zombies","rolled_back"); + SV_ModeBridgeFrame();assert(strstr(cached,"result=rolled_back") && !broadcasts); + puts("mode bridge: bounded IPC, root peer, strict grammar, permissions, reply binding and notification passed"); + return 0; +} diff --git a/tests/test_mode_bridge.py b/tests/test_mode_bridge.py new file mode 100644 index 00000000..f9b62215 --- /dev/null +++ b/tests/test_mode_bridge.py @@ -0,0 +1,62 @@ +"""Native authenticated bridge policy; no game assets or Docker privileges.""" +from pathlib import Path +import subprocess +import tempfile +import unittest +ROOT = Path(__file__).resolve().parents[1] +class ModeBridge(unittest.TestCase): + def test_native_policy_and_ipc(self): + with tempfile.TemporaryDirectory() as d: + binary=Path(d)/'bridge' + subprocess.run(['gcc','-m32','-D_GNU_SOURCE','-ffunction-sections','-fdata-sections', + '-Wl,--gc-sections','-fno-pie','-no-pie',str(ROOT/'tests/test_mode_bridge.c'),'-o',str(binary)],check=True) + subprocess.run([str(binary)],check=True) + + def test_source_rcon_restores_context_after_rejected_command(self): + from test_rcon import function + fixture=r''' +#include +#include +#include +#include +#include +#define SV_OUTPUTBUF_LENGTH 4096 +#define CON_CHANNEL_DONT_FILTER 0 +static int current=73,client=8,auth_power=20,ended,executed; +static uint64_t identity=99; +static char invoker[64]="previous"; +int Cmd_GetInvokerPower(void){return current;} +int Cmd_GetInvokerClnum(void){return client;} +uint64_t Cmd_GetInvokerSteamID(void){return identity;} +const char *Cmd_GetInvokerName(char *out,int n){snprintf(out,n,"%s",invoker);return out;} +void Cmd_SetCurrentInvokerInfo(int p,int c,uint64_t id,const char *name){current=p;client=c;identity=id;snprintf(invoker,sizeof(invoker),"%s",name);} +int Auth_GetClPowerBySteamID(uint64_t id){return auth_power;} +const char *Auth_GetNameBySteamID(uint64_t id){return "admin";} +void HL2Rcon_SourceRconFlushRedirect(char *s){} +void Com_BeginRedirect(char *b,int n,void(*f)(char*)){} +void Com_EndRedirect(void){ended++;} +void Com_Printf(int channel,const char *fmt,...){} +void Q_strncpyz(char *out,const char *value,int n){snprintf(out,n,"%s",value);} +void Q_strchrrepl(char *s,char from,char to){for(;*s;s++)if(*s==from){*s=to;break;}} +int Q_stricmpn(const char*a,const char*b,int n){return strncasecmp(a,b,n);} +int Cmd_GetPower(const char *s){return !strcmp(s,"rcon_password")?-1:100;} +void Cmd_ExecuteSingleCommand(int a,int b,const char*s){executed++;} +void HL2Rcon_StatusCommand(void){} +''' + fixture+=function('src/hl2rcon.c','void HL2Rcon_ExecuteConsoleCommand(') + fixture+=r''' +int main(void){ + const char *bad[]={"x","abcdefghijklmnopqrstuvwxyz0123456789","change_mode zombies","rcon_password","rcon_password attacker"}; + for(unsigned i=0;i<5;i++){ + HL2Rcon_ExecuteConsoleCommand(bad[i],123); + assert(current==73 && client==8 && identity==99 && !strcmp(invoker,"previous")); + assert(ended==(int)i+1 && executed==0); + } + auth_power=100;HL2Rcon_ExecuteConsoleCommand("rcon_password",123);assert(executed==1 && current==73); + return 0; +} +''' + with tempfile.TemporaryDirectory() as d: + source=Path(d)/'source.c';source.write_text(fixture);binary=Path(d)/'source' + subprocess.run(['gcc',str(source),'-o',str(binary)],check=True) + subprocess.run([str(binary)],check=True) diff --git a/tests/test_rcon.py b/tests/test_rcon.py index f54ebea3..a9f06ea9 100644 --- a/tests/test_rcon.py +++ b/tests/test_rcon.py @@ -32,6 +32,8 @@ def setUpClass(cls): path = Path(cls.workspace.name) pieces = [(ROOT / 'tests/rcon_harness.c').read_text()] for file, signature in [ + ('src/sv_mode_bridge.c', 'qboolean SV_RconModeFraming('), + ('src/sv_mode_bridge.c', 'qboolean SV_RconModeCommand('), ('src/msg.c', 'char *MSG_ReadStringLine('), ('src/cmd.c', 'static void Cmd_TokenizeStringInternal('), ('src/cvar.c', 'static int Cvar_SetVariant( cvar_t *var, CvarValue value ,qboolean force ) {'), @@ -73,6 +75,31 @@ def udp(self, length, quoted=False, wrong=False, command='status', packet=None): process.kill() process.communicate() + def test_mode_ingress_requires_authentication_and_complete_wire_frame(self): + self.assertEqual(self.udp(16, command='change_mode promod'), b'INGRESS_ALLOWED') + self.assertEqual(self.udp(16, wrong=True, command='change_mode promod'), b'Bad rcon') + self.assertIn(b'shorter than 8', self.udp(7, command='change_mode promod')) + password = ('Ab9' * 400)[:16] + for suffix in (b'\nquit', b'\0quit', b'\rquit'): + packet = b'\xff' * 4 + f'rcon {password} change_mode promod'.encode() + suffix + self.assertEqual(self.udp(16, packet=packet), b'INGRESS_INVALID') + + def test_source_identity_uses_verified_record_not_numeric_name(self): + result=subprocess.run([str(self.binary),'--source-bound', + '76561198000000999 SyntheticAccountPassword'],text=True,capture_output=True,check=True) + self.assertIn('source_bound_to_verified_record=1 steamid=42',result.stdout) + + def test_mode_request_logs_omit_untrusted_arguments(self): + self.assertEqual(self.udp(16,command='change_mode promod MODE_SECRET_CANARY'),b'INGRESS_ALLOWED') + + def test_source_zero_account_cannot_impersonate_master_console(self): + rejected=subprocess.run([str(self.binary),'--source-zero','console SyntheticAccountPassword'], + text=True,capture_output=True,check=True) + self.assertIn('source_rejected=1',rejected.stdout) + master=subprocess.run([str(self.binary),'--source-console','SyntheticServerPassword'], + text=True,capture_output=True,check=True) + self.assertIn('source_master_console_authenticated=1',master.stdout) + def test_udp_lengths_and_quotes(self): for length in (16, 23, 24, 28, 29, 32, 48, 64): for quoted in (False, True):