security.rst
This file
Path
docs/security.rst
250 lines · 9.4 KiB
Last changed by
fix code blockDavid Lordbefore adoption1c35b98
History of this fileTake it
The walk stopped after 200 commits: lines older than afb613c point at it.
Added some missing documentation information.Armin Ronacherbefore adoptionafb613c
lines 1–17why, 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.. _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 Scriptingresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 18why, one step back18<https://en.wikipedia.org/wiki/Cross-site_scripting>`_.Added some missing documentation information.Armin Ronacherbefore adoptionafb613c
lines 19–27why, one step back1920Flask 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 theMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 28why, one step back28 ``Content-Disposition: attachment`` header to prevent that problem.Added some missing documentation information.Armin Ronacherbefore adoptionafb613c
lines 29–40why, one step back29- 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+jinja40Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993
line 41why, one step back41 <input value="{{ value }}">Added some missing documentation information.Armin Ronacherbefore adoptionafb613c
lines 42–48why, one step back4243Why 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:: html48Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993
line 49why, one step back49 onmouseover=alert(document.cookie)Added some missing documentation information.Armin Ronacherbefore adoptionafb613c
line 50why, one step back50Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993
line 51why, one step back51When the user would then move with the mouse over the input, the cookieAdded some missing documentation information.Armin Ronacherbefore adoptionafb613c
lines 52–57why, one step back52would 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.57Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993
lines 58–68why, one step back58There 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.68Added some missing documentation information.Armin Ronacherbefore adoptionafb613c
lines 69–83why, one step back69Cross-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.83Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
lines 84–85why, one step back84Say you have a specific URL that, when you sent ``POST`` requests to will85delete a user's profile (say ``http://example.com/user/delete``). If anAdded some missing documentation information.Armin Ronacherbefore adoptionafb613c
line 86why, one step back86attacker now creates a page that sends a post request to that page withresolve merge conflictsKenneth Reitzbefore adoption31174fe
line 87why, one step back87some JavaScript they just have to trick some users to load that page andAdded some missing documentation information.Armin Ronacherbefore adoptionafb613c
lines 88–108why, one step back88their 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-------------108resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 109–110why, one step back109In 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.Added some missing documentation information.Armin Ronacherbefore adoptionafb613c
line 111why, one step back111resolve merge conflictsKenneth Reitzbefore adoption31174fe
lines 112–117why, one step back112ECMAScript 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.Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
lines 118–121why, one step back118119Security Headers120----------------121clean up security header docsDavid Lordbefore adoption8eff9bd
lines 122–125why, one step back122Browsers 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.Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 126why, one step back126clean up security header docsDavid Lordbefore adoption8eff9bd
lines 127–128why, one step back127.. _Flask-Talisman: https://github.com/GoogleCloudPlatform/flask-talisman128Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 129why, one step back129HTTP Strict Transport Security (HSTS)clean up security header docsDavid Lordbefore adoption8eff9bd
line 130why, one step back130~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 131why, one step back131clean up security header docsDavid Lordbefore adoption8eff9bd
lines 132–133why, one step back132Tells the browser to convert all HTTP requests to HTTPS, preventing133man-in-the-middle (MITM) attacks. ::Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 134why, one step back134Fix typo in docs (#2419)asmith26before adoption8e2ef5b
line 135why, one step back135 response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 136why, one step back136clean up security header docsDavid Lordbefore adoption8eff9bd
line 137why, one step back137- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-SecurityMerge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 138why, one step back138Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993
lines 139–140why, one step back139.. _security-csp:140clean up security header docsDavid Lordbefore adoption8eff9bd
lines 141–142why, one step back141Content Security Policy (CSP)142~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 143why, one step back143clean up security header docsDavid Lordbefore adoption8eff9bd
lines 144–146why, one step back144Tell 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::Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 147why, one step back147Merge pull request #2364 from davidism/xss-noteDavid Lordbefore adoption9d82993
line 148why, one step back148 response.headers['Content-Security-Policy'] = "default-src 'self'"Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 149why, one step back149clean up security header docsDavid Lordbefore adoption8eff9bd
lines 150–151why, one step back150- https://csp.withgoogle.com/docs/index.html151- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-PolicyMerge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 152why, one step back152clean up security header docsDavid Lordbefore adoption8eff9bd
lines 153–154why, one step back153X-Content-Type-Options154~~~~~~~~~~~~~~~~~~~~~~Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 155why, one step back155clean up security header docsDavid Lordbefore adoption8eff9bd
lines 156–158why, one step back156Forces 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. ::Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 159why, one step back159clean up security header docsDavid Lordbefore adoption8eff9bd
line 160why, one step back160 response.headers['X-Content-Type-Options'] = 'nosniff'Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 161why, one step back161clean up security header docsDavid Lordbefore adoption8eff9bd
line 162why, one step back162- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-OptionsMerge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 163why, one step back163clean up security header docsDavid Lordbefore adoption8eff9bd
lines 164–165why, one step back164X-Frame-Options165~~~~~~~~~~~~~~~Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 166why, one step back166clean up security header docsDavid Lordbefore adoption8eff9bd
lines 167–170why, one step back167Prevents 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". ::Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 171why, one step back171clean up security header docsDavid Lordbefore adoption8eff9bd
line 172why, one step back172 response.headers['X-Frame-Options'] = 'SAMEORIGIN'Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 173why, one step back173clean up security header docsDavid Lordbefore adoption8eff9bd
line 174why, one step back174- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-OptionsMerge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 175why, one step back175clean up security header docsDavid Lordbefore adoption8eff9bd
lines 176–177why, one step back176X-XSS-Protection177~~~~~~~~~~~~~~~~Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 178why, one step back178clean up security header docsDavid Lordbefore adoption8eff9bd
lines 179–181why, one step back179The 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. ::Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 182why, one step back182clean up security header docsDavid Lordbefore adoption8eff9bd
line 183why, one step back183 response.headers['X-XSS-Protection'] = '1; mode=block'Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 184why, one step back184clean up security header docsDavid Lordbefore adoption8eff9bd
line 185why, one step back185- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-ProtectionMerge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 186why, one step back186clean up security header docsDavid Lordbefore adoption8eff9bd
lines 187–188why, one step back187Set-Cookie options188~~~~~~~~~~~~~~~~~~Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 189why, one step back189clean up security header docsDavid Lordbefore adoption8eff9bd
lines 190–192why, one step back190These options can be added to a ``Set-Cookie`` header to improve their191security. Flask has configuration options to set these on the session cookie.192They can be set on other cookies too.Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 193why, one step back193clean up security header docsDavid Lordbefore adoption8eff9bd
lines 194–198why, one step back194- ``Secure`` limits cookies to HTTPS traffic only.195- ``HttpOnly`` protects the contents of cookies from being read with196 JavaScript.197- ``SameSite`` ensures that cookies can only be requested from the same198 domain that created them. It is not supported by Flask yet.Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 199why, one step back199clean up security header docsDavid Lordbefore adoption8eff9bd
line 200why, one step back200::Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 201why, one step back201clean up security header docsDavid Lordbefore adoption8eff9bd
lines 202–205why, one step back202 app.config.update(203 SESSION_COOKIE_SECURE=True,204 SESSION_COOKIE_HTTPONLY=True,205 )Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 206why, one step back206clean up security header docsDavid Lordbefore adoption8eff9bd
line 207why, one step back207 response.set_cookie('username', 'flask', secure=True, httponly=True)Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 208why, one step back208mention that session signature checks max ageDavid Lordbefore adoption2efb565
lines 209–219why, one step back209Specifying ``Expires`` or ``Max-Age`` options, will remove the cookie after210the given time, or the current time plus the age, respectively. If neither211option is set, the cookie will be removed when the browser is closed. ::212213 # cookie expires after 10 minutes214 response.set_cookie('snakes', '3', max_age=600)215216For the session cookie, if ``session.permanent`` is set, then217:data:`SESSION_COOKIE_LIFETIME` is used to set the expiration. Flask's default218cookie implementation validates that the cryptographic signature is not older219than this value. Lowering this value may help mitigate replay attacks, wherefix code blockDavid Lordbefore adoption1c35b98
line 220why, one step back220intercepted cookies can be sent at a later time. ::mention that session signature checks max ageDavid Lordbefore adoption2efb565
lines 221–238why, one step back221222 app.config.update(223 PERMANENT_SESSION_LIFETIME=600224 )225226 @app.route('/login', methods=['POST'])227 def login():228 ...229 session.clear()230 session['user_id'] = user.id231 session.permanent = True232 ...233234Use :class:`TimedSerializer` to sign and validate other cookie values (or any235values that need secure signatures).236237- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies238- https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-CookieMerge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 239why, one step back239clean up security header docsDavid Lordbefore adoption8eff9bd
lines 240–241why, one step back240HTTP Public Key Pinning (HPKP)241~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 242why, one step back242clean up security header docsDavid Lordbefore adoption8eff9bd
lines 243–244why, one step back243This tells the browser to authenticate with the server using only the specific244certificate key to prevent MITM attacks.Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 245why, one step back245clean up security header docsDavid Lordbefore adoption8eff9bd
lines 246–248why, one step back246.. warning::247 Be careful when enabling this, as it is very difficult to undo if you set up248 or upgrade your key incorrectly.Merge pull request #2309 from aqt01/masterKenneth Reitzbefore adoption3acec5f
line 249why, one step back249clean up security header docsDavid Lordbefore adoption8eff9bd
line 250why, one step back250- https://developer.mozilla.org/en-US/docs/Web/HTTP/Public_Key_Pinning