Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
  • Loading branch information...
commit 8c4a525871df19163d5bfdf5939eff33b544c2e2 1 parent fcf059d
Malcolm Tredinnick authored August 26, 2008
28  django/template/defaultfilters.py
@@ -62,20 +62,24 @@ def capfirst(value):
62 62
 capfirst.is_safe=True
63 63
 capfirst = stringfilter(capfirst)
64 64
 
65  
-_js_escapes = (
66  
-    ('\\', '\\\\'),
67  
-    ('"', '\\"'),
68  
-    ("'", "\\'"),
69  
-    ('\n', '\\n'),
70  
-    ('\r', '\\r'),
71  
-    ('\b', '\\b'),
72  
-    ('\f', '\\f'),
73  
-    ('\t', '\\t'),
74  
-    ('\v', '\\v'),
75  
-    ('</', '<\\/'),
  65
+_base_js_escapes = (
  66
+    ('\\', r'\x5C'),
  67
+    ('\'', r'\x27'),
  68
+    ('"', r'\x22'),
  69
+    ('>', r'\x3E'),
  70
+    ('<', r'\x3C'),
  71
+    ('&', r'\x26'),
  72
+    ('=', r'\x3D'),
  73
+    ('-', r'\x2D'),
  74
+    (';', r'\x3B')
76 75
 )
  76
+
  77
+# Escape every ASCII character with a value less than 32.
  78
+_js_escapes = (_base_js_escapes +
  79
+               tuple([('%c' % z, '\\x%02X' % z) for z in range(32)]))
  80
+
77 81
 def escapejs(value):
78  
-    """Backslash-escapes characters for use in JavaScript strings."""
  82
+    """Hex encodes characters for use in JavaScript strings."""
79 83
     for bad, good in _js_escapes:
80 84
         value = value.replace(bad, good)
81 85
     return value
3  tests/regressiontests/templates/filters.py
@@ -262,5 +262,8 @@ def get_filter_tests():
262 262
         'autoescape-stringfilter02': (r'{% autoescape off %}{{ unsafe|capfirst }}{% endautoescape %}', {'unsafe': UnsafeClass()}, 'You & me'),
263 263
         'autoescape-stringfilter03': (r'{{ safe|capfirst }}', {'safe': SafeClass()}, 'You &gt; me'),
264 264
         'autoescape-stringfilter04': (r'{% autoescape off %}{{ safe|capfirst }}{% endautoescape %}', {'safe': SafeClass()}, 'You &gt; me'),
  265
+
  266
+        'escapejs01': (r'{{ a|escapejs }}', {'a': 'testing\r\njavascript \'string" <b>escaping</b>'}, 'testing\\x0D\\x0Ajavascript \\x27string\\x22 \\x3Cb\\x3Eescaping\\x3C/b\\x3E'),
  267
+        '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'),
265 268
     }
266 269
 

0 notes on commit 8c4a525

Please sign in to comment.
Something went wrong with that request. Please try again.