0% found this document useful (0 votes)
146 views

XML External Entity Prevention Cheatsheet

XML External Entity Prevention Cheatsheet

Uploaded by

Rizki Kurniawan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
146 views

XML External Entity Prevention Cheatsheet

XML External Entity Prevention Cheatsheet

Uploaded by

Rizki Kurniawan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series XML External Entity Prevention Cheat Sheet Introduction XML eXternal Entity injection (XXE), which is now part of the OWASP Top 10 via the point Ad, is a type of attack against an application that parses XML input. XXE issue is referenced under the ID 611 inthe Common Weakness Enumeration referential. This attack occurs when untrusted XML input containing a reference to an external entity is processed by a weakly configured XML parser. This attack may lead tothe disclosure of confidential data, denial of service, Server Side Request Forgery (SRF), port scanning from the perspective of the machine where the parser is located, and other system impacts. The following guide provides concise information o prevent this vulnerability. For more information on XXE, please visit XML. External Entity (XE). General Guidance The safest way to prevent XXE is always to disable DTDs (Extemal Entities) completely. Depending on the parser, the method should be similar to the following factory .setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); Disabling DTDs also makes the parser secure against denial of services (D0S) attacks such as Billion Laughs. Ifit is not possible to disable DTDs completely then extemal entities and extemal document type declarations must be disabledin the way thats specific o each parser. Detailed XXE Prevention guidance for a number of languages and commonly used XMIL parsers in those languages is provided below. C/CH libxml2 Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html ane 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series ‘The Enum xmiParserOption should not have the follwing options defined: + 01L_PARSE_NOENT Expands entities and substitutes them with replacement text ‘* XML_PARSE_DTOLOAD : Load the extemal DTD. Note: Per: According o this post, starting with litxml2 version 2.9, XXE has been disabled by default as committed by the following patch, Search for the usage of the following APIs to ensure there isno xML_PARSE_NOENT and XML_PARSE_DTDLOAD defined in the parameters: © xmictxtReaddoc © emlctxtReadrd © xmlctxtReadFile * xmictxtReadto © xmlctxtReadMenory ¢ xmlctxtUseoptions ¢ xmlParseInNodeContext © xmlReaddoc © xmlReadré © emlReadFile © xmlReadro © xmlReadMenory libxerces-c Use of XercesdoNParser do this to prevent XXE: XercesDOMParser “parser = new XercesbOMParser; parser->setCreateEntityReferenceNodes(true); parser->setDisableDefaultEntityResolution( true) ; Use of SAXParset, do this to prevent XXE: SAXParser* parser = new SAXParser; parser->setDisableDefaultEnttyResolution( true) ; Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html 218 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series Use of SAX2XMLReader, do this to prevent XXE: SAX2XMLReader* reader = XMLReaderFactory::createXMLReader(); parser->setFeature(XMLUni : :fgXercesDisableDefaultEntityResolution, true); Java Java applications using XMIL libraries are particularly vulnerable to XXE because the default settings for most Java XML parsersis to have XXE enabled. To use these parsers safely, youhave to explicitly disable XX€ in the parser you use. The following describes how to disable XXE inthe most commonly used XML parsers for Java. JAXP DocumentBuilderFactory, SAXParserFactory and DOM4J DocunentButlderFactory, SAXParserFactory and 0O"4) xML Parsers can be configured using ‘the same techniques to protect them against XXE. Only the DocunentauilderFactory example is presented here. The JAXP DocunentBuilderFactory setFeature method allows a developer to control wrich implementation- specific XML processor features are enabled or disabled. ‘The features can either be set on the factory or the underlying xNLReader setFeature method, Each XML processor implementation has its own features that govem haw DTDs and extemal entities are processed, For a syntaxhighlighted exemple code snippet using saxParserFactory ,Jook here, import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; // catching unsupported features DocunentBuilderFactory dbf = DocumentBuilderFactory .newInstance() ; String FEATURE = null; try ¢ // This is the PRIVARY defense. If DTDs (doctypes) are disallowed, almost all // XML entity attacks are prevented // Xerces 2 only ~ http://xerces.apache.org/xerces2-j/features.htnl#disallow- doctype-dec. FEATURE = "http://apache.org/xml/features/¢isallow-doctype-decl” ; dbf .setFeature(FEATURE, true); // If you can't completely disable [TDs, then at least do the following: Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html ae 9123122, 8:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series I Xerces 1 ~ http://xerces.apache .org/xerces-j/features. html#external- general-entities I Xerces 2 ~ http://xerces.apache .org/xerces2-j/features-html#external- general-entities 11 JOK7+ ~ http: //mil.org/sax/features/extemal-general-entities //This feature has to be used together with the following one, otherwise it will not protect you from XXE for sure FEATURE = “http://xnl org/sax/features/external-general-entities' dbf .setFeature(FEATURE, false); I1 Xerces 1 ~ http://xerces.apache .org/xerces~j/features.html#external- paraneter-entities J/ Xerces 2 - http://xerces.apache .org/xerces2~j/features.html#external- paraneter-entities 11 JDK7+ ~ http://xml.org/sax/features/external-paraneter-entities i [This feature has to be used together with the previous one, otherwise it will not protect you fro XXE for sure FEATURE = “http://xnl.org/sax/features/external-paraneter-entities" ; dbf .setFeature(FEATURE, false); J Disable external DTDs as well FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dte" ; dbf .setFeature(FEATURE, false); // and these as well, per Timothy Horgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" ‘dbf .setXIncludesware (false); dbf .setExpandEntityReferences( false) ; // And, per Timothy Morgan: "If for sone reason support for inline DOCTYPES are a requirement, then // ensure the entity settings are disabled (as shown above) and beware that SSRF attacks // (http://cve.mitre.org/data/definitions/918.html) and denial // of service attacks (such as billion laughs or decompression bonbs via "jar:") are a risk." // remaining parser logic } catch (ParserConfigurationéxception e) ( // This should catch a failed setFeature feature Logger «info(“ParserConfigurationException was thrown. The feature FEATURE +" is probably not supported by your XML processor."); } catch (SAXException e) { // On Apache, this should be thrown when disallowing DOCTYPE logger.warning("A DOCTYPE was passed into the XML document"); } catch (Toexception «) { ‘// XXE that points to a file that doesn't exist logger.error(*T0Fxception occurred, XXE may still possible: e.getHessage()); Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html ane. 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series } // Load XML file or stream using @ XXE agnostic configured parser... DocumentBuilder safebuilder = dbf.nenDocunentBuilder () ; Xerces 1 Features: + Donot includeextemal entities by setting this featureto false. # Donot include parameter entities ty setting this feature to false. + Donot includeextema DTDsby setting this feature to false Xerces 2 Features: «Disallow an inline DTD by setting this featureto true. * Donot includeextema entities by setting this featureto false. * Donot include parameter entities by setting this feature to false. + Donot includeextema DTDsby setting this featureto false. Note: The above defenses require Java7 Update 67, Java 8 update 20, or above, because the above countermeasures for DocunentBuilderFactory and SAXParserFactory ate broken in earlier Java versions, per: CVE-2014-6517. XMLInputFactory (a StAX parser) ‘SYAX parsers such as X™"LinputFactory allaw Various properties and features tobe set. To protect a Java xiLInputFactory fom XXE, dothis: // This disables DTDs entirely for that factory xmLinputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false) ; // This causes XMLStreanException to be thrown if extemal DTDs are accessed. xmlInputFactory.setProperty(xMLConstants .ACOESS.EXTERNAL.DTD, ""); // disable external entities xmlInputFactory.setProperty("javex.xml.stream.isSupportingExternalEntities", false); Oracle DOM Parser Follow Oracle recommendation e.g: // Extend oracle. xmil.parser.v2.XMLParser DoMParser donParser = new DOMParser(); Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html site 9123/22, 8:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series /1 Do not expand entity references domParser.setAttribute(DONParser.EXPANDENTITYREF, false); 1/ dtd0bj is an instance of oracle.ml.parser.v2.D1D domParser.setAttribute(DOMParser.DTDCB.ECT, dtd0bj) ; // Do rot allow more than 11 levels of entity expansion domParser .setAt tribute (DOMParser.ENTITY_EXPANSION_DEPTH, 12); TransformerFactory Toprotect a javax.xml.transform.TransformerFactory from XXE, do this: TransformerFactory tf = TransformerFactory .newInstance() ; ‘tf .setAttribute(XMLConstants. ACCESS_EXTERNALDTD, "*) ; ‘tf -setAttribute(XML Constants. ACCESS_EXTERNAL_STYLESHEET, Validator To protect javax.xnl.validation. validator from XXE, do this: SchenaFactory factory = ‘SchenaFactory .newInstance( "http: //www.w3 .org/2801/XHLSchema" ); Schema schema = factory.nenSchema() ; Validator validator = schene.newValidator(); validator .setProperty(XMLConstants .ACCESS_EXTERNALDTD, ""); validator .setProperty(XMLConstant's .ACCESS_EXTERNAL_SCHEMA, SchemaFactory Toprotecta javax.xml.validation.SchenaFactory from XXE, dothis: SchemaFactory factory = ‘SchenaFactory .newInstance( "http: //www.w3 .org/2801 /XHLSchema" ); factory. setProperty(xMLConstants .AOCESSEXTERNALDTD, ""); factory. setProperty(xMLConstants . AOCESS_EXTERNAL_SCHEMA, Schema schema = factory.nevSchema (Source); SAXTransformerFactory Toprotecta javax.xml.transform.sox.SaxTransfornerfactory from XXE, do this: Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html ene 9123/22, 8:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series ‘SaxTransformerFactory sf = SAXTransfornerFactory newlnstance(); ‘9f setAttribute(XML Constants. AOCESS_EXTERNAL_DTD, ""); ‘sf -setAttribute(XML Constants. ACCESS_EXTERNAL_STYLESHEET, ‘sf .newXMLFilter(Source) ; Note: Use of the following x"LConstants requires JAXP 1.5, which was added to Java in 7u40 and Java 8: © jevax.xml .xMLCons tants .ACCESS_EXTERNAL_DTD © jevax.xml .xMLConstents .ACCESS_EXTERNAL_ SCHEMA © javax.xml.xMLConstants ACCESS_EXTERNAL_STYLESHEET XMLReader To protect a Java ory.xnl.sax.XMLReader from XXE, do this: XMLReader reader = XMLReaderFactory.createdM.Reader() reader .setFeature("http://apache.org/x@l/features/disallow-doctype-decl", tru // This may not be strictly required as DTDs shouldn't be allowed at all, per Previous line. reader .setFeature(“http://apache.org/x@l/features/nonvalidating/load-external- avd", false); reader .setFeature(“http: //xml.org/sax/features/external-general-entities", false); reader .setFeature(http: //xml.org/sax/features/external-paraneter-entities", false); ‘SAXReader To protect a Java org.don4j..io.SAxReader from XXE, do this: saxReader .setFeature( “http: //epache.org/xnl/features/disallon-doctype-decl”, true); saxReader .setFeature( “http: //xml.org/sax/features/external-general-entities" false); saxReader .setFeature( “http: //xnl.org/sax/festures/external-parameter-entities", false); Based on testing, if you are missing one of these, you can still be vulnerable to an XXE attack. ‘SAXBuilder To protect a Java org. jdon2. input .SAXBuillder ftom XXE, dothis: Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html m8. 9123/22, 8:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series SaxBuilder builder = new SAXBUAI¢er() ; builder .setFeature( "http:/ /epache.org/xnl / features /disallow-doctype-decl”, true) ; builder.setFeature(“http://aml.org/sax/features/external-general-entities", false); builder. setFeature(“http://xml.org/sax/features/external-paraneter-entities" false); builder .setExpandéntities( false) ; Document doc = builder .build(new File(fileName)); No-op EntityResolver For APIs that take an EntityResolver , YoU can neutalize an XMIL parser's ability to resohe entities by supplying @ no-op implementation: public final class NoOpintityResolver inplenents EntityResolver { public InputSource resolvetntity(String publicId, String systentd) { return new InputSource(new StringReader("*)); y y Tee xmiReader .setEntityResolver (new NoOpEntityResolver()) ; documentBuilder .setEntityResolver (new NoOpEntityResolver()); ormore simply: EntityResolver noop = (publicId, systemId) -> new InputSource(new StringReader(*")); xmlReader .setentityResolver(noop) ; documentBuilder .setEntityResolver (noop) ; JAXB Unmarshaller Sincea javax.xml.bind.Unmarshaller parses XML anddoes nct support any flags for disabling XXE, it's imperative to parse the untrusted XML through a configurable secure parser frst, generate a source object as a result, and pass the source object tothe Unmarshaller. For example: /[Pisable XE ‘SAXParserFactory spf = SAXParserFactory.newinstance() spf .setFeature("http://xnl.org/sex/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); 7/00 umarshall operation Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html ane 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series Source xmlSource = new SAXSource(spf.nenSAxParser() .getXMLReader(), new InputSource(new StringReader(xml))); JaxBContext jc = JAXBContext ,newInstance (Ob ject .class) ; Unmarshaller um = jc.createunmarshaller(); un.unmarshal(xm1Source) ; XPathExpression A jovax. xn xpeth.XPathexpression can net be configured securely by itself so the untrusted data must be parsed through ancther securable XML parser fist. For example: DocumentBuilderFactory df = DocunentBuilderFactory.newinstance(); df .setAttribute(XMLConstants AOCESS_EXTERNALDTD, ""); df .setAttr ibute(XMLConstantss, AOCESS_EXTERNAL_SCHEMA, DocumentBuilder builder = df .newDocumentBuilder () ; String result = new xPathExpression() .evaluate( builder .parse( new ByteArrayInputStream(xml .getBytes())) ); java.beans.XMLDecoder ‘The readObject() method in this class is fundamentally unsafe. Not only is the XML it parses subject to XXE, but the method can be used to construct any Java okject, and execute arbitrary code as described here. And there is no way to make use of this class safe except to trust or properly validate the input, being passed into it. ‘As such, we'd strongly recommend completely avoiding the use of this class and replacing it with a safe or properly configured XML parser as described elsewhere in this cheat sheet. Other XML Parsers ‘There are many third-party libraries that parse XML either directly or through their use of other libraries. Please test and verify their XML parser is secure against XXE by default. If the parser is not secure by default, look for flags supported by the parser to disable all possible external resource inclu ns like the examples given above. If there's no control exposed to the outside, make sure the untrusted content is passed through a secure parser first and then passed to insecure third-party parser similar to how the Unmarshaller is secured. ‘Spring Framework MVC/OXM XXE Vulnerabilities Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html ons 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series For example, some XXE vulnerabilities were found in Spring OXM and Spring MVC. The following versions of the Spring Framework are vulnerable to XXE: + 3.0.0 to 3.2.3 (Spring OXM & Spring MVC) + 4.0.0.M1 (Spring OXM) + 4.0.0.M1-4. M2 (Spring MVC) There were other issues as well that were fixed later, so to fully address these issues, Spring recommends you upgrade to Spring Framework 3.2.8+ or 4.0.2+. For Spring OXM, this is referring to the use of org. springframework.oxm jaxb.Jaxb2Marshaller. Note that the CVE for Spring OXM specifically indicates that 2 XML parsing situations are up to the developer to get right, and 2 are the responsibility of Spring and were fixed to address this CVE, Here's what they say: ‘Two situations developers must handle: + Fora Do™Source, the XML has already been parsed ty user code and that code is responsible for protecting against XXE. © Fora StaxSource , the XMLStreamReader has already been created ty user code and that code is responsible for protecting against XXE. The issue Spring fixed: For SAXSource and StreamSource instances, Spring processed extemal entities by default thereby creating this vulnerability. Here's an example of using a SteamSource that was vulnerable, but is now safe, ifyou are using a fixed version of Spring OXM or Spring MVC: import org.springfranework.oxm.Jaxb2Marshaller ; import org.springframework .oxm. jaxb.Jaxb2Marshaller j Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); // Must cast return Object to whatever type you are umarshalling mmarshaller-urmarshal(new StreenSource (new StringReader(sone_string_containing_XML)); So, per the Spring OXM CVE writeup, the above is new safe. But if you were to use a DOMSource or ‘StAXSource instead, it would be up to you to configure those sources to be safe from XXE. Castor Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html sone 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series Castor is a data binding framework for Java. It allows conversion between Java otjects, XML, and relational tables. The XML features in Castor prior to version 1.3.3 are vulnerable to XXE, and should be upgraded to the latest version. For additional information, check the official XML configuration file NET ‘The follwing, upto date information for XXE injection in NET is ditectly from this web application of unit tests by Dean Fleming. This web application covers all curently supported .NET XML Parsers, and has test cases for each demonstrating when they are safe from XXE injection and When they are not, but tests are onty with injection from file and net direct DTD (used by DoS attacks). For DoSattacks using a direct DTD (such as the Billion laughs attack), a separate testing application from Josh Grossman at Bounce Security has been created to verify that NET >=4.5.2 is safe from these attacks. Previously, this information was based on some older articles which may nct be 100% accurate induding: ‘¢ James Jardine's excellent NET XXE article, ‘# Guidance from Microsoft on how to prevent XE and XML Denial of Service in NET. The following table lists all supported NET XML parsers and their default safety levels. Note tht in .NET Framework 24.52 in all cases if @ DoS attempt is performed, an exception is thrown due to the expanded XML being too many characters. Table explanation: + V=Not Vuherable + X=Vuherable + 2 =Not dear Attack NET XDocument _XmlDictionaryReader_ —XmiDocument —_Xmib Type Framework (Lingo Version XML) External ASQ ov Vv x entity Attacks Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html 18 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series Attack NET XDocument _XmlDictionaryReader_ XmiDocument —_Xmit Type Framework (Lingo Version XML) 2452 v v v Billion ]>" + “edoc>awit “" + xxePayload; string xml XmlDocument xm1Doc = new XmlDocunent(); // Setting this to NJLL disables DTDs - Its NOT null by default. xmldoc.XmlResolver = null; xmlDoc .LoadXml (xmL) Console.WriteLine(xmlDoc. InnerText) ; Console. ReadLine() ; For NET Framework version >4.5.2, this is safe by default. XmlDocunent. can become unsafe if you create your cwn nonnull xn1Resoiver with default or unsafe settings. If you need to enable DTD processing, instructions on how to do so safely are described in detail in the referenced MSDN article, XmiNodeReader System. Xml. XmINodeReader objects ate safe by default and will ignore DTDs even when constructed with an unsafe parser or wrapped in another unsafe parser. XmiReader system. Xm1.xniReader objectsare safe by default. ‘They are set by default to have their ProhibitDtd property set to false in .NET Framework versions 40 andearlier,or their DtdProcessing property set to Protibit in .NET versions 4.0 and later. ‘Addtionally, in .NET versions 4.5.2 and later, the Xn1ReaderSet tings belonging to the XmiReader hasits XmiResolver set to null by default, which provides an additional layer cf safety. Therefore, xniReader objects will only become unsafe in version 45.2 end up ifboth the DtdProcessing property is set to Parse and the XmlReaderSetting's XmlResolver issettoa nonnull XmiResolver with default or unsafe settings, f you need to enable DTD processing, instructions on how to do so safely are described in detail in the referenced MSDN article. xmiTextReader Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html 1388 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series System. Xm1.XmlTextReader is unsafe by defaultin .NET Framework versions prior to 45.2. Here is how to make it safe in various .NET versions: Prior to .NET 4.0 In .NET Framework versions prior to.4.0, DTD parsingbehavior for xm1Reader objects like XmlTextReader are controled by the Boolean Prohibitotd property found in the System. Xml.XmlReaderSettings and System. Xml.xmlTextReader classes. Set these values to true to disable inline DTDs completely. XmlTextReader reader = new XmlTextReader (stream); // NEEDED because the default is FALSE! reader .ProhibitDtd = true; .NET 4.0- NET 45.2 In .NET Framework version 4.0, DTD parsing behavior has been changed The Prohibitotd Property has been deprecated in favor of the new DtdProcessing property. However, they didrit change the default settings so xniTextReader is stil vuherable to XE by defautt. Setting D:dProcessing to Prohibit causes theruntime'to throw an exceptionif a elementis present in the XML. Toset this value yourself, it looks like this. XmlTextReader reader = new XmlTextReader (stream); // NEEDED because the default is Parse reader,DtdProcessing = DtdProcessing.Prohibit; Altematively, you can setthe DtdProcessing property to Tanore , which will nct throw an exception on encountering a element but will simply skip over it and nct process it. Finally, you can set otéProcessing 10 Parse if you do want to allow and process inline DTDs. -NET 4.5.2 and later In NET Framework versions 4.5.2 and up, XnlTextReader sintemal XniResolver is setto null by default, making the Xm1TextReader ignore DTDs by default. The xml TextReader can become unsafe if you create your own nonnull Xm1Resolver with default or unsafe settings. XPathNavigator Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html sane 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series system. Xm1.XPath .XPathNavigator is unsafe by default in .NET Framework versions prior to 452, This is due o the fact that it implements TxPathNavigable objects like xm1Oocunent , which are also unsafe by default in versions prior to 4.5.2 You can meke XPathNavigator safeby diving it a safeparser ike XmlReader (which is safeby default) in the xPathDocument's constructor. Hereis an example: XmlReader reader = xmlReader .Create("exenple XPathDocument doc = new XPathDocument(reader) ; XPathNavigator nav = doc,CreateNavigator() ‘string xml = nav.Innerxml ,ToString(); ml"); For NET Framework version 24.5.2, XPathNavigator is safe by default. XsICompiledTransform system. XL. Xs1.Xs]ConpiledTransform (an XML transfornei) is safe by default as longas the parser its givenis safe. Itis safe by default because the default parser of the Transform() methodsis an XniReader , Which is safe by defautt (per above). ‘The source code for this method is here. Some of the Transform() methods accept an xnlReader OF IxPathNavigable (eg, XmLDocunent ) as an input, and if you pass in an unsafe XML Parser then the Transform will also beunsate. iOS libxmni2 10S includes the C/C#+ lisxm!2Iibrary described above, so that guidance applies if youare using litxmi2 directly. However, the version of libxmi2 provided up through i0S6 is prior to version 2.9 of litxml2 (which protects against XXE by default). Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html s98 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series NSXMLDocument 10S also provides an NsxsLDocunent type, which is built on top of libxmt2. However, NSxHLDocurent provides some addtional protections againet XXE that arertt available in litxmi2 directly. Per the ‘NSXMLDocument External Entity Restriction API’ section of this page: * i0S4 andeatlier: All extemal entities are loaded by default. + i085 andlater: Only entities that dorit require network access are loaded. (Which is safer) However to completely disable XE in an NSxMLDocunent inany version of iOS you simply specify NSKMINodel oadExternalentitiesNever when creatingthe NSxMLDocunent « PHP When using the default XML parser (based on libxmI2), PHP 8.0 and newer prevent XXE by default. For PHP versions prior 108.0, per the PHP documentation, the following should be set when using the default PHP XML parser in order to prevent XXE: Libxml_set_external_entity_loader(nul1) ; ‘A description of how to abuse thisin PHP is presented in a goad SensePost article describing a cool PHP based XXE vulnerability that was fixed in Facebook. Python The Python 3 official documentation contains a section on xmi vulnerabilities. As of the 1st January 2020 Python 2 is no longer supported, hcwever the Python website still contains some legacy documentation. The following table gives an overview of various modules in Python 3 used for XML parsing and whether or not they are vulnerable. ‘Attack Type sax etree mrinidom pulkion amipe Bilion Laughs Vulnerable == Vuherable. © Vuherable. © Vuherable_ = Vuherable Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html 168 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series ‘Attack Type sx etree minidom pulkiom xmirpe Quadratic Vulnerable VUherable © Vuherable. «© Vulnerable. == Vuherable Blowup ExtemalEntity Safe Safe Safe Safe Safe Expansion DTDRetrievat Safe Safe Safe Safe Safe Decompression Safe Safe Safe Safe Vuherable Bomb To protect your application from the applicable attacks, two packages exist to help you sanitize ‘your input and protect your application against DDoS andremecte attacks. Semgrep Rules ‘Semgrep is a command-line tool for offline static analysis. Use pre-built or custom rules to enforce code and security standards in your codebase. Java Below are the rules for different XML parsers in Java Digester Identifying XXE vulnerability in the org.apache..connons..digester3 Digester library Rule canbe played here https://semgrep.dev/s/salecharohit:xxe-Digester DocumentBuiderFactory Identifying XxE vulnerabiltyin the javax.xml.parsers.DocunentBuilderFactory brary Rule can be played here htips://semgrep.dev/s/salecharohit.xxe-dbt ‘SAXBuilder Identifying XXE vulnerability in the org.jdon2.input.SaxBuilder fbrary Ruke can be playedhere https://semagrep.dev/s/salecharohit>xxe-saxbuilder Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html smH8 9725122, 6:59 AM XML External Entity Prevention - OWASP Cheat Sheet Series SAXParsetFactory Identifying XxE vulnerability in the javex.xnl.parsers.SAXParserFactory library Ruke can be played here https://semgrep.dev/s/salecharohitxxe-SAXParserFactory ‘SAXReader Identifying XXE vulnerability in the org.dom4j.10.SAXReader library Rule can be played here https://semgrep.dev/s/salecharohit:xxe-SAXReader XMLinputFactory Identifying XxE vulnerability in the javex.xm1.strean.xMLInputFectory library Rule can be played hefe https://semgrep.dev/s/salecharohit:xxe-XMLInputFactory XMLReader Identifying XXE vulnerability in the org.xnl.sax.XMLReader library Rule can be played here https://semgrep.dev/s/salecharohit:xxe-XMLReader References # XXE by InfoSecinstitute ‘© OWASP Top 10-2017 AA: XML External Entities (XXE) ‘* Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks” + FindSecBugs XXE Detection # XxEbugFind Too! ‘Testing for XML Injection Intps:ifeheatshectseries.owasp.orgicheatsheetsIXML_Extemal_Enity_Prevention_Cheat_Sheet.html

You might also like