# YAML Deserialization Remote Code Execution

Language: Python
Severity: Critical
CWE: CWE-502

## Source
6

## Flow
6-7

## Sink
7

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

## Explanation

The raw HTTP request body is decoded on line 6 and passed directly to yaml.load() on line 7 without specifying a safe Loader argument. yaml.load() with no Loader (or with the default FullLoader/UnsafeLoader) can deserialize arbitrary Python objects embedded in the YAML payload, enabling remote code execution. An attacker can craft a malicious YAML payload using Python-specific tags to execute OS commands on the server.

## Remediation

The fix replaces `yaml.load(raw_payload)` with `yaml.safe_load(raw_payload)`, which uses the SafeLoader that only deserializes standard YAML types (strings, numbers, lists, dicts) and refuses to instantiate arbitrary Python objects. An additional type check ensures the parsed result is a dictionary, preventing unexpected input shapes from propagating further.

## Secure Code
```python
import yaml
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/iot/device/config', methods=['POST'])
def sync_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: expected a YAML mapping'}), 400
        device_id = dev_cfg.get('device_id', 'unknown')
        thresholds = dev_cfg.get('thresholds', {})
        return jsonify({'status': 'synced', 'device': device_id, 'cfg': thresholds})
    except Exception as exc:
        return jsonify({'error': str(exc)}), 400
```
