C# - Starting process under different user than the IIS application pool user - c#

public static string StartProcess(string cmd, string args, string workingDirectory, string username, string password)
{
// launch system process
ProcessStartInfo startInfo = new ProcessStartInfo(cmd, args);
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.UserName = username;
startInfo.Password = ConvertStringToSecureString(password);
// get working directory from executable path
if (String.IsNullOrEmpty(workingDirectory))
{
startInfo.WorkingDirectory = Path.GetDirectoryName(cmd);
}
else
{
startInfo.WorkingDirectory = workingDirectory;
}
var results = new StringBuilder();
using (var process = Process.Start(startInfo))
{
process.StandardInput.Flush();
process.StandardInput.Close();
var reader = process.StandardOutput;
string lineOut;
while ((lineOut = reader.ReadLine()) != null)
{
results.AppendLine(lineOut);
}
while (!process.HasExited) System.Threading.Thread.Sleep(1000);
}
return results.ToString();
}
I am trying to launch a process from within my IIS application using a different username / password than the one that the IIS application pool is operating under.
The IIS app pool is running under a full admin user, and when the process starts, it completes, the result is return, no issues. When I specify a username / password, the process starts, then immediately closes.
I also have
Application popup: conhost.exe - Application Error : The application was unable to start correctly (0xc0000142). Click OK to close the application.
in my event logs. If I take the above code and put into its own exe file and run it via the desktop using the same admin user IIS is running under, the process starts (using the username / password for the other user) and completes without issues.
It appears to just be limited to IIS. Am I missing something?

For me chaging the user/process id of the application pool of my site worked.
Go to IIS Manager -> app pools -> select your pool -> advanced settings
-> under process model you can set your identity for example to your local admin account.

Related

C# System.Diagnostics.Process launches on my local IIS, but doesn't launch on the server

I'm trying to make my program to run a bat file, that launches an exe file. It works fine on my local computer, but doesn't work on the server IIS. It doesn't work regardless of whether I specify the username and password in the ProcessStartInfo or not. I've searched forums and applied different stuff, but none of them help.
In Windows event viewer it doesn't give me any errors as well as the process output. If I change a directory and it can't find the bat file, the output gives me an error, but when it finds the file, it doesn't return anything and just doesn't launch the program.
Now, if I provide a credentials for the process, specifying psi.Domain, psi.UserName and psi. Password, the StandartOutput doesn't return any error, but Windows Events gives me two following errors:
Application popup: cmd.exe - Application Error : The application was unable to start correctly (0xc0000142). Click OK to close the application.
And
Application popup: conhost.exe - Application Error : The application was unable to start correctly (0xc0000142). Click OK to close the application.
Here's the code:
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(#"C:\inetpub\CopyToAD\pspasswd\passchange.bat");
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
psi.CreateNoWindow = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process listFiles;
listFiles = new System.Diagnostics.Process();
listFiles.EnableRaisingEvents = false;
listFiles.StartInfo = psi;
listFiles.Start();
System.IO.StreamReader myOutput = listFiles.StandardOutput;
listFiles.WaitForExit(2000);
myOutput.ReadToEnd();
string output = myOutput.ReadToEnd();
ViewBag.View6 += output + "***";
if (listFiles.HasExited)
{
output = myOutput.ReadToEnd();
ViewBag.View6 += output;
}

Process Start Did Not Work

I have a windows service which is writing in C#.
When I start debug the program it is working without any problem. But if I publish it does not work and I am not getting any error in my log file or eventviwer.
I checked the UAC to never notify.
Also my code is like this:
using (Process tvProcess = new Process())
{
tvProcess.StartInfo.WorkingDirectory = installationPath;
tvProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
tvProcess.StartInfo.UseShellExecute = true;
tvProcess.StartInfo.FileName = TVAppFileName;
bool started = tvProcess.Start();
tvProcess.WaitForInputIdle();
Logger.TraceFormat("TV - TV was started from the path {0}. Status : {1}",
System.IO.Path.Combine(installationPath, TVAppFileName),
started);
}
Also my installationPath = #"C:\Program Files (x86)\TeamViewer\Version8\"
TVAppFileName = "TeamViewer.exe"
How can I start this process without debug?
Thanks

cscript crashes when starting a process from ASP.NET Application

I´m having a problem with my ASP application. I´m getting an error from the cscript when I run a process on the server.
When I debug locally the page just works fine and the process is executed correctly, but when I deploy the application to the IIS and run it from another machine explorer it crashes when the process starts.
I imagine it was a matter of the user, so I added this line to the web.config, to ensure that.
<identity impersonate="true" userName="domain\user" password="password" />
Then, I added the user that I wanted the process to start with but the page keeps crashing. The error that I get in the server side each time the process is launch (when a button is pressed) is:
cscript.exe - Application Error
The application failed to initialize properly (0xc0000142). Click on OK to terminate the application
The code that launches the process is:
public static void actualizarPersona(csPersona persona)
{
string nombreArchivo = "card.js";
File.WriteAllText(nombreArchivo, persona.setFileActualizarPersona(persona), Encoding.GetEncoding(1252));
Process proc = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.FileName = "cscript.exe";
startInfo.Arguments = nombreArchivo;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UserName = "Administrator";
SecureString password = new SecureString();
string contraseña = "myPassword";
foreach (char c in contraseña)
{
password.AppendChar(c);
}
startInfo.Password = password;
proc.StartInfo = startInfo;
proc.Start();
proc.WaitForExit();
proc.Close();
proc.Dispose();
}
Does anyone have any idea of what may be happening?. I´ve been stuck here for a while today.
Thanks you.
You may need to load the user's profile
startInfo.LoadUserProfile = true
Edit
Try creating a new app pool with a a new admin account. If that works remove the user from the admin group and create a new group with the necessary permissions for the app.
(see trying to run a process from an asp.net application)

How to shutdown machine from ASP.NET

I have a machine running Windows Home Server v1 (WHS is based on Windows Server 2003 and is runningh IIS6) and on here I have a restful webservice running which I build in C# VS2008 (dotnet 3.5). From within the webservice I want to be able to;
1 Check that certain windows services are running;
2 Start certain windows services
3 Stop certain windows services
4 Reboot the machine
5 Shutdown the machine
For 1-3 then I am using impersonation to elevate the ASPNET user to the local administrator (it is only me running this on a local secure network) and then "ServiceController" to control the services. This works perfectly.
For for 4 & 5 I am having issues and can't get it to work.
If I use System.Diagnostics.Process to call the "shutdown.exe" command with the parameters "/s /f" then the process executes without any errors but does not do anything! No shutdown, no exception nothing and I can't work out why. I have tried setting the local admin username & password but it does not help, and the impersonate user call does not help.
My code
string shut_args = "/s /f /t 10";
Process process1 = new Process();
process1.StartInfo.FileName = "shutdown.exe";
process1.StartInfo.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.System);
SecureString password = new SecureString();
foreach (char c in "mypassword")
password.AppendChar(c);
process1.StartInfo.Password = password;
process1.StartInfo.Domain = "homeserver";
process1.StartInfo.UserName = "Administrator";
process1.StartInfo.Arguments = shut_args;
process1.StartInfo.CreateNoWindow = true;
process1.StartInfo.UseShellExecute = false;
process1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
impersonateValidUser();
process1.Start();
So instead I tried to use WMI (code taken from another post on here) but here I get an "Privilege not held" error when trying to call InvokeMethod
Mycode
ManagementBaseObject mboShutdown = null; ManagementClass mcWin32 = new ManagementClass ("Win32_OperatingSystem"); mcWin32.Get();
mcWin32.Scope.Options.Impersonation = ImpersonationLevel.Impersonate;
mcWin32.Scope.Options.Authentication = AuthenticationLevel.Connect;
mcWin32.Scope.Options.EnablePrivileges = true;
ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");
// Flag 1 means we want to shut down the system. Use "2" to reboot.
mboShutdownParams["Flags"] = "1";
mboShutdownParams["Reserved"] = "0";
foreach (ManagementObject manObj in mcWin32.GetInstances())
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
}
I have also been through all of my security settings for the ASPNET and NETWORK_SERVICE user and they have rights to shutdown the server, the WMI security settings are also set-up for these users. But I just can't figure out what is wrong.
Any ideas?
Cheers
Have you tried to run a simple batch file instead of starting up the shutdown process in ASP.NET ?
The whole process is described here: remote shutdown/restart using ASP.NET
Old question, but I wanted to do this myself, and just figured out the answer. So try this:
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "shutdown";
startInfo.Arguments = "/s /t 5";
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
process.StartInfo = startInfo;
process.Start();

Why does impersonating a process return "The directory name is invalid"?

I have a process that needs to run under administrative privileges. I need the average joe to run the process, but I don't want to give everyone access... so I've created a simple class that will run this ONE task as an administrator, using impersonation.
The code is VERY striaght-forward, but I can't understand why this is crashing. HELP??!!
I'm running this via a batch file, and I've even copied the file that needs to execute to the local hard drive, thinking this might be a permission issue for running an app over the network.
public static Process ImpersonateProcess(string exe, string args, string Username, string Password)
{
ProcessStartInfo psi = new ProcessStartInfo(exe);
psi.Arguments = args;
psi.UseShellExecute = false;
psi.UserName = Username;
psi.Password = new SecureString();
foreach (char c in Password.ToCharArray())
{
psi.Password.AppendChar(c);
}
Process proc = null;
Console.WriteLine("starting...");
proc = Process.Start(psi);
Console.WriteLine("started");
return proc;
}
In the code above, I never get to "started". It throws an error in the Process.Start(psi) and with an error message of "the directory name is invalid."
It could be because you're not setting the WorkingDirectory property. According to the
docs:
Important Note:
The WorkingDirectory property must be set if UserName and Password are provided. If the property is not set, the default working directory is %SYSTEMROOT%\system32.

Categories