2

I have a Windows form program created in c#, which is just a form and a single button. What I want to achieve here execute a hard-coded byte array, using VirtualAlloc and a delegate. This hard coded byte array pertains to the bytes of wrar.exe installer. I just wanted to try if it works. No special reason in choosing winrar installer. So in the button click event, I have this code:

private UInt32 MEM_COMMIT = 0x1000;
private UInt32 PAGE_EXECUTE_READWRITE = 0x40;
private UInt32 MEM_RELEASE = 0x8000;
private delegate void Runner();

[DllImport("kernel32")]
private static extern IntPtr VirtualAlloc(UInt32 lpStartAddr, UInt32 size, UInt32 flAllocationType, UInt32 flProtect);

byte[] body = new byte[1517376] { <actual bytes of the winrar installer EXE>};


private void btnExit_Click(object sender, EventArgs e)
{
        try
        {
            IntPtr buf = VirtualAlloc(0, (UInt32)body.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
            Marshal.Copy(body, 0, (IntPtr)buf, body.Length);
            Runner ptr = (Runner)Marshal.GetDelegateForFunctionPointer(buf, typeof(Runner));
            ptr();
            Application.Exit();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
}

However, when I execute the program and click the button, I am having this error/exception: enter image description here

What am I doing wrong here? It seems it's related to the memory allocation. How do I fix this? Thanks a lot in advance!

jaysonpryde
  • 2,733
  • 11
  • 44
  • 61
  • So you load bytes that represent an exe somewhere in memory and then expect it to run? Why don't you Process.Start that exe? – rene Aug 26 '15 at 12:57
  • An exe file does not have an entry point at byte 0, and even if you passed the appropriate address to GetDelegateForFunctionPointer, there are still many things missing - you haven't resolved any dynamic imports for the executable, and any WinAPI or kernel calls it makes could get very confused with the fact that the "process" doesn't have a proper HModule. What you want to do is possible in principle, but you're a long ways off from doing it and it's probably the wrong solution to whatever your problem is. – user5090812 Aug 26 '15 at 13:01
  • thanks for the feedback! – jaysonpryde Aug 26 '15 at 13:10

1 Answers1

0

The code you wrote is for calling a function stored in memory.

What you stored is not a function but an executable. You need to find the offset of the entry point of the executable. Then call it.

  • And probably do a lot of other things the OS loader does, like allocating memory, fix-up jump addresses .... – rene Aug 26 '15 at 13:06
  • I'm guessing your code is a prototype for something, what's your end goal ? If it's code injection you're doing the other way around. – Poppuff Arthem Aug 26 '15 at 13:16