security.rst
This file
Path
docs/security.rst
274 lines · 10.5 KiB
Last changed by
Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689
History of this fileTake it
The walk stopped after 200 commits: lines older than 93a7f08 point at it.
pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 1–25why, 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 Jinja2Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689
line 26why, one step back26- calling :class:`~markupsafe.Markup` on data submitted by userspin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 27–274why, one step back27- 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-Options175176.. _security-cookie:177178Set-Cookie options179~~~~~~~~~~~~~~~~~~180181These options can be added to a ``Set-Cookie`` header to improve their182security. Flask has configuration options to set these on the session cookie.183They can be set on other cookies too.184185- ``Secure`` limits cookies to HTTPS traffic only.186- ``HttpOnly`` protects the contents of cookies from being read with187 JavaScript.188- ``SameSite`` restricts how cookies are sent with requests from189 external sites. Can be set to ``'Lax'`` (recommended) or ``'Strict'``.190 ``Lax`` prevents sending cookies with CSRF-prone requests from191 external sites, such as submitting a form. ``Strict`` prevents sending192 cookies with all external requests, including following regular links.193194::195196 app.config.update(197 SESSION_COOKIE_SECURE=True,198 SESSION_COOKIE_HTTPONLY=True,199 SESSION_COOKIE_SAMESITE='Lax',200 )201202 response.set_cookie('username', 'flask', secure=True, httponly=True, samesite='Lax')203204Specifying ``Expires`` or ``Max-Age`` options, will remove the cookie after205the given time, or the current time plus the age, respectively. If neither206option is set, the cookie will be removed when the browser is closed. ::207208 # cookie expires after 10 minutes209 response.set_cookie('snakes', '3', max_age=600)210211For the session cookie, if :attr:`session.permanent <flask.session.permanent>`212is set, then :data:`PERMANENT_SESSION_LIFETIME` is used to set the expiration.213Flask's default cookie implementation validates that the cryptographic214signature is not older than this value. Lowering this value may help mitigate215replay attacks, where intercepted cookies can be sent at a later time. ::216217 app.config.update(218 PERMANENT_SESSION_LIFETIME=600219 )220221 @app.route('/login', methods=['POST'])222 def login():223 ...224 session.clear()225 session['user_id'] = user.id226 session.permanent = True227 ...228229Use :class:`itsdangerous.TimedSerializer` to sign and validate other cookie230values (or any values that need secure signatures).231232- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies233- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie234235.. _samesite_support: https://caniuse.com/#feat=same-site-cookie-attribute236237238HTTP Public Key Pinning (HPKP)239~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~240241This tells the browser to authenticate with the server using only the specific242certificate key to prevent MITM attacks.243244.. warning::245 Be careful when enabling this, as it is very difficult to undo if you set up246 or upgrade your key incorrectly.247248- https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning249250251Copy/Paste to Terminal252----------------------253254Hidden characters such as the backspace character (``\b``, ``^H``) can255cause text to render differently in HTML than how it is interpreted if256`pasted into a terminal <https://security.stackexchange.com/q/39118>`__.257258For example, ``import y\bose\bm\bi\bt\be\b`` renders as259``import yosemite`` in HTML, but the backspaces are applied when pasted260into a terminal, and it becomes ``import os``.261262If you expect users to copy and paste untrusted code from your site,263such as from comments posted by users on a technical blog, consider264applying extra filtering, such as replacing all ``\b`` characters.265266.. code-block:: python267268 body = body.replace("\b", "")269270Most modern terminals will warn about and remove hidden characters when271pasting, so this isn't strictly necessary. It's also possible to craft272dangerous commands in other ways that aren't possible to filter.273Depending on your site's use case, it may be good to show a warning274about copying code in general.