Skip to content
Myr

security.rst

This file

Path

docs/security.rst

260 lines · 9.8 KiB

Last changed by

Merge pull request #2607 from FadhelC/SameSite-cookie-featureDavid Lordbefore adoptione21abd9

History of this file

Take it

The walk stopped after 200 commits: lines older than 62406e6 point at it.

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 1–40why, one step back
1Security Considerations
2=======================34Web applications usually face all kinds of security problems and it's very5hard to get everything right. Flask tries to solve a few of these things6for you, but there are a couple more you have to take care of yourself.78.. _xss:910Cross-Site Scripting (XSS)11--------------------------1213Cross site scripting is the concept of injecting arbitrary HTML (and with14it JavaScript) into the context of a website. To remedy this, developers15have to properly escape text so that it cannot include arbitrary HTML16tags. For more information on that have a look at the Wikipedia article17on `Cross-Site Scripting18<https://en.wikipedia.org/wiki/Cross-site_scripting>`_.1920Flask configures Jinja2 to automatically escape all values unless21explicitly told otherwise. This should rule out all XSS problems caused22in templates, but there are still other places where you have to be23careful:2425- generating HTML without the help of Jinja226- calling :class:`~flask.Markup` on data submitted by users27- sending out HTML from uploaded files, never do that, use the28 ``Content-Disposition: attachment`` header to prevent that problem.29- sending out textfiles from uploaded files. Some browsers are using30 content-type guessing based on the first few bytes so users could31 trick a browser to execute HTML.3233Another thing that is very important are unquoted attributes. While34Jinja2 can protect you from XSS issues by escaping HTML, there is one35thing it cannot protect you from: XSS by attribute injection. To counter36this possible attack vector, be sure to always quote your attributes with37either double or single quotes when using Jinja expressions in them:3839.. sourcecode:: html+jinja40

Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993

line 41why, one step back
41 <input value="{{ value }}">

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 42–48why, one step back
42
43Why is this necessary? Because if you would not be doing that, an44attacker could easily inject custom JavaScript handlers. For example an45attacker could inject this piece of HTML+JavaScript:4647.. sourcecode:: html48

Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993

line 49why, one step back
49 onmouseover=alert(document.cookie)

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

line 50why, one step back
50

Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993

line 51why, one step back
51When the user would then move with the mouse over the input, the cookie

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 52–57why, one step back
52would be presented to the user in an alert window. But instead of showing
53the cookie to the user, a good attacker might also execute any other54JavaScript code. In combination with CSS injections the attacker might55even make the element fill out the entire page so that the user would56just have to have the mouse anywhere on the page to trigger the attack.57

Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993

lines 58–68why, one step back
58There is one class of XSS issues that Jinja's escaping does not protect
59against. The ``a`` tag's ``href`` attribute can contain a `javascript:` URI,60which the browser will execute when clicked if not secured properly.6162.. sourcecode:: html6364 <a href="{{ value }}">click here</a>65 <a href="javascript:alert('unsafe');">click here</a>6667To prevent this, you'll need to set the :ref:`security-csp` response header.68

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 69–134why, one step back
69Cross-Site Request Forgery (CSRF)
70---------------------------------7172Another big problem is CSRF. This is a very complex topic and I won't73outline it here in detail just mention what it is and how to theoretically74prevent it.7576If your authentication information is stored in cookies, you have implicit77state management. The state of "being logged in" is controlled by a78cookie, and that cookie is sent with each request to a page.79Unfortunately that includes requests triggered by 3rd party sites. If you80don't keep that in mind, some people might be able to trick your81application's users with social engineering to do stupid things without82them knowing.8384Say you have a specific URL that, when you sent ``POST`` requests to will85delete a user's profile (say ``http://example.com/user/delete``). If an86attacker now creates a page that sends a post request to that page with87some JavaScript they just have to trick some users to load that page and88their profiles will end up being deleted.8990Imagine you were to run Facebook with millions of concurrent users and91someone would send out links to images of little kittens. When users92would go to that page, their profiles would get deleted while they are93looking at images of fluffy cats.9495How can you prevent that? Basically for each request that modifies96content on the server you would have to either use a one-time token and97store that in the cookie **and** also transmit it with the form data.98After receiving the data on the server again, you would then have to99compare the two tokens and ensure they are equal.100101Why does Flask not do that for you? The ideal place for this to happen is102the form validation framework, which does not exist in Flask.103104.. _json-security:105106JSON Security107-------------108109In Flask 0.10 and lower, :func:`~flask.jsonify` did not serialize top-level110arrays to JSON. This was because of a security vulnerability in ECMAScript 4.111112ECMAScript 5 closed this vulnerability, so only extremely old browsers are113still vulnerable. All of these browsers have `other more serious114vulnerabilities115<https://github.com/pallets/flask/issues/248#issuecomment-59934857>`_, so116this behavior was changed and :func:`~flask.jsonify` now supports serializing117arrays.118119Security Headers120----------------121122Browsers recognize various response headers in order to control security. We123recommend reviewing each of the headers below for use in your application.124The `Flask-Talisman`_ extension can be used to manage HTTPS and the security125headers for you.126127.. _Flask-Talisman: https://github.com/GoogleCloudPlatform/flask-talisman128129HTTP Strict Transport Security (HSTS)130~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~131132Tells the browser to convert all HTTP requests to HTTPS, preventing133man-in-the-middle (MITM) attacks. ::134

Fix typo in docs (#2419)asmith26before adoption8e2ef5b

line 135why, one step back
135 response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 136–138why, one step back
136
137- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security138

Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993

lines 139–140why, one step back
139.. _security-csp:
140

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 141–147why, one step back
141Content Security Policy (CSP)
142~~~~~~~~~~~~~~~~~~~~~~~~~~~~~143144Tell the browser where it can load various types of resource from. This header145should be used whenever possible, but requires some work to define the correct146policy for your site. A very strict policy would be::147

Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993

line 148why, one step back
148 response.headers['Content-Security-Policy'] = "default-src 'self'"

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 149–186why, one step back
149
150- https://csp.withgoogle.com/docs/index.html151- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy152153X-Content-Type-Options154~~~~~~~~~~~~~~~~~~~~~~155156Forces the browser to honor the response content type instead of trying to157detect it, which can be abused to generate a cross-site scripting (XSS)158attack. ::159160 response.headers['X-Content-Type-Options'] = 'nosniff'161162- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options163164X-Frame-Options165~~~~~~~~~~~~~~~166167Prevents external sites from embedding your site in an ``iframe``. This168prevents a class of attacks where clicks in the outer frame can be translated169invisibly to clicks on your page's elements. This is also known as170"clickjacking". ::171172 response.headers['X-Frame-Options'] = 'SAMEORIGIN'173174- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options175176X-XSS-Protection177~~~~~~~~~~~~~~~~178179The browser will try to prevent reflected XSS attacks by not loading the page180if the request contains something that looks like JavaScript and the response181contains the same data. ::182183 response.headers['X-XSS-Protection'] = '1; mode=block'184185- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection186

Merge pull request #2607 from FadhelC/SameSite-cookie-featureDavid Lordbefore adoptione21abd9

lines 187–189why, one step back
187
188.. _security-cookie:189

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 190–199why, one step back
190Set-Cookie options
191~~~~~~~~~~~~~~~~~~192193These options can be added to a ``Set-Cookie`` header to improve their194security. Flask has configuration options to set these on the session cookie.195They can be set on other cookies too.196197- ``Secure`` limits cookies to HTTPS traffic only.198- ``HttpOnly`` protects the contents of cookies from being read with199 JavaScript.

Merge pull request #2607 from FadhelC/SameSite-cookie-featureDavid Lordbefore adoptione21abd9

lines 200–204why, one step back
200- ``SameSite`` restricts how cookies are sent with requests from
201 external sites. Can be set to ``'Lax'`` (recommended) or ``'Strict'``.202 ``Lax`` prevents sending cookies with CSRF-prone requests from203 external sites, such as submitting a form. ``Strict`` prevents sending204 cookies with all external requests, including following regular links.

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 205–210why, one step back
205
206::207208 app.config.update(209 SESSION_COOKIE_SECURE=True,210 SESSION_COOKIE_HTTPONLY=True,

Merge pull request #2607 from FadhelC/SameSite-cookie-featureDavid Lordbefore adoptione21abd9

line 211why, one step back
211 SESSION_COOKIE_SAMESITE='Lax',

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 212–213why, one step back
212 )
213

Merge pull request #2607 from FadhelC/SameSite-cookie-featureDavid Lordbefore adoptione21abd9

line 214why, one step back
214 response.set_cookie('username', 'flask', secure=True, httponly=True, samesite='Lax')

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

line 215why, one step back
215

mention that session signature checks max ageDavid Lordbefore adoption2efb565

lines 216–222why, one step back
216Specifying ``Expires`` or ``Max-Age`` options, will remove the cookie after
217the given time, or the current time plus the age, respectively. If neither218option is set, the cookie will be removed when the browser is closed. ::219220 # cookie expires after 10 minutes221 response.set_cookie('snakes', '3', max_age=600)222

fix linksDavid Lordbefore adoption97ad085

lines 223–227why, one step back
223For the session cookie, if :attr:`session.permanent <flask.session.permanent>`
224is set, then :data:`PERMANENT_SESSION_LIFETIME` is used to set the expiration.225Flask's default cookie implementation validates that the cryptographic226signature is not older than this value. Lowering this value may help mitigate227replay attacks, where intercepted cookies can be sent at a later time. ::

mention that session signature checks max ageDavid Lordbefore adoption2efb565

lines 228–240why, one step back
228
229 app.config.update(230 PERMANENT_SESSION_LIFETIME=600231 )232233 @app.route('/login', methods=['POST'])234 def login():235 ...236 session.clear()237 session['user_id'] = user.id238 session.permanent = True239 ...240

fix linksDavid Lordbefore adoption97ad085

lines 241–242why, one step back
241Use :class:`itsdangerous.TimedSerializer` to sign and validate other cookie
242values (or any values that need secure signatures).

mention that session signature checks max ageDavid Lordbefore adoption2efb565

lines 243–245why, one step back
243
244- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies245- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie

Merge pull request #2607 from FadhelC/SameSite-cookie-featureDavid Lordbefore adoptione21abd9

lines 246–248why, one step back
246
247.. _samesite_support: https://caniuse.com/#feat=same-site-cookie-attribute248

Merge pull request #2352 from davidism/json-object-hookDavid Lordbefore adoption62406e6

lines 249–260why, one step back
249
250HTTP Public Key Pinning (HPKP)251~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~252253This tells the browser to authenticate with the server using only the specific254certificate key to prevent MITM attacks.255256.. warning::257 Be careful when enabling this, as it is very difficult to undo if you set up258 or upgrade your key incorrectly.259260- https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning