1

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;
            }
          }
        }
      }
      if (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.

  1. An explanation of the code in general.

  2. Why is it necessary for both machines to have user accounts with identical username + passoword combination?

  3. Why is it the privileges of the two user accounts (Admin or Non-Admin) is irrelevant?

Thank you in advance.

Sach
  • 10,091
  • 8
  • 47
  • 84
  • This code would not compile. Your line `impersonationContext = tempWindowsIdentity.Impersonate();` needs to be `WindowsImpersonationContext impersonationContext = tempWindowsIdentity.Impersonate();`. Inside `if (impersonationContext != null) { ... }` is where you would do your work as the other account. – vapcguy Feb 23 '17 at 22:17
  • Better, instead of this, would be to have this function return the WIC so you can do your work elsewhere, and call another function to close your token handles after you're done. See what I did here: http://stackoverflow.com/questions/1335065/check-status-of-services-that-run-in-a-remote-computer-using-c-sharp/42424560#42424560 – vapcguy Feb 23 '17 at 22:21

1 Answers1

2

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)

Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
  • Simon, thanks a lot for the response. So let me see if I got this right. – Sach Dec 10 '10 at 02:52
  • Re 1. Let us say we have machine A on which ServiceA runs. I have machine B from which I want to Start/Stop ServiceA. The application I am developing now runs on machine B. So, when I use LogonUser method, it logs in to the given user account in Machine B, am I right? Then, Impersonate() method does what? – Sach Dec 10 '10 at 02:58
  • Re 2. I tried to access the ServiceA from a user account in MachineB which has different credentials, but it fails. Can you please provide me with a code sample where I can Start/Stop services in remote machine WITHOUT having to have the same UserName+Password combo in both machines? – Sach Dec 10 '10 at 03:00
  • There is a discussion on SO that explain how to install/start/stop a service using the unmanaged Windows API: http://stackoverflow.com/questions/358700/how-to-install-a-windows-service-programmatically-in-c – Simon Mourier Dec 13 '10 at 07:23
  • I realize this is an old post, but for the benefit of all that may Google and find this: It doesn't matter what account the service is running under if you have an account with Admin privileges on machine A. When you use the `LogonUser()` method you send that method the credentials for the account you want to use, aka that Admin account on machine A. All that function gives is a `IntPtr phToken` back. You then duplicate that token and assign it the Impersonation level security flag (that number `2` you gave it means that). Then you're creating a `WindowsIdentity` with the duplicate token. – vapcguy Feb 23 '17 at 22:25
  • Then you create a `WindowsImpersonationContext` from that `WindowsIdentity` using `.Impersonate()`. The WIC is what you actually use, and from that point on, any code is performed in the context of the impersonated account until you do `impersonationContext.Undo()`, which is missing in the original code above, and then you close the token handles for that identity just as a way to tidy up before the next impersonation you might perform. – vapcguy Feb 23 '17 at 22:27