3
votes

I have to create a wrapper DLL that exports some symbols (functions). Within its resources it contains another encrypted DLL that actually does the job.

Upon the wrapper DLL initialization it decrypts the original one, saves it in a file, and loads into the address space by LoadLibrary. However I'd like to avoid saving this DLL in a file.

I know that this doesn't guarantee a bullet-proof protection, actually one may dump the process virtual memory and see it there. I also know that it's possible to create a file with FILE_FLAG_DELETE_ON_CLOSE attribute, which ensures this file will be deleted as soon as the process terminates. But still I'd like to know if there's an option to load the DLL "not from a file".

So far I thought about the following:

  1. Allocate a virtual memory block with adequate protection (PAGE_EXECUTE_READ or PAGE_EXECUTE_READWRITE). Preferrably at the image preferred base address.
  2. Extract/decrypt the DLL image there.
  3. If the image base address isn't its preferred address - do the relocation "manually". I.e. - analyze the relocation table and patch the image in-place.
  4. Handle the image imports. Load its dependency DLLs and fill symbol addresses.
  5. Invoke its initialization function (DllMain).

That is, I can do the work of the loader. But unfortunately there are some areas where the DLL loaded by the above trick will behave differently, since it's not a properly-loaded DLL from the OS's perspective. This includes the following:

  • The DllMain requires the DLL "module handle", which is just its base address. It may use this handle in calls to various API functions, such as LoadResource. Those calls will probably fail.
  • There will be problems with exception handling. The OS won't see the DLL's SAFESEH section, hence its internal exception handling code won't be invoked (it's a 64-bit DLL, means SAFESEH is mandatory for exception handling).

Here's my question: Is there an API to properly load the DLL into the process address space without the need for it to be in a file? An alternative variant of LoadLibrary that works, say, on a file mapping instead of a file-system file?

Thanks in advance.

1

1 Answers

3
votes

Yes, it is possible to load a DLL which is located in the resources of another image and execute it without needing a file! Take a look at this article, this is exactly what you want. It works, I tried it.