[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,94 +2,193 @@
|
||||
id: wiki-2026-0508-timing-attack
|
||||
title: Timing Attack
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-392C3B]
|
||||
aliases: [Timing Side Channel, Constant Time Comparison]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [security, side-channel, cryptography, constant-time]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Timing Attack"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: nodejs
|
||||
---
|
||||
|
||||
# [[Timing Attack|Timing Attack]]
|
||||
# Timing Attack
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> 타이밍 공격(Timing Attack)은 캐시 적중률이나 메모리 접근 패턴 등 시스템의 작업 수행 시간을 극도로 정밀하게 측정함으로써 의도치 않은 정보를 유출하거나 보안 경계를 우회하는 부채널 공격([[Side-channel Attack|Side-channel Attack]])의 일종입니다 [1-3]. 스펙터(Spectre)와 멜트다운(Meltdown)이 대표적인 예로, CPU의 추측 실행(Speculative Execution) 기능을 악용하여 L1 캐시와 메인 메모리 간의 접근 지연 시간 차이를 관찰함으로써 데이터를 탈취합니다 [3-5]. 웹 환경에서 이러한 공격은 신뢰할 수 없는 [[JavaScript|JavaScript]]나 WebAssembly 코드가 호스트 프로세스의 메모리를 읽을 수 있게 하므로, 브라우저 차원의 타이머 정밀도 저하 및 분기 없는 보안 검사([[Branchless Security Checks|Branchless Security Checks]]) 등의 방어 기법이 필수적입니다 [6-8].
|
||||
## 매 한 줄
|
||||
> **"매 execution time 의 secret-dependent variation 의 leak"**. 1996 Kocher RSA timing paper origin — comparison/branch/cache 가 secret bit 에 dependent 면 attacker 가 multiple measurement 의 statistical analysis 로 secret 을 추출. Mitigation 의 핵심: constant-time code.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **공격의 원리 및 메커니즘:** 타이밍 공격은 마이크로초 미만의 미세한 시간 차이를 관찰하여 캐시 사이드 채널 공격을 가능하게 합니다 [2]. 스펙터(Spectre) 공격은 공격자가 CPU의 분기(branch)를 제어하고 추측 실행 과정에서 정보 유출을 유도하는 방식으로 작동합니다 [5]. 캐시된 데이터와 메인 메모리에 있는 데이터의 로드 속도 차이를 측정하여, 특정 데이터가 추측 실행을 통해 L1 캐시에 로드되었는지 여부를 알아냅니다 [3, 5].
|
||||
- **GPU 그래픽 API의 취약점:** [[WebGL|WebGL]]의 `EXT_disjoint_timer_query`와 같은 API는 매우 높은 해상도의 타이밍 측정 기능을 제공하여 부채널 공격의 주요 표적이 되었습니다 [1, 9]. 이러한 고정밀 타임스탬프 쿼리를 이용하면 GPU 캐시 미스 비율을 관찰하거나, 물리적 메모리 레이아웃을 파악하여 로우해머([[Rowhammer|Rowhammer]]) 공격을 통해 페이지 테이블을 조작할 수도 있습니다 [10]. 또한 'Clock Around the Clock'과 같이 디바이스 핑거프린팅(Device Fingerprinting)에도 악용될 수 있습니다 [10].
|
||||
- **보안 완화 기술 (Mitigations):**
|
||||
- **타이머 정밀도 감소 및 지터(Jitter) 도입:** 브라우저 엔진은 캐시 사이드 채널 공격을 막기 위해 `performance.now()`의 정밀도를 1ms 또는 100마이크로초로 낮추고, 무작위 '지터(Jitter)'를 도입하여 통계적인 고정밀 클록 재구성을 방지합니다 [2, 8]. 또한 고해상도 타이머를 만들 수 있는 `SharedArrayBuffer` 기능을 비활성화합니다 [8].
|
||||
- **타임스탬프 양자화 ([[Quantization|Quantization]]):** [[WebGPU|WebGPU]]와 같은 최신 API는 보안을 위해 타임스탬프 쿼리의 정밀도를 낮추는 양자화 기법을 도입했습니다 [1, 11]. 컨텍스트의 교차 출처 격리(Cross-origin isolated) 상태에 따라 타이머 분해능을 조절(예: 100마이크로초로 제한)하여 타이밍 공격과 핑거프린팅을 방지합니다 [11-14].
|
||||
- **분기 없는 보안 검사 (Branchless Security Checks):** 스펙터 공격이 조건부 분기 명령을 악용하는 것을 막기 위해, 브라우저는 인덱스 마스킹([[Index Masking|Index Masking]])과 포인터 포이즈닝([[Pointer Poisoning|Pointer Poisoning]]) 기법을 도입했습니다 [2, 8, 15, 16]. 이를 통해 분기 없이 타입 검사나 경계 검사(Bounds Check)를 수행하여 추측 실행으로 인한 취약점을 근본적으로 차단합니다 [8, 16].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 Vulnerable patterns
|
||||
- **Early-exit string compare**: `==` / `strcmp` returns on first mismatch byte.
|
||||
- **Secret-dependent branch**: `if (key[i] == 0)` 의 cache miss timing differs.
|
||||
- **Secret-dependent table lookup**: AES S-box → cache line timing.
|
||||
- **Modular exponentiation**: square-and-multiply 의 bit-dependent ops.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[Side-channel Attack|Side-channel Attack]], Spectre and Meltdown, Speculative Execution, [[Timestamp Quantization|Timestamp Quantization]], [[Branchless Security Checks|Branchless Security Checks]]
|
||||
- **Projects/Contexts:** [[WebKit|WebKit]], WebGL, [[WebGPU|WebGPU]]
|
||||
- **Contradictions/Notes:** 소스 내에서 특별한 모순점은 발견되지 않았습니다. 개발자들의 성능 분석 요구와 타이밍 공격(보안)이라는 상충하는 두 가지 목표를 해결하기 위해, WebGPU 표준에서는 타임스탬프 쿼리를 전면 차단하는 대신 '정밀도 양자화(Quantization)'를 절충안으로 도입하는 데 합의했습니다 [1, 10, 11].
|
||||
### 매 Mitigation
|
||||
- **Constant-time compare**: scan all bytes regardless, XOR-accumulate.
|
||||
- **No secret-dependent branches**: use bitwise mask instead.
|
||||
- **No secret-dependent indices**: scan full table or use bit-slicing.
|
||||
- **Blinding**: randomize input (RSA: blind w/ random r, decrypt, unblind).
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-19*
|
||||
### 매 응용
|
||||
1. HMAC token comparison (auth bypass via timing).
|
||||
2. Password hash compare (after bcrypt — still need constant-time).
|
||||
3. JWT signature verify.
|
||||
|
||||
---
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### Vulnerable: early-exit compare
|
||||
```typescript
|
||||
// ❌ DON'T — leaks prefix length
|
||||
function badCompare(a: string, b: string): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i] !== b[i]) return false; // early exit reveals match length
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Attacker measures: "aaaa" vs "baaa" faster than "aaaa" vs "aaab"
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Constant-time compare (Node.js)
|
||||
```typescript
|
||||
import { timingSafeEqual } from 'node:crypto';
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
function safeCompare(a: string, b: string): boolean {
|
||||
const bufA = Buffer.from(a);
|
||||
const bufB = Buffer.from(b);
|
||||
if (bufA.length !== bufB.length) {
|
||||
// length leak unavoidable — pad to fixed length OR accept
|
||||
timingSafeEqual(bufA, bufA); // dummy compare to equalize timing
|
||||
return false;
|
||||
}
|
||||
return timingSafeEqual(bufA, bufB);
|
||||
}
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// HMAC token check
|
||||
import { createHmac } from 'node:crypto';
|
||||
function verifyToken(token: string, payload: string, secret: string): boolean {
|
||||
const expected = createHmac('sha256', secret).update(payload).digest('hex');
|
||||
return expected.length === token.length &&
|
||||
timingSafeEqual(Buffer.from(expected), Buffer.from(token));
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Browser: SubtleCrypto + manual constant-time
|
||||
```typescript
|
||||
// Web Crypto has no timingSafeEqual — implement carefully
|
||||
function ctEqualBytes(a: Uint8Array, b: Uint8Array): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
let diff = 0;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
diff |= a[i] ^ b[i]; // XOR-accumulate, no branch
|
||||
}
|
||||
return diff === 0;
|
||||
}
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
async function verifyHmac(msg: string, sig: ArrayBuffer, key: CryptoKey) {
|
||||
const computed = await crypto.subtle.sign(
|
||||
'HMAC', key, new TextEncoder().encode(msg)
|
||||
);
|
||||
return ctEqualBytes(new Uint8Array(computed), new Uint8Array(sig));
|
||||
}
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Python constant-time compare
|
||||
```python
|
||||
import hmac
|
||||
|
||||
def verify(token: str, expected: str) -> bool:
|
||||
return hmac.compare_digest(token, expected)
|
||||
|
||||
# bcrypt — already constant-time via library
|
||||
import bcrypt
|
||||
def check_password(plain: bytes, hashed: bytes) -> bool:
|
||||
return bcrypt.checkpw(plain, hashed) # safe internally
|
||||
```
|
||||
|
||||
### Go constant-time
|
||||
```go
|
||||
import "crypto/subtle"
|
||||
|
||||
func verify(a, b []byte) bool {
|
||||
return subtle.ConstantTimeCompare(a, b) == 1
|
||||
}
|
||||
|
||||
// Conditional copy without branch
|
||||
func ctSelect(cond int, a, b []byte) {
|
||||
subtle.ConstantTimeCopy(cond, a, b)
|
||||
}
|
||||
```
|
||||
|
||||
### Branchless conditional (C-style)
|
||||
```typescript
|
||||
// Constant-time conditional select
|
||||
function ctSelect(cond: number, a: number, b: number): number {
|
||||
// cond must be 0 or 1
|
||||
const mask = -cond; // 0 or 0xFFFFFFFF
|
||||
return (a & mask) | (b & ~mask);
|
||||
}
|
||||
|
||||
// Constant-time min/max without branch
|
||||
function ctMin(a: number, b: number): number {
|
||||
const lt = (a - b) >>> 31; // 1 if a<b
|
||||
return ctSelect(lt, a, b);
|
||||
}
|
||||
```
|
||||
|
||||
### Remote timing (network attacks)
|
||||
```text
|
||||
Lucky 13 (TLS 2013): MAC verify timing leaked plaintext.
|
||||
CRIME / BREACH: compression length leaked secrets (different side channel).
|
||||
|
||||
Mitigation:
|
||||
- Always run full computation regardless of input validity.
|
||||
- Add randomized delay (debatable — may not help, can hurt).
|
||||
- Rate-limit + monitoring for anomalous timing-probe traffic.
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Password hash check | bcrypt/argon2 lib (already CT) |
|
||||
| HMAC/token compare | timingSafeEqual / hmac.compare_digest |
|
||||
| AES on untrusted host | AES-NI (HW) or bit-sliced soft impl |
|
||||
| Secret-dependent index | bitwise mask or full-table scan |
|
||||
| RSA/ECDSA private op | use vetted lib (BoringSSL, libsodium) — never roll your own |
|
||||
|
||||
**기본값**: never write your own crypto compare. Use language stdlib `timingSafeEqual` / `compare_digest` / `subtle.ConstantTimeCompare`.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Side Channel Attack]] · [[Cryptography]]
|
||||
- 변형: [[Spectre]] · [[Cache Timing Attack]] · [[Power Analysis]]
|
||||
- 응용: [[HMAC]] · [[Token Verification]] · [[Constant Time Cryptography]]
|
||||
- Adjacent: [[Lucky 13]] · [[CRIME Attack]] · [[BREACH Attack]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: auth code review, HMAC/token compare, custom crypto routines, security audit.
|
||||
**언제 X**: high-level app logic where no secrets are compared (UI rendering, business rules).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **`a === b` for secrets**: V8/JIT may early-exit, branch, or short-circuit.
|
||||
- **Custom "constant-time" without testing**: compiler can re-introduce branches via optimization. Test with `dudect`.
|
||||
- **Throwing on mismatch**: exception path differs in timing from success path.
|
||||
- **Logging mismatch position**: leaks comparison index.
|
||||
- **Comparing hashes in DB**: even hash compare 의 leaks length prefix → use CT.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Kocher 1996 paper, Node.js crypto docs, Go subtle pkg, OWASP Cryptographic Storage CS).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full canonical (CT compare + branchless + Node/Go/Python + remote attacks) |
|
||||
|
||||
Reference in New Issue
Block a user