Source file src/net/http/csrf.go
1 // Copyright 2025 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package http 6 7 import ( 8 "errors" 9 "fmt" 10 "net/url" 11 "sync" 12 "sync/atomic" 13 ) 14 15 // CrossOriginProtection implements protections against [Cross-Site Request 16 // Forgery (CSRF)] by rejecting non-safe cross-origin browser requests. 17 // 18 // Cross-origin requests are currently detected with the [Sec-Fetch-Site] 19 // header, available in all browsers since 2023, or by comparing the hostname of 20 // the [Origin] header with the Host header. 21 // 22 // The GET, HEAD, and OPTIONS methods are [safe methods] and are always allowed. 23 // It's important that applications do not perform any state changing actions 24 // due to requests with safe methods. 25 // 26 // Requests without Sec-Fetch-Site or Origin headers are currently assumed to be 27 // either same-origin or non-browser requests, and are allowed. 28 // 29 // The zero value of CrossOriginProtection is valid and has no trusted origins 30 // or bypass patterns. 31 // 32 // [Sec-Fetch-Site]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Site 33 // [Origin]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin 34 // [Cross-Site Request Forgery (CSRF)]: https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF 35 // [safe methods]: https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP 36 type CrossOriginProtection struct { 37 bypass atomic.Pointer[ServeMux] 38 trustedMu sync.RWMutex 39 trusted map[string]bool 40 deny atomic.Pointer[Handler] 41 } 42 43 // NewCrossOriginProtection returns a new [CrossOriginProtection] value. 44 func NewCrossOriginProtection() *CrossOriginProtection { 45 return &CrossOriginProtection{} 46 } 47 48 // AddTrustedOrigin allows all requests with an [Origin] header 49 // which exactly matches the given value. 50 // 51 // Origin header values are of the form "scheme://host[:port]". 52 // 53 // AddTrustedOrigin can be called concurrently with other methods 54 // or request handling, and applies to future requests. 55 // 56 // [Origin]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin 57 func (c *CrossOriginProtection) AddTrustedOrigin(origin string) error { 58 u, err := url.Parse(origin) 59 if err != nil { 60 return fmt.Errorf("invalid origin %q: %w", origin, err) 61 } 62 if u.Scheme == "" { 63 return fmt.Errorf("invalid origin %q: scheme is required", origin) 64 } 65 if u.Host == "" { 66 return fmt.Errorf("invalid origin %q: host is required", origin) 67 } 68 if u.Path != "" || u.RawQuery != "" || u.Fragment != "" { 69 return fmt.Errorf("invalid origin %q: path, query, and fragment are not allowed", origin) 70 } 71 c.trustedMu.Lock() 72 defer c.trustedMu.Unlock() 73 if c.trusted == nil { 74 c.trusted = make(map[string]bool) 75 } 76 c.trusted[origin] = true 77 return nil 78 } 79 80 var noopHandler = HandlerFunc(func(w ResponseWriter, r *Request) {}) 81 82 // AddInsecureBypassPattern permits all requests that match the given pattern. 83 // The pattern syntax and precedence rules are the same as [ServeMux]. 84 // 85 // AddInsecureBypassPattern can be called concurrently with other methods 86 // or request handling, and applies to future requests. 87 func (c *CrossOriginProtection) AddInsecureBypassPattern(pattern string) { 88 var bypass *ServeMux 89 90 // Lazily initialize c.bypass 91 for { 92 bypass = c.bypass.Load() 93 if bypass != nil { 94 break 95 } 96 bypass = NewServeMux() 97 if c.bypass.CompareAndSwap(nil, bypass) { 98 break 99 } 100 } 101 102 bypass.Handle(pattern, noopHandler) 103 } 104 105 // SetDenyHandler sets a handler to invoke when a request is rejected. 106 // The default error handler responds with a 403 Forbidden status. 107 // 108 // SetDenyHandler can be called concurrently with other methods 109 // or request handling, and applies to future requests. 110 // 111 // Check does not call the error handler. 112 func (c *CrossOriginProtection) SetDenyHandler(h Handler) { 113 if h == nil { 114 c.deny.Store(nil) 115 return 116 } 117 c.deny.Store(&h) 118 } 119 120 // Check applies cross-origin checks to a request. 121 // It returns an error if the request should be rejected. 122 func (c *CrossOriginProtection) Check(req *Request) error { 123 switch req.Method { 124 case "GET", "HEAD", "OPTIONS": 125 // Safe methods are always allowed. 126 return nil 127 } 128 129 switch req.Header.Get("Sec-Fetch-Site") { 130 case "": 131 // No Sec-Fetch-Site header is present. 132 // Fallthrough to check the Origin header. 133 case "same-origin", "none": 134 return nil 135 default: 136 if c.isRequestExempt(req) { 137 return nil 138 } 139 return errCrossOriginRequest 140 } 141 142 origin := req.Header.Get("Origin") 143 if origin == "" { 144 // Neither Sec-Fetch-Site nor Origin headers are present. 145 // Either the request is same-origin or not a browser request. 146 return nil 147 } 148 149 if o, err := url.Parse(origin); err == nil && o.Host == req.Host { 150 // The Origin header matches the Host header. Note that the Host header 151 // doesn't include the scheme, so we don't know if this might be an 152 // HTTP→HTTPS cross-origin request. We fail open, since all modern 153 // browsers support Sec-Fetch-Site since 2023, and running an older 154 // browser makes a clear security trade-off already. Sites can mitigate 155 // this with HTTP Strict Transport Security (HSTS). 156 return nil 157 } 158 159 if c.isRequestExempt(req) { 160 return nil 161 } 162 return errCrossOriginRequestFromOldBrowser 163 } 164 165 var ( 166 errCrossOriginRequest = errors.New("cross-origin request detected from Sec-Fetch-Site header") 167 errCrossOriginRequestFromOldBrowser = errors.New("cross-origin request detected, and/or browser is out of date: " + 168 "Sec-Fetch-Site is missing, and Origin does not match Host") 169 ) 170 171 // isRequestExempt checks the bypasses which require taking a lock, and should 172 // be deferred until the last moment. 173 func (c *CrossOriginProtection) isRequestExempt(req *Request) bool { 174 if bypass := c.bypass.Load(); bypass != nil { 175 if _, pattern := bypass.Handler(req); pattern != "" { 176 // The request matches a bypass pattern. 177 return true 178 } 179 } 180 181 c.trustedMu.RLock() 182 defer c.trustedMu.RUnlock() 183 origin := req.Header.Get("Origin") 184 // The request matches a trusted origin. 185 return origin != "" && c.trusted[origin] 186 } 187 188 // Handler returns a handler that applies cross-origin checks 189 // before invoking the handler h. 190 // 191 // If a request fails cross-origin checks, the request is rejected 192 // with a 403 Forbidden status or handled with the handler passed 193 // to [CrossOriginProtection.SetDenyHandler]. 194 func (c *CrossOriginProtection) Handler(h Handler) Handler { 195 return HandlerFunc(func(w ResponseWriter, r *Request) { 196 if err := c.Check(r); err != nil { 197 if deny := c.deny.Load(); deny != nil { 198 (*deny).ServeHTTP(w, r) 199 return 200 } 201 Error(w, err.Error(), StatusForbidden) 202 return 203 } 204 h.ServeHTTP(w, r) 205 }) 206 } 207