1
votes

The OWASP XSS (Cross Site Scripting) Prevention Cheat Sheet lists rules to prevent XSS attacks by escaping data appropriately, and it contains links to reference implementations of these escaping methods in the Java language (HTML Escape, Attribute Escape, Javsacript Escape, CSS Escape, URL Escape).

Is there an implementation anywhere of these in Javascript, or do I have to 'roll my own'?

UPDATE: I mean Javascript running in the browser. For example, for escaping text rendered with the jQuery html() method (though of course text() is safer), or escaping data rendered using a template engine such as EJS.

UPDATE2: ESAPI JavaScript seems to be what I was looking for, though it's still only "Alpha Quality"

2
JavaScript … running where? The libraries you'll have available to you will depend on your environment (and browsers are very different to nodejs which is very different to classic ASP which is very different to etc etc etc)Quentin
Sorry for not being clearer. I mean Javascript running in the browser. For example, for escaping text rendered with the jQuery html() method (though of course text() is safer), or escaping data rendered using a template engine such as EJS.GStephens

2 Answers

2
votes

Since you tend to work with the DOM in (client-side) JavaScript, there is no need for HTML and HTML attribute escaping. For example, given untrusted input input,

var el = document.createElement('div');
el.setAttribute('title', input);
el.appendChild(document.createTextNode(input));

is perfectly safe, since you are never constructing (serialized) HTML in the first place.

If you are writing custom JavaScript or CSS from JavaScript code, you are doing something wrong (including using document.write or some data URI script src abominations), so there is no escaping provided for either. You can simply write your code or styles beforehand and then call the appropriate functions or set the appropriate classes.

encodeURI and encodeURIComponent can be used to encode URIs or their components.

0
votes

You can use js-xss library. For me it worked against test cases I've been using for injecting scripts into HTML.