Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions csharp/src/security/CWE-611/ExplicitInsecureXmlParserConfig.qhelp
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>

<overview>
<p>
An XML parser that processes Document Type Definitions (DTDs) and also has an unrestricted
<code>XmlResolver</code> resolves external entities declared in the document. If any part of the XML can be
influenced by an attacker, an entity such as <code>&lt;!ENTITY xxe SYSTEM "file:///etc/passwd"&gt;</code> can
disclose local files or make the server issue requests to arbitrary hosts (XML External Entity, XXE).
</p>
<p>
On modern .NET, <code>XmlReader.Create</code> prohibits DTDs by default and <code>XmlTextReader</code> does not
resolve external entities unless a resolver is assigned. This query therefore only reports parsers where the code
explicitly opts in to both behaviors:
</p>
<ul>
<li><code>XmlReader.Create</code> called with <code>XmlReaderSettings</code> that set
<code>DtdProcessing = DtdProcessing.Parse</code> (or <code>ProhibitDtd = false</code>) and assign a resolver that
is neither <code>null</code> nor an <code>XmlSecureResolver</code>, such as <code>XmlUrlResolver</code>.</li>
<li><code>XmlTextReader</code> with such a resolver assigned and DTD processing not disabled
(<code>XmlTextReader</code> parses DTDs by default).</li>
</ul>
<p>
Unlike <code>cs/xml/insecure-dtd-handling</code>, 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.
</p>
</overview>

<recommendation>
<p>
For <code>XmlReaderSettings</code>, leave <code>DtdProcessing</code> at its default of <code>Prohibit</code> (or set
it to <code>Ignore</code>), and do not assign an <code>XmlResolver</code>, or set it to <code>null</code>.
<code>XmlTextReader</code> parses DTDs by default, so set its <code>DtdProcessing</code> to <code>Prohibit</code> or
<code>Ignore</code> explicitly, and do not assign an <code>XmlResolver</code>, or set it to <code>null</code>. If DTD
processing is genuinely needed, set <code>XmlResolver = null</code> so that external entities are not fetched.
</p>
</recommendation>

<example>
<p>
The following reader resolves external entities because both DTD processing and an <code>XmlUrlResolver</code>
are enabled:
</p>
<sample language="csharp">
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.XmlResolver = new XmlUrlResolver();
XmlReader reader = XmlReader.Create(stream, settings); // BAD
</sample>
<p>
The fix is to keep DTD processing disabled and not assign a resolver:
</p>
<sample language="csharp">
var settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
XmlReader reader = XmlReader.Create(stream, settings); // GOOD
</sample>
</example>

<section title="Known limitations">
<p>
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. An
<code>XmlTextReader</code> is only reported when its <code>Read</code> or <code>ReadAsync</code> method is called
in the method that creates it.
</p>
<p>
When <code>XmlReaderSettings</code> are created in one method and passed to <code>XmlReader.Create</code> in another,
the query only looks at the settings where a <code>return</code> statement returns them, and ignores changes that
the caller makes afterwards. Settings stored in a field, returned by an expression-bodied member or passed as an
argument are not reported.
</p>
</section>

<references>
<li>OWASP: <a href="https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html">XML External Entity Prevention Cheat Sheet</a>.</li>
<li>Microsoft Learn: <a href="https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreadersettings.dtdprocessing">XmlReaderSettings.DtdProcessing</a>.</li>
</references>

</qhelp>
221 changes: 221 additions & 0 deletions csharp/src/security/CWE-611/ExplicitInsecureXmlParserConfig.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
/**
* @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 githubsecuritylab/cs/explicit-insecure-dtd-resolver
* @tags security
* experimental
* 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")
Comment on lines +22 to +26
)
}

/** 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` or `ProhibitDtd` that disables DTD processing. */
predicate isDtdDisabled(Expr e) {
e.(FieldAccess).getTarget().(EnumConstant).hasName(["Prohibit", "Ignore"]) and
e.getType().(Enum).hasFullyQualifiedName("System.Xml", "DtdProcessing")
or
e.(BoolLiteral).getBoolValue() = true
}

/** An object creation of `XmlReaderSettings` or `XmlTextReader`, whose properties configure a parser. */
class XmlParserConfigCreation extends ObjectCreation {
XmlParserConfigCreation() {
this.getObjectType().hasFullyQualifiedName("System.Xml", ["XmlReaderSettings", "XmlTextReader"])
}
}

/** Holds if `write` assigns `prop` on the object created by `create`. */
private predicate writesProperty(XmlParserConfigCreation 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)
)
}

/** Holds if `write` assigns one of the properties that control DTD processing. */
private predicate writesDtdProperty(XmlParserConfigCreation create, AssignExpr write) {
writesProperty(create, ["DtdProcessing", "ProhibitDtd"], write)
}

/**
* Holds if `later` follows `write`, both writes to a property of the object created by `create`.
* In the same basic block only the order of the writes counts, so that a loop back edge does
* not make each of them follow the other.
*/
private predicate followsWrite(XmlParserConfigCreation create, AssignExpr write, AssignExpr later) {
writesProperty(create, _, write) and
writesProperty(create, _, later) and
(
exists(BasicBlock bb, int i, int j |
bb.getNode(i) = write.getControlFlowNode() and
bb.getNode(j) = later.getControlFlowNode() and
i < j
)
or
later.getBasicBlock() = write.getBasicBlock().getASuccessor+() and
later.getBasicBlock() != write.getBasicBlock()
)
}

/**
* Gets a value assigned to property `prop` of the object created by `create` that is not
* overwritten before `end`.
*/
Expr getAValueForProp(XmlParserConfigCreation 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
followsWrite(create, write, later) and
end.reachableFrom(later)
Comment on lines +98 to +102
) and
result = write.getRightOperand()
)
}

/**
* Gets a value assigned to `DtdProcessing` or `ProhibitDtd` of the object created by `create`
* that is not overwritten by either property before `end`.
*/
Expr getAValueForDtdProp(XmlParserConfigCreation create, ControlFlowElement end) {
exists(AssignExpr write |
writesDtdProperty(create, write) and
end.reachableFrom(write) and
not exists(AssignExpr later |
writesDtdProperty(create, later) and
followsWrite(create, write, later) and
end.reachableFrom(later)
) and
result = write.getRightOperand()
)
}

/**
* Gets a point at which the configuration of `create` is observed: a call to `XmlReader.Create`
* in the same callable, or a return of the object created by `create`.
*/
private ControlFlowElement getAConfigurationEnd(XmlParserConfigCreation create) {
result.(XmlReaderCreateCall).getEnclosingCallable() = create.getEnclosingCallable()
or
exists(ReturnStmt ret |
ret.getEnclosingCallable() = create.getEnclosingCallable() and
DataFlow::localExprFlow(create, ret.getExpr()) and
result = ret
)
}

/** Holds if `settings` explicitly enables DTD processing and an unrestricted resolver at `end`. */
predicate insecureSettings(
XmlParserConfigCreation settings, ControlFlowElement end, Expr dtd, Expr resolver
) {
settings.getObjectType().hasFullyQualifiedName("System.Xml", "XmlReaderSettings") and
end = getAConfigurationEnd(settings) and
resolver = getAValueForProp(settings, "XmlResolver", end) and
isUnrestrictedResolver(resolver) and
dtd = getAValueForDtdProp(settings, end) and
(
isDtdParse(dtd)
or
dtd.(BoolLiteral).getBoolValue() = false
)
}

/**
* Holds if `settings` is insecure with `resolver` when `create` uses it: at `create` itself when
* both are in the same callable, otherwise where `settings` is returned.
*/
predicate insecureSettingsAt(
XmlParserConfigCreation settings, XmlReaderCreateCall create, Expr resolver
) {
exists(ControlFlowElement end | insecureSettings(settings, end, _, resolver) |
end = create
or
end instanceof ReturnStmt and
create.getEnclosingCallable() != settings.getEnclosingCallable()
)
}

/** A call to `XmlReader.Create` that reads XML with the given settings. */
class XmlReaderCreateCall extends MethodCall {
XmlReaderCreateCall() {
this.getTarget().hasFullyQualifiedName("System.Xml", "XmlReader", "Create") and
// A wrapped reader keeps the DTD processing of the reader it wraps.
not this.getArgument(0)
.getType()
.(RefType)
.getABaseType*()
.hasFullyQualifiedName("System.Xml", "XmlReader")
}

/** Gets the `XmlReaderSettings` argument of this call. */
Expr getSettingsArgument() {
result = this.getAnArgument() and
result.getType().(RefType).hasFullyQualifiedName("System.Xml", "XmlReaderSettings")
}
}

module InsecureSettingsConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node source) { insecureSettings(source.asExpr(), _, _, _) }

predicate isSink(DataFlow::Node sink) {
sink.asExpr() = any(XmlReaderCreateCall create).getSettingsArgument()
}
}

module InsecureSettingsFlow = DataFlow::Global<InsecureSettingsConfig>;

from Call parser, Expr resolver, string kind
where
exists(XmlParserConfigCreation settings, XmlReaderCreateCall create |
create = parser and
insecureSettingsAt(settings, create, resolver) and
InsecureSettingsFlow::flow(DataFlow::exprNode(settings),
DataFlow::exprNode(create.getSettingsArgument())) and
kind = "XmlReaderSettings with DTD processing enabled"
)
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
resolver = getAValueForProp(parser, "XmlResolver", read) and
isUnrestrictedResolver(resolver) and
not isDtdDisabled(getAValueForDtdProp(parser, read)) and
kind = "XmlTextReader with DTD processing enabled"
)
select parser, "This XML parser resolves external entities: " + kind + " and an unrestricted $@.",
resolver, "XmlResolver"
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
| Test.cs:22:36:22:69 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DTD processing enabled 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 DTD processing enabled 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 DTD processing enabled 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 DTD processing enabled 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 DTD processing enabled 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 DTD processing enabled 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 |
| Test.cs:244:16:244:49 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DTD processing enabled and an unrestricted $@. | Test.cs:243:32:243:51 | object creation of type XmlUrlResolver | XmlResolver |
| Test.cs:252:16:252:49 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DTD processing enabled and an unrestricted $@. | Test.cs:251:32:251:51 | object creation of type XmlUrlResolver | XmlResolver |
| Test.cs:272:16:272:49 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DTD processing enabled and an unrestricted $@. | Test.cs:271:36:271:55 | object creation of type XmlUrlResolver | XmlResolver |
| Test.cs:301:13:301:46 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DTD processing enabled and an unrestricted $@. | Test.cs:300:36:300:55 | object creation of type XmlUrlResolver | XmlResolver |
| Test.cs:313:13:313:46 | call to method Create | This XML parser resolves external entities: XmlReaderSettings with DTD processing enabled and an unrestricted $@. | Test.cs:312:36:312:55 | object creation of type XmlUrlResolver | XmlResolver |
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
query: security/CWE-611/ExplicitInsecureXmlParserConfig.ql
Loading