Help Understanding Impersonation
I was looking for a way to Start / Stop Windows Services residing in a remote machine using C# code, and found the following code sample. It works fine for me. It is coded using Impersonation Technique, which apparently requires both the machines (let's say A and B) have a user account with the same UserName + Password combination.
int LOGON32_LOGON_INTERACTIVE = 2;
int LOGON32_PROVIDER_DEFAULT = 0;
private bool impersonateValidUser(String userName, String machineName, String passWord)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, machineName, passWord,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
i开发者_运维技巧f (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
return false;
}
Now I need to know the answers to the following questions, so would greatly appreciate if somebody could help me.
An explanation of the code in general.
Why is it necessary for both machines to have user accounts with identical username + passoword combination?
Why is it the privileges of the two user accounts (Admin or Non-Admin) is irrelevant?
Thank you in advance.
Here is a good general explanation of impersonation: A .NET Developer's Guide to Windows Security: Understanding Impersonation
1) what the code does is "Logon on as a user". The central APIs here are LogonUser (Native call) and Impersonate() (.NET), which are documented here: http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx and here: http://msdn.microsoft.com/en-us/library/w070t6ka.aspx
The rest is more or less needed plumbing.
2) It's not necessary, but I suppose that's what has been chosen in your infrastructure because the machine may not be in the same account domain, or there is no account domain at all. In this case the identical account names+passwords is an old trick. If the machine are in the same Windows Domain (AD), it's not needed.
3) Impersonation does not require the Admin priviledge (only on Windows 2000 and before, if I remember correctly)
精彩评论