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.

851 lines
28 KiB

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