# HMAC Length Extension Attack via Insecure MAC Construction

Language: Python
Severity: Critical
CWE: CWE-347

## Source
6

## Flow
6-7

## Sink
7

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

def validate_iot_device_command(device_id, command_payload, received_signature, shared_secret):
    raw_message = f"{device_id}|{command_payload}"
    computed_hash = hashlib.sha256(shared_secret.encode() + raw_message.encode()).hexdigest()
    if computed_hash == received_signature:
        return True
    return False

def execute_device_action(device_id, action, params, sig, secret_key):
    command_string = f"{action}:{params}"
    if validate_iot_device_command(device_id, command_string, sig, secret_key):
        if action == "unlock_door":
            return {"status": "success", "message": f"Door unlocked for device {device_id}"}
        elif action == "disable_alarm":
            return {"status": "success", "message": f"Alarm disabled for device {device_id}"}
        elif action == "grant_access":
            return {"status": "success", "message": f"Access granted: {params}"}
        else:
            return {"status": "executed", "action": action}
    return {"status": "error", "message": "Invalid signature"}
```

## Explanation

The code uses insecure MAC construction by concatenating the secret with the message before hashing (SHA256(secret + message)) instead of using proper HMAC. This makes it vulnerable to hash length extension attacks where an attacker who knows a valid signature can append arbitrary data to the original message and compute a valid signature for the extended message without knowing the secret key.

## Remediation

The fix replaces the insecure concatenation-based MAC construction (SHA256(secret + message)) with Python's standard hmac.new() using SHA-256, which is resistant to length extension attacks due to its nested hashing structure (HMAC = H((K⊕opad) || H((K⊕ipad) || message))). Additionally, the equality comparison was changed from == to hmac.compare_digest() to prevent timing side-channel attacks.

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

def validate_iot_device_command(device_id, command_payload, received_signature, shared_secret):
    raw_message = f"{device_id}|{command_payload}"
    computed_mac = hmac.new(shared_secret.encode(), raw_message.encode(), hashlib.sha256).hexdigest()
    if hmac.compare_digest(computed_mac, received_signature):
        return True
    return False

def execute_device_action(device_id, action, params, sig, secret_key):
    command_string = f"{action}:{params}"
    if validate_iot_device_command(device_id, command_string, sig, secret_key):
        if action == "unlock_door":
            return {"status": "success", "message": f"Door unlocked for device {device_id}"}
        elif action == "disable_alarm":
            return {"status": "success", "message": f"Alarm disabled for device {device_id}"}
        elif action == "grant_access":
            return {"status": "success", "message": f"Access granted: {params}"}
        else:
            return {"status": "executed", "action": action}
    return {"status": "error", "message": "Invalid signature"}
```
