From 2758ed355073105a60b8b836b25265b8cdcb3b42 Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Sat, 21 May 2022 07:02:12 +0200 Subject: [PATCH] [fix] Abort the handshake if the Upgrade header is invalid Close the connection if the Upgrade header field in the HTTP response contains a value that is not an ASCII case-insensitive match for the value "websocket". --- lib/websocket.js | 5 +++++ test/websocket.test.js | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/lib/websocket.js b/lib/websocket.js index c39b34cdf..1802274b0 100644 --- a/lib/websocket.js +++ b/lib/websocket.js @@ -783,6 +783,11 @@ function initAsClient(websocket, address, protocols, options) { req = websocket._req = null; + if (res.headers.upgrade.toLowerCase() !== 'websocket') { + abortHandshake(websocket, socket, 'Invalid Upgrade header'); + return; + } + const digest = createHash('sha1') .update(key + GUID) .digest('base64'); diff --git a/test/websocket.test.js b/test/websocket.test.js index 717ecbdf3..36d3ba0a6 100644 --- a/test/websocket.test.js +++ b/test/websocket.test.js @@ -525,6 +525,26 @@ describe('WebSocket', () => { beforeEach((done) => server.listen(0, done)); afterEach((done) => server.close(done)); + it('fails if the Upgrade header field value is not "websocket"', (done) => { + server.once('upgrade', (req, socket) => { + socket.on('end', socket.end); + socket.write( + 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Connection: Upgrade\r\n' + + 'Upgrade: foo\r\n' + + '\r\n' + ); + }); + + const ws = new WebSocket(`ws://localhost:${server.address().port}`); + + ws.on('error', (err) => { + assert.ok(err instanceof Error); + assert.strictEqual(err.message, 'Invalid Upgrade header'); + done(); + }); + }); + it('fails if the Sec-WebSocket-Accept header is invalid', (done) => { server.once('upgrade', (req, socket) => { socket.on('end', socket.end);