Skip to content

Commit 0fdcc0a

Browse files
committedMay 21, 2022
[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 e56cdfe commit 0fdcc0a

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
@@ -889,6 +889,11 @@ function initAsClient(websocket, address, protocols, options) {
889889

890890
req = websocket._req = null;
891891

892+
if (res.headers.upgrade.toLowerCase() !== 'websocket') {
893+
abortHandshake(websocket, socket, 'Invalid Upgrade header');
894+
return;
895+
}
896+
892897
const digest = createHash('sha1')
893898
.update(key + GUID)
894899
.digest('base64');

‎test/websocket.test.js

+20
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,26 @@ describe('WebSocket', () => {
685685
beforeEach((done) => server.listen(0, done));
686686
afterEach((done) => server.close(done));
687687

688+
it('fails if the Upgrade header field value is not "websocket"', (done) => {
689+
server.once('upgrade', (req, socket) => {
690+
socket.on('end', socket.end);
691+
socket.write(
692+
'HTTP/1.1 101 Switching Protocols\r\n' +
693+
'Connection: Upgrade\r\n' +
694+
'Upgrade: foo\r\n' +
695+
'\r\n'
696+
);
697+
});
698+
699+
const ws = new WebSocket(`ws://localhost:${server.address().port}`);
700+
701+
ws.on('error', (err) => {
702+
assert.ok(err instanceof Error);
703+
assert.strictEqual(err.message, 'Invalid Upgrade header');
704+
done();
705+
});
706+
});
707+
688708
it('fails if the Sec-WebSocket-Accept header is invalid', (done) => {
689709
server.once('upgrade', (req, socket) => {
690710
socket.on('end', socket.end);

0 commit comments

Comments
 (0)
Please sign in to comment.