为什么SafeHandle.DangerousGetHandle()“危险”?

时间:2011-12-06 08:12:48

标签: c# .net-3.5 pinvoke handles

这是我第一次使用SafeHandle

我需要调用这个需要UIntPtr的P / Invoke方法。

    [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    public static extern int RegOpenKeyEx(
      UIntPtr hKey,
      string subKey,
      int ulOptions,
      int samDesired,
      out UIntPtr hkResult);

此UIntPtr将派生自.NET的RegistryKey类。我将使用上面的方法将RegistryKey类转换为IntPtr,以便我可以使用上面的P / Invoke:

        private static IntPtr GetRegistryKeyHandle(RegistryKey rKey)
        {
            //Get the type of the RegistryKey
            Type registryKeyType = typeof(RegistryKey);

            //Get the FieldInfo of the 'hkey' member of RegistryKey
            System.Reflection.FieldInfo fieldInfo =
                registryKeyType.GetField("hkey", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            //Get the handle held by hkey
            if (fieldInfo != null)
            {
                SafeHandle handle = (SafeHandle)fieldInfo.GetValue(rKey);

                //Get the unsafe handle
                IntPtr dangerousHandle = handle.DangerousGetHandle();                
                return dangerousHandle;
            }
}

问题:

  1. 有没有更好的方法来编写它而不使用“不安全”的句柄?
  2. 为什么不安全处理危险?

2 个答案:

答案 0 :(得分:4)

RegistryKey有一个handle属性。所以你可以使用

private static IntPtr GetRegistryKeyHandle(RegistryKey rKey)
{
    return rKey.Handle.DangerousGetHandle;
}

这有潜在危险,因为您使用它时指针可能不再有效。引自MSDN

  

使用DangerousGetHandle方法可能会带来安全风险,因为如果使用SetHandleAsInvalid将句柄标记为无效,DangerousGetHandle仍会返回原始的,可能过时的句柄值。返回的手柄也可以在任何时候回收。充其量,这意味着手柄可能会突然停止工作。在最坏的情况下,如果句柄或句柄所代表的资源暴露给不受信任的代码,则可能导致对重用或返回句柄的回收安全攻击。例如,不受信任的调用者可以查询刚返回的句柄上的数据,并接收完全不相关的资源的信息。有关使用DangerousGetHandle方法的更多信息,请参阅DangerousAddRef和DangerousRelease方法。

答案 1 :(得分:3)

你所做的事实上是危险的。您使用的RegistryKey对象可以在使用IntPtr时收集垃圾并最终确定。这使得句柄值无效,使您的代码随机失败。好吧,好吧,随机故障并不是完全危险的,但如果你实际上长时间保持手柄,它确实会打开手柄回收攻击的大门。随机失败模式应该足以激励你做些什么。

让你的pinvoke声明如下:

[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
internal static extern int RegOpenKeyEx(SafeRegistryHandle key, string subkey, 
    int options, int sam, out SafeRegistryHandle result);

因此,您可以始终使用安全句柄包装类。相应地调整反射代码。

相关问题