{"title":"Timing Attack via Naive Equality Comparison for API Key Verification","language":"Python","severity":"High","cwe":"CWE-208","source_lines":[9],"flow_lines":[9,10,11],"sink_lines":[11],"vulnerable_code":"import hashlib\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\nIOT_DEVICE_MASTER_KEY = \"iot_secure_key_9a8f7e6d5c4b3a2\"\n\n@app.route('/api/v1/device/telemetry', methods=['POST'])\ndef receive_telemetry():\n    device_auth_header = request.headers.get('X-Device-Auth-Token', '')\n    computed_hash = hashlib.sha256(device_auth_header.encode()).hexdigest()\n    expected_hash = hashlib.sha256(IOT_DEVICE_MASTER_KEY.encode()).hexdigest()\n    if computed_hash == expected_hash:\n        telemetry_data = request.json\n        return jsonify({\"status\": \"accepted\", \"device_id\": telemetry_data.get('device_id')}), 200\n    return jsonify({\"error\": \"unauthorized_device\"}), 401","explanation":"The code uses Python's standard equality operator (==) to compare hashed authentication tokens, which is vulnerable to timing attacks. The comparison short-circuits on the first mismatching character, allowing attackers to measure response times and iteratively guess the correct hash byte-by-byte, even though SHA-256 is used.","remediation":"The fix replaces the naive equality operator (==) with hmac.compare_digest(), which performs a constant-time comparison of the two hash strings. This prevents timing attacks because the function always takes the same amount of time regardless of how many characters match, eliminating the information leakage from early short-circuit exits.","secure_code":"import hashlib\nimport hmac\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\nIOT_DEVICE_MASTER_KEY = \"iot_secure_key_9a8f7e6d5c4b3a2\"\n\n@app.route('/api/v1/device/telemetry', methods=['POST'])\ndef receive_telemetry():\n    device_auth_header = request.headers.get('X-Device-Auth-Token', '')\n    computed_hash = hashlib.sha256(device_auth_header.encode()).hexdigest()\n    expected_hash = hashlib.sha256(IOT_DEVICE_MASTER_KEY.encode()).hexdigest()\n    if hmac.compare_digest(computed_hash, expected_hash):\n        telemetry_data = request.json\n        return jsonify({\"status\": \"accepted\", \"device_id\": telemetry_data.get('device_id')}), 200\n    return jsonify({\"error\": \"unauthorized_device\"}), 401"}