Debian Codegraph @

secure.go

raw symbols SCIP
1 package secure
2
3 import (
4 "context"
5 "fmt"
6 "net/http"
7 "regexp"
8 "strings"
9 )
10
11 type secureCtxKey string
12
13 const (
14 stsHeader = "Strict-Transport-Security"
15 stsSubdomainString = "; includeSubDomains"
16 stsPreloadString = "; preload"
17 frameOptionsHeader = "X-Frame-Options"
18 frameOptionsValue = "DENY"
19 contentTypeHeader = "X-Content-Type-Options"
20 contentTypeValue = "nosniff"
21 xssProtectionHeader = "X-XSS-Protection"
22 xssProtectionValue = "1; mode=block"
23 cspHeader = "Content-Security-Policy"
24 cspReportOnlyHeader = "Content-Security-Policy-Report-Only"
25 hpkpHeader = "Public-Key-Pins"
26 referrerPolicyHeader = "Referrer-Policy"
27 featurePolicyHeader = "Feature-Policy"
28 permissionsPolicyHeader = "Permissions-Policy"
29 expectCTHeader = "Expect-CT"
30
31 ctxDefaultSecureHeaderKey = secureCtxKey("SecureResponseHeader")
32 cspNonceSize = 16
33 )
34
35 // SSLHostFunc a type whose pointer is the type of field `SSLHostFunc` of `Options` struct
36 type SSLHostFunc func(host string) (newHost string)
37
38 func defaultBadHostHandler(w http.ResponseWriter, r *http.Request) {
39 http.Error(w, "Bad Host", http.StatusInternalServerError)
40 }
41
42 // Options is a struct for specifying configuration options for the secure.Secure middleware.
43 type Options struct {
44 // If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false.
45 BrowserXssFilter bool // nolint: golint
46 // If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false.
47 ContentTypeNosniff bool
48 // If ForceSTSHeader is set to true, the STS header will be added even when the connection is HTTP. Default is false.
49 ForceSTSHeader bool
50 // If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false.
51 FrameDeny bool
52 // When developing, the AllowedHosts, SSL, and STS options can cause some unwanted effects. Usually testing happens on http, not https, and on localhost, not your production domain... so set this to true for dev environment.
53 // If you would like your development environment to mimic production with complete Host blocking, SSL redirects, and STS headers, leave this as false. Default if false.
54 IsDevelopment bool
55 // nonceEnabled is used internally for dynamic nouces.
56 nonceEnabled bool
57 // If SSLRedirect is set to true, then only allow https requests. Default is false.
58 SSLRedirect bool
59 // If SSLForceHost is true and SSLHost is set, requests will be forced to use SSLHost even the ones that are already using SSL. Default is false.
60 SSLForceHost bool
61 // If SSLTemporaryRedirect is true, the a 302 will be used while redirecting. Default is false (301).
62 SSLTemporaryRedirect bool
63 // If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false.
64 STSIncludeSubdomains bool
65 // If STSPreload is set to true, the `preload` flag will be appended to the Strict-Transport-Security header. Default is false.
66 STSPreload bool
67 // ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "".
68 ContentSecurityPolicy string
69 // ContentSecurityPolicyReportOnly allows the Content-Security-Policy-Report-Only header value to be set with a custom value. Default is "".
70 ContentSecurityPolicyReportOnly string
71 // CustomBrowserXssValue allows the X-XSS-Protection header value to be set with a custom value. This overrides the BrowserXssFilter option. Default is "".
72 CustomBrowserXssValue string // nolint: golint
73 // Passing a template string will replace `$NONCE` with a dynamic nonce value of 16 bytes for each request which can be later retrieved using the Nonce function.
74 // Eg: script-src $NONCE -> script-src 'nonce-a2ZobGFoZg=='
75 // CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option. Default is "".
76 CustomFrameOptionsValue string
77 // PublicKey implements HPKP to prevent MITM attacks with forged certificates. Default is "".
78 // Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible.
79 PublicKey string
80 // ReferrerPolicy allows sites to control when browsers will pass the Referer header to other sites. Default is "".
81 ReferrerPolicy string
82 // FeaturePolicy allows to selectively enable and disable use of various browser features and APIs. Default is "".
83 // Deprecated: This header has been renamed to Permissions-Policy.
84 FeaturePolicy string
85 // PermissionsPolicy allows to selectively enable and disable use of various browser features and APIs. Default is "".
86 PermissionsPolicy string
87 // SSLHost is the host name that is used to redirect http requests to https. Default is "", which indicates to use the same host.
88 SSLHost string
89 // AllowedHosts is a list of fully qualified domain names that are allowed. Default is empty list, which allows any and all host names.
90 AllowedHosts []string
91 // AllowedHostsAreRegex determines, if the provided slice contains valid regular expressions. If this flag is set to true, every request's
92 // host will be checked against these expressions. Default is false for backwards compatibility.
93 AllowedHostsAreRegex bool
94 // HostsProxyHeaders is a set of header keys that may hold a proxied hostname value for the request.
95 HostsProxyHeaders []string
96 // SSLHostFunc is a function pointer, the return value of the function is the host name that has same functionality as `SSHost`. Default is nil.
97 // If SSLHostFunc is nil, the `SSLHost` option will be used.
98 SSLHostFunc *SSLHostFunc
99 // SSLProxyHeaders is set of header keys with associated values that would indicate a valid https request. Useful when using Nginx: `map[string]string{"X-Forwarded-Proto": "https"}`. Default is blank map.
100 SSLProxyHeaders map[string]string
101 // STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header.
102 STSSeconds int64
103 // ExpectCTHeader allows the Expect-CT header value to be set with a custom value. Default is "".
104 ExpectCTHeader string
105 // SecureContextKey allows a custom key to be specified for context storage.
106 SecureContextKey string
107 }
108
109 // Secure is a middleware that helps setup a few basic security features. A single secure.Options struct can be
110 // provided to configure which features should be enabled, and the ability to override a few of the default values.
111 type Secure struct {
112 // Customize Secure with an Options struct.
113 opt Options
114
115 // badHostHandler is the handler used when an incorrect host is passed in.
116 badHostHandler http.Handler
117
118 // cRegexAllowedHosts saves the compiled regular expressions of the AllowedHosts
119 // option for subsequent use in processRequest
120 cRegexAllowedHosts []*regexp.Regexp
121
122 // ctxSecureHeaderKey is the key used for context storage for request modification.
123 ctxSecureHeaderKey secureCtxKey
124 }
125
126 // New constructs a new Secure instance with the supplied options.
127 func New(options ...Options) *Secure {
128 var o Options
129 if len(options) == 0 {
130 o = Options{}
131 } else {
132 o = options[0]
133 }
134
135 o.ContentSecurityPolicy = strings.Replace(o.ContentSecurityPolicy, "$NONCE", "'nonce-%[1]s'", -1)
136 o.ContentSecurityPolicyReportOnly = strings.Replace(o.ContentSecurityPolicyReportOnly, "$NONCE", "'nonce-%[1]s'", -1)
137
138 o.nonceEnabled = strings.Contains(o.ContentSecurityPolicy, "%[1]s") || strings.Contains(o.ContentSecurityPolicyReportOnly, "%[1]s")
139
140 s := &Secure{
141 opt: o,
142 badHostHandler: http.HandlerFunc(defaultBadHostHandler),
143 }
144
145 if s.opt.AllowedHostsAreRegex {
146 // Test for invalid regular expressions in AllowedHosts
147 for _, allowedHost := range o.AllowedHosts {
148 regex, err := regexp.Compile(fmt.Sprintf("^%s$", allowedHost))
149 if err != nil {
150 panic(fmt.Sprintf("Error parsing AllowedHost: %s", err))
151 }
152 s.cRegexAllowedHosts = append(s.cRegexAllowedHosts, regex)
153 }
154 }
155
156 s.ctxSecureHeaderKey = ctxDefaultSecureHeaderKey
157 if len(s.opt.SecureContextKey) > 0 {
158 s.ctxSecureHeaderKey = secureCtxKey(s.opt.SecureContextKey)
159 }
160
161 return s
162 }
163
164 // SetBadHostHandler sets the handler to call when secure rejects the host name.
165 func (s *Secure) SetBadHostHandler(handler http.Handler) {
166 s.badHostHandler = handler
167 }
168
169 // Handler implements the http.HandlerFunc for integration with the standard net/http lib.
170 func (s *Secure) Handler(h http.Handler) http.Handler {
171 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
172 // Let secure process the request. If it returns an error,
173 // that indicates the request should not continue.
174 responseHeader, r, err := s.processRequest(w, r)
175 addResponseHeaders(responseHeader, w)
176
177 // If there was an error, do not continue.
178 if err != nil {
179 return
180 }
181
182 h.ServeHTTP(w, r)
183 })
184 }
185
186 // HandlerForRequestOnly implements the http.HandlerFunc for integration with the standard net/http lib.
187 // Note that this is for requests only and will not write any headers.
188 func (s *Secure) HandlerForRequestOnly(h http.Handler) http.Handler {
189 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
190 // Let secure process the request. If it returns an error,
191 // that indicates the request should not continue.
192 responseHeader, r, err := s.processRequest(w, r)
193
194 // If there was an error, do not continue.
195 if err != nil {
196 return
197 }
198
199 // Save response headers in the request context.
200 ctx := context.WithValue(r.Context(), s.ctxSecureHeaderKey, responseHeader)
201
202 // No headers will be written to the ResponseWriter.
203 h.ServeHTTP(w, r.WithContext(ctx))
204 })
205 }
206
207 // HandlerFuncWithNext is a special implementation for Negroni, but could be used elsewhere.
208 func (s *Secure) HandlerFuncWithNext(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
209 // Let secure process the request. If it returns an error,
210 // that indicates the request should not continue.
211 responseHeader, r, err := s.processRequest(w, r)
212 addResponseHeaders(responseHeader, w)
213
214 // If there was an error, do not call next.
215 if err == nil && next != nil {
216 next(w, r)
217 }
218 }
219
220 // HandlerFuncWithNextForRequestOnly is a special implementation for Negroni, but could be used elsewhere.
221 // Note that this is for requests only and will not write any headers.
222 func (s *Secure) HandlerFuncWithNextForRequestOnly(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
223 // Let secure process the request. If it returns an error,
224 // that indicates the request should not continue.
225 responseHeader, r, err := s.processRequest(w, r)
226
227 // If there was an error, do not call next.
228 if err == nil && next != nil {
229 // Save response headers in the request context
230 ctx := context.WithValue(r.Context(), s.ctxSecureHeaderKey, responseHeader)
231
232 // No headers will be written to the ResponseWriter.
233 next(w, r.WithContext(ctx))
234 }
235 }
236
237 // addResponseHeaders Adds the headers from 'responseHeader' to the response.
238 func addResponseHeaders(responseHeader http.Header, w http.ResponseWriter) {
239 for key, values := range responseHeader {
240 for _, value := range values {
241 w.Header().Set(key, value)
242 }
243 }
244 }
245
246 // Process runs the actual checks and writes the headers in the ResponseWriter.
247 func (s *Secure) Process(w http.ResponseWriter, r *http.Request) error {
248 responseHeader, _, err := s.processRequest(w, r)
249 addResponseHeaders(responseHeader, w)
250
251 return err
252 }
253
254 // ProcessAndReturnNonce runs the actual checks and writes the headers in the ResponseWriter.
255 // In addition, the generated nonce for the request is returned as well as the error value.
256 func (s *Secure) ProcessAndReturnNonce(w http.ResponseWriter, r *http.Request) (string, error) {
257 responseHeader, newR, err := s.processRequest(w, r)
258 if err != nil {
259 return "", err
260 }
261
262 addResponseHeaders(responseHeader, w)
263
264 return CSPNonce(newR.Context()), err
265 }
266
267 // ProcessNoModifyRequest runs the actual checks but does not write the headers in the ResponseWriter.
268 func (s *Secure) ProcessNoModifyRequest(w http.ResponseWriter, r *http.Request) (http.Header, *http.Request, error) {
269 return s.processRequest(w, r)
270 }
271
272 // processRequest runs the actual checks on the request and returns an error if the middleware chain should stop.
273 func (s *Secure) processRequest(w http.ResponseWriter, r *http.Request) (http.Header, *http.Request, error) {
274 // Setup nonce if required.
275 if s.opt.nonceEnabled {
276 r = withCSPNonce(r, cspRandNonce())
277 }
278
279 // Resolve the host for the request, using proxy headers if present.
280 host := r.Host
281 for _, header := range s.opt.HostsProxyHeaders {
282 if h := r.Header.Get(header); h != "" {
283 host = h
284 break
285 }
286 }
287
288 // Allowed hosts check.
289 if len(s.opt.AllowedHosts) > 0 && !s.opt.IsDevelopment {
290 isGoodHost := false
291 if s.opt.AllowedHostsAreRegex {
292 for _, allowedHost := range s.cRegexAllowedHosts {
293 if match := allowedHost.MatchString(host); match {
294 isGoodHost = true
295 break
296 }
297 }
298 } else {
299 for _, allowedHost := range s.opt.AllowedHosts {
300 if strings.EqualFold(allowedHost, host) {
301 isGoodHost = true
302 break
303 }
304 }
305 }
306
307 if !isGoodHost {
308 s.badHostHandler.ServeHTTP(w, r)
309 return nil, nil, fmt.Errorf("bad host name: %s", host)
310 }
311 }
312
313 // Determine if we are on HTTPS.
314 ssl := s.isSSL(r)
315
316 // SSL check.
317 if s.opt.SSLRedirect && !ssl && !s.opt.IsDevelopment {
318 url := r.URL
319 url.Scheme = "https"
320 url.Host = host
321
322 if s.opt.SSLHostFunc != nil {
323 if h := (*s.opt.SSLHostFunc)(host); len(h) > 0 {
324 url.Host = h
325 }
326 } else if len(s.opt.SSLHost) > 0 {
327 url.Host = s.opt.SSLHost
328 }
329
330 status := http.StatusMovedPermanently
331 if s.opt.SSLTemporaryRedirect {
332 status = http.StatusTemporaryRedirect
333 }
334
335 http.Redirect(w, r, url.String(), status)
336 return nil, nil, fmt.Errorf("redirecting to HTTPS")
337 }
338
339 if s.opt.SSLForceHost {
340 var SSLHost = host
341 if s.opt.SSLHostFunc != nil {
342 if h := (*s.opt.SSLHostFunc)(host); len(h) > 0 {
343 SSLHost = h
344 }
345 } else if len(s.opt.SSLHost) > 0 {
346 SSLHost = s.opt.SSLHost
347 }
348 if SSLHost != host {
349 url := r.URL
350 url.Scheme = "https"
351 url.Host = SSLHost
352
353 status := http.StatusMovedPermanently
354 if s.opt.SSLTemporaryRedirect {
355 status = http.StatusTemporaryRedirect
356 }
357
358 http.Redirect(w, r, url.String(), status)
359 return nil, nil, fmt.Errorf("redirecting to HTTPS")
360 }
361 }
362
363 // Create our header container.
364 responseHeader := make(http.Header)
365
366 // Strict Transport Security header. Only add header when we know it's an SSL connection.
367 // See https://tools.ietf.org/html/rfc6797#section-7.2 for details.
368 if s.opt.STSSeconds != 0 && (ssl || s.opt.ForceSTSHeader) && !s.opt.IsDevelopment {
369 stsSub := ""
370 if s.opt.STSIncludeSubdomains {
371 stsSub = stsSubdomainString
372 }
373
374 if s.opt.STSPreload {
375 stsSub += stsPreloadString
376 }
377
378 responseHeader.Set(stsHeader, fmt.Sprintf("max-age=%d%s", s.opt.STSSeconds, stsSub))
379 }
380
381 // Frame Options header.
382 if len(s.opt.CustomFrameOptionsValue) > 0 {
383 responseHeader.Set(frameOptionsHeader, s.opt.CustomFrameOptionsValue)
384 } else if s.opt.FrameDeny {
385 responseHeader.Set(frameOptionsHeader, frameOptionsValue)
386 }
387
388 // Content Type Options header.
389 if s.opt.ContentTypeNosniff {
390 responseHeader.Set(contentTypeHeader, contentTypeValue)
391 }
392
393 // XSS Protection header.
394 if len(s.opt.CustomBrowserXssValue) > 0 {
395 responseHeader.Set(xssProtectionHeader, s.opt.CustomBrowserXssValue)
396 } else if s.opt.BrowserXssFilter {
397 responseHeader.Set(xssProtectionHeader, xssProtectionValue)
398 }
399
400 // HPKP header.
401 if len(s.opt.PublicKey) > 0 && ssl && !s.opt.IsDevelopment {
402 responseHeader.Set(hpkpHeader, s.opt.PublicKey)
403 }
404
405 // Content Security Policy header.
406 if len(s.opt.ContentSecurityPolicy) > 0 {
407 if s.opt.nonceEnabled {
408 responseHeader.Set(cspHeader, fmt.Sprintf(s.opt.ContentSecurityPolicy, CSPNonce(r.Context())))
409 } else {
410 responseHeader.Set(cspHeader, s.opt.ContentSecurityPolicy)
411 }
412 }
413
414 // Content Security Policy Report Only header.
415 if len(s.opt.ContentSecurityPolicyReportOnly) > 0 {
416 if s.opt.nonceEnabled {
417 responseHeader.Set(cspReportOnlyHeader, fmt.Sprintf(s.opt.ContentSecurityPolicyReportOnly, CSPNonce(r.Context())))
418 } else {
419 responseHeader.Set(cspReportOnlyHeader, s.opt.ContentSecurityPolicyReportOnly)
420 }
421 }
422
423 // Referrer Policy header.
424 if len(s.opt.ReferrerPolicy) > 0 {
425 responseHeader.Set(referrerPolicyHeader, s.opt.ReferrerPolicy)
426 }
427
428 // Feature Policy header.
429 if len(s.opt.FeaturePolicy) > 0 {
430 responseHeader.Set(featurePolicyHeader, s.opt.FeaturePolicy)
431 }
432
433 // Permissions Policy header.
434 if len(s.opt.PermissionsPolicy) > 0 {
435 responseHeader.Set(permissionsPolicyHeader, s.opt.PermissionsPolicy)
436 }
437
438 // Expect-CT header.
439 if len(s.opt.ExpectCTHeader) > 0 {
440 responseHeader.Set(expectCTHeader, s.opt.ExpectCTHeader)
441 }
442
443 return responseHeader, r, nil
444 }
445
446 // isSSL determine if we are on HTTPS.
447 func (s *Secure) isSSL(r *http.Request) bool {
448 ssl := strings.EqualFold(r.URL.Scheme, "https") || r.TLS != nil
449 if !ssl {
450 for k, v := range s.opt.SSLProxyHeaders {
451 if r.Header.Get(k) == v {
452 ssl = true
453 break
454 }
455 }
456 }
457 return ssl
458 }
459
460 // ModifyResponseHeaders modifies the Response.
461 // Used by http.ReverseProxy.
462 func (s *Secure) ModifyResponseHeaders(res *http.Response) error {
463 if res != nil && res.Request != nil {
464 // Fix Location response header http to https:
465 // When SSL is enabled,
466 // And SSLHost is defined,
467 // And the response location header includes the SSLHost as the domain with a trailing slash,
468 // Or an exact match to the SSLHost.
469 location := res.Header.Get("Location")
470 if s.isSSL(res.Request) &&
471 len(s.opt.SSLHost) > 0 &&
472 (strings.HasPrefix(location, fmt.Sprintf("http://%s/", s.opt.SSLHost)) || location == fmt.Sprintf("http://%s", s.opt.SSLHost)) {
473 location = strings.Replace(location, "http:", "https:", 1)
474 res.Header.Set("Location", location)
475 }
476
477 responseHeader := res.Request.Context().Value(s.ctxSecureHeaderKey)
478 if responseHeader != nil {
479 for header, values := range responseHeader.(http.Header) {
480 if len(values) > 0 {
481 res.Header.Set(header, strings.Join(values, ","))
482 }
483 }
484 }
485 }
486 return nil
487 }