TLS callbacks Assembly x86-64

05 January 2016

Learn how execute code before the entry point with the TLS callback trick and x86-64 assembly.

Introduction

Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread. Developers use TLS to provide unique data for each thread that the process can access using a global index.

TLS calls are subroutines that are called by the system before the entry point. There is a .tls section in the PE file that describes the place of TLS callbacks.

Some malwares employ TLS callbacks to detect debuggers, notwithstanding, this trick has been used for years and modern analysis tools detect it.

TLS callbacks 64-bit

We developed this assembly code to demonstrate the functioning of TLS callbacks.

Compile the code above with Fasm to obtain a 64-bit Windows executable

We can clearly see the structure of the TLS section.

This program will execute three MessageBox functions in a specific order.

"This is the first tls callback"

"This is the second tls callback"

"Hello World"

As you can see, despite it is the first and only function called after the entry point, the MessageBox with the "Hello World" message will be executed last.

By default most debuggers break at the entry point and consequently the TLS callbacks function are executed.An attacker could insert an anti-debugging routine inside the TLS callback function to mislead an analyst.