Run Only signed powershell scripts from C #

I have a windows service that loads a script and then runs it.

I am trying to make my Windows service more secure by forcing it to accept only signed shell scripts.

I ran the Set-ExecutionPolicy AllSigned command on the server, and this works on the Windows command prompt.

However, my code still works with both signed and unsigned scripts, even if set-executionpolicy is set to a limit.

I tried two approaches:

RunspaceConfiguration runpaceConfiguration = RunspaceConfiguration.Create ();

        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();

        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
        Pipeline pipeline = runspace.CreatePipeline();         
        pipeline.Commands.AddScript(@"Set-ExecutionPolicy AllSigned");
        pipeline.Commands.AddScript(@"Get-ExecutionPolicy");
        pipeline.Commands.AddScript(script);
        Collection<PSObject> results = pipeline.Invoke();

And another approach:

using (PowerShell ps = PowerShell.Create())
                {
                    ps.AddCommand("Set-ExecutionPolicy").AddArgument("Restricted");
                    ps.AddScript("Set-ExecutionPolicy Restricted");
                    ps.AddScript(script);
                    Collection<PSObject> results = ps.Invoke();
                  }

In both situations, the code also runs unsigned scripts.

Did I miss something?

+5
source share
1

. - Get-AuthenticodSignature:

 public bool checkSignature(string path)
    {

        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();
        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(String.Format("Get-AuthenticodeSignature \"{0}\"", path));
        Collection<PSObject> results = pipeline.Invoke();
        Signature check = (Signature)results[0].BaseObject;
        runspace.Close();
        if (check.Status == SignatureStatus.Valid)
        {
            return true;
        }
        return false;
    }

,

Dan

+1

All Articles