Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery XSS potential reading from query strings

My javascript reads data from a query string and puts that data into a text box using jQuery.val().

This works fine but I am wondering is this safe from XSS attacks?

Say the query string looked like...

site.com?q="javascript:alert(document.cookie)

Which would effectively do:

jQuery.val('"javascript:alert(document.cookie)')

From what I have tested in IE8 / firefox this sets the input value as seen and doesn't do the actual injection.

If I run this function over the string first:

function htmlEncode(str) {
    return str.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#039;').replace(/"/g, '&quot;');
}

Then you literally see &quot;javascript:alert(document.cookie) in the input value which is not what I want.

Using jQuery 1.5.2 I guess my question is does jQuery.val() handle the HTML entities for you and is therefore considered safe?

like image 620
fire Avatar asked May 07 '11 14:05

fire


1 Answers

Given the following:

jQuery("#SomeTextbox").val("new value for SomeTextbox")

the jQuery code for the val function simply does this:

this.value = "new value for SomeTextbox";

where this is a reference to the Text object in the DOM that represents the textbox with id "SomeTextbox". The string "new value for SomeTextbox" is stored as the value property of that DOM object. It does not get transformed or sanitized in any way. But it doesn't get parsed/interpreted by the JavaScript engine either (e.g. as it would with InnerHTML). So regardless of what your argument to val is, it isn't going to "do" anything. It just changes the value of a string property of an object in the DOM. So, yes, it would be safe.

EDIT:

Here is some additional information that you may find helpful.

In general, putting something into a text box, no matter how malicious it may appear, and regardless of how it gets there is "safe" as long as it stays in the text box. But it matters a lot where it goes from there.

If the content of the textbox is subsequently rendered in a stream of parsed HTML, then it is no longer safe. A common scenario is to store the content of a textbox in a database, then retrieve it later and render it in a context where the browser parses is as HTML. If the re-display occurs in the context of a different user, it creates an opportunity for a malicious user to enter data into the textbox in order to gain access to another users private information at some future time.

like image 88
Joel Lee Avatar answered Sep 20 '22 02:09

Joel Lee