-
Notifications
You must be signed in to change notification settings - Fork 52
/
tests.py
605 lines (472 loc) · 20.3 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
from __future__ import print_function
import io
import os
import sys
import unittest
import warnings
from unittest import mock
from xml.etree import ElementTree as orig_elementtree
from xml.etree.ElementTree import Element as ElementBeforeImport
from xml.sax.saxutils import XMLGenerator
from xml.sax import SAXParseException
from pyexpat import ExpatError
from defusedxml import ElementTree, minidom, pulldom, sax, xmlrpc, expatreader
from defusedxml import defuse_stdlib
from defusedxml import (
DTDForbidden,
EntitiesForbidden,
ExternalReferenceForbidden,
NotSupportedError,
)
from xml.etree.ElementTree import Element as ElementAfterImport
if sys.version_info < (3, 7):
warnings.filterwarnings("once", category=DeprecationWarning)
with warnings.catch_warnings(record=True) as cetree_warnings:
from defusedxml import cElementTree
try:
import gzip
except ImportError:
gzip = None
try:
with warnings.catch_warnings(record=True) as lxml_warnings:
from defusedxml import lxml
from lxml import etree as lxml_etree
LXML3 = lxml.LXML3
except ImportError:
lxml = None
lxml_etree = None
LXML3 = False
lxml_warnings = None
warnings.filterwarnings("always", category=DeprecationWarning, module=r"defusedxml\..*")
HERE = os.path.dirname(os.path.abspath(__file__))
# prevent web access
# based on Debian's rules, Port 9 is discard
os.environ["http_proxy"] = "http://127.0.9.1:9"
os.environ["https_proxy"] = os.environ["http_proxy"]
os.environ["ftp_proxy"] = os.environ["http_proxy"]
class DefusedTestCase(unittest.TestCase):
content_binary = False
xml_dtd = os.path.join(HERE, "xmltestdata", "dtd.xml")
xml_external = os.path.join(HERE, "xmltestdata", "external.xml")
xml_external_file = os.path.join(HERE, "xmltestdata", "external_file.xml")
xml_quadratic = os.path.join(HERE, "xmltestdata", "quadratic.xml")
xml_simple = os.path.join(HERE, "xmltestdata", "simple.xml")
xml_simple_ns = os.path.join(HERE, "xmltestdata", "simple-ns.xml")
xml_bomb = os.path.join(HERE, "xmltestdata", "xmlbomb.xml")
xml_bomb2 = os.path.join(HERE, "xmltestdata", "xmlbomb2.xml")
xml_cyclic = os.path.join(HERE, "xmltestdata", "cyclic.xml")
xml_dtd_element = os.path.join(HERE, "xmltestdata", "dtd_element.xml")
xml_schema_include = os.path.join(HERE, "xmltestdata", "schema-include.xsd")
def get_content(self, xmlfile):
mode = "rb" if self.content_binary else "r"
with io.open(xmlfile, mode) as f:
data = f.read()
return data
class BaseTests(DefusedTestCase):
module = None
dtd_external_ref = False
external_ref_exception = ExternalReferenceForbidden
cyclic_error = None
iterparse = None
def test_simple_parse(self):
self.parse(self.xml_simple)
self.parseString(self.get_content(self.xml_simple))
if self.iterparse:
self.iterparse(self.xml_simple)
def test_simple_parse_ns(self):
self.parse(self.xml_simple_ns)
self.parseString(self.get_content(self.xml_simple_ns))
if self.iterparse:
self.iterparse(self.xml_simple_ns)
def test_entities_forbidden(self):
self.assertRaises(EntitiesForbidden, self.parse, self.xml_bomb)
self.assertRaises(EntitiesForbidden, self.parse, self.xml_quadratic)
self.assertRaises(EntitiesForbidden, self.parse, self.xml_external)
self.assertRaises(EntitiesForbidden, self.parseString, self.get_content(self.xml_bomb))
self.assertRaises(
EntitiesForbidden, self.parseString, self.get_content(self.xml_quadratic)
)
self.assertRaises(
EntitiesForbidden, self.parseString, self.get_content(self.xml_external)
)
if self.iterparse:
self.assertRaises(EntitiesForbidden, self.iterparse, self.xml_bomb)
self.assertRaises(EntitiesForbidden, self.iterparse, self.xml_quadratic)
self.assertRaises(EntitiesForbidden, self.iterparse, self.xml_external)
def test_entity_cycle(self):
self.assertRaises(self.cyclic_error, self.parse, self.xml_cyclic, forbid_entities=False)
def test_dtd_forbidden(self):
self.assertRaises(DTDForbidden, self.parse, self.xml_bomb, forbid_dtd=True)
self.assertRaises(DTDForbidden, self.parse, self.xml_quadratic, forbid_dtd=True)
self.assertRaises(DTDForbidden, self.parse, self.xml_external, forbid_dtd=True)
self.assertRaises(DTDForbidden, self.parse, self.xml_dtd, forbid_dtd=True)
self.assertRaises(
DTDForbidden, self.parseString, self.get_content(self.xml_bomb), forbid_dtd=True
)
self.assertRaises(
DTDForbidden, self.parseString, self.get_content(self.xml_quadratic), forbid_dtd=True
)
self.assertRaises(
DTDForbidden, self.parseString, self.get_content(self.xml_external), forbid_dtd=True
)
self.assertRaises(
DTDForbidden, self.parseString, self.get_content(self.xml_dtd), forbid_dtd=True
)
if self.iterparse:
self.assertRaises(DTDForbidden, self.iterparse, self.xml_bomb, forbid_dtd=True)
self.assertRaises(DTDForbidden, self.iterparse, self.xml_quadratic, forbid_dtd=True)
self.assertRaises(DTDForbidden, self.iterparse, self.xml_external, forbid_dtd=True)
self.assertRaises(DTDForbidden, self.iterparse, self.xml_dtd, forbid_dtd=True)
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)
def test_external_ref(self):
self.assertRaises(
self.external_ref_exception, self.parse, self.xml_external, forbid_entities=False
)
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
)
def test_allow_expansion(self):
self.parse(self.xml_bomb2, forbid_entities=False)
self.parseString(self.get_content(self.xml_bomb2), forbid_entities=False)
def test_dtd_element(self):
self.parse(self.xml_dtd_element)
class TestDefusedElementTree(BaseTests):
module = ElementTree
# etree doesn't do external ref lookup
# external_ref_exception = ElementTree.ParseError
cyclic_error = ElementTree.ParseError
def parse(self, xmlfile, **kwargs):
tree = self.module.parse(xmlfile, **kwargs)
return self.module.tostring(tree.getroot())
def parseString(self, xmlstring, **kwargs):
tree = self.module.fromstring(xmlstring, **kwargs)
return self.module.tostring(tree)
def parseStringList(self, sequence, **kwargs):
tree = self.module.fromstringlist(sequence, **kwargs)
return self.module.tostring(tree)
def iterparse(self, source, **kwargs):
return list(self.module.iterparse(source, **kwargs))
def test_html_arg(self):
with warnings.catch_warnings(record=True) as w:
self.module.XMLParse(html=0)
self.assertEqual(len(w), 1)
self.assertIs(w[0].category, DeprecationWarning)
with self.assertRaises(TypeError):
self.module.XMLParse(html=1)
def test_aliases(self):
parser = self.module.DefusedXMLParser
assert self.module.XMLTreeBuilder is parser
assert self.module.XMLParser is parser
assert self.module.XMLParse is parser
def test_fromstringlist(self):
seq = ["<root>", '<tag id="one" />', '<tag id="two" />', "</root>"]
tree = self.module.fromstringlist(seq)
result = self.module.tostring(tree)
self.assertEqual(result, "".join(seq).encode("utf-8"))
def test_import_order(self):
from xml.etree import ElementTree as second_elementtree
self.assertIs(orig_elementtree, second_elementtree)
def test_orig_parseerror(self):
# https://github.com/tiran/defusedxml/issues/63
self.assertIs(self.module.ParseError, orig_elementtree.ParseError)
try:
self.parseString("invalid")
except Exception as e:
self.assertIsInstance(e, orig_elementtree.ParseError)
self.assertIsInstance(e, self.module.ParseError)
def test_etree_element(self):
tree = tree = self.module.parse(self.xml_simple)
root = tree.getroot()
root.append(orig_elementtree.Element("module-import"))
root.append(ElementBeforeImport("before-import"))
root.append(ElementAfterImport("after-import"))
s = orig_elementtree.tostring(root)
self.assertEqual(s.count(b"import"), 3, s)
class TestDefusedcElementTree(TestDefusedElementTree):
module = cElementTree
def test_celementtree_warnings(self):
self.assertTrue(cetree_warnings)
self.assertEqual(cetree_warnings[0].category, DeprecationWarning)
self.assertIn("tests.py", cetree_warnings[0].filename)
class TestDefusedMinidom(BaseTests):
module = minidom
cyclic_error = ExpatError
iterparse = None
def parse(self, xmlfile, **kwargs):
doc = self.module.parse(xmlfile, **kwargs)
return doc.toxml()
def parseString(self, xmlstring, **kwargs):
doc = self.module.parseString(xmlstring, **kwargs)
return doc.toxml()
class TestDefusedMinidomWithParser(TestDefusedMinidom):
cyclic_error = SAXParseException
dtd_external_ref = True
def parse(self, xmlfile, **kwargs):
doc = self.module.parse(xmlfile, parser=expatreader.create_parser(**kwargs), **kwargs)
return doc.toxml()
def parseString(self, xmlstring, **kwargs):
doc = self.module.parseString(
xmlstring, parser=expatreader.create_parser(**kwargs), **kwargs
)
return doc.toxml()
class TestDefusedPulldom(BaseTests):
module = pulldom
cyclic_error = SAXParseException
dtd_external_ref = True
def parse(self, xmlfile, **kwargs):
events = self.module.parse(xmlfile, **kwargs)
return list(events)
def parseString(self, xmlstring, **kwargs):
events = self.module.parseString(xmlstring, **kwargs)
return list(events)
class TestDefusedSax(BaseTests):
module = sax
cyclic_error = SAXParseException
content_binary = True
dtd_external_ref = True
def parse(self, xmlfile, **kwargs):
with io.StringIO() as result:
handler = XMLGenerator(result)
self.module.parse(xmlfile, handler, **kwargs)
return result.getvalue()
def parseString(self, xmlstring, **kwargs):
with io.StringIO() as result:
handler = XMLGenerator(result)
self.module.parseString(xmlstring, handler, **kwargs)
return result.getvalue()
def test_exceptions(self):
with self.assertRaises(EntitiesForbidden) as ctx:
self.parse(self.xml_bomb)
msg = "EntitiesForbidden(name='a', system_id=None, public_id=None)"
self.assertEqual(str(ctx.exception), msg)
self.assertEqual(repr(ctx.exception), msg)
with self.assertRaises(ExternalReferenceForbidden) as ctx:
self.parse(self.xml_external, forbid_entities=False)
msg = (
"ExternalReferenceForbidden"
"(system_id='http://www.w3schools.com/xml/note.xml', public_id=None)"
)
self.assertEqual(str(ctx.exception), msg)
self.assertEqual(repr(ctx.exception), msg)
with self.assertRaises(DTDForbidden) as ctx:
self.parse(self.xml_bomb, forbid_dtd=True)
msg = "DTDForbidden(name='xmlbomb', system_id=None, public_id=None)"
self.assertEqual(str(ctx.exception), msg)
self.assertEqual(repr(ctx.exception), msg)
@unittest.skipUnless(lxml is not None, "test requires lxml")
class TestDefusedLxml(BaseTests):
module = lxml
cyclic_error = getattr(lxml_etree, "XMLSyntaxError", None)
content_binary = True
def parse(self, xmlfile, **kwargs):
try:
tree = self.module.parse(xmlfile, **kwargs)
except lxml_etree.XMLSyntaxError:
self.skipTest("lxml detects entity reference loop")
return self.module.tostring(tree)
def parseString(self, xmlstring, **kwargs):
try:
tree = self.module.fromstring(xmlstring, **kwargs)
except lxml_etree.XMLSyntaxError:
self.skipTest("lxml detects entity reference loop")
return self.module.tostring(tree)
if not LXML3:
def test_entities_forbidden(self):
self.assertRaises(NotSupportedError, self.parse, self.xml_bomb)
def test_dtd_with_external_ref(self):
self.assertRaises(NotSupportedError, self.parse, self.xml_dtd)
def test_external_ref(self):
pass
def test_external_file_ref(self):
pass
def test_restricted_element1(self):
try:
tree = self.module.parse(self.xml_bomb, forbid_dtd=False, forbid_entities=False)
except lxml_etree.XMLSyntaxError:
self.skipTest("lxml detects entityt reference loop")
root = tree.getroot()
self.assertEqual(root.text, None)
self.assertEqual(list(root), [])
self.assertEqual(root.getchildren(), [])
self.assertEqual(list(root.iter()), [root])
self.assertEqual(list(root.iterchildren()), [])
self.assertEqual(list(root.iterdescendants()), [])
self.assertEqual(list(root.itersiblings()), [])
self.assertEqual(list(root.getiterator()), [root])
self.assertEqual(root.getnext(), None)
def test_restricted_element2(self):
try:
tree = self.module.parse(self.xml_bomb2, forbid_dtd=False, forbid_entities=False)
except lxml_etree.XMLSyntaxError:
self.skipTest("lxml detects entityt reference loop")
root = tree.getroot()
bomb, tag = root
self.assertEqual(root.text, "text")
self.assertEqual(list(root), [bomb, tag])
self.assertEqual(root.getchildren(), [bomb, tag])
self.assertEqual(list(root.iter()), [root, bomb, tag])
self.assertEqual(list(root.iterchildren()), [bomb, tag])
self.assertEqual(list(root.iterdescendants()), [bomb, tag])
self.assertEqual(list(root.itersiblings()), [])
self.assertEqual(list(root.getiterator()), [root, bomb, tag])
self.assertEqual(root.getnext(), None)
self.assertEqual(root.getprevious(), None)
self.assertEqual(list(bomb.itersiblings()), [tag])
self.assertEqual(bomb.getnext(), tag)
self.assertEqual(bomb.getprevious(), None)
self.assertEqual(tag.getnext(), None)
self.assertEqual(tag.getprevious(), bomb)
def test_xpath_injection(self):
# show XPath injection vulnerability
xml = """<root><tag id="one" /><tag id="two"/></root>"""
expr = "one' or @id='two"
root = lxml.fromstring(xml)
# insecure way
xp = "tag[@id='%s']" % expr
elements = root.xpath(xp)
self.assertEqual(len(elements), 2)
self.assertEqual(elements, list(root))
# proper and safe way
xp = "tag[@id=$idname]"
elements = root.xpath(xp, idname=expr)
self.assertEqual(len(elements), 0)
self.assertEqual(elements, [])
elements = root.xpath(xp, idname="one")
self.assertEqual(len(elements), 1)
self.assertEqual(elements, list(root)[:1])
def test_lxml_warnings(self):
self.assertTrue(lxml_warnings)
self.assertEqual(lxml_warnings[0].category, DeprecationWarning)
self.assertIn("tests.py", lxml_warnings[0].filename)
def test_lxml_schema_include(self):
# attempt to trigger network ops and error
with mock.patch.dict(os.environ):
os.environ.pop("no_proxy", None)
os.environ["http_proxy"] = "http://proxy.invalid:3128"
os.environ["https_proxy"] = "http://proxy.invalid:3128"
doc = self.module.fromstring("<root>true</root>")
schema = lxml_etree.XMLSchema(file=self.xml_schema_include)
schema.validate(doc)
schema_etree = self.module.parse(self.xml_schema_include)
lxml_etree.XMLSchema(etree=schema_etree)
schema.validate(doc)
class XmlRpcTarget(object):
def __init__(self):
self._data = []
def __str__(self):
return "".join(self._data)
def xml(self, encoding, standalone):
pass
def start(self, tag, attrs):
self._data.append("<%s>" % tag)
def data(self, text):
self._data.append(text)
def end(self, tag):
self._data.append("</%s>" % tag)
class TestXmlRpc(DefusedTestCase):
module = xmlrpc
def parse(self, xmlfile, **kwargs):
target = XmlRpcTarget()
parser = self.module.DefusedExpatParser(target, **kwargs)
data = self.get_content(xmlfile)
parser.feed(data)
parser.close()
return target
def parse_unpatched(self, xmlfile):
target = XmlRpcTarget()
parser = self.module.ExpatParser(target)
data = self.get_content(xmlfile)
parser.feed(data)
parser.close()
return target
def test_xmlrpc(self):
self.assertRaises(EntitiesForbidden, self.parse, self.xml_bomb)
self.assertRaises(EntitiesForbidden, self.parse, self.xml_quadratic)
self.parse(self.xml_dtd)
self.assertRaises(DTDForbidden, self.parse, self.xml_dtd, forbid_dtd=True)
# def test_xmlrpc_unpatched(self):
# for fname in (self.xml_external, self.xml_dtd):
# print(self.parse_unpatched(fname))
def test_monkeypatch(self):
try:
xmlrpc.monkey_patch()
finally:
xmlrpc.unmonkey_patch()
@unittest.skipUnless(gzip is not None, "test requires gzip")
class TestDefusedGzip(DefusedTestCase):
def get_gzipped(self, length):
f = io.BytesIO()
self.addCleanup(f.close)
gzf = gzip.GzipFile(mode="wb", fileobj=f)
gzf.write(b"d" * length)
gzf.close()
f.seek(0)
return f
def decode_response(self, response, limit=None, readlength=1024):
dec = xmlrpc.DefusedGzipDecodedResponse(response, limit)
acc = []
while True:
data = dec.read(readlength)
if not data:
break
acc.append(data)
return b"".join(acc)
def test_defused_gzip_decode(self):
data = self.get_gzipped(4096).getvalue()
result = xmlrpc.defused_gzip_decode(data)
self.assertEqual(result, b"d" * 4096)
result = xmlrpc.defused_gzip_decode(data, -1)
self.assertEqual(result, b"d" * 4096)
result = xmlrpc.defused_gzip_decode(data, 4096)
self.assertEqual(result, b"d" * 4096)
with self.assertRaises(ValueError):
result = xmlrpc.defused_gzip_decode(data, 4095)
with self.assertRaises(ValueError):
result = xmlrpc.defused_gzip_decode(data, 0)
def test_defused_gzip_response(self):
clen = len(self.get_gzipped(4096).getvalue())
response = self.get_gzipped(4096)
data = self.decode_response(response)
self.assertEqual(data, b"d" * 4096)
with self.assertRaises(ValueError):
response = self.get_gzipped(4096)
xmlrpc.DefusedGzipDecodedResponse(response, clen - 1)
with self.assertRaises(ValueError):
response = self.get_gzipped(4096)
self.decode_response(response, 4095)
with self.assertRaises(ValueError):
response = self.get_gzipped(4096)
self.decode_response(response, 4095, 8192)
def test_main():
suite = unittest.TestSuite()
cls = [
TestDefusedElementTree,
TestDefusedcElementTree,
TestDefusedMinidom,
TestDefusedMinidomWithParser,
TestDefusedPulldom,
TestDefusedSax,
TestDefusedLxml,
TestXmlRpc,
TestDefusedGzip,
]
for c in cls:
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(c))
return suite
if __name__ == "__main__":
suite = test_main()
result = unittest.TextTestRunner(verbosity=1).run(suite)
# TODO: test that it actually works
defuse_stdlib()
sys.exit(not result.wasSuccessful())