From bd95f77131f5f299edae4e08b1f8a623e1363260 Mon Sep 17 00:00:00 2001 From: "Torsten Schulz (local)" Date: Sun, 16 Nov 2025 00:02:55 +0100 Subject: [PATCH] Refactor WebSocket upgrade key generation for improved security This commit updates the `testWebSocket.js` and `testWebSocketApache.js` scripts to enhance the generation of the Sec-WebSocket-Key. The key is now generated using a secure method that allocates 16 bytes of random data, ensuring compliance with WebSocket protocol requirements. This change improves the robustness of WebSocket upgrade requests in both scripts. --- backend/scripts/testWebSocket.js | 9 +++++++-- backend/scripts/testWebSocketApache.js | 9 +++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/backend/scripts/testWebSocket.js b/backend/scripts/testWebSocket.js index 13d2caf..4879674 100644 --- a/backend/scripts/testWebSocket.js +++ b/backend/scripts/testWebSocket.js @@ -75,7 +75,12 @@ pollingReq.setTimeout(5000, () => { function testWebSocketUpgrade(host, port, sessionId) { // WebSocket-Upgrade-Request - const wsKey = Buffer.from(Math.random().toString()).toString('base64').substring(0, 16); + // Sec-WebSocket-Key muss 16 Bytes (128 Bits) sein, base64-encoded + const wsKey = Buffer.allocUnsafe(16); + for (let i = 0; i < 16; i++) { + wsKey[i] = Math.floor(Math.random() * 256); + } + const wsKeyBase64 = wsKey.toString('base64'); const path = sessionId ? `/socket.io/?EIO=4&transport=websocket&sid=${sessionId}` : '/socket.io/?EIO=4&transport=websocket'; @@ -88,7 +93,7 @@ function testWebSocketUpgrade(host, port, sessionId) { headers: { 'Upgrade': 'websocket', 'Connection': 'Upgrade', - 'Sec-WebSocket-Key': wsKey, + 'Sec-WebSocket-Key': wsKeyBase64, 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Protocol': 'chat, superchat' } diff --git a/backend/scripts/testWebSocketApache.js b/backend/scripts/testWebSocketApache.js index dd27814..f409161 100755 --- a/backend/scripts/testWebSocketApache.js +++ b/backend/scripts/testWebSocketApache.js @@ -77,7 +77,12 @@ pollingReq.setTimeout(10000, () => { function testWebSocketUpgrade(baseUrl, sessionId, useHttps) { // WebSocket-Upgrade-Request - const wsKey = Buffer.from(Math.random().toString()).toString('base64').substring(0, 16); + // Sec-WebSocket-Key muss 16 Bytes (128 Bits) sein, base64-encoded + const wsKey = Buffer.allocUnsafe(16); + for (let i = 0; i < 16; i++) { + wsKey[i] = Math.floor(Math.random() * 256); + } + const wsKeyBase64 = wsKey.toString('base64'); const path = sessionId ? `/socket.io/?EIO=4&transport=websocket&sid=${sessionId}` : `/socket.io/?EIO=4&transport=websocket`; @@ -91,7 +96,7 @@ function testWebSocketUpgrade(baseUrl, sessionId, useHttps) { headers: { 'Upgrade': 'websocket', 'Connection': 'Upgrade', - 'Sec-WebSocket-Key': wsKey, + 'Sec-WebSocket-Key': wsKeyBase64, 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Protocol': 'chat, superchat', 'Origin': baseUrl