开发者

Win32 User Impersonation Curiosity

开发者 https://www.devze.com 2023-03-06 04:45 出处:网络
I have found some sample code on codeproject that allows for user impersonation. This code works by importing the following unmanaged Win32 API functions:

I have found some sample code on codeproject that allows for user impersonation.

This code works by importing the following unmanaged Win32 API functions:

[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);

These functions are used to impersonate the target user, then perform some operations, then revert the impersonation context. Impersonating the user is achieved like so:

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();
    }
}

I'm trying to understand why this code first gets the required token using LogonUser, then duplicates that token, before performing the impersonation on the duplicated token. Why not just impersonate using the token that you get from the LogonUser method.

Obviously the person that wrote this article understands this better than I do so it would appear that I am missing something. Could I please get an explanation of why the seemingly redundant token duplica开发者_开发知识库tion step of this process is required?


As far as I know, token, passed to WindowsIdentity ctor should be an impersonation token. So, the author of that code using

DuplicateToken( token, 2, ref tokenDuplicate )

to create an impersonation token from primary token, returned by LogonUser(). That '2' magic number stands for SecurityImpersonation member of SECURITY_IMPERSONATION_LEVEL enum.

Links:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消