-1

I have a grails project with the UI mostly implemented in javascript(BackBone.js). Briefly speaking i have a gsp file that includes a javascript file. The events of the gsp page are handled by the handlers defined in the Javascript file.

Now i have some DOM XSS violations in the javascript file. eg. cell1.innerHTML = '<div name="caCertFileName">' + item.fileName.substring(33) + '</div>';

Now i cannot understand how to use the encodeAsHTML / encodeAsJavascript funtions in the javascript file. I need a short example to figure this out.

Som Bhattacharyya
  • 3,972
  • 35
  • 54
  • 1
    you can't use encodeAs stuff in the javascript file but you can in a javascript segment of a given GSP (this will hit grails and be processed) where as your static js files so far as I understand aren't. Choices are to move that handler to the gsp or a centralised gsp and try to do encoding around a script wrapper there - or possibly look at encoding the item which may be the cause to your issue item.fileName?.substring(33) bit maybe you should pass that specific thing to backend javascript function that handles the item.fileName.substring(33) as a variable – V H Jan 24 '18 at 17:30
  • https://github.com/vahidhedayati/grails-wschat-plugin/blob/1698a6eaca51b50a4f5fb42d35e68ebb6228aa49/grails-app/views/customerChat/_liveChatPage.gsp#L28 in a gsp – V H Jan 24 '18 at 17:33
  • Possible duplicate of [How to encode html in Backbone model to guard against DOM based XSS](https://stackoverflow.com/questions/48283916/how-to-encode-html-in-backbone-model-to-guard-against-dom-based-xss) – Emile Bergeron Jan 24 '18 at 20:34
  • This is essentially the same question as your other one, formulated differently with server-side/client-side language confusion mixed in. – Emile Bergeron Jan 24 '18 at 20:35

1 Answers1

2

You can define JavaScript function to do html escaping, and use it like:

cell1.innerHTML = '<div name="caCertFileName">' + encodeHtml(item.fileName.substring(33)) + '</div>';

With a function like encodeHtml that converts characters like < to &lt;, and the data being inserted between tags and not inside them, this can work.

See: Can I escape html special chars in javascript? for implementations.

You may be better off avoiding innerHTML though, and using the DOM manipulation functions. With jQuery for example you can write:

$(cell1).append($("<div>")
    .attr("name", "caCertFileName")
    .text(item.fileName.substring(33)));

This keeps a separation between the HTML structure and user data.

fgb
  • 18,439
  • 2
  • 38
  • 52