security.txt 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. ==================
  2. Security in Django
  3. ==================
  4. This document is an overview of Django's security features. It includes advice
  5. on securing a Django-powered site.
  6. .. _cross-site-scripting:
  7. Cross site scripting (XSS) protection
  8. =====================================
  9. .. highlightlang:: html+django
  10. XSS attacks allow a user to inject client side scripts into the browsers of
  11. other users. This is usually achieved by storing the malicious scripts in the
  12. database where it will be retrieved and displayed to other users, or by getting
  13. users to click a link which will cause the attacker's JavaScript to be executed
  14. by the user's browser. However, XSS attacks can originate from any untrusted
  15. source of data, such as cookies or Web services, whenever the data is not
  16. sufficiently sanitized before including in a page.
  17. Using Django templates protects you against the majority of XSS attacks.
  18. However, it is important to understand what protections it provides
  19. and its limitations.
  20. Django templates :ref:`escape specific characters <automatic-html-escaping>`
  21. which are particularly dangerous to HTML. While this protects users from most
  22. malicious input, it is not entirely foolproof. For example, it will not
  23. protect the following:
  24. .. code-block:: html+django
  25. <style class={{ var }}>...</style>
  26. If ``var`` is set to ``'class1 onmouseover=javascript:func()'``, this can result
  27. in unauthorized JavaScript execution, depending on how the browser renders
  28. imperfect HTML.
  29. It is also important to be particularly careful when using ``is_safe`` with
  30. custom template tags, the :ttag:`safe` template tag, :mod:`mark_safe
  31. <django.utils.safestring>`, and when autoescape is turned off.
  32. In addition, if you are using the template system to output something other
  33. than HTML, there may be entirely separate characters and words which require
  34. escaping.
  35. You should also be very careful when storing HTML in the database, especially
  36. when that HTML is retrieved and displayed.
  37. Markup library
  38. --------------
  39. If you use :mod:`django.contrib.markup`, you need to ensure that the filters are
  40. only used on trusted input, or that you have correctly configured them to ensure
  41. they do not allow raw HTML output. See the documentation of that module for more
  42. information.
  43. Cross site request forgery (CSRF) protection
  44. ============================================
  45. CSRF attacks allow a malicious user to execute actions using the credentials
  46. of another user without that user's knowledge or consent.
  47. Django has built-in protection against most types of CSRF attacks, providing you
  48. have :ref:`enabled and used it <using-csrf>` where appropriate. However, as with
  49. any mitigation technique, there are limitations. For example, it is possible to
  50. disable the CSRF module globally or for particular views. You should only do
  51. this if you know what you are doing. There are other :ref:`limitations
  52. <csrf-limitations>` if your site has subdomains that are outside of your
  53. control.
  54. :ref:`CSRF protection works <how-csrf-works>` by checking for a nonce in each
  55. POST request. This ensures that a malicious user cannot simply "replay" a form
  56. POST to your Web site and have another logged in user unwittingly submit that
  57. form. The malicious user would have to know the nonce, which is user specific
  58. (using a cookie).
  59. When deployed with :ref:`HTTPS <security-recommendation-ssl>`,
  60. ``CsrfViewMiddleware`` will check that the HTTP referer header is set to a
  61. URL on the same origin (including subdomain and port). Because HTTPS
  62. provides additional security, it is imperative to ensure connections use HTTPS
  63. where it is available by forwarding insecure connection requests and using
  64. HSTS for supported browsers.
  65. Be very careful with marking views with the ``csrf_exempt`` decorator unless
  66. it is absolutely necessary.
  67. SQL injection protection
  68. ========================
  69. SQL injection is a type of attack where a malicious user is able to execute
  70. arbitrary SQL code on a database. This can result in records
  71. being deleted or data leakage.
  72. By using Django's querysets, the resulting SQL will be properly escaped by
  73. the underlying database driver. However, Django also gives developers power to
  74. write :ref:`raw queries <executing-raw-queries>` or execute
  75. :ref:`custom sql <executing-custom-sql>`. These capabilities should be used
  76. sparingly and you should always be careful to properly escape any parameters
  77. that the user can control. In addition, you should exercise caution when using
  78. :meth:`extra() <django.db.models.query.QuerySet.extra>`.
  79. Clickjacking protection
  80. =======================
  81. Clickjacking is a type of attack where a malicious site wraps another site
  82. in a frame. This attack can result in an unsuspecting user being tricked
  83. into performing unintended actions on the target site.
  84. Django contains :ref:`clickjacking protection <clickjacking-prevention>` in
  85. the form of the
  86. :mod:`X-Frame-Options middleware <django.middleware.clickjacking.XFrameOptionsMiddleware>`
  87. which in a supporting browser can prevent a site from being rendered inside
  88. a frame. It is possible to disable the protection on a per view basis
  89. or to configure the exact header value sent.
  90. The middleware is strongly recommended for any site that does not need to have
  91. its pages wrapped in a frame by third party sites, or only needs to allow that
  92. for a small section of the site.
  93. .. _security-recommendation-ssl:
  94. SSL/HTTPS
  95. =========
  96. It is always better for security, though not always practical in all cases, to
  97. deploy your site behind HTTPS. Without this, it is possible for malicious
  98. network users to sniff authentication credentials or any other information
  99. transferred between client and server, and in some cases -- **active** network
  100. attackers -- to alter data that is sent in either direction.
  101. If you want the protection that HTTPS provides, and have enabled it on your
  102. server, there are some additional steps you may need:
  103. * If necessary, set :setting:`SECURE_PROXY_SSL_HEADER`, ensuring that you have
  104. understood the warnings there thoroughly. Failure to do this can result
  105. in CSRF vulnerabilities, and failure to do it correctly can also be
  106. dangerous!
  107. * Set up redirection so that requests over HTTP are redirected to HTTPS.
  108. This could be done using a custom middleware. Please note the caveats under
  109. :setting:`SECURE_PROXY_SSL_HEADER`. For the case of a reverse proxy, it may be
  110. easier or more secure to configure the main Web server to do the redirect to
  111. HTTPS.
  112. * Use 'secure' cookies.
  113. If a browser connects initially via HTTP, which is the default for most
  114. browsers, it is possible for existing cookies to be leaked. For this reason,
  115. you should set your :setting:`SESSION_COOKIE_SECURE` and
  116. :setting:`CSRF_COOKIE_SECURE` settings to ``True``. This instructs the browser
  117. to only send these cookies over HTTPS connections. Note that this will mean
  118. that sessions will not work over HTTP, and the CSRF protection will prevent
  119. any POST data being accepted over HTTP (which will be fine if you are
  120. redirecting all HTTP traffic to HTTPS).
  121. * Use HTTP Strict Transport Security (HSTS)
  122. HSTS is an HTTP header that informs a browser that all future connections
  123. to a particular site should always use HTTPS. Combined with redirecting
  124. requests over HTTP to HTTPS, this will ensure that connections always enjoy
  125. the added security of SSL provided one successful connection has occurred.
  126. HSTS is usually configured on the web server.
  127. .. _host-headers-virtual-hosting:
  128. Host headers and virtual hosting
  129. ================================
  130. Django uses the ``Host`` header provided by the client to construct URLs
  131. in certain cases. While these values are sanitized to prevent Cross
  132. Site Scripting attacks, they can be used for Cross-Site Request
  133. Forgery and cache poisoning attacks in some circumstances. We
  134. recommend you ensure your Web server is configured such that:
  135. * It always validates incoming HTTP ``Host`` headers against the expected
  136. host name.
  137. * Disallows requests with no ``Host`` header.
  138. * Is *not* configured with a catch-all virtual host that forwards requests
  139. to a Django application.
  140. Additionally, as of 1.3.1, Django requires you to explicitly enable support for
  141. the ``X-Forwarded-Host`` header if your configuration requires it.
  142. .. _additional-security-topics:
  143. Additional security topics
  144. ==========================
  145. While Django provides good security protection out of the box, it is still
  146. important to properly deploy your application and take advantage of the
  147. security protection of the Web server, operating system and other components.
  148. * Make sure that your Python code is outside of the Web server's root. This
  149. will ensure that your Python code is not accidentally served as plain text
  150. (or accidentally executed).
  151. * Take care with any :ref:`user uploaded files <file-upload-security>`.
  152. * Django does not throttle requests to authenticate users. To protect against
  153. brute-force attacks against the authentication system, you may consider
  154. deploying a Django plugin or Web server module to throttle these requests.
  155. * If your site accepts file uploads, it is strongly advised that you limit
  156. these uploads in your Web server configuration to a reasonable
  157. size in order to prevent denial of service (DOS) attacks. In Apache, this
  158. can be easily set using the LimitRequestBody_ directive.
  159. * Keep your :setting:`SECRET_KEY` a secret.
  160. * It is a good idea to limit the accessibility of your caching system and
  161. database using a firewall.
  162. .. _LimitRequestBody: http://httpd.apache.org/docs/2.2/mod/core.html#limitrequestbody