Skip to content

Commit

Permalink
[fix] Abort the handshake if the Upgrade header is invalid
Browse files Browse the repository at this point in the history
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".
  • Loading branch information
lpinca committed May 21, 2022
1 parent e56cdfe commit 0fdcc0a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/websocket.js
Expand Up @@ -889,6 +889,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');
Expand Down
20 changes: 20 additions & 0 deletions test/websocket.test.js
Expand Up @@ -685,6 +685,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);
Expand Down

0 comments on commit 0fdcc0a

Please sign in to comment.