4

I have a piece of code where there is veracode finding for Improper Restriction of XML External Entity Reference ('XXE') Attack.

Code:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(node);
        transformer.transform(source, result); //CWE ID 611, impacted line.

I used

transformer.setOutputProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformer.setOutputProperty(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

but no luck.

Ab_sin
  • 121
  • 2
  • 10

3 Answers3

4

The issue got resolved with the following code:

        TransformerFactory transformer = TransformerFactory.newInstance();//.newTransformer();
        transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
        transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(node);
        transformer.newTransformer().transform(source, result);
Ab_sin
  • 121
  • 2
  • 10
0

It is advised to put a try-catch block.

try{
            transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
            transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

        } catch (IllegalArgumentException e) {
            //jaxp 1.5 feature not supported
        }
Ab_sin
  • 121
  • 2
  • 10
0

Please note for anyone running the application on JDK5 or older that you will not have these XML Constants available:

transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

Instead you will have to parse to a Document using a secured document builder then use a DOM source in your transformer.

private static void example(String xmlDocument, Result result) throws ParserConfigurationException, IOException, SAXException, TransformerException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String s, String s1) throws SAXException, IOException {
            return new InputSource(new StringReader(""));
        }
    });
    Document doc = db.parse(new InputSource(new StringReader(xmlDocument)));

    DOMSource domSource = new DOMSource(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.transform(domSource, result);
}
Verna Smith
  • 51
  • 1
  • 3