码迷,mamicode.com
首页 > Web开发 > 详细

How to prevent XXE attack ( XmlDocument in .net)

时间:2018-07-03 21:32:32      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:wan   provided   public   tail   arp   tom   def   prevent   resources   

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

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

  

If you want to filter where these 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();
xmlDoc.LoadXml(OurOutputXMLString);

  

For more details about how XML external resources are resolved just read Resolving External Resources on MS Docs. If your code is more complex than this example then you should definitely read Remarks section for XmlDocument.XmlResolver property.

 

https://stackoverflow.com/questions/14230988/how-to-prevent-xxe-attack-xmldocument-in-net

How to prevent XXE attack ( XmlDocument in .net)

标签:wan   provided   public   tail   arp   tom   def   prevent   resources   

原文地址:https://www.cnblogs.com/jakl/p/9260562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!