Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rasta-mouse
Created January 31, 2021 14:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rasta-mouse/844d3f5040546a20366b7b2e013290c1 to your computer and use it in GitHub Desktop.
Save rasta-mouse/844d3f5040546a20366b7b2e013290c1 to your computer and use it in GitHub Desktop.
Modifying self with dnlib
C:\>ConsoleApp1.exe
dlroW olleH
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Load ourself
var module = ModuleDefMD.Load(typeof(Program).Module);
// Get method definition of PrintStuff()
var method = module.Types
.FirstOrDefault(t => t.Name == "Program")
.Methods
.FirstOrDefault(m => m.Name == "PrintStuff");
// Overwrite the "Hello World" string
method.Body.Instructions.FirstOrDefault(i => i.OpCode == OpCodes.Ldstr).Operand = "dlroW olleH";
byte[] newAssembly;
// Output modified assembly to byte[]
using (var ms = new MemoryStream())
{
module.Write(ms);
newAssembly = ms.ToArray();
}
// Load new byte[]
var asm = Assembly.Load(newAssembly);
// Invoke the now modified PrintStuff method
asm.GetType("ConsoleApp1.Program").InvokeMember("PrintStuff", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static, null, null, null);
}
static void PrintStuff()
{
Console.WriteLine("Hello World");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment