{"title":"Timing Attack via Non-Constant-Time Secret Comparison","language":"Python","severity":"High","cwe":"CWE-208","source_lines":[8],"flow_lines":[7,8],"sink_lines":[8],"vulnerable_code":"import hmac\nimport hashlib\n\ndef verify_iot_device_signature(device_id, payload, received_sig):\n    master_key = b\"IoT_Master_Secret_2024_XK9P\"\n    device_secret = hashlib.sha256(master_key + device_id.encode()).digest()\n    expected_sig = hmac.new(device_secret, payload.encode(), hashlib.sha256).hexdigest()\n    if received_sig == expected_sig:\n        return {\"authenticated\": True, \"device\": device_id}\n    return {\"authenticated\": False, \"error\": \"Invalid signature\"}","explanation":"The code uses the non-constant-time equality operator (==) to compare cryptographic signatures on line 8. This allows timing attacks where an attacker can measure response times to determine correct signature bytes sequentially, eventually reconstructing a valid signature without knowing the secret key.","remediation":"The fix replaces the non-constant-time string equality operator (==) with hmac.compare_digest(), which performs a constant-time comparison of two strings. This prevents timing attacks because the comparison always takes the same amount of time regardless of how many bytes match, making it impossible for an attacker to deduce the expected signature by measuring response times.","secure_code":"import hmac\nimport hashlib\n\ndef verify_iot_device_signature(device_id, payload, received_sig):\n    master_key = b\"IoT_Master_Secret_2024_XK9P\"\n    device_secret = hashlib.sha256(master_key + device_id.encode()).digest()\n    expected_sig = hmac.new(device_secret, payload.encode(), hashlib.sha256).hexdigest()\n    if hmac.compare_digest(received_sig, expected_sig):\n        return {\"authenticated\": True, \"device\": device_id}\n    return {\"authenticated\": False, \"error\": \"Invalid signature\"}"}