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=
"<ce><input><transaction><length>00000</length><tran_type>Login</tran_type></transaction><user><user_id>ce_userid</user_id><subscriber_name>ce_subscribername</subscriber_name><subscriber_id>ce_subscriberid</subscriber_id><group_id>ce_groupid</group_id><permissions></permissions></user><consumer><login_details><username>UnitTester9</username><password>pDhE5AsKBHw85Sqgg6qdKQ==</password><pin>tOlkiae9epM=</pin></login_details></consumer></input></ce>"
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(OurOutputXMLString);
In the audit report they say that it's failing because an XML entity can contain URLs that can resolve outside of intended control. 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 doesn't 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();
xmlDoc.Load(reader);
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?
External resources are resolved using the XmlResolver provided via XmlDocument.XmlResolver property. 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.
So its better to use
new XmlDocument { XmlResolver = null };
Interestingly from .net 4.5.2 and 4.6, the default resolver behaves differently and does not use an XmlUrlResolver upfront implicitly to resolve any urls or locations as i seen.
//In pre 4.5.2 it is a security issue.
//In 4.5.2 it will not resolve any more the url references in dtd and such,
//Still better to avoid the below since it will trigger security warnings.
new XmlDocument();
Setting the XmlReaderSettings.DtdProcessing to DtdProcessing.Prohibit works totally fine in .NET 4.7.2. Here is what i used to test.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE demo
[
<!ELEMENT demo ANY >
<!ENTITY % extentity SYSTEM "https://www.hl7.org/documentcenter/public/wg/structure/CDA.xsl">
%extentity;
]>
<test>
Some random content
</test>
Saved the above content in a file and read the file from the following fragment of c# code.
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
settings.MaxCharactersFromEntities = 6000;
//The following stream should be the filestream of the above content.
XmlReader reader = XmlReader.Create(stream, settings);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
I get the following exception.
For security reasons DTD is prohibited in this XML document. To enable DTD
processing set the DtdProcessing property on XmlReaderSettings to Parse and
pass the settings into XmlReader.Create method.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ParseDoctypeDecl()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
at System.Xml.XmlDocument.Load(XmlReader reader)
Related
I want to change an attribute inside an xml file using C#.
Here is a sample XML file
<?xml version="1.0" encoding="us-ascii"?>
<Client>
<Age>25</Age>
<Weight>50</Weight>
</Client>
I tried loading the xml file using both XmlDocument and XDocument. They both take so much time (more than 5 minutes) to load.
Here is the code I am using to load the file:
string filePath = #"myFile.xml";
XmlDocument xmlData = new XmlDocument();
As per Google, the problem is that XDocument and XmlDocument will load all the DTDs for XML file, and this is why it takes much time. Is there a workaround for this? or maybe any alternative that allows me to change an attribute without loading all the DtDs?
You can control how DTDs are cached, parsed or used for validation with XmlReaderSettings and still use XDocument.
If you can take the time to cache the DTDs and changing them isn't part of your test, you could take the hit once and cache them.
If that's too much time or they aren't available and they aren't needed for your tests, you could skip DTD processing.
using (var reader = XmlReader.Create(_,
new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Ignore,
ValidationType = ValidationType.None,
//DtdProcessing = DtdProcessing.Parse,
//ValidationType = ValidationType.DTD,
XmlResolver = new XmlUrlResolver
{
CachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheIfAvailable),
//CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore),
}
}))
{
var doc = XDocument.Load(reader);
//…
}
XmlReaderSettings has many other properties that sometimes come in handy.
When I process the XML files using C#, I get this error. I searched previous questions and found the reason. I understand these entities are not predefined in XML and must be included in DTD. It is included in the DTD. My XML files include the following DTD.
<!DOCTYPE doc PUBLIC "-//Location//EN"
"NAME.dtd" [
<!ENTITY C-1FHY "SD FFF">
<!ENTITY Ca- "XX">
]>
Also
I need to read content from this XML file. I used XMLReader.
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
XmlReader doc = XmlReader.Create(f, settings);
while (doc.Read())
{
If I ignore DTD, it throws the error. If I parse, then it says it couldnt find the DTD in the location where every file is. If I copy the DTD in the same location where the file is, i dont have any problem.
My problem is there are 500+ docs in more than 60+ sub folders. I can't put a copy of the DTD in every folder. Is there a way I store a single copy of DTD in a path and link it in the code? Please help me in this.
You can make a custom XmlUrlResolver that remaps the file location:
public class XmlUrlOverrideResolver : XmlUrlResolver
{
public Dictionary<string, string> DtdFileMap { get; private set; }
public XmlUrlOverrideResolver()
{
this.DtdFileMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
public override Uri ResolveUri(Uri baseUri, string relativeUri)
{
string remappedLocation;
if (DtdFileMap.TryGetValue(relativeUri, out remappedLocation))
return new Uri(remappedLocation);
var value = base.ResolveUri(baseUri, relativeUri);
return value;
}
}
And then use it like:
var resolver = new XmlUrlOverrideResolver();
resolver.DtdFileMap[#"NAME.dtd"] = #"C:\Location\Of\File\name.dtd";
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = resolver;
// Proceed as before.
I am working with Mismo 2.3.1, dtd based schema. I converted the dtd to xsd and then generated c# code to serialize/deserialze object representations of the xml doc.
Given a valid mismo 2.3.1 xml doc, I can deserialize into my generated C# class.
I have code working to use XmlSerializer along with XmlReaderSettings and XmlSchmeas collection, reading in my converted xsd.
If I put xmlns="http://mySchema..." in the root element, and try to validate intentionally invalid xml, works as expected, my validation event gets pinged with accurate description.
If I take out the xmlns attribute, then i get "could not find schema information for element [my root element]"
Any idea on how to validate xml that comes in without the xmlns spec? Any settings to say to the serializer "use this schema when you come across this element"?
Thanks in advance!
static void Main() {
var settings = new XmlReaderSettings();
settings.NameTable = new NameTable();
var nsMgr = new XmlNamespaceManager(settings.NameTable);
nsMgr.AddNamespace("", "http://example.com/2013/ns"); // <-- set default namespace
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, #"C:\XSDSchema.xsd"); // <-- set schema location for the default namespace
var parserCtx = new XmlParserContext(settings.NameTable, nsMgr, XmlSpace.Default);
using (var reader = XmlReader.Create(#"C:\file.xml", settings, parserCtx)) {
var serializer = new XmlSerializer(typeof(Foo));
Foo f = (Foo)serializer.Deserialize(reader);
}
}
I literally just want to be able to traverse the contents of various XML files that I have been given but having a non-standard DTD means I am hitting some issues - one error being "Reference to undeclared entity 'reg'" and another saying it is unable to locate the .DTD file.
Is it possible to do this sort of thing for XML files when no DTD is available? I have no control over these files and cannot change them. I am looking to grab various amounts of them at a time, move through the contents as efficiently as possible, email out some notifications and thats it.
Sample of XML file below:
<!DOCTYPE Toro-Pub PUBLIC "-//Toro//DTD Toro Publication V1.0//EN//XML" "Toro-Pub.dtd">
<!--Arbortext, Inc., 1988-2011, v.4002-->
<?Pub UDT _nopagebreak _touchup KeepsKeep="yes" KeepsPrev="no" KeepsNext="no" KeepsBoundary="page"?>
<?Pub UDT template _font?>
<?Pub UDT _bookmark _target?>
<?Pub UDT _nocolumnbreak _touchup KeepsKeep="yes" KeepsPrev="no" KeepsNext="no" KeepsBoundary="column"?>
<?Pub UDT instructions _comment FontColor="red"?>
<?Pub EntList alpha bull copy rArr sect trade deg?>
<?Pub Inc?>
<Toro-Pub><PubMeta Brand="Toro" CE="Yes" ClientPubNo="" CopyrightYear="2013" FormNumber="3378-827" Lang="CS" LangParentForm="3378-826" LangParentID="72729" LangParentRev="A" PageSize="" PhoneNoCan="" PhoneNoMex="" PhoneNoUS="" ProductFamily="sample product name" PubID="72730" PublicationType="Operator Manual" RegistrationURL="www.website.com" Rev="A" ServiceURL="www.website.com"><?TranslationData DueDate="07/01/2013" InCarton(1-yes)="0" Author="Mr Smith" EngParent="https://lwww.website.com?vPubID=423&vPubNum=3378-826" ?></PubMeta><Pub-TBlock>
<Body-TB>
...
Many thanks.
UPDATE #1
I have tried the below code taken from the suggested comment:
Stream file = File.OpenRead("4d00fa60800e0a5d_3378-827.xml");
// The next line is the fix!!!
XmlTextReader xmlTextReader = new XmlTextReader(file);
xmlTextReader.XmlResolver = null; // Don't require file in system32\inetsrv
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
//readerSettings.Schemas.Add(null, "");
readerSettings.DtdProcessing = DtdProcessing.Ignore;
readerSettings.XmlResolver = null; // Doesn't help
//readerSettings.ValidationEventHandler += ValidationEventHandle;
XmlReader myXmlReader = XmlReader.Create(xmlTextReader, readerSettings);
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.XmlResolver = null; // Doesn't help
myXmlDocument.Load(myXmlReader); // Load doc, no .dtd required on local disk
However, I now get a new error of 'Operation is not valid due to the current state of the object.' on the line 'myXmlDocument.Load(myXmlReader)'.
This has been bugging me for a couple days. I'm trying to load a XML from an uploaded file to into an XmlDocument object and get the following yellow-screen-of-death:
For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings to false and pass the settings into XmlReader.Create method.
Here's my code. You can clearly see I'm setting ProhibitDtd to false.
public static XmlDocument LoadXml(FileUpload fu)
{
var settings = new XmlReaderSettings
{
ProhibitDtd = false,
ValidationType = ValidationType.DTD
};
var sDtdPath = string.Format(#"{0}", HttpContext.Current.Server.MapPath("/includes/dtds/2.3/archivearticle.dtd"));
settings.Schemas.Add(null, sDtdPath);
var r = XmlReader.Create(new StreamReader(fu.PostedFile.InputStream), settings);
var document = new XmlDocument();
document.Load(r);
return document;
}
Add XmlResolver=null to your XmlReaderSettings. This will prevent the xmlDocument from trying to access the DTD. If you need to validate, do that in a separate operation.