Restarting IIS website, copying new files with external program - c#

I have website (.net core 3.1) up on IIS (v10) on Windows (10)
website is calling external .exe that will stop IIS website (caller website), copy new files to iis website folder and start the site again. Problem is, when i stop website from external exe it doesn't shut down the website like admin does, then external program can't copy new files to website folder.
When i stop website manually i can copy and overwrite files it works as it should
Here is a snipped of website code that is calling external .exe:
using (var process = new Process())
{
process.StartInfo.FileName = _configuration.GetValue<string>("AppSettings:UpdaterPath");
process.StartInfo.Arguments = args;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.UseShellExecute = true;
process.Start();
}
here is a snippet of my external exe code:
ServerManager server = new ServerManager();
var site = server.Sites.FirstOrDefault(s => s.Name == _settings.WebsiteName);
if (site != null)
{
//Cloning old version to backup
Log($"Copying old files to backup...");
CloneDirectory(_settings.WebsitePath, Path.Combine(_settings.BackupPath, _settings.WebsiteName));
//Copying new version to working dir
//if(!Directory.Exists(temp_folder)) Directory.CreateDirectory(temp_folder);
Log($"Extracting new files...");
ZipFile.ExtractToDirectory(temp_zip, temp_folder, true);
Log($"Stopping {_settings.WebsiteName}...");
site.Stop();
Log($"Copying new files...");
CloneDirectory(Path.Combine(_settings.FilesPath, "temp"), _settings.WebsitePath);
Log($"Starting {_settings.WebsiteName}...");
site.Start();
if (site.State == ObjectState.Started)
{
server.ApplicationPools[site.Applications["/"].ApplicationPoolName].Recycle();
}
}
CloneDirectory() just copies/overwrites files recursively.
I've tried stoping website pool, recycling, server.CommitChanges(), but nothing works because main dll files with real changes to website can't be copied because **
access is denied
**
this all works fine when i call exe as administrator
I've tried giving folder/files user privileges to IIS_IUSRS and my website default pool
I've tried giving website physical path credentials as administrator
I've tried giving website pool privileges identity set to admin acc, or NetworkService, LocalService
basically any combo i can think off
what i noticed is when i stop app pool in my exe it stops working after a few seconds
I assume there is a problem with privileges (cant stop iis, copy files etc)

Related

Getting "Access is Denied" error on Process.Start() on an application running an executable with all permissions granted

The context here is that we have a C# service that normally runs scheduled jobs, but an executable was created that allows jobs to be triggered manually via command line. We put that executable on a separate IIS server, and did NOT install it as a service. The code inside the app to determine how it's being run is simply:
if (Environment.UserInteractive)
{
//parse the parameters and run the specified job
}
else
{
//start the service jobs
}
I made an API as a wrapper to call that executable, which uses the following code to run the executable with arguments as a user of the machine.
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
WorkingDirectory = (absolute path of the folder that contains the exe),
FileName = (absolute path to the exe),
Arguments = (args),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
Domain = (domain),
UserName = (username),
Password = (password),
Verb = "runas"
}
};
proc.Start();
proc.WaitForExit();
The API and the exe live in the same base folder. The API runs in IIS under an app pool user that is the same user it is running the process with. This user has Full Access permissions to the folder and executable, as well as the app pool user. We also added the user to the Administrator's group on that machine.
Running the exe via command line locally on that machine works fine. Only when calling from this application do we get the following error:
System.ComponentModel.Win32Exception (5): Access is denied
at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
I've confirmed that we are targeting the right file, that my SessionId is not 0 (I would get an error saying the service was not installed whenever I didn't start the process as a specified user), and that the app pool user and windows user have permissions to execute the file. UAC is off, and the API and exe are not on the C:/ drive. After hours of googling and trying different things, I'm out of ideas. Any help would be very appreciated.

IIS 8( windows server 2012) cannot run batch file

Im hosting an asp.net application in IIS8 on windows server 2012.
this application suppose to execute an batch file.
it works perfect if i execute the application with visual studio in debug mode. but when i upload it to the IIS the application cant execute the batch file.
i tried to change the batch file with exe file. same problem.
the batch file suppose to execute from the application(WCF application) that in the IIS:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.WorkingDirectory = #"C:\path";
proc.StartInfo.FileName = #"C:\path\executer.bat";
proc.Start();
proc.Close();
please help,
Most likely the problem you are experiencing is due to permissions. You need to check what account the IIS Application Pool that your app is running under is configured for and whether that account has rights to run your batch file or the commands within that batch file.
When running in Visual Studio you're likely running IIS Express as the interactive user.
When running under IIS by default you're running under ApplicationPoolUser identity which has no rights to execute code, has no file access or anything else. Unless you've explicitly set a different account with appropriate file access rights to the batch file, and rights to execute the commands inside of the batch file, you won't be able to run the batch file from within IIS. To change that change the Application Pool user identity to a user that does have rights to both read and execute the batch file on disk and has any rights required to run what's executing in the batch file.
Make sure any folder or file accessed by your application have permissions granted to the AppPoolUser account. It is also important to check your applications resource folders too. For example, if you are writing logs, make sure you give the appPool user account enough permission to write to that file.
Your code is working fine . May be there is some issue in batch file i faced before .My batch file is
start "" BATCHLOG.exe
where BATCHLOG.exe is the executable
Some times batchfile named only
BATCHLOG.exe
does not work correctly on windows scheduler so may be in that case of yours

Exe working if executing from VS2012 but not working when hosted on IIS

I am executing this code from MVC website.If i run this code from VS 2012 IIS express it is working but if I host the website on IIS server, it does not work. I tried debugging but there is some error code coming. If I also impersonate my id and pass the my id but all in vain.
Code:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
Char[] chr = Password.ToCharArray();
System.Security.SecureString pwd = new System.Security.SecureString();
foreach (char c in chr)
{
pwd.AppendChar(c);
}
proc.StartInfo.FileName = path to WZZip.exe
//proc.StartInfo.Arguments = -ys20480 pathtosplit landingZone;
proc.StartInfo.UserName = UserName; //Comes from config file
proc.StartInfo.Password = pwd; //Comes from config file
proc.StartInfo.Domain = Domain; //Comes from config file
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
bool result = proc.Start();
When running a exe through iis You should start with the some questions:
A) Should I bypass built-in security that protects the IIS Server and Windows System ?
B) If you allow executables to run using paths into the OS or the IIS sever who else can use this ie "HAcker" ?
C) There have been changes to Windows and IIS Server to protect the system(s) from "Attacks" and to limit the Surface Area for exploits.
What Security Monitoring is being done for the system & IIS Server ?
What security protection will you implement for your executable ?
If you can justify the risks for A - C you can "Work Around" the restrictions.
If you understand the Risks Technet has tools to help with some of the issues http://blogs.technet.com/b/elevationpowertoys/ .
For Windows Vista Windows 7 Windows 2008 you have the Standard User and limits for Permissions and Rights
a thread http://forums.iis.net/p/1178151/1981859.aspx#1981859 for who can do what.
You can Search (Goole or Bing) for "Changes to Windows Destop Security" "Session(0) changes and impacts for Systems & Services"
you also can get a copy of the "Vista Developer Story" from Microsoft Download Center.
You should check the MSDN library for Application Compatability and how to Design using User Access Control (UAC).
Many of the security changes have been added to Windows 2003 and IIS 6.0 server.
Finally u can Add MIME Types in IIS
Open IIS Manager.
Browse to the IIS Site or subfolder where the ThinApp EXE .
Right click on that site or subfolder and select PROPERTIES.
Select the HTTP HEADERS tab.
Click on the MIME TYPES button.
In the extension box, type ".exe".
In the MIME TYPE box, type "application/octet-stream".
Click OK.

Calling a .exe as Admin from within my code in Program Files folder

I have a C# application which calls an .exe file. This executable file must be started with administrator rights. But I don't want to run my application with admin rights.
I use the following code for that:
ProcessStartInfo procStartInfo = new ProcessStartInfo("foo.exe");
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
procStartInfo.Verb = "runas";
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
If I put my application in no specific folder, everything works fine, when calling the executable, the user is asked to run it as admin. But when I put my application in the "Program Files" folder and start it, when calling the execution file, there is NO question to run it as admin. And because of that, execution fails.
I'm using Windows 7 and the executable file is not lying in the "Program Files" folder. Is there a way to always run this file as admin but not my application?
Just add a manifest to the target application stating that it should be run as admin. The responsibility for that generally lies with the application being started, not the application which starts it.
An exception would be cases like Notepad being called to open a shared configuration file, but you haven't provided enough details to determine that.
Just Add a new Application manifest file in your project and
change this <requestedExecutionLevel> as
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

How to get server-side console app to run on ASP.net website(IIS7)?

I have an ASP.net website that is hosted on IIS7, within the asp.net code I have a C# statement that launches a .exe on my webserver on a button click. For some reason in visual studio it will launch on the local development server but when I move it to the IIS7 server it will not pop up a black console box on button click. This is what I am doing.
generateSpanish = "/n= " + serverName + "GenerateVoice SpanishVoice";
Process serverSideCommandSpanish = new Process();
serverSideCommandSpanish.StartInfo.FileName = Server.MapPath("Config\myexe.exe");
serverSideCommandSpanish.StartInfo.Arguments = generateSpanish;
serverSideCommandSpanish.EnableRaisingEvents = true;
serverSideCommandSpanish.StartInfo.UseShellExecute = true;
serverSideCommandSpanish.Start();
Again it launches in visual studio( a black console app pops up on the "server") but on my IIS server it does not do the console app popup serverside?
You need to enable the handler for exe's under IIS7. Do this by going to the web site under MMC and select Handler Mappings.
You may be able to get this to work using telling your Process to run PsExec with the -i argument and having PsExec run the .exe you're actually trying to start. The -i argument tells PsExec to execute the target in interactive mode on the desktop of a specified user session.

Categories

Resources