There’s just one more detail to cover before hooking application memory. As mentioned earlier, DLL functions are loaded into application memory and used as if they were internal functions. There is nothing resembling the system call table that was used to perform kernel hooking, so inserting a hook into application memory will require a little more preparation. Figure 4-2 shows the trampoline process.
The DLL hook method used in Ghost employs a trampoline function. A trampoline function simply executes one instruction and performs one jump. The one instruction in the trampoline is the first instruction of the hooked function, and the jump is to the second instruction of the hooked function. This eliminates the need for the first instruction of the hooked function, which allows for the placement of a jump into the injected function. This jump can call the injected function to establish a hook.
After replacing the first instruction of the hooked function with a jump to the injected function, the injected function can then call the trampoline to execute the original function. The only things you need to keep track of are the location of the trampoline, the location of the second instruction of the hooked function, and the actual instruction that was yanked into the trampoline function. Because these sizes are known, space can be allocated within injected memory.
The initial version of Ghost also has a method to offset where the jump is placed in the original function. This enables a matching pattern to start after a critical instruction, such as retrieving a global variable. Because ZwMapViewOfSection is used before global variable locations have been localized, a function that has a first instruction to load a global address cannot be copied and used later. To get around this problem, the jump can be inserted further into the original function. If the location of the jump is after the function’s stack adjustment, there will need to be a late stack adjustment so that hooked functions can get to the original stack location.