0

There are many ways to hook Windows APIs. Inline-hook is one of them. That is, to replace the first 5 bytes of the function with a long jump instruction. There are talks and implementations, to ensure the thread safety of the program, generally they will suspend all the threads while patching. That is, do something like this:

threads = get_threads();
for (thread in threads) {
    suspend(thread);
}

I am very confused, I don't think it's safe. Because threads can be started or stopped on the fly, while you are in the looping, things changed. Isn't it (Q1) ?

Since Windows SP2, Windows APIs are hot-patchable. You can also enable hotpatching on your own image by passing the /hotpatch flag(since VS2008). That is, the compiler ensures that first instruction of a function is at least two bytes. And put 5 or 6 bytes padding before the function. The padding bytes can be replaced with a long jump instruction to redirect to the new version of this function, and the two bytes instruction can be replaced with a short jump instruction to redirect to the long jump instruction before it.

Q2: It seems that I don't needed to suspend all the threads while replacing the first two bytes instruction (Although I don't know how to suspend all the threads at all) of a hot-patchable function, is it ?

Q3: Do I need any atomic operation or memory fence or volatile or something to ensure the replacing is thread-safe ? If so, does compiler ensure the address of each function is aligned ?

Community
  • 1
  • 1
amanjiang
  • 1,213
  • 14
  • 33
  • Research your question first, google "windows hotpatching". The 2nd hit explains why suspending threads doesn't work, the 3rd hit explains how it is implemented. – Hans Passant Dec 10 '15 at 16:39
  • @HansPassant Of course. But there're no answers for my questions. – amanjiang Dec 10 '15 at 17:01
  • DeviareInProc is a very good hooking library (and small ) , you can check the techniques involved there. https://github.com/nektra/Deviare-InProc – Hernán Dec 10 '15 at 19:33
  • @Hernán Thank you, I will do researching on this. I have seen many libraries and I used to write some hooking code, but I am not sure, so I still wanted some exact answers. – amanjiang Dec 11 '15 at 01:37
  • It might be possible to use the fact that no new thread can start when a DllMain function is running. (Provided the API function you're hooking isn't used during thread initialization, that is.) – Harry Johnston Dec 11 '15 at 01:44
  • @HarryJohnston Yes, that is exactly what I do, I am doing injecting. – amanjiang Dec 11 '15 at 02:18
  • If you're inside DllMain and have successfully suspended all the other threads then I *think* hooking an API should be (relatively) safe unless the API in question is used during thread initialization. Any pending threads, including any threads injected from outside, won't be able to start up until you've exited DllMain. – Harry Johnston Dec 11 '15 at 02:58

0 Answers0