Windows process impersonation using RunAs, Windows APIs, and psexec
Impersonation is the ability of a thread or process to execute in a security context that is different from the context of the process that owns the thread or process. On Windows, there are many ways to impersonate a user. Some methods are very easy to use. Some are very insecure. In this post we will review the following methods:
Impersonation is also available on Unix/Linux system. We will explorer this in a future post.
1. Using RunAs
RunAs ships with Windows. It is incredibly easy to use. Let’s jump right in with an example.
In the example below, RunAs attempts to execute C:\myexec.exe as the user, MYCOMPUTER\dimascio. RunAs will prompt for the user’s password prior to execution
runas /user:MYCOMPUTER\dimascio C:/myexec.exe"
If the script is execute and run unattended, this solution is clearly not good enough. No human will be present to enter the password. One obvious workaround, might be to echo the password and pipe it to runas.
echo MyPassword|runas /user:MYCOMPUTER\dimascio C:/myexec.exe"
Unfortunately (or fortunately), this does not work! It is consciously made not to work. Why? Security!
By piping a password to RunAs, one can easily observe the user’s password. One can do so, simply by inspecting the running process. The password may also appear in the command’s title area. Yikes!
2. Using Windows APIs to impersonate securely?
There are many ways to do this properly. For example, one can securely write the process impersonation logic by using Windows APIs available in C++, C#, and more. How? See the following article from Microsoft here
3. Using psexec
Well, if security is really of no interest to you and you are comfortable with a completely insecure, yet simple solution, try using psexec. It supports passwords on the command line.
NOTE: psexec can be a secure solution, however if a user’s password is specified on the psexec command line, we have ventured into the land of the terribly insecure.
Here is an example of process impersonation using psexec. We will specify the password on the command line.
c:\Data\Applications\PSTools\psexec -u MYCOMPUTER\dimascio -p MyPassword -w C:\working_directory cmd /c "c:\myexec.exe"
You can download psexec from Microsoft here.