Skip to content

Safe Handle

"SafeHandle.DangerousGetHandle" should not be called

What does this mean ?

This method may be used to get the real handle value from a SafeHandle derived class instance. Because many properties in the.NET Framework return IntPtr handle types, this function is required for backwards compatibility. Platform-specific IntPtr handle types are used to represent a pointer or a handle. The SafeHandle.DangerousGetHandle method is, unsurprisingly, hazardous. This is due to the possibility that it will not return a valid handle.

What can happen ?

Its use might result in data breaches and risks. While it is possible to apply the approach effectively, doing it correctly is incredibly difficult, hence the method should be avoided entirely. The DangerousGetHandle method can be dangerous since it still returns the original, potentially stale handle value even if the handle has been designated as invalid using SetHandleAsInvalid. At any time, the returned handle can be recycled. At the very least, this indicates that the handle may abruptly stop operating. In the worst-case scenario, exposing the handle or the resource it represents to untrusted code might result in a recycling security attack on the reused or returned handle. An untrusted caller, for example, might query data on the handle that was just returned and retrieve information about a completely different resource.

Recommendation

The method SafeHandle.DangerousGetHandle should not be used in the code.

Sample Code

Vulnerable :

static void Main(string[] args)
{
    System.Reflection.FieldInfo fieldInfo = ...;
    SafeHandle handle = (SafeHandle)fieldInfo.GetValue(rKey);
    IntPtr dangerousHandle = handle.DangerousGetHandle();  // Noncompliant
}

References