Search code examples
windowspsexeccreateprocessasuserauth-token

How to get Windows SYSTEM user token


Operating system is Windows 7 or higher with UAC enabled. Calling process has admin rights, already confirmed by the UAC box.

I want to spawn a new Console window (cmd.exe) under user SYSTEM (don't ask why). I can do this interactively by using PsExec tool from Sysinternals or something similar, but I don't have the source code and I need to understand how this works.

I understand that I have to call CreateProcessAsUser() and that works fine with the first parameter (hToken) set to NULL, but now I need to know how to get the hToken. I understand that I can get such a token by calling LogonUser() - but not for SYSTEM. How would I get the token for SYSTEM?

I thought of using DuplicateTokenEx(), but that requires an original token, that I don't have.

Would I have to query the process list, find any SYSTEM process and try to get that token duplicated or something? I don't want to reverse engineer the PsExec tool or one of the others doing exactly this.


Solution

  • Typically you would install and launch a service, configured to log in as SYSTEM. You can then use OpenProcessToken and DuplicateTokenEx to make a copy of the token.

    You will probably need to use SetTokenInformation to change the session ID for the token to match that of the interactive user. You need Act As Part Of the Operating System privilege to do that, so you should do this from inside the service itself. Once the duplicate token is ready to use, you can use DuplicateHandle to copy the handle into the administrative process, or (with the right options) you could launch the command shell directly from the service too.