User-provided data, such as URL parameters, POST data payloads, or cookies, are tainted with user-controlled inputs. Therefore, they should always
be considered untrusted.
XML injection occurs when user-controlled input is embedded into XML syntax. In such a scenario, an attacker can abuse the XML syntax and inject
arbitrary XML elements. This can lead to cross-site scripting issues or denial-of-service attacks.
In addition, the application may parse the XML document with a weakly configured XML parser (namely, a parser with external entity support
enabled). In this case, an XML External Entity (XXE) injection would expose the application to sensitive file disclosure or server-side request
forgeries (SSRF).
An attacker can also elevate privileges if the XML data is used for authentication.
Noncompliant Code Example
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String xml = "<node id=\""+req.getParameter("id")+\"></node>";
FileOutputStream fos = new FileOutputStream("output.xml");
fos.write(xml.getBytes(Charset.forName("UTF-8"))); // Noncompliant
}
javax.xml.parsers.DocumentBuilder
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String xml = "<node id=\""+req.getParameter("id")+\"></node>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml))); // Noncompliant
}
Compliant Solution
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String id = req.getParameter("id");
if(id.matches("^[A-Za-z0-9_]+$")) {
String xml = "<node id=\""+id+\"></node>";
FileOutputStream fos = new FileOutputStream("output.xml");
fos.write(xml.getBytes(Charset.forName("UTF-8")));
}
}
javax.xml.parsers.DocumentBuilder
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String xml = "<node></node>;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xml))); // Noncompliant
Element element = (Element) doc.getElementsByTagName("something").item(0);
element.setAttribute("id", req.getParameter("id"));
}
See