-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBoringSecretHunter.java
More file actions
1213 lines (990 loc) · 50.2 KB
/
BoringSecretHunter.java
File metadata and controls
1213 lines (990 loc) · 50.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
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
import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressSetView;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.listing.Data;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Listing;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.Memory;
import ghidra.program.model.symbol.Reference;
import ghidra.program.model.symbol.ReferenceIterator;
import ghidra.program.model.symbol.ReferenceManager;
import ghidra.program.model.listing.DataIterator;
import ghidra.program.model.mem.MemoryAccessException;
import ghidra.program.model.mem.MemoryBlock;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.listing.InstructionIterator;
import ghidra.program.model.symbol.Symbol;
import ghidra.program.model.symbol.SymbolTable;
import java.util.*;
public class BoringSecretHunter extends GhidraScript {
private static String identified_pattern = "";
// Custom implementation of Pair class
public class Pair<K, V> {
private final K first;
private final V second;
public Pair(K first, V second) {
this.first = first;
this.second = second;
}
public K getFirst() {
return first;
}
public V getSecond() {
return second;
}
}
private static final String VERSION = "1.2.1";
private static boolean DEBUG_RUN = false;
private static String LARGE_DUMP_MODE = "normal"; // "normal", "fast", or "skip"
public static boolean identifiedTls13 = false;
public static String tls13GhidraOffset = null;
public static String tls13IdaOffset = null;
public static String tls13BytePattern = null;
public static Function tls13label = null;
private void printBoringSecretHunterLogo() {
if(DEBUG_RUN){
System.out.println("[!] BoringSecretHunter Environment infos: ");
System.out.println("[!] Running on Java version: " + System.getProperty("java.version"));
System.out.println("[!] Current Ghidra version: " + currentProgram.getLanguage().getVersion()+"\n");
}
println("");
System.out.println("""
BoringSecretHunter
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⣀⣀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⠾⠛⢉⣉⣉⣉⡉⠛⠷⣦⣄⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⠋⣠⣴⣿⣿⣿⣿⣿⡿⣿⣶⣌⠹⣷⡀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⣼⠁⣴⣿⣿⣿⣿⣿⣿⣿⣿⣆⠉⠻⣧⠘⣷⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⢰⡇⢰⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀⠀⠈⠀⢹⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⢸⣿⠛⣿⣿⣿⣿⣿⣿⡿⠃⠀⠀⠀⠀⢸⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠈⣷⠀⢿⡆⠈⠛⠻⠟⠛⠉⠀⠀⠀⠀⠀⠀⣾⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣧⡀⠻⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⠃⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢼⠿⣦⣄⠀⠀⠀⠀⠀⠀⠀⣀⣴⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⣠⣾⣿⣦⠀⠀⠈⠉⠛⠓⠲⠶⠖⠚⠋⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣠⣾⣿⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⣠⣾⣿⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⣾⣿⣿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⣄⠈⠛⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
""");
System.out.println("Identifying the ssl_log_secret() function for extracting key material using Frida.");
System.out.println("Version: " + VERSION + " by Daniel Baier\n");
}
private int get_pointer_size(){
int pointer_size = 0x4;
String languageID = currentProgram.getLanguageID().toString();
if(languageID.contains("64")){
pointer_size = 0x8;
}
return pointer_size;
}
public void printTls13Info() {
if (!BoringSecretHunter.identifiedTls13) {
System.out.println("[-] TLS 1.3 pattern not yet identified.");
return;
}
System.out.println("[*] TLS 1.3 RusTLS:");
System.out.println("[*] Function label: " + tls13label.getName()+ " ("+ tls13label.toString() +")");
System.out.println("[*] Function offset (Ghidra): " + BoringSecretHunter.tls13GhidraOffset + " (0x" + BoringSecretHunter.tls13GhidraOffset + ")");
System.out.println("[*] Function offset (IDA with base 0x0): " + BoringSecretHunter.tls13IdaOffset + " (0x" + BoringSecretHunter.tls13IdaOffset + ")");
System.out.println("[*] Byte pattern for frida (friTap): " + BoringSecretHunter.tls13BytePattern);
}
/**
* Searches backward from 'target' in steps of 'pointerSize' to find
* the first address that has a reference (XREF) pointing to 'target'.
*
* @param program The current Program
* @param target The address (e.g. part of a string) for which we want to find a referencing pointer
* @return The address that references 'target', or null if none found
*/
private Address findBackwardsXref(Program program, Address target) {
int pointerSize = get_pointer_size();
ReferenceManager refMgr = program.getReferenceManager();
AddressSpace space = target.getAddressSpace();
long offset = target.getOffset();
// Keep stepping backwards by pointerSize until we go past the start of the address space
while (offset > space.getMinAddress().getOffset()) {
offset -= pointerSize;
Address candidate = space.getAddress(offset);
// Check if 'candidate' has references (XREFs) going TO 'target'
Reference[] fromRefs = refMgr.getReferencesFrom(candidate);
for (Reference ref : fromRefs) {
if (ref.getToAddress().equals(target)) {
// Found an address that references our target
return candidate;
}
}
}
// Alternative approach when the target address is not in the beginning
Address middle = target; // The offset you discovered in memory
Data data = getDataContaining(middle);
if (data == null) {
System.out.println("[-] No data item containing " + middle + " (IDA: 0x"+get_ida_address(middle)+")");
return null;
}
// 2) Ghidra's recognized data item might start earlier (e.g. 0x2e563)
Address dataStart = data.getMinAddress();
System.out.println("[*] Target starts at: " + dataStart + " (IDA: 0x"+get_ida_address(dataStart)+")");
// 3) Retrieve references to that start address
ReferenceManager refMgr1 = currentProgram.getReferenceManager();
ReferenceIterator refIter = refMgr1.getReferencesTo(dataStart);
if (refIter.hasNext() == false) {
System.out.println("[-] No references to " + dataStart + " (IDA: 0x"+get_ida_address(dataStart)+")");
} else {
while (refIter.hasNext()) {
Reference ref = refIter.next();
Address fromAddr = ref.getFromAddress();
//System.out.println(" " + fromAddr + " => " + dataStart + " (type: " + ref.getReferenceType() + ")");
// returning reference
return fromAddr;
}
}
return null; // none found
}
private void print_rustls_results(String tls12_pattern){
// TLS 1.3 BoringSecretHunter.identified_pattern;
print_max_pattern();
}
private boolean is_string_in_binary(String stringToFind){
Listing listing = currentProgram.getListing();
DataIterator dataIterator = listing.getDefinedData(true);
while (dataIterator.hasNext()) {
Data data = dataIterator.next();
if (data.getDataType().getName().equals("string") && data.getValue().toString().toLowerCase().contains(stringToFind.toLowerCase())) {
return true;
}
}
return false;
}
private void print_max_pattern(){
String identfied_byte_pattern = BoringSecretHunter.identified_pattern;
if(identfied_byte_pattern.length() > 140){
System.out.println("[*] Orignal pattern was too long! Our analysis showed that a pattern longer than 140 (47 hex bytes) is unable to identify the target function...");
System.out.println("[*] Byte pattern for frida (friTap) truncated version: " + identfied_byte_pattern.substring(0, 140));
}
}
private Pair<Set<Function>, Address> findStringUsage(String stringToFind) {
Set<Function> functions = new HashSet<>();
Address referenceAddress = null;
Listing listing = currentProgram.getListing();
DataIterator dataIterator = listing.getDefinedData(true);
while (dataIterator.hasNext()) {
Data data = dataIterator.next();
if (data.getDataType().getName().equals("string") && data.getValue().toString().toLowerCase().contains(stringToFind.toLowerCase())) {
Reference[] references = getReferencesTo(data.getAddress());
if(DEBUG_RUN){
System.out.println("[!] Found string \""+stringToFind+ "\"at location "+data.getAddress()+ " (IDA: 0x"+get_ida_address(data.getAddress())+")" +" with value "+data.getValue().toString());
}
for (Reference ref : references) {
referenceAddress = ref.getFromAddress(); // Store the reference address
Function func = getFunctionContaining(ref.getFromAddress());
if (func != null) {
functions.add(func);
}
}
}
}
return new Pair<>(functions, referenceAddress); // Return both the set of functions and the reference address
}
private boolean isARM32(){
String languageID = currentProgram.getLanguageID().toString();
String architecture_String = languageID.toString().toUpperCase();
boolean isARM32 = architecture_String.contains("ARM:LE:32");
return isARM32;
}
private MemoryBlock findRodataBlock() {
Memory memory = currentProgram.getMemory();
String[] sectionNames = {".rodata", ".rdata", "__cstring", "__const"};
for (String name : sectionNames) {
MemoryBlock block = memory.getBlock(name);
if (block != null) {
return block;
}
}
// Fallback for raw data dumps: return first readable block
for (MemoryBlock block : memory.getBlocks()) {
if (block.isRead()) {
if (DEBUG_RUN) {
System.out.println("[!] No named rodata section found, using block: " + block.getName());
}
return block;
}
}
return null;
}
private List<MemoryBlock> findAllRodataBlocks() {
Memory memory = currentProgram.getMemory();
String[] sectionNames = {".rodata", ".rdata", "__cstring", "__const"};
List<MemoryBlock> blocks = new ArrayList<>();
for (String name : sectionNames) {
MemoryBlock block = memory.getBlock(name);
if (block != null) {
blocks.add(block);
}
}
// Fallback for raw data dumps (BinaryLoader): no named sections exist.
// Search all readable memory blocks instead.
if (blocks.isEmpty()) {
for (MemoryBlock block : memory.getBlocks()) {
if (block.isRead()) {
blocks.add(block);
}
}
if (!blocks.isEmpty() && DEBUG_RUN) {
System.out.println("[!] No named rodata sections found, falling back to all readable memory blocks (" + blocks.size() + " block(s))");
}
}
return blocks;
}
private boolean isDataSection(String blockName) {
if (blockName == null) return false;
String[] dataSections = {".data", ".rodata", ".rdata", "__const", "__cstring", "__data"};
for (String section : dataSections) {
if (blockName.contains(section)) {
return true;
}
}
return false;
}
private int countXRefs(Function function){
// Get the entry point of the function.
Address entry = function.getEntryPoint();
// Obtain an iterator over all references to the entry point.
ReferenceIterator refIter = currentProgram.getReferenceManager().getReferencesTo(entry);
// Count the number of references.
int count = 0;
while (refIter.hasNext()) {
Reference ref = refIter.next();
if (ref.getReferenceType().isCall()) {
count++;
}
}
return count;
}
// Utility function to append a byte to a byte array
private byte[] appendByte(byte[] original, byte value) {
byte[] result = new byte[original.length + 1];
System.arraycopy(original, 0, result, 0, original.length);
result[original.length] = value;
return result;
}
private String byteArrayToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
return sb.toString().trim();
}
private Address searchForPattern(Memory memory, Address start, Address end, byte[] pattern) {
Address current = start;
try {
while (current.compareTo(end) <= 0) {
byte[] memoryBytes = new byte[pattern.length];
memory.getBytes(current, memoryBytes);
if (java.util.Arrays.equals(memoryBytes, pattern)) {
return current; // Pattern found
}
current = current.add(1); // Increment address by 1 byte
}
} catch (MemoryAccessException e) {
println("Memory access error at: " + current);
}
return null; // Pattern not found
}
private Address searchPatterns(Memory memory, Address start, Address end, byte[][] patterns) throws Exception {
for (byte[] pattern : patterns) {
Address foundAddress = searchForPattern(memory, start, end, pattern);
if (foundAddress != null) {
System.out.println("[*] Found pattern: " + byteArrayToHex(pattern) + " at: " + foundAddress+ " (IDA: 0x"+get_ida_address(foundAddress)+")");
return foundAddress;
}
}
return null;
}
private Address searchPatternFast(Memory memory, Address start, Address end, byte[] pattern) {
try {
return memory.findBytes(start, end, pattern, null, true, getMonitor());
} catch (Exception e) {
if (DEBUG_RUN) {
System.out.println("[!] Fast search failed, falling back to manual scan: " + e.getMessage());
}
return searchForPattern(memory, start, end, pattern);
}
}
private Address searchPatternsFast(Memory memory, Address start, Address end, byte[][] patterns) throws Exception {
for (byte[] pattern : patterns) {
Address foundAddress = searchPatternFast(memory, start, end, pattern);
if (foundAddress != null) {
System.out.println("[*] Found pattern: " + byteArrayToHex(pattern) + " at: " + foundAddress + " (IDA: 0x" + get_ida_address(foundAddress) + ")");
return foundAddress;
}
}
return null;
}
public Pair<Function, Address> traceDataSectionPointer(Program program, Address startAddress, int maxAttempts) {
Listing listing = program.getListing();
int addressSize = program.getAddressFactory().getDefaultAddressSpace().getPointerSize();
Address refAddress = null;
Address currentAddress = startAddress;
for (int attempt = 0; attempt < maxAttempts; attempt++) {
// Check if the current address contains a pointer to a function
Function function = listing.getFunctionAt(currentAddress);
ReferenceManager referenceManager = currentProgram.getReferenceManager();
ReferenceIterator references = referenceManager.getReferencesTo(currentAddress);
Reference reference = references.next();
if(reference != null){
refAddress = reference.getFromAddress();
Function function1 = getFunctionContaining(refAddress);
function = function1;
}
if (function != null && refAddress != null) {
System.out.println("[*] Found reference to function: " + function.getName() +
" at target address: " + currentAddress+ " (IDA: 0x"+get_ida_address(currentAddress)+")");
Pair<Function, Address> funcPair = new Pair<>(function,refAddress);
return funcPair; // Found the function reference
}
// Move one address size backward
currentAddress = currentAddress.subtract(addressSize);
if (currentAddress == null) {
System.out.println("[-] Reached invalid address while stepping back.");
break;
}
}
System.out.println("[*] No function reference found after " + maxAttempts + " attempts.");
return null; // No valid function reference found
}
private Pair<Function, Address> findFunctionReferences(Address dataRelRoAddress, String sectionName) {
List<Pair<Function, Address>> functionAddressPairs = new ArrayList<>();
ReferenceManager referenceManager = currentProgram.getReferenceManager();
ReferenceIterator references = referenceManager.getReferencesTo(dataRelRoAddress);
while (references.hasNext()) {
Reference reference = references.next();
Address refAddress = reference.getFromAddress();
Function function = getFunctionContaining(refAddress);
if (function != null) {
System.out.println("[*] Found reference to "+sectionName+" at " + refAddress+ " (IDA: 0x"+get_ida_address(refAddress)+")" + " in function: " + function.getName());
functionAddressPairs.add(new Pair<>(function, refAddress));
}else{
Memory memory = currentProgram.getMemory();
MemoryBlock block = memory.getBlock(refAddress);
if (block != null) {
String blockName = block.getName();
// Determine if the address belongs to a data section
if (isDataSection(blockName)) {
if(DEBUG_RUN){
System.out.println("[!] The address is pointing to another data section:"+blockName+ " at address: "+refAddress);
}
Pair<Function, Address> dataPair = traceDataSectionPointer(currentProgram, refAddress,4);
if(dataPair.first != null && dataPair.second != null){
functionAddressPairs.add(dataPair);
}
}else {
System.out.println("The address is in an unknown section.");
}
} else {
System.out.println("No memory block found for address: " + refAddress);
}
}
}
if(DEBUG_RUN && functionAddressPairs.size() > 1){
System.out.println("[!] Found more than pair, but currently only the first one will be used for further processing...");
System.out.println("[!] Full list of Pairs: ");
for(Pair<Function, Address> analysisPair : functionAddressPairs){
System.out.println("[!] Function: "+analysisPair.first.getName() + " at address: "+analysisPair.getSecond());
}
}
if(functionAddressPairs == null || functionAddressPairs.size() == 0){
if(isARM32()){
Pair<Set<Function>, Address> resBinder = findHexStringInRodataWrapper("res binder", false);
if(resBinder.getFirst() != null && resBinder.getSecond() != null){
Set<Function> functionSet = resBinder.getFirst();
if (functionSet != null && !functionSet.isEmpty()) {
Function firstFunction = functionSet.iterator().next();
functionAddressPairs.add(new Pair<>(firstFunction, resBinder.getSecond()));
}
}
}else{
Address refAddr = findBackwardsXref(getCurrentProgram(), dataRelRoAddress);
if (refAddr != null) {
Function function = getFunctionContaining(refAddr);
if(function == null){
if(DEBUG_RUN){
System.out.println("[!] function is null and ref is probably pointing to another section ("+refAddr+")...");
}
}
if(function != null) {
System.out.println("[*] Found a reference to " + dataRelRoAddress + " at: " + refAddr + " in function: " + function.getName());
} else {
System.out.println("[*] Found a reference to " + dataRelRoAddress + " at: " + refAddr + " in function: <UNDEFINED>");
}
functionAddressPairs.add(new Pair<>(function, refAddr));
}else{
System.out.println("[-] Error: No backwards reference found for " + dataRelRoAddress);
return null;
}
}
}
return functionAddressPairs.getFirst();
}
private boolean isHexStringInRodata(String targetString) {
byte[] targetBytes = targetString.getBytes();
Memory memory = currentProgram.getMemory();
List<MemoryBlock> rodataBlocks = findAllRodataBlocks();
if (rodataBlocks.isEmpty()) {
return false;
}
byte[] littleEndianPattern = new byte[targetBytes.length];
for (int i = 0; i < targetBytes.length; i++) {
littleEndianPattern[i] = targetBytes[targetBytes.length - 1 - i];
}
byte[] bigEndianWithNull = appendByte(targetBytes, (byte) 0x00);
byte[] bigEndianWithSpace = appendByte(targetBytes, (byte) 0x20);
byte[] littleEndianWithNull = appendByte(littleEndianPattern, (byte) 0x00);
byte[] littleEndianWithSpace = appendByte(littleEndianPattern, (byte) 0x20);
for (MemoryBlock rodataBlock : rodataBlocks) {
Address start = rodataBlock.getStart();
Address end = rodataBlock.getEnd();
Address foundAddress = null;
try {
foundAddress = searchPatterns(memory, start, end,
new byte[][] {bigEndianWithNull, bigEndianWithSpace, targetBytes});
if (foundAddress != null) {
return true;
}
foundAddress = searchPatterns(memory, start, end,
new byte[][] {littleEndianWithNull, littleEndianWithSpace, littleEndianPattern});
if (foundAddress != null) {
return true;
}
} catch (MemoryAccessException e) {
// continue to next block
} catch (Exception e) {
// continue to next block
}
}
return false;
}
private Pair<Set<Function>, Address> findHexStringInRodata(String targetString, boolean do_print_info_msg) {
Set<Function> functions = new HashSet<>();
Pair<Function, Address> functionAddressPair;
Address referenceAddress = null;
byte[] targetBytes = targetString.getBytes();
Memory memory = currentProgram.getMemory();
List<MemoryBlock> rodataBlocks = findAllRodataBlocks();
if (rodataBlocks.isEmpty()) {
if(do_print_info_msg){
System.out.println("[-] No read-only data sections found (checked: .rodata, .rdata, __cstring, __const)!");
}
return new Pair<>(functions, null);
}
if ("skip".equals(LARGE_DUMP_MODE)) {
long totalSize = 0;
for (MemoryBlock b : rodataBlocks) { totalSize += b.getSize(); }
if (totalSize > 100 * 1024 * 1024) {
System.out.println("[!] Skipping large memory region (" + (totalSize / (1024 * 1024)) + " MB) due to LARGE_DUMP_MODE=skip");
return new Pair<>(functions, null);
}
}
byte[] littleEndianPattern = new byte[targetBytes.length];
for (int i = 0; i < targetBytes.length; i++) {
littleEndianPattern[i] = targetBytes[targetBytes.length - 1 - i];
}
byte[] bigEndianWithNull = appendByte(targetBytes, (byte) 0x00);
byte[] bigEndianWithSpace = appendByte(targetBytes, (byte) 0x20);
byte[] littleEndianWithNull = appendByte(littleEndianPattern, (byte) 0x00);
byte[] littleEndianWithSpace = appendByte(littleEndianPattern, (byte) 0x20);
Address foundAddress = null;
String foundBlockName = null;
for (MemoryBlock rodataBlock : rodataBlocks) {
Address start = rodataBlock.getStart();
Address end = rodataBlock.getEnd();
try {
if ("fast".equals(LARGE_DUMP_MODE)) {
foundAddress = searchPatternsFast(memory, start, end,
new byte[][] {bigEndianWithNull, bigEndianWithSpace, targetBytes});
} else {
foundAddress = searchPatterns(memory, start, end,
new byte[][] {bigEndianWithNull, bigEndianWithSpace, targetBytes});
}
if (foundAddress != null && DEBUG_RUN && do_print_info_msg) {
System.out.println("[*] Found big-endian pattern at: " + foundAddress + " in section " + rodataBlock.getName());
}
if(foundAddress == null){
if ("fast".equals(LARGE_DUMP_MODE)) {
foundAddress = searchPatternsFast(memory, start, end,
new byte[][] {littleEndianWithNull, littleEndianWithSpace, littleEndianPattern});
} else {
foundAddress = searchPatterns(memory, start, end,
new byte[][] {littleEndianWithNull, littleEndianWithSpace, littleEndianPattern});
}
if (foundAddress != null && DEBUG_RUN && do_print_info_msg) {
System.out.println("[*] Found little-endian pattern at: " + foundAddress + " in section " + rodataBlock.getName());
}
}
if (foundAddress != null) {
foundBlockName = rodataBlock.getName();
break;
}
} catch (MemoryAccessException e) {
System.err.println("[-] Error accessing memory in " + rodataBlock.getName() + ": " + e.getMessage());
} catch (Exception e) {
System.err.println("[-] Error in pattern identification in " + rodataBlock.getName() + ": " + e.getMessage());
}
}
if(foundAddress != null){
if(do_print_info_msg){
System.out.println("[*] String found in " + foundBlockName + " section at address: " + foundAddress);
}
functionAddressPair = findFunctionReferences(foundAddress, foundBlockName);
if(functionAddressPair == null){
System.out.println("[-] Error in findFunctionReferences...");
return new Pair<>(functions, referenceAddress);
}
functions.add(functionAddressPair.getFirst());
referenceAddress = functionAddressPair.getSecond();
}else{
if(do_print_info_msg){
StringBuilder checkedSections = new StringBuilder();
for (MemoryBlock b : rodataBlocks) {
if (checkedSections.length() > 0) checkedSections.append(", ");
checkedSections.append(b.getName());
}
System.err.println("[-] Unable to find pattern in any read-only data section (checked: " + checkedSections + ")");
}
}
return new Pair<>(functions, referenceAddress);
}
private String get_ida_address(Address ghidra_address){
/*
The default base address in Ghidra is 0x00010000 for 32bit and 0x00100000 for 64bit and in IDA it is
just 0x0 therefore we just do the math here
*/
long offset = 0x00010000; // offset 32bit
String languageID = currentProgram.getLanguageID().toString();
if(languageID.contains("64")){
offset = 0x00100000;
}
// Subtract the offset from the Ghidra address
Address ida_address = ghidra_address.subtract(offset);
return ida_address.toString().toUpperCase();
}
private boolean is_target_binary_a_rust_binary(){
Memory memory = currentProgram.getMemory();
for (MemoryBlock block : memory.getBlocks()) {
String blockName = block.getName();
if (blockName != null && (blockName.contains(".rustc") || blockName.contains("note.rustc"))) {
System.out.println("0");
return true;
}
}
SymbolTable symbolTable = currentProgram.getSymbolTable();
String[] rustSymbols = {
"rust_eh_personality",
"core::panicking::panic_fmt",
"alloc::alloc::alloc",
"std::rt::lang_start",
"_ZN3std2rt10lang_start",
"DW.ref.rust_eh_personality"
};
for (Symbol symbol : symbolTable.getAllSymbols(true)) {
for (String rustSymbol : rustSymbols) {
if (symbol.getName().contains(rustSymbol)) {
System.out.println("[*] Rust Binary Detected! Symbol found: " + symbol.getName());
return true; // Stop early if Rust is confirmed
}
}
}
List<String> rustStringMarkers = Arrays.asList(
"rustls::record_layer",
"Cargo.toml",
"begin_panic",
"panicked at",
"core::"
);
for (String marker : rustStringMarkers) {
boolean has_rust_String = is_string_in_binary(marker);
if(has_rust_String){
System.out.println("1");
// we have a rust binary
return true;
}
}
for (String marker : rustStringMarkers) {
boolean has_rust_String = isHexStringInRodata(marker);
if(has_rust_String){
// we have a rust binary
System.out.println("2");
return true;
}
}
if(DEBUG_RUN){
System.out.println("[*] None rust binary...");
}
return false;
}
private String get_rustcall_mangled_function_name(Address targetAddress){
SymbolTable symbolTable = currentProgram.getSymbolTable();
for (Symbol symbol : symbolTable.getAllSymbols(false)) {
Function function = getFunctionAt(symbol.getAddress());
if (function != null) {
if(targetAddress == symbol.getAddress() || function.getName().toLowerCase().contains("log_secret")){
String mangledName = symbol.getName(); // Raw symbol name (likely mangled)
// Only process symbols with "Rust" style mangling (_ZN...)
if (mangledName.startsWith("_ZN")) {
return mangledName;
}
}
}
}
return "";
}
/**
* Returns the first function that calls the given function.
*
* @param function The function whose caller is to be determined.
* @return The caller function if found; otherwise, null.
*/
private Function getFirstCaller(Function function) {
// Get the entry point of the function.
Address entry = function.getEntryPoint();
// Retrieve all references to this address.
ReferenceIterator refIter = currentProgram.getReferenceManager().getReferencesTo(entry);
while (refIter.hasNext()) {
Reference ref = refIter.next();
// Check if the reference is a call.
if (ref.getReferenceType().isCall()) {
// Get the function containing the caller address.
Function caller = getFunctionContaining(ref.getFromAddress());
if (caller != null) {
return caller;
}
}
}
return null;
}
// Function to extract function information
private void extractFunctionInfo(Function function, boolean is_rust_tls12_run) {
Address entryPoint = function.getEntryPoint();
String label = function.getName();
// Get the memory object
Memory memory = currentProgram.getMemory();
// Ensure the memory block is valid and readable
if (memory.getBlock(entryPoint) == null) {
System.err.println("[-] Memory block not found for entry point: " + entryPoint);
return;
}
// Determine the length of bytes until the first branch
int numBytes = getLengthUntilBranch(function);
if(numBytes == -42){
System.out.println("[*] Couldn't find a branching instruction in current function...");
Function callerFunction = getFirstCaller(function);
if(callerFunction == null){
System.err.println("[-] Unable to identify target calling function..");
}else{
System.out.println("[*] Using calling function as ssl_log()...");
numBytes = getLengthUntilBranch(callerFunction);
function = callerFunction;
entryPoint = function.getEntryPoint();
label = function.getName();
}
}
// Use the custom readBytes function to read the dynamically determined length of bytes
byte[] byteData = readBytes(memory, entryPoint, numBytes);
// Convert the byte array into a formatted string of hex values
StringBuilder bytePattern = new StringBuilder();
for (byte b : byteData) {
bytePattern.append(String.format("%02X ", b & 0xFF)); // Ensure uppercase hex values
}
// Print the function information to the terminal
System.out.println();
if(function.getCallingConventionName().contains("rust")){
System.out.println("[!] Keep in mind that hooking function using the "+function.getCallingConventionName()+" with frida is a little bit tricky...");
String mangled_target_function_name = get_rustcall_mangled_function_name(entryPoint);
System.out.println("[*] Function label: " + label+ " ("+ mangled_target_function_name +")");
}else{
System.out.println("[*] Function label: " + label+ " ("+ function.toString() +")");
}
if(is_rust_tls12_run){
System.out.println("\n");
System.out.println("[*] TLS 1.2 RusTLS:");
System.out.println("[*] Function label: " + label+ " ("+ function.toString() +")");
System.out.println("[*] Function offset (Ghidra): " + entryPoint.toString().toUpperCase() + " (0x" + entryPoint.toString().toUpperCase() + ")");
System.out.println("[*] Function offset (IDA with base 0x0): " + get_ida_address(entryPoint) + " (0x" + get_ida_address(entryPoint) + ")");
System.out.println("[*] Byte pattern for frida (friTap): " + bytePattern.toString().trim());
System.out.println();
printTls13Info();
return;
}
System.out.println("[*] Function offset (Ghidra): " + entryPoint.toString().toUpperCase() + " (0x" + entryPoint.toString().toUpperCase() + ")");
System.out.println("[*] Function offset (IDA with base 0x0): " + get_ida_address(entryPoint) + " (0x" + get_ida_address(entryPoint) + ")");
System.out.println("[*] Byte pattern for frida (friTap): " + bytePattern.toString().trim());
System.out.println("");
BoringSecretHunter.identified_pattern = bytePattern.toString().trim();
BoringSecretHunter.identifiedTls13 = true;
BoringSecretHunter.tls13GhidraOffset = entryPoint.toString().toUpperCase();
BoringSecretHunter.tls13IdaOffset = get_ida_address(entryPoint);
BoringSecretHunter.tls13BytePattern = bytePattern.toString().trim();
BoringSecretHunter.tls13label = function;
}
// Helper function to read bytes from memory
private byte[] readBytes(Memory memory, Address address, int numBytes) {
byte[] byteData = new byte[numBytes];
try {
memory.getBytes(address, byteData);
} catch (MemoryAccessException e) {
System.err.println("[-] Error reading bytes from memory at " + address + ": " + e.getMessage());
}
return byteData;
}
private Address findReferenceToStringAtAddress(Address referenceAddr, Function function) {
System.out.println("[*] Analyzing reference at address: " + referenceAddr + " in function: "+function.getName());
Listing listing = currentProgram.getListing();
Instruction instruction = listing.getInstructionAt(referenceAddr);
if (instruction == null) {
System.err.println("[-] No instruction found at reference address: " + referenceAddr);
return null;
}
// Look for the function containing this reference
Function containingFunction = getFunctionContaining(referenceAddr);
// Need to fix this in future releases - this is a temporary workaround for problems on ARM32
if(isARM32()){
return containingFunction.getEntryPoint();
}
if (containingFunction != null) {
if(DEBUG_RUN){
System.out.println("[!] Start analyzing the function at ref: "+containingFunction.getName());
}
while (instruction != null && !instruction.getFlowType().isCall()) {
instruction = instruction.getNext();
}
if(containingFunction.getBody().contains(instruction.getAddress())){
if(DEBUG_RUN){
System.out.println("[!] Target address is part of the analyzed function");
}
}else{
if(DEBUG_RUN){
System.out.println("[!] Target address is not part of the analyzed function...");
}
return null;
}
if (instruction != null && instruction.getFlowType().isCall()) {
Address[] flowRefs = instruction.getFlows(); // Get the flow references for function calls
if (flowRefs.length > 0) {
return flowRefs[0]; // Return the first flow reference as the called function address
}else{
if(DEBUG_RUN){
System.out.println("[!] flowRefs: "+flowRefs.length + " on instruction: "+instruction.toString());
}
}
}
}
System.err.println("[-] No function call found near the string reference.");
if(DEBUG_RUN){
System.out.println("[!] instruction: "+instruction.toString());
}
return null;
}
private int getLengthUntilBranch(Function function) {
Address entryPoint = function.getEntryPoint();
Listing listing = currentProgram.getListing();
AddressSetView functionBody = function.getBody();
// Get the first instruction at the entry point
InstructionIterator instructions = listing.getInstructions(functionBody, true);
Instruction start_instruction = listing.getInstructionAt(entryPoint);
int length = 0;
boolean found_call = false;
if (start_instruction == null) {
println("[-] No instruction found at entry point: " + entryPoint);
println("[-] Defaulting to 32 bytes");
return 32; // Default to 32 if no instructions are found
}
while (instructions.hasNext()) {
Instruction instruction = instructions.next();
if (instruction == null) {
break; // Break if there's no instruction at the current address
}
// Check if the instruction is a branch, jump, or call
if (instruction.getFlowType().isJump() ||
instruction.getFlowType().isConditional() ||
instruction.getFlowType().isCall()) {
// with that we ensure that we also count the length of the branch itself
length += instruction.getLength();
//instruction = listing.getInstructionAt(entryPoint);
Address[] flows = instruction.getFlows();
if (flows.length > 0) {
Address target_address_of_call_instruction = flows[0];
// is this function call still part of the analysed function
if (function.getBody().contains(target_address_of_call_instruction) && (target_address_of_call_instruction.subtract(instruction.getAddress()))< 10) {
continue;
}
}