Repository navigation
[NEW QUERY] C#: cs/unsafe-reflection (CWE-470) and cs/untrusted-search-path (CWE-426) #341
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Copilot
wants to merge
4
commits into
main
Choose a base branch
from
copilot/csharp-query-create-ssrf-reflection-injection
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| # Use of externally-controlled input to select classes or code | ||
|
|
||
| Reflection APIs such as `Type.GetType`, `Assembly.GetType`, `Assembly.CreateInstance`, `Activator.CreateInstance(string, string)` and `AppDomain.CreateInstanceAndUnwrap` look up a type (and sometimes load an assembly) by name at run time. If that name comes from a user, the user can choose any type that can be loaded by the application. Instantiating it runs the type's constructor, static initializer and any other code that the application then calls on the object, which can lead to unexpected behavior, information disclosure, or code execution. | ||
|
|
||
| ## Recommendation | ||
|
|
||
| Do not let users choose arbitrary type or assembly names. Map user input to a fixed set of known types (for example with a dictionary from a user-visible key to a `Type`), or check the name against an explicit allow list before resolving it. | ||
|
|
||
| ## Example | ||
|
|
||
| The following program resolves a type named on the command line and creates an instance of it: | ||
|
|
||
| ```csharp | ||
| Type type = Type.GetType(Environment.GetCommandLineArgs()[1]); | ||
| var surprise = Activator.CreateInstance(type!); | ||
| ``` | ||
|
|
||
| Instead, map the input to a known set of types: | ||
|
|
||
| ```csharp | ||
| static readonly Dictionary<string, Type> Plugins = new() | ||
| { | ||
| ["csv"] = typeof(CsvExporter), | ||
| ["json"] = typeof(JsonExporter), | ||
| }; | ||
|
|
||
| if (Plugins.TryGetValue(args[0], out var type)) | ||
| { | ||
| var exporter = Activator.CreateInstance(type); | ||
| } | ||
| ``` | ||
|
|
||
| ## Notes | ||
|
|
||
| The query uses the active threat models. Command-line arguments, environment variables and console input are `local` sources, so they are only reported when the `local` threat model is enabled. | ||
|
|
||
| ## References | ||
|
|
||
| - Common Weakness Enumeration: [CWE-470](https://cwe.mitre.org/data/definitions/470.html). | ||
| - OWASP: [Unsafe use of Reflection](https://owasp.org/www-community/vulnerabilities/Unsafe_use_of_Reflection). |
150 changes: 150 additions & 0 deletions
150
languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| /** | ||
| * @name Use of externally-controlled input to select classes or code | ||
| * @description Resolving or instantiating a type whose name is controlled by a user | ||
| * allows the user to load and construct arbitrary types, running their | ||
| * constructors and other code that the application did not intend to run. | ||
| * @kind path-problem | ||
| * @problem.severity warning | ||
| * @security-severity 6.5 | ||
| * @precision medium | ||
| * @id cs/unsafe-reflection | ||
| * @tags security | ||
| * external/cwe/cwe-470 | ||
| */ | ||
|
|
||
| import csharp | ||
| import semmle.code.csharp.commons.ComparisonTest | ||
| import semmle.code.csharp.controlflow.Guards | ||
| import semmle.code.csharp.security.dataflow.flowsources.FlowSources | ||
| import UnsafeReflectionFlow::PathGraph | ||
|
|
||
| /** | ||
| * A string argument that names a type (or the assembly containing it) that is | ||
| * resolved or instantiated through reflection. | ||
| */ | ||
| class ReflectionTypeNameSink extends DataFlow::ExprNode { | ||
| ReflectionTypeNameSink() { | ||
| exists(Call c, Callable target, Parameter p | | ||
| target = c.getTarget() and | ||
| p = target.getAParameter() and | ||
| p.getType() instanceof StringType and | ||
| this.getExpr() = c.getArgumentForParameter(p) | ||
| | | ||
| // System.Type.GetType(string typeName, ...) and Type.GetTypeFromProgID(string progID, ...) | ||
| target.getDeclaringType().hasFullyQualifiedName("System", "Type") and | ||
| target.hasName(["GetType", "GetTypeFromProgID"]) and | ||
| p.getPosition() = 0 | ||
| or | ||
| // System.Reflection.Assembly / Module .GetType(string name, ...) and Assembly.CreateInstance(string typeName, ...) | ||
| target | ||
| .getDeclaringType() | ||
| .getABaseType*() | ||
| .hasFullyQualifiedName("System.Reflection", ["Assembly", "Module"]) and | ||
| target.hasName(["GetType", "CreateInstance"]) and | ||
| p.getPosition() = 0 | ||
| or | ||
| // System.Activator.CreateInstance(From)(string assemblyName, string typeName, ...) | ||
| target.getDeclaringType().hasFullyQualifiedName("System", "Activator") and | ||
| target.hasName(["CreateInstance", "CreateInstanceFrom"]) and | ||
| p.hasName(["assemblyName", "assemblyFile", "typeName"]) | ||
| or | ||
| // System.AppDomain.CreateInstance*(string assemblyName, string typeName, ...) | ||
| target.getDeclaringType().hasFullyQualifiedName("System", "AppDomain") and | ||
| target.getName().matches("CreateInstance%") and | ||
| p.hasName(["assemblyName", "assemblyFile", "typeName"]) | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Holds if `guard` restricts `e` to an allow-listed value when it evaluates to `branch`, | ||
| * either by membership in a collection (`allowed.Contains(e)`) or by equality with a | ||
| * compile-time constant. | ||
| */ | ||
| private predicate allowListGuard(Guard guard, Expr e, GuardValue branch) { | ||
| exists(MethodCall mc | mc = guard | | ||
| ( | ||
| exists(Expr receiver | | ||
| mc.getQualifier() = receiver and | ||
| mc.getArgument(0) = e and | ||
| mc.getTarget().hasName("Contains") and | ||
| not mc.getTarget().getDeclaringType().hasFullyQualifiedName("System", "String") and | ||
| isCollectionMembershipReceiver(receiver) | ||
| ) | ||
| or | ||
| exists(Expr receiver | | ||
| mc.getQualifier() = receiver and | ||
| mc.getArgument(0) = e and | ||
| mc.getTarget().hasName("ContainsKey") and | ||
| isDictionaryMembershipReceiver(receiver) | ||
| ) | ||
| or | ||
| mc.getTarget().getDeclaringType().hasFullyQualifiedName("System.Linq", "Enumerable") and | ||
| mc.getTarget().hasName("Contains") and | ||
| mc.getArgument(1) = e | ||
| ) and | ||
| branch.asBooleanValue() = true | ||
| ) | ||
| or | ||
| exists(ComparisonTest ct | ct.getExpr() = guard | | ||
| ct.getAnArgument() = e and | ||
| ct.getAnArgument() instanceof StringLiteral and | ||
| ( | ||
| ct.getComparisonKind().isEquality() and branch.asBooleanValue() = true | ||
| or | ||
| ct.getComparisonKind().isInequality() and branch.asBooleanValue() = false | ||
| ) | ||
| ) | ||
| } | ||
|
|
||
| private predicate isCollectionMembershipReceiver(Expr receiver) { | ||
| exists(ValueOrRefType receiverType | | ||
| receiverType = receiver.getType() and | ||
| ( | ||
| receiverType | ||
| .getABaseType*() | ||
| .hasFullyQualifiedName("System.Collections", ["IList", "IDictionary"]) | ||
| or | ||
| exists(ConstructedType base | | ||
| base = receiverType.getABaseType*() and | ||
| base.getUnboundGeneric() | ||
| .hasFullyQualifiedName("System.Collections.Generic", ["ICollection`1", "ISet`1"]) | ||
| ) | ||
| ) | ||
| ) | ||
| } | ||
|
|
||
| private predicate isDictionaryMembershipReceiver(Expr receiver) { | ||
| exists(ValueOrRefType receiverType | | ||
| receiverType = receiver.getType() and | ||
| ( | ||
| receiverType.getABaseType*().hasFullyQualifiedName("System.Collections", "IDictionary") | ||
| or | ||
| exists(ConstructedType base | | ||
| base = receiverType.getABaseType*() and | ||
| base.getUnboundGeneric() | ||
| .hasFullyQualifiedName("System.Collections.Generic", "IDictionary`2") | ||
| ) | ||
| ) | ||
| ) | ||
| } | ||
|
|
||
| module UnsafeReflectionConfig implements DataFlow::ConfigSig { | ||
| predicate isSource(DataFlow::Node source) { source instanceof ActiveThreatModelSource } | ||
|
|
||
| predicate isSink(DataFlow::Node sink) { sink instanceof ReflectionTypeNameSink } | ||
|
|
||
| predicate isBarrier(DataFlow::Node node) { | ||
| node = DataFlow::BarrierGuard<allowListGuard/3>::getABarrierNode() | ||
| } | ||
|
|
||
| predicate observeDiffInformedIncrementalMode() { any() } | ||
| } | ||
|
|
||
| module UnsafeReflectionFlow = TaintTracking::Global<UnsafeReflectionConfig>; | ||
|
|
||
| from UnsafeReflectionFlow::PathNode source, UnsafeReflectionFlow::PathNode sink | ||
| where UnsafeReflectionFlow::flowPath(source, sink) | ||
| select sink.getNode(), source, sink, | ||
| "This type name, which is used to load or instantiate a type through reflection, depends on a $@.", | ||
| source.getNode(), "user-provided value" |
37 changes: 37 additions & 0 deletions
37
languages/csharp/custom/src/UntrustedSearchPath/UntrustedSearchPath.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| # Process started without a fully qualified path | ||
|
|
||
| When a program is started with `Process.Start`, `new ProcessStartInfo(...)` or by setting `ProcessStartInfo.FileName` to a bare name such as `ls` or `cmd.exe`, the operating system locates the executable by searching the directories in the `PATH` environment variable (and, on Windows, the application and current directories). If an attacker can place a file with the same name earlier in that search order, their program runs instead of the intended one, with the privileges of the application. | ||
|
|
||
| ## Recommendation | ||
|
|
||
| Start external programs by their fully qualified path, for example `/bin/ls` or `C:\Windows\System32\cmd.exe`, or build the path from a trusted location such as `Environment.SystemDirectory`. | ||
|
|
||
| ## Example | ||
|
|
||
| In the following example, the command is started by its bare name, so it is resolved through the search path: | ||
|
|
||
| ```csharp | ||
| var startInfo = new ProcessStartInfo(); | ||
| startInfo.FileName = "ls"; | ||
| startInfo.Arguments = "-la"; | ||
| Process.Start(startInfo); | ||
| ``` | ||
|
|
||
| Use the full path to the executable instead: | ||
|
|
||
| ```csharp | ||
| var startInfo = new ProcessStartInfo(); | ||
| startInfo.FileName = "/bin/ls"; | ||
| startInfo.Arguments = "-la"; | ||
| Process.Start(startInfo); | ||
| ``` | ||
|
|
||
| ## Notes | ||
|
|
||
| Names with a non-executable file extension (for example `readme.txt`) are not reported, since they are normally documents opened through a file association rather than programs looked up on the search path. | ||
|
|
||
| ## References | ||
|
|
||
| - Common Weakness Enumeration: [CWE-426](https://cwe.mitre.org/data/definitions/426.html). | ||
| - Common Weakness Enumeration: [CWE-427](https://cwe.mitre.org/data/definitions/427.html). | ||
| - Microsoft: [ProcessStartInfo.FileName](https://learn.microsoft.com/dotnet/api/system.diagnostics.processstartinfo.filename). |
84 changes: 84 additions & 0 deletions
84
languages/csharp/custom/src/UntrustedSearchPath/UntrustedSearchPath.ql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| /** | ||
| * @name Process started without a fully qualified path | ||
| * @description Starting an external program by its bare name (for example `ls` or | ||
| * `cmd.exe`) makes the operating system resolve it through the `PATH` | ||
| * search path (and, on Windows, the application and current directories). | ||
| * An attacker who can place a same-named executable earlier in that search | ||
| * order can run their own program with the privileges of the application. | ||
| * @kind path-problem | ||
| * @problem.severity warning | ||
| * @security-severity 6.7 | ||
| * @precision medium | ||
| * @id cs/untrusted-search-path | ||
| * @tags security | ||
| * external/cwe/cwe-426 | ||
| * external/cwe/cwe-427 | ||
| */ | ||
|
|
||
| import csharp | ||
| import UntrustedSearchPathFlow::PathGraph | ||
|
|
||
| /** | ||
| * A string literal that names a program without any directory component, so that it | ||
| * is resolved through the search path when it is started. | ||
| * | ||
| * Names with a file extension other than a Windows executable extension (for example | ||
| * `readme.txt`) are excluded, since they are typically documents opened through a file | ||
| * association rather than programs looked up on the search path. | ||
| */ | ||
| class BareExecutableNameLiteral extends StringLiteral { | ||
| BareExecutableNameLiteral() { | ||
| exists(string v | v = this.getValue() | | ||
| v.regexpMatch("[A-Za-z0-9_][A-Za-z0-9_.+-]*") and | ||
| ( | ||
| not v.regexpMatch(".*\\.[A-Za-z][A-Za-z0-9]*") | ||
| or | ||
| v.regexpMatch("(?i).*\\.(exe|com|bat|cmd)") | ||
| ) | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| /** An expression that specifies the program file to start as a new process. */ | ||
| class ProcessFileNameSink extends DataFlow::ExprNode { | ||
| ProcessFileNameSink() { | ||
| // startInfo.FileName = ... (including object initializers) | ||
| exists(Property p | | ||
| p.getDeclaringType().hasFullyQualifiedName("System.Diagnostics", "ProcessStartInfo") and | ||
| p.hasName("FileName") and | ||
| this.getExpr() = p.getAnAssignedValue() | ||
| ) | ||
| or | ||
| // new ProcessStartInfo(fileName, ...) and Process.Start(fileName, ...) | ||
| exists(Call c, Callable target | | ||
| target = c.getTarget() and | ||
| ( | ||
| target | ||
| .(InstanceConstructor) | ||
| .getDeclaringType() | ||
| .hasFullyQualifiedName("System.Diagnostics", "ProcessStartInfo") | ||
| or | ||
| target.(Method).isStatic() and | ||
| target.hasName("Start") and | ||
| target.getDeclaringType().hasFullyQualifiedName("System.Diagnostics", "Process") | ||
| ) and | ||
| this.getExpr() = c.getArgumentForName("fileName") | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| module UntrustedSearchPathConfig implements DataFlow::ConfigSig { | ||
| predicate isSource(DataFlow::Node source) { source.asExpr() instanceof BareExecutableNameLiteral } | ||
|
|
||
| predicate isSink(DataFlow::Node sink) { sink instanceof ProcessFileNameSink } | ||
|
|
||
| predicate observeDiffInformedIncrementalMode() { any() } | ||
| } | ||
|
|
||
| module UntrustedSearchPathFlow = DataFlow::Global<UntrustedSearchPathConfig>; | ||
|
|
||
| from UntrustedSearchPathFlow::PathNode source, UntrustedSearchPathFlow::PathNode sink | ||
| where UntrustedSearchPathFlow::flowPath(source, sink) | ||
| select sink.getNode(), source, sink, | ||
| "This process is started using the bare program name $@, which is resolved through the untrusted search path.", | ||
| source.getNode(), source.getNode().asExpr().(StringLiteral).getValue() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| // Reduced from a console program that instantiates a type named on the command line. | ||
| // (Written with an explicit Main because the test extractor compiles a library.) | ||
| using System; | ||
|
|
||
| public static class Program | ||
| { | ||
| public static void Main(string[] args) // $ Source | ||
| { | ||
| Console.WriteLine("I don't need a ctor!"); | ||
| Type type = Type.GetType(Environment.GetCommandLineArgs()[1]); // $ Alert | ||
| var surprise = Activator.CreateInstance(type!); | ||
| Console.WriteLine(surprise.ToString()); | ||
|
|
||
| Type fromArgs = Type.GetType(args[0]); // $ Alert | ||
| Activator.CreateInstance(fromArgs); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.