Thursday, June 13, 2019

ASP.NET: Xml control loading a XML string in a safe way

In the .aspx file:

<asp:Xml id="xml1" runat="server" />

In the .aspx.cs file:

XmlSchema schema = new XmlSchema();
XmlSchemaElement elementRoot = new XmlSchemaElement();
elementRoot.Name = "root";

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.DtdProcessing = DtdProcessing.Prohibit;   // to prevent XXE attack.
StringReader sr = new StringReader(xmlInString);
XmlReader reader = XmlReader.Create(sr, settings);

xml1.Document.XmlResolver = null;   // to prevent XXE attack.

Note: the schema generated has only the root element (as below). If xmlInString contains any type of children elements, it will be validated as good.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="">
  <xs:element name="root"/>

Since Xml.Document is an obsolete property, for the above example, we should use another property DocumentContent. If Schema validation is not needed, we have a much simpler code:

xml1.DocumentContent = xmlInString;

No comments:

Get This <