Using the OWASP checklist, which is the correct way protect this situation? This is url inside of a javascript string where a url parameter needs to have xss protection.
Problem:
<script>
var u = 'xyz.html?x=<% url.baddata %>'
dosomeAjax(u);
</script>
Possible solution 1:
var u = 'xyz.html?x=<% encodeForURL(url.baddata) %>'
Possible solution 2:
var u = 'xyz.html?x=<% encodeForJavaScript(url.baddata) %>'
Possible solution 3:
var u = 'xyz.html?x=<% encodeForJavaScript(encodeForURL(url.baddata)) %>'
Solution 3 should be used:
//solution 3:
var u = 'xyz.html?x=<% encodeForJavaScript(encodeForURL(url.baddata)) %>';
It is easier to see that this is correct if we rewrite the expression as:
var u = '<% encodeForJavaScript("xyz.html?x=" + encodeForURL(url.baddata)) %>';
First, we are creating a safe URL by appending baddata
to a string constant, using the appropriate escape function. Then we are taking that safe URL and placing it in a JavaScript string, so we have to call the JavaScript escape function.