Skip to content

Commit 2758ed3

Browse files
committed
[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".
1 parent a370613 commit 2758ed3

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

lib/websocket.js

+5
Original file line numberDiff line numberDiff line change
@@ -783,6 +783,11 @@ function initAsClient(websocket, address, protocols, options) {
783783

784784
req = websocket._req = null;
785785

786+
if (res.headers.upgrade.toLowerCase() !== 'websocket') {
787+
abortHandshake(websocket, socket, 'Invalid Upgrade header');
788+
return;
789+
}
790+
786791
const digest = createHash('sha1')
787792
.update(key + GUID)
788793
.digest('base64');

test/websocket.test.js

+20
Original file line numberDiff line numberDiff line change
@@ -525,6 +525,26 @@ describe('WebSocket', () => {
525525
beforeEach((done) => server.listen(0, done));
526526
afterEach((done) => server.close(done));
527527

528+
it('fails if the Upgrade header field value is not "websocket"', (done) => {
529+
server.once('upgrade', (req, socket) => {
530+
socket.on('end', socket.end);
531+
socket.write(
532+
'HTTP/1.1 101 Switching Protocols\r\n' +
533+
'Connection: Upgrade\r\n' +
534+
'Upgrade: foo\r\n' +
535+
'\r\n'
536+
);
537+
});
538+
539+
const ws = new WebSocket(`ws://localhost:${server.address().port}`);
540+
541+
ws.on('error', (err) => {
542+
assert.ok(err instanceof Error);
543+
assert.strictEqual(err.message, 'Invalid Upgrade header');
544+
done();
545+
});
546+
});
547+
528548
it('fails if the Sec-WebSocket-Accept header is invalid', (done) => {
529549
server.once('upgrade', (req, socket) => {
530550
socket.on('end', socket.end);

0 commit comments

Comments
 (0)