I came across a document called The Ultimate Anti-Reversing Reference, which describes various Anti-Debugging techniques. in point 4.Thread Local Storage There is a mention
Thread Local Storage callbacks are called whenever a thread is created or destroyed (unless the process calls the kernel32 DisableThreadLibraryCalls() or the ntdll LdrDisableThreadCalloutsForDll() functions). That includes the thread that is created by Windows when a debugger attaches to a process. The debugger thread is special, in that its entrypoint does not point inside the image. Instead, it points inside kernel32.dll. Thus, a simple debugger detection method is to use a Thread Local Storage callback to query the start address of each thread that is created. The check can be made using this 32-bit code to examine the 32-bit Windows environment on either the 32-bit or 64-bit versions of Windows:
push eax
mov eax, esp
push 0
push 4
push eax
;ThreadQuerySetWin32StartAddress
push 9
push -2 ;GetCurrentThread()
call NtQueryInformationThread
pop eax
cmp eax, offset l1
jnb being_debugged
...
I wrote the c++ code as below
bool fooBar()
{
uintptr_t dwStartAddress;
TFNNtQueryInformationThread ntQueryInformationThread = (TFNNtQueryInformationThread)GetProcAddress(
GetModuleHandle(TEXT("ntdll.dll")), "NtQueryInformationThread");
if (ntQueryInformationThread != 0) {
NTSTATUS status = ntQueryInformationThread(
(HANDLE)-2,
(_THREADINFOCLASS)9,
&dwStartAddress,
sizeof(dwStartAddress),
nullptr);
cout << hex << "dwStartAddress: 0x" << dwStartAddress << dec << endl;
}
and I'm running this inside the TLS callbacks
EXTERN_C
#ifdef _M_X64
#pragma const_seg (".CRT$XLB")
const
#else
#pragma data_seg (".CRT$XLB")
#endif
PIMAGE_TLS_CALLBACK p_thread_callback = fooBar;
#pragma data_seg ()
#pragma const_seg ()
The value of dwStartAddress points to the .exe module, not to kernel32.dll as stated in the text. Regardless if I just run the exe or run in debugger or attach a debugger to the process (tho I'm not very experienced with attaching so maybe I'm doing something wrong here).
Am I doing something wrong, or the text is wrong / no longer valid?