# Unsafe YAML Deserialization via yaml.load() with Loader

Language: Python
Severity: Critical
CWE: CWE-502

## Source
8

## Flow
8-9

## Sink
9

## Vulnerable Code
```python
import yaml
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/iot/device/provision', methods=['POST'])
def provision_iot_device():
    device_manifest = request.data.decode('utf-8')
    parsed_config = yaml.load(device_manifest, Loader=yaml.Loader)
    device_id = parsed_config.get('device_id', 'unknown')
    firmware_ver = parsed_config.get('firmware_version', '1.0.0')
    security_profile = parsed_config.get('security_profile', {})
    print(f"Provisioning device {device_id} with firmware {firmware_ver}")
    return jsonify({"status": "provisioned", "device_id": device_id, "profile": security_profile})
```

## Explanation

The application uses yaml.load() with yaml.Loader to deserialize untrusted YAML data from user requests without validation. This allows attackers to execute arbitrary Python code through malicious YAML payloads containing Python object constructor tags, leading to Remote Code Execution (RCE).

## Remediation

The fix replaces yaml.load() with yaml.Loader with yaml.safe_load(), which only deserializes standard YAML types (strings, numbers, lists, dicts) and refuses to construct arbitrary Python objects. Additionally, a type check ensures the parsed result is a dictionary before accessing fields, preventing unexpected behavior from non-mapping YAML inputs.

## Secure Code
```python
import yaml
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/iot/device/provision', methods=['POST'])
def provision_iot_device():
    device_manifest = request.data.decode('utf-8')
    parsed_config = yaml.safe_load(device_manifest)
    if not isinstance(parsed_config, dict):
        return jsonify({"error": "Invalid manifest format"}), 400
    device_id = parsed_config.get('device_id', 'unknown')
    firmware_ver = parsed_config.get('firmware_version', '1.0.0')
    security_profile = parsed_config.get('security_profile', {})
    print(f"Provisioning device {device_id} with firmware {firmware_ver}")
    return jsonify({"status": "provisioned", "device_id": device_id, "profile": security_profile})
```
