Main Image

What are TLS Callbacks?

Thread Local Storage (TLS) is a Windows operating system mechanism that allows each thread in a process to have its own copy of specific variables. To support this, Windows PE (Portable Executable) executable files contain a TLS directory (IMAGE_TLS_DIRECTORY). This directory not only describes where the TLS data is stored and its size, but also includes a list of callback functions.

TLS callbacks are an execution mechanism that allows code to run automatically when a process or thread starts, even before the program’s normal entry point (main or WinMain for EXEs, or DllMain for DLLs) is reached.

The Problem: Hidden Execution in DLLs

The author performed tests to verify the behavior of TLS callbacks in DLLs. A test DLL was created with two functions:

  1. A TLS callback function.
  2. A standard DllMain function.

When compiling and loading the DLL using rundll32, it was observed that the TLS callback function was executed before the DllMain function.

This behavior is of particular interest for cybersecurity, as attackers can exploit this mechanism to execute malicious code before the main execution of the program or DLL is started, which can evade certain security analysis techniques.

Implications for Security Analysis

The ability to execute code before the primary entry point has important implications for threat detection:

  • Static Analysis: When performing a static analysis of a suspicious binary, it is not sufficient to examine only the DllMain function or the exported functions. Analysts should actively search for TLS callbacks to identify malicious code. PE analysis tools can help list these callbacks.
  • Dynamic Analysis and Debugging: During debugging, it is crucial to configure the debugger to stop at TLS callbacks. If the debugger is not configured this way, malicious code in the callback could be inadvertently executed, allowing the malware to continue its execution undetected during the dynamic analysis phase.

Conclusion

The technique of using TLS callbacks in DLLs represents an evasion vector that security analysts must take into account. It is essential that both static analysis tools and debuggers are configured to inspect and detect code that is executed through this mechanism. Understanding the order of execution of the components of a PE file is essential for modern malware detection.