Cross Site scripting issue with document.write

I am working with some old code that is reportedly vulnerable to cross-site scripting. Line of code

document.write("<input type=hidden name=field1 value='" + getCookieValue('fieldval') + "' />");

      

The report also provides an example of using malicious code on a page. By updating the cookie value as

fieldval='><img src=x onerror=alert(1)>

      

Can anyone understand how this vulnerability could be fixed?

+3


source to share


2 answers


You will need to validate the data coming from getCookieValue. If you are expecting a number, make sure the return value is numeric. Also make sure that any escape characters (like quotes that come out of your javascript) are missing from the field. The fix for this would look like this:

function is_valid(value) {
     // Do some check here depending on what you're expecting.
     // I also recommend escaping any quotes (i.e. " becomes \")
     // Ideally, you'd just whitelist what is acceptable input (A-Z0-9 or whatever,
     // and return false from this function if something else is present in 
     // value!)
}

var cookie_value = getCookieValue('fieldval');

if(is_valid(cookie_value)) {
    document.write('<input type="hidden name="field1" value="' + cookie_value + '" />');
}

      



In short, misinform the data before document.write or you get reflected XSS.

As mentioned in the comments above, XSS generated from the user's own cookies (something they modify themselves) isn't much of a concern. However, any coding techniques that lead to this are likely to be present elsewhere. I would recommend looking at your source and making sure all input from users is treated as untrustworthy and sanitized appropriately.

+2


source


Your code contains two errors:

  • You are inserting untrusted data into the output file without encoding it correctly (which opens the door to deflected XSS attacks).
  • You are using document.write

    to insert normal HTML into the DOM (which opens the door to DOM XSS attacks).

Before reinventing the wheel, you should check the OWASP cheat sheet to fix the errors:



As you can see, your problem is not fixed, just by avoiding quotes. Whiteness of your untrustworthy data is always the preferred method and valid advice. For further reading of XSS in general, the links contain many links.

+2


source







All Articles