Run process under current user - c#

There is "Setup project" in VS. During installation I launch another process:
System.Diagnostics.Process process = new System.Diagnostics.Process();
//fill StartInfo and run call Start()
process.Start();
If I run installer under Windows 7 and install for "Everyone", process start under the SYSTEM. If I install "Just for me", process start under Current user. How do I always start process under Current user?

I have found very simple solution. All that you need it just create a new class and copy text from this link.
To launch the process call ProcessAsUser.Launch("program name");

I had a similar problem: My setup extension (custom action) needed Admin privileges which brought up an elevation box. After I start my application at the end of "Just for Me" the process had settings that were made for the admin context. For example my user account likes to see all extensions of files in Windows Explorer but the admin account was configured to hide them. So in every file open box I couldn't see the extensions. To cure this this piece of code worked:
ProcessStartInfo startInfo = new ProcessStartInfo(ShortcutTarget);
startInfo.LoadUserProfile = true;
startInfo.UseShellExecute = false;
Process.Start(startInfo);
It works only in "Just for Me" mode, in "Everyone" the admin's settings are used. But this is ok for me.

Use ProcessStartInfo class and its property UserName, then use it as argument for Process.Start static method.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Process.Start(startInfo);

Related

Start Azure Storage Emulator for non-Admin users on Startup

At work we use Azure functions for simple tasks.
To debug or run the function you need a running Azure Storage Emulator.
The problem is that our developer accounts don't have admin privileges so we can't start the emulator ourselves.
For now we solve this by asking an admin to start it for us, but that works only until you restart/turn off the machine.
We tried many things for the emulator to start for each user( as if it was run by the admin) but nothing worked.
Here is one of the methods we tried. A simple program that runs at startup and starts the emulator. If you start it manually as admin it does the job and the emulator starts without problems.
But when scheduled to start(with the admin account) at startup or at logon it starts it but only for the admin account and not the current user.
Code for the program we run at startup:
internal class Program
{
private static void Main(string[] args)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = #"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe";
startInfo.Arguments = "start";
process.StartInfo = startInfo;
process.Start();
}
}
Do you have any idea or suggestions how to solve the above problem ?
P.S:I have searched the related topics posted on StackOverflow for issues of the same kind but they ware not much help or the use-case was different.
:)
As per this link: the first time you run your emulator, the emulator environment will need to configure itself: it will create a database in LocalDB and it will register some HTTP ports. In order for the configuration process to succeed, you need administrator privilege.
The next time you'll run the storage emulator, you will no longer need administrator privilege.
So there is a tricky way, just for your reference.
you can use administrator to start the emulator, then wait for a few seconds(it finishes the inialization), stop emulator.
Then you can use normal user account to start it, it would be run for you.
Code like below:
with admin account:
private static void Main(string[] args)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = #"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe";
startInfo.Arguments = "start";
process.StartInfo = startInfo;
process.Start();
//Wait for finished initialization
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
//After initialization, close the Emulator
Process[] processes = Process.GetProcessesByName("AzureStorageEmulator");
foreach (var p in processes)
{
p.Kill();
}
}
Then you can start Emulator again using your developer account, the code is similar to the above.
It maybe a not good choice, you can also submit an question on here.

need help: "The requested operation requires elevation" [duplicate]

I'm working on a WPF application targeting .NET 3.0. I need to call an exe which requires administrative privileges. I can get the UAC to prompt for permission by using something like:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Verb = "runas";
startInfo.UseShellExecute = true;
startInfo.FileName = "target.exe";
Process p = new Process();
p.StartInfo = startInfo;
p.Start();
My problem is I need to redirect standard output, and doing so with UseShellExecute = true results in an exception stating that:
The Process object must have the UseShellExecute property set to false
in order to redirect IO streams
However, setting it to false results in the UAC not prompting for permission and I get an exception stating:
The requested operation requires elevation
How can I redirect standard output and prompt for UAC?
I have seen this similar question, however the solution is to use the app.manifest to give my application administrative privileges. This is something I cannot do due to requirements.
UseShellExecute must be set to false to redirect IO, and to true to use the Verb property. So you can't.
But this article seems do the magic, although I haven't tested it.
It's written in C++, but a wrapper API can easily be created to be called from C# by using DllImport.
Note: If you want to pass data between the two programs and have access to the target program's source code, you can easily re-design you application to use Named Pipes instead of redirecting standard I/O.
There is another pretty simple solution:
If you want to run a child-executable elevated AND redirect the output (optionally including window hiding), then your main code must be running elevated too. This is a security requirement.
To accomplish this:
Manually edit your app.manifest in your project folder.
Find the comment regarding UAC Manifest Options, you will see the 3 examples of requestedExecutionLevel.
Under the comment, locate the tricky asInvoker which is currently enabled, and replace it with requireAdministrator.
Restart Visual Studio in order to take into effect, and after re-building your app it should have the typical UAC shield icon.
Now your code will run elevated, everything that it launches will be elevated too, and you can also capture output streams. Here is an example in VB.NET:
Dim startInfo As New ProcessStartInfo
startInfo.Verb = "runas"
startInfo.FileName = "subprocess-elevated.exe"
startInfo.Arguments = "arg1 arg2 arg3"
startInfo.WorkingDirectory = Environment.CurrentDirectory
startInfo.WindowStyle = ProcessWindowStyle.Hidden
startInfo.CreateNoWindow = True
Dim p As Process = New Process()
p.StartInfo = startInfo
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.RedirectStandardError = True
p.Start()
Console.WriteLine(p.StandardOutput.ReadToEnd)
Console.WriteLine(p.StandardError.ReadToEnd)
p.WaitForExit()

Redirect standard output and prompt for UAC with ProcessStartInfo

I'm working on a WPF application targeting .NET 3.0. I need to call an exe which requires administrative privileges. I can get the UAC to prompt for permission by using something like:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Verb = "runas";
startInfo.UseShellExecute = true;
startInfo.FileName = "target.exe";
Process p = new Process();
p.StartInfo = startInfo;
p.Start();
My problem is I need to redirect standard output, and doing so with UseShellExecute = true results in an exception stating that:
The Process object must have the UseShellExecute property set to false
in order to redirect IO streams
However, setting it to false results in the UAC not prompting for permission and I get an exception stating:
The requested operation requires elevation
How can I redirect standard output and prompt for UAC?
I have seen this similar question, however the solution is to use the app.manifest to give my application administrative privileges. This is something I cannot do due to requirements.
UseShellExecute must be set to false to redirect IO, and to true to use the Verb property. So you can't.
But this article seems do the magic, although I haven't tested it.
It's written in C++, but a wrapper API can easily be created to be called from C# by using DllImport.
Note: If you want to pass data between the two programs and have access to the target program's source code, you can easily re-design you application to use Named Pipes instead of redirecting standard I/O.
There is another pretty simple solution:
If you want to run a child-executable elevated AND redirect the output (optionally including window hiding), then your main code must be running elevated too. This is a security requirement.
To accomplish this:
Manually edit your app.manifest in your project folder.
Find the comment regarding UAC Manifest Options, you will see the 3 examples of requestedExecutionLevel.
Under the comment, locate the tricky asInvoker which is currently enabled, and replace it with requireAdministrator.
Restart Visual Studio in order to take into effect, and after re-building your app it should have the typical UAC shield icon.
Now your code will run elevated, everything that it launches will be elevated too, and you can also capture output streams. Here is an example in VB.NET:
Dim startInfo As New ProcessStartInfo
startInfo.Verb = "runas"
startInfo.FileName = "subprocess-elevated.exe"
startInfo.Arguments = "arg1 arg2 arg3"
startInfo.WorkingDirectory = Environment.CurrentDirectory
startInfo.WindowStyle = ProcessWindowStyle.Hidden
startInfo.CreateNoWindow = True
Dim p As Process = New Process()
p.StartInfo = startInfo
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.RedirectStandardError = True
p.Start()
Console.WriteLine(p.StandardOutput.ReadToEnd)
Console.WriteLine(p.StandardError.ReadToEnd)
p.WaitForExit()

Program running in administrative mode needs to run another application in non-administrative mode?

I have a program that runs in administrative mode. This program should run another application. Since my application is run in administrative mode, the new application is run in administrative too. How to run this new application in non-administrative mode?
What you want is Process.Start passing a StartInfo object specifies the credentials of the use you want to start the process as.
Process.Start Method (ProcessStartInfo)
Something like this should get you started . . .
var startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "Myexe.exe";
startInfo.UserName = "Myuser";
startInfo.Password = "MyUsersPassword";
System.Diagnostics.Process.Start(startInfo);
If you want it to run as the current user, but not in admin mode, try passing the current users credentials, I haven't tested it, but it might work.

Elevating process privilege programmatically?

I'm trying to install a service using InstallUtil.exe but invoked through Process.Start. Here's the code:
ProcessStartInfo startInfo = new ProcessStartInfo (m_strInstallUtil, strExePath);
System.Diagnostics.Process.Start (startInfo);
where m_strInstallUtil is the fully qualified path and exe to "InstallUtil.exe" and strExePath is the fully qualified path/name to my service.
Running the command line syntax from an elevated command prompt works; running from my app (using the above code) does not. I assume I'm dealing with some process elevation issue, so how would I run my process in an elevated state? Do I need to look at ShellExecute for this?
This is all on Windows Vista. I am running the process in the VS2008 debugger elevated to admin privilege.
I also tried setting startInfo.Verb = "runas"; but it didn't seem to solve the problem.
You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows:
startInfo.Verb = "runas";
This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.
This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.
Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.
This code puts the above all together and restarts the current wpf app with admin privs:
if (IsAdministrator() == false)
{
// Restart program and run as admin
var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
startInfo.Verb = "runas";
System.Diagnostics.Process.Start(startInfo);
Application.Current.Shutdown();
return;
}
private static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
// To run as admin, alter exe manifest file after building.
// Or create shortcut with "as admin" checked.
// Or ShellExecute(C# Process.Start) can elevate - use verb "runas".
// Or an elevate vbs script can launch programs as admin.
// (does not work: "runas /user:admin" from cmd-line prompts for admin pass)
Update: The app manifest way is preferred:
Right click project in visual studio, add, new application manifest file, change the file so you have requireAdministrator set as shown in the above.
A problem with the original way: If you put the restart code in app.xaml.cs OnStartup, it still may start the main window briefly even though Shutdown was called. My main window blew up if app.xaml.cs init was not run and in certain race conditions it would do this.
According to the article Chris Corio: Teach Your Apps To Play Nicely With Windows Vista User Account Control, MSDN Magazine, Jan. 2007, only ShellExecute checks the embedded manifest and prompts the user for elevation if needed, while CreateProcess and other APIs don't. Hope it helps.
See also: same article as .chm.
[PrincipalPermission(SecurityAction.Demand, Role = #"BUILTIN\Administrators")]
This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.
i know this is a very old post, but i just wanted to share my solution:
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo
{
UseShellExecute = true, //<- for elevation
Verb = "runas", //<- for elevation
WorkingDirectory = Environment.CurrentDirectory,
FileName = "EDHM_UI_Patcher.exe",
Arguments = #"\D -FF"
};
System.Diagnostics.Process p = System.Diagnostics.Process.Start(StartInfo);
NOTE: If VisualStudio is already running Elevated then the UAC dialog won't show up, to test it run the exe from the bin folder.
You should use Impersonation to elevate the state.
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
Don't forget to undo the impersonated context when you are done.

Categories

Resources