Starting Process from ASP.NET - asp.net

I'm running an ASP web application that should start a Powershell script on the server. To run this Powershell script a lot of Domain rights are needed. So I run the apppool under a user that has all the rights.
But when I start the powershellscript I alway get the that the access is denied.
Has any one an idea how to solve the problem?
When I start a process as described, is the process running under the usercontext of the app pool or under the usercontext of the user which is logged in in the ASP.NET web application?
I'ver tried two methods
1.
string cmdArg = "C:\\Scripts\\test.ps1 " + username;
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(cmdArg);
pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
string test = Environment.UserName;
}
return results[0].ToString();
2.
string cmdArg = "C:\\Scripts\\test.ps1 " + username;
Process myProcess = new Process();
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("powershell.exe",cmdArg);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
StreamReader myStreamReader = myProcess.StandardOutput;
myProcess.WaitForExit();
string myString = myStreamReader.ReadLine();
return myString;
Ok, you think running the Apppool with these grand permissions is not best practise.
What about puting a webservice between? The webservice is in an appdomain that is only reachable from localhost?
Update
Ok, I've written an asp.net webservice. The webservice runs in an applicationpool with all rights but is only reachable from localhost. The webservice contains the code to start the script. The ASP MVC3 webapplication is running in a applicationpool with nearly no rights.
But when the webmethod is executed I always get an error that tell me, that I haven't enought rights. I tried to set the impersonate in the webconfig false, but without success.
Does anyone know how to solve this probleme?
Update:
I've read out the current user who execute the powershell when I start it from the webservice. I says it is the user who've got all rights. But the ps throws Errors like: you can't start a method with value null.
Then I've tried to run the ps with runsas as a low level user. I get the same errors.
Then I've tried to run the ps with the same user as in the webservice and everything worked!
Is there anyone who could explain this phenomenon?
And what is the different between my code above and a runas? (same user context)
thanks a lot!

Starting a new process in a HTTP request is not great for performance and it may also be a security risk. However, before ASP.NET and other modern web servers was available the only way to serve content (besides static files) was to execute a program in a separate process.
The API for doing this called the Common Gateway Interface (CGI) and still supported by IIS. If configured correctly you can execute a program on each request.
I'm not sure that you can use CGI to execute a script but then you can create an ISAPI filter that will execute PowerShell on files having extension .ps1. This is basically how for instance php.exe is executed in a new process when a file with extension .php is requested.
Enabling executable content can and should be done on a folder-by-folder basis to limit the security risk. In general you should avoid mixing different kinds of content, ie. it should not be possible to both view a script and also execute it.
If you intention is to be able to remotely run PowerShell scripts and not much else it should also be easy to write a small HTTP server in PowerShell completely removing IIS and ASP.NET from the equation.

I suppose this merely depends on the impersonation settings, if impersonation is enabled, then the currently logged in user is used, otherwise the app pool user

Related

Why app is throwing error in test environment but working fine in local machine using ASP.NET Web Forms and MSAL?

Scenario:
Using the application, customer can access the emails in within the application and decide to save it. I have used Exchange Web Service Managed API for this. Things were working fine until IT implemented Multi factor Authentication. Now the program cannot access the mailbox based on the username and password.
Solution
In order to overcome this issue I integrated MSAL(Microsoft Authentication Library) to acquire the Access token in order to use it with the EWS Managed API to access the emails. I have registered an application in the Azure and used the clientID and TenentID. It works perfectly fine when testing locally. But throws an error when deploying in dev/test environnment. I am not sure what to do. Could you please help me with this?
Private Function GetDelegatedExService() As ExchangeService
If Session("EwsOAuthToken") Is Nothing Then
Dim caller As New AsyncGetToken(AddressOf GetDelegatedToken)
' Initiate the asynchronous call.
Dim result As IAsyncResult = caller.BeginInvoke(Nothing, Nothing)
' thread from any process ready to run and has a higher priority then Sleep(0) will yield the processor and let it run
Thread.Sleep(0)
' Perform additional processing here and then wait for the WaitHandle to be signaled.
result.AsyncWaitHandle.WaitOne()
' Call EndInvoke to retrieve the results.
Dim returnValue As String = caller.EndInvoke(result)
Session("EwsOAuthToken") = returnValue
End If
Dim ewsClient = New ExchangeService()
ewsClient.Url = New Uri("https://outlook.office365.com/EWS/Exchange.asmx")
Dim myToken = Session("EwsOAuthToken").ToString()
' Setup OAuthCredentials with the token
ewsClient.Credentials = New OAuthCredentials(myToken)
Return ewsClient
End Function
Private Function GetDelegatedToken() As String
Dim pcaOptions = New PublicClientApplicationOptions() With
{
.ClientId = ConfigurationManager.AppSettings("appId"),
.TenantId = ConfigurationManager.AppSettings("tenantId")
}
Dim redirectUrl = ConfigurationManager.AppSettings("EBWebURL")
Dim pca = PublicClientApplicationBuilder _
.CreateWithApplicationOptions(pcaOptions) _
.WithRedirectUri(redirectUrl) _
.Build()
' The permission scope required for EWS access
Dim token = OpenAuthPopup(pca).GetAwaiter().GetResult()
Return token
End Function
Private Async Function OpenAuthPopup(pca As PublicClientApplication) As Tasks.Task(Of String)
Dim ewsScopes = {"https://outlook.office365.com/EWS.AccessAsUser.All"}
Dim authResult = Await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync()
Return authResult.AccessToken
End Function
This is the local testing where user is able to get the login by Microsoft account prompt. They have to enter their organization account details, gets the Multi Factor Auth code in phone, adds in the prompt and then gets authenticated(it simply returns a access token).
But when the code is deployed to DEV/TEST environment. I get the following error. It is not even prompting for the Microsoft Login. And I tried searching for the given error, but not able to figure out what the problem actually is with the asp.net web app or Microsoft Auth Library.
I am not experienced with the technologies you describe in your question but I will try to give you my persepctive on the issue. From what I can understand, the code you have pasted here is supposed to run on the web-server. Testing the application locally, the client is requesting information from the web-server but the web-server needs first to aqcuire an authentication token. The modal window that appears on the screen, asking from the client to authenticate, seems to be fired by
pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync()
This code runs on the web-server and it is the web-server that shows this pop-up. The clients can only enter their credentials because the testing is taking place on the same machine where the web-server lives. In produciton environments, web app code is not allowed to open a modal window. Even if it was permitted, there would be no one there to interact with the pop-up.
I checked the MSIL library and I found that PublicClientApplication contains more authentication methods and some of them are non-interactive, such as AquireTokenByUsernamePassword. I am not sure how you can handle the code received by the user's mobile. I cannot help any further on the library since I am not familiar with it.
Another option might be to make the client-browser open a pop-up window on https://outlook.office365.com/EWS.AccessAsUser.All and somehow return the authorization token back to the web-server. You might want to take a look at this and see if it suits your needs.

When a Asp.net Web App is recycled in Azure?

We have a asp.net web app with "Always on" that is running a long task. To avoid to run this task two or more time simultaneously, at the beggining of the task a flag is set to database. If this task is forced to shutdown the flag is not removed, and the task is not gonna run again without manual intervention.
I've been looking for if the concept of recycle a website is existing in Azure, I didn't find much about it. I found for example https://stackoverflow.com/a/21841469/1081568 it seems that is never executed recycled, but I find some people complaining about web apps with "always on" set that recycles randomly.
I would like to know in which circumstance an app could be Recycled/shutdown in Azure? Just for maintenance? Azure recycle asp.net webs apps? Or is a concept exclusive of On-Premise servers?
And another question, Is there a way to capture this shutdown/recycle from Azure and stop my running task gracefully if it's running.
Thanks
As far as I know, normally azure will not recycled your web app's resource, if you set web apps with "always on".
If web app's “Always On” setting is off, which means the web site will be recycled after period of inactivity (20 minutes).
And another question, Is there a way to capture this shutdown/recycle from Azure and stop my running task gracefully if it's running.
According to your description, I suggest you could send a kudu restapi request to get the current web app's processid.
If the application restarted, the processid will be changed. By comparing the processid, you could capture this web app is recycled.
More details about how to get the current web app's processid, you could refer to below steps:
1.Set a Deployment credentials in your azure web application as below:
Notice:Remember the user name and password, we will use them to generate the access token
2.Send the request to below url to get the process information.
Url:https://yourwebsitename.scm.azurewebsites.net/api/processes
Code sample:
string url = #"https://yourwebsitename.scm.azurewebsites.net/api/processes";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";
httpWebRequest.ContentLength = 0;
string logininforation = "username:password";
byte[] byt = System.Text.Encoding.UTF8.GetBytes(logininforation);
string encode = Convert.ToBase64String(byt);
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + encode);
using (HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (System.IO.StreamReader r = new System.IO.StreamReader(response.GetResponseStream()))
{
string jsonResponse = r.ReadToEnd();
dynamic result = JsonConvert.DeserializeObject(jsonResponse);
dynamic resultList = result.Children();
foreach (var item in resultList)
{
Console.WriteLine(item.name + " : " + item.id);
}
}
}
Result:
You could also find the processid in the portal.
Select your web app --> Process explorer
Image:

Pre-Load Web Application Pages After Deployment to Prevent Slow Loading

We build and deploy our web application to our dev environment automatically every night (using VSTS). When we come into the office in the morning, the first person to access the application has to wait an extended period for each page to load the first time. Subsequent loads are very fast.
The problem has a greater impact in our live environment where, after a deployment, it is potentially an end-user who is the first person to access the application and complain of slowness. To mitigate for this, a member of the team is currently accessing every page of the application manually after deployment to the live environment so that they 'pre-load' every page, which works, but is obviously time-consuming!
I've done a fair bit of searching on the subject, and have configured the appropriate Application Pool in our IIS server (IIS 8.5) so that its Start Mode is set to "AlwaysRunning". I've also edited our applicationHost file and set the appropriate Sites with the preloadEnabled="true" attribute. I did this after reading the instructions in this very helpful Microsoft documentation.
However, if I'm reading that documentation correctly, any pre-loading of the website which might alleviate the issue we're having (and I'm not even certain that this is the kind of pre-loading that I'm thinking of) only takes place when the server, the IIS service of the Application Pool are restarted. This isn't happening in our case. We need the pre-loading to take place following a deployment of the application to the IIS server.
Is there a way to automate this pre-loading?
One way of doing this would be to perform a HTTP request automatically:
As soon as the app was deployed (by running a task from the deploying machine)
Before the application pool has the chance to shut itself down (using Task Scheduler for instance)
Personally, I use a tool that is run in both cases to keep the site warmed up.
Advantages
Robust control over how and when this warm-up is executed.
It's completely independent from any IIS or web.config setup.
Disadvantages
Generates "bogus" log information.
Keeps the app permanently in memory (the Pool would never time-out, essentially wasting server resources for sites with a low # of visitors).
Sample
Such a tool could be a simple console app written as follows:
var taskInfo = new {
Url = "http://www.a-website-to-keep-warm.url",
UseHostHeader = true,
HostHeader = "www.a-website-to-keep-warm.url",
HttpMethod = "head"
};
HttpStatusCode statusCode = HttpStatusCode.Unused;
long contentLength = 0;
try
{
Dictionary<string, string> headers = new Dictionary<string, string>();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(taskInfo.Url);
webRequest.Method = taskInfo.HttpMethod.ToUpper();
if(taskInfo.UseHostHeader)
webRequest.Host = taskInfo.HostHeader;
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
//did we warm-up the site successfully?
statusCode = webResponse.StatusCode;
contentLength = webResponse.ContentLength;
//optionally read response headers
foreach (string header in webResponse.Headers)
{
headers.Add(header, webResponse.Headers[header]);
}
}
decimal kilobytes = Math.Round(contentLength / 1024M, 1);
Debug.WriteLine($"Got {kilobytes:F1} kB with statuscode: \"{statusCode} \" ...");
}
catch (Exception ex)
{
Debug.WriteLine($"taskInfo failed with exception: {ex.Message}");
}
In my case, I read a bunch of taskInfo objects from a json file and execute them asynchronously every X minutes, making sure X is lower than the Pool-timeout value. It is also run immediately after every deploy.
Because we're not interested in getting the entire content, it uses a HTTP HEAD request instead of GET. Lastly, it supports multiple sites on the same host by adding a Host header to the request.

How to run external exe under specific account from asp.net web service?

Bellow is my code from asp.net service which is trying to run some external exe. It works fine from my Visual Studio on win 7, but fails on my server (server 2008).
Myapp.exe reports back eror that account under which is runned doesn't have sufficiet priviliges.
List<ProcInfo> allProcesses = new List<ProcInfo>();
ProcessStartInfo pInfo = new ProcessStartInfo();
pInfo.FileName = binPath + #"\myApp.exe";
pInfo.WindowStyle = ProcessWindowStyle.Hidden;
pInfo.CreateNoWindow = true;
pInfo.UseShellExecute = false;
pInfo.RedirectStandardOutput = true;
string exitMsg = "";
int exitCode = 1;
try
{
using (Process proc = Process.Start(pInfo))
{
exitMsg = proc.StandardOutput.ReadToEnd();
proc.WaitForExit(1000);
exitCode = proc.ExitCode;
}
}
Resource pool on the server runs under account with sufficient priviliges and I also tried to use same account in code to start service with those same credentials and still nothing.
I have been told that account under which asp.net worker thread runs impose some additional limitations. So even if resource pool runs under appropriate account, you still won't have sufficient priviligies.
I also found something about using pInvoke and win32 api calls as the only way to run external code from asp.net service. But I don't have any win32 api knowlege nor did I found exples of this.
I would be very grateful for any tip/example how to run external exe under specified account from asp.net service.
If the account the worker process is runnning under lacks sufficient privelages then you have a few options.
You can either use impersonation in your code:
WindowsIdentity.Impersonate Method
Or configure IIS to run the application under a user account with the required privileges.
Here is an article which explains different methods of impersonation security:
Understanding ASP.NET Impersonation Security
If you do not feel confident implementing the user impersonation code yourself, here is a link to a codeproject article:
A small C# Class for impersonating a User

File permissions with FileSystemObject - CScript.exe says one thing, Classic ASP says another

I have a classic ASP page - written in JScript - that's using Scripting.FileSystemObject to save files to a network share - and it's not working. ("Permission denied")
The ASP page is running under IIS using Windows authentication, with impersonation enabled.
If I run the following block of code locally via CScript.exe:
var objNet = new ActiveXObject("WScript.Network");
WScript.Echo(objNet.ComputerName);
WScript.Echo(objNet.UserName);
WScript.Echo(objNet.UserDomain);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var path = "\\\\myserver\\my_share\\some_path";
if (fso.FolderExists(path)) {
WScript.Echo("Yes");
} else {
WScript.Echo("No");
}
I get the (expected) output:
MY_COMPUTER
dylan.beattie
MYDOMAIN
Yes
If I run the same code as part of a .ASP page, substituting Response.Write for WScript.Echo I get this output:
MY_COMPUTER
dylan.beattie
MYDOMAIN
No
Now - my understanding is that the WScript.Network object will retrieve the current security credentials of the thread that's actually running the code. If this is correct - then why is the same user, on the same domain, getting different results from CScript.exe vs ASP? If my ASP code is running as dylan.beattie, then why can't I see the network share? And if it's not running as dylan.beattie, why does WScript.Network think it is?
Your problem is clear. In the current implementation you have only impersonation of users and no delegation. I don't want to repeat information already written by Stephen Martin. I only want to add at least three solutions. The classical way of delegation which Stephen Martin suggests is only one way. You can read some more ways here: http://msdn.microsoft.com/en-us/library/ff647404.aspx#paght000023_delegation. I see three practical ways of you solving your problem:
Convert the impersonation token of the user to a token with delegation level of impersonation or to a new primary token. You can do this with respect of DuplicateToken or DuplicateTokenEx.
Use S4U2Self (see http://msdn.microsoft.com/en-us/magazine/cc188757.aspx and http://msdn.microsoft.com/en-us/library/ms998355.aspx) to receive a new token from the old one with respect of one simple .NET statement WindowsIdentity wi = new WindowsIdentity(identity);
You can access another server with respect of one fixed account. It can be a computer account on an account of the application pool of the IIS. It can be another fixed defined account which one will only use for access to the file system.
It is important to know which version of Windows Server you have on the server where IIS is running and which Domain Function Level you have in Active Directory for your Domain (you see this in "Active Directory Domain and Trusts" tool if you select your domain and choose "Raise Domain Functional Level"). It is also interesting to know under which account the application pool of the IIS runs.
The first and the third way will always work. The third way can be bad for your environment and for the current permission in the file system. The second one is very elegant. It allows control of which servers (file server) are accessed from IIS. This way has some restrictions and it needs some work to be done in Active Directory.
Because you use classic ASP, a small scriptable software component must be created to support your implementation.
Which way do you prefer?
UPDATED based on the question from comment: Because you use classic ASP you can not use a Win32 API directly, but you can write a small COM component in VB6 or in .NET which use APIs which you need. As an example you can use code from http://support.microsoft.com/kb/248187/en. But you should do some other things inside. So I explain now which Win32 API can help you to do everything what you need with tokens and impersonation.
First of all a small explanation about impersonation. Everything works very easy. There are always one primary token under which the process runs. To any thread another token (thread token) can be assigned. To do this one needs to have a token of a user hUserToken and call API ImpersonateLoggedOnUser(hUserToken);.
To go back to the original process token (for the current thread only) you can call RevertToSelf() function. The token of user will be received and already impersonated for you by IIS, because you so configured your Web Site. To go back to the original process token you should implement calling of the function RevertToSelf() in your custom COM component. Probably, if you need to do nothing more in the ASP page, it will be enough, but I recommend you be more careful and save current users token in a variable before operation with files. Then you make all operations with file system and at the end reassign users token back to the current thread. You can assign an impersonation token to a thread with respect of SetThreadToken(NULL,hUserToken);. To give (save) current thread token (user token in your case) you can use OpenThreadToken API. It must work.
UPDATED 2: Probably the usage of RevertToSelf() function at the end of one ASP page would be already OK for you. The corresponding C# code can be so:
Create a new Project in C# of the type "Class Library" with the name LoginAdmin. Paste the following code inside
using System;
using System.Runtime.InteropServices;
namespace LoginAdmin {
[InterfaceTypeAttribute (ComInterfaceType.InterfaceIsDual)]
public interface IUserImpersonate {
[DispId(1)]
bool RevertToSelf ();
}
internal static class NativeMethods {
[DllImport ("advapi32.dll", SetLastError = true)]
internal static extern bool RevertToSelf ();
}
[ClassInterface (ClassInterfaceType.AutoDual)]
public class UserImpersonate : IUserImpersonate {
public UserImpersonate () { }
public bool RevertToSelf () {
return NativeMethods.RevertToSelf();
}
}
}
Check in project properties in "Build" part "Register for COM interop". In "Signing" part of the project check Sign the assembly and in "Choose a strong name key file" choose <New...>, then type any filename and password (or check off "protect my key..."). At the end you should modify a line from AssemblyInfo.cs in Properties part of the project:
[assembly: ComVisible (true)]
After compiling this project you get two files, LoginAdmin.dll and LoginAdmin.tlb. The DLL is already registered on the current computer. To register if on the other computer use RegAsm.exe.
To test this COM DLL on a ASP page you can do following
<%# Language="javascript" %>
<html><body>
<% var objNet = Server.CreateObject("WScript.Network");
Response.Write("Current user: ");Response.Write(objNet.UserName);Response.Write("<br/>");
Response.Write("Current user's domain: ");Response.Write(objNet.UserDomain);Response.Write("<br/>");
var objLoginAdmin = Server.CreateObject("LoginAdmin.UserImpersonate");
var isOK = objLoginAdmin.RevertToSelf();
if (isOK)
Response.Write("RevertToSelf return true<br/>");
else
Response.Write("RevertToSelf return false<br/>");
Response.Write("One more time after RevertToSelf()<br/>");
Response.Write("Current user: ");Response.Write(objNet.UserName);Response.Write("<br/>");
Response.Write("Current user's domain: ");Response.Write(objNet.UserDomain);Response.Write("<br/>");
var fso = Server.CreateObject("Scripting.FileSystemObject");
var path = "\\\\mk01\\C\\Oleg";
if (fso.FolderExists(path)) {
Response.Write("Yes");
} else {
Response.Write("No");
}%>
</body></html>
If the account used to run the IIS application pool has access to the corresponding network share, the output will be look like following
Current user: Oleg
Current user's domain: WORKGROUP
RevertToSelf return true
One more time after RevertToSelf()
Current user: DefaultAppPool
Current user's domain: WORKGROUP
Yes
Under impersonation you can only access securable resources on the local computer you cannot access anything over the network.
On Windows when you are running as an impersonated user you are running under what is called a Network token. This token has the user's credentials for local computer access but has no credentials for remote access. So when you access the network share you are actually accessing it as the Anonymous user.
When you are running a process on your desktop (like CScript.exe) then you are running under an Interactive User token. This token has full credentials for both local and remote access, so you are able to access the network share.
In order to access remote resources while impersonating a Windows user you must use Delegation rather then Impersonation. This will involve some changes to your Active directory to allow delegation for the computer and/or the users in your domain. This can be a security risk so it should be reviewed carefully.

Resources