Unsafe reflection (ARCH343)
هذا المحتوى غير متوفر بلغتك بعد.
Key dotnet.security.unsafe-reflection · Severity warning · Category security · CWE CWE-470
Activator.CreateInstance and Type.GetType let code pick a type at run time. When input can decide that type, the caller chooses which class is loaded or instantiated - including ones the code never meant to expose.
The rule reports Activator.CreateInstance only when the code does not pin the type down. A generic call, typeof(...), typeof(X<>).MakeGenericType(...), or a local initialised to one of those and never reassigned is left alone: none of them can be steered by input.
Incorrect
Section titled “Incorrect”public object Create(string typeName){ var type = Type.GetType(typeName); return Activator.CreateInstance(type);}Correct
Section titled “Correct”private static readonly Dictionary<string, Type> Allowed = new(){ ["invoice"] = typeof(InvoiceExporter), ["receipt"] = typeof(ReceiptExporter),};
public object Create(string kind) => Allowed.TryGetValue(kind, out var type) ? Activator.CreateInstance(type)! : throw new ArgumentOutOfRangeException(nameof(kind));Map the input to a type through an allowlist instead of resolving it by name, or fix the type at compile time with a generic or typeof(...).