{"title":"Insecure AES-CBC Encryption via Reused IV","language":"Python","severity":"High","cwe":"CWE-329","source_lines":[4],"flow_lines":[4,9],"sink_lines":[9],"vulnerable_code":"from Crypto.Cipher import AES\nimport hashlib\n\nSTATIC_IV = b'IoTDevice1234567'\n\ndef encrypt_sensor_telemetry(device_id, temperature, humidity, pressure):\n    telemetry_data = f\"{device_id}|{temperature}|{humidity}|{pressure}\"\n    key = hashlib.sha256(b'iot_master_key_2024').digest()\n    cipher = AES.new(key, AES.MODE_CBC, STATIC_IV)\n    padded = telemetry_data + ' ' * (16 - len(telemetry_data) % 16)\n    encrypted = cipher.encrypt(padded.encode())\n    return encrypted.hex()","explanation":"The code uses a static, hardcoded IV (STATIC_IV = b'IoTDevice1234567') for AES-CBC encryption across all telemetry transmissions. Reusing the same IV with the same key allows attackers to detect patterns in encrypted data, perform plaintext recovery through chosen-plaintext attacks, and potentially decrypt all historical sensor data by analyzing ciphertext patterns across multiple transmissions.","remediation":"The fix replaces the static hardcoded IV with a cryptographically secure random IV generated fresh for each encryption operation using get_random_bytes(16). The random IV is prepended to the ciphertext so the receiver can extract it for decryption. Additionally, the insecure manual space-padding was replaced with proper PKCS7 padding via Crypto.Util.Padding.pad().","secure_code":"from Crypto.Cipher import AES\nfrom Crypto.Random import get_random_bytes\nfrom Crypto.Util.Padding import pad\nimport hashlib\n\n\ndef encrypt_sensor_telemetry(device_id, temperature, humidity, pressure):\n    telemetry_data = f\"{device_id}|{temperature}|{humidity}|{pressure}\"\n    key = hashlib.sha256(b'iot_master_key_2024').digest()\n    iv = get_random_bytes(16)\n    cipher = AES.new(key, AES.MODE_CBC, iv)\n    padded = pad(telemetry_data.encode(), AES.block_size)\n    encrypted = cipher.encrypt(padded)\n    return (iv + encrypted).hex()"}