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/goframework/gf/csrf" "github.com/goframework/gf/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. r.HandleFunc("/signup/post", SubmitSignupForm) // Add the middleware to your router by wrapping it. http.ListenAndServe(":8000", csrf.Protect([]byte("32-byte-long-auth-key"))(r)) } 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/goframework/gf/csrf" "github.com/goframework/gf/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) }
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
- Variables
- func CompareTokens(a, b []byte) bool
- func Contains(vals []string, s string) bool
- func EnvError(r *http.Request, err error)
- func FailureReason(r *http.Request) error
- func GenerateRandomBytes(n int) ([]byte, error)
- func Mask(realToken []byte, r *http.Request) string
- func SameOrigin(a, b *url.URL) bool
- func TemplateField(r *http.Request) template.HTML
- func Token(r *http.Request) string
- func Unmask(issued []byte) []byte
- type CsrfProtection
- type Option
Constants ¶
const ( TokenKey string = "csrf.Token" FormKey string = "csrf.Form" ErrorKey string = "csrf.Error" CookieName string = "_csrf" )
Context/session keys & prefixes
const TokenLength = 32
CSRF token length in bytes.
Variables ¶
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") )
var ( // Idempotent (safe) methods as defined by RFC7231 section 4.2.2. SafeMethods = []string{"GET", "HEAD", "OPTIONS", "TRACE"} )
var TemplateTag = "csrfField"
TemplateTag provides a default template tag - e.g. {{ .csrfField }} - for use with the TemplateField function.
Functions ¶
func CompareTokens ¶
compare securely (constant-time) compares the unmasked token from the request against the real token from the session.
func Contains ¶
contains is a helper function to check if a string exists in a slice - e.g. whether a HTTP method exists in a list of safe methods.
func FailureReason ¶
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 GenerateRandomBytes ¶
generateRandomBytes returns securely generated random bytes. It will return an error if the system's secure random number generator fails to function correctly.
func Mask ¶
mask returns a unique-per-request token to mitigate the BREACH attack as per http://breachattack.com/#mitigations
The token is generated by XOR'ing a one-time-pad and the base (session) CSRF token and returning them together as a 64-byte slice. This effectively randomises the token on a per-request basis without breaking multiple browser tabs/windows.
func SameOrigin ¶
sameOrigin returns true if URLs a and b share the same origin. The same origin is defined as host (which includes the port) and scheme.
func TemplateField ¶
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>">
Types ¶
type CsrfProtection ¶
type CsrfProtection struct { Sc *securecookie.SecureCookie St store Opts options // contains filtered or unexported fields }
func InitCsrf ¶
func InitCsrf(authKey []byte, opts ...Option) *CsrfProtection
func (*CsrfProtection) RequestToken ¶
func (cs *CsrfProtection) RequestToken(r *http.Request) []byte
requestToken returns the issued token (pad + masked token) from the HTTP POST body or HTTP header. It will return nil if the token fails to decode.
type Option ¶
type Option func(*CsrfProtection)
Option describes a functional option for configuring the CSRF handler.
func Domain ¶
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 ¶
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.Failure(r) function to retrieve the CSRF validation reason from the request context.
func FieldName ¶
FieldName allows you to change the name attribute of the hidden <input> field inspected by this package. The default is 'gorilla.csrf.Token'.
func MaxAge ¶
MaxAge sets the maximum age (in seconds) of a CSRF token's underlying cookie. Defaults to 12 hours.
func Path ¶
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 ¶
RequestHeader allows you to change the request header the CSRF middleware inspects. The default is X-CSRF-Token.
func Secure ¶
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.