{"title":"Zip Slip via unsafe zipfile extraction","language":"Python","severity":"Critical","cwe":"CWE-22","source_lines":[6],"flow_lines":[6,7,9],"sink_lines":[9],"vulnerable_code":"import zipfile\nimport os\n\ndef deploy_firmware_package(iot_bundle_path, device_root):\n    with zipfile.ZipFile(iot_bundle_path, 'r') as firmware_zip:\n        for component in firmware_zip.namelist():\n            target_path = os.path.join(device_root, component)\n            os.makedirs(os.path.dirname(target_path), exist_ok=True)\n            with open(target_path, 'wb') as output:\n                output.write(firmware_zip.read(component))\n    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":"import zipfile\nimport os\n\ndef deploy_firmware_package(iot_bundle_path, device_root):\n    device_root = os.path.realpath(device_root)\n    with zipfile.ZipFile(iot_bundle_path, 'r') as firmware_zip:\n        for component in firmware_zip.namelist():\n            target_path = os.path.realpath(os.path.join(device_root, component))\n            if not target_path.startswith(device_root + os.sep) and target_path != device_root:\n                raise ValueError(f\"Illegal path in firmware package: {component}\")\n            if component.endswith('/'):\n                os.makedirs(target_path, exist_ok=True)\n            else:\n                os.makedirs(os.path.dirname(target_path), exist_ok=True)\n                with open(target_path, 'wb') as output:\n                    output.write(firmware_zip.read(component))\n    return f\"Firmware deployed to {device_root}\""}