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, '<').replace(/>/g, '>').replace(/'/g, ''').replace(/"/g, '"');
}
Then you literally see "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?
Given the following:
the jQuery code for the
valfunction simply does this:where
thisis a reference to theTextobject in the DOM that represents the textbox with id “SomeTextbox”. The string"new value for SomeTextbox"is stored as thevalueproperty 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 withInnerHTML). So regardless of what your argument tovalis, 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.