Skip to content
Myr

security.rst

This file

Path

docs/security.rst

168 lines · 7.1 KiB

Last changed by

Fixed some small typos in the documentation.Sam Andersonbefore adoptionda00160

History of this file

Take it

1Security 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 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 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   <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.7273Say you have a specific URL that, when you sent `POST` requests to will74delete a user's profile (say `http://example.com/user/delete`).  If an75attacker now creates a page that sends a post request to that page with76some JavaScript he 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-------------9798JSON itself is a high-level serialization format, so there is barely99anything that could cause security problems, right?  You can't declare100recursive structures that could cause problems and the only thing that101could possibly break are very large responses that can cause some kind of102denial of service at the receiver's side.103104However there is a catch.  Due to how browsers work the CSRF issue comes105up with JSON unfortunately.  Fortunately there is also a weird part of the106JavaScript specification that can be used to solve that problem easily and107Flask is kinda doing that for you by preventing you from doing dangerous108stuff.  Unfortunately that protection is only there for109:func:`~flask.jsonify` so you are still at risk when using other ways to110generate JSON.111112So what is the issue and how to avoid it?  The problem are arrays at113top-level in JSON.  Imagine you send the following data out in a JSON114request.  Say that's exporting the names and email addresses of all your115friends for a part of the user interface that is written in JavaScript.116Not very uncommon:117118.. sourcecode:: javascript119120    [121        {"username": "admin",122         "email": "admin@localhost"}123    ]124125And it is doing that of course only as long as you are logged in and only126for you.  And it is doing that for all `GET` requests to a certain URL,127say the URL for that request is128``http://example.com/api/get_friends.json``.129130So now what happens if a clever hacker is embedding this to his website131and social engineers a victim to visiting his site:132133.. sourcecode:: html134135    <script type=text/javascript>136    var captured = [];137    var oldArray = Array;138    function Array() {139      var obj = this, id = 0, capture = function(value) {140        obj.__defineSetter__(id++, capture);141        if (value)142          captured.push(value);143      };144      capture();145    }146    </script>147    <script type=text/javascript148      src=http://example.com/api/get_friends.json></script>149    <script type=text/javascript>150    Array = oldArray;151    // now we have all the data in the captured array.152    </script>153154If you know a bit of JavaScript internals you might know that it's155possible to patch constructors and register callbacks for setters.  An156attacker can use this (like above) to get all the data you exported in157your JSON file.  The browser will totally ignore the ``application/json``158mimetype if ``text/javascript`` is defined as content type in the script159tag and evaluate that as JavaScript.  Because top-level array elements are160allowed (albeit useless) and we hooked in our own constructor, after that161page loaded the data from the JSON response is in the `captured` array.162163Because it is a syntax error in JavaScript to have an object literal164(``{...}``) toplevel an attacker could not just do a request to an165external URL with the script tag to load up the data.  So what Flask does166is to only allow objects as toplevel elements when using167:func:`~flask.jsonify`.  Make sure to do the same when using an ordinary168JSON generate function.