Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

SameSite option #123

Merged
merged 4 commits into from
Oct 8, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions csrf.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,22 @@ var (
ErrBadToken = errors.New("CSRF token invalid")
)

// SameSiteMode allows a server to define a cookie attribute making it impossible for
// the browser to send this cookie along with cross-site requests. The main
// goal is to mitigate the risk of cross-origin information leakage, and provide
// some protection against cross-site request forgery attacks.
//
// See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details.
type SameSiteMode int

// SameSite options
const (
SameSiteDefaultMode SameSiteMode = iota + 1
SameSiteLaxMode
SameSiteStrictMode
SameSiteNoneMode
)

type csrf struct {
h http.Handler
sc *securecookie.SecureCookie
Expand All @@ -68,6 +84,7 @@ type options struct {
// http.Cookie field instead of the "correct" HTTPOnly name that golint suggests.
HttpOnly bool
Secure bool
SameSite SameSiteMode
RequestHeader string
FieldName string
ErrorHandler http.Handler
Expand Down Expand Up @@ -166,6 +183,7 @@ func Protect(authKey []byte, opts ...Option) func(http.Handler) http.Handler {
maxAge: cs.opts.MaxAge,
secure: cs.opts.Secure,
httpOnly: cs.opts.HttpOnly,
sameSite: cs.opts.SameSite,
path: cs.opts.Path,
domain: cs.opts.Domain,
sc: cs.sc,
Expand Down
15 changes: 15 additions & 0 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ func HttpOnly(h bool) Option {
}
}

// SameSite sets the cookie SameSite attribute. Defaults to blank to maintain backwards
// compatibility, however, Strict is recommended. This option is only available for go 1.11+.
//
// This instructs clients to only respond with cookie for that path and its
// subpaths - i.e. a cookie issued from "/register" would be included in requests
// to "/register/step2" and "/register/submit".
func SameSite(s SameSiteMode) Option {
return func(cs *csrf) {
cs.opts.SameSite = s
}
}

// ErrorHandler allows you to change the handler called when CSRF request
// processing encounters an invalid token or request. A typical use would be to
// provide a handler that returns a static HTML file with a HTTP 403 status. By
Expand Down Expand Up @@ -132,6 +144,9 @@ func parseOptions(h http.Handler, opts ...Option) *csrf {
cs.opts.Secure = true
cs.opts.HttpOnly = true

// Default to blank to maintain backwards compatibility
cs.opts.SameSite = SameSiteDefaultMode

// Default; only override this if the package user explicitly calls MaxAge(0)
cs.opts.MaxAge = defaultAge

Expand Down
5 changes: 5 additions & 0 deletions options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func TestOptions(t *testing.T) {
Path(path),
HttpOnly(false),
Secure(false),
SameSite(SameSiteStrictMode),
RequestHeader(header),
FieldName(field),
ErrorHandler(http.HandlerFunc(errorHandler)),
Expand Down Expand Up @@ -53,6 +54,10 @@ func TestOptions(t *testing.T) {
t.Errorf("Secure not set correctly: got %v want %v", cs.opts.Secure, false)
}

if cs.opts.SameSite != SameSiteStrictMode {
t.Errorf("SameSite not set correctly: got %v want %v", cs.opts.SameSite, SameSiteStrictMode)
}

if cs.opts.RequestHeader != header {
t.Errorf("RequestHeader not set correctly: got %v want %v", cs.opts.RequestHeader, header)
}
Expand Down
4 changes: 4 additions & 0 deletions store.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// +build go1.11

package csrf

import (
Expand Down Expand Up @@ -28,6 +30,7 @@ type cookieStore struct {
path string
domain string
sc *securecookie.SecureCookie
sameSite SameSiteMode
}

// Get retrieves a CSRF token from the session cookie. It returns an empty token
Expand Down Expand Up @@ -63,6 +66,7 @@ func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error {
MaxAge: cs.maxAge,
HttpOnly: cs.httpOnly,
Secure: cs.secure,
SameSite: http.SameSite(cs.sameSite),
Path: cs.path,
Domain: cs.domain,
}
Expand Down
86 changes: 86 additions & 0 deletions store_deprecated.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// +build !go1.11
// file for compatibility with go versions prior to 1.11

package csrf

import (
"net/http"
"time"

"github.com/gorilla/securecookie"
)

// store represents the session storage used for CSRF tokens.
type store interface {
// Get returns the real CSRF token from the store.
Get(*http.Request) ([]byte, error)
// Save stores the real CSRF token in the store and writes a
// cookie to the http.ResponseWriter.
// For non-cookie stores, the cookie should contain a unique (256 bit) ID
// or key that references the token in the backend store.
// csrf.GenerateRandomBytes is a helper function for generating secure IDs.
Save(token []byte, w http.ResponseWriter) error
}

// cookieStore is a signed cookie session store for CSRF tokens.
type cookieStore struct {
name string
maxAge int
secure bool
httpOnly bool
path string
domain string
sc *securecookie.SecureCookie
sameSite SameSiteMode
}

// Get retrieves a CSRF token from the session cookie. It returns an empty token
// if decoding fails (e.g. HMAC validation fails or the named cookie doesn't exist).
func (cs *cookieStore) Get(r *http.Request) ([]byte, error) {
// Retrieve the cookie from the request
cookie, err := r.Cookie(cs.name)
if err != nil {
return nil, err
}

token := make([]byte, tokenLength)
// Decode the HMAC authenticated cookie.
err = cs.sc.Decode(cs.name, cookie.Value, &token)
if err != nil {
return nil, err
}

return token, nil
}

// Save stores the CSRF token in the session cookie.
func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error {
// Generate an encoded cookie value with the CSRF token.
encoded, err := cs.sc.Encode(cs.name, token)
if err != nil {
return err
}

cookie := &http.Cookie{
Name: cs.name,
Value: encoded,
MaxAge: cs.maxAge,
HttpOnly: cs.httpOnly,
Secure: cs.secure,
Path: cs.path,
Domain: cs.domain,
}

// Set the Expires field on the cookie based on the MaxAge
// If MaxAge <= 0, we don't set the Expires attribute, making the cookie
// session-only.
if cs.maxAge > 0 {
cookie.Expires = time.Now().Add(
time.Duration(cs.maxAge) * time.Second)
}

// Write the authenticated cookie to the response.
http.SetCookie(w, cookie)

return nil
}
4 changes: 2 additions & 2 deletions store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func TestCookieDecode(t *testing.T) {
// Test with a nil hash key
sc := securecookie.New(nil, nil)
sc.MaxAge(age)
st := &cookieStore{cookieName, age, true, true, "", "", sc}
st := &cookieStore{cookieName, age, true, true, "", "", sc, SameSiteDefaultMode}

// Set a fake cookie value so r.Cookie passes.
r.Header.Set("Cookie", fmt.Sprintf("%s=%s", cookieName, "notacookie"))
Expand All @@ -86,7 +86,7 @@ func TestCookieEncode(t *testing.T) {
// Test with a nil hash key
sc := securecookie.New(nil, nil)
sc.MaxAge(age)
st := &cookieStore{cookieName, age, true, true, "", "", sc}
st := &cookieStore{cookieName, age, true, true, "", "", sc, SameSiteDefaultMode}

rr := httptest.NewRecorder()

Expand Down