# AES-ECB Mode Information Leakage

Language: Python
Severity: Medium
CWE: CWE-327

## Source
11

## Flow
11-12-13-5-6

## Sink
6

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

def secure_iot_telemetry(sensor_readings):
    device_key = b'IoTMaster2024Key'
    cipher = AES.new(device_key, AES.MODE_ECB)
    padded_data = sensor_readings + b' ' * (16 - len(sensor_readings) % 16)
    encrypted_telemetry = cipher.encrypt(padded_data)
    return base64.b64encode(encrypted_telemetry).decode('utf-8')

def transmit_batch_sensors(temp, humidity, pressure):
    payload = f"TEMP:{temp}|HUM:{humidity}|PRES:{pressure}".encode()
    encrypted_payload = secure_iot_telemetry(payload)
    return {"device_id": "sensor_node_47", "data": encrypted_payload}
```

## Explanation

The code uses AES in ECB (Electronic Codebook) mode, which encrypts identical plaintext blocks to identical ciphertext blocks. This allows attackers to detect patterns in sensor data (e.g., repetitive temperature readings) by observing repeated ciphertext blocks, leaking information about the plaintext without decrypting it.

## Remediation

The fix replaces AES-ECB mode with AES-CBC mode, which uses an Initialization Vector (IV) to ensure that identical plaintext blocks produce different ciphertext blocks. A random 16-byte IV is generated for each encryption operation and prepended to the ciphertext so the receiver can extract it for decryption, preventing pattern detection from repeated sensor readings.

## Secure Code
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64

def secure_iot_telemetry(sensor_readings):
    device_key = b'IoTMaster2024Key'
    iv = get_random_bytes(16)
    cipher = AES.new(device_key, AES.MODE_CBC, iv=iv)
    padded_data = sensor_readings + b' ' * (16 - len(sensor_readings) % 16)
    encrypted_telemetry = cipher.encrypt(padded_data)
    return base64.b64encode(iv + encrypted_telemetry).decode('utf-8')

def transmit_batch_sensors(temp, humidity, pressure):
    payload = f"TEMP:{temp}|HUM:{humidity}|PRES:{pressure}".encode()
    encrypted_payload = secure_iot_telemetry(payload)
    return {"device_id": "sensor_node_47", "data": encrypted_payload}
```
