3

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.

1

2 Answers 2

6

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.
0
-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.

4
  • Are you sure that actually works? Have you tried it in a fiddle?
    – Anders
    Commented May 23, 2017 at 11:22
  • Doesn't seem to work. See this fiddle.
    – Anders
    Commented May 23, 2017 at 11:38
  • That is somewhat counter intuitive, but your answer makes sense.
    – Eelke
    Commented May 23, 2017 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
    Commented May 23, 2017 at 17:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .