1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
|
#include <windows.h> #include <evntrace.h> #include <tdh.h> #include <iostream> #include <vector> #include <memory>
#pragma comment(lib, "tdh.lib") #pragma comment(lib, "advapi32.lib")
static const GUID SystemTraceControlGuid = { 0x9e814aad, 0x3204, 0x11d2, { 0x9a, 0x82, 0x00, 0x60, 0x08, 0xa8, 0x69, 0x39 } };
struct MonitorContext { TRACEHANDLE sessionHandle; TRACEHANDLE traceHandle; DWORD targetPid; EVENT_TRACE_PROPERTIES* properties; std::unique_ptr<BYTE[]> propertyBuffer; };
static MonitorContext g_Context = {};
void StopMonitorSession();
BOOL WINAPI ConsoleCtrlHandler(DWORD ctrlType) { switch (ctrlType) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: case CTRL_CLOSE_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: std::cout << "\n[提示] 收到退出信号,正在停止监听..." << std::endl; StopMonitorSession(); return TRUE; default: return FALSE; } }
template<typename T> bool GetEventProperty(PEVENT_RECORD eventRecord, LPCWSTR propertyName, T& value) { PROPERTY_DATA_DESCRIPTOR property = {}; property.PropertyName = reinterpret_cast<ULONGLONG>(propertyName); property.ArrayIndex = ULONG_MAX;
ULONG size = 0; if (TdhGetPropertySize(eventRecord, 0, nullptr, 1, &property, &size) != ERROR_SUCCESS) { return false; }
std::vector<BYTE> buffer(size); if (TdhGetProperty(eventRecord, 0, nullptr, 1, &property, size, buffer.data()) != ERROR_SUCCESS) { return false; }
value = *reinterpret_cast<T*>(buffer.data()); return true; }
void ThreadEventCallback(PEVENT_RECORD eventRecord) { if (!eventRecord) return;
if (eventRecord->EventHeader.EventDescriptor.Opcode != EVENT_TRACE_TYPE_START) { return; }
DWORD creatorPid = eventRecord->EventHeader.ProcessId; DWORD targetPid = 0; DWORD threadId = 0; ULONGLONG startAddr = 0;
if (!GetEventProperty(eventRecord, L"ProcessId", targetPid)) { GetEventProperty(eventRecord, L"TargetProcessId", targetPid); }
if (creatorPid == 0 || targetPid == 0 || creatorPid == targetPid) { return; }
if (creatorPid == 4) { return; }
if (g_Context.targetPid != 0 && targetPid != g_Context.targetPid) { return; }
if (!GetEventProperty(eventRecord, L"ThreadId", threadId)) { GetEventProperty(eventRecord, L"NewThreadId", threadId); }
if (!GetEventProperty(eventRecord, L"StartAddress", startAddr)) { GetEventProperty(eventRecord, L"Win32StartAddr", startAddr); }
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_INTENSITY); std::cout << "\n[!] 检测到远程线程创建" << std::endl; SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
std::cout << " 发起进程 PID: " << creatorPid << std::endl; std::cout << " 目标进程 PID: " << targetPid << std::endl; std::cout << " 线程 ID: " << threadId << std::endl; std::cout << " 起始地址: 0x" << std::hex << startAddr << std::dec << std::endl; std::cout << "========================" << std::endl; }
bool StartMonitorSession(DWORD targetPid) { g_Context.targetPid = targetPid;
std::wstring sessionName = KERNEL_LOGGER_NAME; size_t bufferSize = sizeof(EVENT_TRACE_PROPERTIES) + (sessionName.size() + 1) * sizeof(wchar_t); g_Context.propertyBuffer = std::make_unique<BYTE[]>(bufferSize);
auto ResetProperties = [&]() { ZeroMemory(g_Context.propertyBuffer.get(), bufferSize); g_Context.properties = reinterpret_cast<EVENT_TRACE_PROPERTIES*>(g_Context.propertyBuffer.get()); g_Context.properties->Wnode.BufferSize = static_cast<ULONG>(bufferSize); g_Context.properties->Wnode.Flags = WNODE_FLAG_TRACED_GUID; g_Context.properties->Wnode.Guid = SystemTraceControlGuid; g_Context.properties->Wnode.ClientContext = 1; g_Context.properties->LogFileMode = EVENT_TRACE_REAL_TIME_MODE; g_Context.properties->EnableFlags = EVENT_TRACE_FLAG_THREAD; g_Context.properties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES); LPWSTR loggerName = reinterpret_cast<LPWSTR>(g_Context.propertyBuffer.get() + sizeof(EVENT_TRACE_PROPERTIES)); wcscpy_s(loggerName, sessionName.size() + 1, sessionName.c_str()); };
ResetProperties();
ULONG stopStatus = StopTrace(0, sessionName.c_str(), g_Context.properties); if (stopStatus == ERROR_SUCCESS) { std::cout << "[提示] 清理了残留的 ETW 会话,等待资源释放..." << std::endl; Sleep(500); } else if (stopStatus != ERROR_WMI_INSTANCE_NOT_FOUND) { std::cout << "[提示] StopTrace 返回: " << stopStatus << std::endl; }
ResetProperties();
ULONG status = ERROR_ALREADY_EXISTS; for (int retry = 0; retry < 3 && status == ERROR_ALREADY_EXISTS; retry++) { if (retry > 0) { std::cout << "[提示] 会话仍在释放中,等待后重试 (" << retry << "/3)..." << std::endl; Sleep(500); } status = StartTrace(&g_Context.sessionHandle, sessionName.c_str(), g_Context.properties); }
if (status != ERROR_SUCCESS) { std::cout << "StartTrace 失败,错误码: " << status << std::endl; if (status == ERROR_ALREADY_EXISTS) { std::cout << "[建议] 会话仍被占用,请稍后再试或重启系统" << std::endl; } return false; }
EVENT_TRACE_LOGFILEW logFile = {}; logFile.LoggerName = const_cast<LPWSTR>(sessionName.c_str()); logFile.ProcessTraceMode = PROCESS_TRACE_MODE_EVENT_RECORD | PROCESS_TRACE_MODE_REAL_TIME; logFile.EventRecordCallback = ThreadEventCallback;
g_Context.traceHandle = OpenTrace(&logFile); if (g_Context.traceHandle == reinterpret_cast<TRACEHANDLE>(INVALID_HANDLE_VALUE)) { std::cout << "OpenTrace 失败" << std::endl; StopTrace(g_Context.sessionHandle, sessionName.c_str(), g_Context.properties); return false; }
return true; }
void StopMonitorSession() { if (g_Context.traceHandle != 0) { CloseTrace(g_Context.traceHandle); g_Context.traceHandle = 0; } if (g_Context.sessionHandle != 0) { EVENT_TRACE_PROPERTIES stopProps = {}; stopProps.Wnode.BufferSize = sizeof(stopProps); StopTrace(g_Context.sessionHandle, KERNEL_LOGGER_NAME, &stopProps); g_Context.sessionHandle = 0; } g_Context.propertyBuffer.reset(); g_Context.properties = nullptr; g_Context.targetPid = 0; }
int main() { std::cout << "=== 远程线程创建行为检测 ===" << std::endl; std::cout << "当前进程 PID: " << GetCurrentProcessId() << std::endl; std::cout << std::endl;
std::cout << "请输入需要监控的目标进程 PID (0 表示所有进程): "; DWORD targetPid = 0; std::cin >> targetPid;
SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
if (!StartMonitorSession(targetPid)) { std::cout << "初始化 ETW 监听失败(需要管理员权限)" << std::endl; system("pause"); return 1; }
std::cout << "开始监听..." << std::endl;
ProcessTrace(&g_Context.traceHandle, 1, nullptr, nullptr);
StopMonitorSession();
std::cout << "监听结束" << std::endl; system("pause"); return 0; }
|