title: How to prevent XXE attack (XmlDocument in .NET)
body: <p>We had a security audit on our code, and they mentioned that our code is vulnerable to EXternal Entity (XXE) attack. I am using following code -</p>
  <pre><code>string OurOutputXMLString=
  &quot;&lt;ce&gt;&lt;input&gt;&lt;transaction&gt;&lt;length&gt;00000&lt;/length&gt;&lt;tran_type&gt;Login&lt;/tran_type&gt;&lt;/transaction&gt;&lt;user&gt;&lt;user_id&gt;ce_userid&lt;/user_id&gt;&lt;subscriber_name&gt;ce_subscribername&lt;/subscriber_name&gt;&lt;subscriber_id&gt;ce_subscriberid&lt;/subscriber_id&gt;&lt;group_id&gt;ce_groupid&lt;/group_id&gt;&lt;permissions&gt;&lt;/permissions&gt;&lt;/user&gt;&lt;consumer&gt;&lt;login_details&gt;&lt;username&gt;UnitTester9&lt;/username&gt;&lt;password&gt;pDhE5AsKBHw85Sqgg6qdKQ==&lt;/password&gt;&lt;pin&gt;tOlkiae9epM=&lt;/pin&gt;&lt;/login_details&gt;&lt;/consumer&gt;&lt;/input&gt;&lt;/ce&gt;&quot;
  
   XmlDocument xmlDoc = new XmlDocument();
   xmlDoc.LoadXml(OurOutputXMLString);
  </code></pre>
  <p>In the audit report they say that it's failing because an XML entity can contain URLs that can resolve outside of intended control. XML entity resolver will attempt to resolve and retrieve external references. If attacker-controlled XML can be submitted to one of these functions, then the attacker could gain access to information about an internal network, local filesystem, or other sensitive data.
  To avoid this I wrote the following code but it doesn't work.</p>
  <pre><code>MemoryStream stream =
      new MemoryStream(System.Text.Encoding.Default.GetBytes(OurOutputXMLString));
  
  XmlReaderSettings settings = new XmlReaderSettings();
  
  settings.DtdProcessing = DtdProcessing.Prohibit;
  settings.MaxCharactersFromEntities = 6000;
  XmlReader reader = XmlReader.Create(stream, settings);
  XmlDocument xmlDoc = new XmlDocument();
  xmlDoc.Load(reader);
  </code></pre>
  <p>But I can see here that reader does not have any value to load into <code>xmlDoc(XmlDocument)</code>.
  Can anyone help where I am missing things?</p>