Prevent XXE in .NET XML parsers
To disable external entities in .NET and prevent XXE, rely on the safe defaults of modern XmlReader (DtdProcessing.Prohibit) and set XmlResolver to null on XmlDocument; the main risk is legacy code using XmlTextReader or explicitly re-enabling DTD processing.
Modern .NET (Framework 4.5.2+ and all of .NET Core / .NET 5+) is safe by default for most APIs: XmlReader uses DtdProcessing.Prohibit and no XmlResolver. The danger is older code and explicit opt-ins. The fix is to confirm DTD processing is prohibited and that no resolver is attached to anything parsing untrusted XML.
Secure parser configuration
XmlReader (recommended)
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit, // default on .NET 4.0+
XmlResolver = null // no external resource resolution
};
using var reader = XmlReader.Create(stream, settings);DtdProcessing.Prohibit throws on any DOCTYPE; use .Ignore only if you must tolerate (but not process) a DTD.
XmlDocument
var doc = new XmlDocument();
doc.XmlResolver = null; // disables external entity + DTD resolution
doc.LoadXml(untrustedXml);On .NET Framework < 4.5.2 the resolver is non-null by default — this line is essential there.
XPathDocument / XDocument (LINQ to XML)
// XDocument/XElement do not resolve external entities by default and have no
// XmlResolver. To be explicit, parse via a hardened XmlReader:
using var reader = XmlReader.Create(stream, new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null
});
var xdoc = XDocument.Load(reader);Legacy XmlTextReader
// .NET 4.0+:
var reader = new XmlTextReader(stream) { DtdProcessing = DtdProcessing.Prohibit };
// .NET < 4.0:
// reader.ProhibitDtd = true; // and set XmlResolver = nullXmlTextReader was unsafe by default before 4.5.2 — prefer XmlReader.Create instead.
Common pitfalls that re-introduce XXE
- Explicitly setting DtdProcessing = DtdProcessing.Parse on untrusted input.
- Assigning a non-null XmlUrlResolver to XmlDocument/XmlReader.
- Relying on old framework defaults in code that runs on .NET Framework < 4.5.2.
- Using obsolete XmlTextReader without prohibiting DTDs.
Verifying the fix
Submit a classic file-read payload; a hardened reader throws an XmlException reporting that DTDs are prohibited. Confirm the exception is handled and no file contents appear in the response, and grep the codebase for DtdProcessing.Parse and new XmlUrlResolver.