{"title":"YAML Deserialization Remote Code Execution","language":"Python","severity":"Critical","cwe":"CWE-502","source_lines":[6],"flow_lines":[6,7,8],"sink_lines":[8],"vulnerable_code":"import yaml\nfrom flask import Flask, request, jsonify\napp = Flask(__name__)\n@app.route('/api/iot/device/config', methods=['POST'])\ndef push_device_config():\n    raw_payload = request.data.decode('utf-8')\n    try:\n        device_cfg = yaml.load(raw_payload)\n        dev_id = device_cfg.get('device_id', 'unknown')\n        threshold = device_cfg.get('threshold', 75)\n        return jsonify({'status': 'applied', 'device': dev_id, 'threshold': threshold})\n    except Exception as exc:\n        return jsonify({'error': str(exc)}), 400","explanation":"The raw HTTP request body is decoded from untrusted user input on line 6 and passed directly to yaml.load() on line 8 without specifying a safe Loader argument. yaml.load() with no Loader (or with the default FullLoader/UnsafeLoader) can deserialize arbitrary Python objects via YAML tags like !!python/object/apply:os.system, enabling remote code execution on the server.","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 refuses to instantiate arbitrary Python objects from YAML tags like `!!python/object/apply`. Additionally, a type check ensures the parsed result is a dictionary as expected, and the exception handler is narrowed to `yaml.YAMLError` to avoid masking unrelated errors.","secure_code":"import yaml\nfrom flask import Flask, request, jsonify\napp = Flask(__name__)\n@app.route('/api/iot/device/config', methods=['POST'])\ndef push_device_config():\n    raw_payload = request.data.decode('utf-8')\n    try:\n        device_cfg = yaml.safe_load(raw_payload)\n        if not isinstance(device_cfg, dict):\n            return jsonify({'error': 'Invalid configuration format: expected a YAML mapping'}), 400\n        dev_id = device_cfg.get('device_id', 'unknown')\n        threshold = device_cfg.get('threshold', 75)\n        return jsonify({'status': 'applied', 'device': dev_id, 'threshold': threshold})\n    except yaml.YAMLError as exc:\n        return jsonify({'error': str(exc)}), 400"}