In Memory Execution Of .NET Assembly
Analyzing a Formbook VBS dropper [1] has been a nice introduction to .NET in memory execution. The technique is used for the simplicity it provides in executing .NET assemblies in memory achieving at the same time defence evasion. The payload itself does not have necessarily be present on the disk.
In the following sections
Creating a .NET Assembly on Windows
The following code snippet is a baseline to create a .NET Assembly.
using System;
namespace TestNamespace
{
public class TestClass
{
public static void testMethod()
{
Console.WriteLine("Hello World");
}
public static void Main(string[] args)
{
// empty
}
}
}
To compile the above into an executable, on a Windows platform do:
csc.exe <filename>
To compile the above into a DLL, on a Windows platform do:
csc.exe /target:library <filename>
Load and Execute the .NET Assembly in Memory
This section provides a PowerShell script taken from the FormBook delivery [1].
In order for the script to successfully execute the provided Assembly, the .NET Assembly has to be in HEX encoded format. CyberChef is
function decoder {
param($encoded)
$inpairs = $encoded -split '(..)' | ? {$_}
foreach ($inbytes in $inpairs)
{
[System.Convert]::ToInt32($inbytes,16)
}
}
[string]$encodedAssembly = '<HEX encoded .NET Assembly>'
[Byte[]]$netinbytes = decoder $encodedAssembly
$e = [System.Appdomain].GetMethod("get_CurrentDomain")
$f = $e.Invoke($null,$null)
$silentload = $f.Load($netinbytes)
[TestNamespace.TestClass]::testMethod()
The above PowerShell script once executed, decodes the provided .NET from hex to binary representation, loads it in memory and executes the method testMethod
and prints the string Hello World
More specifically, once loaded in memory we can “pivot” to the appropriate method with the [TestNamespace.TestClass]::testMethod() which follows the notation [namespace.class]::method()
References
[1] https://stmxcsr.com/micro/vbs-dropper.html
tags: #reversing