Author image

Code Injection


Difficulty:
2/5


Code injection is a technique where you insert/inject a piece of code (your custom code) into a target process and then reroute code execution to traverse through your injected code. In a debugger (eg Ollydbg) we search for “code caves” (DB 00 in Ollydbg) i.e. memory regions big enough to store our code. But we can also allocate more memory in the application to store our code as we will do here.

One of the best ways to inject code is via dlls, because they are meant to be loaded by multiple processes at runtime.

Let me just dll you a story Mr. Process…

Minimally, we need:

  1. injector process - DLLInjector project
  2. the process to inject - ProcessToInject project
  3. the dll to inject - dllToInject project

Now the injector will grab the dll and inject it into the process to call custom code.

The discovery of memory addresses of certain API functions, such as LoadLibrary and VirtualAlloc is crucial. Those will be discovered in shared libraries, such as Kernel32.dll or ntddl.dll which are used by almost all windows processes certainly user processes that we will be targeting here. These functions will be used to load the dll into the target process's address space and call its entry point DllMain.

Steps that DLLInjector has to perform:

  1. Get pid of target process. GetWindowThreadProcessId
  2. Get process handle with appropriate permissions. OpenProcess
  3. Allocate memory inside the process to store the dll's code. VirtualAllocEx
  4. Write the dll into that memory. WriteProcessMemory
  5. Create a thread to host and execute the dll's code. CreateRemoteThread
    • Get address of “LoadLibraryA|W” function to use for placing the dll. GetProcAddress
    • calling CreateRemoteThread on target process instructs a newly created thread to execute the dll. This entails a call to LoadLibraryA|W in the target process, with the thread parameter being the memory address you've allocated which points to the dll's newly appointed base address.
  6. WaitForSingleObject until the thread is done executing the dll.
  7. Free the target process's extra memory allocated for the needs of the dll.

Example:

code injection example

For more information about windows libraries & dlls see here.

Github

Github repository link.

Acknowledgements

ollydbg


0 likes