JavaScriptEscape and </script> tags in string literals

0 views
Skip to first unread message

dhasenan

unread,
Jun 11, 2009, 3:10:52 PM6/11/09
to Castle Project Users
Castle.Monorail.Framework.Adapters.ServerUtilityAdapter has a method
JavaScriptEscape. This is intended to sanitize strings for inclusion
in JavaScript string literals:
"';Malicious code!//" => "\';Malicious code!//"

However, it concentrates solely on JS in selfcontained files. A common
use case is including JS in HTML. JavaScriptEscape ignores this:
<% maliciousString = "I'm not terminated! </script>" %>
<script>
var str = '${Html.JavaScriptEscape(maliciousString)}';
</script>

Here, you get a JS error: unterminated string literal 'I\'m not
terminated!

The browser ignores any JS parsing rules and finds the </script> tag
in the string literal. The HTML document is no longer well-formed, but
most browsers will accept this silently. The JS parser can't cope with
an abruptly terminated script.

This can result in a denial of service, depending on where this string
is located.

The fix:
<% maliciousString = "I'm not terminated! </script>" %>
<script>
var str = '${Html.JavaScriptEscape(maliciousString).Replace(">", "\
\>")}';
</script>
Reply all
Reply to author
Forward
0 new messages