解组时无法使用SaxParser执行XML外部实体验证

时间:2018-01-10 06:54:21

标签: java xml unmarshalling saxparser owasp

您好我尝试使用以下代码验证输入XML是否具有外部实体引用,但即使我提供包含外部实体的XML输入,代码也不会抛出任何异常

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

ByteArrayInputStream bais = new ByteArrayInputStream(<XML content here as byte array>);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
SAXParser saxParser = spf.newSAXParser();
XMLReader reader = saxParser.getXMLReader();
Source xmlSource = new SAXSource(reader, new InputSource(bais));
Unmarshaller jaxbUnmarshaller =
JAXBContext.newInstance(XXXX.class).createUnmarshaller();
return (XXXX) jaxbUnmarshaller.unmarshal(xmlSource);

累了直接设置XMLReader中的功能

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    SAXParser saxParser = spf.newSAXParser();
    XMLReader reader = saxParser.getXMLReader();
    reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
    reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Source xmlSource = new SAXSource(reader, new InputSource(bais));


Unmarshaller jaxbUnmarshaller =
    JAXBContext.newInstance(XXXX.class).createUnmarshaller();

return (XXXX) jaxbUnmarshaller.unmarshal(xmlSource);

这两种方法都不起作用,没有抛出异常

如果有任何问题,请告诉我。我正在尝试实施https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#Unmarshaller

1 个答案:

答案 0 :(得分:0)

这是我们用于在ZAP中禁用外部实体处理的代码:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setExpandEntityReferences(false);

https://github.com/zaproxy/zaproxy/blob/develop/src/org/zaproxy/zap/utils/XmlUtils.java