javascriptsecurityxssowasp

How to create "unsafe" environment for JavaScript XSS testing


I am learning about XSS security and how to prevent it. To do that I would like to create voulnerable code and then see how adding security measures would fix it.

I created an html file that accepts parameters and should execute alert when called like this:

http://localhost/index.html?name=<script>alert('XSS attack!')</script>

but I am unable to succeed - it looks like browsers are already doing some security checks for me. What would be the best way how to create a working environment where I can execute such code and then fix this security hole with CSP?


Solution

  • script tags don't get executed when you add them to an existing DOM as HTML text (for instance, by assigning to innerHTML or using insertAdjacentHTML). But if you stored that "name" server-side, then included it in the server-side rendering of the page (both without adequate sanitization), it would run and the Evil Code™ would execute. That kind of vulnerability is sadly common.

    But onxyz attributes don't even require that kind of server round-trip: ?name=<img src="-" onError="evilCode();">Joe That would trigger the code even when added via innerHTML and such:

    document.getElementById("btn").addEventListener("click", () => {
        const name = document.getElementById("name").value;
        document.getElementById("display").innerHTML =
            "Your name is: " + name;
    });
    <label>
        Name:
        <input id="name" type="text" value="<img src=&quot;-&quot; onError=&quot;alert('XSS attack!')&quot;>Joe">
    </label>
    <input id="btn" type="button" value="Save">
    <div id="display"></div>