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的路径, 然后添加到引用中去:

相关推荐
神仙别闹1 天前
基于QT(C++)实现学本科教务系统(URP系统)
数据库·c++·qt
deng-c-f1 天前
Linux C/C++ 学习日记(49):线程池
c++·学习·线程池
ulias2121 天前
C++ 的容器适配器——从stack/queue看
开发语言·c++
daidaidaiyu1 天前
FFmpeg 关键的结构体
c++·ffmpeg
欧特克_Glodon1 天前
C++医学图像处理经典ITK库用法详解<一>:图像输入输出模块功能
c++·图像处理·itk
一个不知名程序员www1 天前
算法学习入门---priority_queue(C++)
c++·算法
2501_930707781 天前
使用C#代码更改 PowerPoint 幻灯片大小
开发语言·c#·powerpoint
Pafey1 天前
C++的左值引用、右值引用以及转发和完美转发
c++
CoderCodingNo1 天前
【GESP】C++三级真题 luogu-B4414 [GESP202509 三级] 日历制作
开发语言·c++·算法
晨曦夜月1 天前
笔试强训day7
开发语言·c++·算法