Reputation: 2716
How do I parse an XML document securely so that it does not allow external entities as part of an incoming XML document? I am using DOM parser -
Document test = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(byteArrayInputStream))
Upvotes: 6
Views: 3834
Reputation: 1
You'll need to set:
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setFeature("http://xml.org/sax/features/external-general-entities", false);
f.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
f.setXIncludeAware(false);
f.setExpandEntityReferences(false);
Document test = f.newDocumentBuilder.parse(...);
To avoid external entity expansion.
Upvotes: 0
Reputation: 269627
You can request secure processing by setting FEATURE_SECURE_PROCESSING
; whether this prohibits external entities is up to the provider of the DocumentBuilderFactory
, but it's a likely candidate.
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Document test = f.newDocumentBuilder.parse(...);
Upvotes: 5