Jan Jongboom
Jan Jongboom

Reputation: 27342

Replacing hash through location.replace considered harmful?

In an application that I encounter hash replacement is done through:

var loc = window.location + ''
loc = loc.substr(0, loc.indexOf('#'))
loc += '#somehash'
location.replace(loc)

instead of:

location.hash = '#somehash'

Now DOMinator Pro gives a 'URL Redirection JSExecution' warning about this as we call location.replace with data that comes from window.location. What I'm wondering now is whether this is a real threat, as I can't think of a way an attacker can abuse this to perform a URL redirect exploit.

Is this a real attack vector, or a false positive?

Upvotes: 2

Views: 561

Answers (3)

Ilmari Karonen
Ilmari Karonen

Reputation: 50378

I agree with the other answers that this is probably a false positive. Still, it's certainly easy to make mistakes with such code, as Bergi's slice example shows.

In modern browsers, this code could be more cleanly written as:

var loc = new URL("#somehash", location);
location.replace(loc);

This avoids any possibility of subtly messing up the URL manipulation.

Upvotes: 1

Bergi
Bergi

Reputation: 665456

There is an attack vector, though I cannot think of a way it cannot be used in your case.

However, the suggested code is definitely clearer, less error-prone, and therefore safer.

I could contrive an example attack if you had used the slice method instead of substr. Should make no difference, should it? Then try it out with the location http://example.com (no trailing slash). If you'd execute the script with

loc = loc.slice(0, loc.indexOf('#'));

then you'll end up at http://example.co#somehash, which might be registered by the attacker.

Upvotes: 1

Eda190
Eda190

Reputation: 679

I'm gonna say this is a false positive attack vector according to this article, the only known way to inject the website is throught adding the #maliciouscode into your URL bar, however your function ignores the # fragments, so no code is really pasted in the website.

Upvotes: 1

Related Questions