Constant-Time Analysis
Analyze cryptographic code to detect operations that leak secret data through execution timing variations.
When to Use
User writing crypto code? ──yes──> Use this skill
│
no
│
v
User asking about timing attacks? ──yes──> Use this skill
│
no
│
v
Code handles secret keys/tokens? ──yes──> Use this skill
│
no
│
v
Skip this skill
Concrete triggers:
- User implements signature, encryption, or key derivation
- Code contains
/ or % operators on secret-derived values
- User mentions "constant-time", "timing attack", "side-channel", "KyberSlash"
- Reviewing functions named
sign, verify, encrypt, decrypt, derive_key
When NOT to Use
- Non-cryptographic code (business logic, UI, etc.)
- Public data processing where timing leaks don't matter
- Code that doesn't handle secrets, keys, or authentication tokens
- High-level API usage where timing is handled by the library
Language Selection
Based on the file extension or language context, refer to the appropriate guide:
| Language |
File Extensions |
Guide |
| C, C++ |
.c, .h, .cpp, .cc, .hpp |
references/compiled.md |
| Go |
.go |
references/compiled.md |
| Rust |
.rs |
references/compiled.md |
| Swift |
.swift |
references/swift.md |
| Java |
.java |
references/vm-compiled.md |
| Kotlin |
.kt, .kts |
references/kotlin.md |
| C# |
.cs |
references/vm-compiled.md |
| PHP |
.php |
references/php.md |
| JavaScript |
.js, .mjs, .cjs |
references/javascript.md |
| TypeScript |
.ts, .tsx |
references/javascript.md |
| Python |
.py |
references/python.md |
| Ruby |
.rb |
references/ruby.md |
Quick Start
# Analyze any supported file type
uv run {baseDir}/ct_analyzer/analyzer.py <source_file>
# Include conditional branch warnings
uv run {baseDir}/ct_analyzer/analyzer.py --warnings <source_file>
# Filter to specific functions
uv run {baseDir}/ct_analyzer/analyzer.py --func 'sign|verify' <source_file>
# JSON output for CI
uv run {baseDir}/ct_analyzer/analyzer.py --json <source_file>
Native Compiled Languages Only (C, C++, Go, Rust)
# Cross-architecture testing (RECOMMENDED)
uv run {baseDir}/ct_analyzer/analyzer.py --arch x86_64 crypto.c
uv run {baseDir}/ct_analyzer/analyzer.py --arch arm64 crypto.c
# Multiple optimization levels
uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O0 crypto.c
uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O3 crypto.c
VM-Compiled Languages (Java, Kotlin, C#)
# Analyze Java bytecode
uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.java
# Analyze Kotlin bytecode (Android/JVM)
uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.kt
# Analyze C# IL
uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.cs
Note: Java, Kotlin, and C# compile to bytecode (JVM/CIL) that runs on a virtual machine with JIT compilation. The analyzer examines the bytecode directly, not the JIT-compiled native code. The --arch and --opt-level flags do not apply to these languages.
Swift (iOS/macOS)
# Analyze Swift for native architecture
uv run {baseDir}/ct_analyzer/analyzer.py crypto.swift
# Analyze for specific architecture (iOS devices)
uv run {baseDir}/ct_analyzer/analyzer.py --arch arm64 crypto.swift
# Analyze with different optimization levels
uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O0 crypto.swift
Note: Swift compiles to native code like C/C++/Go/Rust, so it uses assembly-level analysis and supports --arch and --opt-level flags.
Prerequisites
| Language |
Requirements |
| C, C++, Go, Rust |
Compiler in PATH (gcc/clang, go, rustc) |
| Swift |
Xcode or Swift toolchain (swiftc in PATH) |
| Java |
JDK with javac and javap in PATH |
| Kotlin |
Kotlin compiler (kotlinc) + JDK (javap) in PATH |
| C# |
.NET SDK + ilspycmd (dotnet tool install -g ilspycmd) |
| PHP |
PHP with VLD extension or OPcache |
| JavaScript/TypeScript |
Node.js in PATH |
| Python |
Python 3.x in PATH |
| Ruby |
Ruby with --dump=insns support |
macOS users: Homebrew installs Java and .NET as "keg-only". You must add them to your PATH:
# For Java (add to ~/.zshrc)
export PATH="/opt/homebrew/opt/openjdk@21/bin:$PATH"
# For .NET tools (add to ~/.zshrc)
export PATH="$HOME/.dotnet/tools:$PATH"
See references/vm-compiled.md for detailed setup instructions and troubleshooting.
Quick Reference
| Problem |
Detection |
Fix |
| Division on secrets |
DIV, IDIV, SDIV, UDIV |
Barrett reduction or multiply-by-inverse |
| Branch on secrets |
JE, JNE, BEQ, BNE |
Constant-time selection (cmov, bit masking) |
| Secret comparison |
Early-exit memcmp |
Use crypto/subtle or constant-time compare |
| Weak RNG |
rand(), mt_rand, Math.random |
Use crypto-secure RNG |
| Table lookup by secret |
Array subscript on secret index |
Bit-sliced lookups |
Interpreting Results
PASSED - No variable-time operations detected.
FAILED - Dangerous instructions found. Example:
[ERROR] SDIV
Function: decompose_vulnerable
Reason: SDIV has early termination optimization; execution time depends on operand values
Verifying Results (Avoiding False Positives)
CRITICAL: Not every flagged operation is a vulnerability. The tool has no data flow analysis - it flags ALL potentially dangerous operations regardless of whether they involve secrets.
For each flagged violation, ask: Does this operation's input depend on secret data?
Identify the secret inputs to the function (private keys, plaintext, signatures, tokens)
Trace data flow from the flagged instruction back to inputs
Common false positive patterns:
// FALSE POSITIVE: Division uses public constant, not secret
int num_blocks = data_len / 16; // data_len is length, not content
// TRUE POSITIVE: Division involves secret-derived value
int32_t q = secret_coef / GAMMA2; // secret_coef from private key
Document your analysis for each flagged item
Quick Triage Questions
| Question |
If Yes |
If No |
| Is the operand a compile-time constant? |
Likely false positive |
Continue |
| Is the operand a public parameter (length, count)? |
Likely false positive |
Continue |
| Is the operand derived from key/plaintext/secret? |
TRUE POSITIVE |
Likely false positive |
| Can an attacker influence the operand value? |
TRUE POSITIVE |
Likely false positive |
Limitations
Static Analysis Only: Analyzes assembly/bytecode, not runtime behavior. Cannot detect cache timing or microarchitectural side-channels.
No Data Flow Analysis: Flags all dangerous operations regardless of whether they process secrets. Manual review required.
Compiler/Runtime Variations: Different compilers, optimization levels, and runtime versions may produce different output.
Real-World Impact
- KyberSlash (2023): Division instructions in post-quantum ML-KEM implementations allowed key recovery
- Lucky Thirteen (2013): Timing differences in CBC padding validation enabled plaintext recovery
- RSA Timing Attacks: Early implementations leaked private key bits through division timing
References
1---2name: constant-time-analysis3description: Detects timing side-channel vulnerabilities in cryptographic code. Use when implementing or reviewing crypto code, encountering division on secrets, secret-dependent branches, or constant-time programming questions in C, C++, Go, Rust, Swift, Java, Kotlin, C#, PHP,...4---5
6# Constant-Time Analysis
7
8Analyze cryptographic code to detect operations that leak secret data through execution timing variations.
9
10## When to Use
11
12```text
13User writing crypto code? ──yes──> Use this skill
14 │
15 no
16 │
17 v
18User asking about timing attacks? ──yes──> Use this skill
19 │
20 no
21 │
22 v
23Code handles secret keys/tokens? ──yes──> Use this skill
24 │
25 no
26 │
27 v
28Skip this skill
29```
30
31**Concrete triggers:**
32
33- User implements signature, encryption, or key derivation
34- Code contains `/` or `%` operators on secret-derived values
35- User mentions "constant-time", "timing attack", "side-channel", "KyberSlash"
36- Reviewing functions named `sign`, `verify`, `encrypt`, `decrypt`, `derive_key`
37
38## When NOT to Use
39
40- Non-cryptographic code (business logic, UI, etc.)
41- Public data processing where timing leaks don't matter
42- Code that doesn't handle secrets, keys, or authentication tokens
43- High-level API usage where timing is handled by the library
44
45## Language Selection
46
47Based on the file extension or language context, refer to the appropriate guide:
48
49| Language | File Extensions | Guide |
50| ---------- | --------------------------------- | -------------------------------------------------------- |
51| C, C++ | `.c`, `.h`, `.cpp`, `.cc`, `.hpp` | references/compiled.md |
52| Go | `.go` | references/compiled.md |
53| Rust | `.rs` | references/compiled.md |
54| Swift | `.swift` | references/swift.md |
55| Java | `.java` | references/vm-compiled.md |
56| Kotlin | `.kt`, `.kts` | references/kotlin.md |
57| C# | `.cs` | references/vm-compiled.md |
58| PHP | `.php` | references/php.md |
59| JavaScript | `.js`, `.mjs`, `.cjs` | references/javascript.md |
60| TypeScript | `.ts`, `.tsx` | references/javascript.md |
61| Python | `.py` | references/python.md |
62| Ruby | `.rb` | references/ruby.md |
63
64## Quick Start
65
66```bash
67# Analyze any supported file type
68uv run {baseDir}/ct_analyzer/analyzer.py <source_file>
69
70# Include conditional branch warnings
71uv run {baseDir}/ct_analyzer/analyzer.py --warnings <source_file>
72
73# Filter to specific functions
74uv run {baseDir}/ct_analyzer/analyzer.py --func 'sign|verify' <source_file>
75
76# JSON output for CI
77uv run {baseDir}/ct_analyzer/analyzer.py --json <source_file>
78```
79
80### Native Compiled Languages Only (C, C++, Go, Rust)
81
82```bash
83# Cross-architecture testing (RECOMMENDED)
84uv run {baseDir}/ct_analyzer/analyzer.py --arch x86_64 crypto.c
85uv run {baseDir}/ct_analyzer/analyzer.py --arch arm64 crypto.c
86
87# Multiple optimization levels
88uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O0 crypto.c
89uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O3 crypto.c
90```
91
92### VM-Compiled Languages (Java, Kotlin, C#)
93
94```bash
95# Analyze Java bytecode
96uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.java
97
98# Analyze Kotlin bytecode (Android/JVM)
99uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.kt
100
101# Analyze C# IL
102uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.cs
103```
104
105Note: Java, Kotlin, and C# compile to bytecode (JVM/CIL) that runs on a virtual machine with JIT compilation. The analyzer examines the bytecode directly, not the JIT-compiled native code. The `--arch` and `--opt-level` flags do not apply to these languages.
106
107### Swift (iOS/macOS)
108
109```bash
110# Analyze Swift for native architecture
111uv run {baseDir}/ct_analyzer/analyzer.py crypto.swift
112
113# Analyze for specific architecture (iOS devices)
114uv run {baseDir}/ct_analyzer/analyzer.py --arch arm64 crypto.swift
115
116# Analyze with different optimization levels
117uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O0 crypto.swift
118```
119
120Note: Swift compiles to native code like C/C++/Go/Rust, so it uses assembly-level analysis and supports `--arch` and `--opt-level` flags.
121
122### Prerequisites
123
124| Language | Requirements |
125| ---------------------- | --------------------------------------------------------- |
126| C, C++, Go, Rust | Compiler in PATH (`gcc`/`clang`, `go`, `rustc`) |
127| Swift | Xcode or Swift toolchain (`swiftc` in PATH) |
128| Java | JDK with `javac` and `javap` in PATH |
129| Kotlin | Kotlin compiler (`kotlinc`) + JDK (`javap`) in PATH |
130| C# | .NET SDK + `ilspycmd` (`dotnet tool install -g ilspycmd`) |
131| PHP | PHP with VLD extension or OPcache |
132| JavaScript/TypeScript | Node.js in PATH |
133| Python | Python 3.x in PATH |
134| Ruby | Ruby with `--dump=insns` support |
135
136**macOS users**: Homebrew installs Java and .NET as "keg-only". You must add them to your PATH:
137
138```bash
139# For Java (add to ~/.zshrc)
140export PATH="/opt/homebrew/opt/openjdk@21/bin:$PATH"
141
142# For .NET tools (add to ~/.zshrc)
143export PATH="$HOME/.dotnet/tools:$PATH"
144```
145
146See references/vm-compiled.md for detailed setup instructions and troubleshooting.
147
148## Quick Reference
149
150| Problem | Detection | Fix |
151| ---------------------- | ------------------------------- | -------------------------------------------- |
152| Division on secrets | DIV, IDIV, SDIV, UDIV | Barrett reduction or multiply-by-inverse |
153| Branch on secrets | JE, JNE, BEQ, BNE | Constant-time selection (cmov, bit masking) |
154| Secret comparison | Early-exit memcmp | Use `crypto/subtle` or constant-time compare |
155| Weak RNG | rand(), mt_rand, Math.random | Use crypto-secure RNG |
156| Table lookup by secret | Array subscript on secret index | Bit-sliced lookups |
157
158## Interpreting Results
159
160**PASSED** - No variable-time operations detected.
161
162**FAILED** - Dangerous instructions found. Example:
163
164```text
165[ERROR] SDIV
166 Function: decompose_vulnerable
167 Reason: SDIV has early termination optimization; execution time depends on operand values
168```
169
170## Verifying Results (Avoiding False Positives)
171
172**CRITICAL**: Not every flagged operation is a vulnerability. The tool has no data flow analysis - it flags ALL potentially dangerous operations regardless of whether they involve secrets.
173
174For each flagged violation, ask: **Does this operation's input depend on secret data?**
175
1761. **Identify the secret inputs** to the function (private keys, plaintext, signatures, tokens)
177
1782. **Trace data flow** from the flagged instruction back to inputs
179
1803. **Common false positive patterns**:
181
182 ```c
183 // FALSE POSITIVE: Division uses public constant, not secret
184 int num_blocks = data_len / 16; // data_len is length, not content
185
186 // TRUE POSITIVE: Division involves secret-derived value
187 int32_t q = secret_coef / GAMMA2; // secret_coef from private key
188 ```
189
1904. **Document your analysis** for each flagged item
191
192### Quick Triage Questions
193
194| Question | If Yes | If No |
195| ------------------------------------------------- | --------------------- | --------------------- |
196| Is the operand a compile-time constant? | Likely false positive | Continue |
197| Is the operand a public parameter (length, count)?| Likely false positive | Continue |
198| Is the operand derived from key/plaintext/secret? | **TRUE POSITIVE** | Likely false positive |
199| Can an attacker influence the operand value? | **TRUE POSITIVE** | Likely false positive |
200
201## Limitations
202
2031. **Static Analysis Only**: Analyzes assembly/bytecode, not runtime behavior. Cannot detect cache timing or microarchitectural side-channels.
204
2052. **No Data Flow Analysis**: Flags all dangerous operations regardless of whether they process secrets. Manual review required.
206
2073. **Compiler/Runtime Variations**: Different compilers, optimization levels, and runtime versions may produce different output.
208
209## Real-World Impact
210
211- **KyberSlash (2023)**: Division instructions in post-quantum ML-KEM implementations allowed key recovery
212- **Lucky Thirteen (2013)**: Timing differences in CBC padding validation enabled plaintext recovery
213- **RSA Timing Attacks**: Early implementations leaked private key bits through division timing
214
215## References
216
217- [Cryptocoding Guidelines](https://github.com/veorq/cryptocoding) - Defensive coding for crypto
218- [KyberSlash](https://kyberslash.cr.yp.to/) - Division timing in post-quantum crypto
219- [BearSSL Constant-Time](https://www.bearssl.org/constanttime.html) - Practical constant-time techniques