Coder Social home page Coder Social logo

secure's Introduction

Secure GoDoc Test

Secure is an HTTP middleware for Go that facilitates some quick security wins. It's a standard net/http Handler, and can be used with many frameworks or directly with Go's net/http package.

Usage

// main.go
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{"example\\.com", ".*\\.example\\.com"},
        AllowedHostsAreRegex:  true,
        HostsProxyHeaders:     []string{"X-Forwarded-Host"},
        SSLRedirect:           true,
        SSLHost:               "ssl.example.com",
        SSLProxyHeaders:       map[string]string{"X-Forwarded-Proto": "https"},
        STSSeconds:            31536000,
        STSIncludeSubdomains:  true,
        STSPreload:            true,
        FrameDeny:             true,
        ContentTypeNosniff:    true,
        BrowserXssFilter:      true,
        ContentSecurityPolicy: "script-src $NONCE",
    })

    app := secureMiddleware.Handler(myHandler)
    http.ListenAndServe("127.0.0.1:3000", app)
}

Be sure to include the Secure middleware as close to the top (beginning) as possible (but after logging and recovery). It's best to do the allowed hosts and SSL check before anything else.

The above example will only allow requests with a host name of 'example.com', or 'ssl.example.com'. Also if the request is not HTTPS, it will be redirected to HTTPS with the host name of 'ssl.example.com'. Once those requirements are satisfied, it will add the following headers:

Strict-Transport-Security: 31536000; includeSubdomains; preload
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Content-Security-Policy: script-src 'nonce-a2ZobGFoZg=='

Set the IsDevelopment option to true when developing!

When IsDevelopment is true, the AllowedHosts, SSLRedirect, and STS header will not be in effect. This allows you to work in development/test mode and not have any annoying redirects to HTTPS (ie. development can happen on HTTP), or block localhost has a bad host.

Available options

Secure comes with a variety of configuration options (Note: these are not the default option values. See the defaults below.):

// ...
s := secure.New(secure.Options{
    AllowedHosts: []string{"ssl.example.com"}, // AllowedHosts is a list of fully qualified domain names that are allowed. Default is empty list, which allows any and all host names.
    AllowedHostsAreRegex: false,  // AllowedHostsAreRegex determines, if the provided AllowedHosts slice contains valid regular expressions. Default is false.
    AllowRequestFunc: nil, // AllowRequestFunc is a custom function type that allows you to determine if the request should proceed or not based on your own custom logic. Default is nil.
    HostsProxyHeaders: []string{"X-Forwarded-Hosts"}, // HostsProxyHeaders is a set of header keys that may hold a proxied hostname value for the request.
    SSLRedirect: true, // If SSLRedirect is set to true, then only allow HTTPS requests. Default is false.
    SSLTemporaryRedirect: false, // If SSLTemporaryRedirect is true, the a 302 will be used while redirecting. Default is false (301).
    SSLHost: "ssl.example.com", // SSLHost is the host name that is used to redirect HTTP requests to HTTPS. Default is "", which indicates to use the same host.
    SSLHostFunc: nil, // 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.
    SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"}, // 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.
    STSSeconds: 31536000, // STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header.
    STSIncludeSubdomains: true, // If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false.
    STSPreload: true, // If STSPreload is set to true, the `preload` flag will be appended to the Strict-Transport-Security header. Default is false.
    ForceSTSHeader: false, // STS header is only included when the connection is HTTPS. If you want to force it to always be added, set to true. `IsDevelopment` still overrides this. Default is false.
    FrameDeny: true, // If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false.
    CustomFrameOptionsValue: "SAMEORIGIN", // CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option. Default is "".
    ContentTypeNosniff: true, // If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false.
    BrowserXssFilter: true, // If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false.
    CustomBrowserXssValue: "1; report=https://example.com/xss-report", // CustomBrowserXssValue allows the X-XSS-Protection header value to be set with a custom value. This overrides the BrowserXssFilter option. Default is "".
    ContentSecurityPolicy: "default-src 'self'", // ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "". 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.
    ReferrerPolicy: "same-origin", // ReferrerPolicy allows the Referrer-Policy header with the value to be set with a custom value. Default is "".
    FeaturePolicy: "vibrate 'none';", // Deprecated: this header has been renamed to PermissionsPolicy. FeaturePolicy allows the Feature-Policy header with the value to be set with a custom value. Default is "".
    PermissionsPolicy: "fullscreen=(), geolocation=()", // PermissionsPolicy allows the Permissions-Policy header with the value to be set with a custom value. Default is "".
    CrossOriginOpenerPolicy: "same-origin", // CrossOriginOpenerPolicy allows the Cross-Origin-Opener-Policy header with the value to be set with a custom value. Default is "".

    IsDevelopment: true, // This will cause the AllowedHosts, SSLRedirect, and STSSeconds/STSIncludeSubdomains options to be ignored during development. When deploying to production, be sure to set this to false.
})
// ...

Default options

These are the preset options for Secure:

s := secure.New()

// Is the same as the default configuration options:

l := secure.New(secure.Options{
    AllowedHosts: []string,
    AllowedHostsAreRegex: false,
    AllowRequestFunc: nil,
    HostsProxyHeaders: []string,
    SSLRedirect: false,
    SSLTemporaryRedirect: false,
    SSLHost: "",
    SSLProxyHeaders: map[string]string{},
    STSSeconds: 0,
    STSIncludeSubdomains: false,
    STSPreload: false,
    ForceSTSHeader: false,
    FrameDeny: false,
    CustomFrameOptionsValue: "",
    ContentTypeNosniff: false,
    BrowserXssFilter: false,
    ContentSecurityPolicy: "",
    PublicKey: "",
    ReferrerPolicy: "",
    FeaturePolicy: "",
    PermissionsPolicy: "",
    CrossOriginOpenerPolicy: "",
    IsDevelopment: false,
})

The default bad host handler returns the following error:

http.Error(w, "Bad Host", http.StatusInternalServerError)

Call secure.SetBadHostHandler to set your own custom handler.

The default bad request handler returns the following error:

http.Error(w, "Bad Request", http.StatusBadRequest)

Call secure.SetBadRequestHandler to set your own custom handler.

Allow Request Function

Secure allows you to set a custom function (func(r *http.Request) bool) for the AllowRequestFunc option. You can use this function as a custom filter to allow the request to continue or simply reject it. This can be handy if you need to do any dynamic filtering on any of the request properties. It should be noted that this function will be called on every request, so be sure to make your checks quick and not relying on time consuming external calls (or you will be slowing down all requests). See above on how to set a custom handler for the rejected requests.

Redirecting HTTP to HTTPS

If you want to redirect all HTTP requests to HTTPS, you can use the following example.

// main.go
package main

import (
    "log"
    "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{
        SSLRedirect: true,
        SSLHost:     "localhost:8443", // This is optional in production. The default behavior is to just redirect the request to the HTTPS protocol. Example: http://github.com/some_page would be redirected to https://github.com/some_page.
    })

    app := secureMiddleware.Handler(myHandler)

    // HTTP
    go func() {
        log.Fatal(http.ListenAndServe(":8080", app))
    }()

    // HTTPS
    // To generate a development cert and key, run the following from your *nix terminal:
    // go run $GOROOT/src/crypto/tls/generate_cert.go --host="localhost"
    log.Fatal(http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", app))
}

Strict Transport Security

The STS header will only be sent on verified HTTPS connections (and when IsDevelopment is false). Be sure to set the SSLProxyHeaders option if your application is behind a proxy to ensure the proper behavior. If you need the STS header for all HTTP and HTTPS requests (which you shouldn't), you can use the ForceSTSHeader option. Note that if IsDevelopment is true, it will still disable this header even when ForceSTSHeader is set to true.

  • The preload flag is required for domain inclusion in Chrome's preload list.

Content Security Policy

You can utilize the CSP Builder to create your policies:

import (
	"github.com/unrolled/secure"
	"github.com/unrolled/secure/cspbuilder"
)

cspBuilder := cspbuilder.Builder{
	Directives: map[string][]string{
		cspbuilder.DefaultSrc: {"self"},
		cspbuilder.ScriptSrc:  {"self", "www.google-analytics.com"},
		cspbuilder.ImgSrc:     {"*"},
	},
}

opt := secure.Options{
	ContentSecurityPolicy: cspBuilder.MustBuild(),
}

Integration examples

// main.go
package main

import (
    "net/http"

    "github.com/pressly/chi"
    "github.com/unrolled/secure"
)

func main() {
    secureMiddleware := secure.New(secure.Options{
        FrameDeny: true,
    })

    r := chi.NewRouter()
    r.Use(secureMiddleware.Handler)

    r.Get("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("X-Frame-Options header is now `DENY`."))
    })

    http.ListenAndServe("127.0.0.1:3000", r)
}
// main.go
package main

import (
    "net/http"

    "github.com/labstack/echo"
    "github.com/unrolled/secure"
)

func main() {
    secureMiddleware := secure.New(secure.Options{
        FrameDeny: true,
    })

    e := echo.New()
    e.GET("/", func(c echo.Context) error {
        return c.String(http.StatusOK, "X-Frame-Options header is now `DENY`.")
    })

    e.Use(echo.WrapMiddleware(secureMiddleware.Handler))
    e.Logger.Fatal(e.Start("127.0.0.1:3000"))
}
// main.go
package main

import (
    "github.com/gin-gonic/gin"
    "github.com/unrolled/secure"
)

func main() {
    secureMiddleware := secure.New(secure.Options{
        FrameDeny: true,
    })
    secureFunc := func() gin.HandlerFunc {
        return func(c *gin.Context) {
            err := secureMiddleware.Process(c.Writer, c.Request)

            // If there was an error, do not continue.
            if err != nil {
                c.Abort()
                return
            }

            // Avoid header rewrite if response is a redirection.
            if status := c.Writer.Status(); status > 300 && status < 399 {
                c.Abort()
            }
        }
    }()

    router := gin.Default()
    router.Use(secureFunc)

    router.GET("/", func(c *gin.Context) {
        c.String(200, "X-Frame-Options header is now `DENY`.")
    })

    router.Run("127.0.0.1:3000")
}
// main.go
package main

import (
    "net/http"

    "github.com/unrolled/secure"
    "github.com/zenazn/goji"
    "github.com/zenazn/goji/web"
)

func main() {
    secureMiddleware := secure.New(secure.Options{
        FrameDeny: true,
    })

    goji.Get("/", func(c web.C, w http.ResponseWriter, req *http.Request) {
        w.Write([]byte("X-Frame-Options header is now `DENY`."))
    })
    goji.Use(secureMiddleware.Handler)
    goji.Serve() // Defaults to ":8000".
}
//main.go
package main

import (
    "github.com/kataras/iris/v12"
    "github.com/unrolled/secure"
)

func main() {
    app := iris.New()

    secureMiddleware := secure.New(secure.Options{
        FrameDeny: true,
    })

    app.Use(iris.FromStd(secureMiddleware.HandlerFuncWithNext))
    // Identical to:
    // app.Use(func(ctx iris.Context) {
    //     err := secureMiddleware.Process(ctx.ResponseWriter(), ctx.Request())
    //
    //     // If there was an error, do not continue.
    //     if err != nil {
    //         return
    //     }
    //
    //     ctx.Next()
    // })

    app.Get("/home", func(ctx iris.Context) {
        ctx.Writef("X-Frame-Options header is now `%s`.", "DENY")
    })

    app.Listen(":8080")
}
//main.go
package main

import (
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/unrolled/secure"
)

func main() {
    secureMiddleware := secure.New(secure.Options{
        FrameDeny: true,
    })

    r := mux.NewRouter()
    r.Use(secureMiddleware.Handler)
    http.Handle("/", r)
    log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", 8080), nil))
}

Note this implementation has a special helper function called HandlerFuncWithNext.

// main.go
package main

import (
    "net/http"

    "github.com/urfave/negroni"
    "github.com/unrolled/secure"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        w.Write([]byte("X-Frame-Options header is now `DENY`."))
    })

    secureMiddleware := secure.New(secure.Options{
        FrameDeny: true,
    })

    n := negroni.Classic()
    n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext))
    n.UseHandler(mux)

    n.Run("127.0.0.1:3000")
}

secure's People

Contributors

aek avatar ant1441 avatar balasanjay avatar bramp avatar dtomcej avatar dvrkps avatar dzbarsky avatar ericlagergren avatar franklinexpress avatar hashworks avatar javierprovecho avatar jcgregorio avatar johnweldon avatar justingallardo-okta avatar kataras avatar klische avatar kujenga avatar ldez avatar m22o avatar matbesancon avatar mavimo avatar mmatur avatar pzeinlinger avatar roemerb avatar srikrsna avatar tclem avatar ulan08 avatar unrolled avatar wizr avatar yhlee-tw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

secure's Issues

WSS support

I'm trying to use unrolled secure for CSP support, but I'm finding the static configuration a little inflexible when trying to configure for websockets. Would there be interest in a new configuration option to support websockets in the connect-src option that was slightly more dynamic?

for websockets the policy looks like connect-src wss://theserver. Since the configuration is statically configured at middleware construction time, and it's hard to know what IP the server is actually serving from until runtime; especially with reverse proxys and containers, etc, this makes it hard to achieve with the current middleware.

Options:

  1. write a new middleware and not use the CSP option in unrolled/secure
  2. write code which allows dynamic insertion of WSS/WS using the incoming request's Host value.

Would there be interest in take a PR which implemented something like option 2? or should I just go with something like option 1?

Thanks for writing a very useful middleware!

Any new releases?

Thanks for maintaining this package.

Any chance we can get a release tag for 2021? I'm trying to implement the PermissionsPolicy header but it is still called FeaturePolicy in v1.0.8.

Static SecureHeaderKey does not allow multiple instances

Becuase the context key:
https://github.com/unrolled/secure/blob/v1/secure.go#L30

Is static, it does not allow for multiple secure instances to act in series, as the second will overwrite the key from the first.

@unrolled, Do you have any qualms with me implementing an overrideable context key to allow chaining instances?

The issue we are encountering is we want to define an instance to configure just https redirection, and then another instance just to handle csp etc, and be more modular.

This doesn't work currently, and we would like to make it work.

SSLRedirect not working if only TLS is served

Hello there
i have a problem with SSLRedirect, the problem is that i only serve a TLS instance with
http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", n)
and no plain istance.

Visiting localhost:8443 it doesn't redirect me to https://localhost:8443
And in console i get
2017/10/18 17:27:13 http: TLS handshake error from [::1]:39118: tls: first record does not look like a TLS handshake

There is another solution instead of starting a plain instance?

Bad Host (Cloudflare)

Hello,

I am proxied behind Cloudflare. I Set SSLHost to a number of variations of "https://url.example.co.uk", "https://url.example.co.uk/", "url.example.co.uk", but I keep getting "bad host" at my staging environment.

I should note that my dev environment is working fine, but that's because I've set the IsDevelopment param to true.

I don't think I had this issue before proxying via CloudFlare, so now I am wondering whether that may have caused it. I have also passed all URLs of my project to "AllowedHosts", so technically that should work.

I am slightly lost and was wondering whether you may be able to offer some help. Thanks!

Add Ability to pass a custom AllowedHosts function that returns a list

Can we have an Option to pass a function that if set, assigns the allowedHosts list to the list returned by such a function?

ex.

in secure.go


// AllowedHostsFunc a custom function type that returns a list of strings used in place of AllowedHosts list
type AllowedHostsFunc func() []string

...

type Options struct {
  ...
 	AllowedHostsFunc AllowedHostsFunc
  ...
}

   ...
// Allowed hosts check.
	if s.opt.AllowedHostsFunc != nil {
		s.opt.AllowedHosts = s.opt.AllowedHostsFunc()
	}

	if len(s.opt.AllowedHosts) > 0 && !s.opt.IsDevelopment {
   ...

I wrote some tests and seems to satisfy what I need, which is dynamically fetching cached hosts list

Can't get $NONCE to work properly

I'm currently trying to implement the new (and awesome) dynamic CSP nonce feature to work, but I think I'm doing something wrong.

I created a secure.Options struct with the following params:
secureMiddlewareOptions := secure.Options{ ContentSecurityPolicy: "script-src $NONCE", }

I then add the created middleware to my main negroni route:
secureMiddleware := secure.New(secureMiddlewareOptions) n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext))

The Content-Security-Policy header is added correctly, and the $NONCE is replaced. But instead of replacing it with a random CSP "string" nothing is added. The result looks like this:
Content-Security-Policy:script-src 'nonce-'.

Did I overlook something? Thanks for your help.

500 error when redirecting from http to https on HEAD requests

Using this code to set up our secure:
securer := secure.Secure(secure.Options{
SSLRedirect: strings.ToLower(os.Getenv("FORCE_SSL")) == "true",
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
STSSeconds: 315360000,
STSIncludeSubdomains: true,
FrameDeny: true,
ContentTypeNosniff: true,
BrowserXssFilter: true,
})

Always getting 500 errors on HEAD requests to http://[website] when it tries to redirect to https. Is this a known issue? Is there some configuration to get around this? Thanks!

HSTS seconds in docs is 10 years?

I noticed that in the docs, the value of HSTS is 315360000 seconds which equals to 10 years. In most implementations that I have seen it's just 31536000 which is 1 year. Is this a typo? I can do a quick PR for a fix if needed.

Unexported `processRequest` does not allow modification of the request before next

Hello,

Here is the issue I am encountering:

We have a request that is passed to secure that has been modified by other middleware. The path has been modified, and therefore when passed to secure, the incorrect response is generated.

The solution as far as I see it, is to "unmodify" the path, pass the request to secure, then "remodify" the path after secure has processed the request, but before it passes to next. The issue I am encountering with secure is that processRequest is not exported, and therefore cannot be used by my package.

I am essentially trying to write my own HandlerFuncForRequestOnly (https://github.com/unrolled/secure/blob/v1/secure.go#L183).
Do you think that processRequest could be exported?

Or do you think that we could have a mirrored ProcessNoModifyRequest similar to Process that returns the responseHeaders? something like this:

// ProcessNoModifyRequest runs the actual checks but does not write the headers in the ResponseWriter.
func (s *Secure) ProcessNoModifyRequest(w http.ResponseWriter, r *http.Request) (http.Header, error) {
	return s.processRequest(w, r)
}

Thoughts?

How to redirect from HTTP to HTTPS with CSP set?

Hi, I am seeking to redirect from HTTP to HTTPS, usually the browser may complain that mix-content after redirecting since the original page contains some static http link. Then I saw "Content-Security-Policy: upgrade-insecure-requests" could help from this article.

From the example in this README, I saw it could do the redirection and also there is CSP option, but when I try it out, it can work with redirection but there is no CSP option seen in the http header, what is wrong?

Thanks

Unnecessary redirect in SSL

When SSL is enabled the Location response header is not replaced to HTTPS, causing an unnecessary redirect.

Allow customization of the X-XSS-Protection header

The following are valid values for the X-XSS-Protection header:

X-XSS-Protection: 0
X-XSS-Protection: 1
X-XSS-Protection: 1; mode=block
X-XSS-Protection: 1; report=<reporting-uri>

Setting BrowserXssFilter to true gives the header the value 1; mode=block, but does not allow for setting it as 1 or 1; report=<reporting-uri>.

It would be nice if there is the possibility of setting it to these values: 1 or 1; report=<reporting-uri>.

Dynamic CSP Nonce Support

Hi

Great work. Thanks for this awesome middleware.

Can I send a PR for adding dynamic CSP nonce?

Proposed Implementation would extend the current solution without breaking anything

Now
ContentSecurityPolicy: "script-src 'self'"

Proposed Solution

ContentSecurityPolicy: "script-src 'self' {{ . }}"

Will use Go's template/text package to change this to to a fmt string i.e. script-src 'self' 'nonce-%s' then use this to send headers on every request with a unique nonce for each request.

Add a new Nonce(r *http.Request) function globally to get the nonce for the present request which can be later used to add nonce to scripts like,

<script nonce="2726c7f26c"> var inline = 1; </script>

There can also a nonce length property.

`HPKP` & `Expect-CT` are deprecated.

HPKP was deprecated in 2018.

HPKP was to be replaced by the reactive Certificate Transparency framework coupled with the Expect-CT header but as of today, the Expect-CT header is obsolete.

Chrome requires Certificate Transparency for all publicly trusted certificates issued after April 30, 2018. View ref

Support for Echo 3

	secureMiddleware := secure.New(secure.Options{
		FrameDeny: true,
	})

	e := echo.New()
	e.Use(secureMiddleware.Handler)
cannot use secureMiddleware.Handler (type func(http.Handler) http.Handler) as type echo.MiddlewareFunc in argument to e.Use

use for microservices facing public

Hello,

Not entirely an issues, but rather a question of use. Could I use this library to strengthen security of access for a publicly facing REST API microservice?

Also, once implemented, is there is a way to validate options manually that they are enabled and properly functioning?

Regards,
Max

ModifyResponseHeader rewrites response headers indiscriminately

The commit 624f918

Avoids an extra redirect by modifying the scheme on the location response header.

However, it does not check that the location referred to in the header is SSLHost.

In effect, it rewrites all location responses to https, even if the proxy implementing unrolled/secure is not handling the domain.

It prevents redirecting to third party http URLs.

The modification should also not rewrite the scheme if there is a port defined in the response header.

Related issue: traefik/traefik#5807

PR Incoming

HSTS Warnings

Forcing HTTPS on all subdomains for 10 years is a dangerous to show on the first example. There should probably be some kind of warning about HSTS - that once you add them and user's browsers accept them, they can't be removed. If this Go server is handling all subdomains, then it'll probably be fine, but many people will have CNAMEs pointing elsewhere for various hosted services, etc.

Add support for Expect-CT security header

Please add support for the Expect-CT header. This header allows site admins to get reports from browsers if a received certificated doesn't contain valid Certificate Transparency information. Since CT is now required by all modern browsers this can help admins detect some misconfigurations.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expect-CT
https://scotthelme.co.uk/a-new-security-header-expect-ct/

The header is already checked (but not scored) by securityheaders.io.

Seeking information about redirecting HTTP to HTTPS

Hi, I used your redirecting example and I am interested in knowing if it is SAFE to add more headers to secureMiddleware of your example or not? I am very new to security in Go. The thing is that your approach shows that we create one secureMiddleware and pass it to ListenAndServe go routine as well as ListenAndServeTLS.

What if, I do the same thing but add more header to that secureMiddleware? Is this a possibility that hackers somehow get to understand that we are redirected from http to https and therefore we can get into the http version of the server (because I am passing the main gorilla router to ListenAndServe). Does something like this happen?

And what about future links we visit on the site after first redirection? ListenAndServe was used only once when we typed url without https (I am on development right now). I still want to confirm as I am not sure.

Below is my current main function for your reference:

func main() {

	// HTTPS certificate files
	certPath := "server.pem"
	keyPath := "server.key"

	// secure middleware
	secureMiddleware := secure.New(secure.Options{
		AllowedHosts:         []string{"localhost"},
		HostsProxyHeaders:    []string{"X-Forwarded-Host"},
		SSLRedirect:          true,
		SSLHost:              "localhost:443",
		SSLProxyHeaders:      map[string]string{"X-Forwarded-Proto": "https"},
		STSSeconds:           63072000,
		STSIncludeSubdomains: true,
		STSPreload:           true,
		ForceSTSHeader:       false,
		FrameDeny:            true,
		ContentTypeNosniff:   true,
		BrowserXssFilter:     true,
		// I need to change it as Content-Security-Policy: default-src 'self' *.trusted.com if I want to load images from S3 bucket (See - https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
		// ContentSecurityPolicy: "default-src 'self'",
		PublicKey:      `pin-sha256="base64+primary=="; pin-sha256="base64+backup=="; max-age=5184000; includeSubdomains; report-uri="https://www.example.com/hpkp-report"`,
		ReferrerPolicy: "same-origin",
		// IsDevelopment:         true,
	})

	// Setting up logging files in append mode
	common.SetupLogging()
	common.Log.Info("On line 35 certPath and keyPath")

	// Setting up mongodb
	mongodb, err := datastore.NewDatastore(datastore.MONGODB, "localhost:27017")
	if err != nil {
		common.Log.Warn(err.Error())
	}
	defer mongodb.Close()

	// Passing mongodb to environment variable
	env := common.Env{DB: mongodb}
	common.Log.Info("On line 44")

	// Router and routes
	r := mux.NewRouter()
	r.Handle("/", handlers.Handler{E: &env, H: handlers.Index}).Methods("GET")

	// Middleware and server
	commonMiddleware := handlers.RecoveryHandler(handlers.PrintRecoveryStack(true))(gh.CombinedLoggingHandler(common.TrafficLog, secureMiddleware.Handler(r)))
	common.Log.Info("On line 49")

	sTLS := &http.Server{
		Addr:           ":443",
		Handler:        commonMiddleware,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	common.Log.Info("Serving...")

	go func() {
		log.Fatal(http.ListenAndServe(":80", commonMiddleware))
	}()

	log.Fatal(sTLS.ListenAndServeTLS(certPath, keyPath))
}

Or, should we have one secureMiddleware and one redirectMiddleware; the redirectMiddleware will be exactly like the one in your HTTP to HTTPS redirection example in readme. And, pass this redirectMiddleware to ListenAndServe with the main router (in my case r).

Please clarify. And, if we can use same secureMiddleware then I would prefer we add comments stating something like "// you can have more headers here" in the secureMiddleware of redirection example.

不能用443端口吗?

我把gin代码示例里的端口改成443端口,然后访问不了,说找不到网页。

Add a Content Security Policy builder

Content Security policies can be a long and complex string. Is it worth creating a simple function/struct/builder to make constructing these easier, and in a less error prone way? Something like:

secure.Options{
  ContentSecurityPolicy: secure.ContentSecurityPolicy{
    DefaultSrc: ["self"],
    ScriptSrc: ["self", "www.google-analytics.com"]
  }
}

AllowedHost check wildcard for subdomains

In my opinion, the if clause for the host check should rather be implemented with a regular expression, since e.g. wildcards are often used to allow subdomains.

What's your point of view on this issue? Should I open a pull request?

Propose logo

Hello, am a graphic designer. Will you be interested in me contributing a logo to your repo project? I would make it for you free, that's if you are interested.

Gin accessing CSP nonce

Hello, I am trying to access the generated NONCE using Gin:

nonce := secure.CSPNonce(c.Request.Context())

This always returns an empty string, even tho the nonce appears on the request headers, digging the code I see the nonce beeing added to the request context (I am using the example on the README), but I cant seem to get it properly, here is a more complete example:


func Home(c *gin.Context) {
	c.HTML(http.StatusOK, "home.html", gin.H{
		"nonce":   secure.CSPNonce(c.Request.Context()),
	})
}
func secureFunc(config *app.Config) gin.HandlerFunc {
	// Create secure middleware
	secureMiddleware := secure.New(secure.Options{
		FrameDeny:            true,
		BrowserXssFilter:     true,
		ReferrerPolicy:       "no-referrer",
		ContentTypeNosniff:   true,
		AllowedHostsAreRegex: false,
		SSLRedirect:          !config.DebugMode,
		SSLTemporaryRedirect: false,
		STSSeconds:           31536000,
		ContentSecurityPolicy: fmt.Sprintf(
			"script-src %s",
			"'self' $NONCE",
		),
		IsDevelopment: config.DebugMode,
	})

	return func(c *gin.Context) {
		if err := secureMiddleware.Process(c.Writer, c.Request); err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}

		// Avoid header rewrite if response is a redirection
		if status := c.Writer.Status(); status > 300 && status < 399 {
			c.Abort()
		}
	}
}

Clearly the nonceEnabled should be true (https://github.com/unrolled/secure/blob/v1/secure.go#L248) but the value is not there, I am missing something?

Any ideas?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.