8

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.

jglouie
  • 11,300
  • 5
  • 41
  • 64
user5837579
  • 81
  • 1
  • 2
  • null helps only for DTD schemas, you have to implement your own resolver with blackjack and hookers^w^w^w and do not process all external urls (here is explained better http://stackoverflow.com/questions/32203024/how-to-configure-the-xml-parser-to-disable-external-entity-resolution-in-c-sharp) – vitalygolub Jan 25 '16 at 15:13
  • @vitaygolub I am setting the XmlResolver to null, that in theory should not process any external urls. Also, I did try setting xmlresolver to custom implementation of XmlUrlReolver, but still the issue was not resolved. – user5837579 Jan 25 '16 at 16:16
  • With 'not working', do you mean that Veracode is still complaining or that you're still able to perform a successful XXE attack? – Pieter Witvoet Jan 26 '16 at 11:09
  • I'm having the same issue where the code is implemented properly and Veracode is still complaining – jtate Jun 27 '17 at 18:52

1 Answers1

2

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!

SpikeEdge
  • 461
  • 4
  • 5