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 },}))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 から読み取れます。
CSRFConfig · github.com/labstack/echo/v5@5196b9b
フィールドの説明は英語のソースコードのコメントから生成されています。
| フィールド | 型 | 説明 | ソース |
|---|---|---|---|
Skipper | Skipper | Skipper defines a function to skip middleware. | L29 |
TrustedOrigins | []string | TrustedOrigins 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-headers | L36 |
AllowSecFetchSiteFunc | func(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-headers | L44 |
TokenLength | uint8 | TokenLength is the length of the generated token. | L47 |
TokenLookup | string | TokenLookup 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 |
Generator | func() string | Generator defines a function to generate token. Optional. Defaults to randomString(TokenLength). | L63 |
ContextKey | string | Context key to store generated CSRF token into context. Optional. Default value "csrf". | L67 |
CookieName | string | Name of the CSRF cookie. This cookie will store CSRF token. Optional. Default value "csrf". | L71 |
CookieDomain | string | Domain of the CSRF cookie. Optional. Default value none. | L75 |
CookiePath | string | Path of the CSRF cookie. Optional. Default value none. | L79 |
CookieMaxAge | int | Max age (in seconds) of the CSRF cookie. Optional. Default value 86400 (24hr). | L83 |
CookieSecure | bool | Indicates if CSRF cookie is secure. Optional. Default value false. | L87 |
CookieHTTPOnly | bool | Indicates if CSRF cookie is HTTP only. Optional. Default value false. | L91 |
CookieSameSite | http.SameSite | Indicates SameSite mode of the CSRF cookie. Optional. Default value SameSiteDefaultMode. | L95 |
ErrorHandler | func(c *echo.Context, err error) error | ErrorHandler defines a function which is executed for returning custom errors. | L98 |
デフォルト設定
Section titled “デフォルト設定”var DefaultCSRFConfig = CSRFConfig{ Skipper: DefaultSkipper, TokenLength: 32, TokenLookup: "header:" + echo.HeaderXCSRFToken, ContextKey: "csrf", CookieName: "_csrf", CookieMaxAge: 86400, CookieSameSite: http.SameSiteDefaultMode,}完全に実行可能な例は echox cookbook にあります。