web-security.rst
This file
Path
docs/web-security.rst
316 lines · 12.8 KiB
Last changed by
Merge branch 'stable'David Lordbefore adoption3301232
History of this fileTake it
Merge branch '3.0.x'David Lordbefore adoption6ab71ed
lines 1–3why, one step back1Security Considerations2=======================3add config and docs for limits (#5626)David Lordbefore adoption6f2014d
lines 4–40why, one step back4Web applications face many types of potential security problems, and it can be5hard to get everything right, or even to know what "right" is in general. Flask6tries to solve a few of these things by default, but there are other parts you7may have to take care of yourself. Many of these solutions are tradeoffs, and8will depend on each application's specific needs and threat model. Many hosting9platforms may take care of certain types of problems without the need for the10Flask application to handle them.1112Resource Use13------------1415A common category of attacks is "Denial of Service" (DoS or DDoS). This is a16very broad category, and different variants target different layers in a17deployed application. In general, something is done to increase how much18processing time or memory is used to handle each request, to the point where19there are not enough resources to handle legitimate requests.2021Flask provides a few configuration options to handle resource use. They can22also be set on individual requests to customize only that request. The23documentation for each goes into more detail.2425- :data:`MAX_CONTENT_LENGTH` or :attr:`.Request.max_content_length` controls26 how much data will be read from a request. It is not set by default,27 although it will still block truly unlimited streams unless the WSGI server28 indicates support.29- :data:`MAX_FORM_MEMORY_SIZE` or :attr:`.Request.max_form_memory_size`30 controls how large any non-file ``multipart/form-data`` field can be. It is31 set to 500kB by default.32- :data:`MAX_FORM_PARTS` or :attr:`.Request.max_form_parts` controls how many33 ``multipart/form-data`` fields can be parsed. It is set to 1000 by default.34 Combined with the default `max_form_memory_size`, this means that a form35 will occupy at most 500MB of memory.3637Regardless of these settings, you should also review what settings are available38from your operating system, container deployment (Docker etc), WSGI server, HTTP39server, and hosting platform. They typically have ways to set process resource40limits, timeouts, and other checks regardless of how Flask is configured.Merge branch '3.0.x'David Lordbefore adoption6ab71ed
lines 41–53why, one step back4142.. _security-xss:4344Cross-Site Scripting (XSS)45--------------------------4647Cross site scripting is the concept of injecting arbitrary HTML (and with48it JavaScript) into the context of a website. To remedy this, developers49have to properly escape text so that it cannot include arbitrary HTML50tags. For more information on that have a look at the Wikipedia article51on `Cross-Site Scripting52<https://en.wikipedia.org/wiki/Cross-site_scripting>`_.53Merge branch 'stable'David Lordbefore adoption3301232
line 54why, one step back54Flask configures Jinja to automatically escape all values unlessMerge branch '3.0.x'David Lordbefore adoption6ab71ed
lines 55–58why, one step back55explicitly told otherwise. This should rule out all XSS problems caused56in templates, but there are still other places where you have to be57careful:58Merge branch 'stable'David Lordbefore adoption3301232
line 59why, one step back59- generating HTML without the help of JinjaMerge branch '3.0.x'David Lordbefore adoption6ab71ed
lines 60–67why, one step back60- calling :class:`~markupsafe.Markup` on data submitted by users61- sending out HTML from uploaded files, never do that, use the62 ``Content-Disposition: attachment`` header to prevent that problem.63- sending out textfiles from uploaded files. Some browsers are using64 content-type guessing based on the first few bytes so users could65 trick a browser to execute HTML.6667Another thing that is very important are unquoted attributes. WhileMerge branch 'stable'David Lordbefore adoption3301232
line 68why, one step back68Jinja can protect you from XSS issues by escaping HTML, there is oneMerge branch '3.0.x'David Lordbefore adoption6ab71ed
lines 69–160why, one step back69thing it cannot protect you from: XSS by attribute injection. To counter70this possible attack vector, be sure to always quote your attributes with71either double or single quotes when using Jinja expressions in them:7273.. sourcecode:: html+jinja7475 <input value="{{ value }}">7677Why is this necessary? Because if you would not be doing that, an78attacker could easily inject custom JavaScript handlers. For example an79attacker could inject this piece of HTML+JavaScript:8081.. sourcecode:: html8283 onmouseover=alert(document.cookie)8485When the user would then move with the mouse over the input, the cookie86would be presented to the user in an alert window. But instead of showing87the cookie to the user, a good attacker might also execute any other88JavaScript code. In combination with CSS injections the attacker might89even make the element fill out the entire page so that the user would90just have to have the mouse anywhere on the page to trigger the attack.9192There is one class of XSS issues that Jinja's escaping does not protect93against. The ``a`` tag's ``href`` attribute can contain a `javascript:` URI,94which the browser will execute when clicked if not secured properly.9596.. sourcecode:: html9798 <a href="{{ value }}">click here</a>99 <a href="javascript:alert('unsafe');">click here</a>100101To prevent this, you'll need to set the :ref:`security-csp` response header.102103Cross-Site Request Forgery (CSRF)104---------------------------------105106Another big problem is CSRF. This is a very complex topic and I won't107outline it here in detail just mention what it is and how to theoretically108prevent it.109110If your authentication information is stored in cookies, you have implicit111state management. The state of "being logged in" is controlled by a112cookie, and that cookie is sent with each request to a page.113Unfortunately that includes requests triggered by 3rd party sites. If you114don't keep that in mind, some people might be able to trick your115application's users with social engineering to do stupid things without116them knowing.117118Say you have a specific URL that, when you sent ``POST`` requests to will119delete a user's profile (say ``http://example.com/user/delete``). If an120attacker now creates a page that sends a post request to that page with121some JavaScript they just have to trick some users to load that page and122their profiles will end up being deleted.123124Imagine you were to run Facebook with millions of concurrent users and125someone would send out links to images of little kittens. When users126would go to that page, their profiles would get deleted while they are127looking at images of fluffy cats.128129How can you prevent that? Basically for each request that modifies130content on the server you would have to either use a one-time token and131store that in the cookie **and** also transmit it with the form data.132After receiving the data on the server again, you would then have to133compare the two tokens and ensure they are equal.134135Why does Flask not do that for you? The ideal place for this to happen is136the form validation framework, which does not exist in Flask.137138.. _security-json:139140JSON Security141-------------142143In Flask 0.10 and lower, :func:`~flask.jsonify` did not serialize top-level144arrays to JSON. This was because of a security vulnerability in ECMAScript 4.145146ECMAScript 5 closed this vulnerability, so only extremely old browsers are147still vulnerable. All of these browsers have `other more serious148vulnerabilities149<https://github.com/pallets/flask/issues/248#issuecomment-59934857>`_, so150this behavior was changed and :func:`~flask.jsonify` now supports serializing151arrays.152153Security Headers154----------------155156Browsers recognize various response headers in order to control security. We157recommend reviewing each of the headers below for use in your application.158The `Flask-Talisman`_ extension can be used to manage HTTPS and the security159headers for you.160Merge branch 'stable'David Lordbefore adoption3301232
line 161why, one step back161.. _Flask-Talisman: https://github.com/wntrblm/flask-talismanMerge branch '3.0.x'David Lordbefore adoption6ab71ed
lines 162–269why, one step back162163HTTP Strict Transport Security (HSTS)164~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~165166Tells the browser to convert all HTTP requests to HTTPS, preventing167man-in-the-middle (MITM) attacks. ::168169 response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'170171- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security172173.. _security-csp:174175Content Security Policy (CSP)176~~~~~~~~~~~~~~~~~~~~~~~~~~~~~177178Tell the browser where it can load various types of resource from. This header179should be used whenever possible, but requires some work to define the correct180policy for your site. A very strict policy would be::181182 response.headers['Content-Security-Policy'] = "default-src 'self'"183184- https://csp.withgoogle.com/docs/index.html185- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy186187X-Content-Type-Options188~~~~~~~~~~~~~~~~~~~~~~189190Forces the browser to honor the response content type instead of trying to191detect it, which can be abused to generate a cross-site scripting (XSS)192attack. ::193194 response.headers['X-Content-Type-Options'] = 'nosniff'195196- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options197198X-Frame-Options199~~~~~~~~~~~~~~~200201Prevents external sites from embedding your site in an ``iframe``. This202prevents a class of attacks where clicks in the outer frame can be translated203invisibly to clicks on your page's elements. This is also known as204"clickjacking". ::205206 response.headers['X-Frame-Options'] = 'SAMEORIGIN'207208- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options209210.. _security-cookie:211212Set-Cookie options213~~~~~~~~~~~~~~~~~~214215These options can be added to a ``Set-Cookie`` header to improve their216security. Flask has configuration options to set these on the session cookie.217They can be set on other cookies too.218219- ``Secure`` limits cookies to HTTPS traffic only.220- ``HttpOnly`` protects the contents of cookies from being read with221 JavaScript.222- ``SameSite`` restricts how cookies are sent with requests from223 external sites. Can be set to ``'Lax'`` (recommended) or ``'Strict'``.224 ``Lax`` prevents sending cookies with CSRF-prone requests from225 external sites, such as submitting a form. ``Strict`` prevents sending226 cookies with all external requests, including following regular links.227228::229230 app.config.update(231 SESSION_COOKIE_SECURE=True,232 SESSION_COOKIE_HTTPONLY=True,233 SESSION_COOKIE_SAMESITE='Lax',234 )235236 response.set_cookie('username', 'flask', secure=True, httponly=True, samesite='Lax')237238Specifying ``Expires`` or ``Max-Age`` options, will remove the cookie after239the given time, or the current time plus the age, respectively. If neither240option is set, the cookie will be removed when the browser is closed. ::241242 # cookie expires after 10 minutes243 response.set_cookie('snakes', '3', max_age=600)244245For the session cookie, if :attr:`session.permanent <flask.session.permanent>`246is set, then :data:`PERMANENT_SESSION_LIFETIME` is used to set the expiration.247Flask's default cookie implementation validates that the cryptographic248signature is not older than this value. Lowering this value may help mitigate249replay attacks, where intercepted cookies can be sent at a later time. ::250251 app.config.update(252 PERMANENT_SESSION_LIFETIME=600253 )254255 @app.route('/login', methods=['POST'])256 def login():257 ...258 session.clear()259 session['user_id'] = user.id260 session.permanent = True261 ...262263Use :class:`itsdangerous.TimedSerializer` to sign and validate other cookie264values (or any values that need secure signatures).265266- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies267- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie268269.. _samesite_support: https://caniuse.com/#feat=same-site-cookie-attributeMerge branch 'stable'David Lordbefore adoption3301232
lines 270–290why, one step back270271272Host Header Validation273----------------------274275The ``Host`` header is used by the client to indicate what host name the request276was made to. This is used, for example, by ``url_for(..., _external=True)`` to277generate full URLs, for use in email or other messages outside the browser278window.279280By default the app doesn't know what host(s) it is allowed to be accessed281through, and assumes any host is valid. Although browsers do not allow setting282the ``Host`` header, requests made by attackers in other scenarios could set283the ``Host`` header to a value they want.284285When deploying your application, set :data:`TRUSTED_HOSTS` to restrict what286values the ``Host`` header may be.287288The ``Host`` header may be modified by proxies in between the client and your289application. See :doc:`deploying/proxy_fix` to tell your app which proxy values290to trust.Merge branch '3.0.x'David Lordbefore adoption6ab71ed
lines 291–316why, one step back291292293Copy/Paste to Terminal294----------------------295296Hidden characters such as the backspace character (``\b``, ``^H``) can297cause text to render differently in HTML than how it is interpreted if298`pasted into a terminal <https://security.stackexchange.com/q/39118>`__.299300For example, ``import y\bose\bm\bi\bt\be\b`` renders as301``import yosemite`` in HTML, but the backspaces are applied when pasted302into a terminal, and it becomes ``import os``.303304If you expect users to copy and paste untrusted code from your site,305such as from comments posted by users on a technical blog, consider306applying extra filtering, such as replacing all ``\b`` characters.307308.. code-block:: python309310 body = body.replace("\b", "")311312Most modern terminals will warn about and remove hidden characters when313pasting, so this isn't strictly necessary. It's also possible to craft314dangerous commands in other ways that aren't possible to filter.315Depending on your site's use case, it may be good to show a warning316about copying code in general.