csrf

package module
v1.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 10, 2021 License: BSD-3-Clause Imports: 12 Imported by: 4

README

gorilla/csrf

GoDoc Sourcegraph Reviewed by Hound CircleCI

gorilla/csrf is a HTTP middleware library that provides cross-site request forgery (CSRF) protection. It includes:

  • The csrf.Protect middleware/handler provides CSRF protection on routes attached to a router or a sub-router.
  • A csrf.Token function that provides the token to pass into your response, whether that be a HTML form or a JSON response body.
  • ... and a csrf.TemplateField helper that you can pass into your html/template templates to replace a {{ .csrfField }} template tag with a hidden input field.

gorilla/csrf is designed to work with any Go web framework, including:

gorilla/csrf is also compatible with middleware 'helper' libraries like Alice and Negroni.

Contents

Install

With a properly configured Go toolchain:

go get github.com/gorilla/csrf

Examples

gorilla/csrf is easy to use: add the middleware to your router with the below:

CSRF := csrf.Protect([]byte("32-byte-long-auth-key"))
http.ListenAndServe(":8000", CSRF(r))

...and then collect the token with csrf.Token(r) in your handlers before passing it to the template, JSON body or HTTP header (see below).

Note that the authentication key passed to csrf.Protect([]byte(key)) should be 32-bytes long and persist across application restarts. Generating a random key won't allow you to authenticate existing cookies and will break your CSRF validation.

gorilla/csrf inspects the HTTP headers (first) and form body (second) on subsequent POST/PUT/PATCH/DELETE/etc. requests for the token.

HTML Forms

Here's the common use-case: HTML forms you want to provide CSRF protection for, in order to protect malicious POST requests being made:

package main

import (
    "net/http"

    "github.com/gorilla/csrf"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/signup", ShowSignupForm)
    // All POST requests without a valid token will return HTTP 403 Forbidden.
    // We should also ensure that our mutating (non-idempotent) handler only
    // matches on POST requests. We can check that here, at the router level, or
    // within the handler itself via r.Method.
    r.HandleFunc("/signup/post", SubmitSignupForm).Methods("POST")

    // Add the middleware to your router by wrapping it.
    http.ListenAndServe(":8000",
        csrf.Protect([]byte("32-byte-long-auth-key"))(r))
    // PS: Don't forget to pass csrf.Secure(false) if you're developing locally
    // over plain HTTP (just don't leave it on in production).
}

func ShowSignupForm(w http.ResponseWriter, r *http.Request) {
    // signup_form.tmpl just needs a {{ .csrfField }} template tag for
    // csrf.TemplateField to inject the CSRF token into. Easy!
    t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{
        csrf.TemplateTag: csrf.TemplateField(r),
    })
    // We could also retrieve the token directly from csrf.Token(r) and
    // set it in the request header - w.Header.Set("X-CSRF-Token", token)
    // This is useful if you're sending JSON to clients or a front-end JavaScript
    // framework.
}

func SubmitSignupForm(w http.ResponseWriter, r *http.Request) {
    // We can trust that requests making it this far have satisfied
    // our CSRF protection requirements.
}

Note that the CSRF middleware will (by necessity) consume the request body if the token is passed via POST form values. If you need to consume this in your handler, insert your own middleware earlier in the chain to capture the request body.

JavaScript Applications

This approach is useful if you're using a front-end JavaScript framework like React, Ember or Angular, and are providing a JSON API. Specifically, we need to provide a way for our front-end fetch/AJAX calls to pass the token on each fetch (AJAX/XMLHttpRequest) request. We achieve this by:

  • Parsing the token from the <input> field generated by the csrf.TemplateField(r) helper, or passing it back in a response header.
  • Sending this token back on every request
  • Ensuring our cookie is attached to the request so that the form/header value can be compared to the cookie value.

We'll also look at applying selective CSRF protection using gorilla/mux's sub-routers, as we don't handle any POST/PUT/DELETE requests with our top-level router.

package main

import (
    "github.com/gorilla/csrf"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()
    csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"))

    api := r.PathPrefix("/api").Subrouter()
    api.Use(csrfMiddleware)
    api.HandleFunc("/user/{id}", GetUser).Methods("GET")

    http.ListenAndServe(":8000", r)
}

func GetUser(w http.ResponseWriter, r *http.Request) {
    // Authenticate the request, get the id from the route params,
    // and fetch the user from the DB, etc.

    // Get the token and pass it in the CSRF header. Our JSON-speaking client
    // or JavaScript framework can now read the header and return the token in
    // in its own "X-CSRF-Token" request header on the subsequent POST.
    w.Header().Set("X-CSRF-Token", csrf.Token(r))
    b, err := json.Marshal(user)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    w.Write(b)
}

In our JavaScript application, we should read the token from the response headers and pass it in a request header for all requests. Here's what that looks like when using Axios, a popular JavaScript HTTP client library:

// You can alternatively parse the response header for the X-CSRF-Token, and
// store that instead, if you followed the steps above to write the token to a
// response header.
let csrfToken = document.getElementsByName("gorilla.csrf.Token")[0].value

// via https://github.com/axios/axios#creating-an-instance
const instance = axios.create({
  baseURL: "https://example.com/api/",
  timeout: 1000,
  headers: { "X-CSRF-Token": csrfToken }
})

// Now, any HTTP request you make will include the csrfToken from the page,
// provided you update the csrfToken variable for each render.
try {
  let resp = await instance.post(endpoint, formData)
  // Do something with resp
} catch (err) {
  // Handle the exception
}

If you plan to host your JavaScript application on another domain, you can use the Trusted Origins feature to allow the host of your JavaScript application to make requests to your Go application. Observe the example below:

package main

import (
    "github.com/gorilla/csrf"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()
    csrfMiddleware := csrf.Protect([]byte("32-byte-long-auth-key"), csrf.TrustedOrigins([]string{"ui.domain.com"}))

    api := r.PathPrefix("/api").Subrouter()
    api.Use(csrfMiddleware)
    api.HandleFunc("/user/{id}", GetUser).Methods("GET")

    http.ListenAndServe(":8000", r)
}

func GetUser(w http.ResponseWriter, r *http.Request) {
    // Authenticate the request, get the id from the route params,
    // and fetch the user from the DB, etc.

    // Get the token and pass it in the CSRF header. Our JSON-speaking client
    // or JavaScript framework can now read the header and return the token in
    // in its own "X-CSRF-Token" request header on the subsequent POST.
    w.Header().Set("X-CSRF-Token", csrf.Token(r))
    b, err := json.Marshal(user)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    w.Write(b)
}

On the example above, you're authorizing requests from ui.domain.com to make valid CSRF requests to your application, so you can have your API server on another domain without problems.

Google App Engine

If you're using Google App Engine, (first-generation) which doesn't allow you to hook into the default http.ServeMux directly, you can still use gorilla/csrf (and gorilla/mux):

package app

// Remember: appengine has its own package main
func init() {
    r := mux.NewRouter()
    r.HandleFunc("/", IndexHandler)
    // ...

    // We pass our CSRF-protected router to the DefaultServeMux
    http.Handle("/", csrf.Protect([]byte(your-key))(r))
}

Note: You can ignore this if you're using the second-generation Go runtime on App Engine (Go 1.11 and above).

Setting SameSite

Go 1.11 introduced the option to set the SameSite attribute in cookies. This is valuable if a developer wants to instruct a browser to not include cookies during a cross site request. SameSiteStrictMode prevents all cross site requests from including the cookie. SameSiteLaxMode prevents CSRF prone requests (POST) from including the cookie but allows the cookie to be included in GET requests to support external linking.

func main() {
    CSRF := csrf.Protect(
      []byte("a-32-byte-long-key-goes-here"),
      // instruct the browser to never send cookies during cross site requests
      csrf.SameSite(csrf.SameSiteStrictMode),
    )

    r := mux.NewRouter()
    r.HandleFunc("/signup", GetSignupForm)
    r.HandleFunc("/signup/post", PostSignupForm)

    http.ListenAndServe(":8000", CSRF(r))
}
Setting Options

What about providing your own error handler and changing the HTTP header the package inspects on requests? (i.e. an existing API you're porting to Go). Well, gorilla/csrf provides options for changing these as you see fit:

func main() {
    CSRF := csrf.Protect(
            []byte("a-32-byte-long-key-goes-here"),
            csrf.RequestHeader("Authenticity-Token"),
            csrf.FieldName("authenticity_token"),
            csrf.ErrorHandler(http.HandlerFunc(serverError(403))),
    )

    r := mux.NewRouter()
    r.HandleFunc("/signup", GetSignupForm)
    r.HandleFunc("/signup/post", PostSignupForm)

    http.ListenAndServe(":8000", CSRF(r))
}

Not too bad, right?

If there's something you're confused about or a feature you would like to see added, open an issue.

Design Notes

Getting CSRF protection right is important, so here's some background:

  • This library generates unique-per-request (masked) tokens as a mitigation against the BREACH attack.
  • The 'base' (unmasked) token is stored in the session, which means that multiple browser tabs won't cause a user problems as their per-request token is compared with the base token.
  • Operates on a "whitelist only" approach where safe (non-mutating) HTTP methods (GET, HEAD, OPTIONS, TRACE) are the only methods where token validation is not enforced.
  • The design is based on the battle-tested Django and Ruby on Rails approaches.
  • Cookies are authenticated and based on the securecookie library. They're also Secure (issued over HTTPS only) and are HttpOnly by default, because sane defaults are important.
  • Cookie SameSite attribute (prevents cookies from being sent by a browser during cross site requests) are not set by default to maintain backwards compatibility for legacy systems. The SameSite attribute can be set with the SameSite option.
  • Go's crypto/rand library is used to generate the 32 byte (256 bit) tokens and the one-time-pad used for masking them.

This library does not seek to be adventurous.

License

BSD licensed. See the LICENSE file for details.

Documentation

Overview

Package csrf (gorilla/csrf) provides Cross Site Request Forgery (CSRF) prevention middleware for Go web applications & services.

It includes:

* The `csrf.Protect` middleware/handler provides CSRF protection on routes attached to a router or a sub-router.

* A `csrf.Token` function that provides the token to pass into your response, whether that be a HTML form or a JSON response body.

* ... and a `csrf.TemplateField` helper that you can pass into your `html/template` templates to replace a `{{ .csrfField }}` template tag with a hidden input field.

gorilla/csrf is easy to use: add the middleware to individual handlers with the below:

CSRF := csrf.Protect([]byte("32-byte-long-auth-key"))
http.HandlerFunc("/route", CSRF(YourHandler))

... and then collect the token with `csrf.Token(r)` before passing it to the template, JSON body or HTTP header (you pick!). gorilla/csrf inspects the form body (first) and HTTP headers (second) on subsequent POST/PUT/PATCH/DELETE/etc. requests for the token.

Note that the authentication key passed to `csrf.Protect([]byte(key))` should be 32-bytes long and persist across application restarts. Generating a random key won't allow you to authenticate existing cookies and will break your CSRF validation.

Here's the common use-case: HTML forms you want to provide CSRF protection for, in order to protect malicious POST requests being made:

package main

import (
	"fmt"
	"html/template"
	"net/http"

	"github.com/gorilla/csrf"
	"github.com/gorilla/mux"
)

var form = `
<html>
<head>
<title>Sign Up!</title>
</head>
<body>
<form method="POST" action="/signup/post" accept-charset="UTF-8">
<input type="text" name="name">
<input type="text" name="email">
<!--
The default template tag used by the CSRF middleware .
This will be replaced with a hidden <input> field containing the
masked CSRF token.
-->
{{ .csrfField }}
<input type="submit" value="Sign up!">
</form>
</body>
</html>
`

var t = template.Must(template.New("signup_form.tmpl").Parse(form))

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/signup", ShowSignupForm)
	// All POST requests without a valid token will return HTTP 403 Forbidden.
	// We should also ensure that our mutating (non-idempotent) handler only
	// matches on POST requests. We can check that here, at the router level, or
	// within the handler itself via r.Method.
	r.HandleFunc("/signup/post", SubmitSignupForm).Methods("POST")

	// Add the middleware to your router by wrapping it.
	http.ListenAndServe(":8000",
	csrf.Protect([]byte("32-byte-long-auth-key"))(r))
	// PS: Don't forget to pass csrf.Secure(false) if you're developing locally
	// over plain HTTP (just don't leave it on in production).
}

func ShowSignupForm(w http.ResponseWriter, r *http.Request) {
	// signup_form.tmpl just needs a {{ .csrfField }} template tag for
	// csrf.TemplateField to inject the CSRF token into. Easy!
	t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{
		csrf.TemplateTag: csrf.TemplateField(r),
	})
}

func SubmitSignupForm(w http.ResponseWriter, r *http.Request) {
	// We can trust that requests making it this far have satisfied
	// our CSRF protection requirements.
	fmt.Fprintf(w, "%v\n", r.PostForm)
}

Note that the CSRF middleware will (by necessity) consume the request body if the token is passed via POST form values. If you need to consume this in your handler, insert your own middleware earlier in the chain to capture the request body.

You can also send the CSRF token in the response header. This approach is useful if you're using a front-end JavaScript framework like Ember or Angular, or are providing a JSON API:

package main

import (
	"github.com/gorilla/csrf"
	"github.com/gorilla/mux"
)

func main() {
	r := mux.NewRouter()

	api := r.PathPrefix("/api").Subrouter()
	api.HandleFunc("/user/:id", GetUser).Methods("GET")

	http.ListenAndServe(":8000",
	csrf.Protect([]byte("32-byte-long-auth-key"))(r))
}

func GetUser(w http.ResponseWriter, r *http.Request) {
	// Authenticate the request, get the id from the route params,
	// and fetch the user from the DB, etc.

	// Get the token and pass it in the CSRF header. Our JSON-speaking client
	// or JavaScript framework can now read the header and return the token in
	// in its own "X-CSRF-Token" request header on the subsequent POST.
	w.Header().Set("X-CSRF-Token", csrf.Token(r))
	b, err := json.Marshal(user)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}

	w.Write(b)
}

If you're writing a client that's supposed to mimic browser behavior, make sure to send back the CSRF cookie (the default name is _gorilla_csrf, but this can be changed with the CookieName Option) along with either the X-CSRF-Token header or the gorilla.csrf.Token form field.

In addition: getting CSRF protection right is important, so here's some background:

* This library generates unique-per-request (masked) tokens as a mitigation against the BREACH attack (http://breachattack.com/).

* The 'base' (unmasked) token is stored in the session, which means that multiple browser tabs won't cause a user problems as their per-request token is compared with the base token.

* Operates on a "whitelist only" approach where safe (non-mutating) HTTP methods (GET, HEAD, OPTIONS, TRACE) are the *only* methods where token validation is not enforced.

* The design is based on the battle-tested Django (https://docs.djangoproject.com/en/1.8/ref/csrf/) and Ruby on Rails (http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html) approaches.

* Cookies are authenticated and based on the securecookie (https://github.com/gorilla/securecookie) library. They're also Secure (issued over HTTPS only) and are HttpOnly by default, because sane defaults are important.

* Go's `crypto/rand` library is used to generate the 32 byte (256 bit) tokens and the one-time-pad used for masking them.

This library does not seek to be adventurous.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoReferer is returned when a HTTPS request provides an empty Referer
	// header.
	ErrNoReferer = errors.New("referer not supplied")
	// ErrBadReferer is returned when the scheme & host in the URL do not match
	// the supplied Referer header.
	ErrBadReferer = errors.New("referer invalid")
	// ErrNoToken is returned if no CSRF token is supplied in the request.
	ErrNoToken = errors.New("CSRF token not found in request")
	// ErrBadToken is returned if the CSRF token in the request does not match
	// the token in the session, or is otherwise malformed.
	ErrBadToken = errors.New("CSRF token invalid")
)
View Source
var TemplateTag = "csrfField"

TemplateTag provides a default template tag - e.g. {{ .csrfField }} - for use with the TemplateField function.

Functions

func FailureReason

func FailureReason(r *http.Request) error

FailureReason makes CSRF validation errors available in the request context. This is useful when you want to log the cause of the error or report it to client.

func Protect

func Protect(authKey []byte, opts ...Option) func(http.Handler) http.Handler

Protect is HTTP middleware that provides Cross-Site Request Forgery protection.

It securely generates a masked (unique-per-request) token that can be embedded in the HTTP response (e.g. form field or HTTP header). The original (unmasked) token is stored in the session, which is inaccessible by an attacker (provided you are using HTTPS). Subsequent requests are expected to include this token, which is compared against the session token. Requests that do not provide a matching token are served with a HTTP 403 'Forbidden' error response.

Example:

package main

import (
	"html/template"

	"github.com/gorilla/csrf"
	"github.com/gorilla/mux"
)

var t = template.Must(template.New("signup_form.tmpl").Parse(form))

func main() {
	r := mux.NewRouter()

	r.HandleFunc("/signup", GetSignupForm)
	// POST requests without a valid token will return a HTTP 403 Forbidden.
	r.HandleFunc("/signup/post", PostSignupForm)

	// Add the middleware to your router.
	http.ListenAndServe(":8000",
	// Note that the authentication key provided should be 32 bytes
	// long and persist across application restarts.
		  csrf.Protect([]byte("32-byte-long-auth-key"))(r))
}

func GetSignupForm(w http.ResponseWriter, r *http.Request) {
	// signup_form.tmpl just needs a {{ .csrfField }} template tag for
	// csrf.TemplateField to inject the CSRF token into. Easy!
	t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{
		csrf.TemplateTag: csrf.TemplateField(r),
	})
	// We could also retrieve the token directly from csrf.Token(r) and
	// set it in the request header - w.Header.Set("X-CSRF-Token", token)
	// This is useful if you're sending JSON to clients or a front-end JavaScript
	// framework.
}

func TemplateField

func TemplateField(r *http.Request) template.HTML

TemplateField is a template helper for html/template that provides an <input> field populated with a CSRF token.

Example:

// The following tag in our form.tmpl template:
{{ .csrfField }}

// ... becomes:
<input type="hidden" name="gorilla.csrf.Token" value="<token>">

func Token

func Token(r *http.Request) string

Token returns a masked CSRF token ready for passing into HTML template or a JSON response body. An empty token will be returned if the middleware has not been applied (which will fail subsequent validation).

func UnsafeSkipCheck added in v1.7.0

func UnsafeSkipCheck(r *http.Request) *http.Request

UnsafeSkipCheck will skip the CSRF check for any requests. This must be called before the CSRF middleware.

Note: You should not set this without otherwise securing the request from CSRF attacks. The primary use-case for this function is to turn off CSRF checks for non-browser clients using authorization tokens against your API.

Types

type Option added in v1.7.0

type Option func(*csrf)

Option describes a functional option for configuring the CSRF handler.

func CookieName added in v1.0.2

func CookieName(name string) Option

CookieName changes the name of the CSRF cookie issued to clients.

Note that cookie names should not contain whitespace, commas, semicolons, backslashes or control characters as per RFC6265.

func Domain

func Domain(domain string) Option

Domain sets the cookie domain. Defaults to the current domain of the request only (recommended).

This should be a hostname and not a URL. If set, the domain is treated as being prefixed with a '.' - e.g. "example.com" becomes ".example.com" and matches "www.example.com" and "secure.example.com".

func ErrorHandler

func ErrorHandler(h http.Handler) Option

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 default a HTTP 403 status and a plain text CSRF failure reason are served.

Note that a custom error handler can also access the csrf.FailureReason(r) function to retrieve the CSRF validation reason from the request context.

func FieldName

func FieldName(name string) Option

FieldName allows you to change the name attribute of the hidden <input> field inspected by this package. The default is 'gorilla.csrf.Token'.

func FormValueName added in v1.7.0

func FormValueName(name string) Option

FormValueName allows you to change the name attribute of the param form value The default is 'gorilla.csrf.Token'.

func HttpOnly

func HttpOnly(h bool) Option

HttpOnly sets the 'HttpOnly' flag on the cookie. Defaults to true (recommended).

func MaxAge

func MaxAge(age int) Option

MaxAge sets the maximum age (in seconds) of a CSRF token's underlying cookie. Defaults to 12 hours. Call csrf.MaxAge(0) to explicitly set session-only cookies.

func Path

func Path(p string) Option

Path sets the cookie path. Defaults to the path the cookie was issued from (recommended).

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 RequestHeader

func RequestHeader(header string) Option

RequestHeader allows you to change the request header the CSRF middleware inspects. The default is X-CSRF-Token.

func SameSite added in v1.7.0

func SameSite(s SameSiteMode) Option

SameSite sets the cookie SameSite attribute. Defaults to blank to maintain backwards compatibility, however, Strict is recommended.

SameSite(SameSiteStrictMode) will prevent the cookie from being sent by the browser to the target site in all cross-site browsing context, even when following a regular link (GET request).

SameSite(SameSiteLaxMode) provides a reasonable balance between security and usability for websites that want to maintain user's logged-in session after the user arrives from an external link. The session cookie would be allowed when following a regular link from an external website while blocking it in CSRF-prone request methods (e.g. POST).

This option is only available for go 1.11+.

func Secure

func Secure(s bool) Option

Secure sets the 'Secure' flag on the cookie. Defaults to true (recommended). Set this to 'false' in your development environment otherwise the cookie won't be sent over an insecure channel. Setting this via the presence of a 'DEV' environmental variable is a good way of making sure this won't make it to a production environment.

func TrustedOrigins added in v1.7.0

func TrustedOrigins(origins []string) Option

TrustedOrigins configures a set of origins (Referers) that are considered as trusted. This will allow cross-domain CSRF use-cases - e.g. where the front-end is served from a different domain than the API server - to correctly pass a CSRF check.

You should only provide origins you own or have full control over.

func UnsafePaths added in v1.7.0

func UnsafePaths(paths []string) Option

UnsafePaths configures a set of request paths that are considered as un-trusted despite their methods.

type SameSiteMode added in v1.7.0

type SameSiteMode int

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.

const (
	// SameSiteDefaultMode sets the `SameSite` cookie attribute, which is
	// invalid in some older browsers due to changes in the SameSite spec. These
	// browsers will not send the cookie to the server.
	// csrf uses SameSiteLaxMode (SameSite=Lax) as the default as of v1.7.0+
	SameSiteDefaultMode SameSiteMode = iota + 1
	SameSiteLaxMode
	SameSiteStrictMode
	SameSiteNoneMode
)

SameSite options

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL