Search code examples
c#powershellsecurityexception.net-fiddle

DotNetFiddle throws "System.Security.SecurityException"


As there's no PSFiddle available at present, I wondered if I could use DotNetFiddle for this purpose by wrapping the PS code in C#.

I used the below code:

using System;
using System.Collections.ObjectModel;
using System.Management.Automation;     //if run on your machine, first ensure Windows SDK is installed (https://www.microsoft.com/en-us/download/details.aspx?id=11310)

public class Program
{
    public static void Main()
    {
        string script = @"
            param([string]$name) 
            ""hello $name"" #NB:Double quotes have to be escaped; otherwise all's good
            "; 
        RunPSScript(script);
    }
    private static void RunPSScript(string script) {
        using (PowerShell ps = PowerShell.Create())
        {
            ps.AddScript(script);
            ps.AddParameter("name", "Player One");
            Collection<PSObject> psOutput = ps.Invoke();
            foreach(PSObject item in psOutput) {
                if(item != null) {
                    Console.WriteLine(item.BaseObject.ToString());
                }
            }
        }
    }
}

When run in DotNetFiddle this throws a System.Security.SecurityException error.

This can be found here: https://dotnetfiddle.net/B4JLU0

The code works when run on my local machine, so I assume the issue is due to security on DotNetFiddle.

Question

Is there a workaround to allow this / avoid the exception; or is this simply not possible?


Solution

  • The full error message reads:

    Run-time exception (line 19): The type initializer for 'System.Management.Automation.Runspaces.RunspaceFactory' threw an exception.

    Stack Trace:

    [System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]

    [System.TypeInitializationException: The type initializer for 'System.Management.Automation.Runspaces.RunspaceFactory' threw an exception.] at Program.RunPSScript(String script): line 19 at Program.Main(): line 14

    PowerShell has to run in the context of a user, and when an exception is thrown on System.Security.Permissions.SecurityPermission, it most likely means the current user context does not have the necessary permissions or trust to run PowerShell, and without creating a runspace and doing some impersonation, I imagine it's trying to run as the webservice user which is very likely to have minimal permissions.

    I'm only making assumptions, and you probably have to contact the good folks at Entech Solutions for a clear cut answer, but hopefully this helps answer your question.