We are doing security analysis of our code using veracode and its showing XXE flaw for below code, specifically where Deserialize() is invoked. How can we prevent serializer from accessing external entities. My attempt below to set XMLresolver to null for XMLReader is not working.
public static T DeserializeObject(string xml, string Namespace)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T), Namespace);
MemoryStream stream =
new MemoryStream(Encoding.Default.GetBytes(xml));
XmlReaderSettings settings = new XmlReaderSettings();
// allow entity parsing but do so more safely
settings.DtdProcessing = DtdProcessing.Ignore;
settings.XmlResolver = null;
using (XmlReader reader = XmlReader.Create(stream, settings))
{
return serializer.Deserialize(reader) as T;
}
}
Can anyone suggest what I might be missing or if there is something else to try.
I had the similar issue. You need to change xmlReader with xmlTextReader as you are reading from the string.
something like this -
public static T DeserializeObject(string xml, string Namespace)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T), Namespace);
//**** I don't think you need this block of code *********
//MemoryStream stream = new MemoryStream(Encoding.Default.GetBytes(xml));
//XmlReaderSettings settings = new XmlReaderSettings();
// allow entity parsing but do so more safely
//settings.DtdProcessing = DtdProcessing.Ignore;
//settings.XmlResolver = null;
//*********************************************
XmlTextReader reader = new XmlTextReader(xml)
{
XmlResolver = null
};
return serializer.Deserialize(reader) as T;
}
All the best!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With