gpt4 book ai didi

c# - 为什么 SafeHandle.DangerousGetHandle() "Dangerous"?

转载 作者:太空狗 更新时间:2023-10-29 21:29:37 25 4
gpt4 key购买 nike

这是我第一次使用 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. 为什么不安全的句柄很危险?

最佳答案

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

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

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

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. See the DangerousAddRef and the DangerousRelease methods for more information about using the DangerousGetHandle methodsafely.

关于c# - 为什么 SafeHandle.DangerousGetHandle() "Dangerous"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8396923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com