简体   繁体   中英

PowerShell script failling on IIS

Currently we got an C# MVC web application with basic Windows Authentication deployed on IIS 7.5 on Win Server 2012 R2.

Controller:

 public ActionResult Index([Bind(Include = "ID,cmd,arg1,arg2")] PowerShellCMD PScmd)
    {
        if (ModelState.IsValid)
        {
           //String script = @"C:\TEMP\test.ps1";
            String script = @"D:\a-espinoza\Scripts\wsa.ps1";

            PowerShell ps = PowerShell.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace();
            ps.Runspace = runspace;

            ps.Runspace.Open();

            using (var impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate())
            {

                ps.AddScript(script);
                ps.AddParameter(null, PScmd.cmd);

                // Execute the script
                var results = ps.Invoke();

                runspace.Close();

                if (results.Count > 0)
                {
                    // We use a string builder ton create our result text
                    var builder = new StringBuilder();

                    foreach (var psObject in results)
                    {
                        // Convert the Base Object to a string and append it to the string builder.
                        // Add \r\n for line breaks
                        builder.Append(psObject + "\r\n");
                    }

                    // Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
                    PScmd.result = Server.HtmlEncode(builder.ToString());
                }
            }
            //impersonationContext.Undo();
        }

        return View(PScmd);
    }

Wherever an user without login rights on the IIS server where my app is deployed got the bellow error:

Server Error in '/' Application.

Security Exception

Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Requested registry access is not allowed.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[SecurityException: Requested registry access is not allowed.]
Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable) +14302727 System.Environment.GetEnvironmentVariable(String variable, EnvironmentVariableTarget target) +278
System.Management.Automation.ModuleIntrinsics.GetExpandedEnvironmentVariable(String name, EnvironmentVariableTarget target) +9
System.Management.Automation.ModuleIntrinsics.SetModulePath() +61
System.Management.Automation.ExecutionContext.InitializeCommon(AutomationEngine engine, PSHost hostInterface) +714
System.Management.Automation.AutomationEngine..ctor(PSHost hostInterface, RunspaceConfiguration runspaceConfiguration, InitialSessionState iss) +19187352
System.Management.Automation.Runspaces.LocalRunspace.DoOpenHelper() +19188647 System.Management.Automation.Runspaces.RunspaceBase.CoreOpen(Boolean syncCall) +360
PowerShellExecution.Controllers.PWCmdsController.Index(PowerShellCMD PScmd) +254 lambda_method(Closure , ControllerBase , Object[] ) +127 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary 2 parameters) +242
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 parameters) +242
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 parameters) +242
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 parameters) +39

System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +12
System.Web.Mvc.Async.WrappedAsyncResult 2.CallEndDelegate(IAsyncResult asyncResult) +139
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +112 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +452 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +37 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +241
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid
2.CallEndDelegate(IAsyncResult asyncResult) +139
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +112 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +452 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +37 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +241
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid
2.CallEndDelegate(IAsyncResult asyncResult) +139
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +112 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +452 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +37 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +241
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid
1.CallEndDelegate(IAsyncResult asyncResult) +111

System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53 System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult) +19
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
System.Web.Mvc.Async.WrappedAsyncVoid
1.CallEndDelegate(IAsyncResult asyncResult) +19
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
System.Web.Mvc.Async.WrappedAsyncVoid
1.CallEndDelegate(IAsyncResult asyncResult) +19
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
System.Web.Mvc.Async.WrappedAsyncVoid
1.CallEndDelegate(IAsyncResult asyncResult) +111

System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34274

How can we avoid the error without allow everyone access on the server running IIS?

The Register key have already given read access to everyone.

Are you able to look at the Security logs on the server to see which user is causing the SecurityException?

I could be a little off on this one...but the Runspace is being created outside of the Impersonation so it would be running as the Application Pool identity/user. I wouldn't expect that to run when any user accesses the site.

The user you're impersonating will have to have access to the registry key your script is referencing. Check this out to accomplish that: https://technet.microsoft.com/en-us/library/cc775454(v=ws.10).aspx

Try changing:

PowerShell ps = PowerShell.Create();
Runspace runspace = RunspaceFactory.CreateRunspace();
ps.Runspace = runspace;
ps.Runspace.Open();

using (var impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate())
{
    //...Code
}

To:

using (var impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate())
{
    PowerShell ps = PowerShell.Create();
    Runspace runspace = RunspaceFactory.CreateRunspace();
    ps.Runspace = runspace;
    ps.Runspace.Open();

    //...Code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM