# HMAC Signature Verification Timing Attack via Naive String Comparison

Language: Python
Severity: High
CWE: CWE-208

## Source
9

## Flow
9-11

## Sink
11

## Vulnerable Code
```python
import hmac
import hashlib
from flask import request, jsonify

def validate_iot_device_command(device_secret):
    incoming_cmd = request.json.get('command')
    incoming_sig = request.headers.get('X-Device-Signature')
    expected_sig = hmac.new(device_secret.encode(), incoming_cmd.encode(), hashlib.sha256).hexdigest()
    if incoming_sig == expected_sig:
        return jsonify({'status': 'authorized', 'execute': True})
    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
```python
import hmac
import hashlib
from flask import request, jsonify

def validate_iot_device_command(device_secret):
    incoming_cmd = request.json.get('command')
    incoming_sig = request.headers.get('X-Device-Signature')
    expected_sig = hmac.new(device_secret.encode(), incoming_cmd.encode(), hashlib.sha256).hexdigest()
    if hmac.compare_digest(incoming_sig, expected_sig):
        return jsonify({'status': 'authorized', 'execute': True})
    return jsonify({'status': 'unauthorized', 'execute': False}), 403
```
