Search code examples
c#windowswindows-servicestokenimpersonation

How to get security token of a windows service's LogOn user?


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.


Solution

  • 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.