{"title":"HMAC Verification Bypass via Truncated Tag Comparison","language":"Python","severity":"High","cwe":"CWE-347","source_lines":[6],"flow_lines":[6,7],"sink_lines":[7],"vulnerable_code":"import hmac\nimport hashlib\n\ndef validate_iot_device_command(device_id, command_payload, received_signature):\n    secret_key = get_device_secret(device_id)\n    expected_sig = hmac.new(secret_key.encode(), command_payload.encode(), hashlib.sha256).hexdigest()\n    if expected_sig[:16] == received_signature[:16]:\n        execute_device_action(device_id, command_payload)\n        return {\"status\": \"success\", \"message\": \"Command executed\"}\n    return {\"status\": \"error\", \"message\": \"Invalid signature\"}\n\ndef get_device_secret(dev_id):\n    return f\"device_secret_{dev_id}\"\n\ndef execute_device_action(dev_id, payload):\n    print(f\"Executing {payload} on device {dev_id}\")","explanation":"The code compares only the first 16 characters (64 bits) of the HMAC-SHA256 signature instead of the full signature. This drastically reduces the cryptographic strength from 2^256 to 2^64 possibilities, making it feasible for attackers to brute-force valid signatures and bypass authentication to execute unauthorized IoT device commands such as unlocking doors, manipulating thermostats, or hijacking cameras.","remediation":"The fix replaces the truncated 16-character comparison with hmac.compare_digest() which compares the full HMAC signature in constant time. This restores the full 256-bit cryptographic strength of HMAC-SHA256 and also prevents timing side-channel attacks that could leak information about the expected signature.","secure_code":"import hmac\nimport hashlib\n\ndef validate_iot_device_command(device_id, command_payload, received_signature):\n    secret_key = get_device_secret(device_id)\n    expected_sig = hmac.new(secret_key.encode(), command_payload.encode(), hashlib.sha256).hexdigest()\n    if hmac.compare_digest(expected_sig, received_signature):\n        execute_device_action(device_id, command_payload)\n        return {\"status\": \"success\", \"message\": \"Command executed\"}\n    return {\"status\": \"error\", \"message\": \"Invalid signature\"}\n\ndef get_device_secret(dev_id):\n    return f\"device_secret_{dev_id}\"\n\ndef execute_device_action(dev_id, payload):\n    print(f\"Executing {payload} on device {dev_id}\")"}