Search code examples
c++code-injection

C++ PE injection - EXE file from remote location (e.g. HTTP)


I am a novice security researcher trying to learn about PE injection using droppers/stagers, very much like a cryptolocker would operate.

We are setting up a fire drill for our blue team that handles our QRadar SIEM and we would like to launch some custom malware on it.

So now, for my question :). I understand the general concept op PE injection, but almost all tutorials I have found inject the current EXE (so usually by invoking GetModuleHandle(NULL))

I was wondering how you would go about injecting an EXE from a remote resource (e.g. a HTTP download). Basically my goal is this:

  1. STAGER file downloads EXE in memory
  2. STAGER file inject EXE using PE method in process X

I do not expect a full answer here, but if you could point me in the right direction, that would be great :).

Note that this code will not be used for malicious purposes.

Best regards!


Solution

  • Very simple actually. All you need to do is download the remote EXE/DLL into a buffer, (i.e. from memory), from this point you have a few options.

    You originally need to check for MZ signature, and that it is a valid PE file. You can do this with PIMAGE_NT_HEADERS, checking against Optional.Signature (if valid PE file), and e_magic in PIMAGE_DOS_HEADER (MZ signature)

    Now the question is if you wish to inject a dll, load it from memory, search its export table for a given function, get the code and execute i in remote process, or execute EXE from memory.

    Assuming you just want to get the ImageBase of the image, as you said you read some tutorials online which talked about it via GetModuleHandle, you first need to map the downloaded buffer.

    You can do this via

    CreateFileW (for reading), CreateFileMapping (pass handle from createfile), MapViewOfFile (pass returned handle from createfilemapping).

    After this you will obtain base image address from MapViewOfFile. You can now do many things with the file, you can inject it from memory, or execute it from memory.

    You will need to look into PE fixups (export, and import address table functions), and base relocation via the direct image directory, RVA -> base.

    Take note, if you are executing the image in a remote process after mapping the file, use ZwQueueApcThread injection method instead of the more dull ones like RtlCreateUserThread/CreateRemoteThread.

    If you are executing the code from memory. After fixing the offsets through relocations, make sure to execute the code via VirtualProtectEx, optionally ZwAllocateVirtualMemory (passing PAGE_WRITECOPY instead of PAGE_EXECUTE_READWRITE) instead of ZwWriteVirtualMemory - WriteProcessMemory as it is much stealthier!

    Also, I'm sure you can figure out some other approaches, this is just from the top of my head.