security.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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:: text
  25. <style class={{ var }}>...</style>
  26. .. highlighting as html+django fails due to intentionally missing quotes.
  27. If ``var`` is set to ``'class1 onmouseover=javascript:func()'``, this can result
  28. in unauthorized JavaScript execution, depending on how the browser renders
  29. imperfect HTML. (Quoting the attribute value would fix this case.)
  30. It is also important to be particularly careful when using ``is_safe`` with
  31. custom template tags, the :tfilter:`safe` template tag, :mod:`mark_safe
  32. <django.utils.safestring>`, and when autoescape is turned off.
  33. In addition, if you are using the template system to output something other
  34. than HTML, there may be entirely separate characters and words which require
  35. escaping.
  36. You should also be very careful when storing HTML in the database, especially
  37. when that HTML is retrieved and displayed.
  38. Cross site request forgery (CSRF) protection
  39. ============================================
  40. CSRF attacks allow a malicious user to execute actions using the credentials
  41. of another user without that user's knowledge or consent.
  42. Django has built-in protection against most types of CSRF attacks, providing you
  43. have :ref:`enabled and used it <using-csrf>` where appropriate. However, as with
  44. any mitigation technique, there are limitations. For example, it is possible to
  45. disable the CSRF module globally or for particular views. You should only do
  46. this if you know what you are doing. There are other :ref:`limitations
  47. <csrf-limitations>` if your site has subdomains that are outside of your
  48. control.
  49. :ref:`CSRF protection works <how-csrf-works>` by checking for a secret in each
  50. POST request. This ensures that a malicious user cannot simply "replay" a form
  51. POST to your website and have another logged in user unwittingly submit that
  52. form. The malicious user would have to know the secret, which is user specific
  53. (using a cookie).
  54. When deployed with :ref:`HTTPS <security-recommendation-ssl>`,
  55. ``CsrfViewMiddleware`` will check that the HTTP referer header is set to a
  56. URL on the same origin (including subdomain and port). Because HTTPS
  57. provides additional security, it is imperative to ensure connections use HTTPS
  58. where it is available by forwarding insecure connection requests and using
  59. HSTS for supported browsers.
  60. Be very careful with marking views with the ``csrf_exempt`` decorator unless
  61. it is absolutely necessary.
  62. .. _sql-injection-protection:
  63. SQL injection protection
  64. ========================
  65. SQL injection is a type of attack where a malicious user is able to execute
  66. arbitrary SQL code on a database. This can result in records
  67. being deleted or data leakage.
  68. By using Django's querysets, the resulting SQL will be properly escaped by
  69. the underlying database driver. However, Django also gives developers power to
  70. write :ref:`raw queries <executing-raw-queries>` or execute
  71. :ref:`custom sql <executing-custom-sql>`. These capabilities should be used
  72. sparingly and you should always be careful to properly escape any parameters
  73. that the user can control. In addition, you should exercise caution when using
  74. :meth:`~django.db.models.query.QuerySet.extra` and
  75. :class:`~django.db.models.expressions.RawSQL`.
  76. Clickjacking protection
  77. =======================
  78. Clickjacking is a type of attack where a malicious site wraps another site
  79. in a frame. This attack can result in an unsuspecting user being tricked
  80. into performing unintended actions on the target site.
  81. Django contains :ref:`clickjacking protection <clickjacking-prevention>` in
  82. the form of the
  83. :mod:`X-Frame-Options middleware <django.middleware.clickjacking.XFrameOptionsMiddleware>`
  84. which in a supporting browser can prevent a site from being rendered inside
  85. a frame. It is possible to disable the protection on a per view basis
  86. or to configure the exact header value sent.
  87. The middleware is strongly recommended for any site that does not need to have
  88. its pages wrapped in a frame by third party sites, or only needs to allow that
  89. for a small section of the site.
  90. .. _security-recommendation-ssl:
  91. SSL/HTTPS
  92. =========
  93. It is always better for security to deploy your site behind HTTPS. Without
  94. this, it is possible for malicious network users to sniff authentication
  95. credentials or any other information transferred between client and server, and
  96. in some cases -- **active** network attackers -- to alter data that is sent in
  97. either direction.
  98. If you want the protection that HTTPS provides, and have enabled it on your
  99. server, there are some additional steps you may need:
  100. * If necessary, set :setting:`SECURE_PROXY_SSL_HEADER`, ensuring that you have
  101. understood the warnings there thoroughly. Failure to do this can result
  102. in CSRF vulnerabilities, and failure to do it correctly can also be
  103. dangerous!
  104. * Set :setting:`SECURE_SSL_REDIRECT` to ``True``, so that requests over HTTP
  105. are redirected to HTTPS.
  106. Please note the caveats under :setting:`SECURE_PROXY_SSL_HEADER`. For the
  107. case of a reverse proxy, it may be easier or more secure to configure the
  108. main Web server to do the redirect to HTTPS.
  109. * Use 'secure' cookies.
  110. If a browser connects initially via HTTP, which is the default for most
  111. browsers, it is possible for existing cookies to be leaked. For this reason,
  112. you should set your :setting:`SESSION_COOKIE_SECURE` and
  113. :setting:`CSRF_COOKIE_SECURE` settings to ``True``. This instructs the browser
  114. to only send these cookies over HTTPS connections. Note that this will mean
  115. that sessions will not work over HTTP, and the CSRF protection will prevent
  116. any POST data being accepted over HTTP (which will be fine if you are
  117. redirecting all HTTP traffic to HTTPS).
  118. * Use :ref:`http-strict-transport-security` (HSTS)
  119. HSTS is an HTTP header that informs a browser that all future connections
  120. to a particular site should always use HTTPS. Combined with redirecting
  121. requests over HTTP to HTTPS, this will ensure that connections always enjoy
  122. the added security of SSL provided one successful connection has occurred.
  123. HSTS may either be configured with :setting:`SECURE_HSTS_SECONDS`,
  124. :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`, and :setting:`SECURE_HSTS_PRELOAD`,
  125. or on the Web server.
  126. .. _host-headers-virtual-hosting:
  127. Host header validation
  128. ======================
  129. Django uses the ``Host`` header provided by the client to construct URLs in
  130. certain cases. While these values are sanitized to prevent Cross Site Scripting
  131. attacks, a fake ``Host`` value can be used for Cross-Site Request Forgery,
  132. cache poisoning attacks, and poisoning links in emails.
  133. Because even seemingly-secure web server configurations are susceptible to fake
  134. ``Host`` headers, Django validates ``Host`` headers against the
  135. :setting:`ALLOWED_HOSTS` setting in the
  136. :meth:`django.http.HttpRequest.get_host()` method.
  137. This validation only applies via :meth:`~django.http.HttpRequest.get_host()`;
  138. if your code accesses the ``Host`` header directly from ``request.META`` you
  139. are bypassing this security protection.
  140. For more details see the full :setting:`ALLOWED_HOSTS` documentation.
  141. .. warning::
  142. Previous versions of this document recommended configuring your web server to
  143. ensure it validates incoming HTTP ``Host`` headers. While this is still
  144. recommended, in many common web servers a configuration that seems to
  145. validate the ``Host`` header may not in fact do so. For instance, even if
  146. Apache is configured such that your Django site is served from a non-default
  147. virtual host with the ``ServerName`` set, it is still possible for an HTTP
  148. request to match this virtual host and supply a fake ``Host`` header. Thus,
  149. Django now requires that you set :setting:`ALLOWED_HOSTS` explicitly rather
  150. than relying on web server configuration.
  151. Additionally, Django requires you to explicitly enable support for the
  152. ``X-Forwarded-Host`` header (via the :setting:`USE_X_FORWARDED_HOST` setting)
  153. if your configuration requires it.
  154. Session security
  155. ================
  156. Similar to the :ref:`CSRF limitations <csrf-limitations>` requiring a site to
  157. be deployed such that untrusted users don't have access to any subdomains,
  158. :mod:`django.contrib.sessions` also has limitations. See :ref:`the session
  159. topic guide section on security <topics-session-security>` for details.
  160. .. _user-uploaded-content-security:
  161. User-uploaded content
  162. =====================
  163. .. note::
  164. Consider :ref:`serving static files from a cloud service or CDN
  165. <staticfiles-from-cdn>` to avoid some of these issues.
  166. * If your site accepts file uploads, it is strongly advised that you limit
  167. these uploads in your Web server configuration to a reasonable
  168. size in order to prevent denial of service (DOS) attacks. In Apache, this
  169. can be easily set using the LimitRequestBody_ directive.
  170. * If you are serving your own static files, be sure that handlers like Apache's
  171. ``mod_php``, which would execute static files as code, are disabled. You don't
  172. want users to be able to execute arbitrary code by uploading and requesting a
  173. specially crafted file.
  174. * Django's media upload handling poses some vulnerabilities when that media is
  175. served in ways that do not follow security best practices. Specifically, an
  176. HTML file can be uploaded as an image if that file contains a valid PNG
  177. header followed by malicious HTML. This file will pass verification of the
  178. library that Django uses for :class:`~django.db.models.ImageField` image
  179. processing (Pillow). When this file is subsequently displayed to a
  180. user, it may be displayed as HTML depending on the type and configuration of
  181. your web server.
  182. No bulletproof technical solution exists at the framework level to safely
  183. validate all user uploaded file content, however, there are some other steps
  184. you can take to mitigate these attacks:
  185. 1. One class of attacks can be prevented by always serving user uploaded
  186. content from a distinct top-level or second-level domain. This prevents
  187. any exploit blocked by `same-origin policy`_ protections such as cross
  188. site scripting. For example, if your site runs on ``example.com``, you
  189. would want to serve uploaded content (the :setting:`MEDIA_URL` setting)
  190. from something like ``usercontent-example.com``. It's *not* sufficient to
  191. serve content from a subdomain like ``usercontent.example.com``.
  192. 2. Beyond this, applications may choose to define a whitelist of allowable
  193. file extensions for user uploaded files and configure the web server
  194. to only serve such files.
  195. .. _same-origin policy: https://en.wikipedia.org/wiki/Same-origin_policy
  196. .. _additional-security-topics:
  197. Additional security topics
  198. ==========================
  199. While Django provides good security protection out of the box, it is still
  200. important to properly deploy your application and take advantage of the
  201. security protection of the Web server, operating system and other components.
  202. * Make sure that your Python code is outside of the Web server's root. This
  203. will ensure that your Python code is not accidentally served as plain text
  204. (or accidentally executed).
  205. * Take care with any :ref:`user uploaded files <file-upload-security>`.
  206. * Django does not throttle requests to authenticate users. To protect against
  207. brute-force attacks against the authentication system, you may consider
  208. deploying a Django plugin or Web server module to throttle these requests.
  209. * Keep your :setting:`SECRET_KEY` a secret.
  210. * It is a good idea to limit the accessibility of your caching system and
  211. database using a firewall.
  212. * Take a look at the Open Web Application Security Project (OWASP) `Top 10
  213. list`_ which identifies some common vulnerabilities in web applications. While
  214. Django has tools to address some of the issues, other issues must be
  215. accounted for in the design of your project.
  216. .. _LimitRequestBody: https://httpd.apache.org/docs/2.4/mod/core.html#limitrequestbody
  217. .. _Top 10 list: https://www.owasp.org/index.php/Top_10_2013-Top_10