# Insecure AES-CBC Encryption via Reused IV

Language: Python
Severity: High
CWE: CWE-329

## Source
4

## Flow
4-9

## Sink
9

## Vulnerable Code
```python
from Crypto.Cipher import AES
import hashlib

STATIC_IV = b'IoTDevice1234567'

def encrypt_sensor_telemetry(device_id, temperature, humidity, pressure):
    telemetry_data = f"{device_id}|{temperature}|{humidity}|{pressure}"
    key = hashlib.sha256(b'iot_master_key_2024').digest()
    cipher = AES.new(key, AES.MODE_CBC, STATIC_IV)
    padded = telemetry_data + ' ' * (16 - len(telemetry_data) % 16)
    encrypted = cipher.encrypt(padded.encode())
    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
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad
import hashlib


def encrypt_sensor_telemetry(device_id, temperature, humidity, pressure):
    telemetry_data = f"{device_id}|{temperature}|{humidity}|{pressure}"
    key = hashlib.sha256(b'iot_master_key_2024').digest()
    iv = get_random_bytes(16)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    padded = pad(telemetry_data.encode(), AES.block_size)
    encrypted = cipher.encrypt(padded)
    return (iv + encrypted).hex()
```
