Documentation ¶
Overview ¶
Package secure is an HTTP middleware for Go that facilitates some quick security wins.
package main import ( "net/http" "github.com/unrolled/secure" ) var myHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world")) }) func main() { secureMiddleware := secure.New(secure.Options{ AllowedHosts: []string{"www.example.com", "sub.example.com"}, SSLRedirect: true, }) app := secureMiddleware.Handler(myHandler) http.ListenAndServe("127.0.0.1:3000", app) }
Index ¶
- func CSPNonce(c context.Context) string
- func WithCSPNonce(ctx context.Context, nonce string) context.Context
- type AllowRequestFunc
- type Options
- type SSLHostFunc
- type Secure
- func (s *Secure) Handler(h http.Handler) http.Handler
- func (s *Secure) HandlerForRequestOnly(h http.Handler) http.Handler
- func (s *Secure) HandlerFuncWithNext(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
- func (s *Secure) HandlerFuncWithNextForRequestOnly(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
- func (s *Secure) ModifyResponseHeaders(res *http.Response) error
- func (s *Secure) Process(w http.ResponseWriter, r *http.Request) error
- func (s *Secure) ProcessAndReturnNonce(w http.ResponseWriter, r *http.Request) (string, error)
- func (s *Secure) ProcessNoModifyRequest(w http.ResponseWriter, r *http.Request) (http.Header, *http.Request, error)
- func (s *Secure) SetBadHostHandler(handler http.Handler)
- func (s *Secure) SetBadRequestHandler(handler http.Handler)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CSPNonce ¶
CSPNonce returns the nonce value associated with the present request. If no nonce has been generated it returns an empty string.
func WithCSPNonce ¶
WithCSPNonce returns a context derived from ctx containing the given nonce as a value.
This is intended for testing or more advanced use-cases; For ordinary HTTP handlers, clients can rely on this package's middleware to populate the CSP nonce in the context.
Types ¶
type AllowRequestFunc ¶ added in v1.12.0
AllowRequestFunc is a custom function type that can be used to dynamically determine if a request should proceed or not.
type Options ¶
type Options struct { // If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false. BrowserXssFilter bool //nolint:stylecheck,revive // If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false. ContentTypeNosniff bool // If ForceSTSHeader is set to true, the STS header will be added even when the connection is HTTP. Default is false. ForceSTSHeader bool // If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false. FrameDeny bool // 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. // 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. IsDevelopment bool // If SSLRedirect is set to true, then only allow https requests. Default is false. SSLRedirect bool // 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. SSLForceHost bool // If SSLTemporaryRedirect is true, then a 307 will be used while redirecting. Default is false (301). SSLTemporaryRedirect bool // If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false. STSIncludeSubdomains bool // If STSPreload is set to true, the `preload` flag will be appended to the Strict-Transport-Security header. Default is false. STSPreload bool // ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "". ContentSecurityPolicy string // ContentSecurityPolicyReportOnly allows the Content-Security-Policy-Report-Only header value to be set with a custom value. Default is "". ContentSecurityPolicyReportOnly string // CustomBrowserXssValue allows the X-XSS-Protection header value to be set with a custom value. This overrides the BrowserXssFilter option. Default is "". CustomBrowserXssValue string //nolint:stylecheck,revive // 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. // Eg: script-src $NONCE -> script-src 'nonce-a2ZobGFoZg==' // CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option. Default is "". CustomFrameOptionsValue string // ReferrerPolicy allows sites to control when browsers will pass the Referer header to other sites. Default is "". ReferrerPolicy string // FeaturePolicy allows to selectively enable and disable use of various browser features and APIs. Default is "". // Deprecated: This header has been renamed to Permissions-Policy. FeaturePolicy string // PermissionsPolicy allows to selectively enable and disable use of various browser features and APIs. Default is "". PermissionsPolicy string // CrossOriginOpenerPolicy allows you to ensure a top-level document does not share a browsing context group with cross-origin documents. Default is "". // Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy CrossOriginOpenerPolicy string // CrossOriginResourcePolicy header blocks others from loading your resources cross-origin in some cases. // Reference https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy CrossOriginResourcePolicy string // CrossOriginEmbedderPolicy header helps control what resources can be loaded cross-origin. // Reference https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy CrossOriginEmbedderPolicy string // XDNSPrefetchControl header helps control DNS prefetching, which can improve user privacy at the expense of performance. // Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control XDNSPrefetchControl string // XPermittedCrossDomainPolicies header tells some clients (mostly Adobe products) your domain's policy for loading cross-domain content. // Reference: https://owasp.org/www-project-secure-headers/ XPermittedCrossDomainPolicies string // SSLHost is the host name that is used to redirect http requests to https. Default is "", which indicates to use the same host. SSLHost string // AllowedHosts is a slice of fully qualified domain names that are allowed. Default is an empty slice, which allows any and all host names. AllowedHosts []string // AllowedHostsAreRegex determines, if the provided `AllowedHosts` slice contains valid regular expressions. If this flag is set to true, every request's host will be checked against these expressions. Default is false. AllowedHostsAreRegex bool // AllowRequestFunc is a custom function that allows you to determine if the request should proceed or not based on your own custom logic. Default is nil. AllowRequestFunc AllowRequestFunc `json:"-" toml:"-" yaml:"-"` // HostsProxyHeaders is a set of header keys that may hold a proxied hostname value for the request. HostsProxyHeaders []string // SSLHostFunc is a function pointer, the return value of the function is the host name that has same functionality as `SSHost`. Default is nil. // If SSLHostFunc is nil, the `SSLHost` option will be used. SSLHostFunc *SSLHostFunc `json:"-" toml:"-" yaml:"-"` // 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. SSLProxyHeaders map[string]string // STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header. STSSeconds int64 // SecureContextKey allows a custom key to be specified for context storage. SecureContextKey string // contains filtered or unexported fields }
Options is a struct for specifying configuration options for the secure.Secure middleware.
type SSLHostFunc ¶
SSLHostFunc is a custom function type that can be used to dynamically set the SSL host of a request.
type Secure ¶
type Secure struct {
// contains filtered or unexported fields
}
Secure is a middleware that helps setup a few basic security features. A single secure.Options struct can be provided to configure which features should be enabled, and the ability to override a few of the default values.
func (*Secure) Handler ¶
Handler implements the http.HandlerFunc for integration with the standard net/http lib.
func (*Secure) HandlerForRequestOnly ¶
HandlerForRequestOnly implements the http.HandlerFunc for integration with the standard net/http lib. Note that this is for requests only and will not write any headers.
func (*Secure) HandlerFuncWithNext ¶
func (s *Secure) HandlerFuncWithNext(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
HandlerFuncWithNext is a special implementation for Negroni, but could be used elsewhere.
func (*Secure) HandlerFuncWithNextForRequestOnly ¶
func (s *Secure) HandlerFuncWithNextForRequestOnly(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)
HandlerFuncWithNextForRequestOnly is a special implementation for Negroni, but could be used elsewhere. Note that this is for requests only and will not write any headers.
func (*Secure) ModifyResponseHeaders ¶
ModifyResponseHeaders modifies the Response. Used by http.ReverseProxy.
func (*Secure) Process ¶
Process runs the actual checks and writes the headers in the ResponseWriter.
func (*Secure) ProcessAndReturnNonce ¶ added in v1.0.2
ProcessAndReturnNonce runs the actual checks and writes the headers in the ResponseWriter. In addition, the generated nonce for the request is returned as well as the error value.
func (*Secure) ProcessNoModifyRequest ¶
func (s *Secure) ProcessNoModifyRequest(w http.ResponseWriter, r *http.Request) (http.Header, *http.Request, error)
ProcessNoModifyRequest runs the actual checks but does not write the headers in the ResponseWriter.
func (*Secure) SetBadHostHandler ¶
SetBadHostHandler sets the handler to call when secure rejects the host name.
func (*Secure) SetBadRequestHandler ¶ added in v1.12.0
SetBadRequestHandler sets the handler to call when the AllowRequestFunc rejects a request.