c# - 在 .NET 4 中捕获 AccessViolation。好还是坏?

标签 c# .net exception error-handling corrupted-state-exception

文件中存在类型为 SECURITY_IDENTIFIER 结构的对象。我需要从此结构中获取所有者 SID。为此,我调用 GetSecurityDescriptorOwner WinAPI 函数并创建 System.Security.Principal.SecurityIdentifier(它具有以 IntPtr 作为参数的重载)

问题是文件中的这个结构有时会被破坏,所以我从 GetSecurityDescriptorOwner 获得的指针无效。它不是 IntPtr.Zero,它是无效的,所以当我创建类型为 SecurityIdentifier 的对象时,我得到了 AccessViolationException,这是不可能通过简单的 try- 捕捉到 .NET 4 的捕获。

我知道允许捕获此类异常的属性,所以我暂时使用它,但我不喜欢这个解决方案。不建议捕获损坏状态异常 (CSE),但我没有看到任何其他解决方案。这个 WinAPI 函数返回无效指针,我看不出有什么方法可以检查它的有效性。有什么想法吗?

更新

应用程序接口(interface)

BOOL WINAPI GetSecurityDescriptorOwner(
  _In_   PSECURITY_DESCRIPTOR pSecurityDescriptor,
  _Out_  PSID *pOwner,
  _Out_  LPBOOL lpbOwnerDefaulted
);

外部定义

[DllImport("Advapi32.dll")]
static extern bool GetSecurityDescriptorOwner(
   IntPtr pSecurityDescriptor,
   out IntPtr owner,
   out bool defaulted);

更新

private static SecurityIdentifier GetSecurityIdentifier()
{
    // Allocate managed buffer for invalid security descriptor structure (20 bytes)
    int[] b = new int[5] {1, 1, 1, 1, 1};

    // Allocate unmanaged memory for security descriptor 
    IntPtr descriptorPtr = Marshal.AllocHGlobal(b.Length);

    // Copy invalid security descriptor structure to the unmanaged buffer
    Marshal.Copy(b, 0, descriptorPtr, b.Length);

    IntPtr ownerSid;
    bool defaulted;

    if (GetSecurityDescriptorGroup(descriptorPtr, out ownerSid, out defaulted))
    {
        // GetSecurityDescriptorGroup returns true, but `ownerSid` is `1`
        // Marshal.GetLastWin32Error returns 0 here
        return new SecurityIdentifier(ownerSid);
    }

    return null;
}

此代码有时会从 SecurityIdentifier 构造函数中抛出损坏的状态异常。有什么解决办法吗?

最佳答案

您是否尝试调用 IsValidSecurityDescriptor

[DllImport("Advapi32.dll")]
static extern bool IsValidSecurityDescriptor(IntPtr pSecurityDescriptor);


if (IsValidSecurityDescriptor(descriptorPtr) && 
    GetSecurityDescriptorOwner(descriptorPtr, out ownerSid, out defaulted))
{
     return new SecurityIdentifier(ownerSid);
}

关于c# - 在 .NET 4 中捕获 AccessViolation。好还是坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12306812/

相关文章:

c# - MSChart插入、移动、删除点

.net - 如何使用 typeof 或 GetType() 作为通用模板?

c# - 如何从服务器加载 pdf 作为 aspx 页面(或安全加载 pdf 文件)?

c++ - 来自标准库调用的结构化异常 (SE)

c++ - 你如何调试 MinGW 异常处理?

c# - RSA C# 中的 key 大小没有改变!

c# - CMake C# 项目 "unsafe"属性

c# - 启动时未调用 ValueConverter

.net - F# printfn "%A"到剪贴板

java - 使用 ProGuard 后异常跟踪不显示私有(private)方法的行号