diff options
| author | Malcolm Tredinnick <malcolm.tredinnick@gmail.com> | 2008-08-26 07:56:32 +0000 |
|---|---|---|
| committer | Malcolm Tredinnick <malcolm.tredinnick@gmail.com> | 2008-08-26 07:56:32 +0000 |
| commit | 8c4a525871df19163d5bfdf5939eff33b544c2e2 (patch) | |
| tree | 44adb32e840ffc583de843f4670590482be48eea | |
| parent | fcf059d539d9065a09979bba81dcb7107e41f085 (diff) | |
Fixed #7177 -- Added extra robustness to the escapejs filter so that all
invalid characters are correctly escaped. This avoids any chance to inject raw
HTML inside <script> tags. Thanks to Mike Wiacek for the patch and Collin Grady
for the tests.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8577 bcc190cf-cafb-0310-a4f2-bffc1f526a37
| -rw-r--r-- | django/template/defaultfilters.py | 28 | ||||
| -rw-r--r-- | tests/regressiontests/templates/filters.py | 3 |
2 files changed, 19 insertions, 12 deletions
diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index 1140f7ee40..56bf405018 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -62,20 +62,24 @@ def capfirst(value): capfirst.is_safe=True capfirst = stringfilter(capfirst) -_js_escapes = ( - ('\\', '\\\\'), - ('"', '\\"'), - ("'", "\\'"), - ('\n', '\\n'), - ('\r', '\\r'), - ('\b', '\\b'), - ('\f', '\\f'), - ('\t', '\\t'), - ('\v', '\\v'), - ('</', '<\\/'), +_base_js_escapes = ( + ('\\', r'\x5C'), + ('\'', r'\x27'), + ('"', r'\x22'), + ('>', r'\x3E'), + ('<', r'\x3C'), + ('&', r'\x26'), + ('=', r'\x3D'), + ('-', r'\x2D'), + (';', r'\x3B') ) + +# Escape every ASCII character with a value less than 32. +_js_escapes = (_base_js_escapes + + tuple([('%c' % z, '\\x%02X' % z) for z in range(32)])) + def escapejs(value): - """Backslash-escapes characters for use in JavaScript strings.""" + """Hex encodes characters for use in JavaScript strings.""" for bad, good in _js_escapes: value = value.replace(bad, good) return value diff --git a/tests/regressiontests/templates/filters.py b/tests/regressiontests/templates/filters.py index c71270c9ea..bb92336dcc 100644 --- a/tests/regressiontests/templates/filters.py +++ b/tests/regressiontests/templates/filters.py @@ -262,5 +262,8 @@ def get_filter_tests(): 'autoescape-stringfilter02': (r'{% autoescape off %}{{ unsafe|capfirst }}{% endautoescape %}', {'unsafe': UnsafeClass()}, 'You & me'), 'autoescape-stringfilter03': (r'{{ safe|capfirst }}', {'safe': SafeClass()}, 'You > me'), 'autoescape-stringfilter04': (r'{% autoescape off %}{{ safe|capfirst }}{% endautoescape %}', {'safe': SafeClass()}, 'You > me'), + + 'escapejs01': (r'{{ a|escapejs }}', {'a': 'testing\r\njavascript \'string" <b>escaping</b>'}, 'testing\\x0D\\x0Ajavascript \\x27string\\x22 \\x3Cb\\x3Eescaping\\x3C/b\\x3E'), + 'escapejs02': (r'{% autoescape off %}{{ a|escapejs }}{% endautoescape %}', {'a': 'testing\r\njavascript \'string" <b>escaping</b>'}, 'testing\\x0D\\x0Ajavascript \\x27string\\x22 \\x3Cb\\x3Eescaping\\x3C/b\\x3E'), } |
