Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent XML eXternal Entity (XXE) attack during .net deserialization

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.

like image 312
user5837579 Avatar asked Jan 25 '16 14:01

user5837579


1 Answers

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!

like image 124
SpikeEdge Avatar answered Oct 16 '22 11:10

SpikeEdge