Share via


Must read if you are dealing with XML

 If you are working with XML this is something you must read. The below code is vulnerable to security attacks (more accurately DOS attacks - XML bombs and external entity attacks).

XmlDocument document = newXmlDocument();

document.LoadXml(xml);

 

 The fix is simple. You can create a safe XmlReaderSettings (the below is just an example) and
reuse it when you deal with xml.

 static System.Xml.XmlReaderSettings CreateSecureXmlReaderSettings()

{

    System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();

    settings.IgnoreComments = true;

    settings.IgnoreProcessingInstructions = true;

    settings.IgnoreWhitespace = true;  

  // this will stop xml bombs

    settings.DtdProcessing = System.Xml. DtdProcessing.Ignore;   

  // this will stop the XmlReader from accessing any external URIs that may be in the blob

    settings.XmlResolver = null;

    settings.MaxCharactersInDocument = MaxAcceptedChars;

    settings.MaxCharactersFromEntities = MaxAcceptedChars;   

   return settings;

}

Then use the secure XmlReaderSetting in loading xml strings 

XmlDocument doc = newXmlDocument();

using (XmlReader reader = XmlReader.Create(newStringReader(xml), GetSecureXmlReaderSettings()))

{

    doc.Load(reader);

}

 

More details please read this link https://msdn.microsoft.com/en-us/magazine/ee335713.aspx (a very good read)