Search code examples
xssesapi

Handling HTML and Javascript encoded data using ESAPI in javascript


If one performs HTML and Javascript encoding on the html content to prevent XSS (using ESAPI,Encoder.encodeForJS(Encoder.encodeForHTML(untrustedData))) before sending the response to the client. How to handle this HTML and Javascript encoded data in javascript?

Do I have to canonicalise the data before using the server output in element.innerHTML.

e.g,

var data = $ESAPI.encoder().canonicalize(serverOP); 

element.innerHTML=data;

But canonicalising data with mixed or multiple encoding will throw exception (Intrusion exception).


Solution

  • In this case, the server is first neutralizing HTML, and then neutralizing THAT data to be passed to a javascript function.

    Is the javascript function you're targeting supposed to process HTML?

    If you encode for HTML and then encode for javascript, you then need to call ESAPI.encoder().decodeForJavascript(payload) followed by ESAPI.encoder().decodeForHtml(payload)

    Canonicalization is meant to be used to process data coming in from an untrusted source, and isn't a one-stop decoding function.

    Further, if you know that your javascript function is the only entry point for this data, you shouldn't have to escape for html, just escape for javascript... I say this because "innerHTML" indicates that you intend for the browser to render what you're sending in, so you're doing extra work here by adding an unnecessary decoding step.


    I wanted to add: If the server is passing escaped data intended to be passed to javascript, you won't want to decode it before using it.