Search code examples
javaxmlowaspesapi

XML Data Injection in the response XML from web service


I need to fix the code below for XML Data Injection.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlFromWebService));
Document doc = db.parse(inStream);   // reported at this line by a code audit tool
doc.getDocumentElement().normalize();

How to fix it? Do anyone have any suggestions.


Solution

  • I'm guessing that this has to do with validation of your XML against a given XSD to prevent XML Data Injection. I would suggest modifying your code like this:

    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware( true);
      factory.setValidating( true);
    
      factory.setProperty( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", 
                           "http://www.w3.org/2001/XMLSchema");
      factory.setProperty( "http://java.sun.com/xml/jaxp/properties/schemaSource", 
                           "file:<your_xsd_file>");
    
      DocumentBuilder builder = factory.newDocumentBuilder();
      InputSource inStream = new InputSource();
      inStream.setCharacterStream(new StringReader(xmlFromWebService));
      Document document = builder.parse(inStream);
    
    } catch ( ParserConfigurationException e) {
      e.printStackTrace();
    } catch ( SAXException e) {
      e.printStackTrace();
    } catch ( IOException e) {
      e.printStackTrace();
    }
    

    I hope you get the hint!