【问题标题】:Win32 User Impersonation CuriosityWin32 用户模拟好奇心
【发布时间】:2011-05-15 06:28:21
【问题描述】:

我发现了一些示例代码on codeproject 允许用户模拟。

此代码通过导入以下非托管 Win32 API 函数来工作:

[DllImport("advapi32.dll", SetLastError = true)]
private static extern int LogonUser(
    string lpszUserName,
    string lpszDomain,
    string lpszPassword,
    int dwLogonType,
    int dwLogonProvider,
    ref IntPtr phToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int DuplicateToken(IntPtr hToken,int impersonationLevel,ref IntPtr hNewToken);

[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool RevertToSelf();

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool CloseHandle(IntPtr handle);

这些函数用于模拟目标用户,然后执行一些操作,然后还原模拟上下文。模拟用户是这样实现的:

if ( LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT, ref token ) != 0 )
{
    if ( DuplicateToken( token, 2, ref tokenDuplicate ) != 0 )
    {
        tempWindowsIdentity = new WindowsIdentity( tokenDuplicate );
        impersonationContext = tempWindowsIdentity.Impersonate();
    }
}

我试图了解为什么此代码首先使用LogonUser 获取所需的令牌,然后复制该令牌,然后再对复制的令牌执行模拟。为什么不直接使用从LogonUser 方法获得的令牌进行模拟。

显然写这篇文章的人比我更了解这一点,所以看起来我错过了一些东西。我能否解释一下为什么需要此过程中看似多余的令牌复制步骤?

【问题讨论】:

  • 这是 codeproject,不是 codeplex,对吧?
  • 正确,是的,现在已经更新了,谢谢。

标签: c# windows winapi authentication


【解决方案1】:

据我所知,传递给 WindowsIdentity ctor 的令牌应该是一个模拟令牌。因此,该代码的作者使用

DuplicateToken( token, 2, ref tokenDuplicate )

主令牌 创建一个模拟令牌,由 LogonUser() 返回。 '2' 幻数代表 SECURITY_IMPERSONATION_LEVEL 枚举的 SecurityImpersonation 成员。

链接:

http://msdn.microsoft.com/en-us/library/aa378184%28v=vs.85%29.aspx

http://msdn.microsoft.com/en-us/library/aa379572%28v=vs.85%29.aspx

http://msdn.microsoft.com/en-us/library/aa446616%28v=vs.85%29.aspx

【讨论】:

  • 您好 Torvin,感谢您的回复。这确实是有道理的,在我阅读“LogonUser”方法文档中的这些信息之前,我也一直在思考这些问题。 “然后,您可以使用此令牌句柄来模拟指定的用户,或者在大多数情况下,创建一个在指定用户的上下文中运行的进程。”此处为msdn.microsoft.com/en-us/library/aa378184%28VS.85%29.aspx 的参考。因此,如果这已经允许模拟,为什么还需要复制部分?
  • 嗯,好问题 :) 代码还是有问题的:它从不处理创建的 WindowsIdentity,也不在获得的令牌上调用 CloseHandle(),从而泄漏内核句柄。
  • 谢谢 Torvin,不过我确实意识到了这一点。我提供的代码只是文章中的相关sn-p:D。欣赏您的想法并为您投票。
  • 我也发现了这块code。它基本上是一样的,但没有DuplicateHandle,所以我猜它是不需要的。
  • 感谢托文,我想我可以放心地将那部分标记为多余的。 -- 干杯
猜你喜欢
  • 2014-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 2013-07-25
  • 1970-01-01
相关资源
最近更新 更多