{"title":"Timing Attack via Direct Equality Check on API Keys","language":"Python","severity":"High","cwe":"CWE-208","source_lines":[4],"flow_lines":[4,5,6],"sink_lines":[6],"vulnerable_code":"import boto3\nfrom flask import request, jsonify\n\ndef validate_s3_access_token():\n    client_token = request.headers.get('X-S3-Access-Token')\n    stored_token = boto3.client('ssm').get_parameter(Name='/prod/s3/access_token', WithDecryption=True)['Parameter']['Value']\n    if client_token == stored_token:\n        return jsonify({'status': 'authorized', 's3_bucket': 'prod-data-lake'})\n    return jsonify({'status': 'unauthorized'}), 403","explanation":"The code uses direct string equality comparison (==) to validate the API token, which is vulnerable to timing attacks. An attacker can measure response times to determine correct characters of the token byte-by-byte, as the comparison stops at the first mismatched character, creating measurable time differences.","remediation":"The fix replaces the direct equality comparison (==) with hmac.compare_digest(), which performs a constant-time comparison that takes the same amount of time regardless of where the first mismatch occurs. This prevents timing attacks by ensuring an attacker cannot infer correct characters based on response time differences. Additionally, a None check is added for the client token to prevent errors when the header is missing.","secure_code":"import boto3\nimport hmac\nfrom flask import request, jsonify\n\ndef validate_s3_access_token():\n    client_token = request.headers.get('X-S3-Access-Token')\n    if client_token is None:\n        return jsonify({'status': 'unauthorized'}), 403\n    stored_token = boto3.client('ssm').get_parameter(Name='/prod/s3/access_token', WithDecryption=True)['Parameter']['Value']\n    if hmac.compare_digest(client_token.encode('utf-8'), stored_token.encode('utf-8')):\n        return jsonify({'status': 'authorized', 's3_bucket': 'prod-data-lake'})\n    return jsonify({'status': 'unauthorized'}), 403"}