CS.XXE.DOCUMENT
Possible XML External Entity (XXE) attack
The CS.XXE.DOCUMENT checker flags instances of XML input that are processed by a weakly configured XmlDocument parser.
Vulnerability and risk
An XML External Entity attack is a type of attack against an application that parses XML input. This attack occurs when XML input that contains a reference to an external entity is processed by a weakly configured XML parser. This attack can lead to the disclosure of confidential data, denial of service, server side request forgery, port scanning from the perspective of the machine where the parser is located, and other system impacts.
Mitigation and prevention
The safest way to prevent an XXE attack is to completely disable DTDs (External Entities). Depending on the parser, the method can be different. For example, in .NET 4.5.2+, XDocument has DTDs disabled by default, and can only become unsafe if you use a nonnull XmlResolver with default or unsafe settings.
Vulnerable code example
static void LoadXML()
{
string xxePayload = "<!DOCTYPE doc [<!ENTITY win SYSTEM 'file:///C:/Users/testdata2.txt'>]>"
+ "<doc>&win;</doc>";
string xml = "<?xml version='1.0' ?>" + xxePayload;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.XmlResolver = new XmlUrlResolver(); // Defect reported here. XmlResolver configured with XmlUrlResolver makes it unsafe.
xmlDoc.LoadXml(xml);
Console.WriteLine(xmlDoc.InnerText);
Console.ReadLine();
}
Fixed code example
static void LoadXML()
{
string xxePayload = "<!DOCTYPE doc [<!ENTITY win SYSTEM 'file:///C:/Users/testdata2.txt'>]>"
+ "<doc>&win;</doc>";
string xml = "<?xml version='1.0' ?>" + xxePayload;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.XmlResolver = null; // Setting the XmlResolver to null, or not setting it at all
// (it is null by default), disables DTDs. This should help prevent XXE attacks.
xmlDoc.LoadXml(xml);
Console.WriteLine(xmlDoc.InnerText);
Console.ReadLine();
}
Related checkers
External guidance
Security training
Application security training materials provided by Secure Code Warrior.