Perlindungan Cross Site Request Forgery

The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries. This type of attack occurs when a malicious website contains a link, a form button or some JavaScript that is intended to perform some action on your website, using the credentials of a logged-in user who visits the malicious site in their browser. A related type of attack, 'login CSRF', where an attacking site tricks a user's browser into logging into a site with someone else's credentials, is also covered.

The first defense against CSRF attacks is to ensure that GET requests (and other 'safe' methods, as defined by RFC 9110#section-9.2.1) are side effect free. Requests via 'unsafe' methods, such as POST, PUT, and DELETE, can then be protected by the steps outlined in Bagaimana menggunakan perlindungan CSRF Django.

Bagaimana itu bekerja

Perlindungan CSRF berdasarkan pada hal-hal berikut:

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

    CsrfViewMiddleware sends this cookie with the response whenever django.middleware.csrf.get_token() is called. It can also send it in other cases. 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.

    In order to protect against BREACH attacks, the value of this field is not simply the secret. It is scrambled differently with each response using a mask. The mask is generated randomly on every call to get_token(), so the form field value is different each time.

    Bagian selesai dengan etiket cetakan.

  3. Untuk semua permintaan datang yang tidak menggunakan HTTP GET, HEAD, OPTIONS atau TRACE, kue CSRF harus hadir, dan bidang 'csrfmiddlewaretoken' harus hadir dan benar. Jika itu tidak, pengguna akan mendapatkan kesalahan 403.

    Ketika mengesahkan nilai bidang 'csrfmiddlewaretoken', hanya rahasia, bukan seluruhnya token, dibandingkan dengan rahasia dalam nilai kue. Ini mengizinkan penggunaan dari token selalu-berubah. Selagi setiap permintaan mungkin menggunakan token nya sendiri, rahasia tetap umum pada semua.

    Pemeriksaan ini selesai dengan 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.

    Ini juga membahas serangan seorang-dalam-tengah yang memungkinkan dibawah HTTPS ketika menggunakan sebuah rahasia berdiri sendiri sesi, dikarenakan kenyataan bahwa kepala Set-Cookie HTTP (sayangnya) diterima oleh klien bahkan ketika mereka sedang berbicara pada situs dibawah HTTPS. (Pemeriksaan perujuk belum dilakukan untuk permintaan HTTP karena kehadiran dari kepala Referer tidak cukup handal dibawah 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.

    Memperluas rujukan diterima diluar rumah saat ini atau ranah kue dapat diselesaikan dengan pengaturan CSRF_TRUSTED_ORIGINS.

Ini memastikan bahwa hanya formulir yang asli dari ranah terpercaya dapat digunakan untuk data POST kembali.

It deliberately ignores GET requests (and other requests that are defined as 'safe' by RFC 9110#section-9.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 9110#section-9.2.1 defines POST, PUT, and DELETE as 'unsafe', and all other methods are also assumed to be unsafe, for maximum protection.

Perlindungan CSRF tidak dapat melindungi terhadap serangan seorang-dalam-tengah, jadi gunakan HTTPS dengan HTTP Strict Transport Security. Itu juga menganggap validation of the HOST header dan yang tidak ada cross-site scripting vulnerabilities apapun pada situs anda (karena kerentanan XSS sudah membiarkan seorang penyerang melakukan apapun mengizinkan kerentanan CSRF dan lebih buruk lagi).

Memindahkan kepala Referer

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.

Batasan

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.

Keperluan

Contoh dibawah ini menganggap anda menggunakan tampilan berdasarkan-fungsi. Jika anda sedang bekerja dengan tampilan berdasarkan-kelas, anda dapat mengacu pada Decorating class-based views.

csrf_exempt(view)

Penghias ini menandai sebuah tampilan sebagai menjadi pengecualian dari perlinsungan dipastikan oleh middleware. Contoh:

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


@csrf_exempt
def my_view(request):
    return HttpResponse("Hello world")
Changed in Django 5.0:

Support for wrapping asynchronous view functions was added.

csrf_protect(view)

Penghias yang menyediakan perlindungan dari CsrfViewMiddleware ke sebuah tampilan.

Penggunaan:

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)
Changed in Django 5.0:

Support for wrapping asynchronous view functions was added.

requires_csrf_token(view)

Biasanya etiket cetakan csrf_token tidak akan bekerja jika CsrfViewMiddleware.process_view atauxsetara seperti csrf_protect belum berjalan. Tampilan penghias requires_csrf_token dapat digunakan untuk memastikan etiket cetakan tidak bekerja. Penghias ini bekerja mirip pada csrf_protect, tetapi tidak pernah menolak permintaan datang.

Contoh:

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)
Changed in Django 5.0:

Support for wrapping asynchronous view functions was added.

Penghias ini memaksa sebuah tampilan mengirim kue CSRF.

Changed in Django 5.0:

Support for wrapping asynchronous view functions was added.

Pertanyaan Sering Ditanya

Apakah memasang pasangan token CSRF berubah-ubah (kue dan data POST) sebuah kerentanan?

Tidak, ini adalah berdasarkan perancangan, Tanpa serangan orang-di-tengah, tidak ada cara untuk seorang penyerang mengirim sebuah kue token CSRF ke peramban korban, jadi sebuah serangan berhasil akan butuh mengambil kue peramban korban melalui XSS atau yang mirip, dimana soerang penyerang biasanya tidak butuh serangan CSRF.

Beberapa alat-alat pemeriksaan keamanan menandai ini sebagai sebuah masalah seperti disebutkan sebelumnya, seorang penyerang tidak dapat mencuri kue CSRF peramban pengguna. "Stealing" atau merubah token milik anda menggunakan Firebug, alat-alat pengembangan Chrome, dll. tidak rentan.

Apakah sebuah masalah bahwa perlindungan Django CSRF tidak berkaitan ke sebuah sesi secara awalan?

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.

Jika anda berharap menyimpan token CSRF dalam sesi pengguna, gunakan pengaturan CSRF_USE_SESSIONS.

Mengapa seorang pengguna menghadapi kegagalan pengesahan CSRF setelah masuk?

Untuk alasan keamanan, token CSRF diputar setiap kali pengguna masuk. Halaman apapun dengan sebuah formulir dibangkitkan sebelum masuk akan tua, token CSRF tidak sah dan butuh dimuat kembali. Ini mungkin terjadi jika seorang pengguna menggunakan tombol kembali setelah masuk atau jika mereka masuk dalam peramban berbeda.