How to prevent XXE attack (XmlDocument in. net)

Source: Internet
Author: User
Tags baseuri

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

XmlDocument xmldoc = new XmlDocument (); xmldoc.xmlresolver = Null;xmldoc.loadxml (ouroutputxmlstring);

  

If you want to the filter where these URLs come from (for example to allow only certain domains) just derive your own class fr Om and XmlUrlResolver override the ResolveUri() method. There you can check the "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 is IsUnsafeHost() a custom function This check if the given host is allowed or not. See this post here on so for few ideas. Just return from to null ResolveUri() save Your code from this kind of attacks. The 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 is resolved just read resolving external resources on MS Docs.  If your code is more complex than this example then you should definitely read Remarks sections 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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.