0
XmlDocument doc = new XmlDocument();
doc.LoadXml(template);
XmlElement list = doc.CreateElement(conn.XmlListTagName);
foreach (EaiItem updateItem in itemList)
{
    XmlElement item = doc.CreateElement( conn.XmlItemTagName );
    foreach(String itemAttrib in updateItem.ItemAttributes.Keys)
    {
        item.SetAttribute(itemAttrib, updateItem.ItemAttributes[itemAttrib]);
    }
    item.InnerXml = updateItem.ItemFieldXml;
    list.AppendChild(item);
}
doc.LastChild.AppendChild(list);

Fortify tool displaying the xml injection in the below code

 item.InnerXml = updateItem.ItemFieldXml;

How to prevent the xml injection issue ?

1
  • What is the problem? I assume ItemFieldXml contains XML that you want to insert into your document as a child XML fragment of your item element? or do you want it stored as CDATA? Commented Feb 27, 2017 at 19:33

1 Answer 1

1

If your ItemFieldXml should be stored as CDATA in your XML instead of as actual XML, then use XmlDocument.CreateCDataSection:

So instead of this:

item.InnerXml = updateItem.ItemFieldXml;
list.AppendChild( item );

Do this:

XmlCDataSection cdata = doc.CreateCDataSection( updatedItem.ItemFieldXml );
item.AppendChild( cdata );
list.AppendChild( item );

That will render as this:

<item>
<![CDATA[
<foo>embedded XML that is escaped!</foo>
]]>
</item>

The <foo> text will not be interpreted as actual XML by conforming XML parsers.

An alternative is to create a Text node where the angle-brackets will be converted to the XML entities &lt;, &gt;, and &amp;. Using CDATA will be more efficient if you have many angle-brackets because it will require less space.

item.InnerText = updatedItem.ItemFieldXml;
list.AppendChild( item );

This will render as:

<item>
&lt;foo&gt;embedded XML that is escaped!&lt;/foo&gt;
</item>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.