<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: detecting-side-channel-attacks
description: >-
  Detect and mitigate side-channel attacks including timing attacks, cache
  attacks, power analysis, and electromagnetic emanation. Covers constant-time
  code verification, cache-timing detection, Spectre/Meltdown assessment,
  and hardware-level countermeasures.
domain: cybersecurity
subdomain: cryptography
tags:
  - side-channel
  - timing-attack
  - cache-attack
  - spectre
  - meltdown
  - power-analysis
  - constant-time
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1040"]
---

# Detecting Side-Channel Attacks

## Overview

Side-channel attacks extract secrets by observing physical or logical
characteristics of computation — timing, cache behavior, power consumption,
or electromagnetic emissions. This skill covers timing attack detection,
constant-time code verification, cache-based attack assessment, and
Spectre/Meltdown vulnerability checking.

## Prerequisites

| Requirement | Install |
|---|---|
| Python 3.10+ | For agent tooling |
| perf | `apt install linux-tools-generic` |
| valgrind | `apt install valgrind` |
| OpenSSL 3.x | `apt install openssl` |

## Key Concepts

### Timing Attack Detection

```bash
# Measure timing variance in string comparison (vulnerable)
python3 -c "
import time
secret = 'correct_password'
attempts = ['correct_password', 'xorrect_password', 'cxxxxxxxxxxxxx']
for attempt in attempts:
    start = time.perf_counter_ns()
    for _ in range(10000):
        _ = secret == attempt
    elapsed = time.perf_counter_ns() - start
    print(f'{attempt}: {elapsed}ns')
"

# Verify constant-time comparison (secure)
python3 -c "
import hmac, time
secret = b'correct_password'
for attempt in [b'correct_password', b'xorrect_password', b'cxxxxxxxxxxxxxx']:
    start = time.perf_counter_ns()
    for _ in range(10000):
        hmac.compare_digest(secret, attempt)
    elapsed = time.perf_counter_ns() - start
    print(f'{attempt}: {elapsed}ns')
"
```

### Cache Timing Analysis

```bash
# Monitor cache misses with perf
perf stat -e cache-misses,cache-references,L1-dcache-load-misses \
  openssl speed -evp aes-256-gcm

# Profile cache behavior of a process
perf record -e cache-misses -p $(pgrep -f openssl) -- sleep 5
perf report --stdio

# Check for Flush+Reload vulnerability indicators
perf stat -e LLC-load-misses,LLC-loads -p <pid> -- sleep 10
```

### Spectre/Meltdown Assessment

```bash
# Check CPU vulnerability status (Linux)
grep -r . /sys/devices/system/cpu/vulnerabilities/ 2>/dev/null

# Check specific mitigations
cat /sys/devices/system/cpu/vulnerabilities/spectre_v1
cat /sys/devices/system/cpu/vulnerabilities/spectre_v2
cat /sys/devices/system/cpu/vulnerabilities/meltdown

# Check kernel mitigations
dmesg | grep -iE "spectre|meltdown|retpoline|ibrs|ibpb"
```

### Constant-Time Code Patterns

```bash
# Search for timing-vulnerable comparisons in crypto code
grep -rn '==' --include='*.py' . | \
  grep -iE 'password|secret|token|key|hash|mac|hmac'

# Check for early-return patterns in auth code
grep -rn 'return False\|return None' --include='*.py' . | \
  grep -iE 'verify\|check\|auth\|compare'

# Verify OpenSSL constant-time operations
openssl speed -evp aes-256-gcm 2>&1 | head -20
```

## Common Failures

| Failure | Cause | Fix |
|---|---|---|
| Timing leak in comparison | `==` operator short-circuits | Use `hmac.compare_digest()` |
| Cache-based key recovery | Key-dependent memory access | Constant-time table lookups |
| Spectre variant exposed | Unpatched kernel/microcode | Apply vendor patches |
| Branch-based key leak | Secret-dependent branching | Branchless conditional moves |

## Workflow

1. **Assess** — Identify cryptographic operations exposed to adversary
2. **Profile** — Measure timing variance and cache behavior
3. **Audit** — Review code for timing-dependent operations
4. **Test** — Run statistical timing analysis
5. **Mitigate** — Implement constant-time alternatives
6. **Verify** — Confirm mitigations eliminate measurable leakage

## Verification

| Check | Method |
|---|---|
| Constant-time comparisons | `hmac.compare_digest` or equivalent used |
| No secret-dependent branches | Code review of crypto paths |
| CPU mitigations active | `/sys/devices/system/cpu/vulnerabilities/` clean |
| Cache behavior uniform | `perf stat` shows no anomalous patterns |

## References

- [Spectre Attacks (Kocher et al.)](https://spectreattack.com/)
- [Meltdown (Lipp et al.)](https://meltdownattack.com/)
- [BearSSL Constant-Time Code](https://www.bearssl.org/constanttime.html)
- [CWE-208 — Observable Timing Discrepancy](https://cwe.mitre.org/data/definitions/208.html)
