CSRF
Cross-Site Request Forgery(CSRF,有时读作 “sea-surf”,也称 XSRF)是一类恶意利用, 攻击者会从网站信任的用户那里传递未授权命令。
e.Use(middleware.CSRF())CSRF 中间件支持
Sec-Fetch-Site
header,作为现代的纵深防御方式来进行
CSRF protection,
它在传统 token 机制之外实现了 OWASP 推荐的 Fetch Metadata API。
现代浏览器会自动随每个请求发送 Sec-Fetch-Site header,表明请求来源和目标之间的关系。
中间件会用它做出安全决策:
same-origin或none:允许(完全同源或用户直接导航)same-site:回退到 token 验证(例如子域到主域)cross-site:对不安全方法(POST、PUT、DELETE、PATCH)默认以403错误阻止
对于不发送此 header 的浏览器(旧浏览器),中间件会无缝回退到传统基于 token 的 CSRF 防护。
两个选项可调整 Sec-Fetch-Site 行为:
TrustedOrigins []string:为跨站请求允许特定 origin(适用于 OAuth 回调、webhook)AllowSecFetchSiteFunc func(c *echo.Context) (bool, error):用于 same-site/cross-site 验证的自定义逻辑
e.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{ // Allow OAuth callbacks from a trusted provider. TrustedOrigins: []string{"https://oauth-provider.com"},
// Custom validation for same-site/cross-site requests. AllowSecFetchSiteFunc: func(c *echo.Context) (bool, error) { // Your custom authorization logic here. return validateCustomAuth(c), nil // return true, err // blocks the request with an error // return true, nil // allows the request through // return false, nil // falls back to legacy token logic },}))基于 token 的防护
Section titled “基于 token 的防护”e := echo.New()e.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{ TokenLookup: "header:X-XSRF-TOKEN",}))上面的示例会从 X-XSRF-TOKEN 请求 header 中提取 CSRF token。
改为从 Cookie 读取 token:
middleware.CSRFWithConfig(middleware.CSRFConfig{ TokenLookup: "cookie:_csrf", CookiePath: "/", CookieDomain: "example.com", CookieSecure: true, CookieHTTPOnly: true, CookieSameSite: http.SameSiteStrictMode,})访问 CSRF token
Section titled “访问 CSRF token”- 服务端:token 可从上下文的
ContextKey下取得,并可通过模板传给客户端。 - 客户端:token 可从 CSRF Cookie 中读取。
type CSRFConfig struct { // Skipper defines a function to skip middleware. Skipper Skipper
// TrustedOrigins permits any request with a `Sec-Fetch-Site` header whose `Origin` // header exactly matches one of the listed values. Values should be formatted as // the Origin header: "scheme://host[:port]". TrustedOrigins []string
// AllowSecFetchSiteFunc allows custom behaviour for `Sec-Fetch-Site` requests that // are about to fail with a CSRF error, to be allowed or replaced with a custom // error. Applies to `same-site` and `cross-site` values. AllowSecFetchSiteFunc func(c *echo.Context) (bool, error)
// TokenLength is the length of the generated token. // Optional. Default value 32. TokenLength uint8
// TokenLookup is a string in the form "<source>:<name>" or // "<source>:<name>,<source>:<name>" used to extract the token from the request. // Optional. Default value "header:X-CSRF-Token". // Possible values: // - "header:<name>" or "header:<name>:<cut-prefix>" // - "query:<name>" // - "form:<name>" // Multiple sources example: "header:X-CSRF-Token,query:csrf". TokenLookup string `yaml:"token_lookup"`
// Generator defines a function to generate the token. // Optional. Defaults to randomString(TokenLength). Generator func() string
// ContextKey is the key under which the generated CSRF token is stored in the context. // Optional. Default value "csrf". ContextKey string
// CookieName is the name of the CSRF cookie that stores the token. // Optional. Default value "_csrf". CookieName string
// CookieDomain is the domain of the CSRF cookie. // Optional. Default value none. CookieDomain string
// CookiePath is the path of the CSRF cookie. // Optional. Default value none. CookiePath string
// CookieMaxAge is the max age (in seconds) of the CSRF cookie. // Optional. Default value 86400 (24h). CookieMaxAge int
// CookieSecure indicates whether the CSRF cookie is secure. // Optional. Default value false. CookieSecure bool
// CookieHTTPOnly indicates whether the CSRF cookie is HTTP only. // Optional. Default value false. CookieHTTPOnly bool
// CookieSameSite indicates the SameSite mode of the CSRF cookie. // Optional. Default value SameSiteDefaultMode. CookieSameSite http.SameSite
// ErrorHandler defines a function that returns custom errors. ErrorHandler func(c *echo.Context, err error) error}var DefaultCSRFConfig = CSRFConfig{ Skipper: DefaultSkipper, TokenLength: 32, TokenLookup: "header:" + echo.HeaderXCSRFToken, ContextKey: "csrf", CookieName: "_csrf", CookieMaxAge: 86400, CookieSameSite: http.SameSiteDefaultMode,}完整、可运行的示例可在 echox cookbook 中找到。