2013-03-25 29 views
5

Tôi có dịch vụ cửa sổ tải xuống tập lệnh và sau đó chạy tập lệnh đó.Chỉ chạy các tập lệnh PowerShell đã được ký từ C#

Tôi đã cố gắng làm cho dịch vụ cửa sổ của mình an toàn hơn, làm cho nó chỉ chấp nhận các tập lệnh có trình bao bọc nguồn đã ký.

Tôi đã chạy lệnh Set-ExecutionPolicy AllSigned trên máy chủ và lệnh này hoạt động trong dấu nhắc lệnh trình bao cửa sổ.

Tuy nhiên, mã của tôi vẫn chạy cả tập lệnh đã ký và chưa ký, ngay cả khi đặt chính sách thực thi được đặt thành bị hạn chế.

Tôi đã thử hai cách tiếp cận:

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(); 

Và cách tiếp cận khác:

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

Trong cả hai tình huống mã chạy script unsigned là tốt.

Tôi đã bỏ lỡ điều gì chưa?

+0

Là máy chủ 64 o.s. chút? –

+0

Vâng, @ C.B. Đó là Windows Server 2008R2 64 bit –

Trả lời

1

Tôi đã tìm thấy giải pháp. Cách duy nhất để hạn chế mã chạy script unsigned là để kiểm tra kịch bản bản thân mình với 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; 
    } 

Cảm ơn,

Dan

Các vấn đề liên quan