khl1392
khl1392

Reputation: 19

When are dynamic scripts executed?

I was doing the google XSS games (https://xss-game.appspot.com/level2), but I couldn't quite figure out why level 2 wasn't working the way I was expecting. Even though the hint says that script tags won't work, I didn't know why. My question is basically when are dynamic script tags executed and does this vary by browser?

I tried something simple as:

<script>alert();</script>

And while it adds the element to the page, it doesn't do what I had hoped.

I found this post which has the same problem, but the solution is just an answer, but not an explanation: Dynamically added script will not execute

Upvotes: 1

Views: 404

Answers (2)

Adamsan
Adamsan

Reputation: 662

The answer to your question is that <script> tags added via .innerHTML do not execute.

From https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML :

Security considerations

It is not uncommon to see innerHTML used to insert text in a web page. This comes with a security risk.

var name = "John";
// assuming el is an HTML DOM element
el.innerHTML = name; // harmless in this case

// ...

name = "<script>alert('I am John in an annoying alert!')</script>";
el.innerHTML = name; // harmless in this case

Although this may look like a cross-site scripting attack, the result is harmless. HTML5 specifies that a tag inserted via innerHTML should not execute.

However, there are ways to execute JavaScript without using elements, so there is still a security risk whenever you use innerHTML to set strings over which you have no control. For example:

var name = "<img src=x onerror=alert(1)>";
el.innerHTML = name; // shows the alert

Upvotes: 0

Yuriy Galanter
Yuriy Galanter

Reputation: 39777

If a site sanitizes only SCRIPT tags but allows other HTML - it opens itself to XSS. The hint in the Level 2 is text in the message window having some HTML formatting (italic, color etc.) so the assumption here - HTML tags are allowed.

So you can enter something like

<i>Hello Xss</i>

Into the message window to display text in italic. But a DOM element can have an event handler attached to it - you can include executable JavaScript into event handler without any SCRIPT tags.

Try entering this into message window:

<i onmouseover="alert(1)">Hello Xss</i>

and after submitting message wave mouse over your message text.

Upvotes: 1

Related Questions