Possible XML External Entity (XXE) attack

The CS.XXE.TEXT_READER checker flags instances of XML input that are processed by a weakly configured XmlTextReader 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+, XmlTextReader has DTDs disabled by default, and can only become unsafe if you use a nonnull XmlResolver with default or unsafe settings.

Vulnerable code example

1  static void LoadXML()
2   {
3     string xxePayload = "<!DOCTYPE doc [<!ENTITY win SYSTEM 'file:///C:/Users/SecretData.txt'>]>"
4                       + "<doc>&win;</doc>";
5     string xml = "<?xml version='1.0' ?>" + xxePayload; 
7      XmlTextReader reader = new XmlTextReader(xml);
8      reader.XmlResolver = new XmlUrlResolver(); // Defect: XmlTextReader.XmlResolver configured 
9                                                 // with XmlUrlResolver makes it unsafe
10     while (reader.Read())
11     { ... }
12  }

Fixed code example

1  static void LoadXML()
2  {
3      string xxePayload = "<!DOCTYPE doc [<!ENTITY win SYSTEM 'file:///C:/Users/SecretData.txt'>]>" + "<doc>&win;</doc>";
4      string xml = "<?xml version='1.0' ?>" + xxePayload; 
6      XmlTextReader reader = new XmlTextReader(xml);
7      reader.XmlResolver = null;
8      while (reader.Read())
9      { ... }
10 }

Related checkers

Security training

Application security training materials provided by Secure Code Warrior.