4

I'm working on application SFX / Protector in C# and i want the protected assembly to be executed from a byte array instead of writing it to hard disk, in order to be much harder for reverse engineering.

I have a program within a byte array ( which have a valid entry point ) and i want to execute it. I found a similar question on this website on how can i do that, i know this can be done using the code snippet below but can someone please guide me on how can i run a program from a byte array using this ?

technically he below code let me do this :

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace DynamicX86
{
    class Program
    {
        const uint PAGE_EXECUTE_READWRITE = 0x40;
        const uint MEM_COMMIT = 0x1000;

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

        private delegate int IntReturner();

        static void Main(string[] args)
        {
            List<byte> bodyBuilder = new List<byte>();
            bodyBuilder.Add(0xb8);
            bodyBuilder.AddRange(BitConverter.GetBytes(42));
            bodyBuilder.Add(0xc3);
            byte[] body = bodyBuilder.ToArray();
            IntPtr buf = VirtualAlloc(IntPtr.Zero, (uint)body.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
            Marshal.Copy(body, 0, buf, body.Length);

            IntReturner ptr = (IntReturner)Marshal.GetDelegateForFunctionPointer(buf, typeof(IntReturner));
            Console.WriteLine(ptr());
        }
    }
}

How can i implement this answer to run a program from array of bytes. I can't understand exactly what i can do with this code. Please help

This is a link where i found this answer : Is it possible to execute an x86 assembly sequence from within C#?

Anyhelp would be highly appreciated.

Community
  • 1
  • 1
Rafik Bari
  • 4,867
  • 18
  • 73
  • 123
  • This code obviously is entirely useless to run *real* programs. You'll need to learn about the PE32 file format and implement your own loader that does the same job as the Windows loader. That's *very* difficult to do if the code has any dependencies. If it is actually a managed assembly then just use Assembly.Load(byte[]). – Hans Passant May 01 '12 at 03:36

1 Answers1

3

What is the valid entry point and what is it's signature? How do you get these bytes from? Do you generate IL? If you do, perhaps it might be easier to simply do this.

What the code above is trying to do is allocate unmanaged memory, fill it with x86 instructions and then have .NET create a delegate from this "function pointer" and execute it - which is different from what you want.

Ani
  • 10,826
  • 3
  • 27
  • 46