TLS Callback

Most debuggers start at the program entry point as defined by the PE header. A TLS callback can be used to execute code before the entry point and therefore run secretly in a debugger.

This technique can be used to detect that the process is being debugged and thus terminate the process instead to continue execution.

Code Snippets

#include "windows.h"
#include <stdio.h>

void NTAPI __stdcall TLSCallbacks(PVOID DllHandle, DWORD dwReason, PVOID Reserved);

#ifdef _M_IX86
#pragma comment (linker, "/INCLUDE:__tls_used")
#pragma comment (linker, "/INCLUDE:__tls_callback")
#else
#pragma comment (linker, "/INCLUDE:_tls_used")
#pragma comment (linker, "/INCLUDE:_tls_callback")
#endif
EXTERN_C
#ifdef _M_X64
#pragma const_seg (".CRT$XLB")
const
#else
#pragma data_seg (".CRT$XLB")
#endif

PIMAGE_TLS_CALLBACK _tls_callback = TLSCallbacks;
#pragma data_seg ()
#pragma const_seg ()

void NTAPI __stdcall TLSCallbacks(PVOID DllHandle, DWORD dwReason, PVOID Reserved)
{
	MessageBox(nullptr, "TLS Callback", "", 0);
	ExitProcess(0);
}

int main(int argc, char* argv[])
{
	printf("Main function!");
}

YARA Rules

rule detect_tlscallback {
    meta:
        description = "Simple rule to detect tls callback as anti-debug."
        author = "Thomas Roccia | @fr0gger_"
    strings:
        $str1 = "TLS_CALLBACK" nocase
        $str2 = "TLScallback" nocase
    condition:
        uint32(uint32(0x3C)) == 0x4550 and any of them
}

Additional Resources

Subscribe to our Newsletter and don't miss important updates