Make sure the URL is relative before navigating with JavaScript location.replace ()

I have a login page https://example.com/login#destination, where destinationis the destination URL that the user tried to go to when they needed to log in.
(i.e. https://example.com/destination)

The JavaScript I was thinking about was

function onSuccessfulLogin() {
    location.replace(location.hash.substring(1) || 'default')
}
  • This will result in an XSS vulnerability by the link attacker https://example.com/login#javascript:..

  • I also need to prevent navigation to the site with the username after logging in. https://example.com/login#https://looks-like-example.com
    orhttps://example.com/login#//looks-like-example.com

How to set up onSuccessfulLogin, to make sure that the URL-address in the hash segment #is relative the URL-address, and does not begin with javascript:, https:, //or any other absolute navigation scheme?

, URL- , location.origin . , , ?

+4
2

OWASP :

, , URL- URL-, URL.

, URL-:

// https://example.com/login#destination

var keyToUrl = {
  destination: 'https://example.com/destination',
  defaults: 'https://example.com/default'
};

function onSuccessfulLogin() {
  var hash = location.hash.substring(1);
  var url = keyToUrl[hash] || keyToUrl.defaults;

  location.replace(url);
}

URL- :

// https://example.com/login#destination

function onSuccessfulLogin() {
  var path = location.hash.substring(1);
  var url = 'https://example.com/' + path;

  location.replace(url);
}

.

+1

XSS.

, , /^[a-z]+:/i . , , /^[^:\/?]+:/ -, / ?, :. /^\/\/, URL- , :

// Either
var rexIsProtocol = /(?:^[a-z]+:)|(?:^\/\/)/i;
// Or
var rexIsProtocol = /(?:^[^:\/?]+:)|(?:^\/\/)/i;

:

var url = location.hash.substring(1).trim(); // trim to deal with whitespace
if (rexIsProtocol.test(url)) {
    // It starts with a protocol
} else {
    // It doesn't
}

, , , , - javascript:, .

0

All Articles