METADATA 31 KB

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