Windows ETW之监控进程

没有找到合适的图片

最近一段时间因为一些事稍微去研究了一下Windows ETW。现在在博客里记录一下

正文

使用EtwExplorer可以查看系统中的事件提供者

image.png

我这里选择使用的是Microsoft-Windows-Kernel-Process它可以监控进程相关的事件

代码示例

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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <strsafe.h>
#include <wbemidl.h>
#include <wmistr.h>
#include <evntrace.h>
#include <Evntcons.h>
#include <vector>
#include <tdh.h>
#include <string>
#include <in6addr.h>

#pragma comment(lib, "tdh.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "Advapi32.lib")

using namespace std;

#define filename(x) strrchr(x,'\\')?strrchr(x,'\\')+1:x
#define GetLastErrorEx(lpszFunction){LPVOID lpMsgBuf;DWORD dw = GetLastError();FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_IGNORE_INSERTS,NULL,dw,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPSTR)&lpMsgBuf,0, NULL);\
if (lpszFunction)\
printf("%s(Line:%d)->Funtion:%s\ndiyInfo:%s\nError(%d)->Info:%s\n",\
filename(__FILE__), __LINE__, __FUNCTION__, lpszFunction, dw, lpMsgBuf);\
else \
printf("%s(Line:%d)->Funtion:%s\nError(%d)->Info:%s\n",\
filename(__FILE__), __LINE__, __FUNCTION__, dw, lpMsgBuf);\
LocalFree(lpMsgBuf);\
}

#define LOGSESSION_NAME L"Testing ETW Consumer"

TRACEHANDLE sessionHandle;
TRACEHANDLE traceHandle;

DWORD PointerSize = 0;

int bufferSize = sizeof(EVENT_TRACE_PROPERTIES) + sizeof(LOGSESSION_NAME) + sizeof(WCHAR);

auto pSessionProperties = static_cast<PEVENT_TRACE_PROPERTIES>(malloc(bufferSize));

//"{b2bcc945-9eb9-4231-883c-d6455cf4d86b}"
static const GUID SessionGuid =
{ 0xb2bcc945, 0x9eb9, 0x4231,{ 0x88, 0x3c, 0xd6, 0x45, 0x5c, 0xf4, 0xd8, 0x6b } };

// Microsoft-Windows-Kernel-Process {22FB2CD6-0E7B-422B-A0C7-2FAD1FD0E716}
static const GUID PROCESS_PROVIDER_GUID =
{ 0x22fb2cd6, 0x0e7b, 0x422b,{ 0xa0, 0xc7, 0x2f, 0xad, 0x1f, 0xd0, 0xe7, 0x16 } };

void PrintMapString(PEVENT_MAP_INFO pMapInfo, PBYTE pData)
{
BOOL MatchFound = FALSE;

if ((pMapInfo->Flag & EVENTMAP_INFO_FLAG_MANIFEST_VALUEMAP) == EVENTMAP_INFO_FLAG_MANIFEST_VALUEMAP ||
((pMapInfo->Flag & EVENTMAP_INFO_FLAG_WBEM_VALUEMAP) == EVENTMAP_INFO_FLAG_WBEM_VALUEMAP &&
(pMapInfo->Flag & (~EVENTMAP_INFO_FLAG_WBEM_VALUEMAP)) != EVENTMAP_INFO_FLAG_WBEM_FLAG))
{
if ((pMapInfo->Flag & EVENTMAP_INFO_FLAG_WBEM_NO_MAP) == EVENTMAP_INFO_FLAG_WBEM_NO_MAP)
{
wprintf(L"%s\n", (LPWSTR)((PBYTE)pMapInfo + pMapInfo->MapEntryArray[*(PULONG)pData].OutputOffset));
}
else
{
for (DWORD i = 0; i < pMapInfo->EntryCount; i++)
{
if (pMapInfo->MapEntryArray[i].Value == *(PULONG)pData)
{
wprintf(L"%s\n", (LPWSTR)((PBYTE)pMapInfo + pMapInfo->MapEntryArray[i].OutputOffset));
MatchFound = TRUE;
break;
}
}

if (FALSE == MatchFound)
{
wprintf(L"%lu\n", *(PULONG)pData);
}
}
}
else if ((pMapInfo->Flag & EVENTMAP_INFO_FLAG_MANIFEST_BITMAP) == EVENTMAP_INFO_FLAG_MANIFEST_BITMAP ||
(pMapInfo->Flag & EVENTMAP_INFO_FLAG_WBEM_BITMAP) == EVENTMAP_INFO_FLAG_WBEM_BITMAP ||
((pMapInfo->Flag & EVENTMAP_INFO_FLAG_WBEM_VALUEMAP) == EVENTMAP_INFO_FLAG_WBEM_VALUEMAP &&
(pMapInfo->Flag & (~EVENTMAP_INFO_FLAG_WBEM_VALUEMAP)) == EVENTMAP_INFO_FLAG_WBEM_FLAG))
{
if ((pMapInfo->Flag & EVENTMAP_INFO_FLAG_WBEM_NO_MAP) == EVENTMAP_INFO_FLAG_WBEM_NO_MAP)
{
DWORD BitPosition = 0;

for (DWORD i = 0; i < pMapInfo->EntryCount; i++)
{
if ((*(PULONG)pData & (BitPosition = (1 << i))) == BitPosition)
{
wprintf(L"%s%s",
(MatchFound) ? L" | " : L"",
(LPWSTR)((PBYTE)pMapInfo + pMapInfo->MapEntryArray[i].OutputOffset));

MatchFound = TRUE;
}
}
}
else
{
for (DWORD i = 0; i < pMapInfo->EntryCount; i++)
{
if ((pMapInfo->MapEntryArray[i].Value & *(PULONG)pData) == pMapInfo->MapEntryArray[i].Value)
{
wprintf(L"%s%s",
(MatchFound) ? L" | " : L"",
(LPWSTR)((PBYTE)pMapInfo + pMapInfo->MapEntryArray[i].OutputOffset));

MatchFound = TRUE;
}
}
}

if (MatchFound)
{
wprintf(L"\n");
}
else
{
wprintf(L"%lu\n", *(PULONG)pData);
}
}
}

#define MAX_NAME 256
DWORD FormatAndPrintData(PEVENT_RECORD pEvent, USHORT InType, USHORT OutType, PBYTE pData, DWORD DataSize, PEVENT_MAP_INFO pMapInfo)
{
UNREFERENCED_PARAMETER(pEvent);

DWORD status = ERROR_SUCCESS;

switch (InType)
{
case TDH_INTYPE_UNICODESTRING:
case TDH_INTYPE_COUNTEDSTRING:
case TDH_INTYPE_REVERSEDCOUNTEDSTRING:
case TDH_INTYPE_NONNULLTERMINATEDSTRING:
{
size_t StringLength = 0;

if (TDH_INTYPE_COUNTEDSTRING == InType)
{
StringLength = *(PUSHORT)pData;
}
else if (TDH_INTYPE_REVERSEDCOUNTEDSTRING == InType)
{
StringLength = MAKEWORD(HIBYTE((PUSHORT)pData), LOBYTE((PUSHORT)pData));
}
else if (TDH_INTYPE_NONNULLTERMINATEDSTRING == InType)
{
StringLength = DataSize;
}
else
{
StringLength = wcslen((LPWSTR)pData);
}

wprintf(L"%.*s\n", StringLength, (LPWSTR)pData);
break;
}

case TDH_INTYPE_ANSISTRING:
case TDH_INTYPE_COUNTEDANSISTRING:
case TDH_INTYPE_REVERSEDCOUNTEDANSISTRING:
case TDH_INTYPE_NONNULLTERMINATEDANSISTRING:
{
size_t StringLength = 0;

if (TDH_INTYPE_COUNTEDANSISTRING == InType)
{
StringLength = *(PUSHORT)pData;
}
else if (TDH_INTYPE_REVERSEDCOUNTEDANSISTRING == InType)
{
StringLength = MAKEWORD(HIBYTE((PUSHORT)pData), LOBYTE((PUSHORT)pData));
}
else if (TDH_INTYPE_NONNULLTERMINATEDANSISTRING == InType)
{
StringLength = DataSize;
}
else
{
StringLength = strlen((LPSTR)pData);
}

wprintf(L"%.*S\n", StringLength, (LPSTR)pData);
break;
}

case TDH_INTYPE_INT8:
{
wprintf(L"%hd\n", *(PCHAR)pData);
break;
}

case TDH_INTYPE_UINT8:
{
if (TDH_OUTTYPE_HEXINT8 == OutType)
{
wprintf(L"0x%x\n", *(PBYTE)pData);
}
else
{
wprintf(L"%hu\n", *(PBYTE)pData);
}

break;
}

case TDH_INTYPE_INT16:
{
wprintf(L"%hd\n", *(PSHORT)pData);
break;
}

case TDH_INTYPE_UINT16:
{
if (TDH_OUTTYPE_HEXINT16 == OutType)
{
wprintf(L"0x%x\n", *(PUSHORT)pData);
}
else if (TDH_OUTTYPE_PORT == OutType)
{
wprintf(L"%hu\n", ntohs(*(PUSHORT)pData));
}
else
{
wprintf(L"%hu\n", *(PUSHORT)pData);
}

break;
}

case TDH_INTYPE_INT32:
{
if (TDH_OUTTYPE_HRESULT == OutType)
{
wprintf(L"0x%x\n", *(PLONG)pData);
}
else
{
wprintf(L"%d\n", *(PLONG)pData);
}

break;
}

case TDH_INTYPE_UINT32:
{
if (TDH_OUTTYPE_HRESULT == OutType ||
TDH_OUTTYPE_WIN32ERROR == OutType ||
TDH_OUTTYPE_NTSTATUS == OutType ||
TDH_OUTTYPE_HEXINT32 == OutType)
{
wprintf(L"0x%x\n", *(PULONG)pData);
}
else if (TDH_OUTTYPE_IPV4 == OutType)
{
wprintf(L"%d.%d.%d.%d\n", (*(PLONG)pData >> 0) & 0xff,
(*(PLONG)pData >> 8) & 0xff,
(*(PLONG)pData >> 16) & 0xff,
(*(PLONG)pData >> 24) & 0xff);
}
else
{
if (pMapInfo)
{
PrintMapString(pMapInfo, pData);
}
else
{
wprintf(L"%lu\n", *(PULONG)pData);
}
}

break;
}

case TDH_INTYPE_INT64:
{
wprintf(L"%I64d\n", *(PLONGLONG)pData);

break;
}

case TDH_INTYPE_UINT64:
{
if (TDH_OUTTYPE_HEXINT64 == OutType)
{
wprintf(L"0x%x\n", *(PULONGLONG)pData);
}
else
{
wprintf(L"%I64u\n", *(PULONGLONG)pData);
}

break;
}

case TDH_INTYPE_FLOAT:
{
wprintf(L"%f\n", *(PFLOAT)pData);

break;
}

case TDH_INTYPE_DOUBLE:
{
wprintf(L"%I64f\n", *(DOUBLE*)pData);

break;
}

case TDH_INTYPE_BOOLEAN:
{
wprintf(L"%s\n", (0 == (PBOOL)pData) ? L"false" : L"true");

break;
}

case TDH_INTYPE_BINARY:
{
if (TDH_OUTTYPE_IPV6 == OutType)
{
//WCHAR IPv6AddressAsString[46];
//PIPV6ADDRTOSTRING fnRtlIpv6AddressToString;

//fnRtlIpv6AddressToString = (PIPV6ADDRTOSTRING)GetProcAddress(
// GetModuleHandle(L"ntdll"), "RtlIpv6AddressToStringW");

//if (NULL == fnRtlIpv6AddressToString)
//{
// wprintf(L"GetProcAddress failed with %lu.\n", status = GetLastError());
// goto cleanup;
//}

//fnRtlIpv6AddressToString((IN6_ADDR*)pData, IPv6AddressAsString);

//wprintf(L"%s\n", IPv6AddressAsString);
}
else
{
for (DWORD i = 0; i < DataSize; i++)
{
wprintf(L"%.2x", pData[i]);
}

wprintf(L"\n");
}

break;
}

case TDH_INTYPE_GUID:
{
WCHAR szGuid[50];

StringFromGUID2(*(GUID*)pData, szGuid, sizeof(szGuid) - 1);
wprintf(L"%s\n", szGuid);

break;
}

case TDH_INTYPE_POINTER:
case TDH_INTYPE_SIZET:
{
if (4 == PointerSize)
{
wprintf(L"0x%x\n", *(PULONG)pData);
}
else
{
wprintf(L"0x%x\n", *(PULONGLONG)pData);
}

break;
}

case TDH_INTYPE_FILETIME:
{
ULONGLONG TimeStamp = 0;
SYSTEMTIME st;
SYSTEMTIME stLocal;
FILETIME ft;
ft.dwHighDateTime = pEvent->EventHeader.TimeStamp.HighPart;
ft.dwLowDateTime = pEvent->EventHeader.TimeStamp.LowPart;

FileTimeToSystemTime(&ft, &st);
SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);

TimeStamp = pEvent->EventHeader.TimeStamp.QuadPart;

//Local System Time(YYYY-MM-DD HH:MM:SS):
wprintf(L"%d-%d-%d %d:%d:%d\n", stLocal.wYear, stLocal.wMonth,stLocal.wDay, stLocal.wHour, stLocal.wMinute, stLocal.wSecond);

break;
}

case TDH_INTYPE_SYSTEMTIME:
{
break;
}

case TDH_INTYPE_SID:
{
WCHAR UserName[MAX_NAME];
WCHAR DomainName[MAX_NAME];
DWORD cchUserSize = MAX_NAME;
DWORD cchDomainSize = MAX_NAME;
SID_NAME_USE eNameUse;

if (!LookupAccountSid(NULL, (PSID)pData, UserName, &cchUserSize, DomainName, &cchDomainSize, &eNameUse))
{
if (ERROR_NONE_MAPPED == status)
{
wprintf(L"Unable to locate account for the specified SID\n");
status = ERROR_SUCCESS;
}
else
{
wprintf(L"LookupAccountSid failed with %lu\n", status = GetLastError());
}

goto cleanup;
}
else
{
wprintf(L"%s\\%s\n", DomainName, UserName);
}

break;
}

case TDH_INTYPE_HEXINT32:
{
wprintf(L"0x%x\n", (PULONG)pData);
break;
}

case TDH_INTYPE_HEXINT64:
{
wprintf(L"0x%x\n", (PULONGLONG)pData);
break;
}

case TDH_INTYPE_UNICODECHAR:
{
wprintf(L"%c\n", *(PWCHAR)pData);
break;
}

case TDH_INTYPE_ANSICHAR:
{
wprintf(L"%C\n", *(PCHAR)pData);
break;
}

case TDH_INTYPE_WBEMSID:
{
WCHAR UserName[MAX_NAME];
WCHAR DomainName[MAX_NAME];
DWORD cchUserSize = MAX_NAME;
DWORD cchDomainSize = MAX_NAME;
SID_NAME_USE eNameUse;

if ((PULONG)pData > 0)
{
// A WBEM SID is actually a TOKEN_USER structure followed by the SID. The size of the
// TOKEN_USER structure differs depending on whether the events were generated on a
// 32-bit or 64-bit architecture. Also the structure is aligned on an 8-byte boundary,
// so its size is 8 bytes on a 32-bit computer and 16 bytes on a 64-bit computer.
// Doubling the pointer size handles both cases.

pData += PointerSize * 2;

if (!LookupAccountSid(NULL, (PSID)pData, UserName, &cchUserSize, DomainName, &cchDomainSize, &eNameUse))
{
if (ERROR_NONE_MAPPED == status)
{
wprintf(L"Unable to locate account for the specified SID\n");
status = ERROR_SUCCESS;
}
else
{
wprintf(L"LookupAccountSid failed with %lu\n", status = GetLastError());
}

goto cleanup;
}
else
{
wprintf(L"%s\\%s\n", DomainName, UserName);
}
}

break;
}

default:
status = ERROR_NOT_FOUND;
}

cleanup:

return status;
}

DWORD GetArraySize(PEVENT_RECORD pEvent, PTRACE_EVENT_INFO pInfo, USHORT i, PUSHORT ArraySize)
{
DWORD status = ERROR_SUCCESS;
PROPERTY_DATA_DESCRIPTOR DataDescriptor;
DWORD PropertySize = 0;

if ((pInfo->EventPropertyInfoArray[i].Flags & PropertyParamCount) == PropertyParamCount)
{
DWORD Count = 0; // Expects the count to be defined by a UINT16 or UINT32
DWORD j = pInfo->EventPropertyInfoArray[i].countPropertyIndex;
ZeroMemory(&DataDescriptor, sizeof(PROPERTY_DATA_DESCRIPTOR));
DataDescriptor.PropertyName = (ULONGLONG)((PBYTE)(pInfo)+pInfo->EventPropertyInfoArray[j].NameOffset);
DataDescriptor.ArrayIndex = ULONG_MAX;
status = TdhGetPropertySize(pEvent, 0, NULL, 1, &DataDescriptor, &PropertySize);
status = TdhGetProperty(pEvent, 0, NULL, 1, &DataDescriptor, PropertySize, (PBYTE)&Count);
*ArraySize = (USHORT)Count;
}
else
{
*ArraySize = pInfo->EventPropertyInfoArray[i].count;
}

return status;
}

void RemoveTrailingSpace(PEVENT_MAP_INFO pMapInfo)
{
SIZE_T ByteLength = 0;

for (DWORD i = 0; i < pMapInfo->EntryCount; i++)
{
ByteLength = (wcslen((LPWSTR)((PBYTE)pMapInfo + pMapInfo->MapEntryArray[i].OutputOffset)) - 1) * 2;
*((LPWSTR)((PBYTE)pMapInfo + (pMapInfo->MapEntryArray[i].OutputOffset + ByteLength))) = L'\0';
}
}

DWORD GetMapInfo(PEVENT_RECORD pEvent, LPWSTR pMapName, DWORD DecodingSource, PEVENT_MAP_INFO& pMapInfo)
{
DWORD status = ERROR_SUCCESS;
DWORD MapSize = 0;

// Retrieve the required buffer size for the map info.

status = TdhGetEventMapInformation(pEvent, pMapName, pMapInfo, &MapSize);

if (ERROR_INSUFFICIENT_BUFFER == status)
{
pMapInfo = (PEVENT_MAP_INFO)malloc(MapSize);
if (pMapInfo == NULL)
{
wprintf(L"Failed to allocate memory for map info (size=%lu).\n", MapSize);
status = ERROR_OUTOFMEMORY;
goto cleanup;
}

// Retrieve the map info.

status = TdhGetEventMapInformation(pEvent, pMapName, pMapInfo, &MapSize);
}

if (ERROR_SUCCESS == status)
{
if (DecodingSourceXMLFile == DecodingSource)
{
RemoveTrailingSpace(pMapInfo);
}
}
else
{
if (ERROR_NOT_FOUND == status)
{
status = ERROR_SUCCESS; // This case is okay.
}
else
{
wprintf(L"TdhGetEventMapInformation failed with 0x%x.\n", status);
}
}

cleanup:

return status;
}

DWORD PrintProperties(PEVENT_RECORD pEvent, PTRACE_EVENT_INFO pInfo, USHORT i, LPWSTR pStructureName, USHORT StructIndex)
{
DWORD status = ERROR_SUCCESS;
DWORD LastMember = 0; // Last member of a structure
USHORT ArraySize = 0;
PEVENT_MAP_INFO pMapInfo = NULL;
PROPERTY_DATA_DESCRIPTOR DataDescriptors[2];
ULONG DescriptorsCount = 0;
DWORD PropertySize = 0;
PBYTE pData = NULL;

// Get the size of the array if the property is an array.

status = GetArraySize(pEvent, pInfo, i, &ArraySize);

for (USHORT k = 0; k < ArraySize; k++)
{
wprintf(L"%*s%s: ", (pStructureName) ? 4 : 0, L"", (LPWSTR)((PBYTE)(pInfo)+pInfo->EventPropertyInfoArray[i].NameOffset));

// If the property is a structure, print the members of the structure.

if ((pInfo->EventPropertyInfoArray[i].Flags & PropertyStruct) == PropertyStruct)
{
wprintf(L"\n");

LastMember = pInfo->EventPropertyInfoArray[i].structType.StructStartIndex +
pInfo->EventPropertyInfoArray[i].structType.NumOfStructMembers;

for (USHORT j = pInfo->EventPropertyInfoArray[i].structType.StructStartIndex; j < LastMember; j++)
{
status = PrintProperties(pEvent, pInfo, j, (LPWSTR)((PBYTE)(pInfo)+pInfo->EventPropertyInfoArray[i].NameOffset), k);
if (ERROR_SUCCESS != status)
{
wprintf(L"Printing the members of the structure failed.\n");
goto cleanup;
}
}
}
else
{
ZeroMemory(&DataDescriptors, sizeof(DataDescriptors));

// To retrieve a member of a structure, you need to specify an array of descriptors. The
// first descriptor in the array identifies the name of the structure and the second
// descriptor defines the member of the structure whose data you want to retrieve.

if (pStructureName)
{
DataDescriptors[0].PropertyName = (ULONGLONG)pStructureName;
DataDescriptors[0].ArrayIndex = StructIndex;
DataDescriptors[1].PropertyName = (ULONGLONG)((PBYTE)(pInfo)+pInfo->EventPropertyInfoArray[i].NameOffset);
DataDescriptors[1].ArrayIndex = k;
DescriptorsCount = 2;
}
else
{
DataDescriptors[0].PropertyName = (ULONGLONG)((PBYTE)(pInfo)+pInfo->EventPropertyInfoArray[i].NameOffset);
DataDescriptors[0].ArrayIndex = k;
DescriptorsCount = 1;
}

// The TDH API does not support IPv6 addresses. If the output type is TDH_OUTTYPE_IPV6,
// you will not be able to consume the rest of the event. If you try to consume the
// remainder of the event, you will get ERROR_EVT_INVALID_EVENT_DATA.

if (TDH_INTYPE_BINARY == pInfo->EventPropertyInfoArray[i].nonStructType.InType &&
TDH_OUTTYPE_IPV6 == pInfo->EventPropertyInfoArray[i].nonStructType.OutType)
{
wprintf(L"The event contains an IPv6 address. Skipping event.\n");
status = ERROR_EVT_INVALID_EVENT_DATA;
break;
}
else
{
status = TdhGetPropertySize(pEvent, 0, NULL, DescriptorsCount, &DataDescriptors[0], &PropertySize);

if (ERROR_SUCCESS != status)
{
wprintf(L"TdhGetPropertySize failed with %lu\n", status);
goto cleanup;
}

pData = (PBYTE)malloc(PropertySize);

if (NULL == pData)
{
wprintf(L"Failed to allocate memory for property data\n");
status = ERROR_OUTOFMEMORY;
goto cleanup;
}

status = TdhGetProperty(pEvent, 0, NULL, DescriptorsCount, &DataDescriptors[0], PropertySize, pData);

// Get the name/value mapping if the property specifies a value map.

status = GetMapInfo(pEvent,
(PWCHAR)((PBYTE)(pInfo)+pInfo->EventPropertyInfoArray[i].nonStructType.MapNameOffset),
pInfo->DecodingSource,
pMapInfo);

if (ERROR_SUCCESS != status)
{
wprintf(L"GetMapInfo failed\n");
goto cleanup;
}

status = FormatAndPrintData(pEvent,
pInfo->EventPropertyInfoArray[i].nonStructType.InType,
pInfo->EventPropertyInfoArray[i].nonStructType.OutType,
pData,
PropertySize,
pMapInfo
);

if (ERROR_SUCCESS != status)
{
wprintf(L"GetMapInfo failed\n");
goto cleanup;
}

if (pData)
{
free(pData);
pData = NULL;
}

if (pMapInfo)
{
free(pMapInfo);
pMapInfo = NULL;
}
}
}
}

cleanup:

if (pData)
{
free(pData);
pData = NULL;
}

if (pMapInfo)
{
free(pMapInfo);
pMapInfo = NULL;
}

return status;
}

void Showinfo(PTRACE_EVENT_INFO& pInfo)
{
printf(("Id: %u\n"), pInfo->EventDescriptor.Id);
printf(("Version: %u\n"), pInfo->EventDescriptor.Version);
printf(("Channel: %u\n"), pInfo->EventDescriptor.Channel);
printf(("Level: %u\n"), pInfo->EventDescriptor.Level);
printf(("Opcode: %u\n"), pInfo->EventDescriptor.Opcode);
printf(("Task: %u\n"), pInfo->EventDescriptor.Task);
printf(("Keyword: %lu\n"), pInfo->EventDescriptor.Keyword);

wprintf(L"ProviderName: %s\n", (WCHAR*)pInfo + pInfo->ProviderNameOffset);
wprintf(L"ChannelName: %s\n", (WCHAR*)pInfo + pInfo->ChannelNameOffset);
wprintf(L"KeywordsName: %s\n", (WCHAR*)pInfo + pInfo->KeywordsNameOffset);
wprintf(L"TaskName: %s\n", (WCHAR*)pInfo + pInfo->TaskNameOffset);

//ShowNameString((LPBYTE)pInfo + pInfo->ProviderNameOffset, pInfo->ProviderNameOffset, L"ProviderName");
//ShowNameString((LPBYTE)pInfo + pInfo->ChannelNameOffset, pInfo->ChannelNameOffset, L"ChannelName");
//ShowNameString((LPBYTE)pInfo + pInfo->KeywordsNameOffset, pInfo->KeywordsNameOffset, L"KeywordsName");
//ShowNameString((LPBYTE)pInfo + pInfo->TaskNameOffset, pInfo->TaskNameOffset, L"TaskName");
}

DWORD GetEventInformation(PEVENT_RECORD pEvent, PTRACE_EVENT_INFO& pInfo)
{
DWORD status = ERROR_SUCCESS;
DWORD BufferSize = 0;

status = TdhGetEventInformation(pEvent, 0, NULL, pInfo, &BufferSize);

if (ERROR_INSUFFICIENT_BUFFER == status)
{
pInfo = (TRACE_EVENT_INFO*)malloc(BufferSize);
if (pInfo == NULL)
{
printf("Failed to allocate memory for event info (size=%lu).\n", BufferSize);
status = ERROR_OUTOFMEMORY;
goto cleanup;
}

// Retrieve the event metadata.

status = TdhGetEventInformation(pEvent, 0, NULL, pInfo, &BufferSize);
}

if (ERROR_SUCCESS != status)
{
GetLastErrorEx("TdhGetEventInformation 错误代码", status);
}

cleanup:

return status;
}

VOID WINAPI EventRecordCallback(PEVENT_RECORD pEventRecord)
{
DWORD status = 0;
PTRACE_EVENT_INFO pInfo = NULL;
LPWSTR pwsEventGuid = NULL;
printf("ETW ********************************************************** start\n");
if (!IsEqualGUID(pEventRecord->EventHeader.ProviderId, PROCESS_PROVIDER_GUID))
{
return;
}
else
{
status = GetEventInformation(pEventRecord, pInfo);

if (ERROR_SUCCESS != status)
{
GetLastErrorEx("GetEventInformation 错误代码", status);
exit(0);
}

// Determine whether the event is defined by a MOF class, in an instrumentation manifest, or
// a WPP template; to use TDH to decode the event, it must be defined by one of these three sources.

if (DecodingSourceWbem == pInfo->DecodingSource) // MOF class
{
HRESULT hr = StringFromCLSID(pInfo->EventGuid, &pwsEventGuid);

if (FAILED(hr))
{
GetLastErrorEx("StringFromCLSID 错误代码", hr);
status = hr;
exit(0);
}

wprintf(L"\nEvent GUID: %s\n", pwsEventGuid);
CoTaskMemFree(pwsEventGuid);
pwsEventGuid = NULL;

wprintf(L"Event version: %d\n", pEventRecord->EventHeader.EventDescriptor.Version);
wprintf(L"Event type: %d\n", pEventRecord->EventHeader.EventDescriptor.Opcode);
}
else if (DecodingSourceXMLFile == pInfo->DecodingSource) // Instrumentation manifest
{
}
else // Not handling the WPP case
{
exit(0);
}
}


//打印etw info
Showinfo(pInfo);

// If the event contains event-specific data use TDH to extract the event data. For this
// example, to extract the data, the event must be defined by a MOF class or an instrumentation manifest.

// Need to get the PointerSize for each event to cover the case where you are consuming events
// from multiple log files that could have been generated on different architectures. Otherwise,
// you could have accessed the pointer size when you opened the trace above (see pHeader->PointerSize).

if (EVENT_HEADER_FLAG_32_BIT_HEADER == (pEventRecord->EventHeader.Flags & EVENT_HEADER_FLAG_32_BIT_HEADER))
{
PointerSize = 4;
}
else
{
PointerSize = 8;
}


for (USHORT i = 0; i < pInfo->TopLevelPropertyCount; i++)
{
//ShowPropertyInfo(pEventRecord, pInfo, &pInfo->EventPropertyInfoArray[i], NULL);
status = PrintProperties(pEventRecord, pInfo, i, NULL, 0);
if (ERROR_SUCCESS != status)
{
wprintf(L"Printing top level properties failed.\n");
}
}

printf("ETW ********************************************************** end\n\n");
return;
}


static DWORD WINAPI Win32TracingThread(LPVOID Parameter)
{
printf("processing trace...\n");
auto ptStatus = ProcessTrace(&traceHandle, 1, NULL, NULL);
if (ptStatus != ERROR_SUCCESS && ptStatus != ERROR_CANCELLED)
{
GetLastErrorEx("ProcessTrace 错误代码", ptStatus);
}
return(0);
}

int main(void)
{
printf("entering main program...\n");

ZeroMemory(pSessionProperties, bufferSize);
pSessionProperties->Wnode.BufferSize = bufferSize;
pSessionProperties->Wnode.Flags = WNODE_FLAG_TRACED_GUID;
pSessionProperties->Wnode.ClientContext = 1; //QPC clock resolution
pSessionProperties->Wnode.Guid = SessionGuid;
pSessionProperties->FlushTimer = 0;
//pSessionProperties->EnableFlags = EVENT_TRACE_FLAG_PROCESS | EVENT_TRACE_FLAG_PROCESS_COUNTERS;
pSessionProperties->LogFileMode = EVENT_TRACE_REAL_TIME_MODE;
pSessionProperties->LogFileNameOffset = 0;
pSessionProperties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
StringCbCopy((STRSAFE_LPWSTR)((char*)pSessionProperties + pSessionProperties->LoggerNameOffset), sizeof(LOGSESSION_NAME), LOGSESSION_NAME);

// stop any previous session
auto stopStatus = ControlTrace(0, LOGSESSION_NAME, pSessionProperties, EVENT_TRACE_CONTROL_STOP);

printf("starting trace...\n");
auto sTrStatus = StartTrace(static_cast<PTRACEHANDLE>(&sessionHandle), LOGSESSION_NAME, pSessionProperties);

ENABLE_TRACE_PARAMETERS params{};
params.Version = ENABLE_TRACE_PARAMETERS_VERSION_2;

printf("enabling trace...\n");
auto eTrExstatus = EnableTraceEx2(sessionHandle, &PROCESS_PROVIDER_GUID,
EVENT_CONTROL_CODE_ENABLE_PROVIDER,TRACE_LEVEL_INFORMATION, 0x10|0x40, 0, 0, &params);
if (eTrExstatus != ERROR_SUCCESS)
{
GetLastErrorEx("EnableTraceEx2 错误代码", eTrExstatus);
ControlTrace(sessionHandle, nullptr, pSessionProperties, EVENT_TRACE_CONTROL_STOP);
return -1;
}

EVENT_TRACE_LOGFILE loggerInfo = { 0 };

loggerInfo.ProcessTraceMode = EVENT_TRACE_REAL_TIME_MODE | PROCESS_TRACE_MODE_EVENT_RECORD;

//loggerInfo.BufferCallback = BufferCallback;

// provide a callback whenever we get an event record
loggerInfo.EventRecordCallback = (PEVENT_RECORD_CALLBACK)EventRecordCallback;
loggerInfo.Context = NULL;

loggerInfo.LoggerName = (WCHAR*)LOGSESSION_NAME;
loggerInfo.LogFileName = NULL;

printf("opening trace...\n");
traceHandle = OpenTrace(&loggerInfo);

// calling thread will be blocked until BufferCallback returns FALSE or all events are delivered
// or CloseTrace is called
DWORD ThreadID;
HANDLE ThreadHandle = CreateThread(0, 0, Win32TracingThread, 0, 0, &ThreadID);

bool exit2 = false;
while (exit2 == false)
{
if (GetAsyncKeyState(VK_ESCAPE))
{
exit2 = true;
printf("escape pressed, exiting loop...\n");
}
}
CloseHandle(ThreadHandle);

if ((TRACEHANDLE)INVALID_HANDLE_VALUE != traceHandle)
{
printf("in cleanup...\n");
printf("closing trace...\n");
auto ctStatus = CloseTrace(traceHandle);
}

auto cTrStatus = ControlTrace(sessionHandle, nullptr, pSessionProperties, EVENT_TRACE_CONTROL_STOP);
auto eTrStatus = EnableTraceEx2(sessionHandle, &PROCESS_PROVIDER_GUID, EVENT_CONTROL_CODE_DISABLE_PROVIDER, 0, 0, 0, 0, nullptr);

free(pSessionProperties);
}

我这里主要是监控进程的创建和退出以及dll加载和卸载

效果如下

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
entering main program...
starting trace...
enabling trace...
opening trace...
processing trace...
ETW ********************************************************** start
Id: 6
Version: 0
Channel: 16
Level: 4
Opcode: 0
Task: 6
Keyword: 64
ProviderName: Microsoft-Windows-Kernel-Process
ChannelName: Microsoft-Windows-Kernel-Process/Analytic
KeywordsName: WINEVENT_KEYWORD_IMAGE
TaskName: ImageUnload
ImageBase: 0xc45b0000
ImageSize: 0x32000
ProcessID: 9644
ImageCheckSum: 181919
TimeDateStamp: 1849399745
DefaultBase: 0xc45b0000
ImageName: \Device\HarddiskVolume4\Windows\System32\notepad.exe
ETW ********************************************************** end

ETW ********************************************************** start
Id: 6
Version: 0
Channel: 16
Level: 4
Opcode: 0
Task: 6
Keyword: 64
ProviderName: Microsoft-Windows-Kernel-Process
ChannelName: Microsoft-Windows-Kernel-Process/Analytic
KeywordsName: WINEVENT_KEYWORD_IMAGE
TaskName: ImageUnload
ImageBase: 0x4be50000
ImageSize: 0xd7000
ProcessID: 9644
ImageCheckSum: 904896
TimeDateStamp: 2571084312
DefaultBase: 0x4be50000
ImageName: \Device\HarddiskVolume4\Windows\System32\efswrt.dll
ETW ********************************************************** end

ETW ********************************************************** start
Id: 6
Version: 0
Channel: 16
Level: 4
Opcode: 0
Task: 6
Keyword: 64
ProviderName: Microsoft-Windows-Kernel-Process
ChannelName: Microsoft-Windows-Kernel-Process/Analytic
KeywordsName: WINEVENT_KEYWORD_IMAGE
TaskName: ImageUnload
ImageBase: 0x71e00000
ImageSize: 0x153000
ProcessID: 9644
ImageCheckSum: 1397918
TimeDateStamp: 1527226666
DefaultBase: 0x71e00000
ImageName: \Device\HarddiskVolume5\Stardock\Fences\FencesMenu64.dll
ETW ********************************************************** end

ETW ********************************************************** start
Id: 6
Version: 0
Channel: 16
Level: 4
Opcode: 0
Task: 6
Keyword: 64
ProviderName: Microsoft-Windows-Kernel-Process
ChannelName: Microsoft-Windows-Kernel-Process/Analytic
KeywordsName: WINEVENT_KEYWORD_IMAGE
TaskName: ImageUnload
ImageBase: 0x73730000
ImageSize: 0xbf000
ProcessID: 9644
ImageCheckSum: 796280
TimeDateStamp: 1118443760
DefaultBase: 0x73730000
ImageName: \Device\HarddiskVolume4\Windows\System32\msctfuimanager.dll
ETW ********************************************************** end

ETW ********************************************************** start
Id: 6
Version: 0
Channel: 16
Level: 4
Opcode: 0
Task: 6
Keyword: 64
ProviderName: Microsoft-Windows-Kernel-Process
ChannelName: Microsoft-Windows-Kernel-Process/Analytic
KeywordsName: WINEVENT_KEYWORD_IMAGE
TaskName: ImageUnload
ImageBase: 0x79530000
ImageSize: 0x270000
ProcessID: 9644
ImageCheckSum: 2550189
TimeDateStamp: 3941062522
DefaultBase: 0x79530000
ImageName: \Device\HarddiskVolume4\Windows\System32\UIAutomationCore.dll
ETW ********************************************************** end

不过自己写ETW最难受的地方就是在解析事件信息那里,那个地方需要判断数据类型然后在根据不同的类型做不同的解析,如果不是为了学习ETW的机制推荐使用微软的Krabsetw库

使用Krabsetw库监控进程启动和退出

代码

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
#include "packages/Microsoft.O365.Security.Krabsetw.4.1.18/lib/native/include/krabs.hpp"
#include <iostream>
int main()
{
// Setup basic Microsoft-Windows-Kernel-Process trace
krabs::user_trace trace(L"My magic trace");
krabs::provider<> provider(krabs::guid(L"{22FB2CD6-0E7B-422B-A0C7-2FAD1FD0E716}"));

provider.any(0x10);

krabs::predicates::id_is eventid_is_1 = krabs::predicates::id_is(1);
krabs::predicates::id_is eventid_is_2 = krabs::predicates::id_is(2);

krabs::event_filter filter(
krabs::predicates::any_of({
&eventid_is_1,
&eventid_is_2,
})
);

filter.add_on_event_callback([](const EVENT_RECORD& record, const krabs::trace_context& trace_context) {
krabs::schema schema(record, trace_context.schema_locator);
krabs::parser parser(schema);


printf("Event ID: %d || Opcode: %d || Version %d\n", schema.event_id(), schema.event_opcode(), schema.event_version());

if (schema.event_id() == 1)
{
uint32_t pid = parser.parse<uint32_t>(L"ProcessID");
uint32_t ParentProcessID = parser.parse<uint32_t>(L"ParentProcessID");
std::wstring image_name = parser.parse<std::wstring>(L"ImageName");
std::wcout << schema.provider_name();
std::wcout << L" etw id=";
std::wcout << schema.event_id();
std::wcout << L" task_name=" << schema.task_name();
std::wcout << L" ProcessID=" << pid;
std::wcout << L" ImageName=" << image_name;
std::wcout << L" ParentProcessID=" << ParentProcessID;
std::wcout << "\n";
std::wcout << std::endl;
}



else if(schema.event_id() == 2)
{
uint32_t pid = parser.parse<uint32_t>(L"ProcessID");
uint32_t ExitCode = parser.parse<uint32_t>(L"ExitCode");
std::wcout << schema.provider_name();
std::wcout << L" etw id=";
std::wcout << schema.event_id();
std::wcout << L" task_name=" << schema.task_name();
std::wcout << L" ProcessID=" << pid;
std::wcout << L" ExitCode=" << ExitCode;
std::wcout << "\n";
std::wcout << std::endl;
}
});

// Start ETW Session
provider.add_filter(filter);
trace.enable(provider);
printf("Starting trace...\n");
trace.start();
}

效果如下

1
2
3
4
5
6
Starting trace...
Event ID: 1 || Opcode: 1 || Version 3
Microsoft-Windows-Kernel-Process etw id=1 task_name=ProcessStart ProcessID=28208 ImageName=\Device\HarddiskVolume4\Windows\System32\notepad.exe ParentProcessID=20668

Event ID: 2 || Opcode: 2 || Version 2
Microsoft-Windows-Kernel-Process etw id=2 task_name=ProcessStop ProcessID=28208 ExitCode=0

在这里顺便提一下关于ETW绕过的问题,用EtwExplorer可以查看ETW事件提供者,你能看到系统中有很多的提供者,其中大部分提供者运行于R3层对于这种直接修补Advapi32.dll!EventWrite函数即可(在Win高版本上Advapi32.dll!EventWrite是直接转发到ntdll.dll!EtwEventWrite函数上的)这是一种,另一种更为优雅的bypass方式是找到 EventRegister 函数注册的句柄,然后直接调用 EventUnregister 函数关闭这个句柄这样即使调用EtwEventWrite函数也毫无作用,同时还有一些以Microsoft-Windows-Kernel-XXXXXX名字开头的提供者是内核提供者它们运行于R0进行记录,对于这些提供者在R3来说一般是无法绕过的。对于防御者来说应该尽量使用内核提供者它们更加可靠不容易被绕过。

后话

其实最开始想非常细致的写ETW中的知识点,而且确实也写了一些但是写到后面发现要写的实在是太多了还是鸽了吧,等有机会再说吧,

相关参考
https://docs.microsoft.com/zh-cn/windows/win32/etw/using-tdhgetproperty-to-consume-event-data
https://stackoverflow.com/questions/61197136/not-receiving-microsoft-windows-kernel-process-events-from-real-time-etw-consume
https://github.com/microsoft/krabsetw