Skip to content
Permalink
Browse files Browse the repository at this point in the history
Fix a XSS vulnerability with bad input to json_dumps.
Django's JSON serialization does not handle escaping of any characters
to make them safe for injecting into HTML. This allows an attacker who
can provide part of a JSON-serializable object to craft a string that
can break out of a <script> tag and create its own, injecting a custom
script.

To fix this, we escape '<', '>', and '&' characters in the resulting
string, preventing a </script> from executing.
  • Loading branch information
chipx86 committed Jun 6, 2014
1 parent 57ee1a0 commit 77a68c0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
9 changes: 8 additions & 1 deletion djblets/util/templatetags/djblets_js.py
Expand Up @@ -31,13 +31,20 @@
from django.core.serializers import serialize
from django.db.models.query import QuerySet
from django.utils import six
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe

from djblets.util.serializers import DjbletsJSONEncoder


register = template.Library()

_safe_js_escapes = {
ord('&'): '\\u0026',
ord('<'): '\\u003C',
ord('>'): '\\u003E',
}


@register.simple_tag
def form_dialog_fields(form):
Expand Down Expand Up @@ -75,7 +82,7 @@ def json_dumps(value, indent=None):
else:
result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder)

return mark_safe(result)
return mark_safe(force_text(result).translate(_safe_js_escapes))


@register.filter
Expand Down
19 changes: 19 additions & 0 deletions djblets/util/templatetags/tests.py
@@ -0,0 +1,19 @@
from __future__ import unicode_literals

from djblets.testing.testcases import TestCase
from djblets.util.templatetags.djblets_js import json_dumps


class JSTagTests(TestCase):
"""Unit tests for djblets_js template tags."""
def test_json_dumps_xss(self):
"""Testing json_dumps doesn't allow XSS injection"""
# This is bug 3406.
obj = {
'xss': '</script><script>alert(1);</script>'
}

self.assertEqual(
json_dumps(obj),
'{"xss": "\\u003C/script\\u003E\\u003Cscript\\u003E'
'alert(1);\\u003C/script\\u003E"}')

0 comments on commit 77a68c0

Please sign in to comment.