{"title":"XML Entity Expansion DoS via Billion Laughs in lxml.etree.parse()","language":"Python","severity":"High","cwe":"CWE-776","source_lines":[5],"flow_lines":[5,6],"sink_lines":[6],"vulnerable_code":"from lxml import etree\nimport io\n\ndef process_iot_device_config(xml_payload):\n    device_stream = io.BytesIO(xml_payload.encode('utf-8'))\n    config_tree = etree.parse(device_stream)\n    root_element = config_tree.getroot()\n    device_id = root_element.find('.//device_identifier').text\n    firmware_ver = root_element.find('.//firmware_version').text\n    telemetry_interval = root_element.find('.//telemetry_rate').text\n    return {'id': device_id, 'firmware': firmware_ver, 'interval': telemetry_interval}","explanation":"The code uses lxml.etree.parse() without disabling entity expansion, making it vulnerable to XML Entity Expansion (Billion Laughs) attacks. An attacker can send malicious XML with recursive entity definitions that exponentially expand in memory, causing DoS through resource exhaustion.","remediation":"The fix creates a secure XMLParser instance with resolve_entities=False to prevent entity expansion, no_network=True to block external network access, and load_dtd=False to prevent loading of DTD definitions. This parser is then passed to etree.parse(), ensuring that Billion Laughs and XXE attacks are neutralized by refusing to process entity definitions.","secure_code":"from lxml import etree\nimport io\n\ndef process_iot_device_config(xml_payload):\n    device_stream = io.BytesIO(xml_payload.encode('utf-8'))\n    parser = etree.XMLParser(resolve_entities=False, no_network=True, dtd_validation=False, load_dtd=False)\n    config_tree = etree.parse(device_stream, parser)\n    root_element = config_tree.getroot()\n    device_id = root_element.find('.//device_identifier').text\n    firmware_ver = root_element.find('.//firmware_version').text\n    telemetry_interval = root_element.find('.//telemetry_rate').text\n    return {'id': device_id, 'firmware': firmware_ver, 'interval': telemetry_interval}"}