# Side Channel Attacks

## 📑 **Índice**

1. [Fundamentos dos Side-Channel Attacks](#-fundamentos-dos-side-channel-attacks)
2. [Tipos de Canais Laterais](#-tipos-de-canais-laterais)
3. [Power Analysis (SPA/DPA)](#-power-analysis-spadpa)
4. [Timing Attacks](#-timing-attacks)
5. [Electromagnetic Analysis (EMA)](#-electromagnetic-analysis-ema)
6. [Cache Attacks](#-cache-attacks)
7. [Acoustic Analysis](#-acoustic-analysis)
8. [Thermal Analysis](#-thermal-analysis)
9. [Equipamentos e Ferramentas](#-equipamentos-e-ferramentas)
10. [Mitigações e Proteções](#-mitigações-e-proteções)

***

## 🔍 **Fundamentos dos Side-Channel Attacks**

### **O que são Side-Channel Attacks?**

**Side-Channel Attacks (Ataques de Canal Lateral)** são técnicas que exploram informações físicas inadvertidamente vazadas por um sistema durante a execução de operações criptográficas ou sensíveis. Ao invés de atacar a matemática da criptografia, esses ataques exploram implementações físicas, medindo variações em consumo de energia, tempo de execução, emissões eletromagnéticas, som, temperatura, ou outros fenômenos físicos.

### **Contexto Histórico**

```yaml
Evolução dos Side-Channel Attacks:
  1996: Paul Kocher demonstra timing attacks
  1998: Kocher, Jaffe, Jun introduzem Power Analysis
  1999: Primeiros ataques práticos em smart cards
  2000: Electromagnetic analysis (EMA)
  2005: Cache attacks (Prime+Probe)
  2010: Acoustic cryptanalysis
  2015: Rowhammer (DRAM disturbance)
  2018: Spectre e Meltdown
  2020: Thermal attacks
  2024: ML-based side-channel attacks

Motivação:
  ✅ Dispositivos são fisicamente acessíveis
  ✅ Implementações raramente são constant-time
  ✅ Vazamentos são difíceis de eliminar completamente
  ✅ Equipamento ficou acessível (SDR, osciloscópios)
```

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

```mermaid
graph TD
    subgraph "Dispositivo Alvo"
        A[Operação Criptográfica] --> B[Processador]
        B --> C[Consumo de Energia]
        B --> D[Emissão EM]
        B --> E[Tempo de Execução]
        B --> F[Ruído Acústico]
        B --> G[Calor]
    end
    
    subgraph "Medição"
        H[Osciloscópio] --> I[Traços de Potência]
        J[Antena/SDR] --> K[Espectro EM]
        L[Timer] --> M[Medição de Tempo]
    end
    
    subgraph "Análise"
        N[Correlação Estatística] --> O[Extração de Chave]
    end
    
    C --> H
    D --> J
    E --> L
```

### **Comparação com Ataques Tradicionais**

| Característica    | Ataques Tradicionais | Side-Channel Attacks    |
| ----------------- | -------------------- | ----------------------- |
| **Alvo**          | Algoritmo/Software   | Implementação Física    |
| **Acesso**        | Lógico (rede, USB)   | Físico (proximidade)    |
| **Equipamento**   | Computador comum     | Osciloscópio, SDR, etc. |
| **Conhecimento**  | Matemática/Código    | Física/Eletrônica       |
| **Contramedidas** | Criptografia forte   | Hiding, Masking         |
| **Custo**         | Baixo                | Médio a Alto            |

***

## 📊 **Tipos de Canais Laterais**

### **Classificação por Canal Físico**

| Canal        | Grandeza Medida          | Equipamento             | Precisão | Dificuldade |
| ------------ | ------------------------ | ----------------------- | -------- | ----------- |
| **Power**    | Consumo de energia       | Osciloscópio + sonda    | Alta     | Média       |
| **Timing**   | Tempo de execução        | Timer de alta resolução | Média    | Baixa       |
| **EM**       | Radiação eletromagnética | Antena + SDR            | Alta     | Alta        |
| **Cache**    | Acesso à memória         | Software                | Média    | Média       |
| **Acoustic** | Som                      | Microfone sensível      | Baixa    | Alta        |
| **Thermal**  | Temperatura              | Câmera térmica          | Baixa    | Alta        |
| **Optical**  | Luz emitida              | Fotodiodo               | Média    | Alta        |
| **Fault**    | Erros induzidos          | Laser, glitch           | Alta     | Alta        |

***

## ⚡ **Power Analysis (SPA/DPA)**

### **Simple Power Analysis (SPA)**

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

import numpy as np
import matplotlib.pyplot as plt

class SPAAttack:
    """
    Simple Power Analysis - Observação direta de padrões de potência
    """
    
    @staticmethod
    def generate_rsa_trace(key_bits):
        """
        Gerar traço de potência para RSA
        Cada bit: quadrado (sempre) + multiplicação (se bit=1)
        """
        trace = []
        
        for bit in key_bits:
            # Quadrado (sempre presente)
            trace.extend([0.3, 0.5, 0.4, 0.3, 0.2])
            
            if bit == 1:
                # Multiplicação (extra)
                trace.extend([0.4, 0.6, 0.5, 0.4, 0.3])
            else:
                # Gap
                trace.extend([0.1, 0.1, 0.1, 0.1, 0.1])
        
        # Adicionar ruído
        noise = np.random.normal(0, 0.05, len(trace))
        return np.array(trace) + noise
    
    @staticmethod
    def extract_key_from_trace(trace):
        """
        Extrair chave a partir do traço de potência
        """
        key_bits = []
        i = 0
        window = 10
        
        while i + window < len(trace):
            segment = trace[i:i+window]
            peak = np.max(segment)
            
            # Pico alto indica multiplicação (bit=1)
            if peak > 0.6:
                key_bits.append(1)
                i += window
            else:
                key_bits.append(0)
                i += window // 2
        
        return key_bits
    
    @staticmethod
    def attack_demo():
        """
        Demonstração do ataque SPA
        """
        print("=== Simple Power Analysis (SPA) ===\n")
        
        # Chave secreta (exemplo)
        secret_key = [1, 0, 1, 1, 0, 1, 0, 0, 1]
        print(f"Chave secreta: {secret_key}")
        
        # Gerar traço de potência
        trace = SPAAttack.generate_rsa_trace(secret_key)
        
        # Extrair chave
        extracted_key = SPAAttack.extract_key_from_trace(trace)
        print(f"Chave extraída: {extracted_key}")
        
        # Plotar
        plt.figure(figsize=(12, 4))
        plt.plot(trace)
        plt.title('Traço de Potência RSA - SPA')
        plt.xlabel('Tempo (amostras)')
        plt.ylabel('Consumo de Potência (u.a.)')
        plt.grid(True)
        plt.show()
        
        return extracted_key == secret_key

# Executar
SPAAttack.attack_demo()
```

### **Differential Power Analysis (DPA)**

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

import numpy as np
from scipy.stats import pearsonr

class DPAAttack:
    """
    Differential Power Analysis - Correlação estatística
    """
    
    # S-box do AES (simplificada)
    AES_SBOX = [
        0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
        0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76
    ]
    
    @staticmethod
    def hamming_weight(value):
        """Calcular peso de Hamming"""
        return bin(value).count('1')
    
    @staticmethod
    def predict_power(plaintext, key_guess):
        """
        Predizer consumo baseado na saída da S-box
        """
        sbox_input = plaintext ^ key_guess
        sbox_output = DPAAttack.AES_SBOX[sbox_input % 16]  # Simplificado
        return DPAAttack.hamming_weight(sbox_output)
    
    @staticmethod
    def attack_byte(traces, plaintexts, byte_pos):
        """
        Atacar um byte da chave
        """
        correlations = []
        
        for key_guess in range(256):
            # Predições para este guess
            predictions = []
            for pt in plaintexts:
                pred = DPAAttack.predict_power(pt[byte_pos], key_guess)
                predictions.append(pred)
            
            # Correlação para cada ponto no traço
            max_corr = 0
            for point in range(traces.shape[1]):
                trace_points = traces[:, point]
                corr, _ = pearsonr(trace_points, predictions)
                max_corr = max(max_corr, abs(corr))
            
            correlations.append((key_guess, max_corr))
        
        # Melhor guess
        best_guess = max(correlations, key=lambda x: x[1])
        return best_guess
    
    @staticmethod
    def attack_demo():
        """
        Demonstração do ataque DPA
        """
        print("=== Differential Power Analysis (DPA) ===\n")
        
        # Simular dados
        num_traces = 1000
        trace_length = 500
        real_key = 0x42
        
        # Gerar traces simulados
        traces = []
        plaintexts = []
        
        for _ in range(num_traces):
            pt = np.random.randint(0, 256)
            plaintexts.append(pt)
            
            # Simular traço com vazamento
            trace = np.random.normal(0, 0.1, trace_length)
            pred = DPAAttack.predict_power(pt, real_key)
            trace[250] += pred * 0.5  # Vazamento no ponto 250
            traces.append(trace)
        
        traces = np.array(traces)
        plaintexts = np.array(plaintexts)
        
        # Atacar
        best_guess, corr = DPAAttack.attack_byte(traces, plaintexts, 0)
        
        print(f"Chave real: {hex(real_key)}")
        print(f"Chave recuperada: {hex(best_guess)} (correlação: {corr:.4f})")
        
        return best_guess == real_key

# Executar
DPAAttack.attack_demo()
```

***

## ⏱️ **Timing Attacks**

### **Ataque de Timing a Comparação de Strings**

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

import time
import statistics

class TimingAttack:
    """
    Ataque de timing em comparação de strings
    """
    
    @staticmethod
    def vulnerable_compare(a, b):
        """
        Comparação vulnerável (short-circuit)
        """
        if len(a) != len(b):
            return False
        
        for i in range(len(a)):
            if a[i] != b[i]:
                return False
        return True
    
    @staticmethod
    def constant_time_compare(a, b):
        """
        Comparação com tempo constante
        """
        if len(a) != len(b):
            return False
        
        result = 0
        for i in range(len(a)):
            result |= ord(a[i]) ^ ord(b[i])
        return result == 0
    
    @staticmethod
    def measure_compare_time(secret, guess, compare_func, iterations=1000):
        """
        Medir tempo de comparação
        """
        times = []
        
        for _ in range(iterations):
            start = time.perf_counter_ns()
            compare_func(secret, guess)
            end = time.perf_counter_ns()
            times.append(end - start)
        
        return statistics.mean(times)
    
    @staticmethod
    def attack(secret, compare_func, charset='abcdefghijklmnopqrstuvwxyz'):
        """
        Extrair secret caractere por caractere
        """
        recovered = ""
        
        for pos in range(len(secret)):
            best_char = None
            best_time = 0
            
            for char in charset:
                guess = recovered + char + 'a' * (len(secret) - pos - 1)
                avg_time = TimingAttack.measure_compare_time(secret, guess, compare_func)
                
                print(f"  Tentando '{char}': {avg_time:.2f} ns")
                
                if avg_time > best_time:
                    best_time = avg_time
                    best_char = char
            
            if best_char:
                recovered += best_char
                print(f"[+] Posição {pos}: '{best_char}'")
            else:
                break
        
        return recovered
    
    @staticmethod
    def attack_demo():
        """
        Demonstração do ataque de timing
        """
        print("=== Timing Attack ===\n")
        
        secret = "secretpassword"
        print(f"Secret: {secret}")
        
        print("\n[1] Ataque à comparação vulnerável:")
        recovered = TimingAttack.attack(secret, TimingAttack.vulnerable_compare)
        print(f"\nSecret recuperada: {recovered}")
        
        print("\n[2] Tentativa com comparação constante:")
        recovered = TimingAttack.attack(secret, TimingAttack.constant_time_compare)
        print(f"\nSecret recuperada: {recovered}")

# Executar
TimingAttack.attack_demo()
```

### **Ataque de Timing a RSA**

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

import time
import random

class RSATimingAttack:
    """
    Ataque de timing à exponenciação modular RSA
    """
    
    @staticmethod
    def vulnerable_mod_exp(base, exponent, modulus):
        """
        Exponenciação vulnerável (square-and-multiply)
        """
        result = 1
        base = base % modulus
        
        # Para cada bit do expoente
        while exponent > 0:
            # Quadrado (sempre)
            result = (result * result) % modulus
            
            # Multiplicação (apenas se bit=1) - vaza timing!
            if exponent & 1:
                result = (result * base) % modulus
            
            exponent >>= 1
        
        return result
    
    @staticmethod
    def constant_time_mod_exp(base, exponent, modulus):
        """
        Exponenciação com tempo constante (Montgomery ladder)
        """
        r0 = 1
        r1 = base
        
        # Para cada bit do MSB para LSB
        for i in range(exponent.bit_length() - 1, -1, -1):
            bit = (exponent >> i) & 1
            
            # Sempre executa ambas as operações
            if bit == 0:
                r1 = (r1 * r0) % modulus
                r0 = (r0 * r0) % modulus
            else:
                r0 = (r0 * r1) % modulus
                r1 = (r1 * r1) % modulus
        
        return r0
    
    @staticmethod
    def measure_exp_time(base, exponent, modulus, exp_func, iterations=100):
        """
        Medir tempo de exponenciação
        """
        times = []
        for _ in range(iterations):
            start = time.perf_counter_ns()
            exp_func(base, exponent, modulus)
            end = time.perf_counter_ns()
            times.append(end - start)
        
        return statistics.mean(times)
    
    @staticmethod
    def attack_bit(secret_exp, modulus, known_bits, exp_func):
        """
        Atacar um bit do expoente
        """
        # Criar dois expoentes: um com bit=0 e outro com bit=1
        pos = len(known_bits)
        mask = 1 << (secret_exp.bit_length() - pos - 1)
        
        exp0 = (known_bits << (pos + 1)) | (0 << pos)
        exp1 = (known_bits << (pos + 1)) | (1 << pos)
        
        # Medir tempos
        base = random.randint(2, modulus - 1)
        t0 = RSATimingAttack.measure_exp_time(base, exp0, modulus, exp_func)
        t1 = RSATimingAttack.measure_exp_time(base, exp1, modulus, exp_func)
        
        # O tempo maior indica o bit correto
        return 1 if t1 > t0 else 0

# Uso
# timing = RSATimingAttack()
```

***

## 🔌 **Cache Attacks (Prime+Probe)**

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

import time
import array

class CacheAttack:
    """
    Ataque de cache (Prime+Probe)
    """
    
    def __init__(self, cache_size=1024*1024):
        self.cache_size = cache_size
        self.probe_array = array.array('B', [0]) * cache_size
    
    def prime_cache(self):
        """
        Preencher cache com dados controlados
        """
        for i in range(0, self.cache_size, 64):  # 64 bytes por linha de cache
            self.probe_array[i] = 1
    
    def probe_cache(self):
        """
        Medir tempo de acesso para detectar desalojamento
        """
        times = []
        for i in range(0, self.cache_size, 64):
            start = time.perf_counter_ns()
            _ = self.probe_array[i]
            elapsed = time.perf_counter_ns() - start
            times.append((i, elapsed))
        
        return times
    
    def detect_access(self):
        """
        Detectar quais linhas de cache foram acessadas
        """
        self.prime_cache()
        
        # Aguardar processo alvo executar
        time.sleep(0.1)
        
        probe_results = self.probe_cache()
        
        # Linhas com tempo de acesso alto foram desalojadas
        accessed = [addr for addr, t in probe_results if t > 100]
        return accessed
    
    def attack_demo(self):
        """
        Demonstração do ataque de cache
        """
        print("=== Cache Attack (Prime+Probe) ===\n")
        
        attack = CacheAttack()
        accessed = attack.detect_access()
        
        print(f"Linhas de cache acessadas: {len(accessed)}")
        print(f"Primeiras 10: {accessed[:10]}")

# Executar
# attack = CacheAttack()
# attack.attack_demo()
```

***

## 📡 **Electromagnetic Analysis (EMA)**

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

import numpy as np
from scipy import signal

class EMAttack:
    """
    Análise de emissões eletromagnéticas
    """
    
    @staticmethod
    def simulate_em_trace(operation_type, length=1000):
        """
        Simular traço EM para diferentes operações
        """
        t = np.linspace(0, 1, length)
        
        if operation_type == 'aes':
            # Padrão AES (10 rounds)
            trace = np.zeros(length)
            for i in range(10):
                start = i * 100
                trace[start:start+50] += 0.5 * np.sin(2 * np.pi * 10 * t[start:start+50])
        elif operation_type == 'rsa':
            # Padrão RSA
            trace = 0.3 * np.sin(2 * np.pi * 20 * t) + 0.2 * np.random.random(length)
        else:
            trace = np.random.normal(0, 0.1, length)
        
        return trace
    
    @staticmethod
    def analyze_spectrum(trace, fs=1000):
        """
        Analisar espectro de frequência
        """
        f, Pxx = signal.periodogram(trace, fs)
        
        # Encontrar frequências dominantes
        peaks = []
        for i in range(1, len(Pxx)-1):
            if Pxx[i] > Pxx[i-1] and Pxx[i] > Pxx[i+1] and Pxx[i] > 0.01:
                peaks.append(f[i])
        
        return f, Pxx, peaks
    
    @staticmethod
    def attack_demo():
        """
        Demonstração do ataque EM
        """
        print("=== Electromagnetic Analysis ===\n")
        
        # Simular traço EM de operação AES
        trace = EMAttack.simulate_em_trace('aes')
        
        # Analisar espectro
        f, Pxx, peaks = EMAttack.analyze_spectrum(trace)
        
        print(f"Frequências dominantes: {peaks[:5]}")
        
        # Plotar
        import matplotlib.pyplot as plt
        
        fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))
        
        ax1.plot(trace)
        ax1.set_title('Traço EM no Domínio do Tempo')
        ax1.set_xlabel('Tempo (amostras)')
        ax1.set_ylabel('Amplitude')
        
        ax2.semilogy(f, Pxx)
        ax2.set_title('Espectro EM')
        ax2.set_xlabel('Frequência (Hz)')
        ax2.set_ylabel('Densidade Espectral')
        ax2.grid(True)
        
        plt.tight_layout()
        plt.show()

# Executar
# EMAttack.attack_demo()
```

***

## 🔊 **Acoustic Analysis**

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

import numpy as np
import sounddevice as sd

class AcousticAttack:
    """
    Análise de ruído acústico de capacitores/indutores
    """
    
    @staticmethod
    def record_audio(duration=5, fs=44100):
        """
        Gravar áudio do dispositivo
        """
        print(f"[*] Gravando áudio por {duration} segundos...")
        recording = sd.rec(int(duration * fs), samplerate=fs, channels=1)
        sd.wait()
        return recording.flatten()
    
    @staticmethod
    def analyze_frequencies(audio, fs=44100):
        """
        Analisar frequências do áudio
        """
        from scipy.fft import fft, fftfreq
        
        N = len(audio)
        yf = fft(audio)
        xf = fftfreq(N, 1/fs)
        
        # Encontrar picos
        magnitude = np.abs(yf)
        peaks = []
        
        for i in range(1, len(magnitude)-1):
            if magnitude[i] > magnitude[i-1] and magnitude[i] > magnitude[i+1]:
                if magnitude[i] > np.mean(magnitude) * 2:
                    peaks.append((xf[i], magnitude[i]))
        
        return xf, magnitude, peaks
    
    @staticmethod
    def detect_operation(peaks):
        """
        Detectar operação criptográfica por frequências
        """
        # Diferentes operações geram diferentes frequências
        # devido ao chaveamento de transistores
        
        freq_bands = {
            'idle': (0, 1000),
            'aes_encrypt': (5000, 10000),
            'aes_decrypt': (10000, 15000),
            'rsa': (15000, 20000)
        }
        
        for op, (low, high) in freq_bands.items():
            for freq, mag in peaks:
                if low <= freq <= high:
                    return op
        
        return 'unknown'

# Uso
# attack = AcousticAttack()
# audio = attack.record_audio(5)
# xf, mag, peaks = attack.analyze_frequencies(audio)
# operation = attack.detect_operation(peaks)
```

***

## 🔥 **Thermal Analysis**

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

import numpy as np

class ThermalAttack:
    """
    Análise de variações térmicas
    """
    
    @staticmethod
    def simulate_temperature(power_trace, ambient_temp=25, thermal_capacity=100):
        """
        Simular temperatura a partir do consumo de energia
        """
        temperature = [ambient_temp]
        
        for p in power_trace:
            # Modelo térmico simplificado
            delta_t = (p - (temperature[-1] - ambient_temp)) / thermal_capacity
            temperature.append(temperature[-1] + delta_t)
        
        return np.array(temperature)
    
    @staticmethod
    def extract_key_from_temperature(temp_trace):
        """
        Extrair informações do traço térmico
        """
        # Operações diferentes geram calor diferente
        # Chave pode ser inferida pelo padrão térmico
        
        # Derivada para detectar mudanças
        derivative = np.diff(temp_trace)
        
        # Encontrar picos de atividade
        peaks = []
        for i in range(1, len(derivative)-1):
            if derivative[i] > derivative[i-1] and derivative[i] > derivative[i+1]:
                peaks.append(i)
        
        return peaks
    
    @staticmethod
    def attack_demo():
        """
        Demonstração do ataque térmico
        """
        print("=== Thermal Analysis ===\n")
        
        # Simular traço de potência de operação AES
        power = np.zeros(10000)
        for i in range(10):  # 10 rounds
            start = i * 1000
            power[start:start+500] = 1.0  # Operação intensa
            power[start+500:start+1000] = 0.2  # Gap
        
        # Simular temperatura
        temp = ThermalAttack.simulate_temperature(power)
        
        # Extrair informações
        peaks = ThermalAttack.extract_key_from_temperature(temp)
        
        print(f"Picos de atividade detectados: {len(peaks)}")
        print(f"Rounds identificados: aproximadamente {len(peaks)}")

# Executar
ThermalAttack.attack_demo()
```

***

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

### **Contramedidas por Canal**

```yaml
Proteções Contra Side-Channel Attacks:
  
  Power Analysis:
    - Hiding: adicionar ruído, operações dummy
    - Masking: dividir dados em shares aleatórios
    - Shuffling: randomizar ordem de operações
    - Balanced logic (WDDL)
  
  Timing Attacks:
    - Tempo constante (constant-time)
    - Operações condicionais balanceadas
    - Blinding (randomizar dados)
    - Delay aleatório
  
  EM Attacks:
    - Blindagem eletromagnética
    - Filtros EMI
    - Randomização de clock
    - Uso de capacitores de decoupling
  
  Cache Attacks:
    - Cache flushing
    - Cache partitioning
    - Constant-time access
    - Hardware transactional memory
  
  Acoustic/Thermal:
    - Resfriamento ativo
    - Isolamento acústico
    - Randomização de carga
```

### **Implementação Constant-Time**

```c
// constant_time.c - Comparação com tempo constante

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

// Comparação de strings com tempo constante
int constant_time_memcmp(const void *a, const void *b, size_t n) {
    const uint8_t *pa = a;
    const uint8_t *pb = b;
    uint8_t result = 0;
    
    for (size_t i = 0; i < n; i++) {
        result |= pa[i] ^ pb[i];
    }
    
    return result;  // 0 se igual
}

// Seleção condicional com tempo constante
uint32_t constant_time_select(int condition, uint32_t if_true, uint32_t if_false) {
    uint32_t mask = -condition;  // all ones if condition is true
    return (if_true & mask) | (if_false & ~mask);
}
```

### **Masking para Power Analysis**

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

import random

class MaskingProtection:
    """
    Proteção contra DPA via masking
    """
    
    @staticmethod
    def xor_mask(value, mask=None):
        """
        Aplicar máscara XOR
        """
        if mask is None:
            mask = random.randint(0, 255)
        return value ^ mask, mask
    
    @staticmethod
    def unmask(value, mask):
        """
        Remover máscara
        """
        return value ^ mask
    
    @staticmethod
    def masked_sbox_lookup(sbox_input, sbox, mask_in, mask_out):
        """
        S-box mascarada (S'(x ⊕ mask_in) = S(x) ⊕ mask_out)
        """
        masked_sbox = [0] * 256
        
        for x in range(256):
            masked_input = x ^ mask_in
            sbox_output = sbox[x]
            masked_output = sbox_output ^ mask_out
            masked_sbox[masked_input] = masked_output
        
        return masked_sbox

# Uso
protection = MaskingProtection()
```

***

## 🛠️ **Equipamentos e Ferramentas**

### **Hardware para Side-Channel**

| Equipamento              | Função                   | Preço (R$)    | Onde Comprar       |
| ------------------------ | ------------------------ | ------------- | ------------------ |
| **Rigol DS1054Z**        | Osciloscópio 4 canais    | \~R$2500-3000 | Mercado Livre      |
| **PicoScope 2204A**      | Osciloscópio USB         | \~R$1200-1800 | Importação         |
| **Sonda de Corrente**    | Mede consumo de corrente | \~R$800-2000  | AliExpress, Mouser |
| **Sonda Diferencial**    | Mede tensão diferencial  | \~R$600-1500  | AliExpress         |
| **HackRF One**           | SDR para EM              | \~R$1000-1500 | AliExpress         |
| **ChipWhisperer**        | SCA especializado        | \~R$2500-3500 | newae.com          |
| **Total Setup Básico**   | Osciloscópio + Sonda     | \~R$3500-5000 | -                  |
| **Total Setup Avançado** | + ChipWhisperer          | \~R$6000-8000 | -                  |

### **Ferramentas de Software**

```bash
# ChipWhisperer
pip install chipwhisperer

# Power Analysis Toolkit
git clone https://github.com/IAIK/scapy

# DPA Contest Framework
git clone https://github.com/ikizhvatov/easydpa

# OpenSCA
pip install opensca
```

***

## 📊 **Conclusão**

### **Resumo Técnico**

```yaml
Side-Channel Attacks:
  ✅ Exploram vazamentos físicos inevitáveis
  ✅ Podem quebrar criptografia forte
  ✅ Equipamento ficou acessível
  ✅ Múltiplos canais disponíveis

Ameaças:
  - Power analysis (SPA/DPA)
  - Timing attacks
  - Cache attacks (Spectre, Meltdown)
  - EM analysis
  - Acoustic/Thermal analysis

Defesas:
  - Hiding (ruído, operações dummy)
  - Masking (divisão de dados)
  - Tempo constante
  - Blindagem física
```


---

# 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/hardware/iot/side-channel-attacks.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.
