Rules / C#
SHIELD-CSHARP-021
Unsafe reflection from user-controlled type name
What it detects
Type.GetType or Activator.CreateInstance is invoked with a variable type name from untrusted input.
How to fix
Map user input to an allowlisted set of known types rather than resolving arbitrary type names.
Vulnerable — Shield flags thisExportFactory.cs
public class ExportFactory
{
public object CreateExporter(HttpRequest request)
{
var typeName = request.QueryString["exporter"];
// attacker can instantiate any loadable type
return Activator.CreateInstance(Type.GetType(typeName));
}
}
Fixed — scans cleanExportFactory.cs
public class ExportFactory
{
public IExporter CreateExporter(string format) => format switch
{
"csv" => new CsvExporter(),
"pdf" => new PdfExporter(),
"json" => new JsonExporter(),
_ => throw new NotSupportedException("Unknown export format"),
};
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-CSHARP-021, the fixed one does not.