# Insecure HMAC Comparison via == Timing Leak

Language: Python
Severity: High
CWE: CWE-208

## Source
6

## Flow
6-8

## Sink
8

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

def validate_iot_device_signature(device_id, payload, shared_secret):
    expected_sig = hmac.new(shared_secret.encode(), f"{device_id}:{payload}".encode(), hashlib.sha256).hexdigest()
    received_sig = request.headers.get('X-Device-Signature', '')
    if received_sig == expected_sig:
        return jsonify({"status": "authorized", "device_id": device_id})
    return jsonify({"status": "unauthorized"}), 403
```

## Explanation

The code uses a direct string comparison (==) to validate HMAC signatures instead of a constant-time comparison function like hmac.compare_digest(). This creates a timing side-channel vulnerability where attackers can perform timing attacks to gradually discover the correct signature byte-by-byte, as the comparison fails faster when earlier bytes do not match.

## Remediation

The fix replaces the direct string comparison operator (==) with hmac.compare_digest(), which performs a constant-time comparison. This eliminates the timing side-channel by ensuring the comparison takes the same amount of time regardless of how many bytes match, preventing attackers from incrementally guessing the correct signature.

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

def validate_iot_device_signature(device_id, payload, shared_secret):
    expected_sig = hmac.new(shared_secret.encode(), f"{device_id}:{payload}".encode(), hashlib.sha256).hexdigest()
    received_sig = request.headers.get('X-Device-Signature', '')
    if hmac.compare_digest(received_sig, expected_sig):
        return jsonify({"status": "authorized", "device_id": device_id})
    return jsonify({"status": "unauthorized"}), 403
```
