Repository navigation
Expand file tree
/
Copy pathNTFSJournalParser.cpp
More file actions
510 lines (412 loc) · 17.5 KB
/
Copy pathNTFSJournalParser.cpp
File metadata and controls
510 lines (412 loc) · 17.5 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
/*******************************************************************************
* NTFSJournalParser - Analyseur de journal USN NTFS
*
* Auteur : Ayi NEDJIMI
* Licence : MIT
* Description : Parse le $UsnJrnl (USN Journal NTFS) pour créer une timeline
* des opérations (création/modification/suppression) et analyser
* les activités disque forensiques.
******************************************************************************/
#define UNICODE
#define _UNICODE
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <commctrl.h>
#include <commdlg.h>
#include <shlwapi.h>
#include <winioctl.h>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <memory>
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "shlwapi.lib")
#pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' "\
"version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
// Contrôles
#define IDC_COMBO_VOLUME 1001
#define IDC_BTN_PARSE 1002
#define IDC_LISTVIEW 1003
#define IDC_BTN_FILTER 1004
#define IDC_BTN_EXPORT 1005
#define IDC_EDIT_LOG 1006
#define IDC_PROGRESS 1007
#define IDC_LABEL_STATUS 1008
#define IDC_CHECK_CREATION 1009
#define IDC_CHECK_MODIF 1010
#define IDC_CHECK_DELETE 1011
#define IDC_EDIT_DATE_START 1012
#define IDC_EDIT_DATE_END 1013
// Structures
struct UsnRecord {
DWORDLONG fileRef;
DWORDLONG parentRef;
DWORDLONG usn;
FILETIME timestamp;
DWORD reason;
std::wstring fileName;
std::wstring sourceInfo;
};
// RAII pour handles
class HandleGuard {
HANDLE h;
public:
explicit HandleGuard(HANDLE handle) : h(handle) {}
~HandleGuard() { if (h && h != INVALID_HANDLE_VALUE) CloseHandle(h); }
HANDLE get() const { return h; }
operator bool() const { return h && h != INVALID_HANDLE_VALUE; }
};
// Globals
HWND g_hMainWnd = nullptr;
HWND g_hListView = nullptr;
HWND g_hLog = nullptr;
HWND g_hProgress = nullptr;
HWND g_hStatus = nullptr;
HWND g_hComboVolume = nullptr;
std::vector<UsnRecord> g_records;
bool g_parsing = false;
// Fonctions utilitaires
void Log(const std::wstring& msg) {
if (!g_hLog) return;
int len = GetWindowTextLengthW(g_hLog);
SendMessageW(g_hLog, EM_SETSEL, len, len);
SendMessageW(g_hLog, EM_REPLACESEL, FALSE, (LPARAM)(msg + L"\r\n").c_str());
}
std::wstring FileTimeToString(const FILETIME& ft) {
SYSTEMTIME st;
if (!FileTimeToSystemTime(&ft, &st)) return L"N/A";
wchar_t buf[64];
swprintf_s(buf, L"%04d-%02d-%02d %02d:%02d:%02d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return buf;
}
std::wstring ReasonToString(DWORD reason) {
std::wstring result;
if (reason & USN_REASON_DATA_OVERWRITE) result += L"Écrasement données, ";
if (reason & USN_REASON_DATA_EXTEND) result += L"Extension données, ";
if (reason & USN_REASON_DATA_TRUNCATION) result += L"Troncature données, ";
if (reason & USN_REASON_FILE_CREATE) result += L"Création fichier, ";
if (reason & USN_REASON_FILE_DELETE) result += L"Suppression fichier, ";
if (reason & USN_REASON_RENAME_OLD_NAME) result += L"Renommage (ancien), ";
if (reason & USN_REASON_RENAME_NEW_NAME) result += L"Renommage (nouveau), ";
if (reason & USN_REASON_SECURITY_CHANGE) result += L"Changement sécurité, ";
if (reason & USN_REASON_EA_CHANGE) result += L"Changement EA, ";
if (reason & USN_REASON_CLOSE) result += L"Fermeture, ";
if (!result.empty()) result.pop_back(); result.pop_back(); // Remove trailing ", "
return result.empty() ? L"Inconnu" : result;
}
void UpdateListView() {
if (!g_hListView) return;
SendMessageW(g_hListView, WM_SETREDRAW, FALSE, 0);
ListView_DeleteAllItems(g_hListView);
int idx = 0;
for (const auto& rec : g_records) {
LVITEMW lvi = {};
lvi.mask = LVIF_TEXT;
lvi.iItem = idx++;
// Timestamp
std::wstring timeStr = FileTimeToString(rec.timestamp);
lvi.pszText = const_cast<LPWSTR>(timeStr.c_str());
ListView_InsertItem(g_hListView, &lvi);
// Fichier
ListView_SetItemText(g_hListView, lvi.iItem, 1, const_cast<LPWSTR>(rec.fileName.c_str()));
// Raison
std::wstring reasonStr = ReasonToString(rec.reason);
ListView_SetItemText(g_hListView, lvi.iItem, 2, const_cast<LPWSTR>(reasonStr.c_str()));
// ParentFRN
wchar_t buf[32];
swprintf_s(buf, L"0x%I64X", rec.parentRef);
ListView_SetItemText(g_hListView, lvi.iItem, 3, buf);
// SourceInfo
ListView_SetItemText(g_hListView, lvi.iItem, 4, const_cast<LPWSTR>(rec.sourceInfo.c_str()));
}
SendMessageW(g_hListView, WM_SETREDRAW, TRUE, 0);
InvalidateRect(g_hListView, nullptr, TRUE);
std::wstring status = L"Entrées affichées : " + std::to_wstring(g_records.size());
SetWindowTextW(g_hStatus, status.c_str());
}
DWORD WINAPI ParseJournalThread(LPVOID param) {
std::wstring volume = *reinterpret_cast<std::wstring*>(param);
delete reinterpret_cast<std::wstring*>(param);
g_records.clear();
Log(L"[INFO] Ouverture du volume : " + volume);
std::wstring volumePath = L"\\\\.\\" + volume;
HANDLE hVolume = CreateFileW(volumePath.c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, 0, nullptr);
if (hVolume == INVALID_HANDLE_VALUE) {
Log(L"[ERREUR] Impossible d'ouvrir le volume (Erreur: " +
std::to_wstring(GetLastError()) + L"). Essayez d'exécuter en administrateur.");
g_parsing = false;
EnableWindow(GetDlgItem(g_hMainWnd, IDC_BTN_PARSE), TRUE);
return 1;
}
HandleGuard hGuard(hVolume);
// Query journal
USN_JOURNAL_DATA journalData = {};
DWORD bytesReturned = 0;
if (!DeviceIoControl(hVolume, FSCTL_QUERY_USN_JOURNAL, nullptr, 0,
&journalData, sizeof(journalData), &bytesReturned, nullptr)) {
Log(L"[ERREUR] FSCTL_QUERY_USN_JOURNAL échoué (Erreur: " +
std::to_wstring(GetLastError()) + L")");
g_parsing = false;
EnableWindow(GetDlgItem(g_hMainWnd, IDC_BTN_PARSE), TRUE);
return 1;
}
Log(L"[INFO] Journal ID: " + std::to_wstring(journalData.UsnJournalID));
Log(L"[INFO] First USN: " + std::to_wstring(journalData.FirstUsn));
Log(L"[INFO] Next USN: " + std::to_wstring(journalData.NextUsn));
// Read journal
const DWORD bufferSize = 64 * 1024;
auto buffer = std::make_unique<BYTE[]>(bufferSize);
READ_USN_JOURNAL_DATA readData = {};
readData.StartUsn = journalData.FirstUsn;
readData.ReasonMask = 0xFFFFFFFF;
readData.ReturnOnlyOnClose = FALSE;
readData.Timeout = 0;
readData.BytesToWaitFor = 0;
readData.UsnJournalID = journalData.UsnJournalID;
DWORD recordCount = 0;
bool continueReading = true;
while (continueReading && g_parsing) {
if (!DeviceIoControl(hVolume, FSCTL_READ_USN_JOURNAL, &readData, sizeof(readData),
buffer.get(), bufferSize, &bytesReturned, nullptr)) {
DWORD err = GetLastError();
if (err == ERROR_HANDLE_EOF || err == ERROR_NO_MORE_FILES) {
Log(L"[INFO] Fin du journal atteinte");
break;
}
Log(L"[ERREUR] FSCTL_READ_USN_JOURNAL échoué (Erreur: " + std::to_wstring(err) + L")");
break;
}
if (bytesReturned <= sizeof(USN)) break;
// First 8 bytes = next USN
USN nextUsn = *reinterpret_cast<USN*>(buffer.get());
readData.StartUsn = nextUsn;
DWORD offset = sizeof(USN);
while (offset < bytesReturned) {
PUSN_RECORD usnRecord = reinterpret_cast<PUSN_RECORD>(buffer.get() + offset);
if (usnRecord->RecordLength == 0) break;
UsnRecord rec;
rec.fileRef = usnRecord->FileReferenceNumber;
rec.parentRef = usnRecord->ParentFileReferenceNumber;
rec.usn = usnRecord->Usn;
rec.timestamp = usnRecord->TimeStamp;
rec.reason = usnRecord->Reason;
if (usnRecord->FileNameLength > 0) {
rec.fileName = std::wstring(usnRecord->FileName,
usnRecord->FileNameLength / sizeof(WCHAR));
}
rec.sourceInfo = L"USN: " + std::to_wstring(rec.usn);
g_records.push_back(rec);
recordCount++;
if (recordCount % 1000 == 0) {
SendMessageW(g_hProgress, PBM_SETPOS, (recordCount / 100) % 100, 0);
}
offset += usnRecord->RecordLength;
}
if (recordCount > 100000) {
Log(L"[INFO] Limite de 100k entrées atteinte pour la démo");
break;
}
}
Log(L"[SUCCÈS] Parsing terminé : " + std::to_wstring(recordCount) + L" entrées");
// Sort by timestamp (most recent first)
std::sort(g_records.begin(), g_records.end(),
[](const UsnRecord& a, const UsnRecord& b) {
return CompareFileTime(&a.timestamp, &b.timestamp) > 0;
});
UpdateListView();
g_parsing = false;
EnableWindow(GetDlgItem(g_hMainWnd, IDC_BTN_PARSE), TRUE);
SendMessageW(g_hProgress, PBM_SETPOS, 0, 0);
return 0;
}
void OnParseJournal() {
if (g_parsing) {
MessageBoxW(g_hMainWnd, L"Parsing déjà en cours...", L"Info", MB_OK | MB_ICONINFORMATION);
return;
}
wchar_t volume[8] = {};
GetWindowTextW(g_hComboVolume, volume, 8);
if (wcslen(volume) == 0) {
MessageBoxW(g_hMainWnd, L"Veuillez sélectionner un volume.", L"Erreur", MB_OK | MB_ICONERROR);
return;
}
g_parsing = true;
EnableWindow(GetDlgItem(g_hMainWnd, IDC_BTN_PARSE), FALSE);
auto* volumePtr = new std::wstring(volume);
CreateThread(nullptr, 0, ParseJournalThread, volumePtr, 0, nullptr);
}
void OnFilter() {
// Simple filter dialog
MessageBoxW(g_hMainWnd,
L"Filtres avancés à implémenter :\n"
L"- Plage de dates\n"
L"- Type d'opération (création/modif/suppression)\n"
L"- Extensions de fichiers\n"
L"- Recherche par nom",
L"Filtres", MB_OK | MB_ICONINFORMATION);
}
void OnExport() {
if (g_records.empty()) {
MessageBoxW(g_hMainWnd, L"Aucune donnée à exporter.", L"Info", MB_OK | MB_ICONINFORMATION);
return;
}
OPENFILENAMEW ofn = {};
wchar_t fileName[MAX_PATH] = L"ntfs_journal_timeline.csv";
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = g_hMainWnd;
ofn.lpstrFilter = L"CSV Files (*.csv)\0*.csv\0All Files (*.*)\0*.*\0";
ofn.lpstrFile = fileName;
ofn.nMaxFile = MAX_PATH;
ofn.lpstrDefExt = L"csv";
ofn.Flags = OFN_OVERWRITEPROMPT;
if (!GetSaveFileNameW(&ofn)) return;
std::wofstream ofs(fileName);
if (!ofs) {
MessageBoxW(g_hMainWnd, L"Impossible de créer le fichier.", L"Erreur", MB_OK | MB_ICONERROR);
return;
}
// UTF-8 BOM
ofs.imbue(std::locale(""));
unsigned char bom[] = {0xEF, 0xBB, 0xBF};
ofs.write(reinterpret_cast<wchar_t*>(bom), 0);
ofs << L"Timestamp,Fichier,Raison,ParentFRN,SourceInfo\n";
for (const auto& rec : g_records) {
ofs << FileTimeToString(rec.timestamp) << L","
<< L"\"" << rec.fileName << L"\","
<< L"\"" << ReasonToString(rec.reason) << L"\","
<< L"0x" << std::hex << rec.parentRef << std::dec << L","
<< L"\"" << rec.sourceInfo << L"\"\n";
}
ofs.close();
Log(L"[SUCCÈS] Timeline exportée : " + std::wstring(fileName));
MessageBoxW(g_hMainWnd, L"Timeline exportée avec succès.", L"Succès", MB_OK | MB_ICONINFORMATION);
}
void InitListView(HWND hList) {
ListView_SetExtendedListViewStyle(hList, LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_DOUBLEBUFFER);
LVCOLUMNW lvc = {};
lvc.mask = LVCF_TEXT | LVCF_WIDTH;
lvc.pszText = const_cast<LPWSTR>(L"Timestamp");
lvc.cx = 150;
ListView_InsertColumn(hList, 0, &lvc);
lvc.pszText = const_cast<LPWSTR>(L"Fichier");
lvc.cx = 250;
ListView_InsertColumn(hList, 1, &lvc);
lvc.pszText = const_cast<LPWSTR>(L"Raison");
lvc.cx = 200;
ListView_InsertColumn(hList, 2, &lvc);
lvc.pszText = const_cast<LPWSTR>(L"ParentFRN");
lvc.cx = 120;
ListView_InsertColumn(hList, 3, &lvc);
lvc.pszText = const_cast<LPWSTR>(L"SourceInfo");
lvc.cx = 150;
ListView_InsertColumn(hList, 4, &lvc);
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_CREATE: {
// Volume combo
CreateWindowW(L"STATIC", L"Volume :", WS_CHILD | WS_VISIBLE,
10, 15, 60, 20, hwnd, nullptr, nullptr, nullptr);
g_hComboVolume = CreateWindowW(WC_COMBOBOXW, nullptr,
WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST | WS_VSCROLL,
80, 12, 100, 200, hwnd, (HMENU)IDC_COMBO_VOLUME, nullptr, nullptr);
// Populate volumes
DWORD drives = GetLogicalDrives();
for (int i = 0; i < 26; i++) {
if (drives & (1 << i)) {
wchar_t drive[4] = {L'A' + i, L':', 0};
SendMessageW(g_hComboVolume, CB_ADDSTRING, 0, (LPARAM)drive);
}
}
SendMessageW(g_hComboVolume, CB_SETCURSEL, 0, 0);
// Buttons
CreateWindowW(L"BUTTON", L"Parser Journal", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
190, 10, 120, 25, hwnd, (HMENU)IDC_BTN_PARSE, nullptr, nullptr);
CreateWindowW(L"BUTTON", L"Filtrer", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
320, 10, 80, 25, hwnd, (HMENU)IDC_BTN_FILTER, nullptr, nullptr);
CreateWindowW(L"BUTTON", L"Exporter Timeline", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
410, 10, 140, 25, hwnd, (HMENU)IDC_BTN_EXPORT, nullptr, nullptr);
// Progress bar
g_hProgress = CreateWindowW(PROGRESS_CLASSW, nullptr, WS_CHILD | WS_VISIBLE | PBS_SMOOTH,
560, 12, 200, 20, hwnd, (HMENU)IDC_PROGRESS, nullptr, nullptr);
SendMessageW(g_hProgress, PBM_SETRANGE, 0, MAKELPARAM(0, 100));
// ListView
g_hListView = CreateWindowExW(0, WC_LISTVIEWW, nullptr,
WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_SINGLESEL | WS_BORDER,
10, 45, 760, 320, hwnd, (HMENU)IDC_LISTVIEW, nullptr, nullptr);
InitListView(g_hListView);
// Status
g_hStatus = CreateWindowW(L"STATIC", L"Prêt - Sélectionnez un volume et cliquez sur Parser Journal",
WS_CHILD | WS_VISIBLE | SS_LEFT,
10, 375, 760, 20, hwnd, (HMENU)IDC_LABEL_STATUS, nullptr, nullptr);
// Log
CreateWindowW(L"STATIC", L"Journal :", WS_CHILD | WS_VISIBLE,
10, 400, 100, 20, hwnd, nullptr, nullptr, nullptr);
g_hLog = CreateWindowExW(WS_EX_CLIENTEDGE, L"EDIT", nullptr,
WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL,
10, 420, 760, 120, hwnd, (HMENU)IDC_EDIT_LOG, nullptr, nullptr);
Log(L"NTFSJournalParser - Analyseur de journal USN NTFS");
Log(L"Auteur : Ayi NEDJIMI");
Log(L"Prêt à analyser le journal NTFS.");
return 0;
}
case WM_COMMAND: {
switch (LOWORD(wParam)) {
case IDC_BTN_PARSE:
OnParseJournal();
break;
case IDC_BTN_FILTER:
OnFilter();
break;
case IDC_BTN_EXPORT:
OnExport();
break;
}
return 0;
}
case WM_DESTROY:
g_parsing = false;
PostQuitMessage(0);
return 0;
}
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR, int nCmdShow) {
// Init common controls
INITCOMMONCONTROLSEX icc = {};
icc.dwSize = sizeof(icc);
icc.dwICC = ICC_LISTVIEW_CLASSES | ICC_PROGRESS_CLASS;
InitCommonControlsEx(&icc);
// Register window class
WNDCLASSEXW wc = {};
wc.cbSize = sizeof(wc);
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = L"NTFSJournalParserClass";
wc.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
RegisterClassExW(&wc);
// Create window
g_hMainWnd = CreateWindowExW(0, wc.lpszClassName,
L"NTFSJournalParser - Analyseur USN Journal NTFS | Ayi NEDJIMI",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 800, 600,
nullptr, nullptr, hInstance, nullptr);
ShowWindow(g_hMainWnd, nCmdShow);
UpdateWindow(g_hMainWnd);
// Message loop
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}