title: XML parser configured does not prevent nor limit external entities resolution. This can expose the parser to an XML External Entities attack
body: <p>We had a security audit on our code, and they mentioned that our code is vulnerable to EXternal Entity (XXE) attack.</p>
  
  <p>Explanation- XML External Entities attacks benefit from an XML feature to build documents dynamically at the time of processing. An XML entity allows inclusion of data dynamically from a given resource. External entities allow an XML document to include data from an external URI. Unless configured to do otherwise, external entities force the XML parser to access the resource specified by the URI, e.g., a file on the local machine or on a remote system. This behavior exposes the application to XML External Entity (XXE) attacks, which can be used to perform denial of service of the local system, gain unauthorized access to files on the local machine, scan remote machines, and perform denial of service of remote systems. The following XML document shows an example of an XXE attack.</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
  &lt;!DOCTYPE foo [
  &lt;!ELEMENT foo ANY &gt;
  &lt;!ENTITY xxe SYSTEM "file:///dev/random" &gt;]&gt;&lt;foo&gt;&amp;xxe;&lt;/foo&gt;
  </code></pre>
  
  <p>This example could crash the server (on a UNIX system), if the XML parser attempts to substitute the entity with the contents of the /dev/random file.</p>
  
  <p>Recommendation- The XML unmarshaller should be configured securely so that it does not allow external entities as part of an incoming XML document. To avoid XXE injection do not use unmarshal methods that process an XML source directly as java.io.File, java.io.Reader or java.io.InputStream. Parse the document with a securely configured parser and use an unmarshal method that takes the secure</p>
  
  <p>parser as the XML source as shown in the following example:</p>
  
  <pre><code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  dbf.setExpandEntityReferences(false);
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document document = db.parse(&lt;XML Source&gt;);
  Model model = (Model) u.unmarshal(document);
  </code></pre>
  
  <p>And written code is below where found the XXE attack-</p>
  
  <pre><code>1- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  2- DocumentBuilder db = dbf.newDocumentBuilder();
  3- InputSource is = new InputSource();
  4- is.setCharacterStream(new StringReader(xml));
  5-
  6- Document doc = db.parse(is);
  7- NodeList nodes = doc.getElementsByTagName(elementsByTagName);
  8-
  9- return nodes;
  </code></pre>
  
  <p>I am getting XXE attack on the line no 6.
  Please help how can I resolve the above issue. Anyone help is appreciated !</p>