Why is this an issue?
SafeHandle.DangerousGetHandle method poses significant risks and should be used carefully. This method carries the inherent danger
of potentially returning an invalid handle, which can result in resource leaks and security vulnerabilities. Although it is technically possible to
utilize this method without encountering issues, doing so correctly requires a high level of expertise. Therefore, it is recommended to avoid using
this method altogether.
What is the potential impact?
SafeHandle.DangerousGetHandle method is potentially prone to leaks and vulnerabilities due to its nature and usage. Here are a few
- Invalid handles: the method retrieves the raw handle value without performing any validation or safety checks. This means that
the method can return a handle that is no longer valid or has been closed, leading to undefined behavior or errors when attempting to use it.
- Resource leaks: by directly accessing the handle without the proper safeguards and cleanup provided by the
SafeHandle class, there is an increased risk of failing to dispose system resources correctly.
- Security vulnerabilities: when the handle is interacting with sensitive resources (e.g. file handles, process handles) using
SafeHandle.DangerousGetHandle without proper validation can lead to security vulnerabilities that can be exploited by an attacker.
static void Main(string args)
System.Reflection.FieldInfo fieldInfo = ...;
SafeHandle handle = (SafeHandle)fieldInfo.GetValue(rKey);
IntPtr dangerousHandle = handle.DangerousGetHandle(); // Noncompliant
Articles & blog posts