CRITICAL
Rule Definition
Using the DangerousGetHandle method can pose security risks because, if the handle has been marked as invalid with SetHandleAsInvalid, DangerousGetHandle still returns the original, potentially stale handle value. The returned handle can also be recycled at any point. At best, this means the handle might suddenly stop working. At worst, if the handle or the resource that the handle represents is exposed to untrusted code, this can lead to a recycling security attack on the reused or returned handle. For example, an untrusted caller can query data on the handle just returned and receive information for an entirely unrelated resource.
Remediation
See the DangerousAddRef and the DangerousRelease methods for more information about using the DangerousGetHandle method safely.
Violation Code Sample
static void Main(string[] args)
{
System.Reflection.FieldInfo myfieldInfo = ...;
SafeHandle handle = (SafeHandle)myfieldInfo.GetValue(aKey);
IntPtr dangerousHandle = handle.DangerousGetHandle(); // violation
}
Fixed Code Sample
static void Main(string[] args)
{
System.Reflection.FieldInfo myfieldInfo = ...;
SafeHandle handle = (SafeHandle)myfieldInfo.GetValue(aKey);
bool addedRef = false;
handle.DangerousAddRef(ref addedRef); // no violation
}
Reference
https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.safehandle.dangerousgethandle?view=netcore-3.1
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.