You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
2.3 KiB

4 years ago
  1. # defusedxml
  2. #
  3. # Copyright (c) 2013 by Christian Heimes <christian@python.org>
  4. # Licensed to PSF under a Contributor Agreement.
  5. # See http://www.python.org/psf/license for licensing details.
  6. """Defused xml.sax.expatreader
  7. """
  8. from __future__ import print_function, absolute_import
  9. from xml.sax.expatreader import ExpatParser as _ExpatParser
  10. from .common import (DTDForbidden, EntitiesForbidden,
  11. ExternalReferenceForbidden)
  12. __origin__ = "xml.sax.expatreader"
  13. class DefusedExpatParser(_ExpatParser):
  14. """Defused SAX driver for the pyexpat C module."""
  15. def __init__(self, namespaceHandling=0, bufsize=2 ** 16 - 20,
  16. forbid_dtd=False, forbid_entities=True,
  17. forbid_external=True):
  18. _ExpatParser.__init__(self, namespaceHandling, bufsize)
  19. self.forbid_dtd = forbid_dtd
  20. self.forbid_entities = forbid_entities
  21. self.forbid_external = forbid_external
  22. def defused_start_doctype_decl(self, name, sysid, pubid,
  23. has_internal_subset):
  24. raise DTDForbidden(name, sysid, pubid)
  25. def defused_entity_decl(self, name, is_parameter_entity, value, base,
  26. sysid, pubid, notation_name):
  27. raise EntitiesForbidden(name, value, base, sysid, pubid, notation_name)
  28. def defused_unparsed_entity_decl(self, name, base, sysid, pubid,
  29. notation_name):
  30. # expat 1.2
  31. raise EntitiesForbidden(name, None, base, sysid, pubid, notation_name)
  32. def defused_external_entity_ref_handler(self, context, base, sysid,
  33. pubid):
  34. raise ExternalReferenceForbidden(context, base, sysid, pubid)
  35. def reset(self):
  36. _ExpatParser.reset(self)
  37. parser = self._parser
  38. if self.forbid_dtd:
  39. parser.StartDoctypeDeclHandler = self.defused_start_doctype_decl
  40. if self.forbid_entities:
  41. parser.EntityDeclHandler = self.defused_entity_decl
  42. parser.UnparsedEntityDeclHandler = self.defused_unparsed_entity_decl
  43. if self.forbid_external:
  44. parser.ExternalEntityRefHandler = self.defused_external_entity_ref_handler
  45. def create_parser(*args, **kwargs):
  46. return DefusedExpatParser(*args, **kwargs)