From 91f589db023d66e4aba7112d44cc0d2fb091c553 Mon Sep 17 00:00:00 2001 From: Gary Burd Date: Thu, 25 Jan 2018 10:51:21 -0800 Subject: [PATCH] Improve check origin documentation Remove the example code to disable origin checks from the documentation. I am concerned that developers are copying the code without understanding the security implications of the code. Most applications should not use this code. Change the bad origin error message to mention Upgrader.CheckOrigin Mention cross-site request forgery in the Upgrader.CheckOrigin doc. --- doc.go | 11 ++--------- server.go | 10 +++++++--- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/doc.go b/doc.go index 7cc885e..dcce1a6 100644 --- a/doc.go +++ b/doc.go @@ -144,15 +144,8 @@ // method fails the WebSocket handshake with HTTP status 403. // // If the CheckOrigin field is nil, then the Upgrader uses a safe default: fail -// the handshake if the Origin request header is present and not equal to the -// Host request header. -// -// An application can allow connections from any origin by specifying a -// function that always returns true: -// -// var upgrader = websocket.Upgrader{ -// CheckOrigin: func(r *http.Request) bool { return true }, -// } +// the handshake if the Origin request header is present and the Origin host is +// not equal to the Host request header. // // The deprecated package-level Upgrade function does not perform origin // checking. The application is responsible for checking the Origin header diff --git a/server.go b/server.go index 9a9dfeb..50b58a8 100644 --- a/server.go +++ b/server.go @@ -44,8 +44,12 @@ type Upgrader struct { Error func(w http.ResponseWriter, r *http.Request, status int, reason error) // CheckOrigin returns true if the request Origin header is acceptable. If - // CheckOrigin is nil, the host in the Origin header must not be set or - // must match the host of the request. + // CheckOrigin is nil, then a safe default is used: return false if the + // Origin request header is present and the origin host is not equal to + // request Host header. + // + // A CheckOrigin function should carefully validate the request origin to + // prevent cross-site request forgery. CheckOrigin func(r *http.Request) bool // EnableCompression specify if the server should attempt to negotiate per @@ -131,7 +135,7 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade checkOrigin = checkSameOrigin } if !checkOrigin(r) { - return u.returnError(w, r, http.StatusForbidden, "websocket: 'Origin' header value not allowed") + return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin") } challengeKey := r.Header.Get("Sec-Websocket-Key")