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 26, 2022
1 parent a370613 commit 2758ed3
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
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
20 changes: 20 additions & 0 deletions test/websocket.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 2758ed3

Please sign in to comment.