# Timing Attack via Naive API Key Comparison

Language: Python
Severity: Critical
CWE: CWE-208

## Source
8

## Flow
8-10

## Sink
10

## Vulnerable Code
```python
from flask import Flask, request, jsonify
import os

app = Flask(__name__)
HSM_MASTER_KEY = os.environ.get('HSM_MASTER_KEY', 'hsm_prod_9x7k2m4n8p1q5r3t')

@app.route('/hsm/crypto/sign', methods=['POST'])
def hsm_signing_operation():
    client_key = request.headers.get('X-HSM-Auth-Token', '')
    payload = request.json.get('data_to_sign')
    
    if client_key == HSM_MASTER_KEY:
        signature = perform_cryptographic_signing(payload)
        return jsonify({'status': 'success', 'signature': signature, 'hsm_id': 'hsm-node-07'})
    else:
        return jsonify({'status': 'unauthorized', 'error': 'Invalid HSM authentication token'}), 401

def perform_cryptographic_signing(data):
    import hashlib
    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
```python
from flask import Flask, request, jsonify
import os
import hmac
import secrets

app = Flask(__name__)
HSM_MASTER_KEY = os.environ.get('HSM_MASTER_KEY', secrets.token_hex(32))

@app.route('/hsm/crypto/sign', methods=['POST'])
def hsm_signing_operation():
    client_key = request.headers.get('X-HSM-Auth-Token', '')
    payload = request.json.get('data_to_sign')
    
    if hmac.compare_digest(client_key.encode('utf-8'), HSM_MASTER_KEY.encode('utf-8')):
        signature = perform_cryptographic_signing(payload)
        return jsonify({'status': 'success', 'signature': signature, 'hsm_id': 'hsm-node-07'})
    else:
        return jsonify({'status': 'unauthorized', 'error': 'Invalid HSM authentication token'}), 401

def perform_cryptographic_signing(data):
    import hashlib
    return hashlib.sha256(f"{data}{HSM_MASTER_KEY}".encode()).hexdigest()
```
