| 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 |
|
| 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 |
|
| 43 |
type Options struct { |
| 44 |
|
| 45 |
BrowserXssFilter bool |
| 46 |
|
| 47 |
ContentTypeNosniff bool |
| 48 |
|
| 49 |
ForceSTSHeader bool |
| 50 |
|
| 51 |
FrameDeny bool |
| 52 |
|
| 53 |
|
| 54 |
IsDevelopment bool |
| 55 |
|
| 56 |
nonceEnabled bool |
| 57 |
|
| 58 |
SSLRedirect bool |
| 59 |
|
| 60 |
SSLForceHost bool |
| 61 |
|
| 62 |
SSLTemporaryRedirect bool |
| 63 |
|
| 64 |
STSIncludeSubdomains bool |
| 65 |
|
| 66 |
STSPreload bool |
| 67 |
|
| 68 |
ContentSecurityPolicy string |
| 69 |
|
| 70 |
ContentSecurityPolicyReportOnly string |
| 71 |
|
| 72 |
CustomBrowserXssValue string |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
CustomFrameOptionsValue string |
| 77 |
|
| 78 |
|
| 79 |
PublicKey string |
| 80 |
|
| 81 |
ReferrerPolicy string |
| 82 |
|
| 83 |
|
| 84 |
FeaturePolicy string |
| 85 |
|
| 86 |
PermissionsPolicy string |
| 87 |
|
| 88 |
SSLHost string |
| 89 |
|
| 90 |
AllowedHosts []string |
| 91 |
|
| 92 |
|
| 93 |
AllowedHostsAreRegex bool |
| 94 |
|
| 95 |
HostsProxyHeaders []string |
| 96 |
|
| 97 |
|
| 98 |
SSLHostFunc *SSLHostFunc |
| 99 |
|
| 100 |
SSLProxyHeaders map[string]string |
| 101 |
|
| 102 |
STSSeconds int64 |
| 103 |
|
| 104 |
ExpectCTHeader string |
| 105 |
|
| 106 |
SecureContextKey string |
| 107 |
} |
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
type Secure struct { |
| 112 |
|
| 113 |
opt Options |
| 114 |
|
| 115 |
|
| 116 |
badHostHandler http.Handler |
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
cRegexAllowedHosts []*regexp.Regexp |
| 121 |
|
| 122 |
|
| 123 |
ctxSecureHeaderKey secureCtxKey |
| 124 |
} |
| 125 |
|
| 126 |
|
| 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 |
|
| 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 |
|
| 165 |
func (s *Secure) SetBadHostHandler(handler http.Handler) { |
| 166 |
s.badHostHandler = handler |
| 167 |
} |
| 168 |
|
| 169 |
|
| 170 |
func (s *Secure) Handler(h http.Handler) http.Handler { |
| 171 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 172 |
|
| 173 |
|
| 174 |
responseHeader, r, err := s.processRequest(w, r) |
| 175 |
addResponseHeaders(responseHeader, w) |
| 176 |
|
| 177 |
|
| 178 |
if err != nil { |
| 179 |
return |
| 180 |
} |
| 181 |
|
| 182 |
h.ServeHTTP(w, r) |
| 183 |
}) |
| 184 |
} |
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
func (s *Secure) HandlerForRequestOnly(h http.Handler) http.Handler { |
| 189 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 190 |
|
| 191 |
|
| 192 |
responseHeader, r, err := s.processRequest(w, r) |
| 193 |
|
| 194 |
|
| 195 |
if err != nil { |
| 196 |
return |
| 197 |
} |
| 198 |
|
| 199 |
|
| 200 |
ctx := context.WithValue(r.Context(), s.ctxSecureHeaderKey, responseHeader) |
| 201 |
|
| 202 |
|
| 203 |
h.ServeHTTP(w, r.WithContext(ctx)) |
| 204 |
}) |
| 205 |
} |
| 206 |
|
| 207 |
|
| 208 |
func (s *Secure) HandlerFuncWithNext(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { |
| 209 |
|
| 210 |
|
| 211 |
responseHeader, r, err := s.processRequest(w, r) |
| 212 |
addResponseHeaders(responseHeader, w) |
| 213 |
|
| 214 |
|
| 215 |
if err == nil && next != nil { |
| 216 |
next(w, r) |
| 217 |
} |
| 218 |
} |
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
func (s *Secure) HandlerFuncWithNextForRequestOnly(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { |
| 223 |
|
| 224 |
|
| 225 |
responseHeader, r, err := s.processRequest(w, r) |
| 226 |
|
| 227 |
|
| 228 |
if err == nil && next != nil { |
| 229 |
|
| 230 |
ctx := context.WithValue(r.Context(), s.ctxSecureHeaderKey, responseHeader) |
| 231 |
|
| 232 |
|
| 233 |
next(w, r.WithContext(ctx)) |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
|
| 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 |
|
| 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 |
|
| 255 |
|
| 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 |
|
| 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 |
|
| 273 |
func (s *Secure) processRequest(w http.ResponseWriter, r *http.Request) (http.Header, *http.Request, error) { |
| 274 |
|
| 275 |
if s.opt.nonceEnabled { |
| 276 |
r = withCSPNonce(r, cspRandNonce()) |
| 277 |
} |
| 278 |
|
| 279 |
|
| 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 |
|
| 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 |
|
| 314 |
ssl := s.isSSL(r) |
| 315 |
|
| 316 |
|
| 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 |
|
| 364 |
responseHeader := make(http.Header) |
| 365 |
|
| 366 |
|
| 367 |
|
| 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 |
|
| 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 |
|
| 389 |
if s.opt.ContentTypeNosniff { |
| 390 |
responseHeader.Set(contentTypeHeader, contentTypeValue) |
| 391 |
} |
| 392 |
|
| 393 |
|
| 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 |
|
| 401 |
if len(s.opt.PublicKey) > 0 && ssl && !s.opt.IsDevelopment { |
| 402 |
responseHeader.Set(hpkpHeader, s.opt.PublicKey) |
| 403 |
} |
| 404 |
|
| 405 |
|
| 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 |
|
| 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 |
|
| 424 |
if len(s.opt.ReferrerPolicy) > 0 { |
| 425 |
responseHeader.Set(referrerPolicyHeader, s.opt.ReferrerPolicy) |
| 426 |
} |
| 427 |
|
| 428 |
|
| 429 |
if len(s.opt.FeaturePolicy) > 0 { |
| 430 |
responseHeader.Set(featurePolicyHeader, s.opt.FeaturePolicy) |
| 431 |
} |
| 432 |
|
| 433 |
|
| 434 |
if len(s.opt.PermissionsPolicy) > 0 { |
| 435 |
responseHeader.Set(permissionsPolicyHeader, s.opt.PermissionsPolicy) |
| 436 |
} |
| 437 |
|
| 438 |
|
| 439 |
if len(s.opt.ExpectCTHeader) > 0 { |
| 440 |
responseHeader.Set(expectCTHeader, s.opt.ExpectCTHeader) |
| 441 |
} |
| 442 |
|
| 443 |
return responseHeader, r, nil |
| 444 |
} |
| 445 |
|
| 446 |
|
| 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 |
|
| 461 |
|
| 462 |
func (s *Secure) ModifyResponseHeaders(res *http.Response) error { |
| 463 |
if res != nil && res.Request != nil { |
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 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 |
} |