{"title":"Timing Attack via Naive API Key Comparison","language":"Python","severity":"Critical","cwe":"CWE-208","source_lines":[8],"flow_lines":[8,10],"sink_lines":[10],"vulnerable_code":"from flask import Flask, request, jsonify\nimport os\n\napp = Flask(__name__)\nHSM_MASTER_KEY = os.environ.get('HSM_MASTER_KEY', 'hsm_prod_9x7k2m4n8p1q5r3t')\n\n@app.route('/hsm/crypto/sign', methods=['POST'])\ndef hsm_signing_operation():\n    client_key = request.headers.get('X-HSM-Auth-Token', '')\n    payload = request.json.get('data_to_sign')\n    \n    if client_key == HSM_MASTER_KEY:\n        signature = perform_cryptographic_signing(payload)\n        return jsonify({'status': 'success', 'signature': signature, 'hsm_id': 'hsm-node-07'})\n    else:\n        return jsonify({'status': 'unauthorized', 'error': 'Invalid HSM authentication token'}), 401\n\ndef perform_cryptographic_signing(data):\n    import hashlib\n    return hashlib.sha256(f\"{data}{HSM_MASTER_KEY}\".encode()).hexdigest()","explanation":"The code uses the equality operator (==) to compare the client-provided authentication token with the HSM master key. This naive string comparison is vulnerable to timing attacks because it performs character-by-character comparison and returns false as soon as a mismatch is found, allowing attackers to measure response times and gradually deduce the correct key.","remediation":"The fix replaces the naive equality operator (==) with hmac.compare_digest(), which performs a constant-time comparison that takes the same amount of time regardless of where the first difference occurs, preventing timing-based side-channel attacks. Additionally, the hardcoded default key was replaced with a securely generated random token using secrets.token_hex() to avoid shipping predictable credentials.","secure_code":"from flask import Flask, request, jsonify\nimport os\nimport hmac\nimport secrets\n\napp = Flask(__name__)\nHSM_MASTER_KEY = os.environ.get('HSM_MASTER_KEY', secrets.token_hex(32))\n\n@app.route('/hsm/crypto/sign', methods=['POST'])\ndef hsm_signing_operation():\n    client_key = request.headers.get('X-HSM-Auth-Token', '')\n    payload = request.json.get('data_to_sign')\n    \n    if hmac.compare_digest(client_key.encode('utf-8'), HSM_MASTER_KEY.encode('utf-8')):\n        signature = perform_cryptographic_signing(payload)\n        return jsonify({'status': 'success', 'signature': signature, 'hsm_id': 'hsm-node-07'})\n    else:\n        return jsonify({'status': 'unauthorized', 'error': 'Invalid HSM authentication token'}), 401\n\ndef perform_cryptographic_signing(data):\n    import hashlib\n    return hashlib.sha256(f\"{data}{HSM_MASTER_KEY}\".encode()).hexdigest()"}