Thursday, June 4, 2015

TLS Injector: running shellcodes through TLS callbacks

I would like to share a python script that lets you inject a shellcode in a binary to be executed through a TLS callback. If you don't know what I'm talking about I recommend you to read this post and this one.

Since I didn't find any script to do this automatically I made a first version to use it in my pentests; I’ve called it tlsInjector. This is not intended to be a serious tool (like the nice backdoor factory) but just an additional script to consider when you need to choose a persistence mechanism. Personally I don’t like leaving my evil binary in places where tools like Autoruns usually sniffs out.

The fact of using a TLS callback instead of the usual injection techniques has some added advantages; for example, you don’t need to modify the entry point to jump/call to the code cave and then redirect the execution flow to the original program. Another key advantage is that a TLS callback runs the code before the entry point is reached. This gives you a lot of scope for doing cool things.

The script has the following options:

Basically, It accepts the dummy binary (-f) and the shellcode to be injected (-s). Since most of the times I use the script to load a evil DLL I have included a payload option to get this easily. You only need to use the -l option and feed it with the DLL path as a parameter.

I took this Loadlibrary payload from Metasploit and tweaked it to avoid it kills the process with the exit-function block of code. I just replaced that code (./src/block/block_exitfunk.asm) with a Ret instruction. Note this if you plan to run Metasploit payloads through a TLS callback. The raw payload (loadlibrary.raw) is included in the same folder as the script.

If the binary doesn’t has TLS info a 32-bytes structure will be prepended to the shellcode. This structure will serve as the TLS Directory. The more important field is AddressOfCallbacks which points to an array of callbacks. In our case, we only need that the first entry of this array points to our shellcode. So the layout of the structure+shellcode is as follows:

Unless you set the -t option, the script starts looking for code caves in executable areas. If it doesn’t find anything it will proceed to the other sections. Let’s see an example with Putty and the Loadlibrary payload. The output info is self-explanatory.

If you specify the -t switch the shellcode will be stored in a new section. To get this I have used the python class SectionDoubleP, so credits to n0p since this has saved me so a lot of work. Here a new example with other binary and the -t option.

After infecting your favorite binary I recommend you to check if It works. There are various reasons why the binary could crash (code signing, NSIS, etc.) I will be adding more payloads as needed.

No comments:

Post a Comment