constant-time-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Constant-Time Testing

恒定时间测试

Timing attacks exploit variations in execution time to extract secret information from cryptographic implementations. Unlike cryptanalysis that targets theoretical weaknesses, timing attacks leverage implementation flaws - and they can affect any cryptographic code.
计时攻击利用执行时间的差异从加密实现中提取机密信息。与针对理论缺陷的密码分析不同,计时攻击利用的是实现层面的漏洞——且它们会影响所有加密代码。

Background

背景

Timing attacks were introduced by Kocher in 1996. Since then, researchers have demonstrated practical attacks on RSA (Schindler), OpenSSL (Brumley and Boneh), AES implementations, and even post-quantum algorithms like Kyber.
计时攻击由Kocher于1996年提出。此后,研究人员已证明针对RSA(Schindler)、OpenSSL(Brumley和Boneh)、AES实现甚至后量子算法如Kyber的实际攻击方法。

Key Concepts

核心概念

ConceptDescription
Constant-timeCode path and memory accesses independent of secret data
Timing leakageObservable execution time differences correlated with secrets
Side channelInformation extracted from implementation rather than algorithm
MicroarchitectureCPU-level timing differences (cache, division, shifts)
概念描述
恒定时间代码路径和内存访问与机密数据无关
计时泄露可观测的执行时间差异与机密信息相关
侧信道从实现而非算法中提取的信息
微架构CPU层面的计时差异(缓存、除法、移位)

Why This Matters

重要性

Timing vulnerabilities can:
  • Expose private keys - Extract secret exponents in RSA/ECDH
  • Enable remote attacks - Network-observable timing differences
  • Bypass cryptographic security - Undermine theoretical guarantees
  • Persist silently - Often undetected without specialized analysis
Two prerequisites enable exploitation:
  1. Access to oracle - Sufficient queries to the vulnerable implementation
  2. Timing dependency - Correlation between execution time and secret data
计时漏洞可能:
  • 泄露私钥 - 提取RSA/ECDH中的机密指数
  • 支持远程攻击 - 可通过网络观测到的计时差异
  • 绕过加密安全 - 破坏理论安全保障
  • 静默存在 - 若无专门分析通常无法被发现
漏洞利用需要两个前提:
  1. 访问预言机 - 可对存在漏洞的实现发起足够多的查询
  2. 计时依赖 - 执行时间与机密数据存在相关性

Common Constant-Time Violation Patterns

常见的恒定时间违规模式

Four patterns account for most timing vulnerabilities:
c
// 1. Conditional jumps - most severe timing differences
if(secret == 1) { ... }
while(secret > 0) { ... }

// 2. Array access - cache-timing attacks
lookup_table[secret];

// 3. Integer division (processor dependent)
data = secret / m;

// 4. Shift operation (processor dependent)
data = a << secret;
Conditional jumps cause different code paths, leading to vast timing differences.
Array access dependent on secrets enables cache-timing attacks, as shown in AES cache-timing research.
Integer division and shift operations leak secrets on certain CPU architectures and compiler configurations.
When patterns cannot be avoided, employ masking techniques to remove correlation between timing and secrets.
四种模式导致了大多数计时漏洞:
c
// 1. 条件跳转 - 最严重的计时差异
if(secret == 1) { ... }
while(secret > 0) { ... }

// 2. 数组访问 - 缓存计时攻击
lookup_table[secret];

// 3. 整数除法(取决于处理器)
data = secret / m;

// 4. 移位操作(取决于处理器)
data = a << secret;
条件跳转会导致不同的代码路径,产生巨大的计时差异。
数组访问依赖机密信息会引发缓存计时攻击,如AES缓存计时研究所示。
整数除法和移位操作在某些CPU架构和编译器配置下会泄露机密信息。
当无法避免这些模式时,可采用掩码技术消除计时与机密信息之间的相关性。

Example: Modular Exponentiation Timing Attacks

示例:模幂运算计时攻击

Modular exponentiation (used in RSA and Diffie-Hellman) is susceptible to timing attacks. RSA decryption computes:
$$ct^{d} \mod{N}$$
where $d$ is the secret exponent. The exponentiation by squaring optimization reduces multiplications to $\log{d}$:
$$ \begin{align*} & \textbf{Input: } \text{base }y,\text{exponent } d={d_n,\cdots,d_0}_2,\text{modulus } N \ & r = 1 \ & \textbf{for } i=|n| \text{ downto } 0: \ & \quad\textbf{if } d_i == 1: \ & \quad\quad r = r * y \mod{N} \ & \quad y = y * y \mod{N} \ & \textbf{return }r \end{align*} $$
The code branches on exponent bit $d_i$, violating constant-time principles. When $d_i = 1$, an additional multiplication occurs, increasing execution time and leaking bit information.
Montgomery multiplication (commonly used for modular arithmetic) also leaks timing: when intermediate values exceed modulus $N$, an additional reduction step is required. An attacker constructs inputs $y$ and $y'$ such that:
$$ \begin{align*} y^2 < y^3 < N \ y'^2 < N \leq y'^3 \end{align*} $$
For $y$, both multiplications take time $t_1+t_1$. For $y'$, the second multiplication requires reduction, taking time $t_1+t_2$. This timing difference reveals whether $d_i$ is 0 or 1.
模幂运算(用于RSA和Diffie-Hellman)易受计时攻击。RSA解密计算:
$$ct^{d} \mod{N}$$
其中$d$是机密指数。平方乘优化将乘法次数减少到$\log{d}$:
$$ \begin{align*} & \textbf{输入: } \text{底数 }y,\text{指数 } d={d_n,\cdots,d_0}_2,\text{模数 } N \ & r = 1 \ & \textbf{for } i=|n| \text{ downto } 0: \ & \quad\textbf{if } d_i == 1: \ & \quad\quad r = r * y \mod{N} \ & \quad y = y * y \mod{N} \ & \textbf{返回 }r \end{align*} $$
代码根据指数位$d_i$进行分支,违反了恒定时间原则。当$d_i = 1$时,会执行额外的乘法操作,增加执行时间并泄露位信息。
蒙哥马利乘法(常用于模运算)也会泄露计时信息:当中间值超过模数$N$时,需要额外的约简步骤。攻击者构造输入$y$和$y'$,使得:
$$ \begin{align*} y^2 < y^3 < N \ y'^2 < N \leq y'^3 \end{align*} $$
对于$y$,两次乘法的时间为$t_1+t_1$。对于$y'$,第二次乘法需要约简,时间为$t_1+t_2$。这种计时差异可揭示$d_i$是0还是1。

When to Use

使用场景

Apply constant-time analysis when:
  • Auditing cryptographic implementations (primitives, protocols)
  • Code handles secret keys, passwords, or sensitive cryptographic material
  • Implementing crypto algorithms from scratch
  • Reviewing PRs that touch crypto code
  • Investigating potential timing vulnerabilities
Consider alternatives when:
  • Code does not process secret data
  • Public algorithms with no secret inputs
  • Non-cryptographic timing requirements (performance optimization)
在以下场景应用恒定时间分析:
  • 审计加密实现(原语、协议)
  • 代码处理私钥、密码或敏感加密材料
  • 从零开始实现加密算法
  • 审查涉及加密代码的PR
  • 调查潜在的计时漏洞
在以下场景考虑替代方案:
  • 代码不处理机密数据
  • 无机密输入的公开算法
  • 非加密相关的计时要求(性能优化)

Quick Reference

快速参考

ScenarioRecommended ApproachSkill
Prove absence of leaksFormal verificationSideTrail, ct-verif, FaCT
Detect statistical timing differencesStatistical testingdudect
Track secret data flow at runtimeDynamic analysistimecop
Find cache-timing vulnerabilitiesSymbolic executionBinsec, pitchfork
场景推荐方法工具/技能
证明无泄露形式化验证SideTrail, ct-verif, FaCT
检测统计计时差异统计测试dudect
运行时跟踪机密数据流动态分析timecop
发现缓存计时漏洞符号执行Binsec, pitchfork

Constant-Time Tooling Categories

恒定时间工具分类

The cryptographic community has developed four categories of timing analysis tools:
CategoryApproachProsCons
FormalMathematical proof on modelGuarantees absence of leaksComplexity, modeling assumptions
SymbolicSymbolic execution pathsConcrete counterexamplesTime-intensive path exploration
DynamicRuntime tracing with marked secretsGranular, flexibleLimited coverage to executed paths
StatisticalMeasure real execution timingPractical, simple setupNo root cause, noise sensitivity
密码学界已开发出四类计时分析工具:
分类方法优点缺点
形式化对代码模型进行数学证明可保证无泄露复杂度高,存在建模假设
符号化符号化执行路径提供具体的反例路径探索耗时
动态标记机密数据并运行时跟踪粒度细、灵活覆盖范围仅限于已执行路径
统计测量实际执行时间实用、设置简单无根本原因分析,对噪声敏感

1. Formal Tools

1. 形式化工具

Formal verification mathematically proves timing properties on an abstraction (model) of code. Tools create a model from source/binary and verify it satisfies specified properties (e.g., variables annotated as secret).
Popular tools:
Strengths: Proof of absence, language-agnostic (LLVM bytecode) Weaknesses: Requires expertise, modeling assumptions may miss real-world issues
形式化验证通过数学方法在代码的抽象(模型)上证明计时属性。工具从源代码/二进制文件创建模型,并验证其是否满足指定属性(例如,标注为机密的变量)。
常用工具:
优势: 可证明无泄露,与语言无关(基于LLVM字节码) 劣势: 需要专业知识,建模假设可能遗漏实际问题

2. Symbolic Tools

2. 符号化工具

Symbolic execution analyzes how paths and memory accesses depend on symbolic variables (secrets). Provides concrete counterexamples. Focus on cache-timing attacks.
Popular tools:
Strengths: Concrete counterexamples aid debugging Weaknesses: Path explosion leads to long execution times
符号化执行分析路径和内存访问如何依赖符号变量(机密信息),可提供具体的反例,重点关注缓存计时攻击。
常用工具:
优势: 具体反例有助于调试 劣势: 路径爆炸导致执行时间长

3. Dynamic Tools

3. 动态工具

Dynamic analysis marks sensitive memory regions and traces execution to detect timing-dependent operations.
Popular tools:
Strengths: Granular control, targeted analysis Weaknesses: Coverage limited to executed paths
Detailed Guidance: See the timecop skill for setup and usage.
动态分析标记敏感内存区域并跟踪执行过程,以检测依赖计时的操作。
常用工具:
优势: 控制粒度细,可针对性分析 劣势: 覆盖范围仅限于已执行路径
详细指南: 请查看timecop技能了解设置和使用方法。

4. Statistical Tools

4. 统计工具

Execute code with various inputs, measure elapsed time, and detect inconsistencies. Tests actual implementation including compiler optimizations and architecture.
Popular tools:
Strengths: Simple setup, practical real-world results Weaknesses: No root cause info, noise obscures weak signals
Detailed Guidance: See the dudect skill for setup and usage.
使用各种输入执行代码,测量耗时并检测不一致性。测试实际实现,包括编译器优化和架构影响。
常用工具:
优势: 设置简单,可获得实际实用结果 劣势: 无根本原因信息,噪声会掩盖弱信号
详细指南: 请查看dudect技能了解设置和使用方法。

Testing Workflow

测试流程

Phase 1: Static Analysis        Phase 2: Statistical Testing
┌─────────────────┐            ┌─────────────────┐
│ Identify secret │      →     │ Detect timing   │
│ data flow       │            │ differences     │
│ Tool: ct-verif  │            │ Tool: dudect    │
└─────────────────┘            └─────────────────┘
         ↓                              ↓
Phase 4: Root Cause             Phase 3: Dynamic Tracing
┌─────────────────┐            ┌─────────────────┐
│ Pinpoint leak   │      ←     │ Track secret    │
│ location        │            │ propagation     │
│ Tool: Timecop   │            │ Tool: Timecop   │
└─────────────────┘            └─────────────────┘
Recommended approach:
  1. Start with dudect - Quick statistical check for timing differences
  2. If leaks found - Use Timecop to pinpoint root cause
  3. For high-assurance - Apply formal verification (ct-verif, SideTrail)
  4. Continuous monitoring - Integrate dudect into CI pipeline
Phase 1: Static Analysis        Phase 2: Statistical Testing
┌─────────────────┐            ┌─────────────────┐
│ Identify secret │      →     │ Detect timing   │
│ data flow       │            │ differences     │
│ Tool: ct-verif  │            │ Tool: dudect    │
└─────────────────┘            └─────────────────┘
         ↓                              ↓
Phase 4: Root Cause             Phase 3: Dynamic Tracing
┌─────────────────┐            ┌─────────────────┐
│ Pinpoint leak   │      ←     │ Track secret    │
│ location        │            │ propagation     │
│ Tool: Timecop   │            │ Tool: Timecop   │
└─────────────────┘            └─────────────────┘
推荐方法:
  1. 从dudect开始 - 快速统计检查计时差异
  2. 若发现泄露 - 使用Timecop定位根本原因
  3. 高可信度需求 - 应用形式化验证(ct-verif, SideTrail)
  4. 持续监控 - 将dudect集成到CI流水线

Tools and Approaches

工具与方法

Dudect - Statistical Analysis

Dudect - 统计分析

Dudect measures execution time for two input classes (fixed vs random) and uses Welch's t-test to detect statistically significant differences.
Detailed Guidance: See the dudect skill for complete setup, usage patterns, and CI integration.
Dudect测量两类输入(固定值vs随机值)的执行时间,并使用Welch t检验检测统计上显著的差异。
详细指南: 请查看dudect技能了解完整设置、使用模式和CI集成。

Quick Start for Constant-Time Analysis

恒定时间分析快速入门

c
#define DUDECT_IMPLEMENTATION
#include "dudect.h"

uint8_t do_one_computation(uint8_t *data) {
    // Code to measure goes here
}

void prepare_inputs(dudect_config_t *c, uint8_t *input_data, uint8_t *classes) {
    for (size_t i = 0; i < c->number_measurements; i++) {
        classes[i] = randombit();
        uint8_t *input = input_data + (size_t)i * c->chunk_size;
        if (classes[i] == 0) {
            // Fixed input class
        } else {
            // Random input class
        }
    }
}
Key advantages:
  • Simple C header-only integration
  • Statistical rigor via Welch's t-test
  • Works with compiled binaries (real-world conditions)
Key limitations:
  • No root cause information when leak detected
  • Sensitive to measurement noise
  • Cannot guarantee absence of leaks (statistical confidence only)
c
#define DUDECT_IMPLEMENTATION
#include "dudect.h"

uint8_t do_one_computation(uint8_t *data) {
    // 要测量的代码放在这里
}

void prepare_inputs(dudect_config_t *c, uint8_t *input_data, uint8_t *classes) {
    for (size_t i = 0; i < c->number_measurements; i++) {
        classes[i] = randombit();
        uint8_t *input = input_data + (size_t)i * c->chunk_size;
        if (classes[i] == 0) {
            // 固定输入类
        } else {
            // 随机输入类
        }
    }
}
核心优势:
  • 简单的C头文件集成
  • 通过Welch t检验保证统计严谨性
  • 可用于编译后的二进制文件(真实环境)
核心局限:
  • 检测到泄露时无法提供根本原因信息
  • 对测量噪声敏感
  • 无法保证无泄露(仅提供统计置信度)

Timecop - Dynamic Tracing

Timecop - 动态跟踪

Timecop wraps Valgrind to detect runtime operations dependent on secret memory regions.
Detailed Guidance: See the timecop skill for installation, examples, and debugging.
Timecop包装Valgrind以检测依赖机密内存区域的运行时操作。
详细指南: 请查看timecop技能了解安装、示例和调试方法。

Quick Start for Constant-Time Analysis

恒定时间分析快速入门

c
#include "valgrind/memcheck.h"

#define poison(addr, len) VALGRIND_MAKE_MEM_UNDEFINED(addr, len)
#define unpoison(addr, len) VALGRIND_MAKE_MEM_DEFINED(addr, len)

int main() {
    unsigned long long secret_key = 0x12345678;

    // Mark secret as poisoned
    poison(&secret_key, sizeof(secret_key));

    // Any branching or memory access dependent on secret_key
    // will be reported by Valgrind
    crypto_operation(secret_key);

    unpoison(&secret_key, sizeof(secret_key));
}
Run with Valgrind:
bash
valgrind --leak-check=full --track-origins=yes ./binary
Key advantages:
  • Pinpoints exact line of timing leak
  • No code instrumentation required
  • Tracks secret propagation through execution
Key limitations:
  • Cannot detect microarchitecture timing differences
  • Coverage limited to executed paths
  • Performance overhead (runs on synthetic CPU)
c
#include "valgrind/memcheck.h"

#define poison(addr, len) VALGRIND_MAKE_MEM_UNDEFINED(addr, len)
#define unpoison(addr, len) VALGRIND_MAKE_MEM_DEFINED(addr, len)

int main() {
    unsigned long long secret_key = 0x12345678;

    // 将机密标记为poisoned
    poison(&secret_key, sizeof(secret_key));

    // 任何依赖secret_key的分支或内存访问
    // 都会被Valgrind报告
    crypto_operation(secret_key);

    unpoison(&secret_key, sizeof(secret_key));
}
使用Valgrind运行:
bash
valgrind --leak-check=full --track-origins=yes ./binary
核心优势:
  • 精确定位计时泄露的代码行
  • 无需代码插桩
  • 跟踪机密信息在执行过程中的传播
核心局限:
  • 无法检测微架构层面的计时差异
  • 覆盖范围仅限于已执行路径
  • 性能开销大(在模拟CPU上运行)

Implementation Guide

实施指南

Phase 1: Initial Assessment

阶段1:初始评估

Identify cryptographic code handling secrets:
  • Private keys, exponents, nonces
  • Password hashes, authentication tokens
  • Encryption/decryption operations
Quick statistical check:
  1. Write dudect harness for the crypto function
  2. Run for 5-10 minutes with
    timeout 600 ./ct_test
  3. Monitor t-value: high absolute values indicate leakage
Tools: dudect Expected time: 1-2 hours (harness writing + initial run)
识别处理机密信息的加密代码:
  • 私钥、指数、随机数
  • 密码哈希、认证令牌
  • 加密/解密操作
快速统计检查:
  1. 为加密函数编写dudect测试套
  2. 运行5-10分钟(
    timeout 600 ./ct_test
  3. 监控t值:绝对值越高表示存在泄露
工具: dudect 预计时间: 1-2小时(编写测试套 + 初始运行)

Phase 2: Detailed Analysis

阶段2:详细分析

If dudect detects leakage:
Root cause investigation:
  1. Mark secret variables with Timecop
    poison()
  2. Run under Valgrind to identify exact line
  3. Review the four common violation patterns
  4. Check assembly output for conditional branches
Tools: Timecop, compiler output (
objdump -d
)
如果dudect检测到泄露:
根本原因调查:
  1. 使用Timecop的
    poison()
    标记机密变量
  2. 在Valgrind下运行以精确定位代码行
  3. 检查四种常见的违规模式
  4. 查看汇编输出中的条件分支
工具: Timecop、编译器输出(
objdump -d

Phase 3: Remediation

阶段3:修复

Fix the timing leak:
  • Replace conditional branches with constant-time selection (bitwise operations)
  • Use constant-time comparison functions
  • Replace array lookups with constant-time alternatives or masking
  • Verify compiler doesn't optimize away constant-time code
Re-verify:
  1. Run dudect again for extended period (30+ minutes)
  2. Test across different compilers and optimization levels
  3. Test on different CPU architectures
修复计时泄露:
  • 用恒定时间选择(位运算)替换条件分支
  • 使用恒定时间比较函数
  • 用恒定时间替代方案或掩码技术替换数组查找
  • 验证编译器不会优化掉恒定时间代码
重新验证:
  1. 再次运行dudect更长时间(30+分钟)
  2. 在不同编译器和优化级别下测试
  3. 在不同CPU架构上测试

Phase 4: Continuous Monitoring

阶段4:持续监控

Integrate into CI:
  • Add dudect tests to test suite
  • Run for fixed duration (5-10 minutes in CI)
  • Fail build if leakage detected
See the dudect skill for CI integration examples.
集成到CI:
  • 将dudect测试添加到测试套件
  • 固定运行时长(CI中运行5-10分钟)
  • 若检测到泄露则构建失败
请查看dudect技能了解CI集成示例。

Common Vulnerabilities

常见漏洞

VulnerabilityDescriptionDetectionSeverity
Secret-dependent branch
if (secret_bit) { ... }
dudect, TimecopCRITICAL
Secret-dependent array access
table[secret_index]
Timecop, BinsecHIGH
Variable-time division
result = x / secret
TimecopMEDIUM
Variable-time shift
result = x << secret
TimecopMEDIUM
Montgomery reduction leakExtra reduction when intermediate > NdudectHIGH
漏洞描述检测方法严重程度
依赖机密的分支
if (secret_bit) { ... }
dudect, Timecop关键
依赖机密的数组访问
table[secret_index]
Timecop, Binsec
可变时间除法
result = x / secret
Timecop
可变时间移位
result = x << secret
Timecop
蒙哥马利约简泄露中间值>N时的额外约简dudect

Secret-Dependent Branch: Deep Dive

依赖机密的分支:深入分析

The vulnerability: Execution time differs based on whether branch is taken. Common in optimized modular exponentiation (square-and-multiply).
How to detect with dudect:
c
uint8_t do_one_computation(uint8_t *data) {
    uint64_t base = ((uint64_t*)data)[0];
    uint64_t exponent = ((uint64_t*)data)[1]; // Secret!
    return mod_exp(base, exponent, MODULUS);
}

void prepare_inputs(dudect_config_t *c, uint8_t *input_data, uint8_t *classes) {
    for (size_t i = 0; i < c->number_measurements; i++) {
        classes[i] = randombit();
        uint64_t *input = (uint64_t*)(input_data + i * c->chunk_size);
        input[0] = rand(); // Random base
        input[1] = (classes[i] == 0) ? FIXED_EXPONENT : rand(); // Fixed vs random
    }
}
How to detect with Timecop:
c
poison(&exponent, sizeof(exponent));
result = mod_exp(base, exponent, modulus);
unpoison(&exponent, sizeof(exponent));
Valgrind will report:
Conditional jump or move depends on uninitialised value(s)
  at 0x40115D: mod_exp (example.c:14)
Related skill: dudect, timecop
漏洞: 执行时间因分支是否被执行而不同。常见于优化后的模幂运算(平方乘)。
使用dudect检测:
c
uint8_t do_one_computation(uint8_t *data) {
    uint64_t base = ((uint64_t*)data)[0];
    uint64_t exponent = ((uint64_t*)data)[1]; // 机密!
    return mod_exp(base, exponent, MODULUS);
}

void prepare_inputs(dudect_config_t *c, uint8_t *input_data, uint8_t *classes) {
    for (size_t i = 0; i < c->number_measurements; i++) {
        classes[i] = randombit();
        uint64_t *input = (uint64_t*)(input_data + i * c->chunk_size);
        input[0] = rand(); // 随机底数
        input[1] = (classes[i] == 0) ? FIXED_EXPONENT : rand(); // 固定值vs随机值
    }
}
使用Timecop检测:
c
poison(&exponent, sizeof(exponent));
result = mod_exp(base, exponent, modulus);
unpoison(&exponent, sizeof(exponent));
Valgrind会报告:
Conditional jump or move depends on uninitialised value(s)
  at 0x40115D: mod_exp (example.c:14)
相关技能: dudect, timecop

Case Studies

案例研究

Case Study: OpenSSL RSA Timing Attack

案例研究:OpenSSL RSA计时攻击

Brumley and Boneh (2005) extracted RSA private keys from OpenSSL over a network. The vulnerability exploited Montgomery multiplication's variable-time reduction step.
Attack vector: Timing differences in modular exponentiation Detection approach: Statistical analysis (precursor to dudect) Impact: Remote key extraction
Tools used: Custom timing measurement Techniques applied: Statistical analysis, chosen-ciphertext queries
Brumley和Boneh(2005年)通过网络从OpenSSL中提取RSA私钥。该漏洞利用了蒙哥马利乘法的可变时间约简步骤。
攻击向量: 模幂运算中的计时差异 检测方法: 统计分析(dudect的前身) 影响: 远程提取密钥
使用工具: 自定义计时测量工具 应用技术: 统计分析、选择密文查询

Case Study: KyberSlash

案例研究:KyberSlash

Post-quantum algorithm Kyber's reference implementation contained timing vulnerabilities in polynomial operations. Division operations leaked secret coefficients.
Attack vector: Secret-dependent division timing Detection approach: Dynamic analysis and statistical testing Impact: Secret key recovery in post-quantum cryptography
Tools used: Timing measurement tools Techniques applied: Differential timing analysis
后量子算法Kyber的参考实现中,多项式操作存在计时漏洞。除法操作泄露了机密系数。
攻击向量: 依赖机密的除法计时 检测方法: 动态分析和统计测试 影响: 后量子密码中的密钥恢复
使用工具: 计时测量工具 应用技术: 差分计时分析

Advanced Usage

高级用法

Tips and Tricks

技巧与窍门

TipWhy It Helps
Pin dudect to isolated CPU core (
taskset -c 2
)
Reduces OS noise, improves signal detection
Test multiple compilers (gcc, clang, MSVC)Optimizations may introduce or remove leaks
Run dudect for extended periods (hours)Increases statistical confidence
Minimize non-crypto code in harnessReduces noise that masks weak signals
Check assembly output (
objdump -d
)
Verify compiler didn't introduce branches
Use
-O3 -march=native
in testing
Matches production optimization levels
技巧作用
将dudect绑定到独立CPU核心(
taskset -c 2
减少系统噪声,提升信号检测能力
测试多个编译器(gcc, clang, MSVC)优化可能引入或消除泄露
长时间运行dudect(数小时)提高统计置信度
测试套中尽量减少非加密代码减少掩盖弱信号的噪声
查看汇编输出(
objdump -d
验证编译器未引入分支
测试时使用
-O3 -march=native
匹配生产环境优化级别

Common Mistakes

常见错误

MistakeWhy It's WrongCorrect Approach
Only testing one input distributionMay miss leaks visible with other patternsTest fixed-vs-random, fixed-vs-fixed-different, etc.
Short dudect runs (< 1 minute)Insufficient measurements for weak signalsRun 5-10+ minutes, longer for high assurance
Ignoring compiler optimization levels
-O0
may hide leaks present in
-O3
Test at production optimization level
Not testing on target architecturex86 vs ARM have different timing characteristicsTest on deployment platform
Marking too much as secret in TimecopFalse positives, unclear resultsMark only true secrets (keys, not public data)
错误原因正确做法
仅测试一种输入分布可能遗漏在其他模式下可见的泄露测试固定值vs随机值、固定值vs不同固定值等多种组合
dudect运行时间过短(<1分钟)测量次数不足,无法检测弱信号运行5-10+分钟,高可信度需求下运行更长时间
忽略编译器优化级别
-O0
可能隐藏
-O3
下存在的泄露
在生产环境优化级别下测试
未在目标架构上测试x86与ARM的计时特性不同在部署平台上测试
Timecop中标记过多内容为机密误报多,结果不清晰仅标记真正的机密信息(密钥,而非公开数据)

Related Skills

相关技能

Tool Skills

工具技能

SkillPrimary Use in Constant-Time Analysis
dudectStatistical detection of timing differences via Welch's t-test
timecopDynamic tracing to pinpoint exact location of timing leaks
技能在恒定时间分析中的主要用途
dudect通过Welch t检验统计检测计时差异
timecop动态跟踪以精确定位计时泄露位置

Technique Skills

技术技能

SkillWhen to Apply
coverage-analysisEnsure test inputs exercise all code paths in crypto function
ci-integrationAutomate constant-time testing in continuous integration pipeline
技能应用场景
coverage-analysis确保测试输入覆盖加密函数的所有代码路径
ci-integration在持续集成流水线中自动化恒定时间测试

Related Domain Skills

相关领域技能

SkillRelationship
crypto-testingConstant-time analysis is essential component of cryptographic testing
fuzzingFuzzing crypto code may trigger timing-dependent paths
技能关系
crypto-testing恒定时间分析是密码测试的重要组成部分
fuzzing模糊测试加密代码可能触发依赖计时的路径

Skill Dependency Map

技能依赖图

                    ┌─────────────────────────┐
                    │  constant-time-analysis │
                    │     (this skill)        │
                    └───────────┬─────────────┘
                ┌───────────────┴───────────────┐
                │                               │
                ▼                               ▼
    ┌───────────────────┐           ┌───────────────────┐
    │      dudect       │           │     timecop       │
    │  (statistical)    │           │    (dynamic)      │
    └────────┬──────────┘           └────────┬──────────┘
             │                               │
             └───────────────┬───────────────┘
              ┌──────────────────────────────┐
              │   Supporting Techniques      │
              │ coverage, CI integration     │
              └──────────────────────────────┘
                    ┌─────────────────────────┐
                    │  constant-time-analysis │
                    │     (本技能)        │
                    └───────────┬─────────────┘
                ┌───────────────┴───────────────┐
                │                               │
                ▼                               ▼
    ┌───────────────────┐           ┌───────────────────┐
    │      dudect       │           │     timecop       │
    │  (统计分析)    │           │    (动态分析)      │
    └────────┬──────────┘           └────────┬──────────┘
             │                               │
             └───────────────┬───────────────┘
              ┌──────────────────────────────┐
              │   支持技术      │
              │ 覆盖率分析, CI集成     │
              └──────────────────────────────┘

Resources

资源

Key External Resources

关键外部资源

These results must be false: A usability evaluation of constant-time analysis tools Comprehensive usability study of constant-time analysis tools. Key findings: developers struggle with false positives, need better error messages, and benefit from tool integration. Evaluates FaCT, ct-verif, dudect, and Memsan across multiple cryptographic implementations. Recommends improved tooling UX and better documentation.
List of constant-time tools - CROCS Curated catalog of constant-time analysis tools with tutorials. Covers formal tools (ct-verif, FaCT), dynamic tools (Memsan, Timecop), symbolic tools (Binsec), and statistical tools (dudect). Includes practical tutorials for setup and usage.
Paul Kocher: Timing Attacks on Implementations of Diffie-Hellman, RSA, DSS, and Other Systems Original 1996 paper introducing timing attacks. Demonstrates attacks on modular exponentiation in RSA and Diffie-Hellman. Essential historical context for understanding timing vulnerabilities.
Remote Timing Attacks are Practical (Brumley & Boneh) Demonstrates practical remote timing attacks against OpenSSL. Shows network-level timing differences are sufficient to extract RSA keys. Proves timing attacks work in realistic network conditions.
Cache-timing attacks on AES Shows AES implementations using lookup tables are vulnerable to cache-timing attacks. Demonstrates practical attacks extracting AES keys via cache timing side channels.
KyberSlash: Division Timings Leak Secrets Recent discovery of timing vulnerabilities in Kyber (NIST post-quantum standard). Shows division operations leak secret coefficients. Highlights that constant-time issues persist even in modern post-quantum cryptography.
These results must be false: A usability evaluation of constant-time analysis tools 恒定时间分析工具的综合可用性研究。核心发现:开发者难以处理误报,需要更友好的错误信息,且能从工具集成中获益。评估了FaCT、ct-verif、dudect和Memsan在多个加密实现上的表现。建议改进工具的用户体验和文档。
List of constant-time tools - CROCS 精选的恒定时间分析工具目录,包含教程。涵盖形式化工具(ct-verif, FaCT)、动态工具(Memsan, Timecop)、符号化工具(Binsec)和统计工具(dudect)。包含设置和使用的实用教程。
Paul Kocher: Timing Attacks on Implementations of Diffie-Hellman, RSA, DSS, and Other Systems 1996年引入计时攻击的原始论文。演示了针对RSA和Diffie-Hellman中模幂运算的攻击。是理解计时漏洞的重要历史资料。
Remote Timing Attacks are Practical (Brumley & Boneh) 演示了针对OpenSSL的实际远程计时攻击。证明网络层面的计时差异足以提取RSA密钥。证明计时攻击在真实网络环境中可行。
Cache-timing attacks on AES 证明使用查找表的AES实现易受缓存计时攻击。演示了通过缓存计时侧信道提取AES密钥的实际攻击方法。
KyberSlash: Division Timings Leak Secrets 近期发现NIST后量子标准Kyber中的计时漏洞。证明除法操作泄露了机密系数。强调即使在现代后量子密码中,恒定时间问题仍然存在。

Video Resources

视频资源