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)