1
0

METADATA 32 KB

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