Debian Codegraph @

docs/topics/security.txt

raw
1 ==================
2 Security in Django
3 ==================
4
5 This document is an overview of Django's security features. It includes advice
6 on securing a Django-powered site.
7
8 .. _sanitize-user-input:
9
10 Always sanitize user input
11 ==========================
12
13 The golden rule of web application security is to never trust user-controlled
14 data. Hence, all user input should be sanitized before being used in your
15 application. See the :doc:`forms documentation </topics/forms/index>` for
16 details on validating user inputs in Django.
17
18 .. _cross-site-scripting:
19
20 Cross site scripting (XSS) protection
21 =====================================
22
23 XSS attacks allow a user to inject client side scripts into the browsers of
24 other users. This is usually achieved by storing the malicious scripts in the
25 database where it will be retrieved and displayed to other users, or by getting
26 users to click a link which will cause the attacker's JavaScript to be executed
27 by the user's browser. However, XSS attacks can originate from any untrusted
28 source of data, such as cookies or web services, whenever the data is not
29 sufficiently sanitized before including in a page.
30
31 Using Django templates protects you against the majority of XSS attacks.
32 However, it is important to understand what protections it provides
33 and its limitations.
34
35 Django templates :ref:`escape specific characters <automatic-html-escaping>`
36 which are particularly dangerous to HTML. While this protects users from most
37 malicious input, it is not entirely foolproof. For example, it will not
38 protect the following:
39
40 .. code-block:: text
41
42 <style class={{ var }}>...</style>
43
44 .. highlighting as html+django fails due to intentionally missing quotes.
45
46 If ``var`` is set to ``'class1 onmouseover=javascript:func()'``, this can result
47 in unauthorized JavaScript execution, depending on how the browser renders
48 imperfect HTML. (Quoting the attribute value would fix this case.)
49
50 It is also important to be particularly careful when using ``is_safe`` with
51 custom template tags, the :tfilter:`safe` template tag, :mod:`mark_safe
52 <django.utils.safestring>`, and when autoescape is turned off.
53
54 In addition, if you are using the template system to output something other
55 than HTML, there may be entirely separate characters and words which require
56 escaping.
57
58 You should also be very careful when storing HTML in the database, especially
59 when that HTML is retrieved and displayed.
60
61
62 Cross site request forgery (CSRF) protection
63 ============================================
64
65 CSRF attacks allow a malicious user to execute actions using the credentials
66 of another user without that user's knowledge or consent.
67
68 Django has built-in protection against most types of CSRF attacks, providing you
69 have :ref:`enabled and used it <using-csrf>` where appropriate. However, as with
70 any mitigation technique, there are limitations. For example, it is possible to
71 disable the CSRF module globally or for particular views. You should only do
72 this if you know what you are doing. There are other :ref:`limitations
73 <csrf-limitations>` if your site has subdomains that are outside of your
74 control.
75
76 :ref:`CSRF protection works <how-csrf-works>` by checking for a secret in each
77 POST request. This ensures that a malicious user cannot "replay" a form POST to
78 your website and have another logged-in user unwittingly submit that form. The
79 malicious user would have to know the secret, which is user specific (using a
80 cookie).
81
82 When deployed with :ref:`HTTPS <security-recommendation-ssl>`,
83 ``CsrfViewMiddleware`` will check that the HTTP referer header is set to a
84 URL on the same origin (including subdomain and port). Because HTTPS
85 provides additional security, it is imperative to ensure connections use HTTPS
86 where it is available by forwarding insecure connection requests and using
87 HSTS for supported browsers.
88
89 Be very careful with marking views with the ``csrf_exempt`` decorator unless
90 it is absolutely necessary.
91
92 .. _sql-injection-protection:
93
94 SQL injection protection
95 ========================
96
97 SQL injection is a type of attack where a malicious user is able to execute
98 arbitrary SQL code on a database. This can result in records
99 being deleted or data leakage.
100
101 Django's querysets are protected from SQL injection since their queries are
102 constructed using query parameterization. A query's SQL code is defined
103 separately from the query's parameters. Since parameters may be user-provided
104 and therefore unsafe, they are escaped by the underlying database driver.
105
106 Django also gives developers power to write :ref:`raw queries
107 <executing-raw-queries>` or execute :ref:`custom sql <executing-custom-sql>`.
108 These capabilities should be used sparingly and you should always be careful to
109 properly escape any parameters that the user can control. In addition, you
110 should exercise caution when using :meth:`~django.db.models.query.QuerySet.extra`
111 and :class:`~django.db.models.expressions.RawSQL`.
112
113 Clickjacking protection
114 =======================
115
116 Clickjacking is a type of attack where a malicious site wraps another site
117 in a frame. This attack can result in an unsuspecting user being tricked
118 into performing unintended actions on the target site.
119
120 Django contains :ref:`clickjacking protection <clickjacking-prevention>` in
121 the form of the
122 :mod:`X-Frame-Options middleware <django.middleware.clickjacking.XFrameOptionsMiddleware>`
123 which in a supporting browser can prevent a site from being rendered inside
124 a frame. It is possible to disable the protection on a per view basis
125 or to configure the exact header value sent.
126
127 The middleware is strongly recommended for any site that does not need to have
128 its pages wrapped in a frame by third party sites, or only needs to allow that
129 for a small section of the site.
130
131 .. _security-recommendation-ssl:
132
133 SSL/HTTPS
134 =========
135
136 It is always better for security to deploy your site behind HTTPS. Without
137 this, it is possible for malicious network users to sniff authentication
138 credentials or any other information transferred between client and server, and
139 in some cases -- **active** network attackers -- to alter data that is sent in
140 either direction.
141
142 If you want the protection that HTTPS provides, and have enabled it on your
143 server, there are some additional steps you may need:
144
145 * If necessary, set :setting:`SECURE_PROXY_SSL_HEADER`, ensuring that you have
146 understood the warnings there thoroughly. Failure to do this can result
147 in CSRF vulnerabilities, and failure to do it correctly can also be
148 dangerous!
149
150 * Set :setting:`SECURE_SSL_REDIRECT` to ``True``, so that requests over HTTP
151 are redirected to HTTPS.
152
153 Please note the caveats under :setting:`SECURE_PROXY_SSL_HEADER`. For the
154 case of a reverse proxy, it may be easier or more secure to configure the
155 main web server to do the redirect to HTTPS.
156
157 * Use 'secure' cookies.
158
159 If a browser connects initially via HTTP, which is the default for most
160 browsers, it is possible for existing cookies to be leaked. For this reason,
161 you should set your :setting:`SESSION_COOKIE_SECURE` and
162 :setting:`CSRF_COOKIE_SECURE` settings to ``True``. This instructs the browser
163 to only send these cookies over HTTPS connections. Note that this will mean
164 that sessions will not work over HTTP, and the CSRF protection will prevent
165 any POST data being accepted over HTTP (which will be fine if you are
166 redirecting all HTTP traffic to HTTPS).
167
168 * Use :ref:`http-strict-transport-security` (HSTS)
169
170 HSTS is an HTTP header that informs a browser that all future connections
171 to a particular site should always use HTTPS. Combined with redirecting
172 requests over HTTP to HTTPS, this will ensure that connections always enjoy
173 the added security of SSL provided one successful connection has occurred.
174 HSTS may either be configured with :setting:`SECURE_HSTS_SECONDS`,
175 :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`, and :setting:`SECURE_HSTS_PRELOAD`,
176 or on the web server.
177
178 .. _host-headers-virtual-hosting:
179
180 Host header validation
181 ======================
182
183 Django uses the ``Host`` header provided by the client to construct URLs in
184 certain cases. While these values are sanitized to prevent Cross Site Scripting
185 attacks, a fake ``Host`` value can be used for Cross-Site Request Forgery,
186 cache poisoning attacks, and poisoning links in emails.
187
188 Because even seemingly-secure web server configurations are susceptible to fake
189 ``Host`` headers, Django validates ``Host`` headers against the
190 :setting:`ALLOWED_HOSTS` setting in the
191 :meth:`django.http.HttpRequest.get_host()` method.
192
193 This validation only applies via :meth:`~django.http.HttpRequest.get_host()`;
194 if your code accesses the ``Host`` header directly from ``request.META`` you
195 are bypassing this security protection.
196
197 For more details see the full :setting:`ALLOWED_HOSTS` documentation.
198
199 .. warning::
200
201 Previous versions of this document recommended configuring your web server to
202 ensure it validates incoming HTTP ``Host`` headers. While this is still
203 recommended, in many common web servers a configuration that seems to
204 validate the ``Host`` header may not in fact do so. For instance, even if
205 Apache is configured such that your Django site is served from a non-default
206 virtual host with the ``ServerName`` set, it is still possible for an HTTP
207 request to match this virtual host and supply a fake ``Host`` header. Thus,
208 Django now requires that you set :setting:`ALLOWED_HOSTS` explicitly rather
209 than relying on web server configuration.
210
211 Additionally, Django requires you to explicitly enable support for the
212 ``X-Forwarded-Host`` header (via the :setting:`USE_X_FORWARDED_HOST` setting)
213 if your configuration requires it.
214
215 Referrer policy
216 ===============
217
218 Browsers use the ``Referer`` header as a way to send information to a site
219 about how users got there. By setting a *Referrer Policy* you can help to
220 protect the privacy of your users, restricting under which circumstances the
221 ``Referer`` header is set. See :ref:`the referrer policy section of the
222 security middleware reference <referrer-policy>` for details.
223
224 Cross-origin opener policy
225 ==========================
226
227 The cross-origin opener policy (COOP) header allows browsers to isolate a
228 top-level window from other documents by putting them in a different context
229 group so that they cannot directly interact with the top-level window. If a
230 document protected by COOP opens a cross-origin popup window, the popup’s
231 ``window.opener`` property will be ``null``. COOP protects against cross-origin
232 attacks. See :ref:`the cross-origin opener policy section of the security
233 middleware reference <cross-origin-opener-policy>` for details.
234
235 Session security
236 ================
237
238 Similar to the :ref:`CSRF limitations <csrf-limitations>` requiring a site to
239 be deployed such that untrusted users don't have access to any subdomains,
240 :mod:`django.contrib.sessions` also has limitations. See :ref:`the session
241 topic guide section on security <topics-session-security>` for details.
242
243 .. _user-uploaded-content-security:
244
245 User-uploaded content
246 =====================
247
248 .. note::
249 Consider :ref:`serving static files from a cloud service or CDN
250 <staticfiles-from-cdn>` to avoid some of these issues.
251
252 * If your site accepts file uploads, it is strongly advised that you limit
253 these uploads in your web server configuration to a reasonable
254 size in order to prevent denial of service (DOS) attacks. In Apache, this
255 can be easily set using the LimitRequestBody_ directive.
256
257 * If you are serving your own static files, be sure that handlers like Apache's
258 ``mod_php``, which would execute static files as code, are disabled. You don't
259 want users to be able to execute arbitrary code by uploading and requesting a
260 specially crafted file.
261
262 * Django's media upload handling poses some vulnerabilities when that media is
263 served in ways that do not follow security best practices. Specifically, an
264 HTML file can be uploaded as an image if that file contains a valid PNG
265 header followed by malicious HTML. This file will pass verification of the
266 library that Django uses for :class:`~django.db.models.ImageField` image
267 processing (Pillow). When this file is subsequently displayed to a
268 user, it may be displayed as HTML depending on the type and configuration of
269 your web server.
270
271 No bulletproof technical solution exists at the framework level to safely
272 validate all user uploaded file content, however, there are some other steps
273 you can take to mitigate these attacks:
274
275 #. One class of attacks can be prevented by always serving user uploaded
276 content from a distinct top-level or second-level domain. This prevents
277 any exploit blocked by `same-origin policy`_ protections such as cross
278 site scripting. For example, if your site runs on ``example.com``, you
279 would want to serve uploaded content (the :setting:`MEDIA_URL` setting)
280 from something like ``usercontent-example.com``. It's *not* sufficient to
281 serve content from a subdomain like ``usercontent.example.com``.
282
283 #. Beyond this, applications may choose to define a list of allowable
284 file extensions for user uploaded files and configure the web server
285 to only serve such files.
286
287 .. _same-origin policy: https://en.wikipedia.org/wiki/Same-origin_policy
288
289 .. _additional-security-topics:
290
291 Additional security topics
292 ==========================
293
294 While Django provides good security protection out of the box, it is still
295 important to properly deploy your application and take advantage of the
296 security protection of the web server, operating system and other components.
297
298 * Make sure that your Python code is outside of the web server's root. This
299 will ensure that your Python code is not accidentally served as plain text
300 (or accidentally executed).
301 * Take care with any :ref:`user uploaded files <file-upload-security>`.
302 * Django does not throttle requests to authenticate users. To protect against
303 brute-force attacks against the authentication system, you may consider
304 deploying a Django plugin or web server module to throttle these requests.
305 * Keep your :setting:`SECRET_KEY`, and :setting:`SECRET_KEY_FALLBACKS` if in
306 use, secret.
307 * It is a good idea to limit the accessibility of your caching system and
308 database using a firewall.
309 * Take a look at the Open Web Application Security Project (OWASP) `Top 10
310 list`_ which identifies some common vulnerabilities in web applications. While
311 Django has tools to address some of the issues, other issues must be
312 accounted for in the design of your project.
313 * Mozilla discusses various topics regarding `web security`_. Their
314 pages also include security principles that apply to any system.
315
316 .. _LimitRequestBody: https://httpd.apache.org/docs/2.4/mod/core.html#limitrequestbody
317 .. _Top 10 list: https://owasp.org/Top10/
318 .. _web security: https://infosec.mozilla.org/guidelines/web_security.html