1

I was wondering if this function would be vulnerable to XSS.

var url = "google.com";

if (url.indexOf("http") != 0) { 
    url = "http://" + url;
}

$("<a/>").attr("href", url);

The 'url' is user input, and the <a/> would be placed on some webpage.

I couldn't find a way to execute javascript code on this function. But before I implement this, it would be nice somebody can take a look.

4

What jQuery actually does when you use attr(name, value) is to call setAttribute(name, value) on the relevant DOM elements. Not at home in the jQuery source, but I think this is the relevant part. This means that you can not escape out of the attribute context. So it is as safe as vanilla JS is.

What you need to look out for is the following:

  • Don't let the users control the attribute name - that opens up the door to changing it to something malicious such as onclick. Unless you do whitelisting, only let the user control the value.
  • Some HTML attributes are inherently dangerous. This includes href, since you can do something like javascript:alert("XSS");. Since you make sure the value will always start with http you should be fine, though. Other examples of dangerous attributes are style and JS event handlers.
  • But isn't the javascript:alert(); not dangerous anymore because http:// will be pasted in front of it? – Rob May 24 '17 at 11:38
  • @Rob Exactly, that is what I say in the last sentence. – Anders May 24 '17 at 13:06
-1

As shown in your example code, there is no sanitization the userinput before placed into the HTML code. With using a payload, such as: domain.com" onmouseenter="alert(1)
This will go straight through to the tag and get executed client-side.

Any script attributes that are valid for that tag will be executed client side. This stackoverflow has a function to sanitize the input in jQuery.

  • Are you sure that actually works? Have you tried it in a fiddle? – Anders May 23 '17 at 11:22
  • Doesn't seem to work. See this fiddle. – Anders May 23 '17 at 11:38
  • That is somewhat counter intuitive, but your answer makes sense. – Eelke May 23 '17 at 11:55
  • 1
    NO; DOM-set values are not naively "printed" to the client; you simply can't set an attrib to contain improper nested quotes. see the html5 spec for details. – dandavis May 23 '17 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.