d8a80f6272
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해 끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은 과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업. 도구: Datacollect/scripts/link_reconcile_apply.mjs Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
193 lines
6.3 KiB
Markdown
193 lines
6.3 KiB
Markdown
---
|
|
id: wiki-2026-0508-timing-attack
|
|
title: Timing Attack
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [Timing Side Channel, Constant Time Comparison]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.9
|
|
verification_status: applied
|
|
tags: [security, side-channel, cryptography, constant-time]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: pending
|
|
tech_stack:
|
|
language: typescript
|
|
framework: nodejs
|
|
---
|
|
|
|
# Timing Attack
|
|
|
|
## 매 한 줄
|
|
> **"매 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.
|
|
|
|
## 매 핵심
|
|
|
|
### 매 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.
|
|
|
|
### 매 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).
|
|
|
|
### 매 응용
|
|
1. HMAC token comparison (auth bypass via timing).
|
|
2. Password hash compare (after bcrypt — still need constant-time).
|
|
3. JWT signature verify.
|
|
|
|
## 💻 패턴
|
|
|
|
### 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"
|
|
```
|
|
|
|
### Constant-time compare (Node.js)
|
|
```typescript
|
|
import { timingSafeEqual } from 'node:crypto';
|
|
|
|
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);
|
|
}
|
|
|
|
// 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));
|
|
}
|
|
```
|
|
|
|
### 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;
|
|
}
|
|
|
|
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));
|
|
}
|
|
```
|
|
|
|
### 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]] · [[Practical-Cryptography|Cryptography]]
|
|
- 변형: [[Spectre]] · [[Cache Timing Attack]] · [[Power Analysis]]
|
|
|
|
## 🤖 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) |
|