1

我有一个像下面这样的方法。我已将 FEATURE_SECURE_PROCESSING 设置为 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();
    }

当我在下面运行我的单元测试时,我可以列出项目目录下的文件,这意味着它容易受到 XXE 攻击。

    @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);
    }

如何保护 TransformerFactory 免受此类攻击?

4

1 回答 1

1

您正在向 提供 a DOMSourceTransformerFactory因此 DTD 在TransformerFactory存在之前就已处理。您需要在解析 XML 文档时(即创建 DOM 节点时)应用任何控件。

于 2020-08-07T07:19:18.193 回答