code-injectioneasyhook

Windows - How can I inject code in the kernel of a application before it starts?


I want to make a malware analysis software and I have to inject code into different kernel32 functions of the process, like Sleep to overwrite any sleeps the malware attempts to make, ExitProcess to dump the memory before getting the process killed etc

I tried starting the process suspended then I tried enumerating the libraries hoping that I could get the kernel32 rva but It looks like the libraries aren't even loaded when I start the process as suspended.


Solution

  • What you are trying to achieve can be easily done using EasyHook API. The API is available on

    https://github.com/EasyHook/EasyHook

    Below is the sample which overrides CreateFile from Kernel32.dll. You need to CreateAndInject method

    EasyHook.RemoteHooking.CreateAndInject(
                        targetExe,          // executable to run
                        "",                 // command line arguments for target
                        0,                  // additional process creation flags to pass to CreateProcess
                        EasyHook.InjectionOptions.DoNotRequireStrongName, // allow injectionLibrary to be unsigned
                        injectionLibrary,   // 32-bit library to inject (if target is 32-bit)
                        injectionLibrary,   // 64-bit library to inject (if target is 64-bit)
                        out targetPID,      // retrieve the newly created process ID
                        channelName         // the parameters to pass into injected library
                                            // ...
                    );
    

    The key is to send the main thread id of the process to your Hooking DLL and then that DLL should patch and wake up the main thread. Which is done in EasyHook as below

    if((hThread = OpenThread(THREAD_SUSPEND_RESUME, FALSE, ThreadID)) == NULL)
        THROW(STATUS_INTERNAL_ERROR, L"Unable to open wake up thread.");
    
    if(!ResumeThread(hThread))
        THROW(STATUS_INTERNAL_ERROR, L"Unable to resume process main thread.");
    

    Rest the hooking process is the same as is done for any windows process, by opening the process and writing to its memory to send the payload

    PS: If you need detailed example on file monitoring of a sample notepad application then have a look at

    https://easyhook.github.io/tutorials/remotefilemonitor.html

    More tutorials source code available on

    https://github.com/EasyHook/EasyHook-Tutorials