XML External Entities and Parser Capabilities
Follow an invoice entity from its declaration to an outside file and the returned note, then restrict unneeded parser features.
You’re reading a preview. Premium includes the full lesson and specialist practice. View the full curriculum.
An app reads an invoice's Note element from XML. Normally that note is text inside the invoice. Now the document declares a name whose replacement text comes from an outside file.
An XML entity is a named replacement. A DTD can declare entities. When a parser is allowed to resolve an external entity, reading the invoice can also read something outside the invoice.
We'll use a harmless local marker file to follow three steps: the document declares the resource, the parser resolves it, and the note is returned. Then we'll remove the parser features the invoice format does not need.
Inventory parser capabilities before reading fields
Find the exact parser construction, version, linked library, and options. A secure default in one library does not protect code that explicitly enables a feature. A wrapper can also construct its own parser or apply a custom resolver. Follow the actual object used by the upload handler.
# Unsafe original invoice outline.
parser = etree.XMLParser(load_dtd=True, resolve_entities=True)
root = etree.fromstring(uploaded_xml, parser=parser)
note = root.findtext('Note')
return {'invoiceNote': note}
XML entities can refer to external resources when the parser permits resolution. A document type declaration can define an entity and an element can reference it. The resulting text may no longer be only the bytes the caller supplied. Review where expanded data is returned, stored, rendered, or used in another interpreter.
Trace the resource declaration to the caller-visible field.
Declare. The untrusted DTD names an outside resource.
<!ENTITY marker SYSTEM "file:///fixture/outside-marker.txt">
Resolve. Explicit entity resolution can read under the process’s permissions.
etree.XMLParser(load_dtd=True, resolve_entities=True)
Expose. Expanded Note text enters the returned JSON.
note = root.findtext("Note")
return {"invoiceNote": note}
Review question: Constrain parser capabilities before field validation and response projection.