Перейти к содержанию
Skillpedia
Безопасность8.0k · #12715

constant-time-testing

Что он делает

Этот скилл проверяет скомпилированную криптографическую реализацию на утечки по времени, которые могут раскрыть секретные значения. Он нужен разработчикам и аудиторам, которые проверяют криптографический код.

Когда использовать

  • ✓Когда вы хотите проверить, что криптографическая библиотека работает за одно и то же время, какой бы ни была секретная информация на входе.
  • ✓Когда нужно измерить разброс времени работы скомпилированной программы.
  • ✓Когда аудит отмечает подозрительное ветвление или обращение к памяти в криптографическом коде, и вы хотите это проверить.

Ссылка на скилл

https://github.com/trailofbits/skills/blob/main/plugins/testing-handbook-skills/skills/constant-time-testing/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/trailofbits/skills/blob/main/plugins/testing-handbook-skills/skills/constant-time-testing/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Я хочу проверить, занимает ли наша реализация AES разное время в зависимости от ключа.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Агент запускает код много раз с разными секретными входными данными и с помощью статистики проверяет, отличается ли время. Он также может трассировать программу, чтобы найти ветвления или обращения к памяти, которые зависят от секретов.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

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.

Key Concepts

Concept Description
Constant-time Code path and memory accesses independent of secret data
Timing leakage Observable execution time differences correlated with secrets
Side channel Information extracted from implementation rather than algorithm
Microarchitecture CPU-level timing differences (cache, division, shifts)

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

Common Constant-Time Violation Patterns

Four patterns account for most timing vulnerabilities:

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

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.

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)

Quick Reference

| Scenario | Recommended Approach | Skill | |----------|-------------------

Частые вопросы

Доказывает ли пройденный тест безопасность кода?

Не полностью. Тесты по времени дают доказательства, но нужны и другие тесты и проверки.

Какие инструменты он использует?

Он использует dudect для статистических тестов времени и Timecop вместе с Valgrind для динамической трассировки.

Проверяет ли он все виды криптографических ошибок?

Нет. Он сосредоточен на времени. Другие виды ошибок требуют других проверок.

Подробности

Оригинальное описание автора

Measures timing side channels in cryptographic implementations by running them, using dudect for statistical analysis and Timecop over Valgrind for dynamic tracing. Covers the formal, symbolic, dynamic, and statistical tool categories and how to read a result. Use when testing whether a running implementation is constant-time, measuring timing variance on a compiled binary, or investigating a suspected timing attack. Not for statically inspecting compiler output — the constant-time-analysis plugin covers that.

repo: trailofbits/skills

Популярность

Звёзды на GitHub
8.0k
Место в рейтинге
#12715
Лицензия
CC-BY-SA-4.0
Обновлён
02.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы