• 3.2
  • 5.0
  • 6.1
  • Версия документации: 3.1

Подделка межсайтового запроса (CSRF)

Промежуточное программное обеспечение CSRF и тег шаблона обеспечивают простую в использовании защиту от подделок межсайтовых запросов. Этот тип атаки происходит, когда вредоносный веб-сайт содержит ссылку, кнопку формы или какой-либо код JavaScript, предназначенный для выполнения определенного действия на вашем веб-сайте с использованием учетных данных вошедшего в систему пользователя, который посещает вредоносный сайт в своем браузере. Также рассматривается родственный тип атаки, «login CSRF», когда атакующий сайт обманом заставляет браузер пользователя войти на сайт с чужим учетными данными.

The first defense against CSRF attacks is to ensure that GET requests (and other „safe“ methods, as defined by RFC 7231 Section 4.2.1) are side effect free. Requests via „unsafe“ methods, such as POST, PUT, and DELETE, can then be protected by following the steps below.

Как это использовать

To take advantage of CSRF protection in your views, follow these steps:

  1. The CSRF middleware is activated by default in the MIDDLEWARE setting. If you override that setting, remember that 'django.middleware.csrf.CsrfViewMiddleware' should come before any view middleware that assume that CSRF attacks have been dealt with.

    If you disabled it, which is not recommended, you can use csrf_protect() on particular views you want to protect (see below).

  2. In any template that uses a POST form, use the csrf_token tag inside the <form> element if the form is for an internal URL, e.g.:

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

    This should not be done for POST forms that target external URLs, since that would cause the CSRF token to be leaked, leading to a vulnerability.

  3. In the corresponding view functions, ensure that RequestContext is used to render the response so that {% csrf_token %} will work properly. If you’re using the render() function, generic views, or contrib apps, you are covered already since these all use RequestContext.

AJAX

While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header (as specified by the CSRF_HEADER_NAME setting) to the value of the CSRF token. This is often easier because many JavaScript frameworks provide hooks that allow headers to be set on every request.

First, you must get the CSRF token. How to do that depends on whether or not the CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY settings are enabled.

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 */,
    {headers: {'X-CSRFToken': csrftoken}}
);
fetch(request, {
    method: 'POST',
    mode: 'same-origin'  // Do not send CSRF token to another domain.
}).then(function(response) {
    // ...
});

Using CSRF in Jinja2 templates

Django’s Jinja2 template backend adds {{ csrf_input }} to the context of all templates which is equivalent to {% csrf_token %} in the Django template language. For example:

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

The decorator method

Rather than adding CsrfViewMiddleware as a blanket protection, you can use the csrf_protect decorator, which has exactly the same functionality, on particular views that need the protection. It must be used both on views that insert the CSRF token in the output, and on those that accept the POST form data. (These are often the same view function, but not always).

Use of the decorator by itself is not recommended, since if you forget to use it, you will have a security hole. The „belt and braces“ strategy of using both is fine, and will incur minimal overhead.

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)

If you are using class-based views, you can refer to Decorating class-based views.

Rejected requests

By default, a „403 Forbidden“ response is sent to the user if an incoming request fails the checks performed by CsrfViewMiddleware. This should usually only be seen when there is a genuine Cross Site Request Forgery, or when, due to a programming error, the CSRF token has not been included with a POST form.

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.

Как это работает

CSRF базируется на следующих вещах:

  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. Все HTTP запросы, которые не GET, HEAD, OPTIONS или TRACE, должны содержать CSRF куку, и поле „csrfmiddlewaretoken“ с правильным значением. Иначе пользователь получит 403 ошибку.

    При проверке значения поля csrfmiddlewaretoken сравнивается только секрет, а не полный токен, с секретом в значении файла cookie. Это позволяет использовать постоянно меняющиеся токены. Хотя каждый запрос может использовать свой собственный токен, секрет остается общим для всех.

    Эта проверка выполняется в CsrfViewMiddleware.

  4. In addition, for HTTPS requests, strict referer checking is done by CsrfViewMiddleware. 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.

    В дополнение для HTTPS запросов в CsrfViewMiddleware проверяется «referer»(источник запроса). Это необходимо для предотвращения MITM-атаки(Man-In-The-Middle), которая возможна при использовании HTTPS и токена не привязанного к сессии, т.к. клиенты принимают(к сожалению) HTTP заголовок „Set-Cookie“, несмотря на то, что коммуникация с сервером происходит через HTTPS. (Такая проверка не выполняется для HTTP запросов т.к. «Referer» заголовок легко подменить при использовании HTTP.)

    Если установлен параметр CSRF_COOKIE_DOMAIN, референт сравнивается с ним. Вы можете разрешить запросы между поддоменами, включив точку в начале. Например, CSRF_COOKIE_DOMAIN = .example.com разрешит запросы POST от www.example.com и api.example.com. Если параметр не установлен, то реферер должен соответствовать заголовку HTTP Host.

    Чтобы расширить список доступных доменов, кроме текущего хоста и домена кук, используйте CSRF_TRUSTED_ORIGINS.

Такой подход гарантирует, что только формы, отправленные с доверенных доменов, могут передавать POST данные.

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.

Защита CSRF не может защитить от атак «человек посередине», поэтому используйте HTTPS с HTTP Strict Transport Security. Он также предполагает проверку заголовка HOST и отсутствие уязвимостей межсайтового скриптинга на вашем сайте (поскольку XSS-уязвимости уже позволяют злоумышленнику делать все, что позволяет уязвимость CSRF, и даже хуже).

Удаление заголовка «Referer»

Чтобы избежать раскрытия URL-адреса реферера сторонним сайтам, вы можете захотеть отключить реферер`_ в тегах ``<a> вашего сайта. Например, вы можете использовать тег <meta name="referrer" content="no-referrer"> или включить заголовок Referrer-Policy: no-referrer. Из-за строгой проверки ссылок защиты CSRF на запросах HTTPS эти методы вызывают сбой CSRF на запросах с «небезопасными» методами. Вместо этого используйте альтернативы, такие как <a rel="noreferrer" ...>" для ссылок на сторонние сайты.

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):
    ...

If you are using class-based views, you can refer to 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)

Ограничения

Субдомены на сайте смогут устанавливать файлы cookie на клиенте для всего домена. Установив файл cookie и используя соответствующий токен, субдомены смогут обойти защиту CSRF. Единственный способ избежать этого — убедиться, что субдомены контролируются доверенными пользователями (или, по крайней мере, не могут устанавливать файлы cookie). Обратите внимание, что даже без CSRF существуют другие уязвимости, такие как фиксация сеанса, из-за которых передача поддоменов ненадежным сторонам является плохой идеей, и эти уязвимости невозможно легко исправить с помощью текущих браузеров.

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.

Утилиты

Примеры ниже предполагают, чтобы используете представления-функции. Если вы используете представления-классы, обратитесь к этому разделу.

csrf_exempt(view)

Этот декоратор позволяет исключить представление из процесса проверки CSRF. Например:

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)

Обычно шаблонный тег csrf_token ничего не делает, если CsrfViewMiddleware.process_view, или его аналог csrf_protect, не был выполнен. Декоратор requires_csrf_token можно использовать, чтобы удостовериться, что шаблонный тег сработал. Этот декоратор работает как и csrf_protect, но не возвращает ответ с ошибкой.

Например:

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)

Этот декоратор заставляет представление послать CSRF куку.

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.

Настройки

Параметры, которые могут быть использованы для управления поведением CSRF в Django:

Часто задаваемые вопросы

Является ли публикация произвольной пары токенов CSRF (файлов cookie и данных POST) уязвимостью?

Нет, это задумано. Без атаки «человек посередине» злоумышленник не сможет отправить файл cookie токена CSRF в браузер жертвы, поэтому для успешной атаки потребуется получить файл cookie браузера жертвы через XSS или аналогичный вариант, и в этом случае злоумышленнику обычно не нужны CSRF-атаки.

Некоторые инструменты аудита безопасности отмечают это как проблему, но, как упоминалось ранее, злоумышленник не может украсть CSRF-файл cookie браузера пользователя. «Кража» или изменение вашего токена с помощью Firebug, инструментов разработки Chrome и т. д. не является уязвимостью.

Проблема в том, что CSRF-защита Django по умолчанию не связана с сеансом?

Нет, это задумано. Отсутствие привязки защиты CSRF к сеансу позволяет использовать защиту на таких сайтах, как pastebin, которые позволяют отправлять сообщения анонимным пользователям, у которых нет сеанса.

Если вы хотите сохранить токен CSRF в сеансе пользователя, используйте настройку CSRF_USE_SESSIONS.

Почему пользователь может столкнуться с ошибкой проверки CSRF после входа в систему?

По соображениям безопасности токены CSRF меняются каждый раз, когда пользователь входит в систему. Любая страница с формой, созданной до входа в систему, будет иметь старый, недействительный токен CSRF, и ее необходимо будет перезагрузить. Это может произойти, если пользователь использует кнопку «Назад» после входа в систему или входит в другую вкладку браузера.

Back to Top