Server-side application fails to run command - c#

I have an ASP.NET application that is already deployed in an Azure virtual machine. The situation is as follows:
This application, OCREngine, is deployed on the server along with other 3rd party applications. OCREngine is executed on the server by using a service reference to the web service. It runs fine most of the time. But there is one exception: one of the branches of execution won't run the program it needs to run. Both of the branches have to run a program (both are being run in the same way), but one works and the other one doesn't.
This one works: CleanJPEG.exe
proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "CleanJPEG.exe";
proc.StartInfo.Arguments = "\"" + tempPages + "Color Info.JPEG\"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
And this one doesn't: cpctool.exe
proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "cpctool.exe";
proc.StartInfo.Arguments = "\"" + file + "\" -o \"" + tempPages + "page.tiff\"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
They are both in the same folder, which has full permissions for the AppPool and so does %TEMP%.
If I run the application from the server, everything works fine. But when I run it through the web service, an instance of cpctool.exe gets created (can be seen on Background processes in the task manager) but it doesn't do it's job. And thus the execution of OCREngine never finishes.
This last part is what made me think it was a problem with permissions, but I don't know what else to give permissions to.
I run Folder Changes View on cpctool.exe and it showed access to the folder where the files are stored and one file being saved in %TEMP% (which, funny enough, doesn't appear when running Folder Changes View on the server).
Can anyone think of any special folder that needs permission that I might be forgetting?

You are completely correct to concentrrate on the permissions as that is usually the issue.
If an EXE process starts and does nothing, then it's probably only made for interactive use, and is prompting for something.
Looking at this page it says:
The FIRST TIME the CPCTool.exe runs the user is prompted to read/accept a User Agreement from Cartesian – this agreement MUST be accepted or the converter will not work.
I reckon that's what it's doing. Try logging in as the application pool user, start the program and accept the agreement.

Related

Process on ASP.Net server not running correctly over IIS

I am trying to run an antivirus scan on an uploaded file in an ASP.Net web app. We are using Sophos so have access to their command line API sav32cli. In the code I use:
Process proc = new Process();
proc.StartInfo.FileName = #"C:\Program Files (x86)\Sophos\Sophos Anti-Virus\sav32cli.exe";
proc.StartInfo.Arguments = #"-remove -nc " + SavedFile;
proc.StartInfo.Verb = "runas";
proc.Start();
proc.WaitForExit();
int exitCode = proc.ExitCode;
When stepping through the code, when attached to the w3wp process on dev server, the code just jumps from one line to the next seemingly doing nothing at all. When running from code on dev server, it performs as expected scanning file and deleting if it is seen as a virus.
The server is running IIS 8.0, and the app built in .Net Framework 4. I have changed the machine config to allow the process to run as SYSTEM account, in accordance to these instructions. https://support.microsoft.com/en-us/kb/317012#%2Fen-us%2Fkb%2F317012
<processModel userName="SYSTEM" password="AutoGenerate" />
Is there something I'm missing? What is the best practice for this kind of implementation?
EDIT: When called, the Process returns an ExitCode of 2 (Error stopped execution), rather than the expected 0 (Scan worked, no viruses), or 3 (Scan worked, viruses found).
EDIT 2: As per comment below I changed the code to:
Process proc = new Process();
proc.StartInfo.FileName = #"C:\Program Files (x86)\Sophos\Sophos Anti-Virus\sav32cli.exe";
proc.StartInfo.Arguments = #"-remove -nc " + SavedFile;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
StringBuilder output = new StringBuilder();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
output.AppendLine(line);
}
proc.WaitForExit();
int exitCode = proc.ExitCode;
ASPxMemo2.Text = exitCode.ToString() + Environment.NewLine + output.ToString();
output is always empty when run over IIS, but is populated correctly when running from code.
EDIT 3: Instead of looking at StandardOutput we looked at StandardError and it revealed this error:
Error initialising detection engine [0xa0040200]
(Possible insufficient user Admin rights.)
For the time being we are going to move to another method of virus checking, but would still like to know a possible solution if anyone has it.
You will need to make sure that the application pool that is running your .NET application inside IIS has execute permissions to your file
"C:\Program Files (x86)\Sophos\Sophos Anti-Virus\sav32cli.exe"
You may also need to add this permission to the folder location where the file to be scanned is uploaded (c:\temp) for example
You may also need to have administrator privileges to run the anti virus scan since IIS8 does not run as an administrator. When you are debugging visual studio uses your current logged in windows user(unless you use runas) so this will explain why it would work when debugging.
Have you tried running your web process in elevated trust?
Configuring .NET Trust Levels in IIS 7
<system.web>
<securityPolicy>
<trustLevel name="Full" policyFile="internal"/>
</securityPolicy>
</system.web>
ASP.NET Trust Levels and Policy Files
Most likely the permissions are not configured correctly on the content being scanned (the uploads folder) or the worker process user doesn't have the full permissions it needs to use Sophos. You know the executable itself is accessible by the worker process because you are getting exit codes and error messages that are specific to Sophos.
Because your process will delete files that are perceived as threats you need to grant the user running the process modify or full control permissions on the folders that store the uploaded files.
By default you could use the IIS_IUSRS group for ApplicationPoolIdentity processes, but you can verify (and modify) the user in IIS Manager > App Pools > Advanced.
This answer has more details
Here are some ideas:
Create the process using a different user with elevated privileges on the folder, see for reference start-a-net-process-as-a-different-user
If the previous suggestion fails, login one time on the server using the credentials used in point 1. It will configure registry entries connected to the user profile, some programs requires it.
Develop a simple .net service running on the server and monitoring the upload folder. The service has more probability running the Sophos scan succesfully. Here is a reference on service creation using .net.
The service may also talk to your web page using DB/file system/ etc.. so the operation may seem synchronous.
These are my 4 cents :-)

ASP.NET Process Start

I made new project (ASP.NET MVC Web Application) using Visual Studio Web 2013 Express Edition. Loading index page, redirects and everything works fine, except that in some part of my code I need to create Process and execute it, wait for it to finish, parse output of that external application and show that output to the user. However I get nothing. While debugging the code line by line:
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = Tool;
info.Arguments = filename + " " + avArray;
info.CreateNoWindow = true;
info.UseShellExecute = false;
info.RedirectStandardOutput = true;
Process p = new Process();
p.StartInfo = info;
p.Start();
p.WaitForExit();
Process exits immediately, someone would say it is pretty fast program, but application needs at least 5 seconds (sometimes 20 seconds) to complete.
What I think is happening is that process is not created in the first place, as my IIS settings or whatever other settings are not allowing me to run this EXE. What do I do to change this?
I've been trying to this for the past 2 weeks, I've read probably every post about it, and tried every solution suggested. I am choosing to write on this post since it is the most recent.
First of all, I am using VS2013, testing on IIS Express, and then on IIS 8.5., the webpages version is 3, and the target framework 4.5. And I am assuming that (as with my case) the goal is to launch the process on the server.
What I learned:
Using IIS Express should allow you to run the process without problems. You can try to allow it to launch the window, or start your process through the shell just to be sure that it is actually launching (a shell window should popup and close). If this happens, verify that you are giving the correct path to to your program, etc. So far so good.
Going into the IIS 8.5 is a totally different matter. Theoretically, the bad way of doing it should be preatty straight-forward: you create an app-pool for that server, give it a high privileged account (local system or network system, for instance); go to AdministrativeTools->Services->IIS, LogOn tab, and allow interaction with the desktop. You should be able to do the same as in IISExpress, but in my case is just the same as with a low privilege account.
I actually started by trying just to use impersonation, but also was not able to launch the process with IIS8.5. EDIT: I retried this again today, and the api won't even run if I enable impersonation.
I've spent more time than I would like with this, any input on why I can't get this to work properly with IIS8.5 (#clzola: IIS Express should do the job) is very welcome.

Start a ClickOnce Application From a Service

OK,
So I'm trying to figure out a way to launch a ClickOnce application from a Windows Service. I wanted to do it via the "Local System" (So no log in information prompts were done) account without the "Interact with desktop" option checked (since MS has been trying to get rid of that feature for a while).
I knew that I could launch a application to the desktop without that checked. So I dug a CreateProcessAsUserWrapper from the TechNet Blog. The wrapper can be found here http://code.msdn.microsoft.com/windowsdesktop/CSCreateProcessAsUserFromSe-b682134e/file/50832/8/Interactive%20Windows%20Service%20(CSCreateProcessAsUserFromService).zip
I then created the services application and a small exe with a copy of the .appref-ms of the ClickOnce applicaiton. The server then looks every 10 minutes to see if the ClickOnce app is running. If not it fires off the small exe with the CreateProcessAsUserWrapper which then in turn .appref-ms
Up to this point everything is running smoothly. The problem I've run into is that with the ClickOnce App starts up. It asks if it wants to install, despite being installed.
This is the code starting up the ClickOnce app:
string startupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
startupPath = Path.Combine(startupPath, "app.appref-ms");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "\"" + startupPath + "\"";
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
I don't know if there is anything i do to prevent it from asking to install. I have even tired switching the server over to run under the user account, but then I get errors Querying the User Token for when trying to interact with the desktop.
Anyone have any ideas?

run shell command (manage-bde) as administrator from C#

I need to run "manage-bde" shell command from C# code.
The main application process is already running as administrator and is Elevated.
I used code from : UAC self-elevation example on MS website for confirming the app process is elevated.
(http://code.msdn.microsoft.com/windowsdesktop/CSUACSelfElevation-644673d3)
However, when I try to run manage-bde from the C# code, I get "System can't find file specified".
Process p = new Process();
p.StartInfo.FileName = "C:\\Windows\\System32\\manage-bde.exe";
p.StartInfo.UseShellExecute = true;
p.Start();
As a workaround, I tried to create a batch file that runs the command.
string batchFileName = DateTime.Now.Ticks + ".bat";
StreamWriter writer = new StreamWriter(batchFileName);
writer.WriteLine("manage-bde");
writer.Flush();
writer.Close();
Process p = new Process();
p.StartInfo.FileName = batchFileName;
p.StartInfo.UseShellExecute = true;
p.Start();
The batch file is written , and executed successfully; However, the command "manage-bde" is not recognized.
I changed the code to use the verb "runas" and use admin password and that works, but I want the batch file to work without the need for providing the admin password. The current logged in user is already administrator on the computer but the batch file is not getting executed with the existing admin privileges . I need the batch file to execute and manage-bde to run successfully.
Your help or advice will be very highly appreciated :)
ps: some commands other than manage-bde work fine without need for admin runas.
The reason of the behavior I encountered was the Windows File System Redirector.
In most cases, whenever a 32-bit application attempts to access %windir%\System32, the access is redirected to %windir%\SysWOW64
https://msdn.microsoft.com/en-us/library/windows/desktop/aa384187%28v=vs.85%29.aspx
My application build was 32 bits. Whenever it tried to access System32 windows automatically redirected it to SysWow64 which does not contain "manage-bde.exe". I changed the build to 64 bits and then the application could access manage-bde.exe from System32
Even if you're running as the Administrator user, you're not fully elevated if UAC is running. Meaning that you'll have either the UAC prompt come up or you'll be prompted for a password.
The only real way you could get around that is to run your application elevated first, or to write a service that runs with elevated permissions to start your new process.
The alternative of course is to disable UAC, but that is undesirable in most situations.

Run exe from webpage

We have an internal page that I want to use to run an executable that updates some files on the server. In other words, rather than logging in to the server every time I need to manually run this executable, I would like to run it from the browser. The executable is self-contained on the server and does not interact with the user.
Here is my code:
try
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = Server.MapPath(#"\iPhoneXMLCreator.exe");
p.StartInfo.WorkingDirectory = Server.MapPath(#"\");
p.StartInfo.RedirectStandardOutput = false;
p.Start();
p.WaitForExit();
lblResult.Text = "Success!";
}
catch (Exception ex)
{
lblResult.Text = "Oops, there was a problem.<br><Br>" + ex.Message;
}
When I run it, the process shows up in Task Manager, but then exits within a few seconds without updating the files it is supposed to. There are no arguments to be passed, just a simple executable. Any ideas?
I would start by checking to see if the account which runs the web application has the appropriate permissions.
Most likely this is a permissions issue. Since it's the Asp.Net runtime that is executing this program, you need to ensure that the user account that the Asp.Net runtime uses has access to this executable, and to modify any resources (files, databases, etc) that get modified by the executable.
You can do this via impersonation, or by granting rights tot he appropriate accounts. The proper approach is to use impersonation.
http://msdn.microsoft.com/en-us/library/xh507fc5.aspx
Does the executable file run and process the XML when you run it manually on the server logged in as yourself?
Then it may be a simple permissions issue, since unless you are impersonating ...it's probably trying to run the exe under the ASPNET machine account, which most likely doesn't have rights to the folder the XML is in. Just a thought based on the info you provided.
2 things that you could do:
Run Process Monitor while you attempt to run the exe. I've used it many times to help to find security config problems (especially on web servers). It will log every io and registry access, and more importantly indicate success or failure. Get it here: http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx It requires no setup. Great tool!
Redirect stdout on your console exe. This will allow you to capture any error message that it is attempting to write to the console. Here's how to do it:
try
{
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = Server.MapPath(#"\iPhoneXMLCreator.exe");
p.StartInfo.WorkingDirectory = Server.MapPath(#"\");
// redirect stdout
p.StartInfo.RedirectStandardOutput = true;
var ConsoleOutput = new StringBuilder();
p.OutputDataReceived += (s, e) => ConsoleOutput.AppendLine(e.Data);
p.Start();
p.BeginOutputReadLine(); // if I remember correctly, you have to call Start() first or you get an exception
p.WaitForExit();
string output = ConsoleOutput.ToString();
lblResult.Text = "Success!";
}
catch (Exception ex)
{
lblResult.Text = "Oops, there was a problem." + ex.Message;
}
Rather than playing with website permissions for the Exe, one workaround that uses a level of indirection and puts a buffer between your web site and the Exe is to simply set a flag value into a text file on the web server when the Page representing the Exe is hit.
Set up a scheduled job on the server to check for that flag value every X hours, or minutes, or whenever and if the flag is seen, run the executable. Reset the flag/file when done. This opens up the possibility to check the flag via a webservice or other mechanisms, such that the target Exe doesn't even need to be on the same web server machine.
This is only viable if the exe does not need to run immediately when the page is hit.
Ok, figured it out. It was a data access issue. The .config file for the .exe had an invalid database connection string. Why it would work when logged in, I'm not sure, but it works now.

Categories