| 1 |
package csrf |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"errors" |
| 6 |
"fmt" |
| 7 |
"net/http" |
| 8 |
"net/url" |
| 9 |
"slices" |
| 10 |
|
| 11 |
"github.com/gorilla/securecookie" |
| 12 |
) |
| 13 |
|
| 14 |
// CSRF token length in bytes. |
| 15 |
const tokenLength = 32 |
| 16 |
|
| 17 |
// Context/session keys & prefixes |
| 18 |
const ( |
| 19 |
tokenKey string = "gorilla.csrf.Token" // #nosec G101 |
| 20 |
formKey string = "gorilla.csrf.Form" // #nosec G101 |
| 21 |
errorKey string = "gorilla.csrf.Error" |
| 22 |
skipCheckKey string = "gorilla.csrf.Skip" |
| 23 |
cookieName string = "_gorilla_csrf" |
| 24 |
errorPrefix string = "gorilla/csrf: " |
| 25 |
) |
| 26 |
|
| 27 |
type contextKey string |
| 28 |
|
| 29 |
// PlaintextHTTPContextKey is the context key used to store whether the request |
| 30 |
// is being served via plaintext HTTP. This is used to signal to the middleware |
| 31 |
// that strict Referer checking should not be enforced as is done for HTTPS by |
| 32 |
// default. |
| 33 |
const PlaintextHTTPContextKey contextKey = "plaintext" |
| 34 |
|
| 35 |
var ( |
| 36 |
// The name value used in form fields. |
| 37 |
fieldName = tokenKey |
| 38 |
// defaultAge sets the default MaxAge for cookies. |
| 39 |
defaultAge = 3600 * 12 |
| 40 |
// The default HTTP request header to inspect |
| 41 |
headerName = "X-CSRF-Token" |
| 42 |
// Idempotent (safe) methods as defined by RFC7231 section 4.2.2. |
| 43 |
safeMethods = []string{"GET", "HEAD", "OPTIONS", "TRACE"} |
| 44 |
) |
| 45 |
|
| 46 |
// TemplateTag provides a default template tag - e.g. {{ .csrfField }} - for use |
| 47 |
// with the TemplateField function. |
| 48 |
var TemplateTag = "csrfField" |
| 49 |
|
| 50 |
var ( |
| 51 |
// ErrNoReferer is returned when a HTTPS request provides an empty Referer |
| 52 |
// header. |
| 53 |
ErrNoReferer = errors.New("referer not supplied") |
| 54 |
// ErrBadOrigin is returned when the Origin header is present and is not a |
| 55 |
// trusted origin. |
| 56 |
ErrBadOrigin = errors.New("origin invalid") |
| 57 |
// ErrBadReferer is returned when the scheme & host in the URL do not match |
| 58 |
// the supplied Referer header. |
| 59 |
ErrBadReferer = errors.New("referer invalid") |
| 60 |
// ErrNoToken is returned if no CSRF token is supplied in the request. |
| 61 |
ErrNoToken = errors.New("CSRF token not found in request") |
| 62 |
// ErrBadToken is returned if the CSRF token in the request does not match |
| 63 |
// the token in the session, or is otherwise malformed. |
| 64 |
ErrBadToken = errors.New("CSRF token invalid") |
| 65 |
) |
| 66 |
|
| 67 |
// SameSiteMode allows a server to define a cookie attribute making it impossible for |
| 68 |
// the browser to send this cookie along with cross-site requests. The main |
| 69 |
// goal is to mitigate the risk of cross-origin information leakage, and provide |
| 70 |
// some protection against cross-site request forgery attacks. |
| 71 |
// |
| 72 |
// See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details. |
| 73 |
type SameSiteMode int |
| 74 |
|
| 75 |
// SameSite options |
| 76 |
const ( |
| 77 |
// SameSiteDefaultMode sets the `SameSite` cookie attribute, which is |
| 78 |
// invalid in some older browsers due to changes in the SameSite spec. These |
| 79 |
// browsers will not send the cookie to the server. |
| 80 |
// csrf uses SameSiteLaxMode (SameSite=Lax) as the default as of v1.7.0+ |
| 81 |
SameSiteDefaultMode SameSiteMode = iota + 1 |
| 82 |
SameSiteLaxMode |
| 83 |
SameSiteStrictMode |
| 84 |
SameSiteNoneMode |
| 85 |
) |
| 86 |
|
| 87 |
type csrf struct { |
| 88 |
h http.Handler |
| 89 |
sc *securecookie.SecureCookie |
| 90 |
st store |
| 91 |
opts options |
| 92 |
} |
| 93 |
|
| 94 |
// options contains the optional settings for the CSRF middleware. |
| 95 |
type options struct { |
| 96 |
MaxAge int |
| 97 |
Domain string |
| 98 |
Path string |
| 99 |
// Note that the function and field names match the case of the associated |
| 100 |
// http.Cookie field instead of the "correct" HTTPOnly name that golint suggests. |
| 101 |
HttpOnly bool |
| 102 |
Secure bool |
| 103 |
SameSite SameSiteMode |
| 104 |
RequestHeader string |
| 105 |
FieldName string |
| 106 |
ErrorHandler http.Handler |
| 107 |
CookieName string |
| 108 |
TrustedOrigins []string |
| 109 |
} |
| 110 |
|
| 111 |
// Protect is HTTP middleware that provides Cross-Site Request Forgery |
| 112 |
// protection. |
| 113 |
// |
| 114 |
// It securely generates a masked (unique-per-request) token that |
| 115 |
// can be embedded in the HTTP response (e.g. form field or HTTP header). |
| 116 |
// The original (unmasked) token is stored in the session, which is inaccessible |
| 117 |
// by an attacker (provided you are using HTTPS). Subsequent requests are |
| 118 |
// expected to include this token, which is compared against the session token. |
| 119 |
// Requests that do not provide a matching token are served with a HTTP 403 |
| 120 |
// 'Forbidden' error response. |
| 121 |
// |
| 122 |
// Example: |
| 123 |
// |
| 124 |
// package main |
| 125 |
// |
| 126 |
// import ( |
| 127 |
// "html/template" |
| 128 |
// |
| 129 |
// "github.com/gorilla/csrf" |
| 130 |
// "github.com/gorilla/mux" |
| 131 |
// ) |
| 132 |
// |
| 133 |
// var t = template.Must(template.New("signup_form.tmpl").Parse(form)) |
| 134 |
// |
| 135 |
// func main() { |
| 136 |
// r := mux.NewRouter() |
| 137 |
// |
| 138 |
// r.HandleFunc("/signup", GetSignupForm) |
| 139 |
// // POST requests without a valid token will return a HTTP 403 Forbidden. |
| 140 |
// r.HandleFunc("/signup/post", PostSignupForm) |
| 141 |
// |
| 142 |
// // Add the middleware to your router. |
| 143 |
// http.ListenAndServe(":8000", |
| 144 |
// // Note that the authentication key provided should be 32 bytes |
| 145 |
// // long and persist across application restarts. |
| 146 |
// csrf.Protect([]byte("32-byte-long-auth-key"))(r)) |
| 147 |
// } |
| 148 |
// |
| 149 |
// func GetSignupForm(w http.ResponseWriter, r *http.Request) { |
| 150 |
// // signup_form.tmpl just needs a {{ .csrfField }} template tag for |
| 151 |
// // csrf.TemplateField to inject the CSRF token into. Easy! |
| 152 |
// t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{ |
| 153 |
// csrf.TemplateTag: csrf.TemplateField(r), |
| 154 |
// }) |
| 155 |
// // We could also retrieve the token directly from csrf.Token(r) and |
| 156 |
// // set it in the request header - w.Header.Set("X-CSRF-Token", token) |
| 157 |
// // This is useful if you're sending JSON to clients or a front-end JavaScript |
| 158 |
// // framework. |
| 159 |
// } |
| 160 |
func Protect(authKey []byte, opts ...Option) func(http.Handler) http.Handler { |
| 161 |
return func(h http.Handler) http.Handler { |
| 162 |
cs := parseOptions(h, opts...) |
| 163 |
|
| 164 |
// Set the defaults if no options have been specified |
| 165 |
if cs.opts.ErrorHandler == nil { |
| 166 |
cs.opts.ErrorHandler = http.HandlerFunc(unauthorizedHandler) |
| 167 |
} |
| 168 |
|
| 169 |
if cs.opts.MaxAge < 0 { |
| 170 |
// Default of 12 hours |
| 171 |
cs.opts.MaxAge = defaultAge |
| 172 |
} |
| 173 |
|
| 174 |
if cs.opts.FieldName == "" { |
| 175 |
cs.opts.FieldName = fieldName |
| 176 |
} |
| 177 |
|
| 178 |
if cs.opts.CookieName == "" { |
| 179 |
cs.opts.CookieName = cookieName |
| 180 |
} |
| 181 |
|
| 182 |
if cs.opts.RequestHeader == "" { |
| 183 |
cs.opts.RequestHeader = headerName |
| 184 |
} |
| 185 |
|
| 186 |
// Create an authenticated securecookie instance. |
| 187 |
if cs.sc == nil { |
| 188 |
cs.sc = securecookie.New(authKey, nil) |
| 189 |
// Use JSON serialization (faster than one-off gob encoding) |
| 190 |
cs.sc.SetSerializer(securecookie.JSONEncoder{}) |
| 191 |
// Set the MaxAge of the underlying securecookie. |
| 192 |
cs.sc.MaxAge(cs.opts.MaxAge) |
| 193 |
} |
| 194 |
|
| 195 |
if cs.st == nil { |
| 196 |
// Default to the cookieStore |
| 197 |
cs.st = &cookieStore{ |
| 198 |
name: cs.opts.CookieName, |
| 199 |
maxAge: cs.opts.MaxAge, |
| 200 |
secure: cs.opts.Secure, |
| 201 |
httpOnly: cs.opts.HttpOnly, |
| 202 |
sameSite: cs.opts.SameSite, |
| 203 |
path: cs.opts.Path, |
| 204 |
domain: cs.opts.Domain, |
| 205 |
sc: cs.sc, |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
return cs |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
// Implements http.Handler for the csrf type. |
| 214 |
func (cs *csrf) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 215 |
// Skip the check if directed to. This should always be a bool. |
| 216 |
if val, err := contextGet(r, skipCheckKey); err == nil { |
| 217 |
if skip, ok := val.(bool); ok { |
| 218 |
if skip { |
| 219 |
cs.h.ServeHTTP(w, r) |
| 220 |
return |
| 221 |
} |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
// Retrieve the token from the session. |
| 226 |
// An error represents either a cookie that failed HMAC validation |
| 227 |
// or that doesn't exist. |
| 228 |
realToken, err := cs.st.Get(r) |
| 229 |
if err != nil || len(realToken) != tokenLength { |
| 230 |
// If there was an error retrieving the token, the token doesn't exist |
| 231 |
// yet, or it's the wrong length, generate a new token. |
| 232 |
// Note that the new token will (correctly) fail validation downstream |
| 233 |
// as it will no longer match the request token. |
| 234 |
realToken, err = generateRandomBytes(tokenLength) |
| 235 |
if err != nil { |
| 236 |
r = envError(r, err) |
| 237 |
cs.opts.ErrorHandler.ServeHTTP(w, r) |
| 238 |
return |
| 239 |
} |
| 240 |
|
| 241 |
// Save the new (real) token in the session store. |
| 242 |
err = cs.st.Save(realToken, w) |
| 243 |
if err != nil { |
| 244 |
r = envError(r, err) |
| 245 |
cs.opts.ErrorHandler.ServeHTTP(w, r) |
| 246 |
return |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
// Save the masked token to the request context |
| 251 |
r = contextSave(r, tokenKey, mask(realToken, r)) |
| 252 |
// Save the field name to the request context |
| 253 |
r = contextSave(r, formKey, cs.opts.FieldName) |
| 254 |
|
| 255 |
// HTTP methods not defined as idempotent ("safe") under RFC7231 require |
| 256 |
// inspection. |
| 257 |
if !contains(safeMethods, r.Method) { |
| 258 |
var isPlaintext bool |
| 259 |
val := r.Context().Value(PlaintextHTTPContextKey) |
| 260 |
if val != nil { |
| 261 |
isPlaintext, _ = val.(bool) |
| 262 |
} |
| 263 |
|
| 264 |
// take a copy of the request URL to avoid mutating the original |
| 265 |
// attached to the request. |
| 266 |
// set the scheme & host based on the request context as these are not |
| 267 |
// populated by default for server requests |
| 268 |
// ref: https://pkg.go.dev/net/http#Request |
| 269 |
requestURL := *r.URL // shallow clone |
| 270 |
|
| 271 |
requestURL.Scheme = "https" |
| 272 |
if isPlaintext { |
| 273 |
requestURL.Scheme = "http" |
| 274 |
} |
| 275 |
if requestURL.Host == "" { |
| 276 |
requestURL.Host = r.Host |
| 277 |
} |
| 278 |
|
| 279 |
// if we have an Origin header, check it against our allowlist |
| 280 |
origin := r.Header.Get("Origin") |
| 281 |
if origin != "" { |
| 282 |
parsedOrigin, err := url.Parse(origin) |
| 283 |
if err != nil { |
| 284 |
r = envError(r, ErrBadOrigin) |
| 285 |
cs.opts.ErrorHandler.ServeHTTP(w, r) |
| 286 |
return |
| 287 |
} |
| 288 |
if !sameOrigin(&requestURL, parsedOrigin) && !slices.Contains(cs.opts.TrustedOrigins, parsedOrigin.Host) { |
| 289 |
r = envError(r, ErrBadOrigin) |
| 290 |
cs.opts.ErrorHandler.ServeHTTP(w, r) |
| 291 |
return |
| 292 |
} |
| 293 |
} |
| 294 |
|
| 295 |
// If we are serving via TLS and have no Origin header, prevent against |
| 296 |
// CSRF via HTTP machine in the middle attacks by enforcing strict |
| 297 |
// Referer origin checks. Consider an attacker who performs a |
| 298 |
// successful HTTP Machine-in-the-Middle attack and uses this to inject |
| 299 |
// a form and cause submission to our origin. We strictly disallow |
| 300 |
// cleartext HTTP origins and evaluate the domain against an allowlist. |
| 301 |
if origin == "" && !isPlaintext { |
| 302 |
// Fetch the Referer value. Call the error handler if it's empty or |
| 303 |
// otherwise fails to parse. |
| 304 |
referer, err := url.Parse(r.Referer()) |
| 305 |
if err != nil || referer.String() == "" { |
| 306 |
r = envError(r, ErrNoReferer) |
| 307 |
cs.opts.ErrorHandler.ServeHTTP(w, r) |
| 308 |
return |
| 309 |
} |
| 310 |
|
| 311 |
// disallow cleartext HTTP referers when serving via TLS |
| 312 |
if referer.Scheme == "http" { |
| 313 |
r = envError(r, ErrBadReferer) |
| 314 |
cs.opts.ErrorHandler.ServeHTTP(w, r) |
| 315 |
return |
| 316 |
} |
| 317 |
|
| 318 |
// If the request is being served via TLS and the Referer is not the |
| 319 |
// same origin, check the domain against our allowlist. We only |
| 320 |
// check when we have host information from the referer. |
| 321 |
if referer.Host != "" && referer.Host != r.Host && !slices.Contains(cs.opts.TrustedOrigins, referer.Host) { |
| 322 |
r = envError(r, ErrBadReferer) |
| 323 |
cs.opts.ErrorHandler.ServeHTTP(w, r) |
| 324 |
return |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
// Retrieve the combined token (pad + masked) token... |
| 329 |
maskedToken, err := cs.requestToken(r) |
| 330 |
if err != nil { |
| 331 |
r = envError(r, ErrBadToken) |
| 332 |
cs.opts.ErrorHandler.ServeHTTP(w, r) |
| 333 |
return |
| 334 |
} |
| 335 |
|
| 336 |
if maskedToken == nil { |
| 337 |
r = envError(r, ErrNoToken) |
| 338 |
cs.opts.ErrorHandler.ServeHTTP(w, r) |
| 339 |
return |
| 340 |
} |
| 341 |
|
| 342 |
// ... and unmask it. |
| 343 |
requestToken := unmask(maskedToken) |
| 344 |
|
| 345 |
// Compare the request token against the real token |
| 346 |
if !compareTokens(requestToken, realToken) { |
| 347 |
r = envError(r, ErrBadToken) |
| 348 |
cs.opts.ErrorHandler.ServeHTTP(w, r) |
| 349 |
return |
| 350 |
} |
| 351 |
|
| 352 |
} |
| 353 |
|
| 354 |
// Set the Vary: Cookie header to protect clients from caching the response. |
| 355 |
w.Header().Add("Vary", "Cookie") |
| 356 |
|
| 357 |
// Call the wrapped handler/router on success. |
| 358 |
cs.h.ServeHTTP(w, r) |
| 359 |
// Clear the request context after the handler has completed. |
| 360 |
contextClear(r) |
| 361 |
} |
| 362 |
|
| 363 |
// PlaintextHTTPRequest accepts as input a http.Request and returns a new |
| 364 |
// http.Request with the PlaintextHTTPContextKey set to true. This is used to |
| 365 |
// signal to the CSRF middleware that the request is being served over plaintext |
| 366 |
// HTTP and that Referer-based origin allow-listing checks should be skipped. |
| 367 |
func PlaintextHTTPRequest(r *http.Request) *http.Request { |
| 368 |
ctx := context.WithValue(r.Context(), PlaintextHTTPContextKey, true) |
| 369 |
return r.WithContext(ctx) |
| 370 |
} |
| 371 |
|
| 372 |
// unauthorizedhandler sets a HTTP 403 Forbidden status and writes the |
| 373 |
// CSRF failure reason to the response. |
| 374 |
func unauthorizedHandler(w http.ResponseWriter, r *http.Request) { |
| 375 |
http.Error(w, fmt.Sprintf("%s - %s", |
| 376 |
http.StatusText(http.StatusForbidden), FailureReason(r)), |
| 377 |
http.StatusForbidden) |
| 378 |
} |