尝试了以下代码来验证输入 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
这是我们用于在 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