Fixed a security problem caused by changed simplejson semantics.

Notice: this was never in a release version of Flask.
This commit is contained in:
Armin Ronacher 2010-04-19 18:51:04 +02:00
parent 07e515b071
commit ade490514d
4 changed files with 16 additions and 2 deletions

View file

@ -250,6 +250,8 @@ Returning JSON
doSomethingWith({{ user.username|tojson|safe }});
</script>
Note that the ``|tojson`` filter escapes forward slashes properly.
Template Rendering
------------------

View file

@ -77,7 +77,8 @@ inside a `script` block here where different rules apply.
will not be parsed. Everything until ``</script>`` is handled as script.
This also means that there must never be any ``</`` between the script
tags. ``|tojson`` is kindly enough to do the right thing here and
escape backslashes for you.
escape slashes for you (``{{ "</script>"|tojson|safe }`` is rendered as
``"<\/script>"``).
JSON View Functions

View file

@ -259,6 +259,11 @@ def _get_package_path(name):
return os.getcwd()
def _tojson_filter(string, *args, **kwargs):
"""Calls dumps for the template engine, escaping Slashes properly."""
return json.dumps(string, *args, **kwargs).replace('/', '\\/')
class Flask(object):
"""The flask object implements a WSGI application and acts as the central
object. It is passed the name of the module or package of the
@ -379,7 +384,7 @@ class Flask(object):
get_flashed_messages=get_flashed_messages
)
if json_available:
self.jinja_env.filters['tojson'] = json.dumps
self.jinja_env.filters['tojson'] = _tojson_filter
def create_jinja_loader(self):
"""Creates the Jinja loader. By default just a package loader for

View file

@ -194,6 +194,12 @@ class JSONTestCase(unittest.TestCase):
content_type='application/json')
assert rv.data == '3'
def test_template_escaping(self):
app = flask.Flask(__name__)
with app.test_request_context():
rv = flask.render_template_string('{{ "</script>"|tojson|safe }}')
assert rv == '"<\\/script>"'
class TemplatingTestCase(unittest.TestCase):