97 points · by mikeknoop · 11y ago · 16 comments
Recent versions of libxml (2.9.0+) disable external entity loading by default, so any implementation based on libxml (such as PHP's SimpleXML) should be secure as long as the defaults are left untouched. But if you use an XML parser implemented natively in another language, or one that links to an older version of libxml, you should look really carefully at the default settings.
If you use Python, use defusedxml:
https://pypi.python.org/pypi/defusedxml
It's a drop-in replacement for the stdlib XML parsers and lxml which makes it trivial to import an instance with secure defaults – to quote the docs:
Instead of:
>>> from xml.etree.ElementTree import parse
>>> et = parse(xmlfile)
alter code to:
>>> from defusedxml.ElementTree import parse
>>> et = parse(xmlfile) curl -i https://gist.githubusercontent.com/mikeknoop/e7b3c526738b66950eb4/raw/1d46d432ed380abc986cf15028221318b836395b/text.xml
// other headers...
Content-Type: text/plain
// headers and body...
There is a great service call rawgit[1] that does actually add the correct headers.Updating the post, thank you!
Even so, we as a team of 8 didn't catch the problem for some time because we weren't aware of it. That's part of my rational for giving an easy-to-test-yourself POC.
It has a module which "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."
It sounds like it would have defused your example of lxml, and perhaps a few others you haven't considered.
Seems like parsers should at least disable file-based external entity URIs by default.