Code Monkey home page Code Monkey logo

defusedxml's Introduction

defusedxml -- defusing XML bombs and other exploits

Latest Version Supported Python versions Travis CI codecov PyPI downloads Code style: black

"It's just XML, what could probably go wrong?"

Christian Heimes <[email protected]>

Synopsis

The results of an attack on a vulnerable XML library can be fairly dramatic. With just a few hundred Bytes of XML data an attacker can occupy several Gigabytes of memory within seconds. An attacker can also keep CPUs busy for a long time with a small to medium size request. Under some circumstances it is even possible to access local files on your server, to circumvent a firewall, or to abuse services to rebound attacks to third parties.

The attacks use and abuse less common features of XML and its parsers. The majority of developers are unacquainted with features such as processing instructions and entity expansions that XML inherited from SGML. At best they know about <!DOCTYPE> from experience with HTML but they are not aware that a document type definition (DTD) can generate an HTTP request or load a file from the file system.

None of the issues is new. They have been known for a long time. Billion laughs was first reported in 2003. Nevertheless some XML libraries and applications are still vulnerable and even heavy users of XML are surprised by these features. It's hard to say whom to blame for the situation. It's too short sighted to shift all blame on XML parsers and XML libraries for using insecure default settings. After all they properly implement XML specifications. Application developers must not rely that a library is always configured for security and potential harmful data by default.

Table of Contents

Attack vectors

billion laughs / exponential entity expansion

The Billion Laughs attack -- also known as exponential entity expansion --uses multiple levels of nested entities. The original example uses 9 levels of 10 expansions in each level to expand the string lol to a string of 3 * 10 9 bytes, hence the name "billion laughs". The resulting string occupies 3 GB (2.79 GiB) of memory; intermediate strings require additional memory. Because most parsers don't cache the intermediate step for every expansion it is repeated over and over again. It increases the CPU load even more.

An XML document of just a few hundred bytes can disrupt all services on a machine within seconds.

Example XML:

<!DOCTYPE xmlbomb [
<!ENTITY a "1234567890" >
<!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;">
<!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;">
<!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;">
]>
<bomb>&d;</bomb>

quadratic blowup entity expansion

A quadratic blowup attack is similar to a Billion Laughs attack; it abuses entity expansion, too. Instead of nested entities it repeats one large entity with a couple of thousand chars over and over again. The attack isn't as efficient as the exponential case but it avoids triggering countermeasures of parsers against heavily nested entities. Some parsers limit the depth and breadth of a single entity but not the total amount of expanded text throughout an entire XML document.

A medium-sized XML document with a couple of hundred kilobytes can require a couple of hundred MB to several GB of memory. When the attack is combined with some level of nested expansion an attacker is able to achieve a higher ratio of success.

<!DOCTYPE bomb [
<!ENTITY a "xxxxxxx... a couple of ten thousand chars">
]>
<bomb>&a;&a;&a;... repeat</bomb>

external entity expansion (remote)

Entity declarations can contain more than just text for replacement. They can also point to external resources by public identifiers or system identifiers. System identifiers are standard URIs. When the URI is a URL (e.g. a http:// locator) some parsers download the resource from the remote location and embed them into the XML document verbatim.

Simple example of a parsed external entity:

<!DOCTYPE external [
<!ENTITY ee SYSTEM "http://www.python.org/some.xml">
]>
<root>&ee;</root>

The case of parsed external entities works only for valid XML content. The XML standard also supports unparsed external entities with a NData declaration.

External entity expansion opens the door to plenty of exploits. An attacker can abuse a vulnerable XML library and application to rebound and forward network requests with the IP address of the server. It highly depends on the parser and the application what kind of exploit is possible. For example:

  • An attacker can circumvent firewalls and gain access to restricted resources as all the requests are made from an internal and trustworthy IP address, not from the outside.
  • An attacker can abuse a service to attack, spy on or DoS your servers but also third party services. The attack is disguised with the IP address of the server and the attacker is able to utilize the high bandwidth of a big machine.
  • An attacker can exhaust additional resources on the machine, e.g. with requests to a service that doesn't respond or responds with very large files.
  • An attacker may gain knowledge, when, how often and from which IP address an XML document is accessed.
  • An attacker could send mail from inside your network if the URL handler supports smtp:// URIs.

external entity expansion (local file)

External entities with references to local files are a sub-case of external entity expansion. It's listed as an extra attack because it deserves extra attention. Some XML libraries such as lxml disable network access by default but still allow entity expansion with local file access by default. Local files are either referenced with a file:// URL or by a file path (either relative or absolute). Additionally, lxml's libxml2 has catalog support. XML catalogs like /etc/xml/catalog are XML files, which map schema URIs to local files.

An attacker may be able to access and download all files that can be read by the application process. This may include critical configuration files, too.

<!DOCTYPE external [
<!ENTITY ee SYSTEM "file:///PATH/TO/simple.xml">
]>
<root>&ee;</root>

DTD retrieval

This case is similar to external entity expansion, too. Some XML libraries like Python's xml.dom.pulldom retrieve document type definitions from remote or local locations. Several attack scenarios from the external entity case apply to this issue as well.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head/>
    <body>text</body>
</html>

Python XML Libraries

kind sax etree minidom pulldom xmlrpc
billion laughs Maybe (1) Maybe (1) Maybe (1) Maybe (1) Maybe (1)
quadratic blowup Maybe (1) Maybe (1) Maybe (1) Maybe (1) Maybe (1)
external entity expansion (remote) False (2) False (3) False (4) False (2) false
external entity expansion (local file) False (2) False (3) False (4) False (2) false
DTD retrieval False (2) False False False (2) false
gzip bomb False False False False True
xpath support (6) False False False False False
xsl(t) support (6) False False False False False
xinclude support (6) False True (5) False False False
C library expat expat expat expat expat

vulnerabilities and features

  1. expat parser >= 2.4.0 has billion laughs protection against XML bombs (CVE-2013-0340). The parser has sensible defaults for XML_SetBillionLaughsAttackProtectionMaximumAmplification and XML_SetBillionLaughsAttackProtectionActivationThreshold.
  2. Python >= 3.6.8, >= 3.7.1, and >= 3.8 no longer retrieve local and remote resources with urllib, see bpo-17239.
  3. xml.etree doesn't expand entities and raises a ParserError when an entity occurs.
  4. minidom doesn't expand entities and simply returns the unexpanded entity verbatim.
  5. Library has (limited) XInclude support but requires an additional step to process inclusion.
  6. These are features but they may introduce exploitable holes, see Other things to consider

Settings in standard library

xml.sax.handler Features

feature_external_ges (http://xml.org/sax/features/external-general-entities)
disables external entity expansion

feature_external_pes (http://xml.org/sax/features/external-parameter-entities)
the option is ignored and doesn't modify any functionality

DOM xml.dom.xmlbuilder.Options

external_parameter_entities
ignored

external_general_entities
ignored

external_dtd_subset
ignored

entities
unsure

defusedxml

The defusedxml package (defusedxml on PyPI) contains several Python-only workarounds and fixes for denial of service and other vulnerabilities in Python's XML libraries. In order to benefit from the protection you just have to import and use the listed functions / classes from the right defusedxml module instead of the original module. Merely defusedxml.xmlrpc is implemented as monkey patch.

Instead of:

>>> from xml.etree.ElementTree import parse
>>> et = parse(xmlfile)

alter code to:

>>> from defusedxml.ElementTree import parse
>>> et = parse(xmlfile)

Note

The defusedxml modules are not drop-in replacements of their stdlib counterparts. The modules only provide functions and classes related to parsing and loading of XML. For all other features, use the classes, functions, and constants from the stdlib modules. For example:

>>> from defusedxml import ElementTree as DET
>>> from xml.etree.ElementTree as ET

>>> root = DET.fromstring("<root/>")
>>> root.append(ET.Element("item"))
>>> ET.tostring(root)
b'<root><item /></root>'

Additionally the package has an untested function to monkey patch all stdlib modules with defusedxml.defuse_stdlib().

Warning

defuse_stdlib() should be avoided. It can break third party package or cause surprising side effects. Instead you should use the parsing features of defusedxml explicitly.

All functions and parser classes accept three additional keyword arguments. They return either the same objects as the original functions or compatible subclasses.

forbid_dtd (default: False)
disallow XML with a <!DOCTYPE> processing instruction and raise a DTDForbidden exception when a DTD processing instruction is found.

forbid_entities (default: True)
disallow XML with <!ENTITY> declarations inside the DTD and raise an EntitiesForbidden exception when an entity is declared.

forbid_external (default: True)
disallow any access to remote or local resources in external entities or DTD and raising an ExternalReferenceForbidden exception when a DTD or entity references an external resource.

defusedxml (package)

DefusedXmlException, DTDForbidden, EntitiesForbidden, ExternalReferenceForbidden, NotSupportedError

defuse_stdlib() (experimental)

defusedxml.cElementTree

NOTE defusedxml.cElementTree is deprecated and will be removed in a future release. Import from defusedxml.ElementTree instead.

parse(), iterparse(), fromstring(), XMLParser

defusedxml.ElementTree

parse(), iterparse(), fromstring(), XMLParser

defusedxml.expatreader

create_parser(), DefusedExpatParser

defusedxml.sax

parse(), parseString(), make_parser()

defusedxml.expatbuilder

parse(), parseString(), DefusedExpatBuilder, DefusedExpatBuilderNS

defusedxml.minidom

parse(), parseString()

defusedxml.pulldom

parse(), parseString()

defusedxml.xmlrpc

The fix is implemented as monkey patch for the stdlib's xmlrpc package (3.x) or xmlrpclib module (2.x). The function monkey_patch() enables the fixes, unmonkey_patch() removes the patch and puts the code in its former state.

The monkey patch protects against XML related attacks as well as decompression bombs and excessively large requests or responses. The default setting is 30 MB for requests, responses and gzip decompression. You can modify the default by changing the module variable MAX_DATA. A value of -1 disables the limit.

defusedxml.lxml

DEPRECATED The module is deprecated and will be removed in a future release.

lxml is safe against most attack scenarios. lxml uses libxml2 for parsing XML. The library has builtin mitigations against billion laughs and quadratic blowup attacks. The parser allows a limit amount of entity expansions, then fails. lxml also disables network access by default. libxml2 lxml FAQ lists additional recommendations for safe parsing, for example counter measures against compression bombs.

The default parser resolves entities and protects against huge trees and deeply nested entities. To disable entities expansion, use a custom parser object:

from lxml import etree

parser = etree.XMLParser(resolve_entities=False)
root = etree.fromstring("<example/>", parser=parser)

The module acts as an example how you could protect code that uses lxml.etree. It implements a custom Element class that filters out Entity instances, a custom parser factory and a thread local storage for parser instances. It also has a check_docinfo() function which inspects a tree for internal or external DTDs and entity declarations. In order to check for entities lxml > 3.0 is required.

parse(), fromstring() RestrictedElement, GlobalParserTLS, getDefaultParser(), check_docinfo()

defusedexpat

The defusedexpat package (defusedexpat on PyPI) is no longer supported. expat parser 2.4.0 and newer come with billion laughs protection against XML bombs.

How to avoid XML vulnerabilities

Update to Python 3.6.8, 3.7.1, or newer. The SAX and DOM parser do not load external entities from files or network resources.

Update to expat to 2.4.0 or newer. It has billion laughs protection with sensible default limits to mitigate billion laughs and quadratic blowup.

Official binaries from python.org use libexpat 2.4.0 since 3.7.12, 3.8.12, 3.9.7, and 3.10.0 (August 2021). Third party vendors may use older or newer versions of expat. pyexpat.version_info contains the current runtime version of libexpat. Vendors may have backported fixes to older versions without bumping the version number.

Example:

import sys
import pyexpat

has_mitigations = (
    sys.version_info >= (3, 7, 1) and
    pyexpat.version_info >= (2, 4, 0)
)

Best practices

  • Don't allow DTDs
  • Don't expand entities
  • Don't resolve externals
  • Limit parse depth
  • Limit total input size
  • Limit parse time
  • Favor a SAX or iterparse-like parser for potential large data
  • Validate and properly quote arguments to XSL transformations and XPath queries
  • Don't use XPath expression from untrusted sources
  • Don't apply XSL transformations that come untrusted sources

(based on Brad Hill's Attacking XML Security)

Other things to consider

XML, XML parsers and processing libraries have more features and possible issue that could lead to DoS vulnerabilities or security exploits in applications. I have compiled an incomplete list of theoretical issues that need further research and more attention. The list is deliberately pessimistic and a bit paranoid, too. It contains things that might go wrong under daffy circumstances.

attribute blowup / hash collision attack

XML parsers may use an algorithm with quadratic runtime O(n 2) to handle attributes and namespaces. If it uses hash tables (dictionaries) to store attributes and namespaces the implementation may be vulnerable to hash collision attacks, thus reducing the performance to O(n 2) again. In either case an attacker is able to forge a denial of service attack with an XML document that contains thousands upon thousands of attributes in a single node.

I haven't researched yet if expat, pyexpat or libxml2 are vulnerable.

decompression bomb

The issue of decompression bombs (aka ZIP bomb) apply to all XML libraries that can parse compressed XML stream like gzipped HTTP streams or LZMA-ed files. For an attacker it can reduce the amount of transmitted data by three magnitudes or more. Gzip is able to compress 1 GiB zeros to roughly 1 MB, lzma is even better:

$ dd if=/dev/zero bs=1M count=1024 | gzip > zeros.gz
$ dd if=/dev/zero bs=1M count=1024 | lzma -z > zeros.xy
$ ls -sh zeros.*
1020K zeros.gz
 148K zeros.xy

None of Python's standard XML libraries decompress streams except for xmlrpclib. The module is vulnerable <https://bugs.python.org/issue16043> to decompression bombs.

lxml can load and process compressed data through libxml2 transparently. libxml2 can handle even very large blobs of compressed data efficiently without using too much memory. But it doesn't protect applications from decompression bombs. A carefully written SAX or iterparse-like approach can be safe.

Processing Instruction

PI's like:

<?xml-stylesheet type="text/xsl" href="style.xsl"?>

may impose more threats for XML processing. It depends if and how a processor handles processing instructions. The issue of URL retrieval with network or local file access apply to processing instructions, too.

Other DTD features

DTD has more features like <!NOTATION>. I haven't researched how these features may be a security threat.

XPath

XPath statements may introduce DoS vulnerabilities. Code should never execute queries from untrusted sources. An attacker may also be able to create an XML document that makes certain XPath queries costly or resource hungry.

XPath injection attacks

XPath injeciton attacks pretty much work like SQL injection attacks. Arguments to XPath queries must be quoted and validated properly, especially when they are taken from the user. The page Avoid the dangers of XPath injection list some ramifications of XPath injections.

Python's standard library doesn't have XPath support. Lxml supports parameterized XPath queries which does proper quoting. You just have to use its xpath() method correctly:

# DON'T
>>> tree.xpath("/tag[@id='%s']" % value)

# instead do
>>> tree.xpath("/tag[@id=$tagid]", tagid=name)

XInclude

XML Inclusion is another way to load and include external files:

<root xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="filename.txt" parse="text" />
</root>

This feature should be disabled when XML files from an untrusted source are processed. Some Python XML libraries and libxml2 support XInclude but don't have an option to sandbox inclusion and limit it to allowed directories.

XMLSchema location

A validating XML parser may download schema files from the information in a xsi:schemaLocation attribute.

<ead xmlns="urn:isbn:1-931666-22-9"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="urn:isbn:1-931666-22-9 http://www.loc.gov/ead/ead.xsd">
</ead>

XSL Transformation

You should keep in mind that XSLT is a Turing complete language. Never process XSLT code from unknown or untrusted source! XSLT processors may allow you to interact with external resources in ways you can't even imagine. Some processors even support extensions that allow read/write access to file system, access to JRE objects or scripting with Jython.

Example from Attacking XML Security for Xalan-J:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime"
 xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object"
 exclude-result-prefixes= "rt ob">
 <xsl:template match="/">
   <xsl:variable name="runtimeObject" select="rt:getRuntime()"/>
   <xsl:variable name="command"
     select="rt:exec($runtimeObject, &apos;c:\Windows\system32\cmd.exe&apos;)"/>
   <xsl:variable name="commandAsString" select="ob:toString($command)"/>
   <xsl:value-of select="$commandAsString"/>
 </xsl:template>
</xsl:stylesheet>

Related CVEs

CVE-2013-1664
Unrestricted entity expansion induces DoS vulnerabilities in Python XML libraries (XML bomb)

CVE-2013-1665
External entity expansion in Python XML libraries inflicts potential security flaws and DoS vulnerabilities

Other languages / frameworks

Several other programming languages and frameworks are vulnerable as well. A couple of them are affected by the fact that libxml2 up to 2.9.0 has no protection against quadratic blowup attacks. Most of them have potential dangerous default settings for entity expansion and external entities, too.

Perl

Perl's XML::Simple is vulnerable to quadratic entity expansion and external entity expansion (both local and remote).

Ruby

Ruby's REXML document parser is vulnerable to entity expansion attacks (both quadratic and exponential) but it doesn't do external entity expansion by default. In order to counteract entity expansion you have to disable the feature:

REXML::Document.entity_expansion_limit = 0

libxml-ruby and hpricot don't expand entities in their default configuration.

PHP

PHP's SimpleXML API is vulnerable to quadratic entity expansion and loads entities from local and remote resources. The option LIBXML_NONET disables network access but still allows local file access. LIBXML_NOENT seems to have no effect on entity expansion in PHP 5.4.6.

C# / .NET / Mono

Information in XML DoS and Defenses (MSDN) suggest that .NET is vulnerable with its default settings. The article contains code snippets how to create a secure XML reader:

XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = false;
settings.MaxCharactersFromEntities = 1024;
settings.XmlResolver = null;
XmlReader reader = XmlReader.Create(stream, settings);

Java

Untested. The documentation of Xerces and its Xerces SecurityMananger sounds like Xerces is also vulnerable to billion laugh attacks with its default settings. It also does entity resolving when an org.xml.sax.EntityResolver is configured. I'm not yet sure about the default setting here.

Java specialists suggest to have a custom builder factory:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setXIncludeAware(False);
builderFactory.setExpandEntityReferences(False);
builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, True);
# either
builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", True);
# or if you need DTDs
builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", False);
builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", False);
builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", False);
builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", False);

TODO

  • DOM: Use xml.dom.xmlbuilder options for entity handling
  • SAX: take feature_external_ges and feature_external_pes (?) into account
  • test experimental monkey patching of stdlib modules
  • improve documentation

License

Copyright (c) 2013-2023 by Christian Heimes <[email protected]>

Licensed to PSF under a Contributor Agreement.

See https://www.python.org/psf/license for licensing details.

Acknowledgements

Brett Cannon (Python Core developer)
review and code cleanup

Antoine Pitrou (Python Core developer)
code review

Aaron Patterson, Ben Murphy and Michael Koziarski (Ruby community)
Many thanks to Aaron, Ben and Michael from the Ruby community for their report and assistance.

Thierry Carrez (OpenStack)
Many thanks to Thierry for his report to the Python Security Response Team on behalf of the OpenStack security team.

Carl Meyer (Django)
Many thanks to Carl for his report to PSRT on behalf of the Django security team.

Daniel Veillard (libxml2)
Many thanks to Daniel for his insight and assistance with libxml2.

semantics GmbH (https://www.semantics.de/)
Many thanks to my employer semantics for letting me work on the issue during working hours as part of semantics's open source initiative.

References

Changelog

defusedxml 0.8.0

Release date: 2023

  • Fix testing without lxml
  • Test on 3.13-dev and PyPy 3.9

defusedxml 0.8.0rc2

Release date: 29-Sep-2023

  • Silence deprecation warning in defuse_stdlib.
  • Update lxml safety information

defusedxml 0.8.0rc1

Release date: 26-Sep-2023

  • Drop support for Python 2.7, 3.4, and 3.5.
  • Test on 3.10, 3.11, and 3.12.
  • Add defusedxml.ElementTree.fromstringlist()
  • Update vulnerabilities and features table in README.
  • Pending removal The defusedxml.lxml module has been unmaintained and deprecated since 2019. The module will be removed in the next version.
  • Pending removal The defusedxml.cElementTree will be removed in the next version. Please use defusedxml.ElementTree instead.

defusedxml 0.7.1

Release date: 08-Mar-2021

  • Fix regression defusedxml.ElementTree.ParseError (#63) The ParseError exception is now the same class object as xml.etree.ElementTree.ParseError again.

defusedxml 0.7.0

Release date: 4-Mar-2021

  • No changes

defusedxml 0.7.0rc2

Release date: 12-Jan-2021

  • Re-add and deprecate defusedxml.cElementTree
  • Use GitHub Actions instead of TravisCI
  • Restore ElementTree attribute of xml.etree module after patching

defusedxml 0.7.0rc1

Release date: 04-May-2020

  • Add support for Python 3.9
  • defusedxml.cElementTree is not available with Python 3.9.
  • Python 2 is deprecate. Support for Python 2 will be removed in 0.8.0.

defusedxml 0.6.0

Release date: 17-Apr-2019

  • Increase test coverage.
  • Add badges to README.

defusedxml 0.6.0rc1

Release date: 14-Apr-2019

  • Test on Python 3.7 stable and 3.8-dev
  • Drop support for Python 3.4
  • No longer pass html argument to XMLParse. It has been deprecated and ignored for a long time. The DefusedXMLParser still takes a html argument. A deprecation warning is issued when the argument is False and a TypeError when it's True.
  • defusedxml now fails early when pyexpat stdlib module is not available or broken.
  • defusedxml.ElementTree.__all__ now lists ParseError as public attribute.
  • The defusedxml.ElementTree and defusedxml.cElementTree modules had a typo and used XMLParse instead of XMLParser as an alias for DefusedXMLParser. Both the old and fixed name are now available.

defusedxml 0.5.0

Release date: 07-Feb-2017

  • No changes

defusedxml 0.5.0.rc1

Release date: 28-Jan-2017

  • Add compatibility with Python 3.6
  • Drop support for Python 2.6, 3.1, 3.2, 3.3
  • Fix lxml tests (XMLSyntaxError: Detected an entity reference loop)

defusedxml 0.4.1

Release date: 28-Mar-2013

  • Add more demo exploits, e.g. python_external.py and Xalan XSLT demos.
  • Improved documentation.

defusedxml 0.4

Release date: 25-Feb-2013

  • As per http://seclists.org/oss-sec/2013/q1/340 please REJECT CVE-2013-0278, CVE-2013-0279 and CVE-2013-0280 and use CVE-2013-1664, CVE-2013-1665 for OpenStack/etc.
  • Add missing parser_list argument to sax.make_parser(). The argument is ignored, though. (thanks to Florian Apolloner)
  • Add demo exploit for external entity attack on Python's SAX parser, XML-RPC and WebDAV.

defusedxml 0.3

Release date: 19-Feb-2013

  • Improve documentation

defusedxml 0.2

Release date: 15-Feb-2013

  • Rename ExternalEntitiesForbidden to ExternalReferenceForbidden
  • Rename defusedxml.lxml.check_dtd() to check_docinfo()
  • Unify argument names in callbacks
  • Add arguments and formatted representation to exceptions
  • Add forbid_external argument to all functions and classes
  • More tests
  • LOTS of documentation
  • Add example code for other languages (Ruby, Perl, PHP) and parsers (Genshi)
  • Add protection against XML and gzip attacks to xmlrpclib

defusedxml 0.1

Release date: 08-Feb-2013

  • Initial and internal release for PSRT review

defusedxml's People

Contributors

brettcannon avatar freddrake avatar jdufresne avatar jwilk avatar kianmeng avatar tiran avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

defusedxml's Issues

equivalent of lxml.objectify cleanup_namespaces in defusedxml

I am getting below error in bandit. Using lxml.etree.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace lxml.etree.parse with its defusedxml equivalent function.

I want the below code's equivlent with defusedxml.

`from lxml import etree, objectify
def fn_read_xml_root(xml_file):
"""
function open xml and remove annotation and return the root node
xml_file : xml file to be parsed
"""
with open(xml_file, "r", encoding="utf-8") as x_file:
xml_data = x_file.read()

parser = etree.XMLParser(remove_blank_text=True)
xtree = etree.parse(xml_file, parser)
xroot = xtree.getroot()
for elem in xroot.getiterator():
    if not hasattr(elem.tag, "find"):
        continue  # (1)
    idx = elem.tag.find("}")
    if idx >= 0:
        elem.tag = elem.tag[idx + 1:]
objectify.deannotate(xroot, cleanup_namespaces=True)
# return xml data and root node of the file
return xml_data, xroot`

https://stackoverflow.com/questions/69237690/equivalent-of-lxml-objectify-cleanup-namespaces-in-defusedxml

custom parser in fromstring not working

i have a custom parser that works in parse() but not in fromstring() :
it seems that the fromstring function doesn't use it

from ssxtd.semi_structured_xml_to_dict import DictBuilder
import defusedxml.ElementTree as DET
from io import BytesIO

a = b'<animals><i>John the <b>real</b> chicken</i><i>John the <b>real</b> chicken</i></animals>\n'
parser = DET.XMLParser(target=DictBuilder())
root = DET.fromstring(a, parser)
print(type(root))

b = BytesIO('''
<animals><i>John the <b>real</b> chicken</i></animals>
'''.encode('utf-8'))

parser = DET.XMLParser(target=DictBuilder())
tree = DET.parse(b, parser)
root = tree.getroot()
print(type(root))

<class 'xml.etree.ElementTree.Element'>
<class 'dict'>

etree is not found in lxml 4

Hi I am receiving this error:

from lxml import etree as _etree
ImportError: cannot import name 'etree'

I am using lxml 4.2.5 but according to the documentation defusedxml supports lxml > 3

Expose defusedxml.ElementTree.ParseError in __all__

If defusedxml.ElementTree.fromstring fails, it produces an error that can only be caught with defusedxml.ElementTree.ParseError, not the standard xml.etree.ElementTree.ParseError. Example:

>>> from xml.etree.ElementTree import ParseError as std_ParseError
>>> from defusedxml.ElementTree import fromstring, ParseError as defused_ParseError
>>> 
>>> try:
...     fromstring('sdfsfsdf')
... except std_ParseError:
...     print('XXX')
... except defused_ParseError:
...     print('YYY')
YYY

But defusedxml.ElementTree.ParseError is not exposed in defusedxml.ElementTree.__all__, so linters complain about the import statement.

Unexpected behaviour with ElementTree.ParseError

Hello,

No sure if it is a bug or feature, but this is certainly a regression in 0.7.0. To reproduce:

import defusedxml.ElementTree
import xml.etree.ElementTree

try:
    defusedxml.ElementTree.fromstring("")
    print("OK")
except xml.etree.ElementTree.ParseError as e:
    print("PARSEERROR", e.__class__)
except Exception as e:
    print("NOT PARSEERROR", e.__class__)

which outputs:

NOT PARSEERROR <class 'xml.etree.ElementTree.ParseError'>

Unsurprisingly, it can be bisected to:

commit 3a48453780793c3e98251b0139e9e89e310fb617 (HEAD, refs/bisect/bad)
Author: Christian Heimes <[email protected]>
Date:   Tue Jan 12 16:37:17 2021 +0100

    Restore xml.etree.ElementTree after patch
    
    Restore ``ElementTree`` attribute of ``xml.etree`` module after patching

Is this a bug or should we do this in a different manner? Regardless, this is very confusing.

Thanks.

LXML XML Schema retrieval vulnerability

LXML has a XML Schema retrieval vulnerability that's not fixed by defusedxml.

Vulnerable calling code looks like this:

    with open(schema_path) as fp:
        schema = lxml.etree.XMLSchema(lxml.etree.parse(fp))

Where the schema file (directly or indirectly) accidentally imports a file from HTTP:

<xs:import namespace="http://www.w3.org/XML/1998/namespace"
           schemaLocation="http://www.w3.org/2001/xml.xsd" />

Note that in my case the actual parse() call is safe because it's parsing a trusted local file, it's the XMLSchema() call that is vulnerable, because that resolves xs:import statements.

While the schema I'm parsing is from a local file, I discovered that my XML schema accidentally includes a schema from HTTP, so this does an insecure HTTP request to http://www.w3.org/2001/xml.xsd . That fails if the network is down, and would also allow a malicious attacker to replace the schema and cause problems. There are multiple levels of include between the XML Schema file I started with and the one that contains the HTTP URL, so this wasn't obvious.

Here's the corresponding LXML issue (from 2013): https://bugs.launchpad.net/lxml/+bug/1234114

The LXML people decided it was not a security issue, because it is caused by user misconfiguration - my schema files shouldn't be including schemas from HTTP. I think it is insecure-by-default in LXML and it is very easy to accidentally make a vulnerable program. It's not clear how a I'm supposed to notice this misconfiguration when it works fine in testing. It's also not clear how I can stop this bug from being reintroduced by other developers working on this project, or even write a test case for this.

I was hoping there would be something like defusedxml.lxml.XMLSchema() that I could use, but that doesn't seem to exist.

Please can defusedxml at least document this vulnerability in the LXML section, and ideally provide a safe replacement for the XMLSchema() function?

Calling defuse_stdlib() raises a DeprecationWarning error with python -W

$ python -W error -c 'import defusedxml; defusedxml.defuse_stdlib()'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/jamison/.local/lib/python3.9/site-packages/defusedxml/__init__.py", line 30, in defuse_stdlib
    from . import cElementTree
  File "/home/jamison/.local/lib/python3.9/site-packages/defusedxml/cElementTree.py", line 38, in <module>
    warnings.warn(
DeprecationWarning: defusedxml.cElementTree is deprecated, import from defusedxml.ElementTree instead.
$ pip freeze | grep defusedxml
defusedxml==0.7.1

defusedxml has no method of registering namespaces.

As the title says, there is no equivalent of https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.register_namespace

The reason this is a problem is that it makes it impossible to verify XML signatures using something like signxml- namespaces are auto-renamed from their proper names to things like 'ns0' and 'ns1' and we have no way of modifying that.

A good example of this is a SAML AuthNRequest, which may start with a tag along the lines of
<saml2p:AuthnRequest xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol" AssertionConsumerServiceURL="[...]

When parsed using defusedxml.ElementTree.parse, it will instead be
<ns0:AuthnRequest xmlns:ns0="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:ns1="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" AssertionConsumerServiceURL="[...]

This obviously fails to match the signature of the XML and the entire thing bombs out. LXML handles with correctly by default, and python's built-in ElementTree offers register_namespace() as seen in https://technotes.shemyak.com/posts/xml-signatures-with-python-elementtree/ which allows you to predefine the namespaces you require, but defusedxml has no equivalent that I can find.

lxml module status

The defusedxml.lxml module states that it is an example. What would make this module better?

I see some things around the lxml parser that seem to be in question, like whether the remove_comments option should be enabled by default, or whether comments should be blacklisted. Do you have an opinion on those, especially in relation to the latest saml vulnerability by duo?

Use XMLParser arguments in DefusedXMLParser

Hello,

How do I use other arguments of XMLParser while using DefusedXMLParser or fromstring method of defusedxml such as the following:

attribute_defaults=False, dtd_validation=False, load_dtd=False, no_network=True, ns_clean=False, recover=False, schema: XMLSchema=None, huge_tree=False, remove_blank_text=False, remove_comments=False, remove_pis=False, strip_cdata=True, collect_ids=True, compact=True.

DefusedXMLParser only uses the following:
html=0, target=None, encoding=None, forbid_dtd=False, forbid_entities=True, forbid_external=True

Thanks

defusedxml reads bytes, not str

Description

If I parse a file with defusedxml into an etree, and then try to write it, I get an error message:

TypeError: write() argument must be str, not bytes

I expect to see a serialized XML string.

My use case: I would like to parse an XML file with defusedxml and write it out without DTD etc, so that I can read it again with lxml, so that I can use its xpath function. I'm still trying to find out if that will work though.

How to reproduce

Create a program readwrite.py:

from defusedxml.ElementTree import parse
import sys

t = parse(sys.argv[1])
t.write(sys.stdout)

Use the test input, dtd.xml:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head/>
    <body>text</body>
</html>

and run it:

$ python readwritexml.py dtd.xml
Traceback (most recent call last):
  File "readwritexml.py", line 5, in <module>
    t.write(sys.stdout)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 772, in write
    serialize(write, self._root, qnames, namespaces,
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/contextlib.py", line 120, in __exit__
    next(self.gen)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/xml/etree/ElementTree.py", line 832, in _get_writer
    yield file.write
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/contextlib.py", line 525, in __exit__
    raise exc_details[1]
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/contextlib.py", line 510, in __exit__
    if cb(*exc_details):
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/contextlib.py", line 382, in _exit_wrapper
    callback(*args, **kwds)
TypeError: write() argument must be str, not bytes

My suspicion is that Python's ElementTree expects the data to be of type str and that defusedxml provides bytes.

import defusedxml.lxml.html

I get an error when trying to use lxml:

>>> import defusedxml.lxml.html
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named html

Importing defusedxml.ElementTree

Importing defusedxml.ElementTree before xml.etree.ElementTree cause the C optimized version (_elementtree) to not load:

>>> import defusedxml.ElementTree
>>> import xml.etree.ElementTree as ET
>>> ET.Element is ET._Element_Py
True

Viceversa works as expected:

>>> import xml.etree.ElementTree as ET
>>> import defusedxml.ElementTree
>>> ET.Element is ET._Element_Py
False

Best,
Davide

Ignore DTD when parsing with SAX

I want to ignore the declaration when parsing in an XML document using the SAX parser.

An example of such a declaration (from a PubMed XML file):
<!DOCTYPE PubmedArticleSet SYSTEM "http://dtd.nlm.nih.gov/ncbi/pubmed/out/pubmed_190101.dtd">

What happens currently: I get a ExternalReferenceForbidden error, and the parser quits.

What I want to happen: It ignores the declaration (possibly outputting a warning) and continues to process the rest of the file.

It's possible that what I want can already be done; if that's the case, then I'd like either documentation that explains how to do it, or sample code that can be modified for use.

I posted a query at Stack Overflow (https://stackoverflow.com/questions/67328148/) asking how to do this, but did not get any responses.

I'll include an excerpt of my Python code below.

`def ProcessXMLFile(
SAXParser = defusedxml.sax.make_parser()
SAXParser.setContentHandler(ElementHandler()
ContentHandler = SAXParser.getContentHandler()
Input = xml.sax.InputSource()
Input.setCharacterStream(strXMLFile)
Input.setEncoding('utf-8')
SAXParser.parse(Input.getCharacterStream())

class ElementHandler(xml.sax.handler.ContentHandler):
<init(), startElement(), endElement() etc. here>
`

LXML DeprecationWarning

DeprecationWarning: defusedxml.lxml is no longer supported and will be removed in a future release.

File "/usr/local/lib/python2.7/dist-packages/defusedxml/lxml.py", line 29, in
stacklevel=2,

Why was this added? Can I help fix it?

[QUESTION] Retaining XML comments during parse

We would like to retain comments in an XML object. We used to do this as follows

import xml.etree.ElementTree as Et
self.__xml_tree = Et.parse(path, Et.XMLParser(target=Et.TreeBuilder(insert_comments=True), encoding="utf-8"))

Can I retain comments in my parse object with defusedxml?
Thank you

defusedxml lacks an Element class

defusedxml currently lacks an Element class. In order to implement return types on functions that return an Element, currently you need to leverage xml.etree.ElementTree.Element, which then causes issues when using the discovery feature of unittest.

Here is an example error message that unittest can show when mixing xml.etree.ElementTree and defusedxml.

======================================================================
FAIL: test_parse_xml (XYZ)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/jonzeolla/src/abc/tests/test_api_functions.py", line 155, in test_parse_xml
    self.assertIs(
AssertionError: <class 'xml.etree.ElementTree.Element'> is not <class 'xml.etree.ElementTree.Element'>

----------------------------------------------------------------------

Element.append() does not work with defusedxml?

See the script below. This works as expected.

# from defusedxml.ElementTree import fromstring
import xml.etree.ElementTree as ET

THE_XML = "<ListOfItems></ListOfItems>"
# xml = fromstring(THE_XML)
xml = ET.fromstring(THE_XML)
item = ET.Element('Item')
xml.append(item)

However it I swap for the version that uses defusedxml then I get this error:

Traceback (most recent call last):
File "c:\temp\defusing.py", line 7, in <module>
    xml.append(item)
TypeError: append() argument must be xml.etree.ElementTree.Element, not Element

Is this caused by defusedxml or is this some subtle difference between the C and Python implementations of xml.etree.Elementree?

Using unicode with xml.dom.minidom and defusedxml.minidom does not behave the same

Hi there,

Thanks for a great lib.

I have noticed the following that I tought might be a bug:

Calling

xml.dom.minidom.parse()

with unicode behaves the same as calling it with str whereas

defusedxml.minidom.parse()

does not.

This seems due to the fact that cpython uses isinstance(file, StringTypes) source

when defusedxml uses isinstance(file, str) source.

Should defusedxml align with the standard lib?

Still doesn't work with Python 3.6

1d34223 is not sufficient to make defusedxml work properly with Python 3.6. It stops defusedxml outright choking in _get_py3_cls, but it doesn't work properly. It results in common._generate_etree_functions() failing, as can be seen in the 10 failed tests from the Travis run for that commit.

I naively attempted just changing the if PY26 or PY31: condition in _generate_etree_functions() to if PY26 or PY31 or sys.version_info >= (3, 6): , but that's not good enough either because that code really is tailored to the Python 2.6 / 3.1 implementation; it doesn't work at all for the Python 3.6 implementation. It seems like we need an entirely new approach to defusing iterparse for 3.6, but I'm not smart enough to write that. At least, not at this time in the morning...

This is a bit of a problem for us (Fedora) as Python 3.6 landed in Rawhide today, and now defusedxml won't install and can't be rebuilt (unless we ignore the fact that it's broken and disable the tests...), and several things that depend on it can't install or be rebuilt either.

Question about validating xml by its schema

Hello,

In lxml to validate an xml, we can parse it and use validate function to validate by schema. This schema can be get by RelaxNG.
The question is how do I validate an xml using defusedxml? And also print errors when the given xml is invalid.

Thanks

Question regarding forbid_dtd

Why do many of the parsing functions explicitly default forbid_dtd to False? It seems like the secure default would be to enable this option, and allow it to be manually disabled.

Without it it appears as though consumers are vulnerable to schema poisoning attacks.

The html argument of XMLParser() is deprecated in python3.7

I think the title says all, however here is the actual warning message.

/Users/debashisdip/.local/share/virtualenvs/EA_SA_805-YTDxf4Xg/lib/python3.7/site-packages/defusedxml/ElementTree.py:68: DeprecationWarning: The html argument of XMLParser() is deprecated
  _XMLParser.__init__(self, html, target, encoding)

tostring(RestrictedElement('X')) produces funky output

>>> from defusedxml.lxml import RestrictedElement, tostring
>>> from lxml.etree import Element
>>> tostring(Element('X'))
b'<X/>'
>>> tostring(RestrictedElement('X'))
b'<RestrictedElement>X</RestrictedElement>'

I was expecting it would serialise to b'<X/>'.

0.7.1: pytest based test suite is failing

+ PYTHONPATH=/home/tkloczko/rpmbuild/BUILDROOT/python-defusedxml-0.7.1-2.fc35.x86_64/usr/lib64/python3.8/site-packages:/home/tkloczko/rpmbuild/BUILDROOT/python-defusedxml-0.7.1-2.fc35.x86_64/usr/lib/python3.8/site-packages
+ /usr/bin/python3 -Bm pytest -ra
=========================================================================== test session starts ============================================================================
platform linux -- Python 3.8.9, pytest-6.2.3, py-1.10.0, pluggy-0.13.1
rootdir: /home/tkloczko/rpmbuild/BUILD/defusedxml-0.7.1, configfile: tox.ini
plugins: forked-1.3.0, shutil-1.7.0, virtualenv-1.7.0, asyncio-0.14.0, expect-1.1.0, cov-2.11.1, mock-3.5.1, httpbin-1.0.0, xdist-2.2.1, flake8-1.0.7, timeout-1.4.2, betamax-0.8.1, pyfakefs-4.4.0, freezegun-0.4.2, flaky-3.7.0, cases-3.4.6, hypothesis-6.10.1, case-1.5.3, isort-1.3.0
collected 91 items

tests.py FFFFFFFFF........F.............F..........................................s.ss...s.........                                                                 [100%]

================================================================================= FAILURES =================================================================================
______________________________________________________________________ BaseTests.test_allow_expansion ______________________________________________________________________

self = <tests.BaseTests testMethod=test_allow_expansion>

    def test_allow_expansion(self):
>       self.parse(self.xml_bomb2, forbid_entities=False)
E       AttributeError: 'BaseTests' object has no attribute 'parse'

tests.py:177: AttributeError
_______________________________________________________________________ BaseTests.test_dtd_forbidden _______________________________________________________________________

self = <tests.BaseTests testMethod=test_dtd_forbidden>

    def test_dtd_forbidden(self):
>       self.assertRaises(DTDForbidden, self.parse, self.xml_bomb, forbid_dtd=True)
E       AttributeError: 'BaseTests' object has no attribute 'parse'

tests.py:130: AttributeError
___________________________________________________________________ BaseTests.test_dtd_with_external_ref ___________________________________________________________________

self = <tests.BaseTests testMethod=test_dtd_with_external_ref>

    def test_dtd_with_external_ref(self):
        if self.dtd_external_ref:
            self.assertRaises(self.external_ref_exception, self.parse, self.xml_dtd)
        else:
>           self.parse(self.xml_dtd)
E           AttributeError: 'BaseTests' object has no attribute 'parse'

tests.py:158: AttributeError
____________________________________________________________________ BaseTests.test_entities_forbidden _____________________________________________________________________

self = <tests.BaseTests testMethod=test_entities_forbidden>

    def test_entities_forbidden(self):
>       self.assertRaises(EntitiesForbidden, self.parse, self.xml_bomb)
E       AttributeError: 'BaseTests' object has no attribute 'parse'

tests.py:109: AttributeError
_______________________________________________________________________ BaseTests.test_entity_cycle ________________________________________________________________________

self = <tests.BaseTests testMethod=test_entity_cycle>

    def test_entity_cycle(self):
>       self.assertRaises(self.cyclic_error, self.parse, self.xml_cyclic, forbid_entities=False)
E       AttributeError: 'BaseTests' object has no attribute 'parse'

tests.py:127: AttributeError
_____________________________________________________________________ BaseTests.test_external_file_ref _____________________________________________________________________

self = <tests.BaseTests testMethod=test_external_file_ref>

    def test_external_file_ref(self):
        content = self.get_content(self.xml_external_file)
        if isinstance(content, bytes):
            here = HERE.encode(sys.getfilesystemencoding())
            content = content.replace(b"/PATH/TO", here)
        else:
            content = content.replace("/PATH/TO", HERE)
        self.assertRaises(
>           self.external_ref_exception, self.parseString, content, forbid_entities=False
        )
E       AttributeError: 'BaseTests' object has no attribute 'parseString'

tests.py:173: AttributeError
_______________________________________________________________________ BaseTests.test_external_ref ________________________________________________________________________

self = <tests.BaseTests testMethod=test_external_ref>

    def test_external_ref(self):
        self.assertRaises(
>           self.external_ref_exception, self.parse, self.xml_external, forbid_entities=False
        )
E       AttributeError: 'BaseTests' object has no attribute 'parse'

tests.py:162: AttributeError
_______________________________________________________________________ BaseTests.test_simple_parse ________________________________________________________________________

self = <tests.BaseTests testMethod=test_simple_parse>

    def test_simple_parse(self):
>       self.parse(self.xml_simple)
E       AttributeError: 'BaseTests' object has no attribute 'parse'

tests.py:97: AttributeError
______________________________________________________________________ BaseTests.test_simple_parse_ns ______________________________________________________________________

self = <tests.BaseTests testMethod=test_simple_parse_ns>

    def test_simple_parse_ns(self):
>       self.parse(self.xml_simple_ns)
E       AttributeError: 'BaseTests' object has no attribute 'parse'

tests.py:103: AttributeError
___________________________________________________________________ TestDefusedElementTree.test_html_arg ___________________________________________________________________

self = <tests.TestDefusedElementTree testMethod=test_html_arg>

    def test_html_arg(self):
        with self.assertRaises(DeprecationWarning):
>           ElementTree.XMLParse(html=0)
E           AssertionError: DeprecationWarning not raised

tests.py:202: AssertionError
__________________________________________________________________ TestDefusedcElementTree.test_html_arg ___________________________________________________________________

self = <tests.TestDefusedcElementTree testMethod=test_html_arg>

    def test_html_arg(self):
        with self.assertRaises(DeprecationWarning):
>           ElementTree.XMLParse(html=0)
E           AssertionError: DeprecationWarning not raised

tests.py:202: AssertionError
============================================================================= warnings summary =============================================================================
tests.py::TestDefusedElementTree::test_html_arg
tests.py::TestDefusedcElementTree::test_html_arg
  /home/tkloczko/rpmbuild/BUILD/defusedxml-0.7.1/defusedxml/ElementTree.py:97: DeprecationWarning: 'html' keyword argument is no longer supported. Pass in arguments as keyword arguments.
    warnings.warn(

-- Docs: https://docs.pytest.org/en/stable/warnings.html
========================================================================= short test summary info ==========================================================================
SKIPPED [1] tests.py:129: lxml detects entityt reference loop
SKIPPED [1] tests.py:108: lxml detects entityt reference loop
SKIPPED [1] tests.py:126: lxml detects entityt reference loop
SKIPPED [1] tests.py:367: lxml detects entityt reference loop
FAILED tests.py::BaseTests::test_allow_expansion - AttributeError: 'BaseTests' object has no attribute 'parse'
FAILED tests.py::BaseTests::test_dtd_forbidden - AttributeError: 'BaseTests' object has no attribute 'parse'
FAILED tests.py::BaseTests::test_dtd_with_external_ref - AttributeError: 'BaseTests' object has no attribute 'parse'
FAILED tests.py::BaseTests::test_entities_forbidden - AttributeError: 'BaseTests' object has no attribute 'parse'
FAILED tests.py::BaseTests::test_entity_cycle - AttributeError: 'BaseTests' object has no attribute 'parse'
FAILED tests.py::BaseTests::test_external_file_ref - AttributeError: 'BaseTests' object has no attribute 'parseString'
FAILED tests.py::BaseTests::test_external_ref - AttributeError: 'BaseTests' object has no attribute 'parse'
FAILED tests.py::BaseTests::test_simple_parse - AttributeError: 'BaseTests' object has no attribute 'parse'
FAILED tests.py::BaseTests::test_simple_parse_ns - AttributeError: 'BaseTests' object has no attribute 'parse'
FAILED tests.py::TestDefusedElementTree::test_html_arg - AssertionError: DeprecationWarning not raised
FAILED tests.py::TestDefusedcElementTree::test_html_arg - AssertionError: DeprecationWarning not raised
=========================================================== 11 failed, 76 passed, 4 skipped, 2 warnings in 0.66s ===========================================================

[Question] Correct way to parse HTML with defusedxml?

Heya, thanks for the nice project!

    from defusedxml import ElementTree as etree
    tree = etree.fromstring(bytes(html_content, encoding='utf-8'))

results in mismatched tag: line 47, column 4, however the previous lxml implementation was automatically tolerant of mismatched tags

I dug around in the issue queue and found #31 , #24 and others, but it's not quite clear what the process should be

-    from lxml import etree, html
+    from defusedxml import ElementTree as etree
 
-    tree = html.fromstring(bytes(html_content, encoding='utf-8'))
+    tree = etree.fromstring(bytes(html_content, encoding='utf-8'))

# ( for some background, I'm trying to parse the HTML tree then execute a xpath query 
r = tree.xpath(xpath_filter.strip(), namespaces={'re': 'http://exslt.org/regular-expressions'})

Is there a way to make lxml use defusedxml here for HTML? or am I going about it the right way? Or is it that my understanding of defusedxml sits is wrong?

And what about in the case of arbitrary HTML "from the wild" where there could be hanging/open tags etc? Do I need to supply some kind of "recover=true" ( https://lxml.de/api/lxml.etree.XMLParser-class.html ) ?

thanks again!

defusedxml.xmlrpc fails when expat is not installed

I'm not sure if this is a bug in defusedxml, since I don't know expat is a strict dependency of Python. However, I ran into this when trying to use defusedxml with distroless/python2.7, so maybe it's useful for someone else to know why it happens.

If expat is not installed, import defusedxml.xmlrpc fails with cannot create 'NoneType' instances.

Repro:

> cat Dockerfile
FROM debian:stretch

RUN apt-get update \
    && apt-get -y install \
        python2.7-minimal \
    && rm -rf /var/apt/lists/*

ADD https://github.com/tiran/defusedxml/archive/v0.5.0.tar.gz /
RUN tar xf v0.5.0.tar.gz

RUN rm /lib/*/libexpat*

WORKDIR /defusedxml-0.5.0
CMD python2.7 -c 'import defusedxml.xmlrpc'
> docker build -t dx .  
[SNIP]
Successfully built 24f82ef10dbc
> docker run --rm -it dx
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "defusedxml/xmlrpc.py", line 109, in <module>
    class DefusedExpatParser(ExpatParser):
TypeError: Error when calling the metaclass bases
    cannot create 'NoneType' instances

Cannot use `xpath` and any other functionality from `lxml`

I can see that defusedxml.lxml is deprecated. The question what we should use to gain the functionality of xpath for instance.

When I am trying to do the following:

from defusedxml import ElementTree

et = ElementTree.fromstring("<tag>value</tag>")
et.xpath('')

I got an error:

AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'xpath'

The question is how to use lxml's tree functionality?

importing minidom is causing unexpected errors on macos

My application breaks on MacOS when I uncomment from defusedxml.minidom import parseString -- an import that's not even being used in the current file. Using from xml.dom.minidom import parseString works just fine. But using from defusedxml.minidom import parseString works fine on my linux server.

I get errors with libxmlsec1 about the supplied certificate not matching the one the XML.

Differences from MacOS server and linux server are python versions 2.7.10 vs 2.7.6. Libxmlsec versions 1.2.20 vs 1.2.18.

from defusedxml.lxml import tostring, fromstring
from os.path import basename, dirname, join

# !!!!!!!!!!!!!!!!!!!!
# Uncomment this line and it fails
# !!!!!!!!!!!!!!!!!!!!
#from defusedxml.minidom import parseString

import dm.xmlsec.binding as xmlsec

xml = """<insert xml>"""

pem = """-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----"""

def print_xmlsec_errors(filename, line, func, error_object, error_subject, reason, msg):
    """
    Auxiliary method. It overrides the default xmlsec debug message.
    """

    info = []
    if error_object != "unknown":
        info.append("obj=" + error_object)
    if error_subject != "unknown":
        info.append("subject=" + error_subject)
    if msg.strip():
        info.append("msg=" + msg)
    if reason != 1:
        info.append("errno=%d" % reason)
    if info:
        print "xmlsec1 -- %s:%d(%s)" % (filename, line, func), " ".join(info)

def validate_node_sign(signature_node, elem, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False):
    try:
        xmlsec.initialize()
        xmlsec.set_error_callback(print_xmlsec_errors)

        xmlsec.addIDs(elem, ["ID"])

        print "--- Signature Node ---"
        print tostring(signature_node)
        print "+++ Signature Node +++"

        #file_name = "/Users/fingermark/cacert.pem"

        dsig_ctx = xmlsec.DSigCtx()
        #signKey = xmlsec.Key.load(file_name, xmlsec.KeyDataFormatCertPem, None)
        signKey = xmlsec.Key.loadMemory(pem, xmlsec.KeyDataFormatCertPem)
        #signKey.name = basename(file_name)
        dsig_ctx.signKey = signKey
        print "signKey.name: %s" % signKey.name

        dsig_ctx.setEnabledKeyData([xmlsec.KeyDataX509])
        dsig_ctx.verify(signature_node)

        print "verified"

        return True
    except Exception as err:
        print "Node verification error:"
        print err.__str__()
        return False

if __name__ == "__main__":
    elem = fromstring(xml)
    node = elem.find(".//{%s}Signature" % xmlsec.DSigNs)
    print validate_node_sign(node, elem)

See more:
SAML-Toolkits/python-saml#166 (comment)

defusedxml.ElementTree breaks the xml.etree.ElementTree package

This has already been reported as #43 and #48. I am opening yet another issue for this because the previous issues describe symptoms instead of the underlying problem and I want to spare others from debugging for hours, like I just did.

@marienz has opened the PR #53 to fix this, and provided the following minimal breaking example:

from xml.etree import ElementTree as FirstElementTree
from defusedxml import ElementTree as DefusedElementTree
from xml.etree import ElementTree as SecondElementTree
assert FirstElementTree is SecondElementTree

Attempting to append an element from the FirstElementTree to the SecondElementTree yields the error described in #43:

TypeError: append() argument must be xml.etree.ElementTree.Element, not Element

This bug is bound to affect any larger Python project that uses both defusedxml and python-markdown (see Python-Markdown/markdown/issues/950). Examples of projects affected by this are Jupyter (jupyter/nbviewer/issues/909, danielfrg/pelican-jupyter/issues/124) and Zulip.

@tiran would you mind merging #53 and releasing a new version? Considering that CPython's etree is still vulnerable to billion laughs and quadratic blowup.

LXML Support and XML Validator

Hi developers,

I saw in the defusedxml codes that the lxml will not be supported for the feature releases, do you have a special reason for this? I am asking this due to the lxml XSD validator feature. xmlschema seems the alternative library, however, it is not covered in your tests. How can I combine different library to parse and validate with an XSD schema under defusedxml, if lxml wont be supported anymore.

Thanks for your time!

Best regards
Cem

ElementTree.fromstring broken in Python 3.8

I'm using pygal, which uses cairosvg, which uses defusedxml and I'm getting this error when I use "Python 3.8.0a3":

  File "./alerts.py", line 1013, in <module>
    alert(alertTimeMarkers)
  File "/home/rolf/weather/alert.py", line 305, in __call__
    if self.call(sampleDay, alreadyReportedRecord) is not None:
  File "/home/rolf/weather/dailyRecordAlert.py", line 429, in call
    self.maybePostTweet(
  File "/home/rolf/weather/dailyRecordAlert.py", line 319, in maybePostTweet
    tweet, media = self.tweetText(
  File "/home/rolf/weather/dailyRecordAlert.py", line 123, in tweetText
    self.metarSnowChart(day, field=field, checkMax=recordIsMax) )
  File "/home/rolf/weather/dailyRecordAlert.py", line 47, in metarSnowChart
    return metarSnowChart.main(
  File "/home/rolf/weather/metarSnowChart.py", line 393, in main
    line_chart.render_to_png(fname,
  File "/usr/local/lib/python3.8/site-packages/pygal/graph/public.py", line 119, in render_to_png
    return cairosvg.svg2png(
  File "/usr/local/lib/python3.8/site-packages/cairosvg/__init__.py", line 66, in svg2png
    return surface.PNGSurface.convert(
  File "/usr/local/lib/python3.8/site-packages/cairosvg/surface.py", line 142, in convert
    tree = Tree(
  File "/usr/local/lib/python3.8/site-packages/cairosvg/parser.py", line 400, in __init__
    tree = ElementTree.fromstring(
  File "/usr/local/lib/python3.8/site-packages/defusedxml/common.py", line 113, in fromstring
    parser = DefusedXMLParser(target=_TreeBuilder(),
  File "/usr/local/lib/python3.8/site-packages/defusedxml/ElementTree.py", line 68, in __init__
    _XMLParser.__init__(self, html, target, encoding)
TypeError: __init__() takes 1 positional argument but 4 were given
$ python3.8 -m pip freeze | grep def
defusedxml==0.5.0

I noticed that there is some funny business going on inside ElementTree.py where you are using some hidden functions. Maybe they changed the signatures of those hidden functions?

Is this project abandoned?

Hi @tiran

I have some open issues and unmerged pull requests here that have had no reaction. Just wondering if I should continue to contribute fixes, or if this project has been abandoned?

defusedxml 0.7.1 & Python 3.9 -- TypeError: __init__() takes 1 positional argument but 4 were given

  File "/home/user/main.py", line 6, in <module>
    from openpyxl import Workbook
  File "/var/lib/jenkins/workspace/main/env/lib/python3.9/site-packages/openpyxl/__init__.py", line 6, in <module>
    from openpyxl.workbook import Workbook
  File "/var/lib/jenkins/workspace/main/env/lib/python3.9/site-packages/openpyxl/workbook/__init__.py", line 4, in <module>
    from .workbook import Workbook
  File "/var/lib/jenkins/workspace/main/env/lib/python3.9/site-packages/openpyxl/workbook/workbook.py", line 7, in <module>
    from openpyxl.worksheet.worksheet import Worksheet
  File "/var/lib/jenkins/workspace/main/env/lib/python3.9/site-packages/openpyxl/worksheet/worksheet.py", line 25, in <module>
    from openpyxl.cell import Cell, MergedCell
  File "/var/lib/jenkins/workspace/main/env/lib/python3.9/site-packages/openpyxl/cell/__init__.py", line 3, in <module>
    from .cell import Cell, WriteOnlyCell, MergedCell
  File "/var/lib/jenkins/workspace/main/env/lib/python3.9/site-packages/openpyxl/cell/cell.py", line 28, in <module>
    from openpyxl.styles.styleable import StyleableObject
  File "/var/lib/jenkins/workspace/main/env/lib/python3.9/site-packages/openpyxl/styles/styleable.py", line 14, in <module>
    from .builtins import styles
  File "/var/lib/jenkins/workspace/main/env/lib/python3.9/site-packages/openpyxl/styles/builtins.py", line 1346, in <module>
    ('Normal', NamedStyle.from_tree(fromstring(normal))),
  File "/var/lib/jenkins/workspace/main/env/lib/python3.9/site-packages/defusedxml/common.py", line 113, in fromstring
    parser = DefusedXMLParser(target=_TreeBuilder(),
  File "/var/lib/jenkins/workspace/main/env/lib/python3.9/site-packages/defusedxml/ElementTree.py", line 68, in __init__
    _XMLParser.__init__(self, html, target, encoding)
TypeError: __init__() takes 1 positional argument but 4 were given

cElementTree was removed in Python 3.9

The xml.etree.cElementTree module was removed from Python master (3.9) an favor of the xml.etree.ElementTree module. See PR python/cpython#19108

Since Python 3.9 no longer offers the module, it makes sense to me to also remove the module from defusedxml.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.