security.rst
This file
The walk stopped after 200 commits: lines older than 2b517a1 point at it.
Merge pull request #3668 from pallets/dependabot/pip/tox-3.16.1dependabot-preview[bot]before adoption2b517a1
lines 1–286why, one step back1Security Considerations2=======================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.. _security-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+jinja4041 <input value="{{ value }}">4243Why 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:: html4849 onmouseover=alert(document.cookie)5051When the user would then move with the mouse over the input, the cookie52would be presented to the user in an alert window. But instead of showing53the 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.5758There is one class of XSS issues that Jinja's escaping does not protect59against. 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.6869Cross-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.. _security-json: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. ::134135 response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'136137- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security138139.. _security-csp:140141Content 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::147148 response.headers['Content-Security-Policy'] = "default-src 'self'"149150- 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-Protection186187188.. _security-cookie:189190Set-Cookie options191~~~~~~~~~~~~~~~~~~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.200- ``SameSite`` restricts how cookies are sent with requests from201 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.205206::207208 app.config.update(209 SESSION_COOKIE_SECURE=True,210 SESSION_COOKIE_HTTPONLY=True,211 SESSION_COOKIE_SAMESITE='Lax',212 )213214 response.set_cookie('username', 'flask', secure=True, httponly=True, samesite='Lax')215216Specifying ``Expires`` or ``Max-Age`` options, will remove the cookie after217the 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)222223For 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. ::228229 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 ...240241Use :class:`itsdangerous.TimedSerializer` to sign and validate other cookie242values (or any values that need secure signatures).243244- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies245- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie246247.. _samesite_support: https://caniuse.com/#feat=same-site-cookie-attribute248249250HTTP 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_Pinning261262263Copy/Paste to Terminal264----------------------265266Hidden characters such as the backspace character (``\b``, ``^H``) can267cause text to render differently in HTML than how it is interpreted if268`pasted into a terminal <https://security.stackexchange.com/q/39118>`__.269270For example, ``import y\bose\bm\bi\bt\be\b`` renders as271``import yosemite`` in HTML, but the backspaces are applied when pasted272into a terminal, and it becomes ``import os``.273274If you expect users to copy and paste untrusted code from your site,275such as from comments posted by users on a technical blog, consider276applying extra filtering, such as replacing all ``\b`` characters.277278.. code-block:: python279280 body = body.replace("\b", "")281282Most modern terminals will warn about and remove hidden characters when283pasting, so this isn't strictly necessary. It's also possible to craft284dangerous commands in other ways that aren't possible to filter.285Depending on your site's use case, it may be good to show a warning286about copying code in general.