我有一个下载脚本然后运行它的Windows服务。
我一直在尝试让我的Windows服务更安全,使其只接受签名的power-shell脚本。
我在服务器上运行了Set-ExecutionPolicy AllSigned命令,这可以在windows power shell命令提示符下运行。
但是,即使set-executionpolicy设置为restricted,我的代码仍会运行有符号和无符号脚本。
我尝试了两种方法:
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();
另一种方法:
using (PowerShell ps = PowerShell.Create())
{
ps.AddCommand("Set-ExecutionPolicy").AddArgument("Restricted");
ps.AddScript("Set-ExecutionPolicy Restricted");
ps.AddScript(script);
Collection<PSObject> results = ps.Invoke();
}
在这两种情况下,代码也会运行未签名的脚本。
我错过了什么吗?
答案 0 :(得分: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;
}
谢谢,
丹