{"title":"XML External Entity (XXE) via xml.dom.minidom.parse on Untrusted XML","language":"Python","severity":"High","cwe":"CWE-611","source_lines":[1],"flow_lines":[1,3,4,5],"sink_lines":[5],"vulnerable_code":"from xml.dom import minidom\nimport os\n\ndef process_iot_device_telemetry(telemetry_xml_data):\n    temp_file = f\"/tmp/telemetry_{os.getpid()}.xml\"\n    with open(temp_file, 'w') as f:\n        f.write(telemetry_xml_data)\n    parsed_doc = minidom.parse(temp_file)\n    device_id = parsed_doc.getElementsByTagName('deviceId')[0].firstChild.data\n    temperature = parsed_doc.getElementsByTagName('temp')[0].firstChild.data\n    humidity = parsed_doc.getElementsByTagName('humidity')[0].firstChild.data\n    os.remove(temp_file)\n    return {'device': device_id, 'temp': temperature, 'humidity': humidity}","explanation":"The function accepts untrusted XML telemetry data as input (telemetry_xml_data parameter) and parses it using xml.dom.minidom.parse() without disabling external entity processing. This allows an attacker to inject malicious XML with external entity references that can read local files, perform SSRF attacks, or cause denial of service.","remediation":"The fix replaces the vulnerable xml.dom.minidom.parse() with defusedxml.minidom.parseString(), which automatically disables external entity processing, DTD retrieval, and other dangerous XML features. Additionally, the unnecessary temporary file creation pattern was removed by parsing the XML string directly, eliminating both the XXE vulnerability and potential file system race conditions.","secure_code":"from defusedxml.minidom import parseString\nimport os\n\ndef process_iot_device_telemetry(telemetry_xml_data):\n    parsed_doc = parseString(telemetry_xml_data)\n    device_id = parsed_doc.getElementsByTagName('deviceId')[0].firstChild.data\n    temperature = parsed_doc.getElementsByTagName('temp')[0].firstChild.data\n    humidity = parsed_doc.getElementsByTagName('humidity')[0].firstChild.data\n    return {'device': device_id, 'temp': temperature, 'humidity': humidity}"}