From b6d8d66438170be6a27273939c1aeafc2a671315 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 31 Oct 2026 03:42:13 +0000 Subject: [PATCH 1/4] Initial plan From 4b01463993f619e561f46503088c4655d2367cf1 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 31 Oct 2026 06:16:00 +0000 Subject: [PATCH 2/4] Add C# cs/unsafe-reflection (CWE-470) and cs/untrusted-search-path (CWE-426) queries with tests Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../src/UnsafeReflection/UnsafeReflection.md | 40 +++++++ .../src/UnsafeReflection/UnsafeReflection.ql | 100 +++++++++++++++++ .../UntrustedSearchPath.md | 37 +++++++ .../UntrustedSearchPath.ql | 84 ++++++++++++++ .../custom/test/UnsafeReflection/Program.cs | 17 +++ .../custom/test/UnsafeReflection/Tests.cs | 89 +++++++++++++++ .../UnsafeReflection.expected | 48 ++++++++ .../UnsafeReflection/UnsafeReflection.ext.yml | 6 + .../UnsafeReflection/UnsafeReflection.qlref | 2 + .../custom/test/UnsafeReflection/options | 1 + .../custom/test/UntrustedSearchPath/Test.cs | 104 ++++++++++++++++++ .../UntrustedSearchPath.expected | 33 ++++++ .../UntrustedSearchPath.qlref | 2 + .../custom/test/UntrustedSearchPath/options | 1 + 14 files changed, 564 insertions(+) create mode 100644 languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.md create mode 100644 languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql create mode 100644 languages/csharp/custom/src/UntrustedSearchPath/UntrustedSearchPath.md create mode 100644 languages/csharp/custom/src/UntrustedSearchPath/UntrustedSearchPath.ql create mode 100644 languages/csharp/custom/test/UnsafeReflection/Program.cs create mode 100644 languages/csharp/custom/test/UnsafeReflection/Tests.cs create mode 100644 languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.expected create mode 100644 languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.ext.yml create mode 100644 languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.qlref create mode 100644 languages/csharp/custom/test/UnsafeReflection/options create mode 100644 languages/csharp/custom/test/UntrustedSearchPath/Test.cs create mode 100644 languages/csharp/custom/test/UntrustedSearchPath/UntrustedSearchPath.expected create mode 100644 languages/csharp/custom/test/UntrustedSearchPath/UntrustedSearchPath.qlref create mode 100644 languages/csharp/custom/test/UntrustedSearchPath/options diff --git a/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.md b/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.md new file mode 100644 index 00000000..f05bf1d5 --- /dev/null +++ b/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.md @@ -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 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). diff --git a/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql b/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql new file mode 100644 index 00000000..f57a51b4 --- /dev/null +++ b/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql @@ -0,0 +1,100 @@ +/** + * @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 | + mc.getTarget().hasName(["Contains", "ContainsKey"]) and + mc.getAnArgument() = 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 + ) + ) +} + +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::getABarrierNode() + } + + predicate observeDiffInformedIncrementalMode() { any() } +} + +module UnsafeReflectionFlow = TaintTracking::Global; + +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" diff --git a/languages/csharp/custom/src/UntrustedSearchPath/UntrustedSearchPath.md b/languages/csharp/custom/src/UntrustedSearchPath/UntrustedSearchPath.md new file mode 100644 index 00000000..370670d4 --- /dev/null +++ b/languages/csharp/custom/src/UntrustedSearchPath/UntrustedSearchPath.md @@ -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). diff --git a/languages/csharp/custom/src/UntrustedSearchPath/UntrustedSearchPath.ql b/languages/csharp/custom/src/UntrustedSearchPath/UntrustedSearchPath.ql new file mode 100644 index 00000000..dbf82d53 --- /dev/null +++ b/languages/csharp/custom/src/UntrustedSearchPath/UntrustedSearchPath.ql @@ -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; + +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() diff --git a/languages/csharp/custom/test/UnsafeReflection/Program.cs b/languages/csharp/custom/test/UnsafeReflection/Program.cs new file mode 100644 index 00000000..489396c7 --- /dev/null +++ b/languages/csharp/custom/test/UnsafeReflection/Program.cs @@ -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); + } +} diff --git a/languages/csharp/custom/test/UnsafeReflection/Tests.cs b/languages/csharp/custom/test/UnsafeReflection/Tests.cs new file mode 100644 index 00000000..14fe1f04 --- /dev/null +++ b/languages/csharp/custom/test/UnsafeReflection/Tests.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace UnsafeReflectionTests +{ + public interface IPlugin { } + + public class Tests + { + private static readonly HashSet AllowedTypes = new HashSet + { + "UnsafeReflectionTests.SafePlugin" + }; + + private static readonly Dictionary TypeMap = new Dictionary + { + ["safe"] = typeof(Tests) + }; + + public void BadTypeGetType() + { + string name = Console.ReadLine(); // $ Source + Type t = Type.GetType(name, true); // $ Alert + Activator.CreateInstance(t); + } + + public void BadActivatorByName() + { + string asm = Console.ReadLine(); // $ Source + string typeName = Console.ReadLine(); // $ Source + Activator.CreateInstance(asm, typeName); // $ Alert + } + + public void BadAssemblyGetType() + { + string typeName = Environment.GetEnvironmentVariable("PLUGIN_TYPE"); // $ Source + Type t = typeof(Tests).Assembly.GetType(typeName); // $ Alert + Activator.CreateInstance(t); + } + + public void BadAssemblyCreateInstance() + { + string typeName = Console.ReadLine(); // $ Source + Assembly.GetExecutingAssembly().CreateInstance("Prefix." + typeName); // $ Alert + } + + public void BadAppDomainCreateInstance() + { + string typeName = Console.ReadLine(); // $ Source + AppDomain.CurrentDomain.CreateInstanceAndUnwrap("SomeAssembly", typeName); // $ Alert + } + + public void GoodConstantTypeName() + { + Type t = Type.GetType("UnsafeReflectionTests.SafePlugin"); + Activator.CreateInstance(t); + } + + public void GoodAllowListContains() + { + string name = Console.ReadLine(); + if (AllowedTypes.Contains(name)) + { + Type t = Type.GetType(name); + Activator.CreateInstance(t); + } + } + + public void GoodAllowListEquality() + { + string name = Console.ReadLine(); + if (name == "UnsafeReflectionTests.SafePlugin") + { + Type t = Type.GetType(name); + Activator.CreateInstance(t); + } + } + + public void GoodLookupTable() + { + string key = Console.ReadLine(); + if (TypeMap.TryGetValue(key, out Type t)) + { + Activator.CreateInstance(t); + } + } + } +} diff --git a/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.expected b/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.expected new file mode 100644 index 00000000..aa431802 --- /dev/null +++ b/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.expected @@ -0,0 +1,48 @@ +#select +| Program.cs:10:34:10:68 | access to array element | Program.cs:10:34:10:65 | call to method GetCommandLineArgs : String[] | Program.cs:10:34:10:68 | access to array element | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Program.cs:10:34:10:65 | call to method GetCommandLineArgs | user-provided value | +| Program.cs:14:38:14:44 | access to array element | Program.cs:7:38:7:41 | args : String[] | Program.cs:14:38:14:44 | access to array element | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Program.cs:7:38:7:41 | args | user-provided value | +| Tests.cs:24:35:24:38 | access to local variable name | Tests.cs:23:27:23:44 | call to method ReadLine : String | Tests.cs:24:35:24:38 | access to local variable name | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Tests.cs:23:27:23:44 | call to method ReadLine | user-provided value | +| Tests.cs:32:38:32:40 | access to local variable asm | Tests.cs:30:26:30:43 | call to method ReadLine : String | Tests.cs:32:38:32:40 | access to local variable asm | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Tests.cs:30:26:30:43 | call to method ReadLine | user-provided value | +| Tests.cs:32:43:32:50 | access to local variable typeName | Tests.cs:31:31:31:48 | call to method ReadLine : String | Tests.cs:32:43:32:50 | access to local variable typeName | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Tests.cs:31:31:31:48 | call to method ReadLine | user-provided value | +| Tests.cs:38:53:38:60 | access to local variable typeName | Tests.cs:37:31:37:79 | call to method GetEnvironmentVariable : String | Tests.cs:38:53:38:60 | access to local variable typeName | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Tests.cs:37:31:37:79 | call to method GetEnvironmentVariable | user-provided value | +| Tests.cs:45:60:45:79 | ... + ... | Tests.cs:44:31:44:48 | call to method ReadLine : String | Tests.cs:45:60:45:79 | ... + ... | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Tests.cs:44:31:44:48 | call to method ReadLine | user-provided value | +| Tests.cs:51:77:51:84 | access to local variable typeName | Tests.cs:50:31:50:48 | call to method ReadLine : String | Tests.cs:51:77:51:84 | access to local variable typeName | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Tests.cs:50:31:50:48 | call to method ReadLine | user-provided value | +edges +| Program.cs:7:38:7:41 | args : String[] | Program.cs:14:38:14:44 | access to array element | provenance | | +| Program.cs:10:34:10:65 | call to method GetCommandLineArgs : String[] | Program.cs:10:34:10:68 | access to array element | provenance | Src:MaD:2455 | +| Tests.cs:23:20:23:23 | access to local variable name : String | Tests.cs:24:35:24:38 | access to local variable name | provenance | | +| Tests.cs:23:27:23:44 | call to method ReadLine : String | Tests.cs:23:20:23:23 | access to local variable name : String | provenance | Src:MaD:2453 | +| Tests.cs:30:20:30:22 | access to local variable asm : String | Tests.cs:32:38:32:40 | access to local variable asm | provenance | | +| Tests.cs:30:26:30:43 | call to method ReadLine : String | Tests.cs:30:20:30:22 | access to local variable asm : String | provenance | Src:MaD:2453 | +| Tests.cs:31:20:31:27 | access to local variable typeName : String | Tests.cs:32:43:32:50 | access to local variable typeName | provenance | | +| Tests.cs:31:31:31:48 | call to method ReadLine : String | Tests.cs:31:20:31:27 | access to local variable typeName : String | provenance | Src:MaD:2453 | +| Tests.cs:37:20:37:27 | access to local variable typeName : String | Tests.cs:38:53:38:60 | access to local variable typeName | provenance | | +| Tests.cs:37:31:37:79 | call to method GetEnvironmentVariable : String | Tests.cs:37:20:37:27 | access to local variable typeName : String | provenance | Src:MaD:2457 | +| Tests.cs:44:20:44:27 | access to local variable typeName : String | Tests.cs:45:60:45:79 | ... + ... | provenance | | +| Tests.cs:44:31:44:48 | call to method ReadLine : String | Tests.cs:44:20:44:27 | access to local variable typeName : String | provenance | Src:MaD:2453 | +| Tests.cs:50:20:50:27 | access to local variable typeName : String | Tests.cs:51:77:51:84 | access to local variable typeName | provenance | | +| Tests.cs:50:31:50:48 | call to method ReadLine : String | Tests.cs:50:20:50:27 | access to local variable typeName : String | provenance | Src:MaD:2453 | +nodes +| Program.cs:7:38:7:41 | args : String[] | semmle.label | args : String[] | +| Program.cs:10:34:10:65 | call to method GetCommandLineArgs : String[] | semmle.label | call to method GetCommandLineArgs : String[] | +| Program.cs:10:34:10:68 | access to array element | semmle.label | access to array element | +| Program.cs:14:38:14:44 | access to array element | semmle.label | access to array element | +| Tests.cs:23:20:23:23 | access to local variable name : String | semmle.label | access to local variable name : String | +| Tests.cs:23:27:23:44 | call to method ReadLine : String | semmle.label | call to method ReadLine : String | +| Tests.cs:24:35:24:38 | access to local variable name | semmle.label | access to local variable name | +| Tests.cs:30:20:30:22 | access to local variable asm : String | semmle.label | access to local variable asm : String | +| Tests.cs:30:26:30:43 | call to method ReadLine : String | semmle.label | call to method ReadLine : String | +| Tests.cs:31:20:31:27 | access to local variable typeName : String | semmle.label | access to local variable typeName : String | +| Tests.cs:31:31:31:48 | call to method ReadLine : String | semmle.label | call to method ReadLine : String | +| Tests.cs:32:38:32:40 | access to local variable asm | semmle.label | access to local variable asm | +| Tests.cs:32:43:32:50 | access to local variable typeName | semmle.label | access to local variable typeName | +| Tests.cs:37:20:37:27 | access to local variable typeName : String | semmle.label | access to local variable typeName : String | +| Tests.cs:37:31:37:79 | call to method GetEnvironmentVariable : String | semmle.label | call to method GetEnvironmentVariable : String | +| Tests.cs:38:53:38:60 | access to local variable typeName | semmle.label | access to local variable typeName | +| Tests.cs:44:20:44:27 | access to local variable typeName : String | semmle.label | access to local variable typeName : String | +| Tests.cs:44:31:44:48 | call to method ReadLine : String | semmle.label | call to method ReadLine : String | +| Tests.cs:45:60:45:79 | ... + ... | semmle.label | ... + ... | +| Tests.cs:50:20:50:27 | access to local variable typeName : String | semmle.label | access to local variable typeName : String | +| Tests.cs:50:31:50:48 | call to method ReadLine : String | semmle.label | call to method ReadLine : String | +| Tests.cs:51:77:51:84 | access to local variable typeName | semmle.label | access to local variable typeName | +subpaths diff --git a/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.ext.yml b/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.ext.yml new file mode 100644 index 00000000..63507f47 --- /dev/null +++ b/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.ext.yml @@ -0,0 +1,6 @@ +extensions: + - addsTo: + pack: codeql/threat-models + extensible: threatModelConfiguration + data: + - ["local", true, 0] diff --git a/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.qlref b/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.qlref new file mode 100644 index 00000000..d527da7e --- /dev/null +++ b/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.qlref @@ -0,0 +1,2 @@ +query: UnsafeReflection/UnsafeReflection.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/languages/csharp/custom/test/UnsafeReflection/options b/languages/csharp/custom/test/UnsafeReflection/options new file mode 100644 index 00000000..71365fa2 --- /dev/null +++ b/languages/csharp/custom/test/UnsafeReflection/options @@ -0,0 +1 @@ +semmle-extractor-options: /r:System.Collections.dll /r:System.Runtime.Extensions.dll diff --git a/languages/csharp/custom/test/UntrustedSearchPath/Test.cs b/languages/csharp/custom/test/UntrustedSearchPath/Test.cs new file mode 100644 index 00000000..2e99b1e0 --- /dev/null +++ b/languages/csharp/custom/test/UntrustedSearchPath/Test.cs @@ -0,0 +1,104 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace UntrustedSearchPathTests +{ + public class Test + { + // Reduced from the Juliet CWE426_Untrusted_Search_Path__Process_01 test case. + public void Bad() + { + string badOsCommand; + string commandArgs; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + badOsCommand = "ls"; // $ Source=ls + commandArgs = "-la"; + } + else + { + badOsCommand = "cmd.exe"; // $ Source=cmd + commandArgs = "/C dir"; + } + using (Process process = new Process()) + { + ProcessStartInfo startInfo = new ProcessStartInfo(); + startInfo.FileName = badOsCommand; // $ Alert=ls Alert=cmd + startInfo.Arguments = commandArgs; + process.StartInfo = startInfo; + process.StartInfo.UseShellExecute = false; + process.Start(); + } + } + + public void Good() + { + string goodOsCommand; + string commandArgs; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + goodOsCommand = "/bin/ls"; + commandArgs = "-la"; + } + else + { + goodOsCommand = "c:\\windows\\system32\\cmd.exe"; + commandArgs = "/C dir"; + } + using (Process process = new Process()) + { + ProcessStartInfo startInfo = new ProcessStartInfo(); + startInfo.FileName = goodOsCommand; + startInfo.Arguments = commandArgs; + process.StartInfo = startInfo; + process.StartInfo.UseShellExecute = false; + process.Start(); + } + } + + public void BadProcessStart() + { + Process.Start("whoami"); // $ Alert + Process.Start("ping", "-c 1 localhost"); // $ Alert + Process.Start("python3.11"); // $ Alert + Process.Start("RUN.BAT"); // $ Alert + } + + public void BadProcessStartInfo() + { + var psi1 = new ProcessStartInfo("git", "status"); // $ Alert + Process.Start(psi1); + var psi2 = new ProcessStartInfo { FileName = "netstat" }; // $ Alert + Process.Start(psi2); + } + + public void BadViaHelper() + { + Run("hostname"); // $ Source=hostname + } + + private static void Run(string program) + { + Process.Start(program); // $ Alert=hostname + } + + public void GoodQualified() + { + Process.Start("/usr/bin/whoami"); + Process.Start(@"C:\Windows\System32\PING.EXE", "localhost"); + Process.Start("./tool"); + Process.Start(".\\tool.exe"); + var psi = new ProcessStartInfo(Environment.ExpandEnvironmentVariables("%SystemRoot%\\System32\\cmd.exe")); + Process.Start(psi); + } + + public void GoodNotAnExecutable() + { + // Documents and URLs are opened through file associations, not the search path. + Process.Start(new ProcessStartInfo("readme.txt") { UseShellExecute = true }); + Process.Start(new ProcessStartInfo("https://example.com") { UseShellExecute = true }); + Process.Start(""); + } + } +} diff --git a/languages/csharp/custom/test/UntrustedSearchPath/UntrustedSearchPath.expected b/languages/csharp/custom/test/UntrustedSearchPath/UntrustedSearchPath.expected new file mode 100644 index 00000000..f10a692b --- /dev/null +++ b/languages/csharp/custom/test/UntrustedSearchPath/UntrustedSearchPath.expected @@ -0,0 +1,33 @@ +#select +| Test.cs:27:38:27:49 | access to local variable badOsCommand | Test.cs:16:32:16:35 | "ls" : String | Test.cs:27:38:27:49 | access to local variable badOsCommand | This process is started using the bare program name $@, which is resolved through the untrusted search path. | Test.cs:16:32:16:35 | "ls" | ls | +| Test.cs:27:38:27:49 | access to local variable badOsCommand | Test.cs:21:32:21:40 | "cmd.exe" : String | Test.cs:27:38:27:49 | access to local variable badOsCommand | This process is started using the bare program name $@, which is resolved through the untrusted search path. | Test.cs:21:32:21:40 | "cmd.exe" | cmd.exe | +| Test.cs:62:27:62:34 | "whoami" | Test.cs:62:27:62:34 | "whoami" | Test.cs:62:27:62:34 | "whoami" | This process is started using the bare program name $@, which is resolved through the untrusted search path. | Test.cs:62:27:62:34 | "whoami" | whoami | +| Test.cs:63:27:63:32 | "ping" | Test.cs:63:27:63:32 | "ping" | Test.cs:63:27:63:32 | "ping" | This process is started using the bare program name $@, which is resolved through the untrusted search path. | Test.cs:63:27:63:32 | "ping" | ping | +| Test.cs:64:27:64:38 | "python3.11" | Test.cs:64:27:64:38 | "python3.11" | Test.cs:64:27:64:38 | "python3.11" | This process is started using the bare program name $@, which is resolved through the untrusted search path. | Test.cs:64:27:64:38 | "python3.11" | python3.11 | +| Test.cs:65:27:65:35 | "RUN.BAT" | Test.cs:65:27:65:35 | "RUN.BAT" | Test.cs:65:27:65:35 | "RUN.BAT" | This process is started using the bare program name $@, which is resolved through the untrusted search path. | Test.cs:65:27:65:35 | "RUN.BAT" | RUN.BAT | +| Test.cs:70:45:70:49 | "git" | Test.cs:70:45:70:49 | "git" | Test.cs:70:45:70:49 | "git" | This process is started using the bare program name $@, which is resolved through the untrusted search path. | Test.cs:70:45:70:49 | "git" | git | +| Test.cs:72:58:72:66 | "netstat" | Test.cs:72:58:72:66 | "netstat" | Test.cs:72:58:72:66 | "netstat" | This process is started using the bare program name $@, which is resolved through the untrusted search path. | Test.cs:72:58:72:66 | "netstat" | netstat | +| Test.cs:83:27:83:33 | access to parameter program | Test.cs:78:17:78:26 | "hostname" : String | Test.cs:83:27:83:33 | access to parameter program | This process is started using the bare program name $@, which is resolved through the untrusted search path. | Test.cs:78:17:78:26 | "hostname" | hostname | +edges +| Test.cs:16:17:16:28 | access to local variable badOsCommand : String | Test.cs:27:38:27:49 | access to local variable badOsCommand | provenance | | +| Test.cs:16:32:16:35 | "ls" : String | Test.cs:16:17:16:28 | access to local variable badOsCommand : String | provenance | | +| Test.cs:21:17:21:28 | access to local variable badOsCommand : String | Test.cs:27:38:27:49 | access to local variable badOsCommand | provenance | | +| Test.cs:21:32:21:40 | "cmd.exe" : String | Test.cs:21:17:21:28 | access to local variable badOsCommand : String | provenance | | +| Test.cs:78:17:78:26 | "hostname" : String | Test.cs:81:40:81:46 | program : String | provenance | | +| Test.cs:81:40:81:46 | program : String | Test.cs:83:27:83:33 | access to parameter program | provenance | | +nodes +| Test.cs:16:17:16:28 | access to local variable badOsCommand : String | semmle.label | access to local variable badOsCommand : String | +| Test.cs:16:32:16:35 | "ls" : String | semmle.label | "ls" : String | +| Test.cs:21:17:21:28 | access to local variable badOsCommand : String | semmle.label | access to local variable badOsCommand : String | +| Test.cs:21:32:21:40 | "cmd.exe" : String | semmle.label | "cmd.exe" : String | +| Test.cs:27:38:27:49 | access to local variable badOsCommand | semmle.label | access to local variable badOsCommand | +| Test.cs:62:27:62:34 | "whoami" | semmle.label | "whoami" | +| Test.cs:63:27:63:32 | "ping" | semmle.label | "ping" | +| Test.cs:64:27:64:38 | "python3.11" | semmle.label | "python3.11" | +| Test.cs:65:27:65:35 | "RUN.BAT" | semmle.label | "RUN.BAT" | +| Test.cs:70:45:70:49 | "git" | semmle.label | "git" | +| Test.cs:72:58:72:66 | "netstat" | semmle.label | "netstat" | +| Test.cs:78:17:78:26 | "hostname" : String | semmle.label | "hostname" : String | +| Test.cs:81:40:81:46 | program : String | semmle.label | program : String | +| Test.cs:83:27:83:33 | access to parameter program | semmle.label | access to parameter program | +subpaths diff --git a/languages/csharp/custom/test/UntrustedSearchPath/UntrustedSearchPath.qlref b/languages/csharp/custom/test/UntrustedSearchPath/UntrustedSearchPath.qlref new file mode 100644 index 00000000..c4466446 --- /dev/null +++ b/languages/csharp/custom/test/UntrustedSearchPath/UntrustedSearchPath.qlref @@ -0,0 +1,2 @@ +query: UntrustedSearchPath/UntrustedSearchPath.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/languages/csharp/custom/test/UntrustedSearchPath/options b/languages/csharp/custom/test/UntrustedSearchPath/options new file mode 100644 index 00000000..4996500c --- /dev/null +++ b/languages/csharp/custom/test/UntrustedSearchPath/options @@ -0,0 +1 @@ +semmle-extractor-options: /r:System.Diagnostics.Process.dll /r:System.Runtime.InteropServices.dll /r:System.Runtime.InteropServices.RuntimeInformation.dll /r:System.ComponentModel.Primitives.dll From dc4f7dabefcaa9dc2fefe60b86c404f8af3e19eb Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 2 Nov 2026 21:27:32 +0000 Subject: [PATCH 3/4] Restrict unsafe reflection allowlist guards Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../src/UnsafeReflection/UnsafeReflection.ql | 53 ++++++++++++++++++- .../custom/test/UnsafeReflection/Tests.cs | 21 ++++++++ .../UnsafeReflection.expected | 6 +++ 3 files changed, 78 insertions(+), 2 deletions(-) diff --git a/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql b/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql index f57a51b4..c988b7a3 100644 --- a/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql +++ b/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql @@ -63,8 +63,26 @@ class ReflectionTypeNameSink extends DataFlow::ExprNode { */ private predicate allowListGuard(Guard guard, Expr e, GuardValue branch) { exists(MethodCall mc | mc = guard | - mc.getTarget().hasName(["Contains", "ContainsKey"]) and - mc.getAnArgument() = e and + ( + 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 @@ -79,6 +97,37 @@ private predicate allowListGuard(Guard guard, Expr e, GuardValue branch) { ) } +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 } diff --git a/languages/csharp/custom/test/UnsafeReflection/Tests.cs b/languages/csharp/custom/test/UnsafeReflection/Tests.cs index 14fe1f04..ba3de223 100644 --- a/languages/csharp/custom/test/UnsafeReflection/Tests.cs +++ b/languages/csharp/custom/test/UnsafeReflection/Tests.cs @@ -67,6 +67,27 @@ public void GoodAllowListContains() } } + public void BadStringContains() + { + string input = Console.ReadLine(); + string name = Console.ReadLine(); // $ Source + if (input.Contains(name)) + { + Type t = Type.GetType(name); // $ Alert + Activator.CreateInstance(t); + } + } + + public void GoodDictionaryContainsKey() + { + string name = Console.ReadLine(); + if (TypeMap.ContainsKey(name)) + { + Type t = Type.GetType(name); + Activator.CreateInstance(t); + } + } + public void GoodAllowListEquality() { string name = Console.ReadLine(); diff --git a/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.expected b/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.expected index aa431802..ee3862ce 100644 --- a/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.expected +++ b/languages/csharp/custom/test/UnsafeReflection/UnsafeReflection.expected @@ -7,6 +7,7 @@ | Tests.cs:38:53:38:60 | access to local variable typeName | Tests.cs:37:31:37:79 | call to method GetEnvironmentVariable : String | Tests.cs:38:53:38:60 | access to local variable typeName | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Tests.cs:37:31:37:79 | call to method GetEnvironmentVariable | user-provided value | | Tests.cs:45:60:45:79 | ... + ... | Tests.cs:44:31:44:48 | call to method ReadLine : String | Tests.cs:45:60:45:79 | ... + ... | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Tests.cs:44:31:44:48 | call to method ReadLine | user-provided value | | Tests.cs:51:77:51:84 | access to local variable typeName | Tests.cs:50:31:50:48 | call to method ReadLine : String | Tests.cs:51:77:51:84 | access to local variable typeName | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Tests.cs:50:31:50:48 | call to method ReadLine | user-provided value | +| Tests.cs:76:39:76:42 | access to local variable name | Tests.cs:73:27:73:44 | call to method ReadLine : String | Tests.cs:76:39:76:42 | access to local variable name | This type name, which is used to load or instantiate a type through reflection, depends on a $@. | Tests.cs:73:27:73:44 | call to method ReadLine | user-provided value | edges | Program.cs:7:38:7:41 | args : String[] | Program.cs:14:38:14:44 | access to array element | provenance | | | Program.cs:10:34:10:65 | call to method GetCommandLineArgs : String[] | Program.cs:10:34:10:68 | access to array element | provenance | Src:MaD:2455 | @@ -22,6 +23,8 @@ edges | Tests.cs:44:31:44:48 | call to method ReadLine : String | Tests.cs:44:20:44:27 | access to local variable typeName : String | provenance | Src:MaD:2453 | | Tests.cs:50:20:50:27 | access to local variable typeName : String | Tests.cs:51:77:51:84 | access to local variable typeName | provenance | | | Tests.cs:50:31:50:48 | call to method ReadLine : String | Tests.cs:50:20:50:27 | access to local variable typeName : String | provenance | Src:MaD:2453 | +| Tests.cs:73:20:73:23 | access to local variable name : String | Tests.cs:76:39:76:42 | access to local variable name | provenance | | +| Tests.cs:73:27:73:44 | call to method ReadLine : String | Tests.cs:73:20:73:23 | access to local variable name : String | provenance | Src:MaD:2453 | nodes | Program.cs:7:38:7:41 | args : String[] | semmle.label | args : String[] | | Program.cs:10:34:10:65 | call to method GetCommandLineArgs : String[] | semmle.label | call to method GetCommandLineArgs : String[] | @@ -45,4 +48,7 @@ nodes | Tests.cs:50:20:50:27 | access to local variable typeName : String | semmle.label | access to local variable typeName : String | | Tests.cs:50:31:50:48 | call to method ReadLine : String | semmle.label | call to method ReadLine : String | | Tests.cs:51:77:51:84 | access to local variable typeName | semmle.label | access to local variable typeName | +| Tests.cs:73:20:73:23 | access to local variable name : String | semmle.label | access to local variable name : String | +| Tests.cs:73:27:73:44 | call to method ReadLine : String | semmle.label | call to method ReadLine : String | +| Tests.cs:76:39:76:42 | access to local variable name | semmle.label | access to local variable name | subpaths From 6f8da97dbf57aaada23d089dedc649d28dbe2ab2 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 2 Nov 2026 21:31:22 +0000 Subject: [PATCH 4/4] Format unsafe reflection membership query Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../custom/src/UnsafeReflection/UnsafeReflection.ql | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql b/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql index c988b7a3..a6336d13 100644 --- a/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql +++ b/languages/csharp/custom/src/UnsafeReflection/UnsafeReflection.ql @@ -101,14 +101,14 @@ private predicate isCollectionMembershipReceiver(Expr receiver) { exists(ValueOrRefType receiverType | receiverType = receiver.getType() and ( - receiverType.getABaseType*().hasFullyQualifiedName("System.Collections", ["IList", "IDictionary"]) + 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"] - ) + base.getUnboundGeneric() + .hasFullyQualifiedName("System.Collections.Generic", ["ICollection`1", "ISet`1"]) ) ) ) @@ -122,7 +122,8 @@ private predicate isDictionaryMembershipReceiver(Expr receiver) { or exists(ConstructedType base | base = receiverType.getABaseType*() and - base.getUnboundGeneric().hasFullyQualifiedName("System.Collections.Generic", "IDictionary`2") + base.getUnboundGeneric() + .hasFullyQualifiedName("System.Collections.Generic", "IDictionary`2") ) ) )