Pages

Saturday, August 25, 2012

Reverse Engineering Powershell cmdlets


Powershell is a commandline interface into the .net framework for Windows. So the majority of reversing powershell is just getting an understanding on how to access the .net code base and decompiling it into readable format. When I started looking up on how to do this most of the posts where not on how to reverse powershell but how to make powershell run in c#. This post is going to explain how to take a powershell cmdlet and get back to the .net code.

This is extremely simple, so simple I was surprised that there where no posts about this. Basically you need to know 2 commands in powershell and use a .net decompiler.
Trace-command
Get-Command
.net reflector

Get-Command will show the dll that holds the cmdlet
 PS C:\> Get-Command Get-Process | fl DLL  
 C:\Windows\assembly\GAC_MSIL\Microsoft.PowerShell.Commands.Management\1.0.0.0__31bf3856ad364e35\Microsoft.PowerShell.Commands.Management.dll  

Trace-Command will show the method call used in the dll
 PS C:\> Trace-Command -name cmdlet,ETS -PSHost -Option executionflow -Command Get-Process notepad  
 DEBUG: Cmdlet Information: 0 : Constructor Enter Ctor Microsoft.PowerShell.Commands.GetProcessCommand: 37470457  
 DEBUG: Cmdlet Information: 0 : Constructor Leave Ctor Microsoft.PowerShell.Commands.GetProcessCommand: 37470457  
 DEBUG: ETS Information: 0 : Method   Enter PSObject..ctor():object = Microsoft.PowerShell.Commands.GetProcessCommand  
 DEBUG: ETS Information: 0 : Method   Leave PSObject..ctor()  
 DEBUG: ETS Information: 0 : Method   Enter PSObject..ctor():object = System.Diagnostics.Process (notepad)  
 DEBUG: ETS Information: 0 : Method   Leave PSObject..ctor()  
 Handles NPM(K)  PM(K)   WS(K) VM(M)  CPU(s)   Id  ProcessName  
 ------- ------  -----   ----- -----  ------   --  -----------  
    62    8      3136    7548  76     7.61     784 notepad  

As you can see above the cmdlet called is Microsoft.PowerShell.Commands.GetProcessCommand . All we need to do now is open .net reflector, attach to the dll, and go to that method call to see the source code.





Here is a good link to learn how to write (and read) cmdlets and allow you to reverse the cmdlet.
http://www.codeproject.com/Articles/32999/How-to-Write-a-Custom-PowerShell-Cmdlet-Part-I

1 comment:

  1. Quick, clear and concise! Thanks a million!!! Btw, this is my first time ever posting on an IT page! :D

    ReplyDelete