andris
andris

Reputation: 1

C# Validate XML against a DTD in separate file throws security Exception

I'm trying to validate a simple xml file with an external dtd schema with schema and xml being in separate files. Unfortunately so far it only works when the dtd schema is defined in the xml DOCTYPE element.

However, when I split the schema to a seperate .dtd file, when I try to specify a specific path to the DTD schema with this line:

settings.Schemas.Add(null, dtdPath);

I get the following exception:

For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.

This is the simple code that I'm using:

            var settings = new XmlReaderSettings {
                ValidationType = ValidationType.DTD,
                DtdProcessing = DtdProcessing.Parse,
                ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings
            };


            string basePath = AppDomain.CurrentDomain.BaseDirectory;
            string xmlPath = Path.Combine(basePath, "data", "sample.xml");
            string dtdPath = Path.Combine(basePath, "data", "sample.dtd");

//Next line is being added when the DTD schema is in the seperate file: 

            settings.Schemas.Add(null, dtdPath);

// ^^ And that is where the exception is being thrown;

 using (XmlReader reader = XmlReader.Create(xmlPath, settings))
 {
     XmlDocument xmlDoc = new XmlDocument();     
     xmlDoc.Load(reader);
}

This is the .dtd file content:

<!ELEMENT store (item)*>
<!ELEMENT item (name,price,dept1)>
<!ATTLIST item type CDATA #REQUIRED>
<!ATTLIST item ISBN CDATA #IMPLIED>
<!ELEMENT name (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT dept1 (#PCDATA)>

With a sample xml file:


<store>
    <item type="supplies"  ISBN="2-3631-4">
        <name>paint</name>
        <price>16.95</price>
        <dept1>Hello</dept1>
    </item>
</store>

When I combine both .dtd and xml file into a single .xml file everything works (with omitted settings.Schemas.Add(null, dtdPath); because it is not needed in this scenario). However I need to achieve a solution where my XML file and DTD schema are in separate entities.

Combined xml file with DTD schema included:

<!--XML file using a DTD-->
<!DOCTYPE store [
    <!ELEMENT store (item)*>
    <!ELEMENT item (name,price,dept1)>
    <!ATTLIST item type CDATA #REQUIRED>
    <!ATTLIST item ISBN CDATA #IMPLIED>
    <!ELEMENT name (#PCDATA)>
    <!ELEMENT price (#PCDATA)>
    <!ELEMENT dept1 (#PCDATA)>
]>
<store>
    <item type="supplies"  ISBN="2-3631-4">
        <name>paint</name>
        <price>16.95</price>
        <dept5555>Hello</dept5555>
    </item>
</store>

I have not yet found a good solution, since all sample codes I find point only to the DtdProcessing = DtdProcessing.Parse setting for XmlReaderSettings that I use already.

Upvotes: 0

Views: 36

Answers (0)

Related Questions