# Zip Slip via unsafe zipfile extraction

Language: Python
Severity: Critical
CWE: CWE-22

## Source
6

## Flow
6-7-9

## Sink
9

## Vulnerable Code
```python
import zipfile
import os

def deploy_firmware_package(iot_bundle_path, device_root):
    with zipfile.ZipFile(iot_bundle_path, 'r') as firmware_zip:
        for component in firmware_zip.namelist():
            target_path = os.path.join(device_root, component)
            os.makedirs(os.path.dirname(target_path), exist_ok=True)
            with open(target_path, 'wb') as output:
                output.write(firmware_zip.read(component))
    return f"Firmware deployed to {device_root}"
```

## Explanation

The code extracts ZIP file entries without validating the component path, allowing path traversal via '../' sequences. An attacker can craft a malicious ZIP with entries like '../../etc/cron.d/malicious' to write files outside the intended device_root directory, potentially overwriting system files or planting malicious code.

## Remediation

The fix resolves the target path using os.path.realpath() and then validates that the resolved path starts with the canonical device_root directory prefix. If any ZIP entry attempts to traverse outside the intended directory via '../' sequences, the function raises a ValueError and aborts extraction.

## Secure Code
```python
import zipfile
import os

def deploy_firmware_package(iot_bundle_path, device_root):
    device_root = os.path.realpath(device_root)
    with zipfile.ZipFile(iot_bundle_path, 'r') as firmware_zip:
        for component in firmware_zip.namelist():
            target_path = os.path.realpath(os.path.join(device_root, component))
            if not target_path.startswith(device_root + os.sep) and target_path != device_root:
                raise ValueError(f"Illegal path in firmware package: {component}")
            if component.endswith('/'):
                os.makedirs(target_path, exist_ok=True)
            else:
                os.makedirs(os.path.dirname(target_path), exist_ok=True)
                with open(target_path, 'wb') as output:
                    output.write(firmware_zip.read(component))
    return f"Firmware deployed to {device_root}"
```
