12importjavax.xml.parsers.DocumentBuilderFactory;3importjavax.xml.parsers.ParserConfigurationException;// catching unsupported features4DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();5StringFEATURE=null;6try{7// This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented8// Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl9FEATURE="http://apache.org/xml/features/disallow-doctype-decl";10dbf.setFeature(FEATURE,true);1112// If you can't completely disable DTDs, then at least do the following:13// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities14// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities15// JDK7+ - http://xml.org/sax/features/external-general-entities 16FEATURE="http://xml.org/sax/features/external-general-entities";17dbf.setFeature(FEATURE,false);1819// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities20// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities21// JDK7+ - http://xml.org/sax/features/external-parameter-entities 22FEATURE="http://xml.org/sax/features/external-parameter-entities";23dbf.setFeature(FEATURE,false);2425// Disable external DTDs as well26FEATURE="http://apache.org/xml/features/nonvalidating/load-external-dtd";27dbf.setFeature(FEATURE,false);2829// and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"30dbf.setXIncludeAware(false);31dbf.setExpandEntityReferences(false);3233// And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then 34// ensure the entity settings are disabled (as shown above) and beware that SSRF attacks35// (http://cwe.mitre.org/data/definitions/918.html) and denial 36// of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk."3738// remaining parser logic39}catch(ParserConfigurationExceptione){40// This should catch a failed setFeature feature41logger.info("ParserConfigurationException was thrown. The feature '"+42FEATURE+"' is probably not supported by your XML processor.");43}44catch(SAXExceptione){45// On Apache, this should be thrown when disallowing DOCTYPE46logger.warning("A DOCTYPE was passed into the XML document");47}48catch(IOExceptione){49// XXE that points to a file that doesn't exist50logger.error("IOException occurred, XXE may still possible: "+e.getMessage());51}52DocumentBuildersafebuilder=dbf.newDocumentBuilder();53
【.Net】
12XmlDocument doc= new XmlDocument();3doc.XmlResolver = null;//关键代码4......5