5

我有一个下载脚本然后运行它的 Windows 服务。

我一直在努力让我的 Windows 服务更安全,让它只接受签名的 power-shell 脚本。

我在服务器上运行了 Set-ExecutionPolicy AllSigned 命令,这适用于 windows power shell 命令提示符。

但是,即使 set-executionpolicy 设置为受限,我的代码仍会同时运行已签名和未签名的脚本。

我尝试了两种方法:

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

在这两种情况下,代码也会运行未签名的脚本。

我错过了什么吗?

4

1 回答 1

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

谢谢,

于 2013-04-10T23:19:11.720 回答