---
id: wiki-2026-0508-side-channel-attack
title: Side-channel Attack
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Side-channel, Timing Attack, Cache Attack]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
verification_status: applied
tags: [security, cryptography, hardware, attack]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: c/python
  framework: openssl/numpy
---

# Side-channel Attack

## 매 한 줄
> **"매 알고리즘 의 정상 output 이 아닌 부수 누출 (시간, 전력, 캐시, EM 방사) 로 secret 추출"**. 매 1996 Kocher 의 timing attack on RSA 가 시초. 매 2018 Spectre/Meltdown 으로 mass awareness. 매 2026 LLM weight extraction, GPU side-channel 까지 확장.

## 매 핵심

### 매 카테고리
- **Timing**: 시간 차이 → key 추출 (RSA, AES, PIN compare).
- **Power analysis (SPA/DPA)**: 전력 trace → key bits.
- **EM**: 전자기 방사 → 동일 정보.
- **Cache (Flush+Reload, Prime+Probe)**: shared L3 cache.
- **Speculative (Spectre, Meltdown)**: speculative exec leak via cache.
- **Microarchitectural (LVI, Foreshadow, Zenbleed)**: CPU bug exploit.
- **Acoustic / Optical**: 매 keyboard sound, monitor flicker.
- **Software**: padding oracle, error message disclosure.

### 매 ML / AI 신종
- **Membership inference**: 매 model 출력 으로 training data 멤버 여부 추론.
- **Model extraction**: 매 query → weight stealing.
- **Prompt injection side-channel**: token timing.

### 매 응용 (defensive)
1. Constant-time crypto code.
2. Cache partitioning.
3. KASLR + KPTI (Meltdown 대응).
4. Differential privacy (ML).

## 💻 패턴

### Timing-vulnerable string compare
```c
// VULNERABLE
int compare_password(const char* a, const char* b, size_t n) {
    for (size_t i = 0; i < n; i++) {
        if (a[i] != b[i]) return 0;  // early exit → timing leak
    }
    return 1;
}

// SAFE — constant time
int safe_compare(const uint8_t* a, const uint8_t* b, size_t n) {
    uint8_t diff = 0;
    for (size_t i = 0; i < n; i++) diff |= a[i] ^ b[i];
    return diff == 0;
}
```

### Timing attack demo
```python
import time, statistics

def measure(guess, target):
    samples = []
    for _ in range(1000):
        t0 = time.perf_counter_ns()
        compare_password(guess, target)
        samples.append(time.perf_counter_ns() - t0)
    return statistics.median(samples)

# Brute force first byte: char with longest median = correct
for c in range(256):
    guess = bytes([c]) + b'\x00'*15
    print(c, measure(guess, target_secret))
```

### Constant-time AES (lookup-free)
```c
// Bitsliced implementation — no data-dependent table lookup → no cache leak
// Reference: bsaes (BearSSL)
void aes_bitsliced_encrypt(uint64_t state[8], uint64_t rk[88]);
```

### Spectre v1 (bounds-check bypass)
```c
// VULNERABLE
if (idx < array_size) {
    y = array2[array1[idx] * 256];  // speculatively executed even if idx large
}
// → array1 OOB read → array2 cache state encodes secret
```

### Spectre mitigation (LFENCE)
```c
if (idx < array_size) {
    __asm__ volatile("lfence" ::: "memory");  // serialize speculation
    y = array2[array1[idx] * 256];
}
```

### Padding oracle (CBC mode)
```python
# VULNERABLE: distinguishable error messages
def decrypt(ciphertext):
    plaintext = aes_cbc_decrypt(ciphertext, key)
    try:
        unpad(plaintext)
    except PaddingError:
        return "Invalid padding"  # ← oracle leak
    return "Invalid MAC"

# SAFE: encrypt-then-MAC (always check MAC first, constant-time)
```

### Differential privacy ML defense
```python
import opacus
from torch.utils.data import DataLoader

privacy_engine = opacus.PrivacyEngine()
model, optimizer, dl = privacy_engine.make_private(
    module=model, optimizer=optimizer, data_loader=dl,
    noise_multiplier=1.1, max_grad_norm=1.0,
)
```

### Cache flush+reload
```c
// Probe shared library page
clflush(&victim_addr);
victim_function();  // runs in target process
uint64_t t0 = rdtsc(); volatile char x = *victim_addr; uint64_t t1 = rdtsc();
if (t1 - t0 < THRESHOLD) printf("hit — accessed by victim\n");
```

## 매 결정 기준
| 상황 | Approach |
|---|---|
| Crypto code (key compare, AES) | Constant-time + bitsliced |
| Web auth | hmac.compare_digest / crypto.timingSafeEqual |
| Cloud multi-tenant | Cache partitioning + Spectre patches |
| ML model serving | Output rate-limit + DP training |
| Embedded HW | Power analysis countermeasures (masking, hiding) |

**기본값**: constant-time primitives + libsodium / BoringSSL 의 사용.

## 🔗 Graph
- 변형: [[Spectre]] · [[Rowhammer]] · [[Timing Attack]]
- 응용: [[Differential Privacy]]

## 🤖 LLM 활용
**언제**: constant-time review, vulnerable code 의 패턴 인식, mitigation suggestions.
**언제 X**: actual exploit development (legal/ethical line).

## ❌ 안티패턴
- **Naive memcmp for secrets**: timing leak.
- **Data-dependent branch in crypto**: cache + branch predictor leak.
- **"Roll your own crypto"**: 매 side-channel free 의 어려움.
- **Verbose error messages**: padding oracle 류.

## 🧪 검증 / 중복
- Verified (Kocher 1996, Spectre paper 2018, Intel/AMD advisories).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full side-channel coverage |
