Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a program requiring admin rights as an admin user from a nonadmin account

Design Flow: Non-Admin User ----> Program A (Non-Admin) --> Program B (Requires Admin)

I'm writing a program to launch a program that requires admin rights from a non-admin account. The program is launched on start-up with any user and it launches the second program (requiring admin rights) as a different user who has admin rights. The issue I am having is the program is saying that to launch a program as a different user it requires admin rights. I know this not to be true so I know I have something incorrect in my code to launch the second process.

The code is as follows:

try
{
    ProcessStartInfo myProcess = new ProcessStartInfo(path);
    myProcess.UserName = username;
    myProcess.Password = MakeSecureString(password);
    myProcess.WorkingDirectory = @"C:\Windows\System32";
    myProcess.UseShellExecute = false;
    myProcess.Verb = "runas"; //Does not work with or without this command
    Process.Start(myProcess);
}

The exception is as follows:

System.ComponentModel.Win32Exception (0x80004005): The requested operation requires elevation
   at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at Loader.Program.RunProgram(String path, String username, String password)
like image 446
CoderWalker Avatar asked Oct 21 '25 15:10

CoderWalker


1 Answers

I guess you're referring to is to trigger an UAC prompt on the newly created process. If so, just a few lines will do the trick, specifically removing the user/pass properties (since they'll be asked by Windows) and setting UseShellExecute to true:

ProcessStartInfo myProcess = new ProcessStartInfo(path);
myProcess.WorkingDirectory = @"C:\Windows\System32";
myProcess.UseShellExecute = true;
myProcess.Verb = "runas";
Process.Start(myProcess);

Two caveats I've noticed with this approach is that, if the user cancels the prompt, an exception will be thrown saying that the user has cancelled (which you must be ready to cancel your processing). Also, if UAC is disabled/not present on the system, the process will NOT be elevated. To counter that, the launched program must be ready to check if it was really given admin permissions.

A complete different approach would be to just add a manifest to the target application (if yuo're able to recompile it) specifying that it requires admin permission.

like image 124
Alejandro Avatar answered Oct 23 '25 06:10

Alejandro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!