junni lomo junni lomo - 8 months ago 54
ASP.NET (C#) Question

How to prevent XXE attack ( XmlDocument in .net)

We had a security audit on our code, and they mentioned that our code is vulnerable to EXternal Entity (XXE) attack. I am using following code -

string OurOutputXMLString=

XmlDocument xmlDoc = new XmlDocument();

In Audit report they say that its failing because XML entity can contain URLs that can resolve outside of intended contronl. XML entity resolver will attempt to resolve and retrieve external references. If attacker-controlled XML can be submitted to one of these functions, then the attacker could gain access to information about an internal network, local filesystem, or other sensitive data.
To avoid this i wrote the following code but it doesnt work.

MemoryStream stream =
new MemoryStream(System.Text.Encoding.Default.GetBytes(OurOutputXMLString));

XmlReaderSettings settings = new XmlReaderSettings();

settings.DtdProcessing = DtdProcessing.Prohibit;
settings.MaxCharactersFromEntities = 6000;
XmlReader reader = XmlReader.Create(stream, settings);
XmlDocument xmlDoc = new XmlDocument();

but i can see here that reader does not have any value to load into xmlDoc(XmlDocument).
Can anyone help where i am missing things?
Anyone help is appreciated !

Answer Source

External resources are resolved using the XmlResolver provided via XmlDocument.XmlResolver property. If your XML documents does not contain any external resource (for example DTDs or schemas) simply set this property to null:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.XmlResolver = null;

If you want to filter where this URLs come from (for example to allow only certain domains) just derive your own class from XmlUrlResolver and override the ResolveUri() method. There you can check what the URL is and sanitize it (for example you can allow only URLs within your local network or from trusted sources).

For example:

class CustomUrlResovler : XmlUrlResolver
    public override Uri ResolveUri(Uri baseUri, string relativeUri)
        Uri uri = new Uri(baseUri, relativeUri);
        if (IsUnsafeHost(uri.Host))
            return null;

        return base.ResolveUri(baseUri, relativeUri);

    private bool IsUnsafeHost(string host)
        return false; 

Where IsUnsafeHost() is a custom function that check if the given host is allowed or not. See this post here on SO for few ideas. Just return null from ResolveUri() to save your code from this kind of attacks. In case the URI is allowed you can simply return the default XmlUrlResolver.ResolveUri() implementation.

To use it:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.XmlResolver = new CustomUrlResolver();

For more details about how XML external resources are resolved just read this article on MSDN.