XML External Entity (XXE) via XmlReaderSettings

High Risk XML Security
csharpxxexmlxmlreaderexternal-entitiesssrf

What it is

XML external entity (XXE) vulnerabilities occur when XML parsers process external entities in user-controlled input without proper configuration. In .NET applications using XmlReaderSettings with DtdProcessing.Parse enabled, attackers can exploit XXE to read local files, perform Server-Side Request Forgery (SSRF), or cause denial of service through entity expansion attacks.

using System.Xml;

public XmlDocument LoadXml(string userInput)
{
    // VULNERABLE: DTD processing enabled with default resolver
    var settings = new XmlReaderSettings
    {
        DtdProcessing = DtdProcessing.Parse,
        XmlResolver = new XmlUrlResolver()
    };
    
    // This can process malicious XML with external entities
    using (var reader = XmlReader.Create(userInput, settings))
    {
        var doc = new XmlDocument();
        doc.Load(reader);
        return doc;
    }
}

// Attack payload:
// <!DOCTYPE root [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
// <root><data>&xxe;</data></root>
using System.Xml;

public XmlDocument LoadXml(string userInput)
{
    // SECURE: DTD processing disabled and resolver set to null
    var settings = new XmlReaderSettings
    {
        DtdProcessing = DtdProcessing.Prohibit,
        XmlResolver = null
    };
    
    // Safe XML processing without external entity risks
    using (var reader = XmlReader.Create(userInput, settings))
    {
        var doc = new XmlDocument();
        doc.Load(reader);
        return doc;
    }
}

💡 Why This Fix Works

The vulnerable code enables DTD processing with DtdProcessing.Parse and uses XmlUrlResolver, allowing attackers to exploit XXE to read files or perform SSRF. The secure version sets DtdProcessing.Prohibit and XmlResolver = null, preventing external entity processing entirely.

Why it happens

Setting DtdProcessing.Parse which allows external entity expansion.

Root causes

Enabling DTD Processing

Setting DtdProcessing.Parse which allows external entity expansion.

Using Default XmlResolver

Using XmlUrlResolver or default resolver that processes external entities.

Processing Untrusted XML

Parsing XML from external sources without secure configuration.

Fixes

1

Disable DTD Processing

Set DtdProcessing.Prohibit to completely disable DTD processing.

2

Set XmlResolver to Null

Set XmlResolver = null to prevent external entity resolution.

3

Use DtdProcessing.Ignore

Alternatively, use DtdProcessing.Ignore to ignore DTDs if complete prohibition isn't suitable.

Detect This Vulnerability in Your Code

Sourcery automatically identifies xml external entity (xxe) via xmlreadersettings and many other security issues in your codebase.