Skip to content
Myr

security.rst

This file

Path

docs/security.rst

134 lines · 5.7 KiB

Last changed by

Typo.florentxbefore adoption7083b35

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.78Cross-Site Scripting (XSS)9--------------------------1011Flask configures Jinja2 to automatically escape all values unless12explicitly told otherwise.  This should rule out all XSS problems caused13in templates, but there are still other places where you have to be14careful:1516-   generating HTML without the help of Jinja217-   calling :class:`~flask.Markup` on data submitted by users18-   sending out HTML from uploaded files, never do that, use the19    `Content-Disposition: attachment` header to prevent that problem.20-   sending out textfiles from uploaded files.  Some browsers are using21    content-type guessing based on the first few bytes so users could22    trick a browser to execute HTML.2324Cross-Site Request Forgery (CSRF)25---------------------------------2627Another big problem is CSRF.  This is a very complex topic and I won't28outline it here in detail just mention what it is and how to theoretically29prevent it.3031So if your authentication information is stored in cookies you have32implicit state management.  By that I mean that the state of "being logged33in" is controlled by a cookie and that cookie is sent with each request to34a page.  Unfortunately that really means "each request" so also requests35triggered by 3rd party sites.  If you don't keep that in mind some people36might be able to trick your application's users with social engineering to37do stupid things without them knowing.3839Say you have a specific URL that, when you sent `POST` requests to will40delete a user's profile (say `http://example.com/user/delete`).  If an41attacker now creates a page that sents a post request to that page with42some JavaScript he just has to trick some users to that page and their43profiles will end up being deleted.4445Imagine you would run Facebook with millions of concurrent users and46someone would send out links to images of little kittens.  When a user47would go to that page their profiles would get deleted while they are48looking at images of fluffy cats.4950So how can you prevent yourself from that?  Basically for each request51that modifies content on the server you would have to either use a52one-time token and store that in the cookie **and** also transmit it with53the form data.   After recieving the data on the server again you would54then have to compare the two tokens and ensure they are equal.5556Why does not Flask do that for you?  The ideal place for this to happen is57the form validation framework which does not exist in Flask.5859.. _json-security:6061JSON Security62-------------6364JSON itself is a high-level serialization format, so there is barely65anything that could cause security problems, right?  You can't declare66recursive structures that could cause problems and the only thing that67could possibly break are very large responses that can cause some kind of68denial of service at the receiver's side.6970However there is a catch.  Due to how browsers work the CSRF issue comes71up with JSON unfortunately.  Fortunately there is also a weird part of the72JavaScript specification that can be used to solve that problem easily and73Flask is kinda doing that for you by preventing you from doing dangerous74stuff.  Unfortunately that protection is only there for75:func:`~flask.jsonify` so you are still at risk when using other ways to76generate JSON.7778So what is the issue and how to avoid it?  The problem are arrays at79toplevel in JSON.  Imagine you send the following data out in a JSON80request.  Say that's exporting the names and email adresses of all your81friends for a part of the userinterface that is written in JavaScript.82Not very uncommon:8384.. sourcecode:: javascript8586    [87        {"username": "admin",88         "email": "admin@localhost"}89    ]9091And it is doing that of course only as long as you are logged in and only92for you.  And it is doing that for all `GET` requests to a certain URL,93say the URL for that request is94``http://example.com/api/get_friends.json``.9596So now what happens if a clever hacker is embedding this to his website97and social engineers a victim to visiting his site:9899.. sourcecode:: html100101    <script type=text/javascript>102    var captured = [];103    var oldArray = Array;104    function Array() {105      var obj = this, id = 0, capture = function(value) {106        obj.__defineSetter__(id++, capture);107        if (value)108          captured.push(value);109      };110      capture();111    }112    </script>113    <script type=text/javascript114      src=http://example.com/api/get_friends.json></script>115    <script type=text/javascript>116    Array = oldArray;117    // now we have all the data in the captured array.118    </script>119120If you know a bit of JavaScript internals you might know that it's121possible to patch constructors and register callbacks for setters.  An122attacker can use this (like above) to get all the data you exported in123your JSON file.  The browser will totally ignore the ``application/json``124mimetype if ``text/javascript`` is defined as content type in the script125tag and evaluate that as JavaScript.  Because toplevel array elements are126allowed (albeit useless) and we hooked in our own constructor, after that127page loaded the data from the JSON response is in the `captured` array.128129Because it is a syntax error in JavaScript to have an object literal130(``{...}``) toplevel an attacker could not just do a request to an131external URL with the script tag to load up the data.  So what Flask does132is only allowing objects as toplevel elements when using133:func:`~flask.jsonify`.  Make sure to do the same when using an ordinary134JSON generate function.