// AntiDbgWithTLS.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#pragma comment(linker,"/INCLUDE:__tls_used")
BOOL LookupProcess();
BOOL IsBeingDbg();
void WINAPI tls_callback(PVOID h, DWORD dwReason, PVOID pv)
{
if (LookupProcess())
{
MessageBox(NULL, _T("Debugger found!"), NULL, 0);
exit(0);
}
if (IsBeingDbg())
{
MessageBox(NULL, _T("Being debugged!"), NULL, 0);
exit(1);
}
std::cout << "In tls_callback" << std::endl;
}
#pragma data_seg(".CRT$XLB")
PIMAGE_TLS_CALLBACK p_Thread_CallBack = tls_callback;
#pragma data_seg()
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "In main..." << std::endl;
return 0;
}
BOOL LookupProcess()
{
BOOL bRet = FALSE;
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(pe32);
HANDLE hSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE)
{
std::cout << "CreateToolhelp32Snapshot failed" << std::endl;
}
BOOL bMore = ::Process32First(hSnap, &pe32);
while (bMore)
{
_tcslwr_s(pe32.szExeFile,_tcslen(pe32.szExeFile) * sizeof(TCHAR));
if (_tcscmp(pe32.szExeFile,_T("ollydbg.exe")) == 0)
{
bRet = TRUE;
break;
}
if (_tcscmp(pe32.szExeFile, _T("peid.exe")) == 0)
{
bRet = TRUE;
break;
}
if (_tcscmp(pe32.szExeFile, _T("ollyice.exe")) == 0)
{
bRet = TRUE;
break;
}
if (_tcscmp(pe32.szExeFile, _T("windbg.exe")) == 0)
{
bRet = TRUE;
break;
}
if (_tcscmp(pe32.szExeFile, _T("idaq.exe")) == 0)
{
bRet = TRUE;
break;
}
bMore = ::Process32Next(hSnap, &pe32);
}
::CloseHandle(hSnap);
return bRet;
}
BOOL IsBeingDbg()
{
BOOL bRet;
bRet = FALSE;
__asm
{
mov ebx, fs:[0x30]//偏移0x30处为PEB
movzx edx, byte ptr ds:[ebx+0x2]//取PEB中Being debug,若为1则被调试
mov bRet,edx
}
if (IsDebuggerPresent())
{
bRet = TRUE;
}
return bRet;
}