Friday, April 5, 2013

Shellcode Execution in .NET using MSIL-based JIT Overwrite


Download: Invoke-ShellcodeMSIL

While investigating MSIL opcodes a while back, I uncovered a useful opcode - Cpblk. Cpblk is the MSIL equivalent of a memcpy. After writing a .NET method that utilized Cpblk, I immediately thought of a practical use - overwrite a JITed .NET method with shellcode. That way, I could execute shellcode directly without needing to call any Win32 functions. I wrote Invoke-ShellcodeMSIL as an implementation of my idea.

For those who are unfamiliar with MSIL. MSIL is Microsoft's implementation of the Common Interface Language or in other words, .NET bytecode. Using reflection or an IL assembler (like ilasm), you can craft .NET methods using raw MSIL opcodes. There is a great introduction to MSIL opcode assembly in "Metaprogramming in .NET."

For Invoke-ShellcodeMSIL, I wrote a dummy method that simply XORs an input number 101 times. I chose to use an XOR function because I was confident that it would not be optimized during the JIT process. As a consequence, this dummy method will contain sufficient space for a shellcode buffer.

I then wrote the 'memcpy' method using the following opcodes:

Ldarg_0 - Arg0 is the destination buffer (i.e. the address of the dummy JITed method)
Ldarg_1 - Arg1 is the source buffer (i.e. where my shellcode is allocated in RW memory)
Ldarg_2 - Arg2 is the length of the source buffer
Volatile
Cpblk
Ret

After defining the XOR method using reflection, I executed it twenty times in order to force the method to be JITed. Finally, I called my overwrite method and overwrote the JITed XOR method with my shellcode. Here are the screenshots of the disassembly before (left) and after (right) the overwrite:


When you provide your shellcode to Invoke-ShellcodeMSIL, make sure your shellcode ends in a RET and that the stack is in proper alignment (duh :P) or PowerShell will crash. A shellcode stub us generated at runtime depending upon the bitness PowerShell. All it does is save the non-volatile registers, jump to your shellcode, and return zero to the caller. The rest is up to you. :D

Enjoy!

No comments:

Post a Comment