7

I have a generic deserialization C# code at my utility class. Below is the code sample. When we performed security scan on our code, we got the 'Deserialization of Untrusted Data' vulnerability at Line 3. The deserialization of xml file is seems to be pretty common. I am not sure how do we fix this issue. Can anyone guide me on this?

public static T DeserializeXmlFile<T>(string xmlFilePath)
   {
       
     try
       
     {
           
     XmlSerializer xs= GetSerializer(typeof(T));  //Line#1
           
     FileStream fs= new FileStream(xmlFilePath, FileMode.Open); //Line#2
           
     var result = (T)xs.Deserialize(fs); //Line #3
           
     fs.Close(); //Line#4
           
     return result; //Line#5
   }
  catch (Exception ex)
  {
     LogException("Deserialization exception"); 
     return default(T);
   }
  }
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
NAK
  • 71
  • 1
  • 4
  • `XmlSerializer` only deserializes known types -- ones statically discoverable via reflection of properties, fields and `XmlInclude` attributes. It doesn't have a mechanism where arbitrary types can be loaded (unless you do something crazy such as what is shown [here](https://stackoverflow.com/a/20418772)). So I'm not sure how to resolve the warning. Does your "security scan" software give any guidance? What software are you using anyway? – dbc Dec 19 '17 at 04:58
  • 1
    You should wrap that `FileStream fs` in a `using` statement rather than closing it manually, by the way. And catching and swallowing all exceptions at such a low level seems... unwise. – dbc Dec 19 '17 at 04:59
  • 1
    @dbc, The details of the vulnerability is similar to what is given in this link - [link]https://www.owasp.org/index.php/Deserialization_of_untrusted_data – NAK Dec 19 '17 at 07:31

1 Answers1

0

Use XmlReader for Deserialize instead of FileStream

//Line#2

XmlReader xmlreader = XmlReader.Create(new FileStream(xmlFilePath, FileMode.Open)); 

Here is a link to microsoft solution - CA5369: Use XmlReader for Deserialize

Here is another link for binary deserialization - CA2300: Do not use insecure deserializer BinaryFormatter

Varun
  • 422
  • 3
  • 14