Created
January 31, 2021 14:52
-
-
Save rasta-mouse/844d3f5040546a20366b7b2e013290c1 to your computer and use it in GitHub Desktop.
Modifying self with dnlib
This file contains 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
C:\>ConsoleApp1.exe | |
dlroW olleH |
This file contains 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 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