Skip to content

Commit 3ae5d9c

Browse files
committed
add Sec-WebSocket-Key header verification
1 parent bcef843 commit 3ae5d9c

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

server.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,8 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade
154154
}
155155

156156
challengeKey := r.Header.Get("Sec-Websocket-Key")
157-
if challengeKey == "" {
158-
return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'Sec-WebSocket-Key' header is missing or blank")
157+
if !isValidChallengeKey(challengeKey) {
158+
return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'Sec-WebSocket-Key' header must be Base64 encoded value of 16-byte in length")
159159
}
160160

161161
subprotocol := u.selectSubprotocol(r, responseHeader)

util.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,3 +281,18 @@ headers:
281281
}
282282
return result
283283
}
284+
285+
// isValidChallengeKey checks if the argument meets RFC6455 specification.
286+
func isValidChallengeKey(s string) bool {
287+
// From RFC6455:
288+
//
289+
// A |Sec-WebSocket-Key| header field with a base64-encoded (see
290+
// Section 4 of [RFC4648]) value that, when decoded, is 16 bytes in
291+
// length.
292+
293+
if s == "" {
294+
return false
295+
}
296+
decoded, err := base64.StdEncoding.DecodeString(s)
297+
return err == nil && len(decoded) == 16
298+
}

0 commit comments

Comments
 (0)