Execute Powershell script from C# with administrator privilege and permissions - c#

I'm traying to execute a Powershell script through C# with administrator privilege.
I've tryied in many ways but with no results.
The best I can do is start a process (System.Diagnostics.Process.Start(p)) with runas Verb. This way, if the user that execute the service is an administrator, I can run my powershell script.
But, what i need is to execute the service with a low privilege user, and, when needed, "login" with the administrator and execute the powershell script.
I've tryied to Impersonate the administrator, but it didn't worked...
The answer Execute PowerShell as an administrator from C# didn't solve the problem, I still can't run my script. The answers are from 2009, i hope someone had solved this kind of issue in the meantime.
// powershell script execution
var processInfo = new System.Diagnostics.ProcessStartInfo
{
Verb = "runas",
LoadUserProfile = true,
FileName = "powershell.exe",
Arguments = scriptPath,
RedirectStandardOutput = true,
UseShellExecute = false
};
var p = System.Diagnostics.Process.Start(processInfo);

Impersonation should work. However, I usually avoid it as I don't like storing user credentials if I don't have to.
I ran into a need for something similar to this in an application I'm working on.
The app runs in IIS and most of the time doesn't need (and shouldn't have) full administrator access.
To deal with this scenario, I have a separate application running (a windows service) that has full admin privileges.
It accepts request from the IIS application and executes the appropriate administrative function.
My IIS app and Windows Service talk over AMQP (with RabbitMQ). However, you could easily use whatever communication channel you prefer - HTTP, TCP, or even just create a file and have the admin application look for the file.

Related

How can a C# program run another program with admin privileges?

I have a problem with this situation:
I made 2 programs:
The first one just print an output saying that was launched with admin provileges or not, and the second one, execute the first program with admin privileges and without use the UAC. The trouble is that the second program can't launch the first with admin privileges i don't know why.
This is my code:
Code of the first program:
// This only prints if you start as administrator or not.
bool isElevated;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
Console.WriteLine("I got admin privileges?: "+isElevated);
Code of the second program:
// This execute the first program with admin privileges without UAC
string username = "myuser";
SecureString userpass = new SecureString();
userpass.AppendChar('m');
userpass.AppendChar('y');
userpass.AppendChar('p');
userpass.AppendChar('a');
userpass.AppendChar('s');
userpass.AppendChar('s');
Process program = new Process();
program.StartInfo.UserName = username;
program.StartInfo.Password = userpass;
program.StartInfo.FileName = "Path/First_program.exe";
program.StartInfo.UseShellExecute = false;
program.Start();
PD: I don't want the user to open the UAC, thats why i already insert the username and the password.
Thanks in advance.
You have half of the answer. The other half is that the program must request to be executed with elevated privileges. By default, Windows programs run in a "Basic" trust level, regardless of the true level of permissions possible under the user. To gain access to administrative powers, the program must request elevation, which by definition will involve UAC.
Programs like yours can request elevation using the runas verb in the ProcessStartInfo, or by specifying requireAdministrator elevated permissions in the manifest of either application (assuming you control them). Either way, if UAC is enabled, the user will get a prompt.
The only way to circumvent this is to set up the program that would otherwise require elevated permissions as a Windows service, configured in services.msc to run with administrative permissions. You'll get one UAC prompt when installing/registering the service to run in this way, and from then on the service can perform that task without any further UAC action. You can then use various communication technologies, from named pipes to true network comms like TCP, to signal the service that it should do what you want.

C# Process.Start with another user not working in Windows 8/10

I have program where i start USMT (load or scanstate) with a domain user that gives administrative privileges on the local computer. This is working perfectly fine in Windows 7.
The program needs to start as a non administrator user, but executing load/scanstate with administrator privileges.
However it fails when running load/scanstate properly becouse its not elevated currectly. But how can i overcome this, without having administrative rights?
Best Regards
Thomas Nissen
ProcessStartInfo restoreProcessInfo = new ProcessStartInfo
{
Verb = "runas",
UseShellExecute = false,
Domain = strAdminDomain,
UserName = strAdminUsername,
Password = strAdminPassword,
FileName = loadstate.exe",
Arguments = "blablabla"
}
As far as I am aware, the "runas" Verb (any Verb, really) is only respected when UseShellExecute is set to true. Try setting UseShellExecute to true while hiding the shell window using the WindowStyle property instead.
This will, however, prevent you from capturing input and output streams from the process. Is that something you are interested in doing?
you can impersonate the user. Impersonation is the ability of a thread to execute using different security information than the process that owns the thread.
Check this thread for how to implement impersonation. So the process will be initially executed with windows domain user's privilege and logic that's is placed within the impersonation block will be executed with with impersonated user's privilege.
//Code outside the impersonation block will be executed with current user privilege
Using(Impersonator impersonator = new Impersonator())
{
//Code written within this block will be executed with elevated(impersonated) user privilege.
}

Permission issue running .exe from ASP.NET web application

We have a .exe which we need to execute at the time an order is placed on a website. When
we test this locally it works fine using IIS Express. When we move it to IIS, it fails. We assume this is a permissions error as if we set the App Pool to run as the administrator then the script works again. The question we have is how do we execute the .exe as the administrator whilst the App Pool is ApplicationIdentity? We are using the following code:
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = executablePath,
Arguments = argumentList,
Domain = domain,
UserName = userName,
Password = securePassword,
UseShellExecute = false,
LoadUserProfile = true
}
};
process.Start();
process.WaitForExit();
process.Close();
The .exe is trying to write to the Users AppData folder which is why it fails. It is a 3rd party app so we cannot change the source code.
EDIT: Just to clarify also, when we specify the username and password in procmon it still appears to run from ISUR.
We fixed this by enabling User profile on IIS AppPool and setting permission for the IIS user on the folder it was trying to write to.
We sue ProcMon to find where the program was failing and the folder it was trying towrite to was C:\Windows\System32\config\systemprofile
i dont remember actually, but one of them is working 100% ( i had this issue before)
just let me know ehich one of them is the correct one.

How to start a Console App as running under the System Windows user account?

I tried
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = filename,
UserName = "System",
UseShellExecute = false,
},
};
process.Start();
but it yields
Win32Exception was unhandled
Login failed: unknown user name or wrong password
I will have to use CreateProcessAsUser?
How can I get the appropriate parameters to pass to that method?
The System accounts password is maintained interally by Windows (I think) i.e. attempting to start a process as the System account by supplying credentials in this way is ultimately destined to failure.
I did however find a forum post that describes a neat trick that can be used to run processes under the system account by (ab)using windows services:
Tip: Run process in system account (sc.exe)
Alternatively the Windows Sysinternals tool PsExec appears to allow you to run a process under the System account by using the -s switch.
The Username should be LocalSystem if you want to run your process with high privileges (it's a member of Administrators group) or LocalService for normal privileges
EDIT: My mistake LocalSystem & LocalService are not regulary users and, therefore, they cannot be provided as a username. Kragen's solution is the right one

Process.Start() not spawning new process under the same user

I was always under the impression that when you're running a process as (domain\user) mydomain\myuser, when using Process.Start() it would start this new process using the same credentials - mydomain\myuser.
The issue I'm having is that my Process.Start() call seems to be creating a process under the SYSTEM account which is causing me permission issues in the started process (which must run under an admin account due to the work it does). If it changes things - I'm spawning this process (a custom built exe) from within a windows installer.
Any suggestions? I've read about windows group policies (possibly) having an impact on this, but if I'm honest, it's lost on me.
EDIT: a little snippet:
Where exename and commandLine are parameters for this method body:
ProcessStartInfo procInfo = new ProcessStartInfo(exeName, commandLine);
procInfo.WorkingDirectory = workingDirectory;
procInfo.UseShellExecute = false;
procInfo.CreateNoWindow = true;
Process process = Process.Start(procInfo);
Process.WaitForExit();
return process.ExitCode;
Either set procInfo.UseShellExecute to true, or execute cmd as a process with your exe as a parameter to the cmd command. When UseShellExecute is set to false, here are a lot of interesting side effects: UseShellExecute
Your impression is true. Process.Start() will always start the new process under current user's credentials - unless you provide alternative credentials in the ProcessStartInfo or use one of the overloads that take credentials.
There must be another problem - share a snippet of your code.
UPDATE
OK! You did not mention anything about installer. All MSI installers will be running under system since they will be run by "Windows Installer" which you can check and they run under SYSTEM.

Categories