Kalyan
Kalyan

Reputation: 7

Cross Site Scripting Issue

I want to prevent a XSS with our code, the problem is it might require both JS as well as html escaping and might be a little tricky.

The following sample code is similar to our code

 <script>
  var CURRENT_VALUE = '<img src=1 onerror=alert(1)>';
  document.getElementById("valueBox").innerHTML = CURRENT_VALUE;
 </script>

let us suppose CURRENT_VALUE is inserted dynamically. So what should I do in this case, I know a simple HTML encoding might not work as the attacker might pass the unicode escaped value and it might be dumped in the document when JS parser clears it.

So what is the correct way,

Should i first do JS escaping and just before document.getElementbyID do the html escaping ? How would that work ?

Assuming the CURRENT_VALUE is say hex encoded and contains /x027img... and so on

Upvotes: 0

Views: 493

Answers (1)

davidkonrad
davidkonrad

Reputation: 85578

Now I think I understand where you are heading - inserting the content as a TextNode does some formatting :

var CURRENT_VALUE = '<img src=1 onerror=alert(1)>';
var node = document.createTextNode(CURRENT_VALUE);
var valueBox = document.getElementById("valueBox");
valueBox.appendChild(node);

console.log(valueBox.innerHTML);

if you look at the console output the inserted HTML is now :

&lt;img src=1 onerror=alert(1)&gt;

Upvotes: 1

Related Questions