イントロダクションIntroduction
クロスサイトリクエストフォージェリは、認証済みユーザーに代わって不正なコマンドを実行する、悪意のある攻撃の一種です。幸いに、Laravelを使用すれば、クロスサイトリクエストフォージェリ(CSRF)攻撃からアプリケーションを簡単に保護できます。Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user. Thankfully, Laravel makes it easy to protect your application from cross-site request forgery[https://en.wikipedia.org/wiki/Cross-site_request_forgery] (CSRF) attacks.
脆弱性の説明An Explanation of the Vulnerability
あなたがクロスサイトリクエストフォージェリを知らない場合に備え、この脆弱性を悪用する方法の例を説明しましょう。アプリケーションに、認証済みユーザーの電子メールアドレスを変更するためのPOSTリクエストを受け入れる/user/emailルートがあるとします。ほとんどの場合、このルートでは、email入力フィールドにユーザーが使用を開始したいメールアドレスが含まれている必要があります。In case you're not familiar with cross-site request forgeries, let's discuss an example of how this vulnerability can be exploited. Imagine your application has a /user/email route that accepts a POST request to change the authenticated user's email address. Most likely, this route expects an email input field to contain the email address the user would like to begin using.
CSRF保護がないと、悪意のあるWebサイトがアプリケーションの/user/emailルートを指すHTMLフォームを作成し、悪意のあるユーザー自身の電子メールアドレスを送信する可能性があります。Without CSRF protection, a malicious website could create an HTML form that points to your application's /user/email route and submits the malicious user's own email address:
<form action="https://your-application.com/user/email" method="POST">
<input type="email" value="malicious-email@example.com">
</form>
<script>
document.forms[0].submit();
</script>
悪意のあるWebサイトがページの読み込み時にフォームを自動的に送信する場合、悪意のあるユーザーは、アプリケーションの疑いを持たないユーザーを誘惑してWebサイトにアクセスするだけで、あなたのアプリケーションの電子メールアドレスが変更されます。If the malicious website automatically submits the form when the page is loaded, the malicious user only needs to lure an unsuspecting user of your application to visit their website and their email address will be changed in your application.
この脆弱性を防ぐには、すべての受信POST、PUT、PATCH、DELETEリクエストを調べて、悪意のあるアプリケーションがアクセスできないシークレットセッション値を確認する必要があります。To prevent this vulnerability, we need to inspect every incoming POST, PUT, PATCH, or DELETE request for a secret session value that the malicious application is unable to access.
CSRFリクエストの防止Preventing CSRF Requests
デフォルトでwebミドルウェアグループに含まれているIlluminate\Foundation\Http\Middleware\PreventRequestForgery ミドルウェアは、2層のアプローチを使用してクロスサイトリクエストフォージェリからアプリケーションを保護します。The Illuminate\Foundation\Http\Middleware\PreventRequestForgery middleware[/docs/{{version}}/middleware], which is included in the web middleware group by default, protects your application from cross-site request forgeries using a two-layer approach.
最初に、ミドルウェアはブラウザのSec-Fetch-Siteヘッダを確認します。最新のブラウザはすべてのリクエストでこのヘッダを自動的に設定し、リクエストが同一オリジン、同一サイト、またはクロスサイトのソースから送信されたものかを示します。ヘッダが同一オリジンからのリクエストであることを示している場合、トークンの検証なしにリクエストを即座に許可します。First, the middleware checks the browser's Sec-Fetch-Site header. Modern browsers automatically set this header on every request, indicating whether it originated from the same origin, the same site, or a cross-site source. If the header indicates the request came from the same origin, the request is allowed immediately without any token verification.
オリジンの検証を通過しなかった場合(たとえば、Sec-Fetch-Siteヘッダを送信しない古いブラウザからのリクエストである場合や、接続が安全でない場合など)、ミドルウェアは従来のCSRFトークンバリデーションへフォールバックします。If origin verification does not pass — for example, because the request comes from an older browser that doesn't send the Sec-Fetch-Site header or because the connection is not secure — the middleware falls back to traditional CSRF token validation.
Laravelは、アプリケーションによって管理されているアクティブなユーザーセッションごとにCSRF「トークン」を自動的に生成します。このトークンは、認証済みユーザーが実際にアプリケーションへリクエストを行っているユーザーであることを確認するために使用されます。このトークンはユーザーのセッションに保存され、セッションが再生成されるたびに変更されるため、悪意のあるアプリケーションはこのトークンへアクセスできません。Laravel automatically generates a CSRF "token" for each active user session[/docs/{{version}}/session] managed by the application. This token is used to verify that the authenticated user is the person actually making the requests to the application. Since this token is stored in the user's session and changes each time the session is regenerated, a malicious application is unable to access it.
現在のセッションのCSRFトークンには、リクエストのセッションまたはcsrf_tokenヘルパ関数を介してアクセスできます。The current session's CSRF token can be accessed via the request's session or via the csrf_token helper function:
use Illuminate\Http\Request;
Route::get('/token', function (Request $request) {
$token = $request->session()->token();
$token = csrf_token();
// ...
});
アプリケーションで"POST"、"PUT"、"PATCH"、"DELETE" HTMLフォームを定義するときはいつでも、CSRF保護ミドルウェアがリクエストを検証できるように、フォームに非表示のCSRF_tokenフィールドを含める必要があります。便利なように、@csrf Bladeディレクティブを使用して、非表示のトークン入力フィールドを生成できます。Anytime you define a "POST", "PUT", "PATCH", or "DELETE" HTML form in your application, you should include a hidden CSRF _token field in the form so that the CSRF protection middleware can validate the request. For convenience, you may use the @csrf Blade directive to generate the hidden token input field:
<form method="POST" action="/profile">
@csrf
<!-- Equivalent to... -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
</form>
CSRF Tokens & SPAsCSRF Tokens & SPAs
LaravelをAPIバックエンドとして利用するSPAを構築している場合は、APIによる認証とCSRFの脆弱性からの保護について、Laravel Sanctumドキュメントを参照してください。If you are building an SPA that is utilizing Laravel as an API backend, you should consult the Laravel Sanctum documentation[/docs/{{version}}/sanctum] for information on authenticating with your API and protecting against CSRF vulnerabilities.
オリジン検証Origin Verification
上述したように、Laravelのリクエストフォージェリミドルウェアは、まずSec-Fetch-Siteヘッダをチェックして、リクエストが同一オリジンからのものかどうかを判断します。このチェックを通過しなかった場合、ミドルウェアはCSRFトークンバリデーションへデフォルトでフォールバックします。As discussed above, Laravel's request forgery middleware first checks the Sec-Fetch-Site header to determine if the request is from the same origin. By default, if this check does not pass, the middleware falls back to CSRF token validation.
しかし、オリジン検証のみに依存し、CSRFトークンのフォールバックを完全に無効にしたい場合は、アプリケーションのbootstrap/app.phpファイルでpreventRequestForgeryメソッドを使用して設定します。However, if you would like to rely solely on origin verification and disable the CSRF token fallback entirely, you may do so using the preventRequestForgery method in your application's bootstrap/app.php file:
->withMiddleware(function (Middleware $middleware): void {
$middleware->preventRequestForgery(originOnly: true);
})
オリジン限定モードを使用している場合、オリジン検証に失敗したリクエストは、CSRFトークンの不一致で通常返される419レスポンスではなく、403HTTPレスポンスを受信します。When using origin-only mode, requests that fail origin verification will receive a 403 HTTP response instead of the 419 response typically associated with CSRF token mismatches.
Warning!
Sec-Fetch-Siteヘッダは、安全な(HTTPS)接続を介してのみブラウザから送信されます。アプリケーションがHTTPSを介して提供されていない場合、オリジン検証は利用できず、ミドルウェアはCSRFトークンバリデーションへフォールバックします。[!WARNING] TheSec-Fetch-Siteheader is only sent by browsers over secure (HTTPS) connections. If your application is not served over HTTPS, origin verification will not be available and the middleware will fall back to CSRF token validation.
アプリケーションがサブドメインからのリクエストを受け入れる必要がある場合(例:example.comからのリクエストをdashboard.example.comが受け入れる場合)、同一オリジンのリクエストに加えて、同一サイトのリクエストを許可できます。If your application needs to accept requests from subdomains (for example, dashboard.example.com accepting requests from example.com), you may allow same-site requests in addition to same-origin requests:
->withMiddleware(function (Middleware $middleware): void {
$middleware->preventRequestForgery(allowSameSite: true);
})
CSRF保護から除外するURIExcluding URIs From CSRF Protection
場合により、一連のURIをCSRF保護から除外したいことが起きます。たとえば、Stripeを使用して支払いを処理し、そのWebhookシステムを利用している場合、StripeはどのCSRFトークンをルートへ送るのか認識していないため、Stripe WebフックハンドラルートをCSRF保護から除外する必要があります。Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe[https://stripe.com] to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.
通常、こうした種類のルートは、Laravelがroutes/web.phpファイルのすべてのルートに適用するwebミドルウェアグループの外側に配置してください。しかし、アプリケーションのbootstrap/app.phpファイルで、preventRequestForgeryメソッドにURIを指定することで、特定のルートを除外することもできます。Typically, you should place these kinds of routes outside of the web middleware group that Laravel applies to all routes in the routes/web.php file. However, you may also exclude specific routes by providing their URIs to the preventRequestForgery method in your application's bootstrap/app.php file:
->withMiddleware(function (Middleware $middleware): void {
$middleware->preventRequestForgery(except: [
'stripe/*',
'http://example.com/foo/bar',
'http://example.com/foo/*',
]);
})
Note: 利便性向上のため、テスト実行時に、CSRFミドルウェアはすべてのルートで自動的に無効になります。[!NOTE] For convenience, the CSRF middleware is automatically disabled for all routes when running tests[/docs/{{version}}/testing].
X-CSRF-TOKENX-CSRF-TOKEN
POSTパラメータとしてCSRFトークンをチェックすることに加え、PreventRequestForgeryミドルウェアはX-CSRF-TOKENリクエストヘッダもチェックします。たとえば、HTMLのmetaタグにトークンを保存できます。In addition to checking for the CSRF token as a POST parameter, the PreventRequestForgery middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in an HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
次にjQueryなどのライブラリで、すべてのリクエストヘッダへトークンを自動的に追加するように指示できます。これにより、レガシーJavaScriptテクノロジーを使用して、AJAXベースのアプリケーションにシンプルで便利なCSRF保護を提供しています。Then, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications using legacy JavaScript technology:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
X-XSRF-TOKENX-XSRF-TOKEN
Laravelはフレームワークが生成する各レスポンスに含めるXSRF-TOKEN暗号化クッキーへ、現在のCSRFトークンを保存します。クッキー値を使用して、X-XSRF-TOKENリクエストヘッダを設定できます。Laravel stores the current CSRF token in an encrypted XSRF-TOKEN cookie that is included with each response generated by the framework. You can use the cookie value to set the X-XSRF-TOKEN request header.
AngularやAxiosなどの一部のJavaScriptフレームワークとライブラリは、同じオリジンのリクエストでその値を自動的にX-XSRF-TOKENヘッダへ配置するため、このクッキーは主に開発者の利便性のために送信されます。This cookie is primarily sent as a developer convenience since some JavaScript frameworks and libraries, like Angular and Axios, automatically place its value in the X-XSRF-TOKEN header on same-origin requests.
Note: デフォルトで、
resources/js/bootstrap.jsファイルにはAxios HTTPライブラリが含まれており、X-XSRF-TOKENヘッダを自動的に送信します。[!NOTE] By default, theresources/js/bootstrap.jsfile includes the Axios HTTP library which will automatically send theX-XSRF-TOKENheader for you.