VC++反调试代码,检测程序是否被调试,检测VS和OD
VC++反调试代码,检测程序是否被调试,检测VS和OD#include <iostream>
#include <windows.h>
#include <winternl.h>
#pragma region 依赖
typedef NTSTATUS(NTAPI* pfnNtQueryInformationProcess)(
_In_ HANDLE ProcessHandle,
_In_ UINT ProcessInformationClass,
_Out_ PVOID ProcessInformation,
_In_ ULONG ProcessInformationLength,
_Out_opt_ PULONG ReturnLength
);
#pragma endregion
#include <Windows.h>
#include <stdio.h>
// linker spec 通知链接器PE文件要创建TLS目录
#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
//此方法测试针对od有效
int checkdebug() {
pfnNtQueryInformationProcess NtQueryInformationProcess = NULL; // 存放 ntdll 中 NtQueryInformationProcess 函数地址
NTSTATUS status; // NTSTATUS 错误代码,0:执行成功
DWORD isDebuggerPresent = -1; // 如果当前被调试,则 = ffffffff
HMODULE hNtDll = LoadLibrary(TEXT("ntdll.dll")); // ntdll 模块句柄
// ntdll 加载成功
if (hNtDll) {
// 取 NtQueryInformationProcess 函数地址
NtQueryInformationProcess = (pfnNtQueryInformationProcess)GetProcAddress(hNtDll, "NtQueryInformationProcess");
// 取地址成功
if (NtQueryInformationProcess) {
// 1.把 NtQueryInformationProcess() 中的 0x7 改成 0x1F
// 2.把 if(status == 0 && isDebuggerPresent != 0) 判断改为 if(status == 0 && isDebuggerPresent == 0)
// NtQueryInformationProcess 检测调试器
status = NtQueryInformationProcess(
GetCurrentProcess(), // 进程句柄
0x1F, // 要检索的进程信息类型,ProcessDebugPort:调试器端口号 0x7 改成 0x1E
&isDebuggerPresent, // 接收进程信息的缓冲区指针
sizeof(DWORD), // 缓冲区大小
NULL // 实际返回进程信息的大小
);
// NtQueryInformationProcess 执行成功
if (status == 0 && isDebuggerPresent == 0) {
// 输出
/*std::cout << "status = " << status << std::endl;
std::cout << "isDebuggerPresent = " << std::hex << isDebuggerPresent << std::endl;
std::cout << "检测到调试器" << std::endl;*/
ExitProcess(0);
//getchar();
return 1;
}
}
}
// 输出
/*std::cout << "status = " << status << std::endl;
std::cout << "isDebuggerPresent = " << std::hex << isDebuggerPresent << std::endl;
std::cout << "没有发现调试器" << std::endl;*/
//getchar();
return 0;
}
void NTAPI __stdcall TLS_CALLBACK(PVOID DllHandle, DWORD dwReason, PVOID Reserved)
{
if (IsDebuggerPresent())//此方法针对VS有效,对OD无效
{
//MessageBox(NULL, L" 检测到调试器 !", L"Error", MB_ICONSTOP);
ExitProcess(0);
}
if (checkdebug() != 0) {//此方法针对OD有效
//MessageBox(NULL, L" 检测到调试器2 !", L"Error", MB_ICONSTOP);
ExitProcess(0);
}
}
// 创建TLS段
EXTERN_C
#ifdef _M_X64
#pragma const_seg (".CRT$XLB")
PIMAGE_TLS_CALLBACK _tls_callback = TLS_CALLBACK;
#else
#pragma data_seg (".CRT$XLB")
PIMAGE_TLS_CALLBACK _tls_callback = TLS_CALLBACK;
#endif
页:
[1]