Starting another process with elevation using different user credentials

Adam Robinson picture Adam Robinson · Mar 26, 2012 · Viewed 9.7k times · Source

I'm trying to start an elevated process from with a non-elevated process, but I also need to supply the username and password for a user with administrative credentials. I've tried both the "runas" method for elevation as well as using a manifest, but both yield different errors.

For example, if I do this (without using a manifest that requires elevation):

ProcessStartInfo info = new ProcessStartInfo(path);

info.UseShellExecute = false;
info.UserName = username;
info.Password = securePwd;
info.Domain = "MyDomain";
info.Verb = "runas";

var proc = Process.Start(info);

The process launches without displaying the UAC confirmation dialog and fails upon trying to execute the command that requires administrator permissions (I'm just trying to write a test file to the Program Files directory).

If I add a manifest to the target application that indicates that it requires elevation, then I get a Win32Exception stating that the operation requires elevation.

The issue seems to be setting UseShellExecute to false(as both approaches work fine when this is not the case), but I have to set it to false in order to launch the process under a different user account.

How can I launch an elevated process from a non-elevated process and supply the username and password manually?

BOUNTY EDIT: While the user cannot be required to enter administrator credentials, a UAC nag dialog is perfectly acceptable. I'm not looking to bypass UAC here.

Answer

Ian Boyd picture Ian Boyd · Apr 4, 2012

i was surprised there's no way to do this, until i found an on blog entry by Chris Jackson:

Why Can’t I Elevate My Application to Run As Administrator While Using CreateProcessWithLogonW?

You need a bootstrapper. Some process which will let you do the transition to the alternate user, which could be responsible for running the requireAdministrator application. So, you could design something like this:

enter image description here

Why don’t we just create the ShellExecuteWithLogonW API? I’ll never say never, and we might at some point. But today, the use cases for this APIs have been use cases where there has been an alternate design which is superior.

The most common request is for people writing home-grown software deployment software, where they’d like to encode credentials right into the app and elevate their own process. The real problem here is not the lack of the API, it’s that you have admin credentials encoded in your app for the world to read.

So the solution requires ShellExecute, it's the only one that knows how to trigger a Consent dialog.

It brings up a good point: What are you doing with a person's password already?

Bonus Chatter

There's no UAC on Server Core because there's no windows to show a consent prompt.