Rewriting string in .NET CLR heaps using dnlib

3.1k Views Asked by At

I need to rewrite strings in #US heap in .NET file. I decided to use dnlib that looks like a powerful library to manipulate .NET files. It is underdocumented unfortunately.

I load the file the usual way. The ModuleDefMD Load() methods seem to be the only way to load the file:

ModuleDefMD module = ModuleDefMD.Load("test.dll");

Now, the dnlib has Writer namespace that suggests it should be used to write to the .NET structures. It contains USHeap class that looks promising.

It seems the Writer needs to create metadata that it can work on:

dnlib.DotNet.Writer.MetaData metadata = dnlib.DotNet.Writer.MetaData.Create(module, null, null, null);

In the USHeap class there is SetRawData() method with description "Overrides what value should be written to the heap". The rest is unclear, let's use it anyway to write 3 raw arbitrary bytes. According to the CLI standard, the first valid offset is 1:

byte[] raw_data = { 0x61, 0x62, 0x63 };   // "abc"
uint offset = 1;   // the least valid offset in #US heap
metadata.USHeap.SetRawData(offset, raw_data);

dnlib Examples show how to write the file:

module.Write("test-out.dll");

This code compiles and runs without errors. Unfortunately the new file has the same #US stream contents as the original.

It seems I didn't get the idea how the Writer works. Studying the sources is not easy as dnlib consists of quite a lot source files and lines.

The dnlib documentation refers to ConfuserEx - obfuscator that uses dnlib to manipulate files. However, looking at its sources, it seems that it doesn't manipulate the #US heap at all.

1

There are 1 best solutions below

1
On BEST ANSWER

Before calling module.Write(), initialize a writer options class. Set the listener to your writer listener and then pass in the options to Write(). After certain writer events you can then start manipulating the metadata before it gets written to the file. You can then add arbitrary strings to the #US heap or any other heap.

There's an example you can look at: https://github.com/0xd4d/dnlib/blob/master/Examples/Example6.cs