-->

XDocument.Parse: Avoid replacing XXE references

2019-09-13 18:42发布

问题:

I'm trying to protect against malicious XXE injections in the XMLs processed by my app. Therefore I'm using XDocument instead of XmlDocument.

The XML represents the payload of a web request so I call XDocument.Parse on its string content. However, I'm seeing the XXE references contained in the XML (&XXE) being replaced in the result with the actual value of ENTITY xxe.

Is it possible to parse the XML with XDocument without replacing &xxe ?

Thanks

EDIT: I managed to avoid the replacement of xxes in the XML using XmlResolver=null for XDocument.Load

回答1:

Instead of Parse try to use Load with a pre-configured reader:

var xdoc = XDocument.Load(new XmlTextReader(
    new StringReader(xmlContent)) { EntityHandling = EntityHandling.ExpandCharEntities });

From MSDN:

When EntityHandling is set to ExpandCharEntities, the reader expands character entities and returns general entities as EntityReference nodes.



回答2:

Use the following example to stop resolving XXE (schemas and DTD).

Dim objXmlReader As System.Xml.XmlTextReader = Nothing
objXmlReader = New System.Xml.XmlTextReader(_patternFilePath)
objXmlReader.XmlResolver = Nothing
patternDocument = XDocument.Load(objXmlReader)