コンテンツにスキップ

CSRF

Cross-Site Request Forgery(CSRF、“sea-surf” と発音されることもある、または XSRF)は、 Web サイトが信頼するユーザーから未承認のコマンドが送信される悪意ある攻撃の一種です。

すべてのコアミドルウェアは middleware パッケージに含まれています:

import "github.com/labstack/echo/v5/middleware"
e.Use(middleware.CSRF())

CSRF ミドルウェアは、現代的な多層防御として Sec-Fetch-Site header をサポートします。 CSRF protection のために、従来の token ベース機構と並行して OWASP 推奨の Fetch Metadata API を実装しています。

現代的なブラウザーはすべてのリクエストに Sec-Fetch-Site header を自動送信し、 リクエスト元とターゲットの関係を示します。ミドルウェアはこれを使ってセキュリティ判断を行います。

  • same-origin または none:許可(完全な同一 origin、またはユーザーの直接ナビゲーション)
  • same-site:token 検証にフォールバック(例:サブドメインからメインドメイン)
  • cross-site:安全でないメソッド(POST、PUT、DELETE、PATCH)ではデフォルトで 403 エラーによりブロック

この header を送信しないブラウザー(古いブラウザー)では、従来の token ベース CSRF 防御へシームレスに フォールバックします。

Sec-Fetch-Site の挙動は 2 つのオプションで調整できます。

  • TrustedOrigins []string:cross-site リクエストで特定 origin を許可リスト化(OAuth callback、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
},
}))
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,
})
  • サーバー側:token は ContextKey の下でコンテキストから利用でき、テンプレート経由でクライアントへ渡せます。
  • クライアント側:token は CSRF Cookie から読み取れます。

CSRFConfig · github.com/labstack/echo/v5@5196b9b

フィールドの説明は英語のソースコードのコメントから生成されています。

パッケージのソースコードのフィールド
フィールド型説明ソース
SkipperSkipperSkipper defines a function to skip middleware.L29
TrustedOrigins[]stringTrustedOrigins permits any request with `Sec-Fetch-Site` header whose `Origin` header exactly matches a configured origin. Values should be formatted as Origin header "scheme://host[:port]". See [Origin]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin See [Sec-Fetch-Site]: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#fetch-metadata-headersL36
AllowSecFetchSiteFuncfunc(c *echo.Context) (bool, error)AllowSecFetchSiteFunc allows custom behaviour for `Sec-Fetch-Site` requests that are about to fail with CSRF error, to be allowed or replaced with custom error. This function applies to `Sec-Fetch-Site` values: - `same-site` same registrable domain (subdomain and/or different port) - `cross-site` request originates from different site See [Sec-Fetch-Site]: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#fetch-metadata-headersL44
TokenLengthuint8TokenLength is the length of the generated token.L47
TokenLookupstringTokenLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used to extract 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"L59
Generatorfunc() stringGenerator defines a function to generate token. Optional. Defaults to randomString(TokenLength).L63
ContextKeystringContext key to store generated CSRF token into context. Optional. Default value "csrf".L67
CookieNamestringName of the CSRF cookie. This cookie will store CSRF token. Optional. Default value "csrf".L71
CookieDomainstringDomain of the CSRF cookie. Optional. Default value none.L75
CookiePathstringPath of the CSRF cookie. Optional. Default value none.L79
CookieMaxAgeintMax age (in seconds) of the CSRF cookie. Optional. Default value 86400 (24hr).L83
CookieSecureboolIndicates if CSRF cookie is secure. Optional. Default value false.L87
CookieHTTPOnlyboolIndicates if CSRF cookie is HTTP only. Optional. Default value false.L91
CookieSameSitehttp.SameSiteIndicates SameSite mode of the CSRF cookie. Optional. Default value SameSiteDefaultMode.L95
ErrorHandlerfunc(c *echo.Context, err error) errorErrorHandler defines a function which is executed for returning custom errors.L98
パッケージのソースコードの関数
型ソース
func CSRF() echo.MiddlewareFuncL117
func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFuncL122
var DefaultCSRFConfig = CSRFConfig{
Skipper: DefaultSkipper,
TokenLength: 32,
TokenLookup: "header:" + echo.HeaderXCSRFToken,
ContextKey: "csrf",
CookieName: "_csrf",
CookieMaxAge: 86400,
CookieSameSite: http.SameSiteDefaultMode,
}

完全に実行可能な例は echox cookbook にあります。