Repository navigation
Description
What to do
Add a C# query that reports an XML parser whose code explicitly enables DTD processing and assigns an
unrestricted XmlResolver, so that the parser resolves external entities (CWE-611, CWE-827). The configuration
is the weakness, so the query needs no source of untrusted data. cs/xml/insecure-dtd-handling requires a
remote source, and cs/insecure-xml-read (@precision low) reports part of this: run it on the test and say in
the pull request what this query adds over it.
Report this:
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = new XmlUrlResolver();
XmlReader reader = XmlReader.Create(stream, settings);Do not report this:
// DTDs stay prohibited and no resolver is assigned.
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
XmlReader reader = XmlReader.Create(stream, settings);
// DTD parsing without a resolver: on modern .NET, XmlTextReader resolves no external entity unless a resolver
// is assigned.
var textReader = new XmlTextReader(new StringReader(xml));
textReader.DtdProcessing = DtdProcessing.Parse;The files below are a draft of this query from another workspace. It was written for another layout and has never run in this repository. Use it as a starting point: port it, prove it with its test, and change it wherever the test or this repository's conventions disagree with it.
Decisions in the draft
- What is reported:
XmlReader.CreatewithXmlReaderSettingsthat setDtdProcessing = DtdProcessing.Parse
(orProhibitDtd = false) and assign a resolver that is neither null nor anXmlSecureResolver, and an
XmlTextReaderwith such a resolver and DTD processing not disabled (XmlTextReaderparses DTDs by default). - Order: the query uses the last assignment of each property before the parser is created or used, when the
assignments are ordered in control flow. It does not tell apart assignments on branches that exclude each
other. - Not reported: DTD processing enabled without a resolver. On modern .NET it resolves no external entity, so
reporting it would only add false positives. - Metadata:
@kind problem,@precision medium,@security-severity 9.1, CWE-611 and CWE-827. The draft id
cs/xml/explicit-insecure-dtd-resolverneeds this repository's id format. - Test: the draft's
optionsfile references framework assemblies. If they do not resolve, use the shared
stubs as the other tests here do.
Files
The paths below follow this repository's layout but are suggestions. The draft was written for another layout, so its .qlref and options files, and its .md query help, need adapting (most C# queries here use .qhelp).
csharp/src/security/CWE-611/ExplicitInsecureXmlParserConfig.md
# XML parser explicitly configured to resolve external entities
An XML parser that processes Document Type Definitions (DTDs) and also has an unrestricted `XmlResolver` resolves external entities declared in the document. If any part of the XML can be influenced by an attacker, an entity such as `<!ENTITY xxe SYSTEM "file:///etc/passwd">` can disclose local files or make the server issue requests to arbitrary hosts (XML External Entity, XXE).
On modern .NET, `XmlReader.Create` prohibits DTDs by default and `XmlTextReader` does not resolve external entities unless a resolver is assigned. This query therefore only reports parsers where the code explicitly opts in to both behaviours:
- `XmlReader.Create` called with `XmlReaderSettings` that set `DtdProcessing = DtdProcessing.Parse` (or `ProhibitDtd = false`) and assign a non-null `XmlResolver` such as `XmlUrlResolver`.
- `XmlTextReader` with a non-null `XmlResolver` assigned and DTD processing not disabled (`XmlTextReader` parses DTDs by default).
Unlike `cs/xml/insecure-dtd-handling`, this query does not require the XML to come from a known remote source, because the configuration is unsafe for any input that is not fully trusted.
## Recommendation
Leave `DtdProcessing` at its default of `Prohibit` (or set it to `Ignore`), and do not assign an `XmlResolver`, or set it to `null`. If DTD processing is genuinely needed, set `XmlResolver = null` so external entities are not fetched.
## Known limitations
The query recognizes the last property assignment when the assignments are ordered in control flow. It does not distinguish settings writes on mutually exclusive branches.
## Example
The following reader resolves external entities because both DTD processing and an `XmlUrlResolver` are enabled:
```csharp
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = new XmlUrlResolver();
XmlReader reader = XmlReader.Create(stream, settings); // BAD
```
The fix is to keep DTD processing disabled and not assign a resolver:
```csharp
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
XmlReader reader = XmlReader.Create(stream, settings); // GOOD
```
## References
- OWASP: [XML External Entity Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html).
- Microsoft Learn: [XmlReaderSettings.DtdProcessing](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreadersettings.dtdprocessing).
- Common Weakness Enumeration: [CWE-611](https://cwe.mitre.org/data/definitions/611.html).
- Common Weakness Enumeration: [CWE-827](https://cwe.mitre.org/data/definitions/827.html).csharp/src/security/CWE-611/ExplicitInsecureXmlParserConfig.ql
/**
* @name XML parser explicitly configured to resolve external entities
* @description An XML parser that is explicitly configured to process DTDs and to use an
* unrestricted `XmlResolver` resolves external entities, which allows local file
* disclosure and server-side request forgery (XXE) if the XML is attacker-controlled.
* @kind problem
* @problem.severity warning
* @security-severity 9.1
* @precision medium
* @id cs/xml/explicit-insecure-dtd-resolver
* @tags security
* external/cwe/cwe-611
* external/cwe/cwe-827
*/
import csharp
/** Holds if `e` is a value for `XmlResolver` that does not restrict external entity resolution. */
predicate isUnrestrictedResolver(Expr e) {
exists(Expr value |
DataFlow::localExprFlow(value, e) and
not (value = e and e instanceof LocalVariableAccess) and
not value instanceof NullLiteral and
not value.getType().(RefType).hasFullyQualifiedName("System.Xml", "XmlSecureResolver") and
value.getType().(RefType).getABaseType*().hasFullyQualifiedName("System.Xml", "XmlResolver")
)
}
/** Holds if `e` is a value for `DtdProcessing` that enables DTD processing. */
predicate isDtdParse(Expr e) {
e.(FieldAccess).getTarget().(EnumConstant).hasName("Parse") and
e.getType().(Enum).hasFullyQualifiedName("System.Xml", "DtdProcessing")
}
/** Holds if `e` is a value for `DtdProcessing` that disables DTD processing. */
predicate isDtdDisabled(Expr e) {
e.(FieldAccess).getTarget().(EnumConstant).hasName(["Prohibit", "Ignore"]) or
e.(BoolLiteral).getBoolValue() = true
}
/** Holds if `write` assigns `prop` on the object created by `create`. */
private predicate writesProperty(ObjectCreation create, string prop, AssignExpr write) {
exists(MemberInitializer init |
init = write and
init = create.getInitializer().(ObjectInitializer).getAMemberInitializer() and
init.getLeftOperand().(PropertyAccess).getTarget().hasName(prop)
)
or
exists(PropertyAccess access |
access = write.getLeftOperand() and
DataFlow::localExprFlow(create, access.getQualifier()) and
access.getTarget().hasName(prop)
)
}
/**
* Gets a value assigned to property `prop` that is not overwritten before `end`.
* `end` is either the reader creation/use or a return of the settings object.
*/
Expr getAValueForProp(ObjectCreation create, string prop, ControlFlowElement end) {
exists(AssignExpr write |
writesProperty(create, prop, write) and
end.reachableFrom(write) and
not exists(AssignExpr later |
writesProperty(create, prop, later) and
later.reachableFrom(write) and
end.reachableFrom(later)
) and
result = write.getRightOperand()
)
}
/** Gets the effective value of either DTD-processing setting at `end`. */
Expr getAValueForDtdProp(ObjectCreation create, ControlFlowElement end) {
exists(AssignExpr write |
(
writesProperty(create, "DtdProcessing", write) or
writesProperty(create, "ProhibitDtd", write)
) and
end.reachableFrom(write) and
not exists(AssignExpr later |
(
writesProperty(create, "DtdProcessing", later) or
writesProperty(create, "ProhibitDtd", later)
) and
later.reachableFrom(write) and
end.reachableFrom(later)
) and
result = write.getRightOperand()
)
}
/** Gets a point at which the configuration of `create` is observed. */
private ControlFlowElement getAConfigurationEnd(ObjectCreation create, ControlFlowElement use) {
use.getEnclosingCallable() = create.getEnclosingCallable() and
result = use
or
exists(ReturnStmt ret |
use.getEnclosingCallable() != create.getEnclosingCallable() and
ret.getEnclosingCallable() = create.getEnclosingCallable() and
DataFlow::localExprFlow(create, ret.getExpr()) and
result = ret
)
}
/** Holds if `settings` explicitly enables DTD processing and an unrestricted resolver. */
predicate insecureSettings(ObjectCreation settings, ControlFlowElement use, Expr dtd, Expr resolver) {
settings.getObjectType().hasFullyQualifiedName("System.Xml", "XmlReaderSettings") and
exists(ControlFlowElement end |
end = getAConfigurationEnd(settings, use) and
resolver = getAValueForProp(settings, "XmlResolver", end) and
isUnrestrictedResolver(resolver) and
(
dtd = getAValueForDtdProp(settings, end) and isDtdParse(dtd)
or
dtd = getAValueForDtdProp(settings, end) and
dtd.(BoolLiteral).getBoolValue() = false
)
)
}
module InsecureSettingsConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node source) {
exists(MethodCall create |
create.getTarget().hasFullyQualifiedName("System.Xml", "XmlReader", "Create") and
insecureSettings(source.asExpr(), create, _, _)
)
}
predicate isSink(DataFlow::Node sink) {
exists(MethodCall mc |
mc.getTarget().hasFullyQualifiedName("System.Xml", "XmlReader", "Create") and
not exists(Expr firstArg |
firstArg = mc.getArgument(0) and
firstArg
.getType()
.(RefType)
.getABaseType*()
.hasFullyQualifiedName("System.Xml", "XmlReader")
) and
sink.asExpr() = mc.getAnArgument() and
sink.asExpr().getType().(RefType).hasFullyQualifiedName("System.Xml", "XmlReaderSettings")
)
}
}
module InsecureSettingsFlow = DataFlow::Global<InsecureSettingsConfig>;
from Call parser, Expr resolver, string kind
where
exists(ObjectCreation settings, MethodCall create |
create = parser and
insecureSettings(settings, create, _, resolver) and
InsecureSettingsFlow::flow(DataFlow::exprNode(settings),
DataFlow::exprNode(create.getAnArgument())) and
kind = "XmlReaderSettings with DtdProcessing.Parse"
)
or
// `XmlTextReader` processes DTDs by default, so an unrestricted resolver is enough
// unless DTD processing is explicitly disabled.
parser.(ObjectCreation).getObjectType().hasFullyQualifiedName("System.Xml", "XmlTextReader") and
exists(MethodCall read |
DataFlow::localExprFlow(parser, read.getQualifier()) and
read.getTarget().getName() in ["Read", "ReadAsync"] and
read.getQualifier()
.getType()
.(RefType)
.getABaseType*()
.hasFullyQualifiedName("System.Xml", "XmlTextReader") and
resolver = getAValueForProp(parser, "XmlResolver", read) and
isUnrestrictedResolver(resolver) and
not exists(Expr dtd | dtd = getAValueForDtdProp(parser, read) and isDtdDisabled(dtd)) and
kind = "XmlTextReader with DTD processing enabled"
)
select parser, "This XML parser resolves external entities: " + kind + " and an unrestricted $@.",
resolver, "XmlResolver"csharp/test/security/CWE-611/ExplicitInsecureXmlParserConfig/ExplicitInsecureXmlParserConfig.expected
| Test.cs:22:36:22:69 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DtdProcessing.Parse and an unrestricted $@. | Test.cs:17:36:17:55 | object creation of type XmlUrlResolver | XmlResolver |
| Test.cs:37:16:37:48 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DtdProcessing.Parse and an unrestricted $@. | Test.cs:35:27:35:46 | object creation of type XmlUrlResolver | XmlResolver |
| Test.cs:50:16:50:53 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DtdProcessing.Parse and an unrestricted $@. | Test.cs:44:25:44:44 | object creation of type XmlUrlResolver | XmlResolver |
| Test.cs:75:16:75:48 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DtdProcessing.Parse and an unrestricted $@. | Test.cs:74:32:74:39 | access to local variable resolver | XmlResolver |
| Test.cs:111:16:111:48 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DtdProcessing.Parse and an unrestricted $@. | Test.cs:110:32:110:51 | object creation of type XmlUrlResolver | XmlResolver |
| Test.cs:120:16:120:48 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DtdProcessing.Parse and an unrestricted $@. | Test.cs:119:32:119:51 | object creation of type XmlUrlResolver | XmlResolver |
| Test.cs:165:32:165:71 | object creation of type XmlTextReader | This XML parser resolves external entities: XmlTextReader with DTD processing enabled and an unrestricted $@. | Test.cs:167:30:167:49 | object creation of type XmlUrlResolver | XmlResolver |
| Test.cs:185:32:185:71 | object creation of type XmlTextReader | This XML parser resolves external entities: XmlTextReader with DTD processing enabled and an unrestricted $@. | Test.cs:186:30:186:49 | object creation of type XmlUrlResolver | XmlResolver |
| Test.cs:211:32:211:71 | object creation of type XmlTextReader | This XML parser resolves external entities: XmlTextReader with DTD processing enabled and an unrestricted $@. | Test.cs:214:30:214:49 | object creation of type XmlUrlResolver | XmlResolver |
csharp/test/security/CWE-611/ExplicitInsecureXmlParserConfig/ExplicitInsecureXmlParserConfig.qlref
query: ExplicitInsecureXmlParserConfig/ExplicitInsecureXmlParserConfig.ql
postprocess: utils/test/InlineExpectationsTestQuery.ql
csharp/test/security/CWE-611/ExplicitInsecureXmlParserConfig/Test.cs
using System;
using System.IO;
using System.Text;
using System.Xml;
public class XmlReaderCases
{
// XML supplied by a caller-provided delegate argument.
public static void IsParserSafe(Func<string, string> parse) { }
public void SettingsParseWithUrlResolver()
{
IsParserSafe((string xml) =>
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = new XmlUrlResolver();
settings.MaxCharactersFromEntities = 6000;
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
XmlReader reader = XmlReader.Create(stream, settings); // $ Alert
var xmlDocument = new XmlDocument();
xmlDocument.Load(reader);
return xmlDocument.InnerText;
}
});
}
public XmlReader SettingsObjectInitializer(TextReader input)
{
var settings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Parse,
XmlResolver = new XmlUrlResolver()
};
return XmlReader.Create(input, settings); // $ Alert
}
private static XmlReaderSettings MakeSettings()
{
var s = new XmlReaderSettings();
s.DtdProcessing = DtdProcessing.Parse;
s.XmlResolver = new XmlUrlResolver();
return s;
}
public XmlReader SettingsFromHelper(string path)
{
return XmlReader.Create(path, MakeSettings()); // $ Alert
}
public XmlReader SettingsParseOnly(TextReader input)
{
// Resolver not set: the default XmlReaderSettings resolver does not resolve external entities.
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
return XmlReader.Create(input, settings);
}
public XmlReader SettingsResolverOnly(TextReader input)
{
// DTDs prohibited by default.
var settings = new XmlReaderSettings();
settings.XmlResolver = new XmlUrlResolver();
return XmlReader.Create(input, settings);
}
public XmlReader SettingsResolverAlias(TextReader input)
{
XmlResolver resolver = new XmlUrlResolver();
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = resolver;
return XmlReader.Create(input, settings); // $ Alert
}
public XmlReader SettingsNullResolverAlias(TextReader input)
{
XmlResolver resolver = null;
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = resolver;
return XmlReader.Create(input, settings);
}
public XmlReader SettingsSecureResolverAlias(TextReader input)
{
XmlResolver resolver = new XmlSecureResolver(new XmlUrlResolver(), "https://example.com/");
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = resolver;
return XmlReader.Create(input, settings);
}
public XmlReader SettingsResolverReset(TextReader input)
{
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = new XmlUrlResolver();
settings.XmlResolver = null;
return XmlReader.Create(input, settings);
}
public XmlReader SettingsDtdOverwrite(TextReader input)
{
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = new XmlUrlResolver();
return XmlReader.Create(input, settings); // $ Alert
}
public XmlReader SettingsDtdAliasOverwrite(TextReader input)
{
var settings = new XmlReaderSettings();
settings.ProhibitDtd = true;
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = new XmlUrlResolver();
return XmlReader.Create(input, settings); // $ Alert
}
public XmlReader WrapExistingReader(XmlReader input)
{
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = new XmlUrlResolver();
return XmlReader.Create(input, settings);
}
public XmlReader SettingsIgnore(TextReader input)
{
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Ignore;
settings.XmlResolver = new XmlUrlResolver();
return XmlReader.Create(input, settings);
}
public XmlReader SettingsProhibit(TextReader input)
{
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
settings.XmlResolver = new XmlUrlResolver();
return XmlReader.Create(input, settings);
}
public XmlReader SettingsNullResolver(TextReader input)
{
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = null;
return XmlReader.Create(input, settings);
}
public XmlReader DefaultSettings(TextReader input)
{
return XmlReader.Create(input);
}
}
public class XmlTextReaderCases
{
public string ParseWithUrlResolver(string xml)
{
XmlTextReader reader = new XmlTextReader(new StringReader(xml)); // $ Alert
reader.DtdProcessing = DtdProcessing.Parse;
reader.XmlResolver = new XmlUrlResolver();
reader.Read();
return reader.Name;
}
public string ParseWithoutResolver()
{
// Constant XML, DTD parsing on, resolver never set: external entities are not resolved.
string xml = "<?xml version=\"1.0\"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM \"file:///etc/passwd\" >]><foo>&xxe;</foo>";
XmlTextReader reader = new XmlTextReader(new StringReader(xml));
reader.DtdProcessing = DtdProcessing.Parse;
reader.Read();
return reader.Name;
}
public string DefaultDtdWithUrlResolver(string xml)
{
// XmlTextReader parses DTDs by default, so only the resolver needs to be opted in.
XmlTextReader reader = new XmlTextReader(new StringReader(xml)); // $ Alert
reader.XmlResolver = new XmlUrlResolver();
reader.Read();
return reader.Name;
}
public string ProhibitWithUrlResolver(string xml)
{
XmlTextReader reader = new XmlTextReader(new StringReader(xml));
reader.DtdProcessing = DtdProcessing.Prohibit;
reader.XmlResolver = new XmlUrlResolver();
reader.Read();
return reader.Name;
}
public string ProhibitDtdWithUrlResolver(string xml)
{
XmlTextReader reader = new XmlTextReader(new StringReader(xml));
reader.ProhibitDtd = true;
reader.XmlResolver = new XmlUrlResolver();
reader.Read();
return reader.Name;
}
public string ProhibitDtdAliasOverwrittenWithParse(string xml)
{
XmlTextReader reader = new XmlTextReader(new StringReader(xml)); // $ Alert
reader.ProhibitDtd = true;
reader.DtdProcessing = DtdProcessing.Parse;
reader.XmlResolver = new XmlUrlResolver();
reader.Read();
return reader.Name;
}
public string ParseWithNullResolver(string xml)
{
XmlTextReader reader = new XmlTextReader(new StringReader(xml));
reader.DtdProcessing = DtdProcessing.Parse;
reader.XmlResolver = null;
reader.Read();
return reader.Name;
}
}csharp/test/security/CWE-611/ExplicitInsecureXmlParserConfig/options
semmle-extractor-options: /r:System.Xml.ReaderWriter.dll /r:System.Private.Xml.dll /r:System.Runtime.Extensions.dll
How to check it
- Port the files and run the test of the new directory. Compare the results with what the draft expects (its
inline$ Alertand$ MISSING: Alertcomments and its.expectedfile), and explain every difference in
the pull request. - Then run the other gates of the agent profile: format, compile with warnings as errors, query help, suite
selection and id uniqueness.
Rules for the change
- Add only the new query, its library file if it has one, its query help and its test directory.
- Pull request title:
[New Query - <id>] - <what it detects>.
Activity