c# - 将 SecureString 与 LogonUser 一起使用

标签 c# .net security securestring

出于学习目的,我正在编写自己的 Active Directory 客户端。为了执行解锁帐户和重置密码等命令,我必须输入我的管理员帐户和密码并使用 WindowsIdentity.Impersonate 作为我的管理员帐户运行代码。我想知道我保护密码的选项,因为它必须在我的程序中多次使用。

据我了解,我可以使用 SecureString 来存储密码。但是要以我的管理员帐户运行代码,我使用了 WindowsIdentity.Impersonate,要使用它,我必须从 LogonUser 获取 token ,这需要一个常规的 string 而不是 SecureString

所以我必须:

  1. 启动时登录

  2. 将输入转换为 SecureString

  3. 清除输入

然后当我想执行一个需要提升的函数时:

  1. 将先前创建的 SecureString 转换为 string

  2. 将转换后的字符串传递给LogonUser

  3. 清除转换字符串为null

  4. 执行命令

  5. 清除 LogonUser 对象

这是解决这个问题的正确方法吗?必须将 SecureString 转换为 string 才能使用它似乎很奇怪......似乎它会破坏目的并在我转换时使密码更容易受到攻击它。

编辑:修复了 LogonUser 的名称

最佳答案

在您的 UserImpersonation 类中,将您声明 LogonUser 的方式更改为使用 IntPtr 而不是 string 作为密码。

Marshal.SecureStringToGlobalAllocUnicode 的代码示例正是您所需要的。这是相关的片段:

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String username, String domain,
                                      IntPtr password, int logonType,
                                      int logonProvider, ref IntPtr token);

...

IntPtr tokenHandle = IntPtr.Zero;

IntPtr passwordPtr = IntPtr.Zero;

try
{
    // Marshal the SecureString to unmanaged memory.
    passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(password);

    returnValue = LogonUser(userName, domainName, passwordPtr,
                            LOGON32_LOGON_INTERACTIVE,
                            LOGON32_PROVIDER_DEFAULT, ref tokenHandle);

 }
 finally
 {
     // Zero-out and free the unmanaged string reference.
     Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);

     // Close the token handle.
     CloseHandle(tokenHandle);
 }

关于c# - 将 SecureString 与 LogonUser 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27850342/

相关文章:

.net - ASP.NET CheckBox 状态和 PostBack

c# - 用 Reflection 找到私有(private)字段?

ruby - 在 ruby​​ 中使用散列密码

c# - 反序列化没有命名空间但在需要命名空间的类中的 XML

c# - 可描述为字符串的 HttpRequest

.net - VS 2010 错误生成单元测试

php - 如何防止 PHP 中的 SQL 注入(inject)?

ruby-on-rails - 即使在同一台计算机上,使用不带 SSL/TLS 的 SMTP 发送电子邮件是否不安全?

c# - 在 StaticResource Canvas 中为 Path 设置不同的大小或自动调整大小

c# - 文本框中仅允许整数