XXE

XXE in Java

Vulnerability: XML External Entities (XXE)

Vulnerable Code:

javaCopy codeDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("input.xml"));

Reason for vulnerability: This code does not disable external entity processing, allowing an attacker to read arbitrary files or perform SSRF attacks.

Fixed Code:

javaCopy codeDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("input.xml"));

Reason for fix: Disabling the DOCTYPE declaration prevents external entities from being processed, mitigating XXE vulnerabilities.


Example 2: Python

Vulnerable Code:

pythonCopy codetree = ET.parse('file.xml')

Reason for vulnerability: External entities are enabled by default, allowing XXE attacks.

Fixed Code:

Reason for fix: Disable external entities to prevent XXE attacks.


Java Example

Vulnerable Code:

Reason for Vulnerability:

This code uses the default configuration of DocumentBuilderFactory, which allows external entity resolution, potentially leading to XXE attacks.

Fixed Code:

Reason for Fix:

The fixed code disables external entity resolution and other potentially dangerous features, preventing XXE attacks.

Java Example

Vulnerable Code:

Reason for Vulnerability:

This code uses the default configuration of SAXReader, which allows external entity resolution, potentially leading to XXE attacks.

Fixed Code:

Reason for Fix:

The fixed code disables external entity resolution and DOCTYPE declarations, preventing XXE attacks when using dom4j.

Python Example

Vulnerable Code:

Reason for Vulnerability:

This code uses the default XMLParser from lxml, which allows entity expansion and external entity resolution, potentially leading to XXE attacks.

Fixed Code:

Reason for Fix:

The fixed code configures the XMLParser to disable entity resolution, network access, and DTD validation, preventing XXE attacks when using lxml.

Last updated