-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
567 lines (488 loc) · 19.6 KB
/
main.cpp
File metadata and controls
567 lines (488 loc) · 19.6 KB
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include <windows.h>
#include <commctrl.h>
#include <shellapi.h>
#include <winternl.h>
#include <iostream>
#include <string>
#include <map>
#include <thread>
#include <chrono>
#include <psapi.h>
#include <tlhelp32.h>
#include <sstream>
#include <iomanip>
#include <mutex>
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "psapi.lib")
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#define WM_TRAYICON (WM_USER + 1)
#define ID_TRAY_EXIT 1001
#define ID_TRAY_SHOW 1002
#define ID_TRAY_CLEAR 1003
#define ID_LISTVIEW 2001
#define TRAY_ICON_ID 1
#define IDD_TABCONTROL 3000
#define ID_MENU_INVESTIGATE 4001
#define MUTEX_NAME L"Global\\DeviceMonitorMutex_UniqueInstance_2024"
#define WM_SHOW_EXISTING (WM_USER + 100)
void InitTrafficUI(HWND);
void ShutdownTraffic();
void OnTabSelChange();
void ResizeTrafficUI(HWND);
struct DeviceInfo {
std::wstring processName;
DWORD processId;
std::wstring deviceType;
std::wstring timestamp;
std::wstring fullPath;
std::wstring commandLine;
std::wstring parentProcess;
};
HWND g_hWnd = NULL;
HWND g_hListView = NULL;
NOTIFYICONDATAW g_nid = {0};
std::map<std::wstring, DeviceInfo> activeDevices;
std::mutex deviceMutex;
bool g_isRunning = true;
HANDLE g_hMutex = NULL;
std::wstring GetCurrentTimestamp() {
SYSTEMTIME st;
GetLocalTime(&st);
wchar_t buffer[64];
swprintf(buffer, 64, L"%02d:%02d:%02d", st.wHour, st.wMinute, st.wSecond);
return buffer;
}
std::wstring GetProcessCommandLine(DWORD pid) {
std::wstring cmdLine = L"<unavailable>";
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
if (!hProcess) return cmdLine;
// Use NtQueryInformationProcess to get PEB
typedef NTSTATUS (NTAPI *pfnNtQueryInformationProcess)(
HANDLE ProcessHandle,
DWORD ProcessInformationClass,
PVOID ProcessInformation,
DWORD ProcessInformationLength,
PDWORD ReturnLength
);
HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
if (hNtdll) {
pfnNtQueryInformationProcess NtQueryInformationProcess =
(pfnNtQueryInformationProcess)GetProcAddress(hNtdll, "NtQueryInformationProcess");
if (NtQueryInformationProcess) {
struct PROCESS_BASIC_INFORMATION {
PVOID Reserved1;
PVOID PebBaseAddress;
PVOID Reserved2[2];
ULONG_PTR UniqueProcessId;
PVOID Reserved3;
} pbi;
if (NtQueryInformationProcess(hProcess, 0, &pbi, sizeof(pbi), NULL) == 0) {
// Read PEB structure
struct PEB {
BYTE Reserved1[2];
BYTE BeingDebugged;
BYTE Reserved2[1];
PVOID Reserved3[2];
PVOID Ldr;
PVOID ProcessParameters;
} peb;
SIZE_T bytesRead;
if (ReadProcessMemory(hProcess, pbi.PebBaseAddress, &peb, sizeof(peb), &bytesRead)) {
struct RTL_USER_PROCESS_PARAMETERS {
BYTE Reserved1[16];
PVOID Reserved2[10];
UNICODE_STRING ImagePathName;
UNICODE_STRING CommandLine;
} params;
if (ReadProcessMemory(hProcess, peb.ProcessParameters, ¶ms, sizeof(params), &bytesRead)) {
wchar_t* buffer = new wchar_t[params.CommandLine.Length / 2 + 1];
if (ReadProcessMemory(hProcess, params.CommandLine.Buffer, buffer, params.CommandLine.Length, &bytesRead)) {
buffer[params.CommandLine.Length / 2] = L'\0';
cmdLine = buffer;
}
delete[] buffer;
}
}
}
}
}
CloseHandle(hProcess);
return cmdLine;
}
std::wstring GetParentProcessName(DWORD pid) {
std::wstring parentName = L"<unknown>";
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) return parentName;
PROCESSENTRY32W pe32;
pe32.dwSize = sizeof(PROCESSENTRY32W);
DWORD parentPid = 0;
if (Process32FirstW(hSnapshot, &pe32)) {
do {
if (pe32.th32ProcessID == pid) {
parentPid = pe32.th32ParentProcessID;
break;
}
} while (Process32NextW(hSnapshot, &pe32));
}
if (parentPid > 0) {
pe32.dwSize = sizeof(PROCESSENTRY32W);
if (Process32FirstW(hSnapshot, &pe32)) {
do {
if (pe32.th32ProcessID == parentPid) {
parentName = pe32.szExeFile;
parentName += L" (PID: " + std::to_wstring(parentPid) + L")";
break;
}
} while (Process32NextW(hSnapshot, &pe32));
}
}
CloseHandle(hSnapshot);
return parentName;
}
void ShowProcessDetails(DWORD pid) {
DeviceInfo* info = nullptr;
{
std::lock_guard<std::mutex> lock(deviceMutex);
for (auto& pair : activeDevices) {
if (pair.second.processId == pid) {
info = &pair.second;
break;
}
}
}
std::wstring details;
details += L"═══════════════════════════════════════════════\n";
details += L"PROCESS INVESTIGATION REPORT\n";
details += L"═══════════════════════════════════════════════\n\n";
if (info) {
details += L"Process Name: " + info->processName + L"\n";
details += L"Process ID: " + std::to_wstring(info->processId) + L"\n";
details += L"Full Path: " + info->fullPath + L"\n\n";
details += L"Parent Process: " + info->parentProcess + L"\n\n";
details += L"Command Line:\n";
details += info->commandLine + L"\n\n";
} else {
details += L"Process ID: " + std::to_wstring(pid) + L"\n";
std::wstring cmdLine = GetProcessCommandLine(pid);
std::wstring parent = GetParentProcessName(pid);
details += L"Parent Process: " + parent + L"\n\n";
details += L"Command Line:\n" + cmdLine + L"\n\n";
}
// Get loaded modules
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
if (hProcess) {
details += L"Loaded Modules (DLLs):\n";
details += L"───────────────────────────────────────────\n";
HMODULE hMods[1024];
DWORD cbNeeded;
if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
int count = 0;
for (unsigned int i = 0; i < (cbNeeded / sizeof(HMODULE)) && count < 20; i++) {
wchar_t szModName[MAX_PATH];
if (GetModuleFileNameExW(hProcess, hMods[i], szModName, sizeof(szModName) / sizeof(wchar_t))) {
details += L" • " + std::wstring(szModName) + L"\n";
count++;
}
}
if (cbNeeded / sizeof(HMODULE) > 20) {
details += L" ... and " + std::to_wstring(cbNeeded / sizeof(HMODULE) - 20) + L" more modules\n";
}
}
CloseHandle(hProcess);
}
details += L"\n═══════════════════════════════════════════════\n";
details += L"TIP: Check command line and parent process\n";
details += L"to identify suspicious behavior or masquerading.\n";
details += L"═══════════════════════════════════════════════\n";
MessageBoxW(g_hWnd, details.c_str(), L"Process Investigation", MB_OK | MB_ICONINFORMATION);
}
void AddToListView(const DeviceInfo& info) {
std::lock_guard<std::mutex> lock(deviceMutex);
int itemCount = ListView_GetItemCount(g_hListView);
LVITEMW lvi = {0};
lvi.mask = LVIF_TEXT | LVIF_PARAM;
lvi.iItem = itemCount;
lvi.iSubItem = 0;
lvi.lParam = (LPARAM)info.processId;
lvi.pszText = const_cast<LPWSTR>(info.timestamp.c_str());
ListView_InsertItem(g_hListView, &lvi);
ListView_SetItemText(g_hListView, itemCount, 1, const_cast<LPWSTR>(info.deviceType.c_str()));
ListView_SetItemText(g_hListView, itemCount, 2, const_cast<LPWSTR>(info.processName.c_str()));
std::wstring pidStr = std::to_wstring(info.processId);
ListView_SetItemText(g_hListView, itemCount, 3, const_cast<LPWSTR>(pidStr.c_str()));
ListView_EnsureVisible(g_hListView, itemCount, FALSE);
}
void ShowTrayNotification(const std::wstring& title, const std::wstring& message) {
NOTIFYICONDATAW nid = {0};
nid.cbSize = sizeof(NOTIFYICONDATAW);
nid.hWnd = g_hWnd;
nid.uID = TRAY_ICON_ID;
nid.uFlags = NIF_INFO;
nid.dwInfoFlags = NIIF_WARNING;
wcscpy_s(nid.szInfoTitle, title.c_str());
wcscpy_s(nid.szInfo, message.c_str());
Shell_NotifyIconW(NIM_MODIFY, &nid);
}
void CheckProcessHandles(const std::wstring& deviceType) {
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) {
return;
}
PROCESSENTRY32W pe32;
pe32.dwSize = sizeof(PROCESSENTRY32W);
if (Process32FirstW(hSnapshot, &pe32)) {
do {
if (pe32.th32ProcessID == GetCurrentProcessId()) {
continue;
}
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe32.th32ProcessID);
if (hProcess) {
wchar_t processPath[MAX_PATH];
if (GetModuleFileNameExW(hProcess, NULL, processPath, MAX_PATH)) {
std::wstring pathLower = processPath;
for (auto& c : pathLower) c = towlower(c);
bool suspiciousProcess = false;
if (deviceType == L"Camera") {
suspiciousProcess = (pathLower.find(L"camera") != std::wstring::npos ||
pathLower.find(L"video") != std::wstring::npos ||
pathLower.find(L"capture") != std::wstring::npos ||
pathLower.find(L"webcam") != std::wstring::npos);
} else if (deviceType == L"Microphone") {
suspiciousProcess = (pathLower.find(L"audio") != std::wstring::npos ||
pathLower.find(L"record") != std::wstring::npos ||
pathLower.find(L"voice") != std::wstring::npos ||
pathLower.find(L"sound") != std::wstring::npos);
}
if (suspiciousProcess) {
std::wstring key = deviceType + L"_" + std::wstring(pe32.szExeFile) +
L"_" + std::to_wstring(pe32.th32ProcessID);
if (activeDevices.find(key) == activeDevices.end()) {
DeviceInfo info;
info.processName = pe32.szExeFile;
info.processId = pe32.th32ProcessID;
info.deviceType = deviceType;
info.timestamp = GetCurrentTimestamp();
info.fullPath = processPath;
info.commandLine = GetProcessCommandLine(pe32.th32ProcessID);
info.parentProcess = GetParentProcessName(pe32.th32ProcessID);
activeDevices[key] = info;
AddToListView(info);
std::wstring msg = L"Process: " + std::wstring(pe32.szExeFile) +
L" (PID: " + std::to_wstring(pe32.th32ProcessID) + L")";
ShowTrayNotification(L"⚠ " + deviceType + L" Access", msg);
}
}
}
CloseHandle(hProcess);
}
} while (Process32NextW(hSnapshot, &pe32));
}
CloseHandle(hSnapshot);
}
void MonitorThread() {
while (g_isRunning) {
CheckProcessHandles(L"Microphone");
CheckProcessHandles(L"Camera");
std::this_thread::sleep_for(std::chrono::seconds(3));
}
}
void ShowTrayMenu(HWND hWnd) {
POINT pt;
GetCursorPos(&pt);
HMENU hMenu = CreatePopupMenu();
AppendMenuW(hMenu, MF_STRING, ID_TRAY_SHOW, L"Show Window");
AppendMenuW(hMenu, MF_STRING, ID_TRAY_CLEAR, L"Clear Log");
AppendMenuW(hMenu, MF_SEPARATOR, 0, NULL);
AppendMenuW(hMenu, MF_STRING, ID_TRAY_EXIT, L"Exit");
SetForegroundWindow(hWnd);
TrackPopupMenu(hMenu, TPM_RIGHTBUTTON, pt.x, pt.y, 0, hWnd, NULL);
DestroyMenu(hMenu);
}
void AddTrayIcon(HWND hWnd) {
g_nid.cbSize = sizeof(NOTIFYICONDATAW);
g_nid.hWnd = hWnd;
g_nid.uID = TRAY_ICON_ID;
g_nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
g_nid.uCallbackMessage = WM_TRAYICON;
g_nid.hIcon = LoadIcon(NULL, IDI_SHIELD);
wcscpy_s(g_nid.szTip, L"Device Monitor - Running");
Shell_NotifyIconW(NIM_ADD, &g_nid);
}
void RemoveTrayIcon() {
Shell_NotifyIconW(NIM_DELETE, &g_nid);
}
void ShowContextMenu(HWND hwnd, POINT pt) {
HMENU hMenu = CreatePopupMenu();
AppendMenuW(hMenu, MF_STRING, ID_MENU_INVESTIGATE, L"Investigate Process...");
int cmd = TrackPopupMenu(hMenu, TPM_RETURNCMD | TPM_RIGHTBUTTON,
pt.x, pt.y, 0, hwnd, NULL);
if (cmd == ID_MENU_INVESTIGATE) {
int selected = ListView_GetNextItem(g_hListView, -1, LVNI_SELECTED);
if (selected != -1) {
LVITEMW lvi = {0};
lvi.mask = LVIF_PARAM;
lvi.iItem = selected;
if (ListView_GetItem(g_hListView, &lvi)) {
DWORD pid = (DWORD)lvi.lParam;
ShowProcessDetails(pid);
}
}
}
DestroyMenu(hMenu);
}
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_CREATE:
InitTrafficUI(hWnd);
AddTrayIcon(hWnd);
break;
case WM_SHOW_EXISTING:
ShowWindow(hWnd, SW_RESTORE);
SetForegroundWindow(hWnd);
SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
MessageBoxW(hWnd,
L"Device Monitor is already running!\n\nThe existing instance has been brought to front.",
L"Already Running",
MB_OK | MB_ICONINFORMATION);
return 0;
case WM_SIZE:
if (wParam == SIZE_MINIMIZED) {
ShowWindow(hWnd, SW_HIDE);
} else if (wParam != SIZE_MINIMIZED) {
ResizeTrafficUI(hWnd);
}
break;
case WM_TRAYICON:
if (lParam == WM_LBUTTONDBLCLK) {
ShowWindow(hWnd, SW_RESTORE);
SetForegroundWindow(hWnd);
} else if (lParam == WM_RBUTTONUP) {
ShowTrayMenu(hWnd);
}
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case ID_TRAY_SHOW:
ShowWindow(hWnd, SW_RESTORE);
SetForegroundWindow(hWnd);
break;
case ID_TRAY_CLEAR:
ListView_DeleteAllItems(g_hListView);
activeDevices.clear();
break;
case ID_TRAY_EXIT:
DestroyWindow(hWnd);
break;
}
break;
case WM_CLOSE:
ShowWindow(hWnd, SW_HIDE);
return 0;
case WM_DESTROY:
g_isRunning = false;
RemoveTrayIcon();
ShutdownTraffic();
if (g_hMutex) {
ReleaseMutex(g_hMutex);
CloseHandle(g_hMutex);
}
PostQuitMessage(0);
break;
case WM_NOTIFY: {
LPNMHDR pnmhdr = (LPNMHDR)lParam;
if (pnmhdr->idFrom == IDD_TABCONTROL && pnmhdr->code == TCN_SELCHANGE) {
OnTabSelChange();
} else if (pnmhdr->idFrom == ID_LISTVIEW) {
if (pnmhdr->code == NM_RCLICK) {
LPNMITEMACTIVATE lpnmitem = (LPNMITEMACTIVATE)lParam;
POINT pt;
GetCursorPos(&pt);
ShowContextMenu(hWnd, pt);
} else if (pnmhdr->code == NM_DBLCLK) {
int selected = ListView_GetNextItem(g_hListView, -1, LVNI_SELECTED);
if (selected != -1) {
LVITEMW lvi = {0};
lvi.mask = LVIF_PARAM;
lvi.iItem = selected;
if (ListView_GetItem(g_hListView, &lvi)) {
DWORD pid = (DWORD)lvi.lParam;
ShowProcessDetails(pid);
}
}
}
}
break;
}
default:
return DefWindowProcW(hWnd, uMsg, wParam, lParam);
}
return 0;
}
HWND FindExistingInstance() {
return FindWindowW(L"DeviceMonitorClass", NULL);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
g_hMutex = CreateMutexW(NULL, TRUE, MUTEX_NAME);
if (GetLastError() == ERROR_ALREADY_EXISTS) {
HWND hwndExisting = FindExistingInstance();
if (hwndExisting) {
SendMessageW(hwndExisting, WM_SHOW_EXISTING, 0, 0);
} else {
MessageBoxW(NULL,
L"Device Monitor is already running, but the window couldn't be found.\n\nCheck the system tray.",
L"Already Running",
MB_OK | MB_ICONWARNING);
}
if (g_hMutex) CloseHandle(g_hMutex);
return 0;
}
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_LISTVIEW_CLASSES | ICC_TAB_CLASSES;
InitCommonControlsEx(&icex);
const wchar_t CLASS_NAME[] = L"DeviceMonitorClass";
WNDCLASSW wc = {0};
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.hIcon = LoadIcon(NULL, IDI_SHIELD);
RegisterClassW(&wc);
g_hWnd = CreateWindowExW(
0,
CLASS_NAME,
L"Device Access Monitor",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 800, 500,
NULL,
NULL,
hInstance,
NULL
);
if (g_hWnd == NULL) {
if (g_hMutex) {
ReleaseMutex(g_hMutex);
CloseHandle(g_hMutex);
}
return 0;
}
ShowWindow(g_hWnd, nCmdShow);
UpdateWindow(g_hWnd);
std::thread monitorThread(MonitorThread);
monitorThread.detach();
MSG msg = {0};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
g_isRunning = false;
return 0;
}