Win32用户模拟好奇心

我在codeproject上find了一些允许用户模拟的示例代码。

此代码通过导入以下非托pipe的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方法获得的令牌。

很显然,写这篇文章的人比我更了解这件事,似乎我错过了一些东西。 请问我能解释一下为什么这个过程的表面冗余令牌重复步骤是必需的?

据我所知,传递给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