constant-time-analysis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Constant-Time Analysis

Constant-Time 分析

Analyze cryptographic code to detect operations that leak secret data through execution timing variations.
分析加密代码,检测通过执行计时差异泄露机密数据的操作。

When to Use

使用场景

text
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
text
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
具体触发场景:
  • 用户正在实现签名、加密或密钥派生功能
  • 代码中包含对机密衍生值使用
    /
    %
    运算符的操作
  • 用户提及"constant-time"、"timing attack"、"side-channel"、"KyberSlash"
  • 审查名为
    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
  • 非加密代码(业务逻辑、UI等)
  • 计时泄露无影响的公开数据处理场景
  • 不处理机密、密钥或认证令牌的代码
  • 使用高层API(计时由库处理)的场景

Language Selection

语言选择

Based on the file extension or language context, refer to the appropriate guide:
LanguageFile ExtensionsGuide
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
根据文件扩展名或语言上下文,参考对应的指南:
语言文件扩展名指南链接
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

快速开始

bash
undefined
bash
undefined

Analyze any supported file type

Analyze any supported file type

uv run {baseDir}/ct_analyzer/analyzer.py <source_file>
uv run {baseDir}/ct_analyzer/analyzer.py <source_file>

Include conditional branch warnings

Include conditional branch warnings

uv run {baseDir}/ct_analyzer/analyzer.py --warnings <source_file>
uv run {baseDir}/ct_analyzer/analyzer.py --warnings <source_file>

Filter to specific functions

Filter to specific functions

uv run {baseDir}/ct_analyzer/analyzer.py --func 'sign|verify' <source_file>
uv run {baseDir}/ct_analyzer/analyzer.py --func 'sign|verify' <source_file>

JSON output for CI

JSON output for CI

uv run {baseDir}/ct_analyzer/analyzer.py --json <source_file>
undefined
uv run {baseDir}/ct_analyzer/analyzer.py --json <source_file>
undefined

Native Compiled Languages Only (C, C++, Go, Rust)

仅适用于原生编译型语言(C, C++, Go, Rust)

bash
undefined
bash
undefined

Cross-architecture testing (RECOMMENDED)

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
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

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
undefined
uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O0 crypto.c uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O3 crypto.c
undefined

VM-Compiled Languages (Java, Kotlin, C#)

虚拟机编译型语言(Java, Kotlin, C#)

bash
undefined
bash
undefined

Analyze Java bytecode

Analyze Java bytecode

uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.java
uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.java

Analyze Kotlin bytecode (Android/JVM)

Analyze Kotlin bytecode (Android/JVM)

uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.kt
uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.kt

Analyze C# IL

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.
uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.cs

注意:Java、Kotlin和C#会编译为字节码(JVM/CIL),在带有JIT编译的虚拟机上运行。本分析器直接检查字节码,而非JIT编译后的原生代码。`--arch`和`--opt-level`标志不适用于这些语言。

Swift (iOS/macOS)

Swift(iOS/macOS)

bash
undefined
bash
undefined

Analyze Swift for native architecture

Analyze Swift for native architecture

uv run {baseDir}/ct_analyzer/analyzer.py crypto.swift
uv run {baseDir}/ct_analyzer/analyzer.py crypto.swift

Analyze for specific architecture (iOS devices)

Analyze for specific architecture (iOS devices)

uv run {baseDir}/ct_analyzer/analyzer.py --arch arm64 crypto.swift
uv run {baseDir}/ct_analyzer/analyzer.py --arch arm64 crypto.swift

Analyze with different optimization levels

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.
uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O0 crypto.swift

注意:Swift与C/C++/Go/Rust一样编译为原生代码,因此使用汇编级分析,并支持`--arch`和`--opt-level`标志。

Prerequisites

前置条件

LanguageRequirements
C, C++, Go, RustCompiler in PATH (
gcc
/
clang
,
go
,
rustc
)
SwiftXcode or Swift toolchain (
swiftc
in PATH)
JavaJDK with
javac
and
javap
in PATH
KotlinKotlin compiler (
kotlinc
) + JDK (
javap
) in PATH
C#.NET SDK +
ilspycmd
(
dotnet tool install -g ilspycmd
)
PHPPHP with VLD extension or OPcache
JavaScript/TypeScriptNode.js in PATH
PythonPython 3.x in PATH
RubyRuby with
--dump=insns
support
macOS users: Homebrew installs Java and .NET as "keg-only". You must add them to your PATH:
bash
undefined
语言要求条件
C, C++, Go, RustPATH中需包含编译器(
gcc
/
clang
go
rustc
SwiftPATH中需包含Xcode或Swift工具链(
swiftc
JavaPATH中需包含带有
javac
javap
的JDK
KotlinPATH中需包含Kotlin编译器(
kotlinc
)+ JDK(
javap
C#.NET SDK +
ilspycmd
dotnet tool install -g ilspycmd
PHP带有VLD扩展或OPcache的PHP
JavaScript/TypeScriptPATH中需包含Node.js
PythonPATH中需包含Python 3.x
Ruby支持
--dump=insns
的Ruby
macOS用户:Homebrew安装的Java和.NET为“keg-only”模式,你需要将它们添加到PATH中:
bash
undefined

For Java (add to ~/.zshrc)

For Java (add to ~/.zshrc)

export PATH="/opt/homebrew/opt/openjdk@21/bin:$PATH"
export PATH="/opt/homebrew/opt/openjdk@21/bin:$PATH"

For .NET tools (add to ~/.zshrc)

For .NET tools (add to ~/.zshrc)

export PATH="$HOME/.dotnet/tools:$PATH"

See [references/vm-compiled.md](references/vm-compiled.md) for detailed setup instructions and troubleshooting.
export PATH="$HOME/.dotnet/tools:$PATH"

详细的设置说明和故障排查请参考[references/vm-compiled.md](references/vm-compiled.md)。

Quick Reference

快速参考

ProblemDetectionFix
Division on secretsDIV, IDIV, SDIV, UDIVBarrett reduction or multiply-by-inverse
Branch on secretsJE, JNE, BEQ, BNEConstant-time selection (cmov, bit masking)
Secret comparisonEarly-exit memcmpUse
crypto/subtle
or constant-time compare
Weak RNGrand(), mt_rand, Math.randomUse crypto-secure RNG
Table lookup by secretArray subscript on secret indexBit-sliced lookups
问题检测方式修复方案
对机密值执行除法运算DIV、IDIV、SDIV、UDIV指令检测使用Barrett约简或乘逆运算
基于机密值的分支JE、JNE、BEQ、BNE指令检测使用常量时间选择(cmov、位掩码)
机密值比较提前退出的memcmp检测使用
crypto/subtle
或常量时间比较函数
弱随机数生成器rand()、mt_rand、Math.random检测使用加密安全的随机数生成器
基于机密索引的表查找机密索引的数组下标访问检测使用位分片查找

Interpreting Results

结果解读

PASSED - No variable-time operations detected.
FAILED - Dangerous instructions found. Example:
text
[ERROR] SDIV
  Function: decompose_vulnerable
  Reason: SDIV has early termination optimization; execution time depends on operand values
PASSED - 未检测到可变时间操作。
FAILED - 发现危险指令。示例:
text
[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?
  1. Identify the secret inputs to the function (private keys, plaintext, signatures, tokens)
  2. Trace data flow from the flagged instruction back to inputs
  3. Common false positive patterns:
    c
    // 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
  4. Document your analysis for each flagged item
关键提示:并非所有标记的操作都是漏洞。本工具无数据流分析功能——它会标记所有潜在危险的操作,无论这些操作是否涉及机密数据。
对于每个标记的违规项,请确认:该操作的输入是否依赖机密数据?
  1. 识别函数的机密输入(私钥、明文、签名、令牌)
  2. 追踪标记指令到输入的数据流
  3. 常见误报模式
    c
    // 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
  4. 为每个标记项记录你的分析结果

Quick Triage Questions

快速分类问题

QuestionIf YesIf No
Is the operand a compile-time constant?Likely false positiveContinue
Is the operand a public parameter (length, count)?Likely false positiveContinue
Is the operand derived from key/plaintext/secret?TRUE POSITIVELikely false positive
Can an attacker influence the operand value?TRUE POSITIVELikely false positive
问题若是若否
操作数是编译时常量吗?大概率是误报继续分析
操作数是公开参数(长度、计数)吗?大概率是误报继续分析
操作数派生自密钥/明文/机密吗?确认为漏洞大概率是误报
攻击者能否影响操作数的值?确认为漏洞大概率是误报

Limitations

局限性

  1. Static Analysis Only: Analyzes assembly/bytecode, not runtime behavior. Cannot detect cache timing or microarchitectural side-channels.
  2. No Data Flow Analysis: Flags all dangerous operations regardless of whether they process secrets. Manual review required.
  3. Compiler/Runtime Variations: Different compilers, optimization levels, and runtime versions may produce different output.
  1. 仅静态分析:分析汇编/字节码,而非运行时行为。无法检测缓存计时或微架构侧信道。
  2. 无数据流分析:标记所有危险操作,无论是否处理机密数据。需要人工审查。
  3. 编译器/运行时差异:不同编译器、优化级别和运行时版本可能产生不同输出。

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
  • KyberSlash (2023):后量子ML-KEM实现中的除法指令导致密钥泄露
  • Lucky Thirteen (2013):CBC填充验证中的计时差异导致明文泄露
  • RSA计时攻击:早期实现通过除法计时泄露私钥位

References

参考资料