-
Notifications
You must be signed in to change notification settings - Fork 1
/
DumpEtwWrites.java
2052 lines (1833 loc) · 101 KB
/
DumpEtwWrites.java
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
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Outputs all calls to EtwWrite* reachable from each function along with provider and event metadata.
//
// functions.txt - functions to analyze. Defaults to exports otherwise.
// ignore.txt - functions to ignore - especially error handling paths.
//
// Kernel-mode ETW functions are prefixed with Etw, the Win32 equivalents with Event and the native API ones with EtwEvent.
// All APIs take the same parameters so this script should partially work on every binary.
//
//@category Functions.ETW
//@author jdu2600
import java.io.*;
import java.lang.Math.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
import generic.stl.Pair;
import docking.options.OptionsService;
import ghidra.app.cmd.function.*;
import ghidra.app.decompiler.*;
import ghidra.app.script.*;
import ghidra.app.services.*;
import ghidra.framework.options.*;
import ghidra.framework.plugintool.util.*;
import ghidra.program.model.address.*;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.pcode.*;
import ghidra.program.model.symbol.*;
import ghidra.program.model.util.*;
import ghidra.util.exception.*;
public class DumpEtwWrites extends GhidraScript {
// **********************
// Configurable Settings
// quickscan: stop processing after maxEvents have been found, or extraCallDepth/maxExportCallDepth has been reached
private Boolean quickScan = true;
// maxEvents: maximum events to report per API
private int maxEvents = 100;
// maxCallDepth: maximum call depth to search for events
private int maxCallDepth = 5;
// extraCallDepth: maximum additional call depth to search for events
private int extraCallDepth = 1;
// maxExportCallDepth: maximum depth of exported functions to search
private int maxExportCallDepth = 0;
// debugPrint: verbose logging
private Boolean debugPrint = false;
// decompileTimeoutSeconds: per-function timeout for Ghidra decompilation
private int decompileTimeoutSeconds = 60;
// **********************
private String functionsFile = "functions.txt"; // analyse these functions
private String ignoreFile = "ignore.txt"; // ignore these functions
private DataType eventDescriptorType = null;
private DataType ucharType = null;
private DataType ushortType = null;
private DataType ulonglongType = null;
private DataType guidType = null;
private DataType stringType = null;
private DecompInterface decomplib = null;
private Set<String> exports = null;
private Set<String> functions = null;
private Set<String> ignored = null;
private PrintWriter csv = null;
private Dictionary<Long,Pair<String,String>> providerGuidMap = new Hashtable<Long,Pair<String,String>>(); // Address, (Guid, GuidSymbol)
private List<String> notYetImplemented = new LinkedList<String>();
@Override
public void run() throws Exception {
printf("\n\n--==[ DumpEtwWrites ]==--\n");
printf(" * %s\n", currentProgram.getName());
if(quickScan)
printf(" * quick scan mode - maxCallDepth=%d extraCallDepth=%d maxExportCallDepth=%d\n", maxCallDepth, extraCallDepth, maxExportCallDepth);
else
printf(" * full scan mode - finding all reachable ETW writes\n");
// we want the names of all exports - as we use these as a measure of relevance
// for a given ETW write
exports = new HashSet<String>();
for(Symbol symbol : currentProgram.getSymbolTable().getAllSymbols(false))
if (symbol.isExternalEntryPoint())
exports.add(symbol.getName());
printf(" * found %d exports\n", exports.size());
// provide a list of the functions that you want to analyse, finding the ETW writes
// if not provided, all exports will be parsed
// e.g. this could be the list of Native API syscalls
// or a list of RPC methods e.g. using xpn's RpcEnum
try {
functions = new HashSet<String>(Files.readAllLines(Paths.get(functionsFile)));
printf(" * analysing %d functions from %s\n", functions.size(), FileSystems.getDefault().getPath(functionsFile));
}
catch(Exception e) {
if(exports.contains("NtQuerySystemInformation")) {
functions = new HashSet<String>();
for(String func : exports) {
if(func.startsWith("Nt"))
functions.add(func);
if(func.startsWith("Zw"))
functions.add(func.replaceFirst("Zw", "Nt"));
}
for(String func : functions)
if(func.startsWith("Nt"))
exports.add(func);
printf(" * %s not provided - analysing all %d syscalls instead\n", functionsFile, functions.size());
} else {
functions = exports;
printf(" * %s not provided - analysing all %d exports instead\n", functionsFile, functions.size());
}
Files.write(FileSystems.getDefault().getPath("exports.txt"), exports);
}
// optionally provide a list of functions you want to ignore
// e.g. common error handling functions like KeBugCheckEx
try {
ignored = new HashSet<String>(Files.readAllLines(Paths.get(ignoreFile)));
printf(" * ignoring %d functions\n", ignored.size());
}
catch(Exception e)
{
ignored = new HashSet<String>();
}
// prepare the output file
File csvFile = new File(currentProgram.getName() + ".csv");
csvFile.delete();
printf(" * output will be written to %s\n", csvFile.getAbsolutePath());
csv = new PrintWriter(csvFile);
csv.println("Function,ProviderGuid,ProviderSymbol,ReghandleSymbol,WriteFunction,EventDescriptorSymbol,Id,Version,Channel,Level,Opcode,Task,Keyword,ContainingFunction,CallDepth,ExportedCallDepth,CallPath");
setUpDataTypes();
setUpDecompiler(currentProgram);
if (!decomplib.openProgram(currentProgram)) {
println("Decompiler Setup Error: " + decomplib.getLastMessage());
return;
}
try {
/* first we cache the REGHANDLE address and the GUID of all register ETW Providers so that we can later
* match ETW events to the Provider GUIDs
*
* providers are registered via [Etw|Event]Register(LPCGUID ProviderId, .., .., PREGHANDLE RegHandle)
*
* https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-etwregister
* https://docs.microsoft.com/en-us/windows/win32/api/evntprov/nf-evntprov-eventregister
*/
for(String etwRegisterFuncName : etwRegisterFuncs) {
List<Function> etwRegisterFuncList = getGlobalFunctions(etwRegisterFuncName);
if(etwRegisterFuncList.size() > 1) {
println("Script aborted: Found " + etwRegisterFuncList.size() + " instances of " + etwRegisterFuncName);
return;
}
if(etwRegisterFuncList.size() == 0)
continue;
Function etwRegisterFunc = etwRegisterFuncList.get(0);
Reference[] refs = this.getSymbolAt(etwRegisterFunc.getEntryPoint()).getReferences(null);
printf(" * found %d %s calls\n", refs.length, etwRegisterFuncName);
for (Reference ref : refs) {
if (monitor.isCancelled())
break;
analyseEtwRegisterCall(ref);
}
}
/* now for each function, output the parameters of all ETW writes ( GUID, Event Id etc)
*/
for(String functionName : functions) {
List<Function> functionList = getGlobalFunctions(functionName);
if(functionList.size() == 0) {
printf(" * %s - function not found\n", functionName);
continue;
}
if(functionList.size() > 1)
throw new Exception("Script aborted: Found " + functionList.size() + " instances of " + functionName);
// decompile function & output ETW writes
analyseFunction(functionList.get(0));
}
}
finally {
decomplib.dispose();
csv.close();
}
// if this isn't empty, then I haven't implemented all possible code paths yet :-(
if (notYetImplemented.size() > 0)
printf(" ---------- TODO ----------\n");
for(String todo : notYetImplemented) {
printf("%s\n", todo);
}
}
/*
* EtwRegister - cache all global REGHANDLE addresses and registration details
*/
List<String> etwRegisterFuncs = Arrays.asList("EtwRegister", "EventRegister", "EtwEventRegister", "EtwNotificationRegister", "EventNotificationRegister", "EtwEventNotificationRegister");
public void analyseEtwRegisterCall(Reference ref) throws Exception {
Address refAddr = ref.getFromAddress();
if (refAddr == null)
throw new NotFoundException("Reference.getFromAddress() == null");
if(refAddr.getOffset() == 0)
return;
// skip 'data' references - e.g. import / export offsets
Data refData = getDataAt(refAddr);
if (refData == null)
refData = getDataContaining(refAddr);
if (refData != null &&
(refData.getDataType().toString().startsWith("_IMAGE_RUNTIME_FUNCTION_ENTRY") ||
refData.getDataType().toString().startsWith("GuardCfgTableEntry") ||
refData.getDataType().isEquivalent(new IBO32DataType()) ||
refData.getDataType().isEquivalent(new DWordDataType())))
return;
Function refFunc = currentProgram.getFunctionManager().getFunctionContaining(refAddr);
if (refFunc == null) {
int transactionID = currentProgram.startTransaction("attempting findFunctionEntry()");
CreateFunctionCmd createCmd = new CreateFunctionCmd(refAddr, true);
createCmd.applyTo(currentProgram);
currentProgram.endTransaction(transactionID, true);
refFunc = currentProgram.getFunctionManager().getFunctionContaining(refAddr);
}
if (refFunc == null)
// programmatic resolution failed - user should try manually finding and defining the function
throw new NotFoundException("getFunctionContaining == null; refAddr=" + refAddr);
ClangTokenGroup cCode = decomplib.decompileFunction(refFunc, decompileTimeoutSeconds, monitor).getCCodeMarkup();
if (cCode == null)
throw new Exception("[CALL EtwRegister] Decompile Error: " + decomplib.getLastMessage());
try {
boolean found = cacheProviderReghandle(refFunc, cCode, refAddr);
if(!found) {
// Could not resolve provider GUID(s) yet.
// :TODO: Search a level deeper.
Reference[] refRefs = this.getSymbolAt(refFunc.getEntryPoint()).getReferences(null);
logTODO("Search the " + refRefs.length + " calls to " + refFunc.getName() + " for EtwRegister calls");
}
} catch(NotYetImplementedException e) {
logTODO(e.getMessage());
}
}
private boolean cacheProviderReghandle(Function f, ClangNode astNode, Address refAddr) throws Exception {
if(astNode == null || astNode.getMinAddress() == null)
return false; // leaf node
if (astNode.getMaxAddress() == null)
throw new InvalidInputException("ClangNode.getMaxAddress() is null");
boolean found = false;
Stack<Function> callPath = new Stack<Function>(); // helps with back tracing constants, and determining relevance
callPath.push(f);
// have we found the call(s) yet?
if (refAddr.getPhysicalAddress().equals(astNode.getMaxAddress()) && astNode instanceof ClangStatement) {
ClangStatement stmt = (ClangStatement) astNode;
PcodeOp pcodeOp = stmt.getPcodeOp();
if (pcodeOp.getOpcode() == PcodeOp.CALL) {
long callAddress = astNode.getMaxAddress().getOffset();
String etwRegisterCall = getFunctionAt(pcodeOp.getInput(0).getAddress()).getName();
List<Long> pGuids = null;
List<Long> reghandles = new LinkedList<Long>();
// we need to pass the calling function in order to back trace through any parameters
Stack<Function> callingFunc = new Stack<Function>();
callingFunc.push(f);
debugPrintf("%s :: %s\n", refAddr.toString(), stmt);
if(etwRegisterCall.endsWith("NotificationRegister")) {
// NTSTATUS EtwNotificationRegister (LPCGUID Guid, ULONG Type, PETW_NOTIFICATION_CALLBACK Callback, PVOID Context, PREGHANDLE RegHandle);
throw new NotYetImplementedException(etwRegisterCall);
}
if(f.getName().startsWith("TraceLogging"))
{
if(pcodeOp.getNumInputs() == 0) {
printf("[WARNING] Incomplete Decompilation @ 0x%x - %s\n", callAddress, stmt.toString());
return false;
}
// TraceLoggingRegisterEx_EtwRegister_EtwSetInformation(PTLGREG param_1, ...)
List<Long> tlgregs = null;
try {
// Only the first parameter is needed
// It points to an undocumented TraceLogging provider registration struct.
tlgregs = resolveToConstant(1, callingFunc);
} catch (NotFoundException e) {
printf(" --> skipping %s due to local variable storage @ 0x%x\n", f.getName(), callAddress);
return true;
}
printf(" * found %d TraceLoggingRegister calls\n", tlgregs.size());
for(int i=0; i < tlgregs.size(); i++) {
Long tlgreg = tlgregs.get(i);
// At offset 8 of the TLG registration is a pointer to the TLG provider metadata
Long tlgprov = getLong(toAddr(tlgreg + 8));
// The provider guid is at offset -0x10
Address guidAddr = toAddr(tlgprov - 0x10);
clearListing(guidAddr, guidAddr.add(guidType.getLength()-1));
createData(guidAddr, guidType);
String guid = getDataAt(guidAddr).toString().substring(5);
// The provider name is at offet +2
Address nameAddr = toAddr(tlgprov + 2);
clearListing(nameAddr);
createData(nameAddr, stringType);
String providerName = getDataAt(nameAddr).toString().substring(3); // strip type
// The REGHANDLE will be saved at offset 0x20
Long reghandle = tlgreg + 0x20;
printf(" --> cached TraceLoggingRegister(%s, %s)\n", guid, providerName);
providerGuidMap.put(reghandle, new Pair<String,String>(guid, providerName));
}
return true;
}
if(etwRegisterCall.startsWith("Etw") || etwRegisterCall.startsWith("Event")) {
if(pcodeOp.getNumInputs() < 5) {
printf("[WARNING] Incomplete Decompilation @ 0x%x - %s\n", callAddress, stmt.toString());
return false;
}
try {
pGuids = resolveFunctionParameterToConstant(pcodeOp, 1, callingFunc);
} catch (NotFoundException e) {
printf(" --> skipping %s as guid not found @ 0x%x\n", etwRegisterCall, callAddress);
return false;
}
try {
reghandles = resolveFunctionParameterToConstant(pcodeOp, 4, callingFunc);
} catch (NotFoundException e) {
// a global REGHANDLE address was not found
// assume local only use - and cache the containing function as the address
debugPrintf("local REGHANDLE @ 0x%x\n", callAddress);
reghandles.add(f.getEntryPoint().getOffset());
}
}
// :TODO: better guarantee the (guid, reghandle) correlation?
if(pGuids.size() != reghandles.size())
throw new NotFoundException("ETW register parameter list size mismatch");
for(int i = 0; i < pGuids.size(); i++) {
long pGuid = pGuids.get(i);
String guid = "";
String guidSymbol = "";
if(pGuid != 0) {
Address guidAddr = toAddr(pGuid);
clearListing(guidAddr, guidAddr.add(guidType.getLength()-1));
createData(guidAddr, guidType);
guid = getDataAt(guidAddr).toString().substring(5); // strip GUID_ prefix
guidSymbol = SymbolAt(pGuid);
}
long reghandle = reghandles.get(i);
if(reghandle != 0 && pGuid != 0) {
printf(" --> cached %s(%s, %s)\n", etwRegisterCall, guid, guidSymbol);
providerGuidMap.put(reghandle, new Pair<String,String>(guid, guidSymbol));
found = true;
}
}
return found; // CALL found - stop looking
}
}
// otherwise traverse children to find call(s)
for (int j = 0; j < astNode.numChildren(); j++) {
found |= cacheProviderReghandle(f, astNode.Child(j), refAddr);
}
return found;
}
/*
* functions of interest
*/
List<String> etwWriteFuncs = Arrays.asList("EtwWrite", "EventWrite", "EtwEventWrite", "EtwWriteEx", "EventWriteEx", "EtwEventWriteEx", "EtwWriteTransfer", "EventWriteTransfer", "EtwEventWriteTransfer", "EtwEventWriteFull", "EtwWriteStartScenario", "EventWriteStartScenario", "EtwEventWriteStartScenario", "EtwWriteEndScenario", "EventWriteEndScenario", "EtwEventWriteEndScenario", "EtwWriteString", "EventWriteString", "EtwEventWriteString", "EtwWriteNoRegistration", "EventWriteNoRegistration", "EtwEventWriteNoRegistration");
List<String> classicMessageFuncs = Arrays.asList("TraceMesssage", "EtwTraceMessage", "TraceMessageVa", "EtwTraceMessageVa");
List<String> classicEventFuncs = Arrays.asList("TraceEvent", "EtwTraceEvent", "TraceEventInstance", "EtwTraceEventInstance");
public void analyseFunction(Function func) throws Exception {
Queue<QueuedFunction> queue = new LinkedList<QueuedFunction>();
List<String> processed = new LinkedList<String>();
Stack<Function> callPath = new Stack<Function>(); // helps with back tracing constants, and determining relevance
callPath.push(func);
int eventCount = 0;
int depth = 0;
int exportDepth = 0;
int maxLocalCallDepth = maxCallDepth;
String lastParameters = null;
// find all reachable ETW writes
for(Function calledFunction : func.getCalledFunctions(monitor))
queue.add(new QueuedFunction(calledFunction, func, 1, 0, callPath));
while (queue.size() != 0) {
if (monitor.isCancelled())
break;
QueuedFunction next = queue.remove();
Function thisFunction = next.queuedFunction;
Function callingFunction = next.callingFunction;
depth = next.callDepth;
exportDepth = next.exportedCallDepth;
callPath = next.callPath;
String funcName = thisFunction.getName();
String containingFunction = callingFunction.getName();
if( containingFunction.startsWith("FUN_")) {
// Search for the first symbol in the call stack
Stack<Function> stack = (Stack<Function>) callPath.clone();
while(containingFunction.startsWith("FUN_"))
containingFunction = stack.pop().getName();
}
if (processed.contains(funcName) || ignored.contains(funcName))
continue;
if(quickScan && (depth > maxLocalCallDepth || exportDepth > maxExportCallDepth || eventCount == maxEvents))
continue;
if(funcName.startsWith("_tlgWrite")) {
ClangTokenGroup cCode = decomplib.decompileFunction(callingFunction, decompileTimeoutSeconds, monitor).getCCodeMarkup();
if (cCode == null)
throw new Exception("[CALL _tlgWrite] Decompile Error: " + decomplib.getLastMessage());
List<StringBuffer> tlgWriteParametersList = new LinkedList<StringBuffer>();
try {
getTlgWriteParameters(funcName, cCode, tlgWriteParametersList, callPath, 0);
for(StringBuffer tlgWriteParameters : tlgWriteParametersList) {
if(tlgWriteParameters.toString().equals(lastParameters))
continue; // remove duplicates
lastParameters = tlgWriteParameters.toString();
csv.printf("%s,%s,%s,%d,%d,%s\n", func.getName(), tlgWriteParameters, containingFunction.replace(',','-'), depth, exportDepth, callPath.toString().replace(',','-').replace(' ','>') );
eventCount++;
maxLocalCallDepth = Math.min(maxLocalCallDepth, depth + extraCallDepth);
}
} catch(NotFoundException e) {
logTODO(e.getMessage());
} catch(NotYetImplementedException e) {
logTODO(e.getMessage());
}
}
else if(classicEventFuncs.contains(funcName)) {
logTODO("Implement classic provider support for " + containingFunction);
}
else if(classicMessageFuncs.contains(funcName)) {
List<String> wppWriteParametersList = getWppWriteParameters(funcName, callingFunction, callPath);
for(String wppWriteParameters : wppWriteParametersList) {
csv.printf("%s,%s,%s,%d,%d,%s\n", func.getName(), wppWriteParameters, containingFunction.replace(',','-'), depth, exportDepth, callPath.toString().replace(',','-').replace(' ','>') );
eventCount++;
maxLocalCallDepth = Math.min(maxLocalCallDepth, depth + extraCallDepth);
}
}
else if(etwWriteFuncs.contains(funcName)) {
ClangTokenGroup cCode = decomplib.decompileFunction(callingFunction, decompileTimeoutSeconds, monitor).getCCodeMarkup();
if (cCode == null)
throw new Exception("[CALL EtwWrite] Decompile Error: " + decomplib.getLastMessage());
List<StringBuffer> etwWriteParametersList = new LinkedList<StringBuffer>();
try {
getEtwWriteParameters(funcName, cCode, etwWriteParametersList, callPath, 0);
for(StringBuffer etwWriteParameters : etwWriteParametersList) {
if(etwWriteParameters.toString().equals(lastParameters))
continue; // remove duplicates
lastParameters = etwWriteParameters.toString();
csv.printf("%s,%s,%s,%d,%d,%s\n", func.getName(), etwWriteParameters, containingFunction.replace(',','-'), depth, exportDepth, callPath.toString().replace(',','-').replace(' ','>') );
eventCount++;
maxLocalCallDepth = Math.min(maxLocalCallDepth, depth + extraCallDepth);
}
} catch(NotFoundException e) {
logTODO(e.getMessage());
} catch(NotYetImplementedException e) {
logTODO(e.getMessage());
}
}
// Handling classic kernel events via this wrapper function adds more context
else if(funcName.equals("EtwTraceKernelEvent")) {
List<String> kernelEventParametersList = getTraceKernelEventParameters(funcName, callingFunction, callPath);
for(String kernelEventParameters : kernelEventParametersList) {
if(kernelEventParameters.toString().equals(lastParameters))
continue; // remove duplicates
lastParameters = kernelEventParameters.toString();
csv.printf("%s,%s,%s,%d,%d,%s\n", func.getName(), kernelEventParameters, containingFunction.replace(',','-'), depth, exportDepth, callPath.toString().replace(',','-').replace(' ','>') );
eventCount++;
maxLocalCallDepth = Math.min(maxLocalCallDepth, depth + extraCallDepth);
}
}
else {
String functionCrumb = func.getName();
if(functionCrumb.length() > 5)
functionCrumb = functionCrumb.substring(2, functionCrumb.length() - 5);
if(exports.contains(funcName) && !funcName.contains(functionCrumb))
exportDepth++;
processed.add(funcName);
for(Function calledFunction : thisFunction.getCalledFunctions(monitor)) {
if(calledFunction == null)
throw new Exception("Argh!");
if(calledFunction.getName() == null)
createFunction(calledFunction.getEntryPoint(), null);
if(calledFunction.getName() == null)
throw new Exception("FUN_" + calledFunction.getEntryPoint().toString() + " is not defined");
callPath = (Stack<Function>) next.callPath.clone();
if(funcName.startsWith("FUN_"))
queue.add(new QueuedFunction(calledFunction, thisFunction, depth, exportDepth, callPath));
else {
callPath.add(thisFunction);
queue.add(new QueuedFunction(calledFunction, thisFunction, depth+1, exportDepth, callPath));
}
}
}
}
printf(" * %s - found %d events in %d functions. callDepth=%d exportDepth=%d\n",
func.getName(), eventCount, processed.size(), maxLocalCallDepth, exportDepth);
csv.flush();
}
private boolean getEtwWriteParameters(String etwWriteCall, ClangNode node, List<StringBuffer> etwWriteParametersList, Stack<Function> callPath, int depth) throws Exception {
if(node == null || node.getMinAddress() == null)
return false; // leaf node
if (node.getMaxAddress() == null)
throw new InvalidInputException("ClangNode.getMaxAddress() is null");
boolean found = false;
// have we found the right CALL yet?
if(node instanceof ClangStatement) {
ClangStatement stmt = (ClangStatement) node;
PcodeOp pcodeOp = stmt.getPcodeOp();
if (pcodeOp != null &&
pcodeOp.getOpcode() == PcodeOp.CALL &&
getSymbolAt(pcodeOp.getInput(0).getAddress()) != null &&
getSymbolAt(pcodeOp.getInput(0).getAddress()).getName().endsWith(etwWriteCall)) {
if(pcodeOp.getNumInputs() < 3) {
printf("[WARNING] Incomplete Decompilation @ 0x%x - %s\n", node.getMaxAddress().getOffset(), stmt.toString());
}
debugPrintf("%s :: %s\n", callPath.peek().toString(), stmt);
if(etwWriteCall.endsWith("WriteNoRegistration")) {
// NTSTATUS EtwEventWriteNoRegistration (PCGUID ProviderId, PCEVENT_DESCRIPTOR EventDescriptor, ULONG UserDataCount, PEVENT_DATA_DESCRIPTOR UserData);
throw new NotYetImplementedException("EtwEventWriteNoRegistration");
}
long reghandle = 0;
if(pcodeOp.getNumInputs() > 1) {
List<Long> reghandles = null;
try
{
reghandles = resolveFunctionParameterToConstant(pcodeOp, 1, callPath);
if(reghandles.size() == 0)
throw new NotFoundException("ETW write with no REGHANDLE");
if(reghandles.size() > 1)
throw new NotYetImplementedException("ETW write with multiple REGHANDLE");
reghandle = reghandles.get(0);
}
catch (NotFoundException e)
{
debugPrintf("ETW write REGHANDLE resolves to local variable in " + callPath.peek());
// Attempt lookup via function address instead
reghandle = callPath.peek().getEntryPoint().getOffset();
}
catch (NotYetImplementedException e) {
// non fatal
logTODO("Handle REGHANDLE in " + e.getMessage());
}
}
String providerGuid = "???";
String providerSymbol = "";
String reghandleSymbol = SymbolAt(reghandle);
Pair<String,String> providerRegistration = providerGuidMap.get(reghandle);
if ( providerRegistration != null) {
providerGuid = providerRegistration.first;
providerSymbol = providerRegistration.second;
}
StringBuffer etwWriteParameters = new StringBuffer();
if(etwWriteCall.endsWith("WriteString")) {
// NTSTATUS EtwWriteString(REGHANDLE RegHandle, UCHAR Level, ULONGLONG Keyword, LPCGUID ActivityId, PCWSTR String)
etwWriteParameters.append(providerGuid + ",");
etwWriteParameters.append(providerSymbol + ",");
etwWriteParameters.append(reghandleSymbol + ",");
etwWriteParameters.append(etwWriteCall + ",");
List<Long> levels = resolveFunctionParameterToConstant(pcodeOp, 2, callPath);
List<Long> keywords = resolveFunctionParameterToConstant(pcodeOp, 3, callPath);
List<Long> strings = resolveFunctionParameterToConstant(pcodeOp, 5, callPath);
if(levels.size() + keywords.size() + strings.size() != 3)
throw new NotYetImplementedException("EtwWriteString with multiple paths");
etwWriteParameters.append(",,,,"+ levels.get(0) + ",,," + keywords.get(0));
// :TODO: output (PCWSTR String) parameter
logTODO(etwWriteCall);
return true;
}
// NTSTATUS EtwWrite*(REGHANDLE RegHandle, PCEVENT_DESCRIPTOR EventDescriptor, LPCGUID ActivityId, ULONG UserDataCount, PEVENT_DATA_DESCRIPTOR UserData);
Address event = null;
if(pcodeOp.getNumInputs() > 2) {
List<Long> pEvents = new LinkedList<Long>();
try
{
debugPrintf("resolveFunctionParameterToConstant(2)\n");
pEvents = resolveFunctionParameterToConstant(pcodeOp, 2, callPath);
if(pEvents.size() == 0)
logTODO("EtwWrite EVENT_DESCRIPTOR not found in " + callPath.peek());
}
catch (NotFoundException e)
{
logTODO("EtwWrite EVENT_DESCRIPTOR not found in " + callPath.peek());
etwWriteParameters = new StringBuffer();
etwWriteParameters.append(providerGuid + ",");
etwWriteParameters.append(providerSymbol + ",");
etwWriteParameters.append(reghandleSymbol + ",");
etwWriteParameters.append(etwWriteCall + ",");
etwWriteParameters.append(",,,,,,,"); // not found
etwWriteParametersList.add(etwWriteParameters);
}
catch (NotYetImplementedException e)
{
throw new NotYetImplementedException("EVENT_DESCRIPTOR " + e.getMessage());
}
for(long pEvent : pEvents) {
if(pEvent == 0)
continue; // a quirk of ghidra's decompilation? Or because of initialise to zero and error paths?
etwWriteParameters = new StringBuffer();
etwWriteParameters.append(providerGuid + ",");
etwWriteParameters.append(providerSymbol + ",");
etwWriteParameters.append(reghandleSymbol + ",");
etwWriteParameters.append(etwWriteCall + ",");
String eventDescriptorSymbol = SymbolAt(pEvent);
etwWriteParameters.append(eventDescriptorSymbol + ",");
event = toAddr(pEvent);
clearListing(event, event.add(eventDescriptorType.getLength()-1));
try {
createData(event, eventDescriptorType);
appendStructure(event, etwWriteParameters, true);
}
catch(CodeUnitInsertionException e)
{
debugPrintf("EVENT_DESCRIPTOR parsing failed @ 0x%x", pEvent);
etwWriteParameters.append(",,,,,,");
}
etwWriteParametersList.add(etwWriteParameters);
}
}
found = true;
}
}
// search children until call(s) found
for (int j = 0; j < node.numChildren(); j++)
found |= getEtwWriteParameters(etwWriteCall, node.Child(j), etwWriteParametersList, callPath, depth + 1);
if(!found && depth == 0)
throw new Exception("didn't find " + etwWriteCall);
return found;
}
private boolean getTlgWriteParameters(String tlgWriteCall, ClangNode node, List<StringBuffer> tlgWriteParametersList, Stack<Function> callPath, int depth) throws Exception {
if(node == null || node.getMinAddress() == null)
return false; // leaf node
if (node.getMaxAddress() == null)
throw new InvalidInputException("ClangNode.getMaxAddress() is null");
boolean found = false;
// have we found the right CALL yet?
if(node instanceof ClangStatement) {
ClangStatement stmt = (ClangStatement) node;
PcodeOp pcodeOp = stmt.getPcodeOp();
if (pcodeOp != null &&
pcodeOp.getOpcode() == PcodeOp.CALL &&
getSymbolAt(pcodeOp.getInput(0).getAddress()) != null &&
getSymbolAt(pcodeOp.getInput(0).getAddress()).getName().endsWith(tlgWriteCall)) {
if(pcodeOp.getNumInputs() < 2) {
printf("[WARNING] Incomplete Decompilation @ 0x%x - %s\n", node.getMaxAddress().getOffset(), stmt.toString());
}
found = true;
if(tlgWriteCall.startsWith("_tlgWriteEx"))
tlgWriteCall = "_tlgWriteEx";
else if(tlgWriteCall.startsWith("_tlgWriteTransfer"))
tlgWriteCall = "_tlgWriteTransfer";
debugPrintf("%s :: %s\n", tlgWriteCall, stmt);
// _tlgWrite(PTLG_REGISTRATION, PTLG_EVENT, ...)
long reghandle = 0;
if(pcodeOp.getNumInputs() > 1) {
List<Long> reghandles = null;
try
{
reghandles = resolveFunctionParameterToConstant(pcodeOp, 1, callPath);
if(reghandles.size() == 0)
throw new NotFoundException("TLG write with no REGHANDLE");
if(reghandles.size() > 1)
throw new NotYetImplementedException("TLG write with multiple REGHANDLE");
// REGHANDLE is at offset 0x20 in TLG_REGISTRATION
reghandle = reghandles.get(0) + 0x20;
}
catch (NotFoundException e)
{
// non fatal
logTODO("_tlgWrite REGHANDLE not found in " + callPath.peek());
}
catch (NotYetImplementedException e) {
// non fatal
logTODO("REGHANDLE " + e.getMessage());
}
}
String providerGuid = "???";
String providerName = "";
Pair<String,String> providerRegistration = providerGuidMap.get(reghandle);
if ( providerRegistration != null) {
providerGuid = providerRegistration.first;
providerName = providerRegistration.second;
}
String reghandleSymbol = SymbolAt(reghandle);
if(reghandleSymbol.startsWith("DAT_"))
reghandleSymbol = "";
if(pcodeOp.getNumInputs() > 2) {
List<Long> pTlgEvents = null; // TLG_EVENT pointers
try
{
pTlgEvents = resolveFunctionParameterToConstant(pcodeOp, 2, callPath);
}
catch (NotFoundException e)
{
throw new NotYetImplementedException("TLG write EVENT_DESCRIPTOR resolves to local variable in " + callPath.peek()); // :TODO:
}
catch (NotYetImplementedException e)
{
throw new NotYetImplementedException("EVENT_DESCRIPTOR " + e.getMessage());
}
if(pTlgEvents.size() == 0)
throw new NotFoundException("TLG write with no EVENT_DESCRIPTOR");
for(long pEvent : pTlgEvents) {
if(pEvent == 0)
continue; // a quirk of ghidra's decompilation? Or because of initialise to zero and error paths?
StringBuffer tlgWriteParameters = new StringBuffer();
tlgWriteParameters.append(providerGuid + ",");
tlgWriteParameters.append(providerName + ",");
tlgWriteParameters.append(reghandleSymbol + ","); // usually empty for TLG
tlgWriteParameters.append(tlgWriteCall + ",");
// https://posts.specterops.io/data-source-analysis-and-dynamic-windows-re-using-wpp-and-tracelogging-e465f8b653f7
// UCHAR Channel
// UCHAR Level
// UCHAR OpCode
// UINT64 Keyword
// UINT16 Size
// UCHAR Zero
// CSTR EventName
Byte channel = getByte(toAddr(pEvent));
Byte level = getByte(toAddr(pEvent + 1));
Byte opcode = getByte(toAddr(pEvent + 2));
Long keyword = getLong(toAddr(pEvent + 3));
Address nameAddr = toAddr(pEvent + 15);
clearListing(nameAddr);
createData(nameAddr, stringType);
String eventName = getDataAt(nameAddr).toString().substring(3); // strip type
// TraceLogging doesn't have equivalent fields for id, task and version.
tlgWriteParameters.append(eventName + ",");
tlgWriteParameters.append("-,-,"); // Id, Version
tlgWriteParameters.append(channel + ",");
tlgWriteParameters.append(level + ",");
tlgWriteParameters.append(opcode + ",");
tlgWriteParameters.append("-,"); // Task
tlgWriteParameters.append(String.format("0x%x", keyword));
tlgWriteParametersList.add(tlgWriteParameters);
}
}
else
{
StringBuffer tlgWriteParameters = new StringBuffer();
tlgWriteParameters.append(providerGuid + ",");
tlgWriteParameters.append(providerName + ",");
tlgWriteParameters.append(reghandleSymbol + ",");
tlgWriteParameters.append(tlgWriteCall + ",");
tlgWriteParameters.append(",,,,,,,");
tlgWriteParametersList.add(tlgWriteParameters);
}
}
}
// search children until call(s) found
for (int j = 0; j < node.numChildren(); j++)
found |= getTlgWriteParameters(tlgWriteCall, node.Child(j), tlgWriteParametersList, callPath, depth + 1);
if(!found && depth == 0)
throw new Exception("didn't find " + tlgWriteCall);
return found;
}
private List<String> getWppWriteParameters(String wppWriteCall, Function callingFunction, Stack<Function> callPath) throws Exception {
HighFunction hf = decomplib.decompileFunction(callingFunction, decompileTimeoutSeconds, monitor).getHighFunction();
if (hf == null)
throw new Exception("[CALL WppWrite] Decompile Error: " + decomplib.getLastMessage());
List<String> wppWriteParametersList = new LinkedList<String>();
boolean found = false;
Iterator<PcodeOpAST> ops = hf.getPcodeOps();
while (ops.hasNext() && !monitor.isCancelled()) {
PcodeOpAST pcodeOp = ops.next();
if (pcodeOp.getOpcode() == PcodeOp.CALL &&
getSymbolAt(pcodeOp.getInput(0).getAddress()) != null &&
getSymbolAt(pcodeOp.getInput(0).getAddress()).getName().endsWith(wppWriteCall)) {
if(pcodeOp.getNumInputs() < 4) {
printf("[WARNING] Incomplete Decompilation of " + callingFunction.getName());
}
// ULONG TraceMessage(TRACEHANDLE LoggerHandle, ULONG MessageFlags, LPCGUID MessageGuid, USHORT MessageNumber, ...);
StringBuffer wppWriteParameters = new StringBuffer();
found = true;
try {
long tracehandle = resolveParameterToConstant(pcodeOp, wppWriteCall, "TRACEHANDLE", 1, callPath);
long messageFlags = resolveParameterToConstant(pcodeOp, wppWriteCall, "MessageFlags", 2, callPath);
long _messageGuid = resolveParameterToConstant(pcodeOp, wppWriteCall, "MessageGuid", 3, callPath);
long messageId = pcodeOp.getNumInputs() == 4 ? 0 : resolveParameterToConstant(pcodeOp, wppWriteCall, "MessageId", 4, callPath);
String providerGuid = "???";
String providerSymbol = "";
String reghandleSymbol = SymbolAt(tracehandle);
Pair<String,String> providerRegistration = providerGuidMap.get(tracehandle);
if ( providerRegistration != null) {
providerGuid = providerRegistration.first;
providerSymbol = providerRegistration.second;
}
String messageGuid = "???";
Pair<String,String> guidRegistration = providerGuidMap.get(_messageGuid);
if ( guidRegistration != null)
messageGuid = guidRegistration.first;
wppWriteParameters.append("WPP_"+providerGuid + ",");
wppWriteParameters.append(providerSymbol + ",");
wppWriteParameters.append(reghandleSymbol + ",");
wppWriteParameters.append(wppWriteCall + ",");
wppWriteParameters.append(messageGuid + ","); // EventDescriptorSymbol
wppWriteParameters.append(messageId + ","); // Id
wppWriteParameters.append(",,,,,"); // Version,Channel,Level,Opcode,Task,
wppWriteParameters.append("Flags=" + messageFlags); // Keyword
} catch(NotFoundException e) {
wppWriteParameters.append(",,,,,,,,,,,");
}
wppWriteParametersList.add(wppWriteParameters.toString());
}
}
if(!found)
throw new NotFoundException("didn't find any " + wppWriteCall + " calls in " + callPath.peek());
return wppWriteParametersList;
}
private List<String> getTraceKernelEventParameters(String funcName, Function callingFunction, Stack<Function> callPath) throws Exception {
HighFunction hf = decomplib.decompileFunction(callingFunction, decompileTimeoutSeconds, monitor).getHighFunction();
if (hf == null)
throw new Exception("[CALL " + funcName + "] Decompile Error: " + decomplib.getLastMessage());
List<String> parametersList = new LinkedList<String>();
boolean found = false;
Iterator<PcodeOpAST> ops = hf.getPcodeOps();
while (ops.hasNext() && !monitor.isCancelled()) {
PcodeOpAST pcodeOp = ops.next();
if (pcodeOp.getOpcode() == PcodeOp.CALL &&
getSymbolAt(pcodeOp.getInput(0).getAddress()) != null &&
getSymbolAt(pcodeOp.getInput(0).getAddress()).getName().endsWith(funcName)) {
if(pcodeOp.getNumInputs() < 3) {
printf("[WARNING] Incomplete Decompilation of " + callingFunction.getName());
}
StringBuffer parameters = new StringBuffer();
found = true;
parameters.append("Windows Kernel Trace,");
try {
// EtwTraceKernelEvent(PEVENT_DESCRIPTOR, UINT32, PERFINFO_GROUPMASK, LOG_TYPE, UINT32)
long perfinfo = resolveParameterToConstant(pcodeOp, funcName, "PERFINFO_GROUPMASK", 3, callPath);
long logtype = resolveParameterToConstant(pcodeOp, funcName, "LOG_TYPE", 4, callPath);
// If someone wants to reverse the format then more event metadata could likely be
// extracted from the 1st, 2nd and 5th parameters.
parameters.append(LookupPerfInfoMask(perfinfo) + ",");
parameters.append(LookupTraceGroup(logtype) + ",");
parameters.append(funcName + ",");
parameters.append(LookupLogType(logtype) + ",");
parameters.append(",,,,,,"); // Id,Version,Channel,Level,Opcode,Task,Keyword
} catch(NotFoundException e) {
parameters.append(",,,,,,,,,,");
}
parametersList.add(parameters.toString());
}
}
if(!found)
throw new NotFoundException("didn't find any " + funcName + " calls in " + callPath.peek());
return parametersList;
}
// resolve an intermediate pcode call parameter to a list of possible constant values
public List<Long> resolveFunctionParameterToConstant(PcodeOp call, int paramIndex, Stack<Function> callPath) throws Exception {
if (call.getOpcode() != PcodeOp.CALL)
throw new InvalidInputException("Expected a CALL function");
Varnode calledFunc = call.getInput(0);
if (calledFunc == null || !calledFunc.isAddress())
throw new InvalidInputException("Invalid CALL PcodeOp");
if (paramIndex >= call.getNumInputs())
throw new InvalidInputException("Decompiler discovered insufficient parameters");
Varnode param = call.getInput(paramIndex);
if (param == null)
throw new NotFoundException("Missing Parameter");
// else process
return resolveVarnodeToConstant(param, callPath, 0);
}
// resolve a variable to a list of possible constant values
private List<Long> resolveVarnodeToConstant(Varnode node, Stack<Function> callPath, int astDepth) throws Exception {
if (node.isConstant())
return new LinkedList<Long>(Arrays.asList(node.getOffset()));
if (node.isAddress())
return new LinkedList<Long>(Arrays.asList(node.getAddress().getOffset()));
HighVariable hvar = node.getHigh();
if (hvar instanceof HighParam)
return resolveToConstant(((HighParam)hvar).getSlot() + 1, callPath);
if (hvar instanceof HighGlobal)
debugPrintf(":TODO: found a global... already handled?");
if (hvar instanceof HighLocal) {
// printf("### HighLocal " + callPath.peek().getName() + " node: " + node.getDef() + "\n");
return resolvePcodeOpToConstant(node.getDef(), callPath, astDepth);
}
if (hvar instanceof HighOther) {
///printf("### HighOther " + callPath.peek().getName() + " hvar: " + hvar + "\n");
///printf("### getRepresentative: " + hvar.getRepresentative().getDef() + "\n");
///printf("### getDef: " + node.getDef() + "\n");
if(hvar.getRepresentative().getDef() != null)