# YAML Deserialization via yaml.load() with Untrusted Input

Language: Python
Severity: Critical
CWE: CWE-502

## Source
6

## Flow
6-8

## Sink
8

## Vulnerable Code
```python
import yaml
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/iot/device/config', methods=['POST'])
def push_device_cfg():
    raw_payload = request.data.decode('utf-8')
    try:
        dev_cfg = yaml.load(raw_payload)
        device_id = dev_cfg.get('device_id')
        firmware_ver = dev_cfg.get('firmware')
        return jsonify({'status': 'updated', 'device': device_id, 'fw': firmware_ver})
    except Exception as exc:
        return jsonify({'error': str(exc)}), 400
```

## Explanation

The raw HTTP POST body is decoded from bytes to a string on line 6 without any validation or sanitization, then passed directly to yaml.load() on line 8 without specifying a safe Loader. yaml.load() with the default FullLoader (or no Loader in older PyYAML versions) supports Python-specific tags like !!python/object/apply:, enabling arbitrary code execution when deserializing attacker-controlled YAML.

## Remediation

The fix replaces `yaml.load(raw_payload)` with `yaml.safe_load(raw_payload)`, which only deserializes standard YAML types (strings, numbers, lists, dicts) and rejects dangerous Python-specific tags like `!!python/object/apply:`. Additionally, a type check ensures the deserialized result is a dictionary as expected, and the exception handler is narrowed to `yaml.YAMLError` to avoid masking unrelated errors.

## Secure Code
```python
import yaml
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/iot/device/config', methods=['POST'])
def push_device_cfg():
    raw_payload = request.data.decode('utf-8')
    try:
        dev_cfg = yaml.safe_load(raw_payload)
        if not isinstance(dev_cfg, dict):
            return jsonify({'error': 'Invalid configuration format'}), 400
        device_id = dev_cfg.get('device_id')
        firmware_ver = dev_cfg.get('firmware')
        return jsonify({'status': 'updated', 'device': device_id, 'fw': firmware_ver})
    except yaml.YAMLError as exc:
        return jsonify({'error': str(exc)}), 400
```
