Skip to content
Myr

security.rst

This file

Path

docs/security.rst

175 lines · 7.4 KiB

Last changed by

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

History of this file

Take it

The walk stopped after 200 commits: lines older than 5693b9d point at it.

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 1–27why, 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<http://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 the

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 28why, one step back
28 ``Content-Disposition: attachment`` header to prevent that problem.

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 29–72why, one step back
29- sending out textfiles from uploaded files. Some browsers are using
30 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 <a href="{{ href }}">the text</a>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 link, 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.5758Cross-Site Request Forgery (CSRF)59---------------------------------6061Another big problem is CSRF. This is a very complex topic and I won't62outline it here in detail just mention what it is and how to theoretically63prevent it.6465If your authentication information is stored in cookies, you have implicit66state management. The state of "being logged in" is controlled by a67cookie, and that cookie is sent with each request to a page.68Unfortunately that includes requests triggered by 3rd party sites. If you69don't keep that in mind, some people might be able to trick your70application's users with social engineering to do stupid things without71them knowing.72

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

lines 73–74why, one step back
73Say you have a specific URL that, when you sent ``POST`` requests to will
74delete a user's profile (say ``http://example.com/user/delete``). If an

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 75–132why, one step back
75attacker now creates a page that sends a post request to that page with
76some JavaScript they just has to trick some users to load that page and77their profiles will end up being deleted.7879Imagine you were to run Facebook with millions of concurrent users and80someone would send out links to images of little kittens. When users81would go to that page, their profiles would get deleted while they are82looking at images of fluffy cats.8384How can you prevent that? Basically for each request that modifies85content on the server you would have to either use a one-time token and86store that in the cookie **and** also transmit it with the form data.87After receiving the data on the server again, you would then have to88compare the two tokens and ensure they are equal.8990Why does Flask not do that for you? The ideal place for this to happen is91the form validation framework, which does not exist in Flask.9293.. _json-security:9495JSON Security96-------------9798.. admonition:: ECMAScript 5 Changes99100 Starting with ECMAScript 5 the behavior of literals changed. Now they101 are not constructed with the constructor of ``Array`` and others, but102 with the builtin constructor of ``Array`` which closes this particular103 attack vector.104105JSON itself is a high-level serialization format, so there is barely106anything that could cause security problems, right? You can't declare107recursive structures that could cause problems and the only thing that108could possibly break are very large responses that can cause some kind of109denial of service at the receiver's side.110111However there is a catch. Due to how browsers work the CSRF issue comes112up with JSON unfortunately. Fortunately there is also a weird part of the113JavaScript specification that can be used to solve that problem easily and114Flask is kinda doing that for you by preventing you from doing dangerous115stuff. Unfortunately that protection is only there for116:func:`~flask.jsonify` so you are still at risk when using other ways to117generate JSON.118119So what is the issue and how to avoid it? The problem are arrays at120top-level in JSON. Imagine you send the following data out in a JSON121request. Say that's exporting the names and email addresses of all your122friends for a part of the user interface that is written in JavaScript.123Not very uncommon:124125.. sourcecode:: javascript126127 [128 {"username": "admin",129 "email": "admin@localhost"}130 ]131132And it is doing that of course only as long as you are logged in and only

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

line 133why, one step back
133for you. And it is doing that for all ``GET`` requests to a certain URL,

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 134–163why, one step back
134say the URL for that request is
135``http://example.com/api/get_friends.json``.136137So now what happens if a clever hacker is embedding this to his website138and social engineers a victim to visiting his site:139140.. sourcecode:: html141142 <script type=text/javascript>143 var captured = [];144 var oldArray = Array;145 function Array() {146 var obj = this, id = 0, capture = function(value) {147 obj.__defineSetter__(id++, capture);148 if (value)149 captured.push(value);150 };151 capture();152 }153 </script>154 <script type=text/javascript155 src=http://example.com/api/get_friends.json></script>156 <script type=text/javascript>157 Array = oldArray;158 // now we have all the data in the captured array.159 </script>160161If you know a bit of JavaScript internals you might know that it's162possible to patch constructors and register callbacks for setters. An163attacker can use this (like above) to get all the data you exported in

Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae

lines 164–165why, one step back
164your JSON file. The browser will totally ignore the :mimetype:`application/json`
165mimetype if :mimetype:`text/javascript` is defined as content type in the script

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 166–175why, one step back
166tag and evaluate that as JavaScript. Because top-level array elements are
167allowed (albeit useless) and we hooked in our own constructor, after that168page loaded the data from the JSON response is in the `captured` array.169170Because it is a syntax error in JavaScript to have an object literal171(``{...}``) toplevel an attacker could not just do a request to an172external URL with the script tag to load up the data. So what Flask does173is to only allow objects as toplevel elements when using174:func:`~flask.jsonify`. Make sure to do the same when using an ordinary175JSON generate function.