2013-03-25 11 views
5

Ich habe einen Windows-Dienst, der ein Skript herunterlädt und es dann ausführt.Run Nur signierte Powershell-Skripte von C#

Ich habe versucht, meinen Windows-Dienst sicherer zu machen, so dass nur signierte Power-Shell-Skripte akzeptiert werden.

Ich habe den Befehl Set-ExecutionPolicy AllSigned auf dem Server ausgeführt, und dies funktioniert in der Windows Power Shell-Eingabeaufforderung.

In meinem Code werden jedoch sowohl signierte als auch nicht signierte Skripts ausgeführt, auch wenn set-executionpolicy auf restricted gesetzt ist.

Ich habe zwei Ansätze versucht:

RunspaceConfiguration runspaceConfiguration = 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(); 

Und ein anderer Ansatz:

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 beiden Situationen ist der Code als auch unsignierte Skripte ausgeführt wird.

Habe ich etwas verpasst?

+0

Ist der Server ein 64-Bit-O. S.? –

+0

Ja ist es, @ C.B. Es ist ein 64-Bit Windows Server 2008R2 –

Antwort

1

Ich fand die Lösung. Der einzige Weg, den Code aus laufenden unsigned Skripte zu beschränken war die Skripte selbst mit Get-AuthenticodSignature zu überprüfen:

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; 
    } 

Danke,

Dan