使用win api检测
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <vector>
// 获取当前进程的线程起始地址
void* GetThreadStartAddress(HANDLE hThread) {
typedef NTSTATUS(WINAPI* NtQueryInformationThreadType)(
HANDLE, THREADINFOCLASS, PVOID, ULONG, PULONG);
HMODULE hNtdll = GetModuleHandle(L"ntdll.dll");
if (!hNtdll) return nullptr;
auto NtQueryInformationThread = (NtQueryInformationThreadType)GetProcAddress(hNtdll, "NtQueryInformationThread");
if (!NtQueryInformationThread) {
std::cerr << "Failed to load NtQueryInformationThread.\n";
return nullptr;
}
void* startAddress = nullptr;
NTSTATUS status = NtQueryInformationThread(
hThread,
(THREADINFOCLASS)9, // 使用 9 查询线程起始地址
&startAddress,
sizeof(startAddress),
nullptr
);
if (status != 0) {
std::cerr << "NtQueryInformationThread failed with status: " << std::hex << status << "\n";
return nullptr;
}
return startAddress;
}
// 检查线程是否属于注入线程
bool IsInjectedThread(DWORD threadId, const std::vector<HMODULE>& modules) {
HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION | THREAD_GET_CONTEXT, FALSE, threadId);
if (!hThread) {
std::cerr << "Failed to open thread ID: " << threadId << "\n";
return false;
}
void* startAddress = GetThreadStartAddress(hThread);
CloseHandle(hThread);
if (!startAddress) return false;
// 检查起始地址是否位于合法模块范围内
for (const auto& module : modules) {
MODULEINFO moduleInfo;
if (GetModuleInformation(GetCurrentProcess(), module, &moduleInfo, sizeof(moduleInfo))) {
void* moduleStart = moduleInfo.lpBaseOfDll;
void* moduleEnd = (BYTE*)moduleStart + moduleInfo.SizeOfImage;
if (startAddress >= moduleStart && startAddress < moduleEnd) {
return false; // 在线程合法模块范围内
}
}
}
return true; // 起始地址不在合法模块范围,可能是注入线程
}
int main() {
DWORD currentPid = GetCurrentProcessId();
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD | TH32CS_SNAPMODULE, currentPid);
if (hSnapshot == INVALID_HANDLE_VALUE) {
std::cerr << "Failed to create snapshot.\n";
return -1;
}
// 获取当前进程的模块列表
std::vector<HMODULE> modules;
HMODULE moduleArray[1024];
DWORD cbNeeded;
if (EnumProcessModules(GetCurrentProcess(), moduleArray, sizeof(moduleArray), &cbNeeded)) {
modules.assign(moduleArray, moduleArray + (cbNeeded / sizeof(HMODULE)));
} else {
std::cerr << "Failed to enumerate modules.\n";
CloseHandle(hSnapshot);
return -1;
}
// 遍历线程
THREADENTRY32 te32;
te32.dwSize = sizeof(THREADENTRY32);
if (Thread32First(hSnapshot, &te32)) {
do {
if (te32.th32OwnerProcessID == currentPid) {
if (IsInjectedThread(te32.th32ThreadID, modules)) {
std::cout << "Injected thread detected!\n";
std::cout << "Thread ID: " << te32.th32ThreadID << "\n";
}
}
} while (Thread32Next(hSnapshot, &te32));
} else {
std::cerr << "Failed to enumerate threads.\n";
}
CloseHandle(hSnapshot);
return 0;
}