How to configure the XML parser to disable external entity resolution in c#

感情迁移 提交于 2019-11-30 09:19:32

Implement a custom XmlResolver and use it for reading the XML. By default, the XmlUrlResolver is used, which automatically downloads the resolved references.

public class CustomResolver : XmlUrlResolver
{
    public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
    {
        // base calls XmlUrlResolver.DownloadManager.GetStream(...) here
    }
}

And use it like this:

var settings = new XmlReaderSettings { XmlResolver = new CustomResolver() };
var reader = XmlReader.Create(fileName, settings);
var xDoc = XDocument.Load(reader);

If you are not using external entity references in your XML, you can disable the resolver by setting it to null, from How to prevent XXE attack ( XmlDocument in .net)

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

If you are expecting the document to contain entity references, then you will need to create a custom resolver and whitelist what you are expecting. Especially, any references to websites that you do not control.

According to the official OWASP documentation you need to do this:

Use of XercesDOMParser do this to prevent XXE:

XercesDOMParser *parser = new XercesDOMParser;
parser->setCreateEntityReferenceNodes(false);

Use of SAXParser, do this to prevent XXE:

SAXParser* parser = new SAXParser;
parser->setDisableDefaultEntityResolution(true);

Use of SAX2XMLReader, do this to prevent XXE:

SAX2XMLReader* reader = XMLReaderFactory::createXMLReader();
parser->setFeature(XMLUni::fgXercesDisableDefaultEntityResolution, true);

Take a look at these guide: https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!