I have a binary file, with serialized .NET object (stream) in it. I need to compile it back to a .NET Assembly (Maybe using CodeDomProvider Class or anything else).
Any pointer will be highly appreciated.
Thanks in Advance.
I have a binary file, with serialized .NET object (stream) in it. I need to compile it back to a .NET Assembly (Maybe using CodeDomProvider Class or anything else).
Any pointer will be highly appreciated.
Thanks in Advance.
There is no guarantee that it is possible to deserialize a BinaryFormatter
serialized object (BinaryFormatter
is the .NET-included binary serializer... and it is considered to be quite "evil") to the source code that generated it. Simple example:
[Serializable]
public class MyClass
{
public DateTime Foo { get; private set; }
public MyClass()
{
Foo = DateTime.Now;
}
}
There is no way in C# to write a MyClass
object with a specific Foo
value unless you are using reflection. You can't write:
var bar = new MyClass { Foo = new DateTime(2018, 1, 1 }
because there is no setter for Foo
.
Specific cases (where there a no private fields and if there are setters they are all setters that only set the value of the backing field without doing extra elaboration) can be converted to C# assignments.
What it is possible to do (but in general it is a bad idea with BinaryFormatter
, because it doesn't handle very well changes to the underlying types) is include the binary file as an embedded resource (see this) and then read the file:
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "ConsoleApp2.Folder1.File1.bin";
MyClass mc;
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
var bf = new BinaryFormatter();
mc = (MyClass)bf.Deserialize(stream);
}
Note that this is a very very bad idea, because if anything changes in the underlying types (even some private fields), everything will break badly.
I've done it using a tool called ClrGuard. https://github.com/endgameinc/ClrGuard. It will capture the .NET assembly as it tries to execute and dump it in disk. Then we can load with ilspy or any other .NET de-compiler.
ClrGuard will hook into all .NET processes on the system. From there, it performs an in-line hook of the native LoadImage() function. This is what Assembly.Load() calls under the CLR hood.
Reference : https://www.endgame.com/blog/technical-blog/hunting-memory-net-attacks