Предотвращение атак CSRF
Межсайтовая подделка запроса – это разновидность вредоносного эксплойта, при котором неавторизованные команды выполняются от имени аутентифицированного пользователя. К счастью, Laravel позволяет легко защитить ваше приложение от Межсайтовой подделки запроса (Cross Site Request Forgery – CSRF).
Объяснение уязвимости
Если вы не знакомы с Межсайтовой подделкой запросов, то давайте обсудим пример того, как можно использовать эту уязвимость. Представьте, что ваше приложение имеет маршрут /user/email , который принимает POST -запрос для изменения адреса электронной почты аутентифицированного пользователя. Скорее всего, этот маршрут ожидает, что поле ввода email будет содержать адрес электронной почты, который пользователь хотел бы начать использовать.
Без защиты от CSRF вредоносный веб-сайт может создать HTML-форму, которая указывает на маршрут вашего приложения /user/email и отправляет собственный адрес электронной почты злоумышленника:
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>
Если вредоносный веб-сайт автоматически отправляет форму при загрузке страницы, злоумышленнику нужно только подтолкнуть ничего не подозревающего пользователя вашего приложения посетить свой веб-сайт, и его адрес электронной почты будет изменен в вашем приложении.
Чтобы предотвратить эту уязвимость, нам необходимо проверять каждый входящий запрос POST , PUT , PATCH , или DELETE на секретное значение сессии, к которому вредоносное приложение не может получить доступ.
Предотвращение запросов CSRF
Laravel автоматически генерирует «токен» CSRF для каждой активной пользовательской сессии, управляемой приложением. Этот токен используется для проверки того, что аутентифицированный пользователь действительно является лицом, выполняющим запросы к приложению. Поскольку этот токен хранится в сессии пользователя и изменяется каждый раз при повторном создании сессии, вредоносное приложение не может получить к нему доступ.
К CSRF-токену текущей сессии можно получить доступ через сессию запроса или с помощью глобального помощника csrf_token :
use Illuminate\Http\Request; Route::get('/token', function (Request $request) < $token = $request->session()->token(); $token = csrf_token(); // . >);
Каждый раз, когда вы создаете HTML-форму «POST», «PUT», «PATCH» или «DELETE» в своем приложении, вы должны включать в форму скрытое поле _token CSRF, чтобы посредник CSRF мог проверить запрос. Для удобства вы можете использовать директиву Blade @csrf для создания скрытого поля ввода, содержащего токен:
form method="POST" action="/profile"> @csrf input type="hidden" name="_token" value=">" /> form>
Посредник App\Http\Middleware\VerifyCsrfToken , который по умолчанию стоит в группе посредников web , автоматически проверяет соответствие токена во входном запросе и токен, хранящийся в сессии. Когда эти два токена совпадают, мы знаем, что запрос инициирует аутентифицированный пользователь.
CSRF-токены и SPA-приложения
Если вы создаете SPA, который использует Laravel в качестве серверной части API, вам следует обратиться к документации Laravel Sanctum для получения информации об аутентификации с помощью вашего API и защите от уязвимостей CSRF.
Исключение URI из защиты от CSRF
По желанию можно исключить набор URI из защиты от CSRF. Например, если вы используете Stripe для обработки платежей и используете их систему веб-хуков, вам нужно будет исключить маршрут обработчика веб-хуков Stripe из защиты от CSRF, поскольку Stripe не будет знать, какой токен CSRF отправить вашим маршрутам.
Как правило, вы должны размещать эти виды маршрутов вне группы посредников web , которую App\Providers\RouteServiceProvider применяет ко всем маршрутам в файле routes/web.php . Однако, вы также можете исключить маршруты, добавив их URI в свойство $except посредника VerifyCsrfToken :
namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; class VerifyCsrfToken extends Middleware < /** * URI, которые следует исключить из проверки CSRF. * * @var array */ protected $except = [ 'stripe/*', 'http://example.com/foo/bar', 'http://example.com/foo/*', ]; >
Для удобства посредник CSRF автоматически отключается для всех маршрутов при выполнении тестов.
Токен X-CSRF
В дополнение к проверке токена CSRF в качестве параметра POST-запроса посредник App\Http\Middleware\VerifyCsrfToken также проверяет заголовок запроса X-CSRF-TOKEN . Вы можете, например, сохранить токен в HTML-теге meta :
meta name="csrf-token" content=">">
Затем, вы можете указать библиотеке, такой как jQuery, автоматически добавлять токен во все заголовки запросов. Это обеспечивает простую и удобную защиту от CSRF для ваших приложений с использованием устаревшей технологии JavaScript на основе AJAX:
$.ajaxSetup(< headers: < 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') > >);
Токен X-XSRF
Laravel хранит текущий токен CSRF в зашифрованном файле Cookies XSRF-TOKEN , который содержится в каждом ответе, генерируемым фреймворком. Вы можете использовать значение Cookies для установки заголовка запроса X-XSRF-TOKEN .
Этот файл Cookies, в первую очередь, отправляется для удобства разработчика, поскольку некоторые фреймворки и библиотеки JavaScript, такие, как Angular и Axios, автоматически помещают его значение в заголовок X-XSRF-TOKEN в запросах с одним и тем же источником.
По умолчанию файл resources/js/bootstrap.js включает HTTP-библиотеку Axios, которая автоматически отправляет заголовок X-XSRF-TOKEN .
Русскоязычное комьюнити
- Группа в VK
- Телеграм LaravelRUS
- Телеграм Laravel для новичков
- Телеграм LaravelPro
Обучающие ресурсы
- Laracasts
- Codecourse
- Курс Дмитрия Елисеева
- Adam Wathan
Блоги разработчиков
- Laravel News
- Freek Van der Herten
- Brent Roose
- Marcel Pociot
Как правильно передать на сервер csrf-токен с content-type != текст
С обычным content-type=’Content-Type’ и «application/x-www-form-urlencoded» проблем нет. Но все мои попытки отправить на сервер с помощью FormData либо application/json терпят неудачу. Мои данные,сформированные в json имеют следующий вид:
Но в ответе от сервера я получаю ошибку 403 о неверном csrf. Я нашел рабочий пример для form-data с jquery тут, но я не использую jquery. И мне пока не ясен секрет. Пробовал выставлять заголовок как там:
xhr.setRequestHeader("X-CSRFToken",data['csrfmiddlewaretoken'])
В заголовках смотрел — токен установился — получил:
405 Method Not Allowed
То же самое и при попытке отправить formdata — с ней данные вообще принимают следующий вид:
——WebKitFormBoundarysH3gth4rOeR1r8Sr Content-Disposition: form-data; name=»csrfmiddlewaretoken» Qme9AMgGBEPitGdCn3I7LWkaEzPfcpy9CrDKrK5amgZLdpxzuHSY9uNNI450fHT5 ——WebKitFormBoundarysH3gth4rOeR1r8Sr Content-Disposition: form-data; name=»Title» ——WebKitFormBoundarysH3gth4rOeR1r8Sr Content-Disposition: form-data; name=»Content» ——WebKitFormBoundarysH3gth4rOeR1r8Sr—
По ссылке видел еще какой-то флаг processData: false , но в обычном XMLHttpRequest я такого метода не нашел. Кто-нибудь сталкивался с подобного рода задачами?
Send CSRF token to javascript
Suppose I maintain a anti CSRF token at server side in a session How am I supposed to pass the token to client side application if my form generation is going to be dynamic(i.e. form will be created after some action has been performed by javascript) Is there a way to pass the token to javascript so that I can inject the token in the form. One working way that I found is send a cookie to the browser containing the token which will be then extracted by javascript. Any suggestions?
asked Jan 26, 2015 at 20:19
Abhishek Agarwal Abhishek Agarwal
694 1 1 gold badge 9 9 silver badges 25 25 bronze badges
2 Answers 2
I would suggest starting out from a secure token, and then improving it through JavaScript according to dynamic form Creation.
Where the «value» parameter is generated on server-side when page loads.
And then you have a script like:
csrftoken = document.mainform.csrftoken.value; # Do something with the CSRF token, like add dynamic values, like sha256(csrftoken + "dynamicvalue"); document.mainform.csrftoken.value = csrftoken;
The main idea of this, is to prevent, that even if they manage to get a exploit that would allow a adverisary to read the JavaScript code, they still cannot make up a valid CSRF token, since they cannot read the original «csrftoken» value that was inside the form at page load. This can also be used to «chain» AJAX requests, like that you start out with the token X during page load. Then you transform it to Y using JavaScript, send it in a AJAX request. In the next AJAX request, you can use Y as base in the algoritm, to create Z, and send to the server. A attacker cannot gain access to X, thus they cannot either get access to Y neither Z, even if they would in some way be able to exploit running JavaScript code to reveal itself.
Note that page contents cannot be read by a adversiary due to Same origin policy. But Javascript can contain exploits that would make it possible to read the actual running JavaScript code. Theres no such exploits currently, but better be safe than sorry.
How to use Django’s CSRF protection¶
To take advantage of CSRF protection in your views, follow these steps:
- 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).
- In any template that uses a POST form, use the csrf_token tag inside the element if the form is for an internal URL, e.g.:
form method="post"> csrf_token %>
Using CSRF protection with 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.
Acquiring the token if CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY are False ¶
The recommended source for the token is the csrftoken cookie, which will be set if you’ve enabled CSRF protection for your views as outlined above.
The CSRF token cookie is named csrftoken by default, but you can control the cookie name via the CSRF_COOKIE_NAME setting.
You can acquire the token like this:
function getCookie(name) let cookieValue = null; if (document.cookie && document.cookie !== '') const cookies = document.cookie.split(';'); for (let i = 0; i cookies.length; i++) const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; > > > return cookieValue; > const csrftoken = getCookie('csrftoken');
The above code could be simplified by using the JavaScript Cookie library to replace getCookie :
const csrftoken = Cookies.get('csrftoken');
The CSRF token is also present in the DOM in a masked form, but only if explicitly included using csrf_token in a template. The cookie contains the canonical, unmasked token. The CsrfViewMiddleware will accept either. However, in order to protect against BREACH attacks, it’s recommended to use a masked token.
If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie() .
Acquiring the token if CSRF_USE_SESSIONS or CSRF_COOKIE_HTTPONLY is True ¶
If you activate CSRF_USE_SESSIONS or CSRF_COOKIE_HTTPONLY , you must include the CSRF token in your HTML and read the token from the DOM with JavaScript:
csrf_token %> script> const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; script>
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) // . >);
Using CSRF protection in Jinja2 templates¶
Django’s Jinja2 template backend adds > to the context of all templates which is equivalent to in the Django template language. For example:
form method="post"> <csrf_input >>
Using 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.
Handling 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.
Using CSRF protection with 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 .
Testing and CSRF protection¶
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)
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.
Disabling CSRF protection 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() .
Setting the token when CsrfViewMiddleware.process_view() is 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.
Including the CSRF token in an unprotected view¶
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).
Protecting a view for only 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()
Protecting a page that uses AJAX without an 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.
CSRF protection in reusable applications¶
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.
Additional Information
Support Django!
Contents
- How to use Django’s CSRF protection
- Using CSRF protection with AJAX
- Acquiring the token if CSRF_USE_SESSIONS and CSRF_COOKIE_HTTPONLY are False
- Acquiring the token if CSRF_USE_SESSIONS or CSRF_COOKIE_HTTPONLY is True
- Setting the token on the AJAX request
- Disabling CSRF protection for just a few views
- Setting the token when CsrfViewMiddleware.process_view() is not used
- Including the CSRF token in an unprotected view
- Protecting a view for only one path
- Protecting a page that uses AJAX without an HTML form
Browse
- Prev: Come autenticarsi usando REMOTE_USER
- Next: Come creare comandi django-admin personalizzati
- Table of contents
- Indice generale
- Indice del modulo Python
You are here:
- Django 4.1 documentation
- guide «How-to»
- How to use Django’s CSRF protection
Getting help
FAQ Try the FAQ — it’s got answers to many common questions. Index, Module Index, or Table of Contents Handy when looking for specific information. django-users mailing list Search for information in the archives of the django-users mailing list, or post a question. #django IRC channel Ask a question in the #django IRC channel, or search the IRC logs to see if it’s been asked before. Django Discord Server Join the Django Discord Community. Official Django Forum Join the community on the Django Forum. Ticket tracker Report bugs with Django or Django documentation in our ticket tracker.
Download:
Offline (Django 4.1): HTML | PDF | ePub
Provided by Read the Docs.
- guide «How-to»
- Using CSRF protection with AJAX
