TransformerFactory still vulnerable to XXE attacks
Asked Answered
G

1

1

I have a method like below. I've set the FEATURE_SECURE_PROCESSING to true.

    public String getString(org.w3c.dom.Node node) throws TransformerException {
        StringWriter writer = new StringWriter();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(node), new StreamResult(writer));

        return writer.toString();
    }

When I run my unit test below, I can list the files under project directory, meaning it is vulnerable to XXE attacks.

    @Test
    public void test() throws Exception {
        String dir = new File("").getAbsolutePath();
        String xml =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "<!DOCTYPE test[" +
                        "<!ENTITY problemEntity SYSTEM \"" + dir + "\">" +
                        "]>" +
                        "<Response>" +
                        "&problemEntity;" +
                        "</Response>";

        org.w3c.dom.Element node = DocumentBuilderFactory
                .newInstance()
                .newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()))
                .getDocumentElement();

        String name = getString(node);
        System.out.println(name);
    }

How can I secure the TransformerFactory to such attacks?

Guan answered 6/8, 2020 at 22:19 Comment(0)
J
2

You're supplying a DOMSource to the TransformerFactory, so the DTD was processed before the TransformerFactory came into existence. You need to apply any controls at the point the XML document is parsed, which is when the DOM Node gets created.

Jahveh answered 7/8, 2020 at 7:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.