> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/web-appsec/injections/cross-site-scripting-xss.md).

# Cross-Site Scripting (XSS)

Cross-Site Scripting (XSS) is a web vulnerability that allows attackers to inject malicious JavaScript into a victim’s browser, executing in the context of a trusted application. This can lead to session hijacking, data theft, or unauthorised actions.

***

#### Types of XSS

1. Reflected XSS
   * A malicious script is reflected from the server response (e.g., via URL or input).
   * Triggered when the victim clicks a crafted link.
2. Stored XSS
   * Payload is stored on the server (e.g., database, comments).
   * Executed when other users load the affected page.
3. DOM-based XSS
   * Occurs entirely on the client-side.
   * Manipulates the DOM via unsafe JavaScript using sources like URL, document.location, etc.

***

### Impact

* **Session hijacking:** Steal or abuse user session cookies to impersonate users.
* **Account takeover:** Perform actions on behalf of authenticated users.
* **Unauthorized actions:** Perform actions such as changing account settings or submitting forms as the victim.
* **Malware delivery:** Redirect users to malicious websites or deliver malware.
* **Phishing attacks:** Display fake login forms or deceptive content to steal user credentials.

***

### Prevention

* **Output encoding/escaping:** Encode untrusted data according to the output context (HTML, JavaScript, CSS, URL, or attributes).
* **Validate and sanitize input:** Filter or sanitize untrusted input where appropriate.
* **Content Security Policy (CSP):** Implement a strict CSP to reduce the impact of injected scripts.
* **Use HTTPOnly and Secure cookies:** Prevent JavaScript from accessing session cookies and ensure secure transmission.
* **Validate URLs:** Prevent `javascript:` and other dangerous URL schemes from being injected.
* **Avoid unsafe DOM APIs:** Avoid APIs such as `innerHTML`, `outerHTML`, and `document.write`; use safer alternatives like `textContent` or `createElement`.
* **Enable framework protections:** Use the built-in XSS protections provided by modern frameworks.
