{"title":"XML External Entity (XXE) Injection via lxml etree.parse()","language":"Python","severity":"High","cwe":"CWE-611","source_lines":[4],"flow_lines":[4,5,6,7],"sink_lines":[7],"vulnerable_code":"from lxml import etree\nimport io\n\ndef process_iot_device_telemetry(telemetry_xml_data):\n    parser = etree.XMLParser(resolve_entities=True)\n    telemetry_stream = io.BytesIO(telemetry_xml_data.encode('utf-8'))\n    device_tree = etree.parse(telemetry_stream, parser)\n    root_element = device_tree.getroot()\n    device_id = root_element.find('.//deviceId').text\n    temperature = root_element.find('.//temperature').text\n    humidity = root_element.find('.//humidity').text\n    return {'device': device_id, 'temp': temperature, 'humidity': humidity}","explanation":"The function accepts untrusted XML telemetry data and parses it with resolve_entities=True explicitly enabled, making it vulnerable to XXE attacks. An attacker can inject malicious XML entities to read arbitrary files, perform SSRF attacks, or cause denial of service through billion laughs attacks.","remediation":"The fix disables XML external entity processing by setting resolve_entities=False, no_network=True, dtd_validation=False, and load_dtd=False on the XMLParser. This prevents attackers from injecting malicious entity declarations that could read local files, perform SSRF, or cause denial of service through entity expansion attacks.","secure_code":"from lxml import etree\nimport io\n\ndef process_iot_device_telemetry(telemetry_xml_data):\n    parser = etree.XMLParser(resolve_entities=False, no_network=True, dtd_validation=False, load_dtd=False)\n    telemetry_stream = io.BytesIO(telemetry_xml_data.encode('utf-8'))\n    device_tree = etree.parse(telemetry_stream, parser)\n    root_element = device_tree.getroot()\n    device_id = root_element.find('.//deviceId').text\n    temperature = root_element.find('.//temperature').text\n    humidity = root_element.find('.//humidity').text\n    return {'device': device_id, 'temp': temperature, 'humidity': humidity}"}