Injecting Code with CreateProcess

[Previous] [Next]

If your process is spawning the process into which you want to inject code, things get a little easier. For one, your process (the parent process) can create the new process suspended. This allows you to alter the child process's state without affecting its execution since it hasn't started executing anything yet. But the parent process also gets a handle to the child process's primary thread. Using this handle, you can alter what code the thread executes. You can solve the problem mentioned in the previous section since you can set the thread's instruction pointer to execute the code in the memory-mapped file.

Here is one way for your process to control what code the child process's primary thread executes:

  1. Have your process spawn the child process suspended.
  2. Retrieve the primary thread's starting memory address from the .exe module's file header.
  3. Save the machine instructions at this memory address.
  4. Force some hand-coded machine instructions at this address. The instructions should call LoadLibrary to load a DLL.
  5. Resume the child process's primary thread so that this code executes.
  6. Restore the original instructions back into the starting address.
  7. Let the process continue execution from the starting address as if nothing had happened.

Steps 6 and 7 above are tricky to get right because you have to change the code that you are currently executing. It is possible, however—I've seen it done.

This technique offers a lot of benefits. First, it gets the address space before the application executes. Second, it works on both Windows 98 and Windows 2000. Third, since you're not a debugger, you can easily debug the application with the injected DLL. And finally, this technique works on both console and GUI applications.

Of course, this technique also has some disadvantages. You can inject the DLL only if your code is the parent process. And, of course, this technique is not CPU-independent; you must make modifications for different CPU platforms.



Programming Applications for Microsoft Windows
Programming Applications for Microsoft Windows (Microsoft Programming Series)
ISBN: 1572319968
EAN: 2147483647
Year: 1999
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net