Back to all terms
Securityadvanced

Timing Attack Prevention

Preventing attackers from extracting secrets by measuring the time differences in how the application processes different inputs.

Also known as: constant-time comparison, timing side-channel prevention, time-based attack mitigation

Description

Timing attacks are a class of side-channel attacks where an attacker extracts sensitive information by precisely measuring the time an application takes to process different inputs. The most common example is string comparison: when comparing a user-supplied token against a stored secret using standard equality operators (=== or ==), the comparison typically returns false at the first mismatched character. This means incorrect tokens that match more leading characters take longer to reject, allowing an attacker to reconstruct the secret one character at a time.

Timing attacks apply to various scenarios: API key validation, HMAC comparison, password hash verification, token comparison, and cryptographic operations. Even sub-millisecond differences can be exploited with statistical analysis over many requests. Network jitter adds noise but does not eliminate the vulnerability, especially for local or same-network attackers. Modern research has demonstrated successful remote timing attacks across the internet using sufficient measurements.

Prevention requires using constant-time comparison functions for all security-sensitive comparisons. In Node.js, crypto.timingSafeEqual() compares two buffers in constant time regardless of where they differ. For password verification, bcrypt.compare() and similar functions are already designed to be constant-time. Beyond string comparison, other timing defenses include processing all authentication steps regardless of early failures (don't return early on user-not-found), adding constant-time padding to cryptographic operations, and avoiding data-dependent branching in security-critical code paths.

Prompt Snippet

Use crypto.timingSafeEqual() for all security-sensitive comparisons (API keys, HMAC signatures, CSRF tokens, webhook signatures): convert both strings to Buffers of equal length before comparison. Never use === or == to compare secrets. For password verification, rely on bcrypt.compare() or argon2.verify() which are constant-time by design. Ensure authentication flows don't leak timing information about user existence -- process the full authentication pipeline (including password hash comparison against a dummy hash) even when the user is not found. For webhook signature validation (Stripe, GitHub), use the provider's SDK verify method which implements constant-time comparison internally.

Tags

timing-attacksside-channelconstant-timecryptographic-security