{"title":"HMAC Signature Verification Timing Attack via Naive String Comparison","language":"Python","severity":"High","cwe":"CWE-208","source_lines":[9],"flow_lines":[9,11],"sink_lines":[11],"vulnerable_code":"import hmac\nimport hashlib\nfrom flask import request, jsonify\n\ndef validate_iot_device_command(device_secret):\n    incoming_cmd = request.json.get('command')\n    incoming_sig = request.headers.get('X-Device-Signature')\n    expected_sig = hmac.new(device_secret.encode(), incoming_cmd.encode(), hashlib.sha256).hexdigest()\n    if incoming_sig == expected_sig:\n        return jsonify({'status': 'authorized', 'execute': True})\n    return jsonify({'status': 'unauthorized', 'execute': False}), 403","explanation":"The code uses a naive string comparison (==) to validate HMAC signatures instead of hmac.compare_digest(). This allows timing attacks where attackers can measure response times to determine correct signature bytes incrementally, potentially bypassing authentication by exploiting early-exit comparison behavior.","remediation":"The fix replaces the naive string comparison operator (==) with hmac.compare_digest(), which performs constant-time comparison regardless of where the strings differ. This prevents timing attacks by ensuring the comparison always takes the same amount of time whether zero bytes or all bytes match.","secure_code":"import hmac\nimport hashlib\nfrom flask import request, jsonify\n\ndef validate_iot_device_command(device_secret):\n    incoming_cmd = request.json.get('command')\n    incoming_sig = request.headers.get('X-Device-Signature')\n    expected_sig = hmac.new(device_secret.encode(), incoming_cmd.encode(), hashlib.sha256).hexdigest()\n    if hmac.compare_digest(incoming_sig, expected_sig):\n        return jsonify({'status': 'authorized', 'execute': True})\n    return jsonify({'status': 'unauthorized', 'execute': False}), 403"}