Harry Blue
Harry Blue

Reputation: 4512

JS Prevent XSS but allow HTML URL

I have an Angular 1 app, with a form input used for creating site notifications.

A user can enter a full url http://example.com or they can also enter a path within the application /foo/barboo

However, an attacker could also enter javascript:alert(1);// and when the notification link is pressed, the JS will fire.

Is it possible to encode this input but still allow url's to be treated as such?

Upvotes: 3

Views: 482

Answers (1)

Luca Kiebel
Luca Kiebel

Reputation: 10096

Here is a regex that'll match both URIs starting with a schema (http/https/ftp) and "relative" URIs starting with a slash:

/((\/[\w-.]+)(\/[\w-.]+)*\/?)|(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?)/gi

const re = /((\/[\w-.]+)(\/[\w-.]+)*\/?)|(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?)/gi

console.log("https://example.com/foo/bar".match(re)[0]); //matches 

console.log("/foo/bar/baz/bim".match(re)[0]); //matches

console.log("javascript:alert('xss');//".match(re)); //doesn't match (null)

console.log("/foo/bar/baz/bim.html".match(re)[0]); //matches

console.log("https://example.com/foo/bar-api.php?e=mc2".match(re)[0]); //matches

regexr.com

Upvotes: 2

Related Questions