matterbridge/vendor/github.com/labstack/echo/v4/middleware/csrf.go

206 lines
6.0 KiB
Go
Raw Normal View History

2017-02-18 22:00:46 +00:00
package middleware
import (
"crypto/subtle"
"net/http"
"time"
"github.com/labstack/echo/v4"
2017-02-18 22:00:46 +00:00
"github.com/labstack/gommon/random"
)
type (
// CSRFConfig defines the config for CSRF middleware.
CSRFConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// TokenLength is the length of the generated token.
2018-02-20 23:48:10 +00:00
TokenLength uint8 `yaml:"token_length"`
2017-02-18 22:00:46 +00:00
// Optional. Default value 32.
2022-03-12 18:41:07 +00:00
// TokenLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used
2017-02-18 22:00:46 +00:00
// to extract token from the request.
// Optional. Default value "header:X-CSRF-Token".
// Possible values:
2022-03-12 18:41:07 +00:00
// - "header:<name>" or "header:<name>:<cut-prefix>"
2017-02-18 22:00:46 +00:00
// - "query:<name>"
2022-03-12 18:41:07 +00:00
// - "form:<name>"
// Multiple sources example:
// - "header:X-CSRF-Token,query:csrf"
2018-02-20 23:48:10 +00:00
TokenLookup string `yaml:"token_lookup"`
2017-02-18 22:00:46 +00:00
// Context key to store generated CSRF token into context.
// Optional. Default value "csrf".
2018-02-20 23:48:10 +00:00
ContextKey string `yaml:"context_key"`
2017-02-18 22:00:46 +00:00
// Name of the CSRF cookie. This cookie will store CSRF token.
// Optional. Default value "csrf".
2018-02-20 23:48:10 +00:00
CookieName string `yaml:"cookie_name"`
2017-02-18 22:00:46 +00:00
// Domain of the CSRF cookie.
// Optional. Default value none.
2018-02-20 23:48:10 +00:00
CookieDomain string `yaml:"cookie_domain"`
2017-02-18 22:00:46 +00:00
// Path of the CSRF cookie.
// Optional. Default value none.
2018-02-20 23:48:10 +00:00
CookiePath string `yaml:"cookie_path"`
2017-02-18 22:00:46 +00:00
// Max age (in seconds) of the CSRF cookie.
// Optional. Default value 86400 (24hr).
2018-02-20 23:48:10 +00:00
CookieMaxAge int `yaml:"cookie_max_age"`
2017-02-18 22:00:46 +00:00
// Indicates if CSRF cookie is secure.
// Optional. Default value false.
2018-02-20 23:48:10 +00:00
CookieSecure bool `yaml:"cookie_secure"`
2017-02-18 22:00:46 +00:00
// Indicates if CSRF cookie is HTTP only.
// Optional. Default value false.
2018-02-20 23:48:10 +00:00
CookieHTTPOnly bool `yaml:"cookie_http_only"`
2021-03-20 21:40:23 +00:00
// Indicates SameSite mode of the CSRF cookie.
// Optional. Default value SameSiteDefaultMode.
CookieSameSite http.SameSite `yaml:"cookie_same_site"`
2017-02-18 22:00:46 +00:00
}
)
2022-03-12 18:41:07 +00:00
// ErrCSRFInvalid is returned when CSRF check fails
var ErrCSRFInvalid = echo.NewHTTPError(http.StatusForbidden, "invalid csrf token")
2017-02-18 22:00:46 +00:00
var (
// DefaultCSRFConfig is the default CSRF middleware config.
DefaultCSRFConfig = CSRFConfig{
2021-03-20 21:40:23 +00:00
Skipper: DefaultSkipper,
TokenLength: 32,
TokenLookup: "header:" + echo.HeaderXCSRFToken,
ContextKey: "csrf",
CookieName: "_csrf",
CookieMaxAge: 86400,
CookieSameSite: http.SameSiteDefaultMode,
2017-02-18 22:00:46 +00:00
}
)
// CSRF returns a Cross-Site Request Forgery (CSRF) middleware.
// See: https://en.wikipedia.org/wiki/Cross-site_request_forgery
func CSRF() echo.MiddlewareFunc {
c := DefaultCSRFConfig
return CSRFWithConfig(c)
}
// CSRFWithConfig returns a CSRF middleware with config.
// See `CSRF()`.
func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc {
// Defaults
if config.Skipper == nil {
config.Skipper = DefaultCSRFConfig.Skipper
}
if config.TokenLength == 0 {
config.TokenLength = DefaultCSRFConfig.TokenLength
}
if config.TokenLookup == "" {
config.TokenLookup = DefaultCSRFConfig.TokenLookup
}
if config.ContextKey == "" {
config.ContextKey = DefaultCSRFConfig.ContextKey
}
if config.CookieName == "" {
config.CookieName = DefaultCSRFConfig.CookieName
}
if config.CookieMaxAge == 0 {
config.CookieMaxAge = DefaultCSRFConfig.CookieMaxAge
}
2021-05-29 22:25:30 +00:00
if config.CookieSameSite == http.SameSiteNoneMode {
2021-03-20 21:40:23 +00:00
config.CookieSecure = true
}
2017-02-18 22:00:46 +00:00
2022-03-12 18:41:07 +00:00
extractors, err := createExtractors(config.TokenLookup, "")
if err != nil {
panic(err)
2017-02-18 22:00:46 +00:00
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
return next(c)
}
token := ""
2022-03-12 18:41:07 +00:00
if k, err := c.Cookie(config.CookieName); err != nil {
token = random.String(config.TokenLength) // Generate token
2017-02-18 22:00:46 +00:00
} else {
2022-03-12 18:41:07 +00:00
token = k.Value // Reuse token
2017-02-18 22:00:46 +00:00
}
2022-03-12 18:41:07 +00:00
switch c.Request().Method {
case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace:
2017-02-18 22:00:46 +00:00
default:
// Validate token only for requests which are not defined as 'safe' by RFC7231
2022-03-12 18:41:07 +00:00
var lastExtractorErr error
var lastTokenErr error
outer:
for _, extractor := range extractors {
clientTokens, err := extractor(c)
if err != nil {
lastExtractorErr = err
continue
}
for _, clientToken := range clientTokens {
if validateCSRFToken(token, clientToken) {
lastTokenErr = nil
lastExtractorErr = nil
break outer
}
lastTokenErr = ErrCSRFInvalid
}
2017-02-18 22:00:46 +00:00
}
2022-03-12 18:41:07 +00:00
if lastTokenErr != nil {
return lastTokenErr
} else if lastExtractorErr != nil {
// ugly part to preserve backwards compatible errors. someone could rely on them
if lastExtractorErr == errQueryExtractorValueMissing {
lastExtractorErr = echo.NewHTTPError(http.StatusBadRequest, "missing csrf token in the query string")
} else if lastExtractorErr == errFormExtractorValueMissing {
lastExtractorErr = echo.NewHTTPError(http.StatusBadRequest, "missing csrf token in the form parameter")
} else if lastExtractorErr == errHeaderExtractorValueMissing {
lastExtractorErr = echo.NewHTTPError(http.StatusBadRequest, "missing csrf token in request header")
} else {
lastExtractorErr = echo.NewHTTPError(http.StatusBadRequest, lastExtractorErr.Error())
}
return lastExtractorErr
2017-02-18 22:00:46 +00:00
}
}
// Set CSRF cookie
cookie := new(http.Cookie)
cookie.Name = config.CookieName
cookie.Value = token
if config.CookiePath != "" {
cookie.Path = config.CookiePath
}
if config.CookieDomain != "" {
cookie.Domain = config.CookieDomain
}
2021-03-20 21:40:23 +00:00
if config.CookieSameSite != http.SameSiteDefaultMode {
cookie.SameSite = config.CookieSameSite
}
2017-02-18 22:00:46 +00:00
cookie.Expires = time.Now().Add(time.Duration(config.CookieMaxAge) * time.Second)
cookie.Secure = config.CookieSecure
cookie.HttpOnly = config.CookieHTTPOnly
c.SetCookie(cookie)
// Store token in the context
c.Set(config.ContextKey, token)
// Protect clients from caching the response
c.Response().Header().Add(echo.HeaderVary, echo.HeaderCookie)
return next(c)
}
}
}
func validateCSRFToken(token, clientToken string) bool {
return subtle.ConstantTimeCompare([]byte(token), []byte(clientToken)) == 1
}