XXE – .NET secure coding

Prior to .NET 4.0
In .NET Framework versions prior to 4.0, DTD parsing behavior for XmlReader and XmlTextReader is controlled by the Boolean ProhibitDtd property found in the System.Xml.XmlReaderSettings and System.Xml.XmlTextReader classes. Set these values to true to disable inline DTDs completely:

XmlReader

XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = true; // Not explicitly needed because the default is 'true'
XmlReader reader = XmlReader.Create(stream, settings);

 

XmlTextReader

XmlTextReader reader = new XmlTextReader(stream);
reader.ProhibitDtd = true; // NEEDED because the default is FALSE!!

 

XmlDocumentReader

XmlDocumentReader doesn’t use a ProhibitDtd property. Instead you have to set its XmlResolver to null.

static void LoadXML()
{
  string xml = "<!DOCTYPE doc
  []
  >&win;";

  XmlDocument xmlDoc = new XmlDocument();
  xmlDoc.XmlResolver = null; // Setting it to NULL disables DTDs (not null by default).
  xmlDoc.LoadXml(xml);
  Console.WriteLine(xmlDoc.InnerText);
  Console.ReadLine();
}

 

.NET 4.0 and later
In .NET Framework version 4.0, DTD parsing behavior has been changed. The ProhibitDtd property has been deprecated in favor of the new DtdProcessing property. However, they didn’t change the default settings so XmlTextReader is still vulnerable to XXE by default.

Setting DtdProcessing to Prohibit causes the runtime to throw an exception if a element is present in the XML. To set this value yourself, it looks like this:

XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
XmlReader reader = XmlReader.Create(stream, settings);

Alternatively, you can set the DtdProcessing property to Ignore, which will not throw an exception on encountering a element but will simply skip over it and not process it. Finally, you can set DtdProcessing to Parse if you do want to allow and process inline DTDs.

 

.NET 4.6 and later
Starting with .NET 4.6, Microsoft finally changed the default behavior of XmlDocument to be safe from XXE by default, by setting the XmlResolver to null.

For more details on all of this, please read James Jardine’s article.

 

Reference:
https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#.NET

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *