Skip to content
Myr

Merge pull request #1671 from jeffwidman/support-json-top-level-arrays

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Add support for serializing top-level arrays to JSON

authored by David Lord · committed by David Lord · parents f17e606, daceb3e · Browse files · 5 files+114 added−115 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+114 added−115 removed

  • tests:+69 added−29 removed
  • other:+45 added−86 removed

5 files+114 added−115 removed

modified:docs/security.rst+8 added-77 removed
93 unmodified lines
9495JSON Security96-------------9798.. admonition:: ECMAScript 5 Changes98In Flask 0.10 and lower, :func:`~flask.jsonify` did not serialize top-level99arrays to JSON. This was because of a security vulnerability in ECMAScript 4.100100 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 only133for you. And it is doing that for all ``GET`` requests to a certain URL,134say the URL for that request is135``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 in164your JSON file. The browser will totally ignore the :mimetype:`application/json`165mimetype if :mimetype:`text/javascript` is defined as content type in the script166tag and evaluate that as JavaScript. Because top-level array elements are167allowed (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.101ECMAScript 5 closed this vulnerability, so only extremely old browsers are102still vulnerable. All of these browsers have `other more serious103vulnerabilities104<https://github.com/mitsuhiko/flask/issues/248#issuecomment-59934857>`_, so105this behavior was changed and :func:`~flask.jsonify` now supports serializing106arrays.
modified:flask/json.py+32 added-8 removed
197 unmodified lines
198 fp.write(unicode(htmlsafe_dumps(obj, **kwargs)))199200201def jsonify(*args, **kwargs):202 """Creates a :class:`~flask.Response` with the JSON representation of203 the given arguments with an :mimetype:`application/json` mimetype. The204 arguments to this function are the same as to the :class:`dict`205 constructor.202 """This function wraps :func:`dumps` to add a few enhancements that make203 life easier. It turns the JSON output into a :class:`~flask.Response`204 object with the :mimetype:`application/json` mimetype. For convenience, it205 also converts multiple arguments into an array or multiple keyword arguments206 into a dict. This means that both ``jsonify(1,2,3)`` and207 ``jsonify([1,2,3])`` serialize to ``[1,2,3]``.208209 For clarity, the JSON serialization behavior has the following differences210 from :func:`dumps`:211212 1. Single argument: Passed straight through to :func:`dumps`.213 2. Multiple arguments: Converted to an array before being passed to214 :func:`dumps`.215 3. Multiple keyword arguments: Converted to a dict before being passed to216 :func:`dumps`.217 4. Both args and kwargs: Behavior undefined and will throw an exception.218219 Example usage::220221 from flask import jsonify222
10 unmodified lines
233 "email": "admin@localhost",234 "id": 42235 }236225 For security reasons only objects are supported toplevel. For more226 information about this, have a look at :ref:`json-security`.237238 .. versionchanged:: 1.0239 Added support for serializing top-level arrays. This introduces a240 security risk in ancient browsers. See :ref:`json_security` for details.241242 This function's response will be pretty printed if it was not requested243 with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless244 the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.245 Compressed (not pretty) formatting currently means no indents and no
9 unmodified lines
255 and not request.is_xhr:256 indent = 2257 separators = (', ', ': ')258259 if args and kwargs:260 raise TypeError(261 "jsonify() behavior undefined when passed both args and kwargs"262 )263 elif len(args) == 1: # single args are passed directly to dumps()264 data = args[0]265 elif args: # convert multiple args into an array266 data = list(args)267 else: # convert kwargs to a dict268 data = dict(kwargs)269270 # Note that we add '\n' to end of response271 # (see https://github.com/mitsuhiko/flask/pull/1262)272 rv = current_app.response_class(248 (dumps(dict(*args, **kwargs), indent=indent, separators=separators),249 '\n'),273 (dumps(data, indent=indent, separators=separators), '\n'),274 mimetype='application/json')275 return rv276277
2 unmodified lines
modified:tests/test_helpers.py+69 added-29 removed
29 unmodified lines
303132class TestJSON(object):3334 def test_jsonify_date_types(self):35 """Test jsonify with datetime.date and datetime.datetime types."""3637 test_dates = (38 datetime.datetime(1973, 3, 11, 6, 30, 45),39 datetime.date(1975, 1, 5)40 )4142 app = flask.Flask(__name__)43 c = app.test_client()4445 for i, d in enumerate(test_dates):46 url = '/datetest{0}'.format(i)47 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))48 rv = c.get(url)49 assert rv.mimetype == 'application/json'50 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())5134 def test_post_empty_json_adds_exception_to_response_content_in_debug(self):35 app = flask.Flask(__name__)36 app.config['DEBUG'] = True37 @app.route('/json', methods=['POST'])
46 unmodified lines
84 resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),85 content_type='application/json; charset=iso-8859-15')86 assert resp.data == u'Hällo Wörld'.encode('utf-8')87106 def test_jsonify(self):107 d = dict(a=23, b=42, c=[1, 2, 3])88 def test_json_as_unicode(self):89 app = flask.Flask(__name__)9091 app.config['JSON_AS_ASCII'] = True92 with app.app_context():93 rv = flask.json.dumps(u'\N{SNOWMAN}')94 assert rv == '"\\u2603"'9596 app.config['JSON_AS_ASCII'] = False97 with app.app_context():98 rv = flask.json.dumps(u'\N{SNOWMAN}')99 assert rv == u'"\u2603"'100101 def test_jsonify_basic_types(self):102 """Test jsonify with basic types."""103 # Should be able to use pytest parametrize on this, but I couldn't104 # figure out the correct syntax105 # https://pytest.org/latest/parametrize.html#pytest-mark-parametrize-parametrizing-test-functions106 test_data = (0, 1, 23, 3.14, 's', "longer string", True, False,)107 app = flask.Flask(__name__)108 c = app.test_client()109 for i, d in enumerate(test_data):110 url = '/jsonify_basic_types{0}'.format(i)111 app.add_url_rule(url, str(i), lambda x=d: flask.jsonify(x))112 rv = c.get(url)113 assert rv.mimetype == 'application/json'114 assert flask.json.loads(rv.data) == d115116 def test_jsonify_dicts(self):117 """Test jsonify with dicts and kwargs unpacking."""118 d = dict(119 a=0, b=23, c=3.14, d='t', e='Hi', f=True, g=False,120 h=['test list', 10, False],121 i={'test':'dict'}122 )123 app = flask.Flask(__name__)124 @app.route('/kw')125 def return_kwargs():126 return flask.jsonify(**d)127 @app.route('/dict')
4 unmodified lines
132 rv = c.get(url)133 assert rv.mimetype == 'application/json'134 assert flask.json.loads(rv.data) == d135121 def test_json_as_unicode(self):136 def test_jsonify_arrays(self):137 """Test jsonify of lists and args unpacking."""138 l = [139 0, 42, 3.14, 't', 'hello', True, False,140 ['test list', 2, False],141 {'test':'dict'}142 ]143 app = flask.Flask(__name__)144 @app.route('/args_unpack')145 def return_args_unpack():146 return flask.jsonify(*l)147 @app.route('/array')148 def return_array():149 return flask.jsonify(l)150 c = app.test_client()151 for url in '/args_unpack', '/array':152 rv = c.get(url)153 assert rv.mimetype == 'application/json'154 assert flask.json.loads(rv.data) == l155124 app.config['JSON_AS_ASCII'] = True125 with app.app_context():126 rv = flask.json.dumps(u'\N{SNOWMAN}')127 assert rv == '"\\u2603"'156 def test_jsonify_date_types(self):157 """Test jsonify with datetime.date and datetime.datetime types."""158129 app.config['JSON_AS_ASCII'] = False130 with app.app_context():131 rv = flask.json.dumps(u'\N{SNOWMAN}')132 assert rv == u'"\u2603"'159 test_dates = (160 datetime.datetime(1973, 3, 11, 6, 30, 45),161 datetime.date(1975, 1, 5)162 )163164 app = flask.Flask(__name__)165 c = app.test_client()166167 for i, d in enumerate(test_dates):168 url = '/datetest{0}'.format(i)169 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))170 rv = c.get(url)171 assert rv.mimetype == 'application/json'172 assert flask.json.loads(rv.data)['x'] == http_date(d.timetuple())173174 def test_json_attr(self):175 app = flask.Flask(__name__)176 @app.route('/add', methods=['POST'])177 def add():
543 unmodified lines
modified:AUTHORS+2 added-1 removed
13 unmodified lines
14- Chris Edgemon15- Chris Grindstaff16- Christopher Grebs17- Daniel Neuhäuser18- David Lord @davidism19- Edmond Burnett20- Florent Xicluna21- Georg Brandl22- Jeff Widman @jeffwidman23- Justin Quick24- Kenneth Reitz25- Keyan Pishdadian26- Marian Sigler
6 unmodified lines
33- Simon Sapin34- Stephane Wirtel35- Thomas Schranz36- Zhao Xiaohong35- David Lord @davidism
modified:CHANGES+3 added
6 unmodified lines
7-----------89(release date to be announced, codename to be selected)1011- Added support to serializing top-level arrays to :func:`flask.jsonify`. This12 introduces a security risk in ancient browsers. See13 :ref:`json_security` for details.14- Added before_render_template signal.15- Added `**kwargs` to :meth:`flask.Test.test_client` to support passing16 additional keyword arguments to the constructor of17 :attr:`flask.Flask.test_client_class`.
542 unmodified lines