クロスサイトリクエストフォージェリ (CSRF) 対策

CSRF ミドルウェアとテンプレートタグは、簡単に扱える Cross Site Request Forgeries 対策を提供しています。このタイプの攻撃は、訪問者のログイン情報を悪用してあなたのサイトに何らかの操作を行うことを目的とした、リンクやフォームボタン、 JavaScript を設置した悪意のあるウェブサイトによって行われます。また、関連する攻撃として、ユーザーを騙して別のユーザー権限でログインさせる 'ログイン CSRF' と呼ばれる攻撃もありますが、これも対策に含まれます。

CSRF 攻撃に対する第一の防御は、 GET リクエスト (および RFC 7231#section-4.2.1 で定義された ‘安全な’ メソッド) から副作用を取り除くというものです。そして、 POST、PUT、DELETE のような、’安全でない’ メソッ ドによるリクエストについては、下記の手順に従うことで対策することができます。

使用方法

CSRF 対策をあなたのビューで有効にするには、以下の手順に従ってください:

  1. CSRF ミドルウェアは、デフォルトで MIDDLEWARE 設定で有効になっています。もし設定をオーバーライドするときは、'django.middleware.csrf.CsrfViewMiddleware' が、 CSRF 攻撃への対策がされていることを前提とした他の全てのビュー・ミドルウェアの前に来るようにしてください。

    (推奨されませんが) もし対策を無効にする場合は、csrf_protect() を使って特定のビューを保護することができます. (下記をご覧ください)

  2. POST フォームを使う全てのテンプレートで、POST が内部 URL に使われる場合は、<form> 要素の内部で csrf_token タグを使用してください。

    <form method="post">{% csrf_token %}
    

    この方法は、外部の URL を対象にする POST フォームで使ってはなりません。CSRF トークンが外部に漏れ、脆弱性の原因となります。

  3. 一致するビュー機能の中で、{% csrf_token %} が適切に動作するように、RequestContext がレスポンスをレンダリングするようにしてください。render() 、汎用ビューもしくは contrib アプリケーションを使う場合は、これら全て RequestContext を使用するためすでに CSRF 対策はなされています。

AJAX

上記の方法は AJAX の POST でも利用可能ですが、多少不便です。すべての POST リクエストで、CSRF トークンを POST するデータに忘れずに含めなければなりません。そのため、別の方法が用意されており、各 XMLHttpRequest に対して、X-CSRFToken という独自ヘッダーに CSRF トークンの値を設定することができます (CSRF_HEADER_NAME 設定でヘッダー名が指定できます)。多くの JavaScript のフレームワークはすべてのリクエストについて、指定したヘッダーを設定するようなフック機能を提供しているので、普通は簡単に設定できます。

まず、あなたは CSRF トークンを取得する必要があります。取得方法は、CSRF_USE_SESSIONSCSRF_COOKIE_HTTPONLY を設定したかどうかによって変わります。

Setting the token on the AJAX request

Finally, you'll need to set the header on your AJAX request. Using the fetch() API:

const request = new Request(
    /* URL */,
    {
        method: 'POST',
        headers: {'X-CSRFToken': csrftoken},
        mode: 'same-origin' // Do not send CSRF token to another domain.
    }
);
fetch(request).then(function(response) {
    // ...
});

Jinja2 テンプレートで CSRF を使用する

Django の Jinja2 テンプレートバックエンドは、すべてのテンプレートのコンテキストに {{ csrf_input }} を追加します。これは、Django テンプレート言語内の {% csrf_token %} と同じ意味です。例えば:

<form method="post">{{ csrf_input }}

デコレータメソッド

全体を保護するために CsrfViewMiddleware を追加する代わりに、保護を必要とする特定のビューにおいて、(まったく同じ機能を持つ) csrf_protect デコレータを使えます。アウトプット内に CSRF トークンを挿入するビューと、POST フォームデータを受け入れるビューの両方で使用する必要があります (多くの場合同じビュー関数ですが、そうでない場合もあります)。

デコレータ自体で使うことは 非推奨 です。もし使い忘れた場合、セキュリティホールを抱えることになるからです。二重対策として両方を使うのは構いませんが、わずかにオーバーヘッドが増加します。

csrf_protect(view)

ビューに対する CsrfViewMiddleware の保護を提供するデコレータです。

使い方は以下の通りです:

from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect

@csrf_protect
def my_view(request):
    c = {}
    # ...
    return render(request, "a_template.html", c)

クラスベースのビューを使っている場合は、 Decorating class-based views を参照してください。

拒否されたリクエスト

受け取ったリクエストが CsrfViewMiddleware による認証に失敗した場合、デフォルトでは、ユーザーには '403 Forbidden' レスポンスが送信されます。これは通常、本当にクロスサイトリクエストフォージェリが行われたか、プログラミングのミスによって POST フォームに CSRF トークンが含まれていない場合に発生します。

The error page, however, is not very friendly, so you may want to provide your own view for handling this condition. To do this, set the CSRF_FAILURE_VIEW setting.

CSRF failures are logged as warnings to the django.security.csrf logger.

How it works

The CSRF protection is based on the following things:

  1. A CSRF cookie that is based on a random secret value, which other sites will not have access to.

    This cookie is set by CsrfViewMiddleware. It is sent with every response that has called django.middleware.csrf.get_token() (the function used internally to retrieve the CSRF token), if it wasn't already set on the request.

    In order to protect against BREACH attacks, the token is not simply the secret; a random mask is prepended to the secret and used to scramble it.

    For security reasons, the value of the secret is changed each time a user logs in.

  2. A hidden form field with the name 'csrfmiddlewaretoken' present in all outgoing POST forms. The value of this field is, again, the value of the secret, with a mask which is both added to it and used to scramble it. The mask is regenerated on every call to get_token() so that the form field value is changed in every such response.

    This part is done by the template tag.

  3. For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or TRACE, a CSRF cookie must be present, and the 'csrfmiddlewaretoken' field must be present and correct. If it isn't, the user will get a 403 error.

    When validating the 'csrfmiddlewaretoken' field value, only the secret, not the full token, is compared with the secret in the cookie value. This allows the use of ever-changing tokens. While each request may use its own token, the secret remains common to all.

    This check is done by CsrfViewMiddleware.

  4. CsrfViewMiddleware verifies the Origin header, if provided by the browser, against the current host and the CSRF_TRUSTED_ORIGINS setting. This provides protection against cross-subdomain attacks.

  5. In addition, for HTTPS requests, if the Origin header isn't provided, CsrfViewMiddleware performs strict referer checking. This means that even if a subdomain can set or modify cookies on your domain, it can't force a user to post to your application since that request won't come from your own exact domain.

    This also addresses a man-in-the-middle attack that's possible under HTTPS when using a session independent secret, due to the fact that HTTP Set-Cookie headers are (unfortunately) accepted by clients even when they are talking to a site under HTTPS. (Referer checking is not done for HTTP requests because the presence of the Referer header isn't reliable enough under HTTP.)

    If the CSRF_COOKIE_DOMAIN setting is set, the referer is compared against it. You can allow cross-subdomain requests by including a leading dot. For example, CSRF_COOKIE_DOMAIN = '.example.com' will allow POST requests from www.example.com and api.example.com. If the setting is not set, then the referer must match the HTTP Host header.

    Expanding the accepted referers beyond the current host or cookie domain can be done with the CSRF_TRUSTED_ORIGINS setting.

New in Django 4.0:

Origin checking was added, as described above.

This ensures that only forms that have originated from trusted domains can be used to POST data back.

It deliberately ignores GET requests (and other requests that are defined as 'safe' by RFC 7231#section-4.2.1). These requests ought never to have any potentially dangerous side effects, and so a CSRF attack with a GET request ought to be harmless. RFC 7231#section-4.2.1 defines POST, PUT, and DELETE as 'unsafe', and all other methods are also assumed to be unsafe, for maximum protection.

The CSRF protection cannot protect against man-in-the-middle attacks, so use HTTPS with HTTP Strict Transport Security. It also assumes validation of the HOST header and that there aren't any cross-site scripting vulnerabilities on your site (because XSS vulnerabilities already let an attacker do anything a CSRF vulnerability allows and much worse).

Removing the Referer header

To avoid disclosing the referrer URL to third-party sites, you might want to disable the referer on your site's <a> tags. For example, you might use the <meta name="referrer" content="no-referrer"> tag or include the Referrer-Policy: no-referrer header. Due to the CSRF protection's strict referer checking on HTTPS requests, those techniques cause a CSRF failure on requests with 'unsafe' methods. Instead, use alternatives like <a rel="noreferrer" ...>" for links to third-party sites.

Caching

If the csrf_token template tag is used by a template (or the get_token function is called some other way), CsrfViewMiddleware will add a cookie and a Vary: Cookie header to the response. This means that the middleware will play well with the cache middleware if it is used as instructed (UpdateCacheMiddleware goes before all other middleware).

However, if you use cache decorators on individual views, the CSRF middleware will not yet have been able to set the Vary header or the CSRF cookie, and the response will be cached without either one. In this case, on any views that will require a CSRF token to be inserted you should use the django.views.decorators.csrf.csrf_protect() decorator first:

from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect

@cache_page(60 * 15)
@csrf_protect
def my_view(request):
    ...

クラスベースのビューを使っている場合は、 Decorating class-based views を参照してください。

テスト

The CsrfViewMiddleware will usually be a big hindrance to testing view functions, due to the need for the CSRF token which must be sent with every POST request. For this reason, Django's HTTP client for tests has been modified to set a flag on requests which relaxes the middleware and the csrf_protect decorator so that they no longer rejects requests. In every other respect (e.g. sending cookies etc.), they behave the same.

If, for some reason, you want the test client to perform CSRF checks, you can create an instance of the test client that enforces CSRF checks:

>>> from django.test import Client
>>> csrf_client = Client(enforce_csrf_checks=True)

制限事項

Subdomains within a site will be able to set cookies on the client for the whole domain. By setting the cookie and using a corresponding token, subdomains will be able to circumvent the CSRF protection. The only way to avoid this is to ensure that subdomains are controlled by trusted users (or, are at least unable to set cookies). Note that even without CSRF, there are other vulnerabilities, such as session fixation, that make giving subdomains to untrusted parties a bad idea, and these vulnerabilities cannot easily be fixed with current browsers.

Edge cases

Certain views can have unusual requirements that mean they don't fit the normal pattern envisaged here. A number of utilities can be useful in these situations. The scenarios they might be needed in are described in the following section.

Utilities

The examples below assume you are using function-based views. If you are working with class-based views, you can refer to Decorating class-based views.

csrf_exempt(view)

This decorator marks a view as being exempt from the protection ensured by the middleware. Example:

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')
requires_csrf_token(view)

Normally the csrf_token template tag will not work if CsrfViewMiddleware.process_view or an equivalent like csrf_protect has not run. The view decorator requires_csrf_token can be used to ensure the template tag does work. This decorator works similarly to csrf_protect, but never rejects an incoming request.

実装例:

from django.shortcuts import render
from django.views.decorators.csrf import requires_csrf_token

@requires_csrf_token
def my_view(request):
    c = {}
    # ...
    return render(request, "a_template.html", c)

This decorator forces a view to send the CSRF cookie.

Scenarios

CSRF protection should be disabled for just a few views

Most views requires CSRF protection, but a few do not.

Solution: rather than disabling the middleware and applying csrf_protect to all the views that need it, enable the middleware and use csrf_exempt().

CsrfViewMiddleware.process_view not used

There are cases when CsrfViewMiddleware.process_view may not have run before your view is run - 404 and 500 handlers, for example - but you still need the CSRF token in a form.

Solution: use requires_csrf_token()

Unprotected view needs the CSRF token

There may be some views that are unprotected and have been exempted by csrf_exempt, but still need to include the CSRF token.

Solution: use csrf_exempt() followed by requires_csrf_token(). (i.e. requires_csrf_token should be the innermost decorator).

View needs protection for one path

A view needs CSRF protection under one set of conditions only, and mustn't have it for the rest of the time.

Solution: use csrf_exempt() for the whole view function, and csrf_protect() for the path within it that needs protection. Example:

from django.views.decorators.csrf import csrf_exempt, csrf_protect

@csrf_exempt
def my_view(request):

    @csrf_protect
    def protected_path(request):
        do_something()

    if some_condition():
       return protected_path(request)
    else:
       do_something_else()

Page uses AJAX without any HTML form

A page makes a POST request via AJAX, and the page does not have an HTML form with a csrf_token that would cause the required CSRF cookie to be sent.

Solution: use ensure_csrf_cookie() on the view that sends the page.

Contrib and reusable apps

Because it is possible for the developer to turn off the CsrfViewMiddleware, all relevant views in contrib apps use the csrf_protect decorator to ensure the security of these applications against CSRF. It is recommended that the developers of other reusable apps that want the same guarantees also use the csrf_protect decorator on their views.

Frequently Asked Questions

Is posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?

No, this is by design. Without a man-in-the-middle attack, there is no way for an attacker to send a CSRF token cookie to a victim's browser, so a successful attack would need to obtain the victim's browser's cookie via XSS or similar, in which case an attacker usually doesn't need CSRF attacks.

Some security audit tools flag this as a problem but as mentioned before, an attacker cannot steal a user's browser's CSRF cookie. "Stealing" or modifying your own token using Firebug, Chrome dev tools, etc. isn't a vulnerability.

Is it a problem that Django's CSRF protection isn't linked to a session by default?

No, this is by design. Not linking CSRF protection to a session allows using the protection on sites such as a pastebin that allow submissions from anonymous users which don't have a session.

If you wish to store the CSRF token in the user's session, use the CSRF_USE_SESSIONS setting.

Why might a user encounter a CSRF validation failure after logging in?

For security reasons, CSRF tokens are rotated each time a user logs in. Any page with a form generated before a login will have an old, invalid CSRF token and need to be reloaded. This might happen if a user uses the back button after a login or if they log in a different browser tab.