# Timing Attack via Direct Equality Check on API Keys

Language: Python
Severity: High
CWE: CWE-208

## Source
4

## Flow
4-5-6

## Sink
6

## Vulnerable Code
```python
import boto3
from flask import request, jsonify

def validate_s3_access_token():
    client_token = request.headers.get('X-S3-Access-Token')
    stored_token = boto3.client('ssm').get_parameter(Name='/prod/s3/access_token', WithDecryption=True)['Parameter']['Value']
    if client_token == stored_token:
        return jsonify({'status': 'authorized', 's3_bucket': 'prod-data-lake'})
    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
```python
import boto3
import hmac
from flask import request, jsonify

def validate_s3_access_token():
    client_token = request.headers.get('X-S3-Access-Token')
    if client_token is None:
        return jsonify({'status': 'unauthorized'}), 403
    stored_token = boto3.client('ssm').get_parameter(Name='/prod/s3/access_token', WithDecryption=True)['Parameter']['Value']
    if hmac.compare_digest(client_token.encode('utf-8'), stored_token.encode('utf-8')):
        return jsonify({'status': 'authorized', 's3_bucket': 'prod-data-lake'})
    return jsonify({'status': 'unauthorized'}), 403
```
