Unmanaged PowerShell

简介

在渗透测试当中经常会使用到PowerShell来执行脚本, 但是直接使用PowerShell.exe是一个非常敏感的行为, EDR等产品对PowerShell.exe进程的创建监控的很密切, 并且随着PowerShell的渗透测试工具的普及, 越来越多的EDR会利用微软提供的AMSI接口对PS脚本进行扫描, 但是对于低版本的PowerShell并没有引入AMSI;

如果我们可以自己实现一个PowerShell, 而不是去调用系统的PowerShell.exe来执行PS脚本, 就会使得我们的行为更加的隐蔽, 甚至我们可以将自实现的PowerShell模块注入到一个第三方进程中去(例如svchost.exe), 可能会使行为更加隐蔽;

通过C#实现PS调用

Powershell实际上是属于C#的子集(System.Management.Automation), 所以实际上我们在C#中调用Powershell就是调用 System.Management.Automation对象:

cpp 复制代码
using System;
using System.Reflection;
using System.Text;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;

namespace Test
{
    class Program
    {
        public static void Main(string[] args)
        {
            InvokePS("PS> ");
        }

        public static int InvokePS(string ps)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            while (true)
            {
                try
                {
                    Console.Write(ps);
                    string cmd = Console.ReadLine();
                    if (cmd.Contains("exit"))
                    {
                        break;
                    }
                    Pipeline pipeline = runspace.CreatePipeline();
                    pipeline.Commands.AddScript(cmd);
                    pipeline.Commands.Add("Out-String");
                    Collection<PSObject> results = pipeline.Invoke();
                    StringBuilder stringBuilder = new StringBuilder();
                    foreach (PSObject obj in results)
                    {
                        foreach (string line in obj.ToString().Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None))
                        {
                            stringBuilder.AppendLine(line.TrimEnd());
                        }
                    }
                    Console.Write(stringBuilder.ToString());
                }
                catch (Exception e)
                {
                    string errorText = e.Message + "\n";
                    Console.Write(errorText);
                }
            }
            return 0;
        }
    }
}

需要注意的是在引用System.Management.Automation时, 需要手动找System.Management.Automation.dll的路径, 然后添加到引用中去:

相关推荐
曼巴UE51 小时前
UE5.3 C++ TArray系列(一)
开发语言·c++·ue5
阿巴~阿巴~2 小时前
多源 BFS 算法详解:从原理到实现,高效解决多源最短路问题
开发语言·数据结构·c++·算法·宽度优先
CoderCodingNo2 小时前
【GESP】C++二级真题 luogu-b3924, [GESP202312 二级] 小杨的H字矩阵
java·c++·矩阵
pchmi3 小时前
CNN常用卷积核
深度学习·神经网络·机器学习·cnn·c#
刃神太酷啦3 小时前
堆和priority_queue
数据结构·c++·蓝桥杯c++组
Heris993 小时前
2.22 c++练习【operator运算符重载、封装消息队列、封装信号灯集】
开发语言·c++
----云烟----3 小时前
C/C++ 中 volatile 关键字详解
c语言·开发语言·c++
yuanpan4 小时前
23种设计模式之《组合模式(Composite)》在c#中的应用及理解
开发语言·设计模式·c#·组合模式
ChoSeitaku4 小时前
12.重复内容去重|添加日志|部署服务到Linux上(C++)
linux·c++·windows
挣扎与觉醒中的技术人5 小时前
网络安全入门持续学习与进阶路径(一)
网络·c++·学习·程序人生·安全·web安全