Ad

Is This Vulnerable To XSS?

- 1 answer

I know this is vulnerable as a hacker could embed an image that visits the site URL and do all sorts with the 'message' parameter:

<script>
var message = // get message parameter from URL, e.g domain.com?message=hello+there
document.write('Your message: ' + message);
</script>

...but is there any way a hacker could do anything with this (on its own without any other JS)?:

<script>
function displayMessage(message) {
  document.write(message);
}
</script>

Obviously I could open a console in a browser and type anything in, but could a hacker invoke a JavaScript method somehow (with this code alone)?

I know the method could be invoked if the website also had the code at the very top, but can a method be invoked on its own?

Btw. I'm not exactly looking to do the above, it just helps me understand this.

What have I tried?

Ad

Answer

In the first code, message is an untrusted string which can contain malicious code. Parsing it as HTML may execute that code:

var message = '<img src="//" onerror="alert(\'You are pwned!\')" />';
document.write('Your message: ' + message);

The second code is different. It's just a function, it doesn't run anything by itself.

Of course, if you call it with an untrusted string, you will have the same problem than in the first one. Therefore, don't do that.

However, attackers can't call arbitrary functions. Well, if they can, it means you are already pwned, so it doesn't matter anymore. I mean, if an attacker has gained enough "privileges" to be able to call displayMessage, why bother calling it instead of calling document.write (or whatever) directly?

Ad
source: stackoverflow.com
Ad