Tuesday, 26 November 2013

Code Injection through dynamic library



Inspired by Oni Mod Anniversary Edition I started playing with code injection. My usual target is my favorite game Commandos Beyond the Call of Duty. I've bought original box version long time ago. My first goal was ability to reuse existing binary executable. It's easier to modify if you can see immediate result. I've start with few failed attempts of using game executable as dll library. I was able to load exe file as library using LoadLibrary Win32 Api call, but load address was always random, without proper reloc segment in exe file it's not possible to use any code from that binary directly, and reconstructing entire reloc segments seemed as impossible task. So I've change my approach. Instead of using binary as dll I decided to create my shared library and inject custom code into starting process. There is an easy way to do that on Windows. One have to create dll library with the same name as one used   by executable. In my case coman_mp.exe uses ddraw.dll. Created library have to provide list of exported functions. Fortunately game binary (coman_mp.exe) uses only one functions from ddraw.dll (DirectDrawCreate).
This approach is based on assumption that game binary will be loaded and fully initialized before any of dynamic libraries required by this binary. During the loading and dynamic linking stage system loader will look for required dynamic libraries in current working directory. So it's enough to create dll that provides DirectDrawCreate function and dummy IDirectDraw interface implementation and store it in the same directory where game binary is.
Code sample presents dynamic library source.
 
#include <windows.h>

struct LPDIRECTDRAW;
struct IUnknown;

HRESULT WINAPI DirectDrawCreate(GUID FAR *lpGUID, LPDIRECTDRAW FAR *lplpDD, IUnknown FAR *pUnkOuter)
{
 return 1;
}

BOOL APIENTRY DllMain(HANDLE hModule, DWORD reason, LPVOID lpReserved)
{
    switch (reason) {
    case DLL_PROCESS_ATTACH:
  // At this point game binary is loaded and initialized
  // we can start patching
        break;
    case DLL_THREAD_DETACH:  
        break;
    }
    return true;
}

End of part one.
This was just very simple introduction to story about my work with Commandos BTCOD game binary.


No comments: