欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

防止 XML外部实体注入

程序员文章站 2022-06-21 21:14:56
...
方式一

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 这是优先选择. 如果不允许DTDs (doctypes) ,几乎可以阻止所有的XML实体攻击
String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
dbf.setFeature(FEATURE, true);

FEATURE = "http://xml.org/sax/features/external-general-entities";
dbf.setFeature(FEATURE, false);

FEATURE = "http://xml.org/sax/features/external-parameter-entities";
dbf.setFeature(FEATURE, false);

FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
dbf.setFeature(FEATURE, false);

dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
org.w3c.dom.Document documentW3c = dbf.newDocumentBuilder().parse(tempFile);

方式二

JAXBContext context = JAXBContext.newInstance(klass);

XMLInputFactory xif = XMLInputFactory.newFactory();
xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
xif.setProperty(XMLInputFactory.SUPPORT_DTD, true);
XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));

Unmarshaller unmarshaller = context.createUnmarshaller();
return unmarshaller.unmarshal(xsr);