Timing Attack

Timing Attack is a side-channel attack that extracts sensitive information by precisely measuring how long operations take. When execution time depends on secret data, attackers can infer the secret through statistical analysis of timing differences.

Common Vulnerable Patterns

String Comparison

// VULNERABLE: Early exit on mismatch
def check_password(input, stored):
    for i in range(len(stored)):
        if input[i] != stored[i]:
            return False  // Exits early!
    return True

// Attacker measures:
// "a..." - fails fast (10μs)
// "p..." - fails slower (15μs) - first char is 'p'!
// "pa.." - even slower (20μs) - second char is 'a'!

Cryptographic Operations

// RSA decryption time varies with bit values
// AES cache timing reveals key bits
// ECDSA nonce bias from timing

Real-World Example

// Timing HMAC comparison
sent_hmac = request.get("hmac")
expected_hmac = compute_hmac(data, secret)

// VULNERABLE
if sent_hmac == expected_hmac:  // Uses non-constant compare
    return "Valid"

// Attacker tries different HMAC values
// Correct bytes take longer to compare

Prevention

// Use constant-time comparison
import hmac
def safe_compare(a, b):
    return hmac.compare_digest(a, b)

// Python
from secrets import compare_digest

// Ruby
require 'rack/utils'
Rack::Utils.secure_compare(a, b)

// Always takes same time regardless of match position

Mitigation Strategies

  • Use constant-time comparison functions
  • Add random delays (weak, can be averaged out)
  • Use cryptographic libraries with timing-safe implementations
  • Consider hardware-based timing protections

See Also