9148c358d0
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를 Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류. - 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로 자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거, 동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거. - 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming, Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business, Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로, 나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는 title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백). 원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지. - 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서. - 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는 지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지. - Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경. - 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
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) |
|