Search code examples
javascriptxmlhttprequestxssowaspveracode

Javascript: Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS)


I'm spending time trying to fix veracode scan flaw CWE-80 Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS).

What I do is an HTTP call to my backend in order to open a blob with a download file.

    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "arraybuffer";
    xhr.onreadystatechange =  () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var windowUrl = window.URL || window.webkitURL;
            var blobUrl = windowUrl.createObjectURL(new Blob([xhr.response]));
            const doc = document.createElement('a');
            document.body.appendChild(doc);
            doc.href = blobUrl;
            if (filename) {
                doc.download = filename;
            }
            doc.click();
            windowUrl.revokeObjectURL(url);
        }
    }
        xhr.send();

veracode complains about this line

document.body.appendChild(doc);

This call to Node.appendChild() contains a cross-site scripting (XSS) flaw. The application populates the HTTP response with untrusted input, allowing an attacker to embed malicious content, such as Javascript code, which will be executed in the context of the victim's browser. XSS vulnerabilities are commonly exploited to steal or manipulate cookies, modify presentation of content, and compromise confidential information, with new attack vectors being discovered on a regular basis.

Not sure what kind of verification upon my response I need to apply.


Solution

  • This is quite a complex topic, the first line of defence should be to Sanitise the HTML before adding it to the page with a tool like this.

    https://github.com/jitbit/HtmlSanitizer

    Wikipedia has a great summary on different prevention techniques.

    https://en.wikipedia.org/wiki/Cross-site_scripting#Preventive_measures

    Their is also this Great cheatsheet on XSS prevention

    https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html