3

I need to impersonate the LogOn user account of a particular windows service.

I have been able to get the username using WMI (sadly the LogOn user identity doesn't seem to be exposed using any of the regular windows service related .NET classes). But, armed with only the username (which could be either a local or domain account) how do I get the token for that windows identity?

The LogonUser WinAPI call which can provide the token expects the password as an argument, which obviously is not available. User input is not an option.

Any insight will be appreciated.

Manas
  • 521
  • 8
  • 26
  • 1
    Do you want to impersonate the user under whose account the service is running ? If so you can use CreateRemoteThread – parapura rajkumar Mar 23 '13 at 00:43
  • Let me get this straight, you want to impersonate the user that the service is running as? Or a completely different user? – Steven V Mar 23 '13 at 00:43
  • @parapurarajkumar Thanks. Will explore. It just occurred to me that perhaps I could also use OpenProcessToken. – Manas Mar 23 '13 at 00:46
  • @StevenVondruska I want to impersonate the user account that the windows service is running under. – Manas Mar 23 '13 at 00:51

2 Answers2

3

Ended up doing the following:

  1. Check if service is running. If not start service.
  2. Get PID from service name using WMI.
  3. Get process handle from PID using .NET Process class.
  4. Get process token using OpenProcessHandle
  5. Duplicate token using DuplicateToken, to verify sufficient privilege.
  6. Create new WindowsIdentity using token obtained in step 4.
  7. Impersonate this new WindowsIdentity, do operation under impersonation, then undo impersonation, using WindowsImpersonationContext.

Hope this is useful to anyone else who needs to impersonate the user account that a service is running under.

Manas
  • 521
  • 8
  • 26
  • The code I am afraid is proprietary. I may however be able to give pointers depending on which step you need clarification on... – Manas May 12 '14 at 21:37
1

While this is completely undocumented by Microsoft because they want to pretend that service logon doesn't require a plaintext password at logon time, it in fact does and services.exe calls LogonUser with the correct password.

The password is shoved somewhere deep in the registry in a place that only SYSTEM has access to and encrypted to boot, but the SYSTEM account can obtain the machine key and decrypt the password.

(defunct source) http:// www.computersecurityarticles.info/security/decrypting-lsa-secrets/

(new source) https://gist.github.com/jborean93/58bba8236fac313e3d4b3970b8213cb6

Please note that because this is undocumented, you should not use it.

Joshua
  • 40,822
  • 8
  • 72
  • 132