-
Notifications
You must be signed in to change notification settings - Fork 2
/
HashDB.java
1746 lines (1544 loc) · 55.9 KB
/
HashDB.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
//Script to look up API functions in HashDB (https://hashdb.openanalysis.net/)
//@author @larsborn @huettenhain
//@category HashDB
//@keybinding F3
//@menupath
//@toolbar
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.OptionalLong;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import ghidra.app.decompiler.DecompInterface;
import ghidra.app.decompiler.DecompileResults;
import ghidra.app.decompiler.DecompilerLocation;
import ghidra.app.plugin.core.analysis.AutoAnalysisManager;
import ghidra.app.script.GhidraScript;
import ghidra.app.services.DataTypeManagerService;
import ghidra.app.tablechooser.AddressableRowObject;
import ghidra.app.tablechooser.StringColumnDisplay;
import ghidra.app.tablechooser.TableChooserDialog;
import ghidra.app.tablechooser.TableChooserExecutor;
import ghidra.framework.plugintool.PluginTool;
import ghidra.program.util.OperandFieldLocation;
import ghidra.util.exception.CancelledException;
import ghidra.util.exception.NotFoundException;
import ghidra.util.task.TaskMonitor;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import docking.widgets.checkbox.GCheckBox;
import docking.widgets.label.GDLabel;
import docking.widgets.table.TableSortState;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;
import ghidra.program.model.data.AbstractIntegerDataType;
import ghidra.program.model.data.Array;
import ghidra.program.model.data.CategoryPath;
import ghidra.program.model.data.DataType;
import ghidra.program.model.data.DataTypeConflictHandler;
import ghidra.program.model.data.DataTypeManager;
import ghidra.program.model.data.DataTypePath;
import ghidra.program.model.data.EnumDataType;
import ghidra.program.model.data.FunctionDefinitionDataType;
import ghidra.program.model.data.PointerDataType;
import ghidra.program.model.data.SourceArchive;
import ghidra.program.model.data.StructureDataType;
import ghidra.program.model.listing.Data;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Instruction;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.MemoryAccessException;
import ghidra.program.model.pcode.HighFunction;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.program.model.pcode.PcodeOpAST;
import ghidra.program.model.pcode.Varnode;
import ghidra.program.model.scalar.Scalar;
import ghidra.program.model.symbol.RefType;
import ghidra.program.model.symbol.Reference;
import java.net.URL;
import java.security.SecureRandom;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ActionEvent;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import org.python.util.PythonInterpreter;
public class HashDB extends GhidraScript {
boolean HTTP_DEBUGGING = false;
boolean GUI_DEBUGGING = false;
boolean PY_DEBUGGING = false;
static String getStackTraceAsString(Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
private class HashDBApi {
private String baseUrl = "https://hashdb.openanalysis.net";
private class Hashes {
@SuppressWarnings({ "unused" })
public long[] hashes;
public Hashes(long[] hashes) {
this.hashes = hashes;
}
}
private ArrayList<String> hunt(long[] hashes, double minimumHitcount) throws Exception {
ArrayList<String> ret = new ArrayList<String>();
JsonObject response = JsonParser
.parseString(httpQuery("POST", "hunt", new Gson().toJson(new Hashes(hashes)).getBytes()))
.getAsJsonObject();
for (JsonElement hit : response.get("hits").getAsJsonArray()) {
JsonObject row = hit.getAsJsonObject();
if (minimumHitcount <= row.get("hitrate").getAsDouble()) {
ret.add(row.get("algorithm").getAsString());
}
}
return ret;
}
public class ApiHashInfo extends HashInfo {
public String apiName;
public String permutation;
public String modules[];
public ApiHashInfo(long hash, String apiName, String permutation, String[] modules) {
super(hash);
this.apiName = apiName;
this.permutation = permutation;
this.modules = modules;
}
@Override
public String getResolutionName() {
return apiName;
}
}
public class NonApiHashInfo extends HashInfo {
public String freeText;
public NonApiHashInfo(long hash, String freeText) {
super(hash);
this.freeText = freeText;
}
@Override
public String getResolutionName() {
return freeText;
}
}
public abstract class HashInfo {
public long hash;
public HashInfo(long hash) {
this.hash = hash;
}
public abstract String getResolutionName();
}
private ArrayList<HashInfo> parseHashInfoFromJson(String httpResponse) {
JsonObject response = JsonParser.parseString(httpResponse).getAsJsonObject();
ArrayList<HashInfo> ret = new ArrayList<HashInfo>();
for (JsonElement hashEntry : response.get("hashes").getAsJsonArray()) {
JsonObject hashObject = hashEntry.getAsJsonObject();
JsonObject stringInfo = hashObject.get("string").getAsJsonObject();
long hash = hashObject.get("hash").getAsLong();
if (stringInfo.get("is_api").getAsBoolean()) {
/*-
* Example Responses:
* {"hashes": [{
* "hash": 2937175076,
* "string": {
* "is_api": true,
* "string": "RtlFreeHeap",
* "permutation": "api",
* "api": "RtlFreeHeap",
* "modules": ["ntdll"]
* }
* }]}
*/
String apiName = stringInfo.get("api").getAsString();
String permutation = stringInfo.get("permutation").getAsString();
JsonArray modulesArray = stringInfo.get("modules").getAsJsonArray();
String[] modules = new String[modulesArray.size()];
for (int i = 0; i < modules.length; i++) {
modules[i] = modulesArray.get(i).getAsString();
}
ret.add(new ApiHashInfo(hash, apiName, permutation, modules));
} else {
/*-
* Example Responses:
* {"hashes": [{
* "hash": 2227199552,
* "string": {
* "is_api": false
* "string": "ntdll.dll",
* }
* }]}
*/
ret.add(new NonApiHashInfo(hash, stringInfo.get("string").getAsString()));
}
}
return ret;
}
private ArrayList<HashInfo> resolve(String algorithm, long hash, String permutation) throws Exception {
ArrayList<HashInfo> ret = parseHashInfoFromJson(
httpQuery("GET", String.format("hash/%s/%d", algorithm, hash)));
ArrayList<HashInfo> filtered = new ArrayList<HashInfo>();
for (HashInfo hashInfo : ret) {
if (permutation != null && ApiHashInfo.class.isInstance(hashInfo)
&& ((ApiHashInfo) hashInfo).permutation.compareTo(permutation) != 0)
continue;
if (hashInfo.hash != hash) {
throw new Exception("hash mismatch");
}
filtered.add(hashInfo);
}
return filtered;
}
private ArrayList<HashInfo> module(String module, String algorithm, String permutation) throws Exception {
return parseHashInfoFromJson(
httpQuery("GET", String.format("module/%s/%s/%s", module, algorithm, permutation)));
}
private String httpQuery(String method, String endpoint) throws Exception {
return httpQuery(method, endpoint, null);
}
private String httpQuery(String method, String endpoint, byte[] postData) throws Exception {
String urlString = String.format("%s/%s", baseUrl, endpoint);
if (HTTP_DEBUGGING) {
logDebugMessage(String.format("%s %s", method, urlString));
}
URL url = new URL(urlString);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, new SecureRandom());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());
conn.setInstanceFollowRedirects(true);
conn.setDoOutput(true);
conn.setRequestMethod(method);
conn.setUseCaches(false);
if (postData != null) {
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
try (OutputStream wr = conn.getOutputStream()) {
wr.write(postData);
}
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
if (HTTP_DEBUGGING) {
logDebugMessage(String.format("HTTP Response: %s", response));
}
return response.toString();
}
}
}
private class HashTableExecutor implements TableChooserExecutor {
public HashTableExecutor() {
}
@Override
public String getButtonName() {
return "Query!";
}
@Override
public boolean execute(AddressableRowObject rowObject) {
return false;
}
}
public enum TransformInvertibility {
NotInvertible, SelfInverse, Manual
}
public class GuiState {
public TransformInvertibility transformInvertibility;
public GuiState(TransformInvertibility transformInvertibility) {
this.transformInvertibility = transformInvertibility;
}
}
public enum OutputMethod {
Enum, Struct
}
class HashTable extends TableChooserDialog {
private JTextField enumNameTextField;
private JTextField nonApiResolutionEnumName;
private JTextField transformationInverseTextField;
private JComboBox<String> transformationTextField;
private JComboBox<String> hashAlgorithmField;
private JComboBox<String> permutationField;
private JTextField hashAlgorithmThresholdField;
private GCheckBox resolveModulesCheckbox;
private JTextField crawlFunctionName;
private JSpinner crawlParameterIndex;
private SpinnerNumberModel crawlParameterIndexModel;
private GCheckBox transformationIsSelfInverseCheckbox;
private GCheckBox transformationIsNotInvertibleCheckbox;
private JRadioButton outputStructRadio;
private JRadioButton outputEnumRadio;
public HashTable(PluginTool tool, TableChooserExecutor executor, Program program, String title) {
super(tool, executor, program, title, null, false);
setFocusComponent(okButton);
okButton.setMnemonic('Q');
}
@Override
public void show() {
super.show();
setSortState(TableSortState.createUnsortedSortState());
}
@Override
protected void setOkEnabled(boolean state) {
return;
}
public OutputMethod getOutputMethod() throws IllegalStateException {
if (outputStructRadio.isSelected())
return OutputMethod.Struct;
if (outputEnumRadio.isSelected())
return OutputMethod.Enum;
throw new IllegalStateException();
}
private String getComboBoxValue(JComboBox<String> box) {
String currentText;
try {
currentText = box.getEditor().getItem().toString();
} catch (Exception e1) {
try {
currentText = box.getSelectedItem().toString();
} catch (Exception e2) {
return null;
}
}
if (currentText.isBlank())
return null;
return currentText.trim();
}
private void addToComboBox(JComboBox<String> box, String value, boolean selectIt) {
boolean exists = false;
if (value == null)
return;
value = value.trim();
if (getComboBoxValue(box) == value)
exists = true;
for (int k = 0; !exists && k < box.getItemCount(); k++) {
String item = box.getItemAt(k);
if (item.compareTo(value) == 0)
exists = true;
}
if (!exists)
box.addItem(value);
if (selectIt)
box.setSelectedItem(value);
}
public void addNewPermutation(String permutation, boolean selectIt) {
int index = 0;
int count = permutationField.getItemCount();
boolean exists = false;
permutation = permutation.trim();
for (index = 0; index < count; index++) {
int stringDiff = permutation.compareTo(permutationField.getItemAt(index));
if (stringDiff == 0) {
exists = true;
break;
} else if (stringDiff < 0) {
break;
}
}
if (!exists)
permutationField.insertItemAt(permutation, index);
if (selectIt)
permutationField.setSelectedItem(permutation);
}
public String getCurrentPermutation() {
return getComboBoxValue(permutationField);
}
public void addNewHashAlgorithm(String algorithm, boolean selectIt) {
addToComboBox(hashAlgorithmField, algorithm, selectIt);
}
public String getCurrentHashAlgorithm() {
return getComboBoxValue(hashAlgorithmField);
}
public String getTransformation() {
return transformationTextField.getEditor().getItem().toString();
}
public boolean isTransformationInvertible() {
return !transformationIsNotInvertibleCheckbox.isSelected();
}
public String getTransformationInverse() throws IllegalStateException {
if (transformationIsNotInvertibleCheckbox.isSelected()) {
throw new IllegalStateException();
}
if (transformationIsSelfInverseCheckbox.isSelected()) {
return getTransformation();
}
return transformationInverseTextField.getText();
}
public String getStorageName() {
return enumNameTextField.getText();
}
public String getNonApiEnumName() {
return nonApiResolutionEnumName.getText();
}
public boolean resolveEntireModules() {
return resolveModulesCheckbox.isSelected();
}
public double getAlgorithmThreshold() {
try {
double threshold = Double.parseDouble(hashAlgorithmThresholdField.getText());
if (threshold < 0) {
return 0;
}
if (threshold > 1.0) {
return 1.0;
}
return threshold;
} catch (NumberFormatException exception) {
return 1;
}
}
public GuiState getCurrentState() {
if (transformationIsNotInvertibleCheckbox.isSelected())
return new GuiState(TransformInvertibility.NotInvertible);
if (transformationIsSelfInverseCheckbox.isSelected())
return new GuiState(TransformInvertibility.SelfInverse);
return new GuiState(TransformInvertibility.Manual);
}
public void enableComponentsAccordingToState(GuiState guiState) {
switch (guiState.transformInvertibility) {
case Manual:
transformationInverseTextField.setEnabled(true);
resolveModulesCheckbox.setEnabled(true);
transformationIsSelfInverseCheckbox.setEnabled(true);
break;
case NotInvertible:
transformationInverseTextField.setEnabled(false);
resolveModulesCheckbox.setEnabled(false);
transformationIsSelfInverseCheckbox.setEnabled(false);
resolveModulesCheckbox.setSelected(false);
break;
case SelfInverse:
transformationInverseTextField.setEnabled(false);
resolveModulesCheckbox.setEnabled(true);
transformationIsSelfInverseCheckbox.setEnabled(true);
break;
}
}
public void selectAllRows() {
selectRows(IntStream.range(0, getRowCount()).toArray());
}
@Override
public void dispose() {
selectAllRows();
for (AddressableRowObject row : dialog.getSelectedRowObjects()) {
remove(row);
}
}
@Override
protected void okCallback() {
TaskMonitor tm = getTaskMonitorComponent();
if (getSelectedRows().length == 0)
selectAllRows();
ArrayList<HashLocation> hashes = getSelectedRowObjects().stream().map(a -> (HashLocation) a)
.collect(Collectors.toCollection(ArrayList::new));
tm.initialize(hashes.size());
showProgressBar("Querying HashDB", true, true, 0);
final class Resolver extends SwingWorker<String, Object> {
private final TaskMonitor taskMonitor;
private final ArrayList<HashLocation> hashLocations;
Resolver(ArrayList<HashLocation> hashLocations, TaskMonitor taskMonitor) {
this.hashLocations = hashLocations;
this.taskMonitor = taskMonitor;
}
@Override
protected String doInBackground() throws Exception {
try {
return resolveHashes(hashLocations, taskMonitor);
} catch (ShowErrorInUi e) {
return e.getMessage();
} catch (Exception e) {
logDebugMessage("Exception during resolution:", e);
return "unexpected error during resolution, see log";
}
}
@Override
protected void done() {
String resultText;
try {
resultText = get();
} catch (InterruptedException | ExecutionException e) {
resultText = "unknown error during execution";
}
waitAndClearSelection();
selectRows();
hideTaskMonitorComponent();
setStatusText(resultText);
}
}
Resolver resolver = new Resolver(hashes, tm);
resolver.execute();
}
public void waitAndClearSelection() {
long maxWaitCount = 200;
while (dialog.isBusy()) {
try {
Thread.sleep(10);
} catch (Exception e) {
logDebugMessage("Exception in waitAndClearSelection:", e);
break;
}
if (maxWaitCount == 0) {
logDebugMessage("UI Timeout in waitAndClearSelection.");
break;
}
maxWaitCount--;
}
clearSelection();
}
public void parentOkCallback() {
super.okCallback();
}
private class TwoColumnPanel {
private JComponent left;
private JComponent right;
private JComponent main;
public TwoColumnPanel(int rowCount) {
left = new JPanel(new GridLayout(rowCount, 1));
right = new JPanel(new GridLayout(rowCount, 1));
main = new JPanel(new BorderLayout());
main.setBorder(new EmptyBorder(5, 2, 0, 2));
JPanel topAlignedContents = new JPanel(new BorderLayout(10, 10));
main.add(topAlignedContents, BorderLayout.NORTH);
topAlignedContents.add(left, BorderLayout.WEST);
topAlignedContents.add(right, BorderLayout.CENTER);
}
public JComponent getMain() {
return main;
}
public void addRow(JComponent component) {
left.add(new GDLabel());
right.add(component);
}
public void addRow(String label, JComponent component) {
left.add(new GDLabel(label));
right.add(component);
}
}
private JComponent addQuerySettingsPanel() {
TwoColumnPanel tc = new TwoColumnPanel(7);
transformationTextField = new JComboBox<>();
transformationTextField.setEditable(true);
transformationTextField.addItem("X # Unaltered Hash Value");
transformationTextField.addItem("X ^ 0xBAADF00D # XOR");
transformationTextField.addItem("((((X ^ 0x76C7) << 0x10) ^ X) ^ 0xAFB9) & 0x1FFFFF # REvil");
transformationTextField.setSelectedIndex(0);
tc.addRow("Hash Transformation:", transformationTextField);
final class UpdateButtons implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
enableComponentsAccordingToState(getCurrentState());
}
}
UpdateButtons updateButtons = new UpdateButtons();
transformationIsSelfInverseCheckbox = new GCheckBox("Transformation Is Self-Inverse");
transformationIsSelfInverseCheckbox.addActionListener(updateButtons);
tc.addRow(transformationIsSelfInverseCheckbox);
transformationIsNotInvertibleCheckbox = new GCheckBox("Transformation Not Invertible");
transformationIsNotInvertibleCheckbox.addActionListener(updateButtons);
tc.addRow(transformationIsNotInvertibleCheckbox);
transformationInverseTextField = new JTextField();
tc.addRow("Transformation Inverse:", transformationInverseTextField);
JPanel hashAlgorithmLine = new JPanel(new BorderLayout(10, 10));
hashAlgorithmField = new JComboBox<>();
hashAlgorithmField.setEditable(true);
hashAlgorithmLine.add(hashAlgorithmField, BorderLayout.CENTER);
hashAlgorithmThresholdField = new JTextField(3);
hashAlgorithmThresholdField.setText("1.0");
hashAlgorithmThresholdField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
hashAlgorithmThresholdField.setText(String.format("%.1f", dialog.getAlgorithmThreshold()));
}
});
hashAlgorithmLine.add(hashAlgorithmThresholdField, BorderLayout.EAST);
tc.addRow("Hash Algorithm:", hashAlgorithmLine);
permutationField = new JComboBox<>();
permutationField.addItem("");
permutationField.setSelectedIndex(0);
tc.addRow("String Permutation:", permutationField);
resolveModulesCheckbox = new GCheckBox("Resolve Entire Modules");
tc.addRow(resolveModulesCheckbox);
transformationIsSelfInverseCheckbox.setSelected(true);
updateButtons.actionPerformed(null);
return tc.getMain();
}
private JComponent addOutputSettingsPanel() {
int rowCount = 4;
TwoColumnPanel tc = new TwoColumnPanel(rowCount);
JPanel radioPanel = new JPanel(new BorderLayout(10, 0));
enumNameTextField = new JTextField("HashDB");
tc.addRow("Data Type Name:", enumNameTextField);
outputStructRadio = new JRadioButton("Generate Struct");
outputStructRadio.setToolTipText(
"The entries of the struct will have the same order as the items in the above table."
+ " They will be named according to the resolved API symbols, or generically when no"
+ " resolution was possible.");
outputEnumRadio = new JRadioButton("Generate Enum");
outputEnumRadio.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(outputEnumRadio);
group.add(outputStructRadio);
radioPanel.add(outputEnumRadio, BorderLayout.WEST);
radioPanel.add(outputStructRadio, BorderLayout.CENTER);
tc.addRow(radioPanel);
nonApiResolutionEnumName = new JTextField("HashDBStrings");
tc.addRow("Enum for non-API resolutions", nonApiResolutionEnumName);
return tc.getMain();
}
private JComponent addEditTablePanel() {
JTextField manualHash = new JTextField();
JButton addHashButton = new JButton("Add Hash");
addHashButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
final class HashAdder extends SwingWorker<Boolean, Object> {
String hashValue;
Address address;
HashAdder(Address address, String hashValue) {
this.hashValue = hashValue;
this.address = address;
}
@Override
protected Boolean doInBackground() throws Exception {
return addHash(address, parseHash(hashValue));
}
@Override
protected void done() {
try {
this.get();
} catch (InterruptedException | ExecutionException e) {
logDebugMessage(String.format("invalid hash value: %s", hashValue));
}
}
}
HashAdder adder = new HashAdder(currentAddress, manualHash.getText());
adder.execute();
}
});
JButton deleteSelectionButton = new JButton("Remove Selection");
deleteSelectionButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
for (AddressableRowObject row : dialog.getSelectedRowObjects()) {
remove(row);
}
}
});
JPanel firstRow = new JPanel(new BorderLayout(10, 10));
firstRow.add(new GDLabel("Hash"), BorderLayout.WEST);
firstRow.add(manualHash, BorderLayout.CENTER);
firstRow.add(addHashButton, BorderLayout.EAST);
JPanel secondRow = new JPanel(new BorderLayout(10, 10));
secondRow.add(deleteSelectionButton, BorderLayout.EAST);
int rowCount = 2;
JPanel topAlignedContents = new JPanel(new GridLayout(rowCount, 1));
topAlignedContents.add(firstRow);
topAlignedContents.add(secondRow);
JPanel main = new JPanel(new BorderLayout());
main.setBorder(new EmptyBorder(5, 2, 0, 2));
main.add(topAlignedContents, BorderLayout.NORTH);
return main;
}
@SuppressWarnings("unchecked")
public void setCrawlFunctionParameterCount(Number count) {
crawlParameterIndexModel.setMaximum((Comparable<Double>) count);
crawlParameterIndexModel.setValue(count); // default select last parameter
}
private JComponent addScanFunctionPanel() {
TwoColumnPanel tc = new TwoColumnPanel(3);
crawlFunctionName = new JTextField("");
tc.addRow("Function Name:", crawlFunctionName);
crawlParameterIndexModel = new SpinnerNumberModel(1, 1, 3, 1);
crawlParameterIndex = new JSpinner(crawlParameterIndexModel);
tc.addRow("Parameter (1 based):", crawlParameterIndex);
JButton scanButton = new JButton("Scan!");
scanButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
List<Function> functions = getGlobalFunctions(crawlFunctionName.getText());
if (functions.size() == 0) {
logDebugMessage("No function with this name found");
} else if (functions.size() > 1) {
logDebugMessage("Multiple functions with this name found");
} else {
TaskMonitor taskMonitor = getTaskMonitorComponent();
showProgressBar("Scanning functions", true, true, 0);
List<Address> calls = getCallAddresses(functions.get(0));
taskMonitor.initialize(calls.size());
final class Resolver extends SwingWorker<Void, Object> {
@Override
protected Void doInBackground() throws Exception {
try {
for (Address callAddr : calls) {
try {
OptionalLong hash = getConstantCallArgument(callAddr,
(Integer) crawlParameterIndex.getValue());
if (hash.isEmpty()) {
logDebugMessage(String.format("Cannot extract value for call at 0x%x",
callAddr.getOffset()));
} else {
addHash(callAddr, hash.getAsLong());
if (GUI_DEBUGGING) {
logDebugMessage(
String.format("Found hash 0x%x passed to call at 0x%x",
hash.getAsLong(), callAddr.getOffset()));
}
}
} catch (Exception e) {
logDebugMessage(String.format(
"Error while extracting parameter value from call at 0x%x",
callAddr.getOffset()), e);
}
taskMonitor.incrementProgress(1);
taskMonitor.checkCanceled();
}
} catch (CancelledException e) {
logDebugMessage("Operation canceled");
}
return null;
}
@Override
protected void done() {
setStatusText(String.format("Scanned %d of %d function calls.",
taskMonitor.getProgress(), calls.size()));
hideTaskMonitorComponent();
try {
get();
} catch (InterruptedException | ExecutionException e) {
logDebugMessage("Unknown error during scanning", e);
}
}
}
Resolver resolver = new Resolver();
resolver.execute();
}
}
});
tc.addRow(scanButton);
return tc.getMain();
}
JTabbedPane McPane;
protected void addWorkPanel(JComponent hauptPanele) {
McPane = new JTabbedPane(); // McPane defies common camelCaseConventions
super.addWorkPanel(hauptPanele);
McPane.addTab("Query Settings", addQuerySettingsPanel());
McPane.addTab("Output Settings", addOutputSettingsPanel());
McPane.addTab("Edit Table", addEditTablePanel());
McPane.addTab("Scan Function", addScanFunctionPanel());
hauptPanele.add(McPane, BorderLayout.SOUTH);
enableComponentsAccordingToState(getCurrentState());
}
public void openQuerySettingsTab() {
McPane.setSelectedIndex(0);
}
public void openScanFunctionTab(Function function) {
crawlFunctionName.setText(function.getName());
setCrawlFunctionParameterCount(function.getParameterCount());
McPane.setSelectedIndex(3);
}
public void setTransformationNotInvertible() {
transformationIsNotInvertibleCheckbox.setSelected(true);
enableComponentsAccordingToState(getCurrentState());
}
}
static HashTable dialog = null;
private void showDialog() {
if (dialog == null) {
if (GUI_DEBUGGING) {
logDebugMessage("Creating new dialog.");
}
dialog = new HashTable(state.getTool(), new HashTableExecutor(), currentProgram, "HashDB is BestDB");
configureTableColumns(dialog);
}
if (!dialog.isVisible()) {
dialog.show();
}
state.getTool().showDialog(dialog);
}
private long parseHash(String input) throws Exception {
if (input.length() == 0) {
throw new Exception(String.format("Invalid input: %s (zero length)", input));
}
boolean endsInH = input.endsWith("h");
boolean startsWith0x = input.startsWith("0x");
if (endsInH) {
input = input.substring(0, input.length() - 1);
}
if (startsWith0x) {
return Long.parseLong(input.substring(2), 16);
}
if (endsInH) {
return Long.parseLong(input, 16);
}
return Long.parseLong(input, 10);
}
private boolean addHash(Address address, long hash) {
HashMap<Long, Address> hashes = new HashMap<Long, Address>();
hashes.put(hash, address);
return addHashes(hashes);
}
private boolean addHashes(HashMap<Long, Address> hashes) {
dialog.selectAllRows();
for (AddressableRowObject aro : dialog.getSelectedRowObjects()) {
HashLocation hl = (HashLocation) aro;
hashes.remove(hl.getHashAsLong());
}
for (Long hash : hashes.keySet()) {
dialog.add(new HashLocation(hashes.get(hash), hash));
}
dialog.waitAndClearSelection();
return true;
}
private void logDebugMessage(String msg) {
logDebugMessage(msg, null);
}
private void logDebugMessage(String msg, Exception e) {
String logOutput = String.format("[HashDB] %s", msg);
if (e != null) {
logOutput = String.format("%s %s", logOutput, getStackTraceAsString(e));
}
println(logOutput);
}
private DataType getDataType(String name, DataType fallback) {
ArrayList<DataType> matchingDataTypes = new ArrayList<>();
DataTypeManager dataTypeManager = currentProgram.getDataTypeManager();
currentProgram.getDataTypeManager().findDataTypes(name, matchingDataTypes);
if (matchingDataTypes.size() == 0) {
AutoAnalysisManager am = AutoAnalysisManager.getAnalysisManager(currentProgram);
DataTypeManagerService service = am.getDataTypeManagerService();
for (SourceArchive a : dataTypeManager.getSourceArchives()) {
String archiveName = a.getName();
DataTypeManager dtm;
try {
dtm = service.openDataTypeArchive(archiveName);
} catch (Exception e) {
logDebugMessage(String.format("unable to open archive %s", archiveName), e);
continue;
}
dtm.findDataTypes(name, matchingDataTypes);
if (matchingDataTypes.size() > 0)
break;
}
}
if (matchingDataTypes.size() > 0)
return matchingDataTypes.iterator().next();
return fallback;
}
public void run() throws Exception {
showDialog();
LinkedHashMap<Long, Address> hashes = new LinkedHashMap<Long, Address>();
if (currentSelection != null) {
long nextCheckpoint = currentSelection.getMinAddress().getOffset();
for (AddressRange addressRange : currentSelection.getAddressRanges(true)) {
for (Address address : addressRange) {
if (address.getOffset() < nextCheckpoint)
continue;
try {
nextCheckpoint = getHashesAt(address, hashes).getOffset();
} catch (Exception e) {
logDebugMessage(String.format("Error parsing data at 0x%08X:", address.getOffset()), e);
}
}
}