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.

Rob
  • 143
  • 1
  • 6
  • See also [Is jQuery .attr() method XSS safe?](https://stackoverflow.com/questions/32520509/is-jquery-attr-method-xss-safe) – Sjoerd May 23 '17 at 08:27

2 Answers2

7

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.
Anders
  • 64,406
  • 24
  • 178
  • 215
-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.

Eelke
  • 506
  • 1
  • 5
  • 18