Cryptographic Timing Attack Vulnerabilities
What it is
A critical vulnerability where cryptographic operations leak sensitive information through timing variations. Attackers can exploit differences in execution time to extract secrets like encryption keys, passwords, tokens, or other sensitive data by measuring how long cryptographic operations take to complete.
// VULNERABLE: String comparison with timing leak
package main
func vulnerableTokenVerify(providedToken, expectedToken string) bool {
// VULNERABLE: Early exit on first character mismatch
if len(providedToken) != len(expectedToken) {
return false
}
for i := 0; i < len(providedToken); i++ {
if providedToken[i] != expectedToken[i] {
return false // Timing reveals mismatch position
}
}
return true
}
func vulnerableAPIKeyCheck(providedKey string, validKeys []string) bool {
// VULNERABLE: Early match = faster response
for _, validKey := range validKeys {
if providedKey == validKey {
return true // Found early = faster
}
}
return false // Checked all = slower
}// SECURE: Constant-time string comparison
package main
import (
"crypto/subtle"
"time"
)
func secureTokenVerify(providedToken, expectedToken string) bool {
providedBytes := []byte(providedToken)
expectedBytes := []byte(expectedToken)
if len(providedBytes) != len(expectedBytes) {
// Still perform comparison for timing consistency
dummyBytes := make([]byte, len(providedBytes))
subtle.ConstantTimeCompare(providedBytes, dummyBytes)
return false
}
// SECURE: Constant-time comparison
return subtle.ConstantTimeCompare(providedBytes, expectedBytes) == 1
}
func secureAPIKeyCheck(providedKey string, validKeys []string) bool {
startTime := time.Now()
isValid := false
// SECURE: Check all keys to maintain constant timing
for _, validKey := range validKeys {
if secureTokenVerify(providedKey, validKey) {
isValid = true
// Don't break - continue for constant timing
}
}
// SECURE: Ensure minimum response time
elapsed := time.Since(startTime)
if elapsed < 100*time.Millisecond {
time.Sleep(100*time.Millisecond - elapsed)
}
return isValid
}💡 Why This Fix Works
The vulnerable code uses character-by-character comparison with early exit, allowing attackers to determine the position of the first incorrect character by measuring response time. The secure version uses crypto/subtle.ConstantTimeCompare which always takes the same time regardless of where differences occur, checks all keys without early termination, and enforces a minimum response time to prevent timing analysis.
Why it happens
Typical mistakes in app/data layers enable this vulnerability.
Root causes
Fixes
Detect This Vulnerability in Your Code
Sourcery automatically identifies cryptographic timing attack vulnerabilities and many other security issues in your codebase.