Asp.net CMD security problem - c#

I am having trouble with permissions on Windows 2008 server. i have a command line utility that I need to run to convert some standard files to CSV files. That are in turn used to import data to my SQL database. I am able to get the done to work fine on my 2003 server but my windows 2008 server is not allowing the code to run. Below is a watered down version of the code. Basically in this example I am just trying to run a simple command. But I keep getting the output access denied. How do I correct this?
public partial class _Bank : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Click(object sender, EventArgs e)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardError = true;
Process process = Process.Start(processStartInfo);
if (process != null)
{
process.StandardInput.WriteLine("dir");
process.StandardInput.Close();
string outputString = process.StandardOutput.ReadToEnd();
Response.Write(outputString);
string error = process.StandardError.ReadToEnd();
Response.Write(error);
}
}
private string ProcessRunner()
{
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
Process process = Process.Start(processStartInfo);
if (process != null)
{
//process.StandardInput.WriteLine("This is a test line");
process.StandardInput.WriteLine("c:\\");
process.StandardInput.WriteLine("This is a test line");
process.StandardInput.Close(); // line added to stop process from hanging on ReadToEnd()
string outputString = process.StandardOutput.ReadToEnd();
Response.Write(outputString);
return outputString;
}
return string.Empty;
}
public static int ExecuteCommand(string Command, int Timeout)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
Process = Process.Start(ProcessInfo);
Process.WaitForExit(Timeout);
ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
}

This is running within an asp.net application with an App-Pool. The App-Pool has an identity (LocalSystem, Network Service etc) this process is executed.
Make sure that this user does have the necessary privileges on the folders you are planning to access.
IMHO: for security reasons starting another process within a web application is not best practice and should never be done on internet web applications.
EDIT:
Usualy the user is named ASPNET or IWAM_[Servername] (IWAM_... Built-in account for Internet Information Services to start out of process applications). Just give access to the folder to that user.

Related

Process.Start doesn't start the process until main application is closed

I have a WPF application. Clicking a button the application "starts" VLC using Process.Start() method. I tested this simple app on 2 computers:
public partial class MainWindow : Window
{
...
private void RunVlcButtonClick(object sender, RoutedEventArgs e)
{
string applicationFile = "vlc.exe";
MainWindow.RunProcess(applicationFile);
}
private static Process RunProcess(string applicationFile, string arguments = "")
{
Console.WriteLine($"Run process: {applicationFile} {arguments}");
Process process = MainWindow.GetProcess(applicationFile, arguments);
bool result = process.Start();
if (!result)
Console.WriteLine($"Can't start {applicationFile} {arguments}");
return process;
}
private static Process GetProcess(string applicationFile, string arguments)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo(applicationFile, arguments);Process.StandardOutput StreamReader.
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.UseShellExecute = false;
processStartInfo.CreateNoWindow = true;
Process cmdProcess = new Process();
cmdProcess.StartInfo = processStartInfo;
cmdProcess.EnableRaisingEvents = true;
return cmdProcess;
}
}
As you can see this is nothing new or complicated. In the first computer works properly, but in the other one VLC instances are started when main application is closed.
The first computer is a Windows 10 Pro (build 16299) desktop.
The second computer is a Windows 10 Enterprise (build 10240) laptop.
Do you know why is this happening?

pg_dump.exe could not run in IIS8.0

I use System.Diagnostics.Process in C# to call the PostgreSQL backup database component pg_dump.exe. Here is my code:
string argbackup = #"--host localhost --port 5432 --username ""postgres"" --no-password --format custom --blobs --verbose --file dtname dtname";
Process backupProcess = new Process();
backupProcess.StartInfo.FileName = #"C:/Program Files/PostgreSQL/9.5/bin/pg_dump.exe";
backupProcess.StartInfo.Arguments = argbackup;
backupProcess.EnableRaisingEvents = true;
backupProcess.Exited += (object sender, EventArgs args) =>
{
//Execution after the process ends.
};
backupProcess.Start();
The code can run successfully in C#. But pg_dum.exe cannot be called when I publish the project in Visual Studio and deploy it on IIS. And the code that was run after the process ended successfully ran.
I modified the above code:
var pinfo = new ProcessStartInfo();
pinfo.Arguments = #"--host localhost --port 5432 --username ""postgres"" --no-password --format custom --blobs --verbose --file dtname dtname";
info.FileName = #"C:/Program Files/PostgreSQL/9.5/bin/pg_dump.exe";
pinfo.UseShellExecute = false;
using (var process = new Process())
{
process.EnableRaisingEvents = true;
process.StartInfo = pinfo;
process.Start();
while (!process.HasExited)
Thread.Sleep(10000);
process.WaitForExit();
if (process.ExitCode != 0)
throw new Exception("error");
process.Close();
}
It can also be used in C#, but it still won't work in IIS.
I modified the code again:
string argpostgre = #"c: && cd C:/Program Files/PostgreSQL/9.5/bin";
string argbackup = #"pg_dump.exe --host localhost --port 5432 --username ""postgres"" --no-password --format custom --blobs --verbose --file dtname dtname";
Process theProcess = new Process();
theProcess.StartInfo.FileName = #"cmd.exe";
theProcess.StartInfo.UseShellExecute = false;
theProcess.StartInfo.RedirectStandardInput = true;
theProcess.StartInfo.RedirectStandardOutput = true;
theProcess.StartInfo.RedirectStandardError = true;
theProcess.StartInfo.CreateNoWindow = false;
theProcess.EnableRaisingEvents = true;
theProcess.Exited += (object sender, EventArgs args) =>
{
//Execution after the process ends.
};
string strOutput = null;
try
{
theProcess.Start();
theProcess.StandardInput.WriteLine(argpostgre + " && " + argbackup + " & exit");
theProcess.WaitForExit();
}
catch (Exception ex)
{
strOutput = ex.Message;
}
It has been runnning in C# and will not exit. But the database can be backed up successfully after I forcefully close the C# program. And it will automatically stop process but the situation is the same as above when I deploy to IIS.
I am sure it is not the setup issue in IIS, because I have also used the Process component to access the WinRAR.exe (C:\Program Files\WinRAR\WinRAR.exe) compression program, which can run successfully.
I wonder if PostgreSQL has permissions so I can not access pg_dump.exe and other components such as pg_restore.exe.

c# start console application in win forms

I'm trying to make launcher for my games and I like to add music player in background, but if I start the process it instantly fail's.
Code
private void btnStartMusic_Click(object sender, EventArgs e)
{
ProcessStartInfo proc = new
ProcessStartInfo("MusicPlayer\\MemequickieMusicPlayer.exe");
proc.CreateNoWindow = true;
proc.WindowStyle = ProcessWindowStyle.Hidden;
proc.RedirectStandardError = false;
proc.RedirectStandardInput = false;
proc.RedirectStandardOutput = false;
proc.UseShellExecute = false;
Process.Start(proc);
}
Any Help is appreciated.
Try using the full path to the exe and setting the working directory; assuming the exe is in your executable folder:
string path = Path.Combine(Application.StartupPath, "MusicPlayer");
ProcessStartInfo proc = new
ProcessStartInfo(Path.Combine(path, "MemequickieMusicPlayer.exe"));
proc.WorkingDirectory = path;
If the error persists and you want to debug the output, change:
proc.RedirectStandardOutput = true;
Create the process like this:
Process process = new Process(proc);
process.Start();
while (!process.StandardOutput.EndOfStream) {
System.Diagnostics.Debug.Write(process.StandardOutput.ReadLine());
}
You should now see the output in your output window.

How do i execute a process in C# that installs a printer driver?

I have to start an executable (installPrint.exe) within my C# code. For this purposes I used the System.Diagnostics.Process class. The exe file installs a printer driver and copy several files into different directories. I can execute the exe from command line and everything work fine. But if i execute the file with the Process class from my C# application, the printer driver will not be installed.
I start my C# application as a admin user on a Windows XP SP2 x86 machine. Why do my executable dont work in the context of my C# application? What possibilities do i have to get it work?
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Arguments = "-i \"My Printer\" -dir . -port myPort -spooler";
startInfo.CreateNoWindow = true;
startInfo.FileName = #"C:\Printer\install.exe";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
//startInfo.Verb = "runas";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.WorkingDirectory = #"C:\Printer\";
session.Log("Working Directory: " + startInfo.WorkingDirectory);
session.Log("Executing " + startInfo.FileName);
try
{
Process process = new Process();
//process.EnableRaisingEvents = false;
process.StartInfo = startInfo;
process.Start();
session.Log("installer.exe started");
StreamReader outReader = process.StandardOutput;
StreamReader errReader = process.StandardError;
process.WaitForExit();
//session.Log(outReader.ReadToEnd());
//session.Log(errReader.ReadToEnd());
session.Log("RETURN CODE: " + process.ExitCode);
}
catch (Exception ex)
{
session.Log("An error occurred during printer installation.");
session.Log(ex.ToString());
}
I take it, you are running your program on Windows Vista or 7. Then, you have to request elevation for your newly created process to run with full access rights. Look at those questions for details:
Request Windows Vista UAC elevation if path is protected?
Windows 7 and Vista UAC - Programmatically requesting elevation in C#
Ok, I see now, that you're using Win XP. Then it may be because of some settings of Process when you start it. Try to start you process as ShellExecute, this way it will be most close to normal starting by the user.
Here's a sample:
var p = new System.Diagnostics.Process();
p.StartInfo = new System.Diagnostics.ProcessStartInfo { FileName = "yourfile.exe", UseShellExecute = true };
p.Start();
I use this class in many parts of my projects:
public class ExecutableLauncher
{
private string _pathExe;
public ExecutableLauncher(string pathExe)
{
_pathExe = pathExe;
}
public bool StartProcessAndWaitEnd(string argoment, bool useShellExecute)
{
try
{
Process currentProcess = new Process();
currentProcess.EnableRaisingEvents = false;
currentProcess.StartInfo.UseShellExecute = useShellExecute;
currentProcess.StartInfo.FileName = _pathExe;
// Es.: currentProcess.StartInfo.Arguments="http://www.microsoft.com";
currentProcess.StartInfo.Arguments = argoment;
currentProcess.Start();
currentProcess.WaitForExit();
currentProcess.Close();
return true;
}
catch (Exception currentException)
{
throw currentException;
}
}
}
I hope to have answered at your question.
M.

Web Application Asp.Net: Execute a Dos Command

I have a web application where I want to send commands to a command line (commands are not known). This is the method I use
public static string ExecuteCommand(string command)
{
String result;
try
{
//Create a new ProcessStartInfo
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
//Settings
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
//Create new Process
System.Diagnostics.Process proc = new System.Diagnostics.Process();
//Set ProcessStartInfo
proc.StartInfo = procStartInfo;
//Start Process
proc.Start();
//Wait to exit
proc.WaitForExit();
//Get Result
result = proc.StandardOutput.ReadToEnd();
//Return
return result;
}
catch
{
}
return null;
}
The command works on a console application but not on a web application (null is returned)
public string test = "NOTHING";
protected void Page_Load(object sender, EventArgs e)
{
test = AppCommandHandler.ExecuteCommand("mkdir test2");
}
What am I doing wrong? Every tutorial I look at tells me to use ProcessStartInfo
Edit I keep getting this error:
{"StandardOut has not been redirected or the process hasn't started
yet."}
Does the web app's pool have enough permissions to execute this command?
You cannot do that like this but you've to do this with using java directly, just see the link:
Run a cmd command with asp dotnet app

Categories

Resources