diff --git a/docs/security/http-web-boundaries.md b/docs/security/http-web-boundaries.md new file mode 100644 index 00000000..e1a3a644 --- /dev/null +++ b/docs/security/http-web-boundaries.md @@ -0,0 +1,70 @@ +# HTTP and Web Console security boundaries + +Independent review of protected engine master +`6c3f326ca2ebb5f72b7af32976560e9e52a3c516` confirmed three issues using isolated +production-function fixtures, without contacting a running game server: + +- A pending HTTP request resized its receive buffer to the declared final length + and then copied an entire larger TCP chunk. AddressSanitizer confirmed a heap + overwrite. The same parser lacked a guaranteed form terminator and useful + header/body limits; an empty session cookie caused an out-of-bounds read. +- Player names passed through the name cleaner and color converter into raw HTML + in the authenticated Web Console. An isolated rendering fixture preserved + event-bearing markup. An administrator viewing such a name could execute + attacker-controlled script with that administrator's browser authority. +- HTTP session cookies and password-changing RCON command arguments entered + diagnostic logs. Browser sessions also remained valid after password recovery. + +Live HTTP/TCP reachability and exploitation were not tested. These are confirmed +code boundaries, not evidence that a production endpoint was compromised. + +The HTTP server now accepts at most 16,384 bytes of headers and 65,536 bytes of +body. It sizes memory from checked received-byte counts, reserves a terminator, +requires complete CRLF header framing and exact method separators, and rejects +excess input, overlong lines, duplicate/overflowing lengths and unsupported +Transfer-Encoding. It supports a single request followed by connection closure; +HTTP pipelining and uploads are not supported by this administrative endpoint. +Client-side HTTP download/status parsing is unchanged. + +Web text and console output are entity-escaped. Only fixed color spans are emitted +as markup, with space reserved for balanced closing spans. Console line breaks +and tabs remain readable. Cookies require the exact session name and a complete +64-character hexadecimal bearer. Responses add `SameSite=Strict` alongside +`HttpOnly`; this does not provide encryption or replace a CSRF token/Origin check. + +HTTP bearer and URL logging is removed. UDP/Source RCON diagnostic logs retain the +request source and an argument-omitted marker, rather than arbitrary command +text. This deliberately reduces log detail because command aliases and cvar +setters can carry passwords. Command execution and authorized responses retain +their existing behavior. + +Password and credential-record replacement revoke existing **browser** sessions. +This change does not expire browser sessions or invalidate established Source +RCON TCP connections after password rotation. Account connections continue to +check current permissions; established shared-password console connections retain +their original console identity. Connection revocation/auth generations, browser +expiry, protected administrative transport and CSRF defenses require separate +focused review. Credentials disclosed in historical logs require an operator-led +exposure assessment; no credential rotation is performed by this patch. + +Validation: `make -j4` and the 83-test Python suite passed (one optional +client-checkout test skipped). The three new Web security tests execute actual +production functions. HTTP and HTML fixtures run with AddressSanitizer and +UndefinedBehaviorSanitizer; the session fixture verifies recovery invalidation. +They cover fragmented valid requests, excess bytes, length overflow/duplicates, +header/method/cookie boundaries, escaped markup, color truncation and console +formatting. UDP RCON tests use synthetic credential-command canaries and assert +that the canary is absent from captured diagnostic logs. + +```sh +python3 -m unittest discover -s tests -p 'test_web_security.py' +python3 -m unittest discover -s tests -p 'test_*.py' +make -j4 +``` + +Independent source review verified this focused change. Tests and review do not +establish whole-engine memory safety or a secure infrastructure baseline. This +patch does not install/enable the mode bridge, change production, deploy images, +rotate credentials or modify infrastructure. Retain the bridge release gates. +Rollback is a reviewed code revert; it reintroduces the documented weaknesses and +must not be used to bypass security qualification. diff --git a/src/hl2rcon.c b/src/hl2rcon.c index e61eaa67..60058e5a 100644 --- a/src/hl2rcon.c +++ b/src/hl2rcon.c @@ -608,7 +608,7 @@ int HL2Rcon_SourceRconEvent(netadr_t *from, msg_t *msg, int connectionId){ MSG_ReadByte(msg); Com_Printf(CON_CHANNEL_DONT_FILTER,"Rcon from: %s command: %s\n", NET_AdrToString(from), - SV_RconModeCommand(command) ? "change_mode request (arguments omitted)" : command); + SV_RconModeCommand(command) ? "change_mode request (arguments omitted)" : "remote command (arguments omitted)"); sourceRcon.redirectUser = connectionId+1; sourceRcon.writeerror = 0; diff --git a/src/httpftp.c b/src/httpftp.c index 07ab561d..da13e496 100644 --- a/src/httpftp.c +++ b/src/httpftp.c @@ -2018,6 +2018,12 @@ static int FTP_SendReceiveData(ftRequest_t* request) */ #ifndef DEMOEXT +/* The built-in HTTP service accepts small administrative forms, not uploads. + * These limits also bound incomplete requests before any length arithmetic. */ +#define HTTP_SERVER_MAX_HEADER 16384 +#define HTTP_SERVER_MAX_BODY 65536 +#define HTTP_SERVER_MAX_REQUEST (HTTP_SERVER_MAX_HEADER + HTTP_SERVER_MAX_BODY) + int HTTPServer_ReadMessage(netadr_t* from, msg_t* msg, ftRequest_t* request) { @@ -2025,7 +2031,7 @@ int HTTPServer_ReadMessage(netadr_t* from, msg_t* msg, ftRequest_t* request) byte* newbuf; char* line; int newsize, i; - qboolean gotheader; + qboolean gotheader, haveContentLength = qfalse; if(request->remote.type == 0) { @@ -2034,60 +2040,67 @@ int HTTPServer_ReadMessage(netadr_t* from, msg_t* msg, ftRequest_t* request) } - if (request->recvmsg.maxsize - request->recvmsg.cursize < msg->cursize) + /* Do not size allocations from Content-Length while copying a larger TCP + * chunk. This service closes each response, so pipelined/excess data is + * rejected rather than interpreted as another request. Reserve a NUL for + * the form parser, including requests ending exactly at buffer capacity. */ + if (msg->cursize < 0 || request->recvmsg.cursize < 0 || + request->recvmsg.cursize > HTTP_SERVER_MAX_REQUEST || + msg->cursize > HTTP_SERVER_MAX_REQUEST - request->recvmsg.cursize) + return -1; + newsize = request->recvmsg.cursize + msg->cursize; + if (request->finallen != -1 && newsize > request->finallen) + return -1; + if (request->recvmsg.maxsize < newsize + 1) { - if(request->finallen != -1) - { - newsize = request->finallen; - }else { - newsize = 2 * request->recvmsg.maxsize + msg->cursize; - } - - newbuf = L_Malloc(newsize); - if(newbuf == NULL) - { - return -1; - } - - Com_Memcpy(newbuf, request->recvmsg.data, request->recvmsg.cursize); - + newbuf = L_Malloc(newsize + 1); + if (!newbuf) return -1; + if (request->recvmsg.cursize) + Com_Memcpy(newbuf, request->recvmsg.data, request->recvmsg.cursize); L_Free(request->recvmsg.data); request->recvmsg.data = newbuf; - request->recvmsg.maxsize = newsize; - + request->recvmsg.maxsize = newsize + 1; } - - Com_Memcpy(&request->recvmsg.data[request->recvmsg.cursize], msg->data, msg->cursize); - - request->recvmsg.cursize += msg->cursize; + if (msg->cursize) + Com_Memcpy(request->recvmsg.data + request->recvmsg.cursize, msg->data, msg->cursize); + request->recvmsg.cursize = newsize; + request->recvmsg.data[newsize] = '\0'; /* Is header complete ? */ if(request->finallen == -1) { gotheader = qfalse; - /* 1st check if the header is complete */ - while ((line = MSG_ReadStringLine(&request->recvmsg, stringlinebuf, sizeof(stringlinebuf))) && line[0] != '\0' ) + /* Locate framing on raw bytes, never on a truncated/string-decoded line. */ + for (i = 0; i + 3 < request->recvmsg.cursize; ++i) { - if(line[0] == '\r') + if (!memcmp(request->recvmsg.data + i, "\r\n\r\n", 4)) { + request->headerLength = i + 4; gotheader = qtrue; break; } } - if(gotheader == qfalse) + if (!gotheader) + return request->recvmsg.cursize >= HTTP_SERVER_MAX_HEADER ? -1 : 0; + if (request->headerLength > HTTP_SERVER_MAX_HEADER || + memchr(request->recvmsg.data, '\0', request->headerLength)) return -1; + /* MSG_ReadStringLine must never truncate a framing/header line. */ + newsize = 0; + for (i = 0; i < request->headerLength; ++i) { - return 0; + if (request->recvmsg.data[i] == '\n') newsize = 0; + else if (++newsize >= sizeof(stringlinebuf) - 1) return -1; } MSG_BeginReading(&request->recvmsg); line = MSG_ReadStringLine(&request->recvmsg, stringlinebuf, sizeof(stringlinebuf)); - if (!Q_strncmp(line, "HEAD", 4)) { + if (!Q_strncmp(line, "HEAD ", 5)) { request->mode = HTTP_HEAD; line += 5; - }else if (!Q_strncmp(line, "POST", 4)) { + }else if (!Q_strncmp(line, "POST ", 5)) { request->mode = HTTP_POST; line += 5; - }else if (!Q_strncmp(line, "GET", 3)) { + }else if (!Q_strncmp(line, "GET ", 4)) { request->mode = HTTP_GET; line += 4; }else { @@ -2098,17 +2111,19 @@ int HTTPServer_ReadMessage(netadr_t* from, msg_t* msg, ftRequest_t* request) i = 0; while (*line != ' ' && *line != '\r' && *line) { + if (i >= sizeof(request->url) - 1) return -1; request->url[i] = *line; i++; line++; } + request->url[i] = '\0'; if(*line == ' ') { line++; } - if(Q_stricmpn(line,"HTTP/1.",7) || isInteger(line + 7, 2) == qfalse || isInteger(line + 9, 4) == qfalse) + if(strcmp(line, "HTTP/1.0\r") && strcmp(line, "HTTP/1.1\r")) { Com_PrintError(CON_CHANNEL_FILEDL,"HTTP_ReceiveData: Packet is corrupt!\nDebug: %s\n", line); @@ -2130,17 +2145,25 @@ int HTTPServer_ReadMessage(netadr_t* from, msg_t* msg, ftRequest_t* request) { if(!Q_stricmpn("Content-Length:", line, 15)) { - if(isInteger(line + 15, 0) == qfalse) - { - Com_PrintError(CON_CHANNEL_FILEDL,"Sec_GetHTTPPacket: Packet is corrupt!\nDebug: %s\n", line); - return -1; - } - request->contentLength = atoi(line + 15); - if(request->contentLength < 0) + const char *value = line + 15; + int length = 0; + if (haveContentLength) return -1; + haveContentLength = qtrue; + while (*value == ' ' || *value == '\t') ++value; + if (*value < '0' || *value > '9') return -1; + while (*value >= '0' && *value <= '9') { - request->contentLength = 0; - return -1; + int digit = *value++ - '0'; + if (length > (HTTP_SERVER_MAX_BODY - digit) / 10) return -1; + length = length * 10 + digit; } + while (*value == ' ' || *value == '\t') ++value; + if (*value && strcmp(value, "\r")) return -1; + request->contentLength = length; + } + else if (!Q_stricmpn("Transfer-Encoding:", line, 18)) + { + return -1; /* Chunked/request smuggling framing is unsupported. */ } else if(!Q_stricmpn("Content-Type:", line, 13)) { @@ -2171,10 +2194,9 @@ int HTTPServer_ReadMessage(netadr_t* from, msg_t* msg, ftRequest_t* request) request->headerLength = request->recvmsg.readcount; request->finallen = request->contentLength + request->headerLength; - if(request->finallen > 1024*1024*640) - { - request->finallen = request->headerLength; - } + if (request->headerLength > HTTP_SERVER_MAX_HEADER || + request->recvmsg.cursize > request->finallen) + return -1; } if(request->recvmsg.maxsize == request->finallen) @@ -2202,7 +2224,7 @@ void HTTPServer_BuildMessage( ftRequest_t* request, char* status, char* message, "Content-Length: %d\r\n" "Access-Control-Allow-Origin: none\r\n" "Content-Type: text/html\r\n" - "Set-Cookie: SessionId=%s; Path=/; HttpOnly\r\n" + "Set-Cookie: SessionId=%s; Path=/; HttpOnly; SameSite=Strict\r\n" "\r\n", status, len, sessionkey); @@ -2348,34 +2370,28 @@ const char* HTTP_GetFormDataItem(httpPostVals_t* values, const char* search) void HTTPServer_ReadSessionId(ftRequest_t* request, char* sessionkey, int len) { - char* cookieval; + const char *cursor = request->cookie, *value; int i; - - - cookieval = strstr(request->cookie, "SessionId=" ); - if(cookieval == NULL) + if (len < 1) return; + sessionkey[0] = '\0'; + if (len < 65) return; + while (*cursor) { - sessionkey[0] = '\0'; - return; - } - cookieval += 10; - i = 0; - - while (cookieval[i] != '\0' && cookieval[i] != ';' && cookieval[i] != ' ') { - i++; - } - if(cookieval[i] == ';' && cookieval[i] == ' ') - { - cookieval[i] = '\0'; - } - - Q_strncpyz(sessionkey, cookieval, len); - - if(sessionkey[strlen(sessionkey) -1] == '\r') - { - sessionkey[strlen(sessionkey) -1] = '\0'; + while (*cursor == ' ' || *cursor == '\t' || *cursor == ';') ++cursor; + if (!strncmp(cursor, "SessionId=", 10)) + { + value = cursor + 10; + for (i = 0; i < 64; ++i) + if (!((value[i] >= '0' && value[i] <= '9') || + (value[i] >= 'a' && value[i] <= 'f') || + (value[i] >= 'A' && value[i] <= 'F'))) return; + if (value[64] && value[64] != ';' && value[64] != ' ' && value[64] != '\r') return; + Com_Memcpy(sessionkey, value, 64); + sessionkey[64] = '\0'; + return; + } + while (*cursor && *cursor != ';') ++cursor; } - } #define MAX_HTTPCLIENTS 256 @@ -2449,7 +2465,7 @@ int HTTPServer_Event(netadr_t* from, msg_t* msg, int connectionId) { HTTPServer_ReadSessionId(request, sessionkey, sizeof(sessionkey)); HTTP_ParseFormDataBody((char*)request->recvmsg.data + request->headerLength, values); - Com_Printf(CON_CHANNEL_FILEDL,"SessionID is: %s\n", sessionkey); + /* Session cookies are bearer credentials and must never enter logs. */ HTTPServer_BuildResponse( request, sessionkey, values); diff --git a/src/sv_auth.c b/src/sv_auth.c index be3ee635..0cbcfcb6 100644 --- a/src/sv_auth.c +++ b/src/sv_auth.c @@ -415,6 +415,7 @@ void Auth_ChangeAdminPassword( uint64_t steamid, const char* password ){ Q_strncpyz(user->sha256, sha256, sizeof(user->sha256)); Q_strncpyz(user->salt, (char *)salt, sizeof(user->salt)); + user->sessionid[0] = '\0'; /* Password recovery revokes browser sessions. */ NV_ProcessEnd(); @@ -519,6 +520,7 @@ qboolean Auth_AddAdminToList(const char* username, const char* password, const c { Q_strncpyz(user->sha256, password, sizeof(user->sha256)); Q_strncpyz(user->salt, salt, sizeof(user->salt)); + user->sessionid[0] = '\0'; } if(power > 0 && power > user->power) diff --git a/src/sv_main.c b/src/sv_main.c index 14606160..0863d172 100644 --- a/src/sv_main.c +++ b/src/sv_main.c @@ -1532,7 +1532,7 @@ __optimize3 __regparm2 static void SVC_RemoteCommand( netadr_t *from, msg_t *msg 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 ); + SV_RconModeCommand(cmd_aux) ? "change_mode request (arguments omitted)" : "remote command (arguments omitted)" ); Com_BeginRedirect (sv_outputbuf, SV_OUTPUTBUF_LENGTH, SV_FlushRedirect); if (SV_RconModeIngress(cmd_aux, 100, from, diff --git a/src/webadmin.c b/src/webadmin.c index c32a4cf6..bfa25012 100644 --- a/src/webadmin.c +++ b/src/webadmin.c @@ -38,49 +38,70 @@ char* htmlq3colors[] = { "#000000", "#FF0000", "#00FF00", "#FFFF00", "#7B8FB0", "#A69169" }; -char* Webadmin_ConvertToHTMLColor(char* qcolorstr, char* hcolorstr, int maxlen) +/* Append untrusted text, never markup, without truncating long console output. */ +static void Webadmin_AppendText(xml_t *xmlobj, const char *text) { - - int colorindex, len, i, y; - char htmlcolor[128]; - qboolean incolor; - - incolor = qfalse; - - for(i = 0, y = 0; qcolorstr[i] && y < maxlen; ++i) + char plain[65], escaped[512]; + int length; + while (*text) { - if (qcolorstr[i] == '^' && qcolorstr[i+1] <= '9' && qcolorstr[i+1] >= '0') + if (*text == '\n' || *text == '\r' || *text == '\t') { - if(incolor) - { - Q_strncpyz(hcolorstr +y, "", maxlen -y); - y += 7; - } - colorindex = qcolorstr[i+1] - '0'; - len = Com_sprintf(htmlcolor, sizeof(htmlcolor), "", htmlq3colors[colorindex]); - Q_strncpyz(&hcolorstr[y], htmlcolor, maxlen -y); - incolor = qtrue; - y += len; - i += 1; - }else{ - hcolorstr[y] = qcolorstr[i]; - ++y; + plain[0] = *text++; plain[1] = '\0'; + XA(plain); + continue; } - - - } - if(incolor) - { - Q_strncpyz(hcolorstr +y, "", maxlen -y); - y += 7; + for (length = 0; length < sizeof(plain) - 1 && text[length] && + text[length] != '\n' && text[length] != '\r' && text[length] != '\t'; ++length) + plain[length] = text[length]; + plain[length] = '\0'; + XML_Escape(escaped, sizeof(escaped), plain); + XA(escaped); + text += length; } +} - if(y < maxlen) +char* Webadmin_ConvertToHTMLColor(char* qcolorstr, char* hcolorstr, int maxlen) +{ + int i = 0, used = 0, length, reserve; + qboolean incolor = qfalse; + const char *token; + char span[64], single[2]; + if (maxlen < 1) return hcolorstr; + hcolorstr[0] = '\0'; + while (qcolorstr[i]) { - hcolorstr[y] = '\0'; - }else { - hcolorstr[maxlen - 1] = '\0'; + if (qcolorstr[i] == '^' && qcolorstr[i+1] >= '0' && qcolorstr[i+1] <= '9') + { + Com_sprintf(span, sizeof(span), "%s", + incolor ? "" : "", htmlq3colors[qcolorstr[i+1] - '0']); + token = span; + length = strlen(token); + if (length + 7 >= maxlen - used) break; + incolor = qtrue; + i += 2; + } + else + { + switch (qcolorstr[i]) + { + case '<': token = "<"; break; + case '>': token = ">"; break; + case '&': token = "&"; break; + case '\"': token = """; break; + case '\'': token = "'"; break; + default: single[0] = qcolorstr[i]; single[1] = '\0'; token = single; break; + } + length = strlen(token); + reserve = incolor ? 7 : 0; + if (length + reserve >= maxlen - used) break; + ++i; + } + memcpy(hcolorstr + used, token, length); + used += length; } + if (incolor) { memcpy(hcolorstr + used, "", 7); used += 7; } + hcolorstr[used] = '\0'; return hcolorstr; } @@ -248,7 +269,7 @@ void Webadmin_BuildServerStatus(xml_t* xmlobj, qboolean showfullguid) Q_strncpyz(teamallies, g_TeamName_Allies->string, sizeof(teamallies)); XO("tr"); XO1("td", "colspan", "6"); - XA(teamaxis); + Webadmin_AppendText(xmlobj, teamaxis); XC; XC; for (cl = svs.clients, gclient = level.clients, i = 0; i < sv_maxclients->integer; i++, cl++, gclient++) { @@ -290,7 +311,7 @@ void Webadmin_BuildServerStatus(xml_t* xmlobj, qboolean showfullguid) } XO("tr"); XO1("td", "colspan", "6"); - XA(teamallies); + Webadmin_AppendText(xmlobj, teamallies); XC; XC; for (cl = svs.clients, gclient = level.clients, i = 0; i < sv_maxclients->integer; i++, cl++, gclient++) { @@ -524,7 +545,7 @@ void Webadmin_FlushRedirect(char *outputbuf, qboolean lastcommand ) } XA("
");
- XA(outputbuf);
+ Webadmin_AppendText(xmlobj, outputbuf);
XA("");
}
@@ -641,7 +662,7 @@ void Webadmin_BuildMessage(msg_t* msg, authData_admin_t* authenticated, qboolean
XO("h3");
XA(Webadmin_ConvertToHTMLColor(sv_hostname->string, colorbuf, sizeof(colorbuf)));
XA(" ");
- XA(sv_mapname->string);
+ Webadmin_AppendText(xmlobj, sv_mapname->string);
XC;
XC;
@@ -660,7 +681,7 @@ void Webadmin_BuildMessage(msg_t* msg, authData_admin_t* authenticated, qboolean
}else {
XO1("div","class","loginusername");
XO1("span","class","label label-primary");
- XA("Logged in as: ");XA(username);XA(". ");
+ XA("Logged in as: ");Webadmin_AppendText(xmlobj, username);XA(". ");
XO2("a","href","/webadmin/?action=logout","style","color: #fff");
XA("Log Out");
XC;
diff --git a/tests/test_rcon.py b/tests/test_rcon.py
index a9f06ea9..26dff01f 100644
--- a/tests/test_rcon.py
+++ b/tests/test_rcon.py
@@ -92,6 +92,12 @@ def test_source_identity_uses_verified_record_not_numeric_name(self):
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_udp_credential_commands_omit_arguments_from_logs(self):
+ for command in ('AdminChangePassword owner MODE_SECRET_CANARY',
+ 'ChangePassword old MODE_SECRET_CANARY',
+ 'set rcon_password MODE_SECRET_CANARY'):
+ self.assertEqual(self.udp(16, command=command), b'EXECUTED:' + command.encode())
+
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)
diff --git a/tests/test_web_security.py b/tests/test_web_security.py
new file mode 100644
index 00000000..968ae7fc
--- /dev/null
+++ b/tests/test_web_security.py
@@ -0,0 +1,181 @@
+"""Execute the production HTTP, HTML and session boundaries without networking."""
+from pathlib import Path
+import os
+import subprocess
+import tempfile
+import unittest
+from test_rcon import function
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def execute(source, sanitize=False):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / 'boundary.c'
+ binary = Path(directory) / 'boundary'
+ path.write_text(source)
+ flags = ['-fsanitize=address,undefined', '-fno-omit-frame-pointer', '-g'] if sanitize else []
+ subprocess.run(['gcc', '-std=gnu11', *flags, str(path), '-o', str(binary)], check=True)
+ env = {**os.environ, 'ASAN_OPTIONS': 'detect_leaks=0'}
+ subprocess.run([str(binary)], check=True, env=env)
+
+
+class WebSecurity(unittest.TestCase):
+ def test_http_segmented_framing_bounds_and_cookie_parsing(self):
+ source = r'''
+#include