# XML External Entity (XXE) Injection via lxml Entity Resolution

Language: Python
Severity: Critical
CWE: CWE-611

## Source
4

## Flow
4-5-6

## Sink
6

## Vulnerable Code
```python
from lxml import etree
import requests

def process_iot_device_config(config_xml_url):
    response = requests.get(config_xml_url)
    parser = etree.XMLParser(resolve_entities=True, no_network=False)
    device_config = etree.fromstring(response.content, parser)
    device_id = device_config.find('.//deviceID').text
    firmware_ver = device_config.find('.//firmware').text
    telemetry_endpoint = device_config.find('.//telemetryURL').text
    return {'id': device_id, 'firmware': firmware_ver, 'endpoint': telemetry_endpoint}
```

## Explanation

The code creates an XMLParser with resolve_entities=True and no_network=False, then parses untrusted XML content from a remote URL. This configuration allows XXE attacks where malicious XML can define external entities to read local files, perform SSRF attacks, or cause denial of service through entity expansion attacks.

## Remediation

The fix disables external entity resolution by setting resolve_entities=False, blocks network access during parsing with no_network=True, and disables DTD loading and validation with dtd_validation=False and load_dtd=False. This prevents attackers from injecting malicious external entities that could read local files, perform SSRF attacks, or cause denial of service.

## Secure Code
```python
from lxml import etree
import requests

def process_iot_device_config(config_xml_url):
    response = requests.get(config_xml_url)
    parser = etree.XMLParser(resolve_entities=False, no_network=True, dtd_validation=False, load_dtd=False)
    device_config = etree.fromstring(response.content, parser)
    device_id = device_config.find('.//deviceID').text
    firmware_ver = device_config.find('.//firmware').text
    telemetry_endpoint = device_config.find('.//telemetryURL').text
    return {'id': device_id, 'firmware': firmware_ver, 'endpoint': telemetry_endpoint}
```
