Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Properly verify Sec-WebSocket-Key header. #962

Merged
merged 1 commit into from
Oct 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions lib/cdp/websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package cdp
import (
"bufio"
"context"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
Expand Down Expand Up @@ -183,17 +185,30 @@ func (e *ErrBadHandshake) Error() string {
)
}

func verifyWebSocketAccept(responseHeaders http.Header, websocketKey string) bool {
expectedKey := websocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
hash := sha1.New()
hash.Write([]byte(expectedKey))
expectedAccept := base64.StdEncoding.EncodeToString(hash.Sum(nil))

return responseHeaders.Get("Sec-WebSocket-Accept") == expectedAccept
}

func (ws *WebSocket) handshake(ctx context.Context, u *url.URL, header http.Header) error {
defaultSecKey := "nil"
req := (&http.Request{Method: http.MethodGet, URL: u, Header: http.Header{
"Upgrade": {"websocket"},
"Connection": {"Upgrade"},
"Sec-WebSocket-Key": {"nil"},
"Sec-WebSocket-Key": {defaultSecKey},
"Sec-WebSocket-Version": {"13"},
}}).WithContext(ctx)

secKey := defaultSecKey
for k, vs := range header {
if k == "Host" && len(vs) > 0 {
req.Host = vs[0]
} else if k == "Sec-WebSocket-Key" && len(vs) > 0 {
secKey = vs[0]
} else {
req.Header[k] = vs
}
Expand All @@ -210,8 +225,7 @@ func (ws *WebSocket) handshake(ctx context.Context, u *url.URL, header http.Head
}
defer func() { _ = res.Body.Close() }()

if res.StatusCode != http.StatusSwitchingProtocols ||
res.Header.Get("Sec-Websocket-Accept") != "Q67D9eATKx531lK8F7u2rqQNnNI=" {
if res.StatusCode != http.StatusSwitchingProtocols || !verifyWebSocketAccept(res.Header, secKey) {
body, _ := ioutil.ReadAll(res.Body)
return &ErrBadHandshake{
Status: res.Status,
Expand Down
5 changes: 3 additions & 2 deletions lib/cdp/websocket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,9 @@ func TestWebSocketHeader(t *testing.T) {

ws := cdp.WebSocket{}
err := ws.Connect(g.Context(), s.URL("/a?q=ok"), http.Header{
"Host": {"test.com"},
"Test": {"header"},
"Host": {"test.com"},
"Test": {"header"},
"Sec-WebSocket-Key": {"key"},
})
<-wait

Expand Down
Loading