csrf

package module
v0.0.0-...-34f2740 Latest Latest
Warning

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

Go to latest
Published: May 2, 2024 License: BSD-3-Clause Imports: 13 Imported by: 53

README

CSRF

CSRF is an Iris middleware 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.

This repository is a highly customized fork of the amazing gorilla/csrf package. Unlike the gorilla/csrf, the iris-contrib csrf middleware provides a way to customize the tokens Store (defaults to cookie store) and also pass cookie options as the standard Go net/http package evolves, without any additional code from our side. Navigate to the example for more.

Contents

Install

go get github.com/iris-contrib/middleware/csrf@master

CSRF is easy to use: add the middleware to your router with the below:

app := iris.New()
// [...]
CSRF := csrf.Protect([]byte("32-byte-long-auth-key"))
app.Use(CSRF)

...and then collect the token with csrf.Token(ctx) 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.

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 (
	"github.com/kataras/iris/v12"

	"github.com/iris-contrib/middleware/csrf"
)

func main() {
	app := iris.New()
	app.RegisterView(iris.HTML("./views", ".html"))
    // 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.
    userAPI := app.Party("/user")
    CSRF := csrf.Protect(
        // Note that the authentication key provided should be 32 bytes
        // long and persist across application restarts.
        []byte("9AB0F421E53A477C084477AEA06096F5"),
        // WARNING: Set it to true on production with HTTPS.
        csrf.Secure(false),
    )
    userAPI.Use(CSRF)
    userAPI.Post("/signup", SubmitSignupForm)
    userAPI.Get("/signup", ShowSignupForm)

    app.Listen(":8080")
}

func ShowSignupForm(ctx iris.Context) {
    // user/signup.html just needs a {{ .csrfField }} template tag for
    // csrf.TemplateField to inject the CSRF token into. Easy!
    ctx.ViewData(csrf.TemplateTag, csrf.TemplateField(ctx))
    ctx.View("user/signup.html")
    // We could also retrieve the token directly from csrf.Token(ctx) and
    // set it in the request header - ctx.Header("X-CSRF-Token", token)
    // This is useful if you're sending JSON to clients or a front-end JavaScript
    // framework.
}

func SubmitSignupForm(ctx iris.Context) {
    // 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(ctx) 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.
func GetUser(ctx iris.Context) {
    // 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.
    ctx.Header("X-CSRF-Token", csrf.Token(ctx))
    ctx.JSON(user)
}

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("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 code snippet below:

CSRF := csrf.New(csrf.Options{
    TrustedOrigins: []string{"ui.domain.com"},
    Store: csrf.NewCookieStore(
        []byte("9AB0F421E53A477C084477AEA06096F5"), csrf.Secure(false)),
}).Protect

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.

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.

import (
    "net/http"

	"github.com/kataras/iris/v12"
	"github.com/iris-contrib/middleware/csrf"
)

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(http.SameSiteStrictMode),
    )

    // [...]
}
Setting Options

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

CSRF := csrf.New(csrf.Options{
    TrustedOrigins: []string{"ui.domain.com"},
    RequestHeader: "X-CSRF-Token",
    FieldName:     "csrf.token",
    ErrorHandler:  csrf.UnauthorizedHandler,
    Store: csrf.NewCookieStore(
        []byte("9AB0F421E53A477C084477AEA06096F5"), csrf.Secure(false)),
})

The CSRF.Filter method.

func access(ctx iris.Context) {
    if CSRF.Filter(ctx) {
        // Succeed.
    } else {
        // It's a failure.
        // Customize the error response, the ErrorHandler is not called.
    }
}

OR use the iris.NewConditionalHandler:

app.Get(iris.NewConditionalHandler(CSRF.Filter, protectedHandler))

The main CSRF.Protect method (same as csrf.Protect package-level function as we've seen in the previous examples).

app.Use(CSRF.Protect)

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

Index

Constants

View Source
const (
	DefaultCookieName string = "_iris_csrf"
)

Context/session keys.

Variables

View Source
var (
	// DefaultFieldName is the default name value used in form fields.
	DefaultFieldName = tokenKey
	// DefaultSameSite 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.
	// The csrf middleware uses the http.SameSiteLaxMode (SameSite=Lax) as the default one.
	DefaultSameSite = http.SameSiteLaxMode
	// DefaultMaxAge sets the default MaxAge for cookies.
	DefaultMaxAge = 3600 * 12
	// DefaultRequestHeader is the default HTTP request header to inspect.
	DefaultRequestHeader = "X-CSRF-Token"
	// TemplateTag is the default HTML template tag provides a default template tag,
	// e.g. {{ .csrfField }} - for use
	// with the TemplateField function.
	TemplateTag = "csrfField"
)
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")
)

Functions

func FailureReason

func FailureReason(ctx iris.Context) 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, cookieOpts ...CookieOption) iris.Handler

Protect is Iris 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.

See `New` package-level function for further customizations.

func TemplateField

func TemplateField(ctx iris.Context) 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="csrf.token" value="<token>">

func Token

func Token(ctx iris.Context) 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 UnauthorizedHandler

func UnauthorizedHandler(ctx iris.Context)

UnauthorizedHandler sets a HTTP 403 Forbidden status and writes the CSRF failure reason to the response.

func UnsafeSkipCheck

func UnsafeSkipCheck(ctx iris.Context)

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 CSRF

type CSRF struct {
	// contains filtered or unexported fields
}

CSRF represents the CSRF feature.

func New

func New(opts Options) *CSRF

New returns the CSRF middleware. Read the `Protect` package-level function for more.

func (*CSRF) Filter

func (csrf *CSRF) Filter(ctx iris.Context) bool

Filter is the Iris Filter type of the csrf middleware. It can be used instead of the `Protect` method when the caller needs to manually manage the response on success (true) and failure (false). The `ErrorHandler` is not fired.

func (*CSRF) Protect

func (csrf *CSRF) Protect(ctx iris.Context)

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

Read more at the Protect package-level function's documentation.

func (*CSRF) RequestToken

func (csrf *CSRF) RequestToken(ctx iris.Context) []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 CookieOption

type CookieOption func(*http.Cookie)

CookieOption represents the Cookie configuration, used by CookieStore.

func CookieName

func CookieName(name string) CookieOption

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) CookieOption

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 HTTPOnly

func HTTPOnly(httpOnly bool) CookieOption

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

func MaxAge

func MaxAge(maxAge int) CookieOption

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(path string) CookieOption

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 SameSite

func SameSite(sameSite http.SameSite) CookieOption

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).

func Secure

func Secure(secure bool) CookieOption

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.

type Options

type Options struct {
	// Store lets you configure the backend storage of the CRSF session.
	Store Store
	// FieldName allows you to change the name attribute of the hidden <input> field
	// inspected by this package. The default is 'csrf.token'.
	FieldName string
	// RequestHeader allows you to change the request header the CSRF middleware
	// inspects. The default is X-CSRF-Token.
	RequestHeader string
	// 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.
	ErrorHandler iris.Handler
	// 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.
	TrustedOrigins []string
}

Options describes the configuration for the CRSF middleware.

type Store

type Store interface {
	// Get returns the real CSRF token from the store.
	Get(ctx iris.Context) ([]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(ctx iris.Context, token []byte) error
}

Store represents the session storage used for CSRF tokens.

func NewCookieStore

func NewCookieStore(authKey []byte, cookieOpts ...CookieOption) Store

NewCookieStore returns a new Store that saves and retrieves the CSRF token to and from the client's cookie jar.

Directories

Path Synopsis
This middleware provides Cross-Site Request Forgery protection.
This middleware provides Cross-Site Request Forgery protection.

Jump to

Keyboard shortcuts

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