PKG-INFO 35 KB

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