Saturday, December 1, 2012

Hotpatching, episode II

Update 2.12.2012: changed links to red so that they can be seen and modified some text to more meaningful.

After publishing my first hotpatching article, I started to think about concurrency issues with it. Since I'm creating a thread and changing values of global variables, it means possible problems with happens-before issues. These changes must be visible to all threads immediately after the change since pointers to original functions may otherwise point to NULL and may cause access violation to happen. I also started to think about dangers of using DllMain. After reading the article about more complete DLL injection by Drew Benton, I decided to make another version of my DLL injection based on his ideas.

I used the Drew's code as a basis and modified it as needed. It took a while to really get into the code. Meanwhile I was enjoying several access violations caused by my almost-correct "assembly code". Since the "shippable" code is written using x86 opcodes, even assembly language can be considered high-level compared to it. This actually reminded me about Java bytecode engineering. If you want to understand what's going on with the code, this reference may be helpful. And if you found my previous hotpatching article too technical, I don't recommend to proceed with the code.

To me this was a real eye-opener: it's really relatively easy to send whatever code you want to be executed by a given process. Just use a couple of x86 opcodes to break in the process by calling your own function in the DLL. It opens endless possibilities. (Do I ever need them is a different story).

Thread-safe DLL code is here and the code doing actual injection is here. Have fun with them ;-) And by the way, don't ever use CriticalSections the way I did in the DLL. I'm using GNU C++ and thus didn't have structured exception handling possibilities, so I decided to leave out exception handling completely.

No comments:

Post a Comment