3

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?

4
  • Why do you need them to be able to use relative links? This would make everything a lot easier Commented Jun 4, 2018 at 9:22
  • You could check the input with a regex. Commented Jun 4, 2018 at 9:23
  • I'm not privy to the design decisions I'm afraid, this is something I have been asked to work on that is 5 or 6 years old. I would change the whole thing if I could Commented Jun 4, 2018 at 9:24
  • @pgGriff did my answer help you? Commented Jun 4, 2018 at 10:14

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.