Constant-Time Comparisons & Timing Attacks
Standard equality (`a == b`) short-circuits on the first mismatched byte. An attacker measuring microsecond network round-trips can deduce secret tokens byte-by-byte. `hmac.compare_digest()` executes in constant time regardless of where differences occur, closing the timing side-channel ⏱️🛡️.
import hmac
actual_token = "f8a93b2c1d0e5f7a"
attacker_guess = "f8a93b2c1d0e5f7b" # Differs on the last byte
# INSECURE: Short-circuits early, leaking character position
# is_valid = (actual_token == attacker_guess)
# SECURE: Constant-time comparison
is_valid = hmac.compare_digest(actual_token, attacker_guess)
print(f"Token matches? {is_valid} 🛡️")
# 62. Constant-Time Comparisons & Timing Attacks If you compare API keys or cryptographic signatures using Python's standard `if token == user_input:`, you have created a severe remote timing vulnerability 🛑. ```python # Standard String Comparison (Vulnerable to Timing Attacks): # "A" == "Z" -> Returns False in ~1 CPU clock cycle (fails index 0) # "A" == "A" -> Moves to index 1, taking slightly longer! # "SECRET_A" vs "SECRET_Z" -> Fails at index 7 (takes 7x longer!) ``` ### The Timing Attack Exploit Vector 1. **Statistical Time Analysis**: An attacker sends thousands of requests measuring server latency down to microsecond or sub-microsecond resolution. 2. **Byte-by-Byte Harvesting**: When they guess the first correct byte, average server response time jumps slightly because the comparison checked index 1 before failing. They lock in that byte and repeat for the next byte. 3. **Constant-Time Invariant**: `hmac.compare_digest()` calculates a bitwise XOR across the entire byte length without early exit, ensuring execution time is independent of byte contents ⏱️🛡️. --- ### Interactive Pop-Quiz 🧠 #### How does an attacker exploit standard string equality (==) to steal secret authentication tokens via a timing attack? - [ ] By measuring the microscopic time differences caused by short-circuiting at the first non-matching byte ⏱️ - [ ] By injecting SQL syntax into the string comparison operator - [ ] By overflowing the CPU floating point register during evaluation - [ ] By triggering an unhandled Segmentation Fault in the interpreter --- ### Practical Challenge 🎯 Implement a secure authentication validator `verify_signature(expected, provided)` using `hmac.compare_digest`. Ensure it accepts strings or bytes (converting str to utf-8 bytes if needed). Test with `expected = 'SECRET_HASH_99'`, once with an exact match and once with `'SECRET_HASH_00'`. Assert the results are `True` and `False`, and print `'TIMING_DEFENSE_OK'`. <details> <summary>Solution</summary> ```python import hmac def verify_signature(expected, provided): if isinstance(expected, str): expected = expected.encode('utf-8') if isinstance(provided, str): provided = provided.encode('utf-8') return hmac.compare_digest(expected, provided) expected = "SECRET_HASH_99" assert verify_signature(expected, "SECRET_HASH_99") is True assert verify_signature(expected, "SECRET_HASH_00") is False print("TIMING_DEFENSE_OK") ``` </details>