防止 XML外部实体注入

阅读更多
方式一

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

你可能感兴趣的:(防止 XML外部实体注入)