You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

875 lines
29 KiB

4 years ago
  1. Metadata-Version: 2.0
  2. Name: defusedxml
  3. Version: 0.5.0
  4. Summary: XML bomb protection for Python stdlib modules
  5. Home-page: https://github.com/tiran/defusedxml
  6. Author: Christian Heimes
  7. Author-email: christian@python.org
  8. License: PSFL
  9. Download-URL: https://pypi.python.org/pypi/defusedxml
  10. Keywords: xml bomb DoS
  11. Platform: all
  12. Classifier: Development Status :: 5 - Production/Stable
  13. Classifier: Intended Audience :: Developers
  14. Classifier: License :: OSI Approved :: Python Software Foundation License
  15. Classifier: Natural Language :: English
  16. Classifier: Programming Language :: Python
  17. Classifier: Programming Language :: Python :: 2
  18. Classifier: Programming Language :: Python :: 2.7
  19. Classifier: Programming Language :: Python :: 3
  20. Classifier: Programming Language :: Python :: 3.4
  21. Classifier: Programming Language :: Python :: 3.5
  22. Classifier: Programming Language :: Python :: 3.6
  23. Classifier: Topic :: Text Processing :: Markup :: XML
  24. ===================================================
  25. defusedxml -- defusing XML bombs and other exploits
  26. ===================================================
  27. "It's just XML, what could probably go wrong?"
  28. Christian Heimes <christian@python.org>
  29. Synopsis
  30. ========
  31. The results of an attack on a vulnerable XML library can be fairly dramatic.
  32. With just a few hundred **Bytes** of XML data an attacker can occupy several
  33. **Gigabytes** of memory within **seconds**. An attacker can also keep
  34. CPUs busy for a long time with a small to medium size request. Under some
  35. circumstances it is even possible to access local files on your
  36. server, to circumvent a firewall, or to abuse services to rebound attacks to
  37. third parties.
  38. The attacks use and abuse less common features of XML and its parsers. The
  39. majority of developers are unacquainted with features such as processing
  40. instructions and entity expansions that XML inherited from SGML. At best
  41. they know about ``<!DOCTYPE>`` from experience with HTML but they are not
  42. aware that a document type definition (DTD) can generate an HTTP request
  43. or load a file from the file system.
  44. None of the issues is new. They have been known for a long time. Billion
  45. laughs was first reported in 2003. Nevertheless some XML libraries and
  46. applications are still vulnerable and even heavy users of XML are
  47. surprised by these features. It's hard to say whom to blame for the
  48. situation. It's too short sighted to shift all blame on XML parsers and
  49. XML libraries for using insecure default settings. After all they
  50. properly implement XML specifications. Application developers must not rely
  51. that a library is always configured for security and potential harmful data
  52. by default.
  53. .. contents:: Table of Contents
  54. :depth: 2
  55. Attack vectors
  56. ==============
  57. billion laughs / exponential entity expansion
  58. ---------------------------------------------
  59. The `Billion Laughs`_ attack -- also known as exponential entity expansion --
  60. uses multiple levels of nested entities. The original example uses 9 levels
  61. of 10 expansions in each level to expand the string ``lol`` to a string of
  62. 3 * 10 :sup:`9` bytes, hence the name "billion laughs". The resulting string
  63. occupies 3 GB (2.79 GiB) of memory; intermediate strings require additional
  64. memory. Because most parsers don't cache the intermediate step for every
  65. expansion it is repeated over and over again. It increases the CPU load even
  66. more.
  67. An XML document of just a few hundred bytes can disrupt all services on a
  68. machine within seconds.
  69. Example XML::
  70. <!DOCTYPE xmlbomb [
  71. <!ENTITY a "1234567890" >
  72. <!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;">
  73. <!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;">
  74. <!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;">
  75. ]>
  76. <bomb>&d;</bomb>
  77. quadratic blowup entity expansion
  78. ---------------------------------
  79. A quadratic blowup attack is similar to a `Billion Laughs`_ attack; it abuses
  80. entity expansion, too. Instead of nested entities it repeats one large entity
  81. with a couple of thousand chars over and over again. The attack isn't as
  82. efficient as the exponential case but it avoids triggering countermeasures of
  83. parsers against heavily nested entities. Some parsers limit the depth and
  84. breadth of a single entity but not the total amount of expanded text
  85. throughout an entire XML document.
  86. A medium-sized XML document with a couple of hundred kilobytes can require a
  87. couple of hundred MB to several GB of memory. When the attack is combined
  88. with some level of nested expansion an attacker is able to achieve a higher
  89. ratio of success.
  90. ::
  91. <!DOCTYPE bomb [
  92. <!ENTITY a "xxxxxxx... a couple of ten thousand chars">
  93. ]>
  94. <bomb>&a;&a;&a;... repeat</bomb>
  95. external entity expansion (remote)
  96. ----------------------------------
  97. Entity declarations can contain more than just text for replacement. They can
  98. also point to external resources by public identifiers or system identifiers.
  99. System identifiers are standard URIs. When the URI is a URL (e.g. a
  100. ``http://`` locator) some parsers download the resource from the remote
  101. location and embed them into the XML document verbatim.
  102. Simple example of a parsed external entity::
  103. <!DOCTYPE external [
  104. <!ENTITY ee SYSTEM "http://www.python.org/some.xml">
  105. ]>
  106. <root>&ee;</root>
  107. The case of parsed external entities works only for valid XML content. The
  108. XML standard also supports unparsed external entities with a
  109. ``NData declaration``.
  110. External entity expansion opens the door to plenty of exploits. An attacker
  111. can abuse a vulnerable XML library and application to rebound and forward
  112. network requests with the IP address of the server. It highly depends
  113. on the parser and the application what kind of exploit is possible. For
  114. example:
  115. * An attacker can circumvent firewalls and gain access to restricted
  116. resources as all the requests are made from an internal and trustworthy
  117. IP address, not from the outside.
  118. * An attacker can abuse a service to attack, spy on or DoS your servers but
  119. also third party services. The attack is disguised with the IP address of
  120. the server and the attacker is able to utilize the high bandwidth of a big
  121. machine.
  122. * An attacker can exhaust additional resources on the machine, e.g. with
  123. requests to a service that doesn't respond or responds with very large
  124. files.
  125. * An attacker may gain knowledge, when, how often and from which IP address
  126. a XML document is accessed.
  127. * An attacker could send mail from inside your network if the URL handler
  128. supports ``smtp://`` URIs.
  129. external entity expansion (local file)
  130. --------------------------------------
  131. External entities with references to local files are a sub-case of external
  132. entity expansion. It's listed as an extra attack because it deserves extra
  133. attention. Some XML libraries such as lxml disable network access by default
  134. but still allow entity expansion with local file access by default. Local
  135. files are either referenced with a ``file://`` URL or by a file path (either
  136. relative or absolute).
  137. An attacker may be able to access and download all files that can be read by
  138. the application process. This may include critical configuration files, too.
  139. ::
  140. <!DOCTYPE external [
  141. <!ENTITY ee SYSTEM "file:///PATH/TO/simple.xml">
  142. ]>
  143. <root>&ee;</root>
  144. DTD retrieval
  145. -------------
  146. This case is similar to external entity expansion, too. Some XML libraries
  147. like Python's xml.dom.pulldom retrieve document type definitions from remote
  148. or local locations. Several attack scenarios from the external entity case
  149. apply to this issue as well.
  150. ::
  151. <?xml version="1.0" encoding="utf-8"?>
  152. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  153. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  154. <html>
  155. <head/>
  156. <body>text</body>
  157. </html>
  158. Python XML Libraries
  159. ====================
  160. .. csv-table:: vulnerabilities and features
  161. :header: "kind", "sax", "etree", "minidom", "pulldom", "xmlrpc", "lxml", "genshi"
  162. :widths: 24, 7, 8, 8, 7, 8, 8, 8
  163. :stub-columns: 0
  164. "billion laughs", "**True**", "**True**", "**True**", "**True**", "**True**", "False (1)", "False (5)"
  165. "quadratic blowup", "**True**", "**True**", "**True**", "**True**", "**True**", "**True**", "False (5)"
  166. "external entity expansion (remote)", "**True**", "False (3)", "False (4)", "**True**", "false", "False (1)", "False (5)"
  167. "external entity expansion (local file)", "**True**", "False (3)", "False (4)", "**True**", "false", "**True**", "False (5)"
  168. "DTD retrieval", "**True**", "False", "False", "**True**", "false", "False (1)", "False"
  169. "gzip bomb", "False", "False", "False", "False", "**True**", "**partly** (2)", "False"
  170. "xpath support (7)", "False", "False", "False", "False", "False", "**True**", "False"
  171. "xsl(t) support (7)", "False", "False", "False", "False", "False", "**True**", "False"
  172. "xinclude support (7)", "False", "**True** (6)", "False", "False", "False", "**True** (6)", "**True**"
  173. "C library", "expat", "expat", "expat", "expat", "expat", "libxml2", "expat"
  174. 1. Lxml is protected against billion laughs attacks and doesn't do network
  175. lookups by default.
  176. 2. libxml2 and lxml are not directly vulnerable to gzip decompression bombs
  177. but they don't protect you against them either.
  178. 3. xml.etree doesn't expand entities and raises a ParserError when an entity
  179. occurs.
  180. 4. minidom doesn't expand entities and simply returns the unexpanded entity
  181. verbatim.
  182. 5. genshi.input of genshi 0.6 doesn't support entity expansion and raises a
  183. ParserError when an entity occurs.
  184. 6. Library has (limited) XInclude support but requires an additional step to
  185. process inclusion.
  186. 7. These are features but they may introduce exploitable holes, see
  187. `Other things to consider`_
  188. Settings in standard library
  189. ----------------------------
  190. xml.sax.handler Features
  191. ........................
  192. feature_external_ges (http://xml.org/sax/features/external-general-entities)
  193. disables external entity expansion
  194. feature_external_pes (http://xml.org/sax/features/external-parameter-entities)
  195. the option is ignored and doesn't modify any functionality
  196. DOM xml.dom.xmlbuilder.Options
  197. ..............................
  198. external_parameter_entities
  199. ignored
  200. external_general_entities
  201. ignored
  202. external_dtd_subset
  203. ignored
  204. entities
  205. unsure
  206. defusedxml
  207. ==========
  208. The `defusedxml package`_ (`defusedxml on PyPI`_)
  209. contains several Python-only workarounds and fixes
  210. for denial of service and other vulnerabilities in Python's XML libraries.
  211. In order to benefit from the protection you just have to import and use the
  212. listed functions / classes from the right defusedxml module instead of the
  213. original module. Merely `defusedxml.xmlrpc`_ is implemented as monkey patch.
  214. Instead of::
  215. >>> from xml.etree.ElementTree import parse
  216. >>> et = parse(xmlfile)
  217. alter code to::
  218. >>> from defusedxml.ElementTree import parse
  219. >>> et = parse(xmlfile)
  220. Additionally the package has an **untested** function to monkey patch
  221. all stdlib modules with ``defusedxml.defuse_stdlib()``.
  222. All functions and parser classes accept three additional keyword arguments.
  223. They return either the same objects as the original functions or compatible
  224. subclasses.
  225. forbid_dtd (default: False)
  226. disallow XML with a ``<!DOCTYPE>`` processing instruction and raise a
  227. *DTDForbidden* exception when a DTD processing instruction is found.
  228. forbid_entities (default: True)
  229. disallow XML with ``<!ENTITY>`` declarations inside the DTD and raise an
  230. *EntitiesForbidden* exception when an entity is declared.
  231. forbid_external (default: True)
  232. disallow any access to remote or local resources in external entities
  233. or DTD and raising an *ExternalReferenceForbidden* exception when a DTD
  234. or entity references an external resource.
  235. defusedxml (package)
  236. --------------------
  237. DefusedXmlException, DTDForbidden, EntitiesForbidden,
  238. ExternalReferenceForbidden, NotSupportedError
  239. defuse_stdlib() (*experimental*)
  240. defusedxml.cElementTree
  241. -----------------------
  242. parse(), iterparse(), fromstring(), XMLParser
  243. defusedxml.ElementTree
  244. -----------------------
  245. parse(), iterparse(), fromstring(), XMLParser
  246. defusedxml.expatreader
  247. ----------------------
  248. create_parser(), DefusedExpatParser
  249. defusedxml.sax
  250. --------------
  251. parse(), parseString(), create_parser()
  252. defusedxml.expatbuilder
  253. -----------------------
  254. parse(), parseString(), DefusedExpatBuilder, DefusedExpatBuilderNS
  255. defusedxml.minidom
  256. ------------------
  257. parse(), parseString()
  258. defusedxml.pulldom
  259. ------------------
  260. parse(), parseString()
  261. defusedxml.xmlrpc
  262. -----------------
  263. The fix is implemented as monkey patch for the stdlib's xmlrpc package (3.x)
  264. or xmlrpclib module (2.x). The function `monkey_patch()` enables the fixes,
  265. `unmonkey_patch()` removes the patch and puts the code in its former state.
  266. The monkey patch protects against XML related attacks as well as
  267. decompression bombs and excessively large requests or responses. The default
  268. setting is 30 MB for requests, responses and gzip decompression. You can
  269. modify the default by changing the module variable `MAX_DATA`. A value of
  270. `-1` disables the limit.
  271. defusedxml.lxml
  272. ---------------
  273. The module acts as an *example* how you could protect code that uses
  274. lxml.etree. It implements a custom Element class that filters out
  275. Entity instances, a custom parser factory and a thread local storage for
  276. parser instances. It also has a check_docinfo() function which inspects
  277. a tree for internal or external DTDs and entity declarations. In order to
  278. check for entities lxml > 3.0 is required.
  279. parse(), fromstring()
  280. RestrictedElement, GlobalParserTLS, getDefaultParser(), check_docinfo()
  281. defusedexpat
  282. ============
  283. The `defusedexpat package`_ (`defusedexpat on PyPI`_)
  284. comes with binary extensions and a
  285. `modified expat`_ libary instead of the standard `expat parser`_. It's
  286. basically a stand-alone version of the patches for Python's standard
  287. library C extensions.
  288. Modifications in expat
  289. ----------------------
  290. new definitions::
  291. XML_BOMB_PROTECTION
  292. XML_DEFAULT_MAX_ENTITY_INDIRECTIONS
  293. XML_DEFAULT_MAX_ENTITY_EXPANSIONS
  294. XML_DEFAULT_RESET_DTD
  295. new XML_FeatureEnum members::
  296. XML_FEATURE_MAX_ENTITY_INDIRECTIONS
  297. XML_FEATURE_MAX_ENTITY_EXPANSIONS
  298. XML_FEATURE_IGNORE_DTD
  299. new XML_Error members::
  300. XML_ERROR_ENTITY_INDIRECTIONS
  301. XML_ERROR_ENTITY_EXPANSION
  302. new API functions::
  303. int XML_GetFeature(XML_Parser parser,
  304. enum XML_FeatureEnum feature,
  305. long *value);
  306. int XML_SetFeature(XML_Parser parser,
  307. enum XML_FeatureEnum feature,
  308. long value);
  309. int XML_GetFeatureDefault(enum XML_FeatureEnum feature,
  310. long *value);
  311. int XML_SetFeatureDefault(enum XML_FeatureEnum feature,
  312. long value);
  313. XML_FEATURE_MAX_ENTITY_INDIRECTIONS
  314. Limit the amount of indirections that are allowed to occur during the
  315. expansion of a nested entity. A counter starts when an entity reference
  316. is encountered. It resets after the entity is fully expanded. The limit
  317. protects the parser against exponential entity expansion attacks (aka
  318. billion laughs attack). When the limit is exceeded the parser stops and
  319. fails with `XML_ERROR_ENTITY_INDIRECTIONS`.
  320. A value of 0 disables the protection.
  321. Supported range
  322. 0 .. UINT_MAX
  323. Default
  324. 40
  325. XML_FEATURE_MAX_ENTITY_EXPANSIONS
  326. Limit the total length of all entity expansions throughout the entire
  327. document. The lengths of all entities are accumulated in a parser variable.
  328. The setting protects against quadratic blowup attacks (lots of expansions
  329. of a large entity declaration). When the sum of all entities exceeds
  330. the limit, the parser stops and fails with `XML_ERROR_ENTITY_EXPANSION`.
  331. A value of 0 disables the protection.
  332. Supported range
  333. 0 .. UINT_MAX
  334. Default
  335. 8 MiB
  336. XML_FEATURE_RESET_DTD
  337. Reset all DTD information after the <!DOCTYPE> block has been parsed. When
  338. the flag is set (default: false) all DTD information after the
  339. endDoctypeDeclHandler has been called. The flag can be set inside the
  340. endDoctypeDeclHandler. Without DTD information any entity reference in
  341. the document body leads to `XML_ERROR_UNDEFINED_ENTITY`.
  342. Supported range
  343. 0, 1
  344. Default
  345. 0
  346. How to avoid XML vulnerabilities
  347. ================================
  348. Best practices
  349. --------------
  350. * Don't allow DTDs
  351. * Don't expand entities
  352. * Don't resolve externals
  353. * Limit parse depth
  354. * Limit total input size
  355. * Limit parse time
  356. * Favor a SAX or iterparse-like parser for potential large data
  357. * Validate and properly quote arguments to XSL transformations and
  358. XPath queries
  359. * Don't use XPath expression from untrusted sources
  360. * Don't apply XSL transformations that come untrusted sources
  361. (based on Brad Hill's `Attacking XML Security`_)
  362. Other things to consider
  363. ========================
  364. XML, XML parsers and processing libraries have more features and possible
  365. issue that could lead to DoS vulnerabilities or security exploits in
  366. applications. I have compiled an incomplete list of theoretical issues that
  367. need further research and more attention. The list is deliberately pessimistic
  368. and a bit paranoid, too. It contains things that might go wrong under daffy
  369. circumstances.
  370. attribute blowup / hash collision attack
  371. ----------------------------------------
  372. XML parsers may use an algorithm with quadratic runtime O(n :sup:`2`) to
  373. handle attributes and namespaces. If it uses hash tables (dictionaries) to
  374. store attributes and namespaces the implementation may be vulnerable to
  375. hash collision attacks, thus reducing the performance to O(n :sup:`2`) again.
  376. In either case an attacker is able to forge a denial of service attack with
  377. an XML document that contains thousands upon thousands of attributes in
  378. a single node.
  379. I haven't researched yet if expat, pyexpat or libxml2 are vulnerable.
  380. decompression bomb
  381. ------------------
  382. The issue of decompression bombs (aka `ZIP bomb`_) apply to all XML libraries
  383. that can parse compressed XML stream like gzipped HTTP streams or LZMA-ed
  384. files. For an attacker it can reduce the amount of transmitted data by three
  385. magnitudes or more. Gzip is able to compress 1 GiB zeros to roughly 1 MB,
  386. lzma is even better::
  387. $ dd if=/dev/zero bs=1M count=1024 | gzip > zeros.gz
  388. $ dd if=/dev/zero bs=1M count=1024 | lzma -z > zeros.xy
  389. $ ls -sh zeros.*
  390. 1020K zeros.gz
  391. 148K zeros.xy
  392. None of Python's standard XML libraries decompress streams except for
  393. ``xmlrpclib``. The module is vulnerable <http://bugs.python.org/issue16043>
  394. to decompression bombs.
  395. lxml can load and process compressed data through libxml2 transparently.
  396. libxml2 can handle even very large blobs of compressed data efficiently
  397. without using too much memory. But it doesn't protect applications from
  398. decompression bombs. A carefully written SAX or iterparse-like approach can
  399. be safe.
  400. Processing Instruction
  401. ----------------------
  402. `PI`_'s like::
  403. <?xml-stylesheet type="text/xsl" href="style.xsl"?>
  404. may impose more threats for XML processing. It depends if and how a
  405. processor handles processing instructions. The issue of URL retrieval with
  406. network or local file access apply to processing instructions, too.
  407. Other DTD features
  408. ------------------
  409. `DTD`_ has more features like ``<!NOTATION>``. I haven't researched how
  410. these features may be a security threat.
  411. XPath
  412. -----
  413. XPath statements may introduce DoS vulnerabilities. Code should never execute
  414. queries from untrusted sources. An attacker may also be able to create a XML
  415. document that makes certain XPath queries costly or resource hungry.
  416. XPath injection attacks
  417. -----------------------
  418. XPath injeciton attacks pretty much work like SQL injection attacks.
  419. Arguments to XPath queries must be quoted and validated properly, especially
  420. when they are taken from the user. The page `Avoid the dangers of XPath injection`_
  421. list some ramifications of XPath injections.
  422. Python's standard library doesn't have XPath support. Lxml supports
  423. parameterized XPath queries which does proper quoting. You just have to use
  424. its xpath() method correctly::
  425. # DON'T
  426. >>> tree.xpath("/tag[@id='%s']" % value)
  427. # instead do
  428. >>> tree.xpath("/tag[@id=$tagid]", tagid=name)
  429. XInclude
  430. --------
  431. `XML Inclusion`_ is another way to load and include external files::
  432. <root xmlns:xi="http://www.w3.org/2001/XInclude">
  433. <xi:include href="filename.txt" parse="text" />
  434. </root>
  435. This feature should be disabled when XML files from an untrusted source are
  436. processed. Some Python XML libraries and libxml2 support XInclude but don't
  437. have an option to sandbox inclusion and limit it to allowed directories.
  438. XMLSchema location
  439. ------------------
  440. A validating XML parser may download schema files from the information in a
  441. ``xsi:schemaLocation`` attribute.
  442. ::
  443. <ead xmlns="urn:isbn:1-931666-22-9"
  444. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  445. xsi:schemaLocation="urn:isbn:1-931666-22-9 http://www.loc.gov/ead/ead.xsd">
  446. </ead>
  447. XSL Transformation
  448. ------------------
  449. You should keep in mind that XSLT is a Turing complete language. Never
  450. process XSLT code from unknown or untrusted source! XSLT processors may
  451. allow you to interact with external resources in ways you can't even imagine.
  452. Some processors even support extensions that allow read/write access to file
  453. system, access to JRE objects or scripting with Jython.
  454. Example from `Attacking XML Security`_ for Xalan-J::
  455. <xsl:stylesheet version="1.0"
  456. xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  457. xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime"
  458. xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object"
  459. exclude-result-prefixes= "rt ob">
  460. <xsl:template match="/">
  461. <xsl:variable name="runtimeObject" select="rt:getRuntime()"/>
  462. <xsl:variable name="command"
  463. select="rt:exec($runtimeObject, &apos;c:\Windows\system32\cmd.exe&apos;)"/>
  464. <xsl:variable name="commandAsString" select="ob:toString($command)"/>
  465. <xsl:value-of select="$commandAsString"/>
  466. </xsl:template>
  467. </xsl:stylesheet>
  468. Related CVEs
  469. ============
  470. CVE-2013-1664
  471. Unrestricted entity expansion induces DoS vulnerabilities in Python XML
  472. libraries (XML bomb)
  473. CVE-2013-1665
  474. External entity expansion in Python XML libraries inflicts potential
  475. security flaws and DoS vulnerabilities
  476. Other languages / frameworks
  477. =============================
  478. Several other programming languages and frameworks are vulnerable as well. A
  479. couple of them are affected by the fact that libxml2 up to 2.9.0 has no
  480. protection against quadratic blowup attacks. Most of them have potential
  481. dangerous default settings for entity expansion and external entities, too.
  482. Perl
  483. ----
  484. Perl's XML::Simple is vulnerable to quadratic entity expansion and external
  485. entity expansion (both local and remote).
  486. Ruby
  487. ----
  488. Ruby's REXML document parser is vulnerable to entity expansion attacks
  489. (both quadratic and exponential) but it doesn't do external entity
  490. expansion by default. In order to counteract entity expansion you have to
  491. disable the feature::
  492. REXML::Document.entity_expansion_limit = 0
  493. libxml-ruby and hpricot don't expand entities in their default configuration.
  494. PHP
  495. ---
  496. PHP's SimpleXML API is vulnerable to quadratic entity expansion and loads
  497. entites from local and remote resources. The option ``LIBXML_NONET`` disables
  498. network access but still allows local file access. ``LIBXML_NOENT`` seems to
  499. have no effect on entity expansion in PHP 5.4.6.
  500. C# / .NET / Mono
  501. ----------------
  502. Information in `XML DoS and Defenses (MSDN)`_ suggest that .NET is
  503. vulnerable with its default settings. The article contains code snippets
  504. how to create a secure XML reader::
  505. XmlReaderSettings settings = new XmlReaderSettings();
  506. settings.ProhibitDtd = false;
  507. settings.MaxCharactersFromEntities = 1024;
  508. settings.XmlResolver = null;
  509. XmlReader reader = XmlReader.Create(stream, settings);
  510. Java
  511. ----
  512. Untested. The documentation of Xerces and its `Xerces SecurityMananger`_
  513. sounds like Xerces is also vulnerable to billion laugh attacks with its
  514. default settings. It also does entity resolving when an
  515. ``org.xml.sax.EntityResolver`` is configured. I'm not yet sure about the
  516. default setting here.
  517. Java specialists suggest to have a custom builder factory::
  518. DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
  519. builderFactory.setXIncludeAware(False);
  520. builderFactory.setExpandEntityReferences(False);
  521. builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, True);
  522. # either
  523. builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", True);
  524. # or if you need DTDs
  525. builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", False);
  526. builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", False);
  527. builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", False);
  528. builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", False);
  529. TODO
  530. ====
  531. * DOM: Use xml.dom.xmlbuilder options for entity handling
  532. * SAX: take feature_external_ges and feature_external_pes (?) into account
  533. * test experimental monkey patching of stdlib modules
  534. * improve documentation
  535. License
  536. =======
  537. Copyright (c) 2013-2017 by Christian Heimes <christian@python.org>
  538. Licensed to PSF under a Contributor Agreement.
  539. See http://www.python.org/psf/license for licensing details.
  540. Acknowledgements
  541. ================
  542. Brett Cannon (Python Core developer)
  543. review and code cleanup
  544. Antoine Pitrou (Python Core developer)
  545. code review
  546. Aaron Patterson, Ben Murphy and Michael Koziarski (Ruby community)
  547. Many thanks to Aaron, Ben and Michael from the Ruby community for their
  548. report and assistance.
  549. Thierry Carrez (OpenStack)
  550. Many thanks to Thierry for his report to the Python Security Response
  551. Team on behalf of the OpenStack security team.
  552. Carl Meyer (Django)
  553. Many thanks to Carl for his report to PSRT on behalf of the Django security
  554. team.
  555. Daniel Veillard (libxml2)
  556. Many thanks to Daniel for his insight and assistance with libxml2.
  557. semantics GmbH (http://www.semantics.de/)
  558. Many thanks to my employer semantics for letting me work on the issue
  559. during working hours as part of semantics's open source initiative.
  560. References
  561. ==========
  562. * `XML DoS and Defenses (MSDN)`_
  563. * `Billion Laughs`_ on Wikipedia
  564. * `ZIP bomb`_ on Wikipedia
  565. * `Configure SAX parsers for secure processing`_
  566. * `Testing for XML Injection`_
  567. .. _defusedxml package: https://bitbucket.org/tiran/defusedxml
  568. .. _defusedxml on PyPI: https://pypi.python.org/pypi/defusedxml
  569. .. _defusedexpat package: https://bitbucket.org/tiran/defusedexpat
  570. .. _defusedexpat on PyPI: https://pypi.python.org/pypi/defusedexpat
  571. .. _modified expat: https://bitbucket.org/tiran/expat
  572. .. _expat parser: http://expat.sourceforge.net/
  573. .. _Attacking XML Security: https://www.isecpartners.com/media/12976/iSEC-HILL-Attacking-XML-Security-bh07.pdf
  574. .. _Billion Laughs: http://en.wikipedia.org/wiki/Billion_laughs
  575. .. _XML DoS and Defenses (MSDN): http://msdn.microsoft.com/en-us/magazine/ee335713.aspx
  576. .. _ZIP bomb: http://en.wikipedia.org/wiki/Zip_bomb
  577. .. _DTD: http://en.wikipedia.org/wiki/Document_Type_Definition
  578. .. _PI: https://en.wikipedia.org/wiki/Processing_Instruction
  579. .. _Avoid the dangers of XPath injection: http://www.ibm.com/developerworks/xml/library/x-xpathinjection/index.html
  580. .. _Configure SAX parsers for secure processing: http://www.ibm.com/developerworks/xml/library/x-tipcfsx/index.html
  581. .. _Testing for XML Injection: https://www.owasp.org/index.php/Testing_for_XML_Injection_(OWASP-DV-008)
  582. .. _Xerces SecurityMananger: http://xerces.apache.org/xerces2-j/javadocs/xerces2/org/apache/xerces/util/SecurityManager.html
  583. .. _XML Inclusion: http://www.w3.org/TR/xinclude/#include_element
  584. Changelog
  585. =========
  586. defusedxml 0.5.0
  587. ----------------
  588. *Release date: 07-Feb-2017*
  589. - No changes
  590. defusedxml 0.5.0.rc1
  591. --------------------
  592. *Release date: 28-Jan-2017*
  593. - Add compatibility with Python 3.6
  594. - Drop support for Python 2.6, 3.1, 3.2, 3.3
  595. - Fix lxml tests (XMLSyntaxError: Detected an entity reference loop)
  596. defusedxml 0.4.1
  597. ----------------
  598. *Release date: 28-Mar-2013*
  599. - Add more demo exploits, e.g. python_external.py and Xalan XSLT demos.
  600. - Improved documentation.
  601. defusedxml 0.4
  602. --------------
  603. *Release date: 25-Feb-2013*
  604. - As per http://seclists.org/oss-sec/2013/q1/340 please REJECT
  605. CVE-2013-0278, CVE-2013-0279 and CVE-2013-0280 and use CVE-2013-1664,
  606. CVE-2013-1665 for OpenStack/etc.
  607. - Add missing parser_list argument to sax.make_parser(). The argument is
  608. ignored, though. (thanks to Florian Apolloner)
  609. - Add demo exploit for external entity attack on Python's SAX parser, XML-RPC
  610. and WebDAV.
  611. defusedxml 0.3
  612. --------------
  613. *Release date: 19-Feb-2013*
  614. - Improve documentation
  615. defusedxml 0.2
  616. --------------
  617. *Release date: 15-Feb-2013*
  618. - Rename ExternalEntitiesForbidden to ExternalReferenceForbidden
  619. - Rename defusedxml.lxml.check_dtd() to check_docinfo()
  620. - Unify argument names in callbacks
  621. - Add arguments and formatted representation to exceptions
  622. - Add forbid_external argument to all functions and classs
  623. - More tests
  624. - LOTS of documentation
  625. - Add example code for other languages (Ruby, Perl, PHP) and parsers (Genshi)
  626. - Add protection against XML and gzip attacks to xmlrpclib
  627. defusedxml 0.1
  628. --------------
  629. *Release date: 08-Feb-2013*
  630. - Initial and internal release for PSRT review