# Timing Attack via Non-Constant-Time Secret Comparison

Language: Python
Severity: High
CWE: CWE-208

## Source
8

## Flow
7-8

## Sink
8

## Vulnerable Code
```python
import hmac
import hashlib

def verify_iot_device_signature(device_id, payload, received_sig):
    master_key = b"IoT_Master_Secret_2024_XK9P"
    device_secret = hashlib.sha256(master_key + device_id.encode()).digest()
    expected_sig = hmac.new(device_secret, payload.encode(), hashlib.sha256).hexdigest()
    if received_sig == expected_sig:
        return {"authenticated": True, "device": device_id}
    return {"authenticated": False, "error": "Invalid signature"}
```

## Explanation

The code uses the non-constant-time equality operator (==) to compare cryptographic signatures on line 8. This allows timing attacks where an attacker can measure response times to determine correct signature bytes sequentially, eventually reconstructing a valid signature without knowing the secret key.

## Remediation

The fix replaces the non-constant-time string equality operator (==) with hmac.compare_digest(), which performs a constant-time comparison of two strings. This prevents timing attacks because the comparison always takes the same amount of time regardless of how many bytes match, making it impossible for an attacker to deduce the expected signature by measuring response times.

## Secure Code
```python
import hmac
import hashlib

def verify_iot_device_signature(device_id, payload, received_sig):
    master_key = b"IoT_Master_Secret_2024_XK9P"
    device_secret = hashlib.sha256(master_key + device_id.encode()).digest()
    expected_sig = hmac.new(device_secret, payload.encode(), hashlib.sha256).hexdigest()
    if hmac.compare_digest(received_sig, expected_sig):
        return {"authenticated": True, "device": device_id}
    return {"authenticated": False, "error": "Invalid signature"}
```
