forked from standard3/snapchange
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbn_snapchange.py
2088 lines (1780 loc) · 80.7 KB
/
bn_snapchange.py
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
#!/usr/bin/env python3
"""
Snapchange Analysis for Binary Ninja - doubles as plugin and command line script
* `python3 bn_snapchange.py --analysis --bps ./examples/01_getpid/example1`
* Copy/Symlink to your binary ninja plugins directory
"""
import enum
import json
import math
import os
import string
import struct
import sys
from pathlib import Path
from collections import deque
if __name__ == "__main__":
# disable plugin loading etc. if we are in headless script mode - need to
# do this before importing binaryninja
os.environ["BN_DISABLE_USER_SETTINGS"] = "True"
os.environ["BN_DISABLE_USER_PLUGINS"] = "True"
os.environ["BN_DISABLE_REPOSITORY_PLUGINS"] = "True"
from typing import List, Optional
import binaryninja as bn
import binaryninja._binaryninjacore as core
from binaryninja import (
BackgroundTaskThread,
BranchType,
HighLevelILOperation,
LowLevelILInstruction,
LowLevelILOperation,
MediumLevelILInstruction,
MediumLevelILOperation,
)
# from binaryninja.log import log_debug, log_error, log_info, log_warn
from binaryninja.lowlevelil import LowLevelILFlag
LOG_ID = "snapchange"
def log_debug(msg, rtype=LOG_ID):
return bn.log.log_debug(msg, rtype)
def log_warn(msg, rtype=LOG_ID):
return bn.log.log_warn(msg, rtype)
def log_info(msg, rtype=LOG_ID):
return bn.log.log_info(msg, rtype)
def log_error(msg, rtype=LOG_ID):
return bn.log.log_error(msg, rtype)
DEFAULT_IGNORE = ["asan", "ubsan", "msan", "lcov", "sanitizer", "interceptor"]
ALPHANUM = set(string.ascii_letters + string.digits)
STR_LEN_THRESHOLD = 128
class FunctionAlias(enum.Enum):
"""
Used to identify aliases of common comparison functions,
e.g., strcmp and curl_strequal, which are essentially the same.
"""
MEMCMP = 1
STRCMP = 2
STRNCMP = 3
STRCASECMP = 4
STRNCASECMP = 5
MEMCHR = 6
RETURN_STATUS_FUNCTION = 100
FUNCTION_ALIASES = {
# essentially strcmp
"strcmp": FunctionAlias.STRCMP,
"xmlStrcmp": FunctionAlias.STRCMP,
"xmlStrEqual": FunctionAlias.STRCMP,
"g_strcmp0": FunctionAlias.STRCMP,
"curl_strequal": FunctionAlias.STRCMP,
"strcsequal": FunctionAlias.STRCMP,
# essentially memcmp
"memcmp": FunctionAlias.MEMCMP,
"bcmp": FunctionAlias.MEMCMP,
"CRYPTO_memcmp": FunctionAlias.MEMCMP,
"OPENSSL_memcmp": FunctionAlias.MEMCMP,
"memcmp_const_time": FunctionAlias.MEMCMP,
"memcmpct": FunctionAlias.MEMCMP,
# essentially strncmp
"strncmp": FunctionAlias.STRNCMP,
"xmlStrncmp": FunctionAlias.STRNCMP,
"curl_strnequal": FunctionAlias.STRNCMP,
# strcasecmp
"strcasecmp": FunctionAlias.STRCASECMP,
"stricmp": FunctionAlias.STRCASECMP,
"ap_cstr_casecmp": FunctionAlias.STRCASECMP,
"OPENSSL_strcasecmp": FunctionAlias.STRCASECMP,
"xmlStrcasecmp": FunctionAlias.STRCASECMP,
"g_strcasecmp": FunctionAlias.STRCASECMP,
"g_ascii_strcasecmp": FunctionAlias.STRCASECMP,
"Curl_strcasecompare": FunctionAlias.STRCASECMP,
"Curl_safe_strcasecompare": FunctionAlias.STRCASECMP,
"cmsstrcasecmp": FunctionAlias.STRCASECMP,
# strncasecmp
"strncasecmp": FunctionAlias.STRNCASECMP,
"strnicmp": FunctionAlias.STRNCASECMP,
"ap_cstr_casecmpn": FunctionAlias.STRNCASECMP,
"OPENSSL_strncasecmp": FunctionAlias.STRNCASECMP,
"xmlStrncasecmp": FunctionAlias.STRNCASECMP,
"g_ascii_strncasecmp": FunctionAlias.STRNCASECMP,
"Curl_strncasecompare": FunctionAlias.STRNCASECMP,
"g_strncasecmp": FunctionAlias.STRNCASECMP,
"memchr": FunctionAlias.MEMCHR,
}
errored_functions = set()
class SnapchangeTask(BackgroundTaskThread):
TASK_NAME = "Snapchange Analysis"
def __init__(
self,
bv: bn.BinaryView,
ignore: Optional[List[str]] = None,
location: Optional[Path] = None,
):
"""
bv:
binaryview to work on - provided by the GUI or needs to be manually opened
location:
file location to save the result to
"""
BackgroundTaskThread.__init__(self, self.TASK_NAME, True)
self.bv = bv
self.ignore = ignore
self.location = location
class SnapchangeCoverageBreakpoints(SnapchangeTask):
TASK_NAME = "Snapchange Coverage Breakpoints"
def run(self):
log_info(f"Task '{self.TASK_NAME}' started")
bv = self.bv
binary = Path(bv.file.filename)
# binary_name = binary.with_suffix("").name
blacklist = DEFAULT_IGNORE
if self.ignore:
blacklist.extend(self.ignore)
log_info(f"Ignore functions: {blacklist}", LOG_ID)
ignored_functions = set()
# Collect functions not in the blacklist
funcs = []
for i, func in enumerate(bv.functions):
if self.cancelled:
return
self.progress = f"{self.TASK_NAME} - {i + 1} / {len(bv.functions)} funcs"
# If any of the blacklist substrings are found in the function name, ignore it
if any(black for black in blacklist if black in func.name):
log_debug(f"Ignoring {func.name}", LOG_ID)
ignored_functions.add(str(func))
continue
funcs.append(func)
# Looking to specifically ignore basic blocks of the `jmp` after an `asan_report` call
# This is due to that `jmp` being seen as the next source line in DWARF, making the .lcov
# coverage file inconsisent
# ┌─────────────────────────────────────────────────────────┐
# │ 0x5936e6 [og] │
# │ mov rax, qword [rbx + 0x260] │
# │ and rax, 7 │
# │ add rax, 1 │
# │ mov cl, byte [rbx + 0x257] │
# │ cmp al, cl │
# │ jl 0x593713 │
# └─────────────────────────────────────────────────────────┘
# f t
# │ │
# │ └────────────────────┐
# ┌───────────────┘ │
# │ │
# ┌───────────────────────────────────────┐ │
# │ [0x593707] │ │
# │ mov rdi, qword [rbx + 0x260] │ │
# │ call sym.__asan_report_store2_noabort │ │
# └───────────────────────────────────────┘ │
# v │
# │ │
# └────────────────┐ ┌───────────────────┘
# │ │
# │ │
# ┌────────────────────┐ <-- IGNORE THIS BLOCK
# │ 0x593713 [oj] │
# │ jmp 0x593718 │
# └────────────────────┘
bad_blocks = []
for func in funcs:
if self.cancelled:
return
for bb in func:
if (
bb.instruction_count == 1
and len(bb.outgoing_edges) == 1
and len(bb.incoming_edges) == 2
):
text = []
for edge in bb.incoming_edges:
block_text = [
str(x) for x in edge.source.get_disassembly_text()
]
text.extend(block_text)
text = " ".join(text)
if "asan_report" in text:
bad_blocks.append(bb.start)
# Get all basic block and block edges that aren't that asan_report finish basic block
blocks = []
for func in funcs:
if self.cancelled:
return
for bb in func:
if bb.start in bad_blocks:
continue
blocks.append(f"{bb.start:#x},{bb.length:#x}")
if ignored_functions:
log_info(f"ignored the following functions: {ignored_functions}", LOG_ID)
log_info(f"found {len(blocks)} basic blocks", LOG_ID)
if self.location:
location = self.location
else:
location = binary.parent / (binary.name + ".covbps")
log_info(f"Writing coverage breakpoints to '{location}'", LOG_ID)
with open(location, "w") as f:
f.write("\n".join(blocks))
log_info(f"Task '{self.TASK_NAME}' done")
class SnapchangeCovAnalysis(SnapchangeTask):
"""
Background task for coverage analysis consumable by snapchange.
"""
TASK_NAME = "Snapchange Coverage Analysis"
def run(self):
log_info(f"Task '{self.TASK_NAME}' started")
bv = self.bv
binary = Path(bv.file.filename)
binary_name = binary.with_suffix("").name
blacklist = DEFAULT_IGNORE
if self.ignore:
blacklist.extend(self.ignore)
log_info(f"Ignore functions: {blacklist}", LOG_ID)
# Lookup table from address to index into the list of basic blocks
lookup = {}
# All basic block nodes
nodes = []
# Found cross references from functions. Used identify "parent" edges to functions to
# allow for inter-functional updates of scores.
function_calls = []
ignored_functions = set()
for i, func in enumerate(bv.functions):
if self.cancelled:
return
self.progress = f"{self.TASK_NAME} - {i + 1} / {len(bv.functions)} funcs"
# If any of the blacklist substrings are found in the function name, ignore it
if any(black for black in blacklist if black in func.name):
log_debug(f"Ignoring {func.name}", LOG_ID)
ignored_functions.add(str(func))
continue
# if func.analysis_skipped:
# fn = str(func)
# if fn not in errored_functions:
# skip_reason = str(func.analysis_skip_reason)
# log_warn(f"Analysis skipped for {func} | {skip_reason}")
# errored_functions.add(func)
# If this function doesn't have LLIL, display the warning only once
if func.low_level_il is None:
fn = str(func)
if fn not in errored_functions:
log_warn(f"Analysis skipped for {func} | missing LLIL")
errored_functions.add(func)
for bb in func:
# Get the starting address for this basic block
start = bb.start
# Cache this node for easy lookup by address
lookup[start] = len(nodes)
# Initialize this node's data
node = {}
node["address"] = start
node["children"] = list(set(x.target.start for x in bb.outgoing_edges))
node["dominator_tree_children"] = set(
x.start for x in bb.dominator_tree_children + bb.dominance_frontier
)
node["parents"] = set()
# Add incoming edges that are not in a loop
for edge in bb.incoming_edges:
incoming_block = edge.source
in_loop = False
# Check if the current basic block is in the incoming edge's dominator
# If so, it is part of a loop and should not be considered when backtracking
# information through the incoming edges
for dom in incoming_block.dominators:
if bb.start == dom.start:
# log_warn(f"Ignoring loop basic block! {incoming_block.start:#x} in loop {dom.start:#x}")
in_loop = True
if not in_loop:
node["parents"].add(incoming_block.start)
node["function"] = func.name
node["function_offset"] = start - func.start
node["called_funcs"] = []
node["dominators"] = list(
set(x.start for x in bb.dominators if x.start != start)
)
if func.llil:
# Check if there is a constant function in the block. If so, add the function as child.
llil = func.get_low_level_il_at(start)
if not hasattr(llil, "il_basic_block"):
continue
if llil.il_basic_block is None:
continue
for il in llil.il_basic_block:
if not il.operation == LowLevelILOperation.LLIL_CALL:
continue
if not il.dest.operation == LowLevelILOperation.LLIL_CONST_PTR:
continue
# Ensure the called function isn't on the blacklist
called_func = bv.get_function_at(il.dest.constant)
# If any of the blacklist substrings are found in the function name, ignore it
if hasattr(called_func, "name") and any(
[black for black in blacklist if black in called_func.name]
):
# log_warn(f"Ignoring called {called_func.name} from {func.name}")
continue
# Do not recurse into the current function
if called_func == func:
continue
# Found a function that is called in this basic block. Add this function
# to the node to add the score of the entire function to this basic block
node["called_funcs"].append(il.dest.constant)
function_calls.append((start, il.dest.constant))
node["dominator_tree_children"] = list(node["dominator_tree_children"])
# Add the node to the list of all nodes
nodes.append(node)
# Add the found function cross references as parents for each function to allow
# inter-funtion score updates
for (caller, callee) in function_calls:
node_index = lookup.get(callee, None)
if node_index is None:
# node_addr = node['address']
callee = int(callee)
caller = int(caller)
log_error(
f"ERROR: Check this called function! Function call not found: {caller:#x} -> {callee:#x}",
LOG_ID,
)
else:
nodes[node_index]["dominators"].append(caller)
if ignored_functions:
log_info(f"ignored the following functions: {ignored_functions}", LOG_ID)
# Make the `parents` a list to allow for JSON serialization
for node in nodes:
node["parents"] = list(node["parents"])
filename = binary.parent / f"{binary_name}.coverage_analysis"
if self.location:
location = self.location
else:
location = filename
log_info(f"Writing coverage analysis to '{location}'", LOG_ID)
with open(location, "w") as f:
f.write(json.dumps(nodes))
log_info(f"Task '{self.TASK_NAME}' done")
class SnapchangeCmpAnalysis(SnapchangeTask):
TASK_NAME = "Snapchange Cmp Analysis"
def __init__(
self,
bv: bn.BinaryView,
ignore: Optional[List[str]] = None,
cmp_location: Optional[Path] = None,
dict_location: Optional[Path] = None,
):
"""
bv:
binaryview to work on - provided by the GUI or needs to be manually opened
location:
file location to save the result to
"""
BackgroundTaskThread.__init__(self, self.TASK_NAME, True)
self.bv = bv
self.ignore = ignore
self.cmp_location = None
if cmp_location:
self.cmp_location = Path(cmp_location)
self.dict_location = None
if dict_location:
self.dict_location = Path(dict_location)
def run(self):
log_info(f"Task '{self.TASK_NAME}' started")
cmps, autodict = run_cmp_analysis(self.bv, self.ignore, self)
if self.cancelled or (cmps is None and autodict is None):
return
if self.cmp_location:
log_info(f"discovered {len(cmps)} comparison instructions for redqueen/input-to-state")
with self.cmp_location.open("w") as f:
f.write("\n".join(map(lambda c: str(c).strip(), cmps)))
if self.dict_location:
self.dict_location.mkdir(parents=True, exist_ok=True)
ints = sum(isinstance(o, int) for o in autodict)
floats = sum(isinstance(o, float) for o in autodict)
bytess = sum(isinstance(o, bytes) or isinstance(o, str) for o in autodict)
others = len(autodict) - ints - floats - bytess
log_info(f"discovered {len(autodict)} dictionary entries ({ints} int, {floats} float, {bytess} strings, {others} others)")
for entry in autodict:
write_dict_entry(entry, self.dict_location)
log_info(f"Task '{self.TASK_NAME}' done")
def write_dict_entry(entry, location: Path):
if isinstance(entry, int):
entry = abs(entry)
# identify the size of constant - we always use the smallest possible one
if entry < (1 << 8):
# we don't bother with byte-size constants
return
if entry < (1 << 16):
size = 2
elif entry < (1 << 32):
size = 4
elif entry < (1 << 64):
size = 8
elif entry < (1 << 128):
size = 16
elif entry < (1 << 256):
size = 32
elif entry < (1 << 512):
size = 64
else:
log_warn("unsupported int constant is too big: " + hex(entry))
# emit both endian - who knows.
for endian in ("little", "big"):
data = entry.to_bytes(size, endian)
fname = endian + "_" + hex(entry)
with (location / fname).open("wb") as f:
f.write(data)
# emit as ascii str
fname = "int_str_" + str(entry).replace("-", "neg")
with (location / fname).open("w") as f:
f.write(str(entry))
elif isinstance(entry, float):
# emit using struct.pack in various formats
for float_fmt in ("e", "f", "d"):
for endian in (("<", "le"), (">", "be")):
fmt = endian[0] + float_fmt
try:
buf = struct.pack(fmt, entry)
# don't write all 0 buffers to dict
if all(b == 0 for b in buf):
continue
fname = "_".join([float_fmt, endian[1], hex(hash(entry))[2:]])
with (location / fname).open("wb") as f:
f.write(buf)
except (ValueError, OverflowError):
pass
# emit as ascii str
fname = "float_str_" + str(entry).replace(".", "_").replace("-", "neg")
with (location / fname).open("w") as f:
str_entry = str(entry)
if str_entry not in ("0.0"):
f.write(str_entry)
elif isinstance(entry, (bytes, str)):
fname = hex(abs(hash(entry)))
if isinstance(entry, str):
fname += "_" + "".join(e if e in ALPHANUM else "_" for e in entry[:8])
entry = entry.encode()
else:
if all(chr(b) in ALPHANUM for b in entry):
fname += "_" + entry.decode()[:8]
else:
fname += "_" + entry.hex()[:8]
with (location / fname).open("wb") as f:
f.write(entry)
entry_stripped = entry.strip(b"\x00\t \n\r")
if entry_stripped != entry:
with (location / (str(fname) + "_trimmed")).open("wb") as f:
f.write(entry_stripped)
else:
log_warn(f"cannot deal with {type(entry)} in auto-dict {entry!r}")
def int_is_interesting_for_dict(i, size, _bv=None):
if i == 0:
return False
if i < 256:
return False
if size == 0:
size = 4
# convert to signed
i_s = i
if i_s & (1 << (size - 1)):
i_s = -(1 << size) + i_s
if abs(i_s) < 256: # small signed constant
return False
for bits in (8, 16, 32, 64, 128, 256, 512):
if bits > size:
break
shift = 1 << bits
if i in (shift, shift - 1):
return False
# check if negative power
if abs(i) in (shift, shift - 1):
return False
# check for some bitmask-like things to weed out.
mask = 0
for shift in range(0, 60, 4):
mask = mask << 4
mask |= 0xF
if i == mask:
return False
try:
if all(b in (0, 0xFF, 0xF0, 0x0F) for b in i.to_bytes(size, "little")):
return False
except OverflowError:
pass
# TODO: check if address -> ignore
# if bv and bv.start <= i and i <= bv.end:
# return False
# ok we found no reason to not find it interesting.
return True
def float_is_interesting_for_dict(f, size):
if math.isnan(f): # ignore NaN
return False
if size < 4: # ignore tiny floats
return False
if f == 0.0: # ignore 0
return False
# ok we found no reason to not find it interesting.
return True
def bytes_is_interesting_for_dict(b):
if len(b) < 2:
return False
if all(i in (0, 0xff) for i in b):
return False
return True
def add_memory_to_dict(
dictionary, bv, addr, memlen=STR_LEN_THRESHOLD, null_term=False, both_cases=False
):
# log_warn(f"adding addr {addr} to dict with len {memlen}")
if addr is None or memlen is None:
return
if not isinstance(memlen, int):
try:
memlen = int(memlen, 0)
except ValueError:
return False
if memlen <= 2:
return False
if isinstance(addr, int):
pass # all good
elif isinstance(addr, str):
if "reg" in addr:
return False
try:
addr = int(addr, 0)
except ValueError:
s = f"cannot convert addr str {addr!r} to concrete address (type int)"
log_error(s)
return False
elif hasattr(addr, "constant"):
addr = int(addr.constant)
else:
s = f"require addr to bye of type int; got {addr!r}"
log_error(s)
raise ValueError(s)
if memlen > STR_LEN_THRESHOLD:
return FAlse
log_debug(f"auto-dict read memory @ '{addr:#x}' len {memlen}")
data = bv.read(addr, memlen)
if not data:
log_debug(f"auto-dict found no data at addr @ {addr:#x}")
return
if null_term:
term = data.find(0)
if term > 0:
data = data[:term]
if len(data) <= 2: # ignore short strings
return
dictionary.add(data)
log_debug(f"added data to dictionary: {data!r}")
if both_cases:
dictionary.add(data.upper())
dictionary.add(data.lower())
return True
def add_const_to_dict(bv, dictionary, c, c_size, is_float=False):
real_size = 0
# is_float = False
if isinstance(c_size, str):
if c_size[0] == "f":
is_float = True
c_size = c_size[1:]
real_size = int(c_size, 0)
else:
real_size = c_size
if not c_size and isinstance(c, bytes):
real_size = len(c)
if isinstance(c, bytes): # was given raw bytes
assert len(c) >= real_size
if real_size in (2, 4, 8, 16) and not is_float:
c = int.from_bytes(c, "little")
elif is_float and real_size in (2, 4, 8):
dictionary.add(c)
if real_size == 4:
c = struct.unpack("@f", c)[0]
elif real_size == 8:
c = struct.unpack("@d", c)[0]
elif real_size == 2:
c = struct.unpack("@e", c)[0]
elif isinstance(c, str):
if c.startswith("load_from"):
x = c.split(" ")
addr = None
if len(x) > 1:
try:
addr = int(x[1], 0)
except ValueError:
addr = None
if addr is not None:
if not is_float:
try:
c = bv.read_int(addr, real_size)
except ValueError:
pass
else:
# for floating points, we read the data as bytes
data = bv.read(addr, real_size)
# add the float bytes to the dictionary
dictionary.add(c)
# but we also attempt to convert to an actual float value using struct
# not sure this is always accurate.
try:
if real_size == 4:
c = struct.unpack("@f", data)[0]
elif real_size == 8:
c = struct.unpack("@d", data)[0]
elif real_size == 2:
c = struct.unpack("@e", data)[0]
except ValueError:
return
else:
# can't load non-constant from memory...
return
elif c.startswith("reg"):
# not a constant
return
else:
try:
if is_float or "." in c:
c = float(c)
else:
c = int(c, 0)
except ValueError:
# log_warn(f"failed to convert {c!r} into number")
return
if isinstance(c, int):
if int_is_interesting_for_dict(c, real_size, bv):
dictionary.add(c)
elif isinstance(c, float):
if float_is_interesting_for_dict(c, real_size):
dictionary.add(c)
elif isinstance(c, bytes):
if bytes_is_interesting_for_dict(c):
dictionary.add(c)
else:
# is there something else?
dictionary.add(c)
def find_const_definition(instr):
find_ssa_defs = [instr]
# this is a non-exhaustive ssa backtracking thing. it is mostly to cover patterns like:
# ```
# reg0 = [constptr]
# if (reg0 == reg1) ...
# ```
while find_ssa_defs:
curr_instr = find_ssa_defs.pop()
if is_instr_const(curr_instr):
return curr_instr
elif curr_instr.operation == LowLevelILOperation.LLIL_REG:
ssa_reg = curr_instr.ssa_form
if hasattr(ssa_reg, "full_reg"):
ssa_reg = ssa_reg.full_reg
elif hasattr(ssa_reg, "src"):
ssa_reg = ssa_reg.src
if (
hasattr(ssa_reg, "operation")
and ssa_reg.operation == LowLevelILOperation.LLIL_CONST
):
return ssa_reg
else:
definition = (
curr_instr.function.ssa_form.get_ssa_reg_definition(
ssa_reg
)
)
if definition:
if hasattr(definition, "non_ssa_form"):
find_ssa_defs.append(definition.non_ssa_form)
else:
log_warn(f"{curr_instr} -> definition {definition} -> has no non-ssa-form ")
elif curr_instr.operation == LowLevelILOperation.LLIL_SET_REG:
find_ssa_defs.append(curr_instr.src)
elif curr_instr.operation == LowLevelILOperation.LLIL_LOAD:
iload = curr_instr
if iload.src.operation == LowLevelILOperation.LLIL_CONST_PTR:
return iload.src
return None
def get_const_from_reg_param_at(callinst, regidx):
if not hasattr(callinst, "ssa_form"):
log_warn(f"call instruction `{callinst}` does not have .ssa_form - odd?")
return None
params = getattr(callinst.ssa_form, "params", None)
if params is None:
log_warn("seems you are on an old binja version. using workaround to retrieve callinst.ssa_form.params")
params = callinst.ssa_form.param.src
if regidx > len(params):
return None
reg = params[regidx].operands[0]
defn = callinst.function.get_ssa_reg_definition(reg)
if not defn:
return None
return find_const_definition(defn)
def run_cmp_analysis(bv, ignore=None, taskref=None):
blacklist = DEFAULT_IGNORE
if ignore:
blacklist.extend(ignore)
log_info(f"Ignore functions: {blacklist}", LOG_ID)
ignored_functions = set()
cmps = []
dictionary = set()
ignored_addresses = []
for _i, func in enumerate(bv.functions):
if taskref and taskref.cancelled:
return (None, None)
# If any of the blacklist substrings are found in the function name, ignore it
if any(black for black in blacklist if black in func.name):
log_debug(f"Ignoring {func.name}", LOG_ID)
ignored_functions.add(str(func))
continue
if func.low_level_il is None:
log_warn(f"skipping func {func!r}, because of missing LLIL")
continue
# Get the number of LLIL expressions (not instructions) for this function
num_exprs = core.BNGetLowLevelILExprCount(func.llil.handle)
# Iterate over the expressions specifically
for expr_index in range(num_exprs):
instr = LowLevelILInstruction.create(func.llil, expr_index, None)
# If this instruction uses the result of a memcmp/strcmp, ignore the
# condition as a rule has already been added from the strcmp/memcmp call site
if instr.address in ignored_addresses:
log_warn(f"Ignoring instruction found in ignored_addresses: {instr}")
continue
if instr.operation == LowLevelILOperation.LLIL_CALL:
# Only interested in const pointer function calls
if instr.dest.operation != LowLevelILOperation.LLIL_CONST_PTR:
continue
s = bv.get_symbol_at(instr.dest.constant)
if not s: # check that there is a symbol
continue
func_name = s.name
func_alias = FUNCTION_ALIASES.get(func_name)
if func_alias is not None:
# Get the registers used for the calling convention
param_regs = (
instr.function.source_function.calling_convention.int_arg_regs
)
# Create the register parameters
params = [f"reg {param_reg}" for param_reg in param_regs]
log_debug(
f"cmp function {instr.address:#x} {func_name} -> {func_alias!r} params: {params!r}"
)
strcmps = (
FunctionAlias.STRCMP,
FunctionAlias.STRCASECMP,
FunctionAlias.STRNCMP,
FunctionAlias.STRNCASECMP,
)
if func_alias in strcmps and len(params) >= 2 and all(params[:2]):
res = f"{instr.address:#x},0x0,{params[0]},strcmp,{params[1]}\n"
cmps.append(res)
# auto-dict code
if func_alias in strcmps:
memlen = STR_LEN_THRESHOLD
if (
func_alias
in (FunctionAlias.STRNCMP, FunctionAlias.STRNCASECMP)
):
x = get_const_from_reg_param_at(instr, 2)
if x:
memlen = int(x)
both_cases = func_alias in (
FunctionAlias.STRNCASECMP,
FunctionAlias.STRCASECMP,
)
for reg_idx in (0, 1):
p_addr = get_const_from_reg_param_at(instr, reg_idx)
if p_addr:
add_memory_to_dict(
dictionary,
bv,
int(p_addr),
null_term=True,
memlen=memlen,
both_cases=both_cases,
)
if len(params) >= 3 and func_alias == FunctionAlias.MEMCMP:
try:
cmp_len = int(params[2], 0)
except ValueError:
cmp_len = params[2]
assert cmp_len
res = f"{instr.address:#x},{cmp_len},{params[0]},memcmp,{params[1]}\n"
if "flag" not in res:
cmps.append(res)
else:
log_warn(f"Flag found! {res}")
if func_alias == FunctionAlias.MEMCMP:
cmp_len = get_const_from_reg_param_at(instr, 2)
if cmp_len:
cmp_len = int(cmp_len)
for reg_idx in (0, 1):
p_addr = get_const_from_reg_param_at(instr, reg_idx)
if p_addr:
add_memory_to_dict(
dictionary,
bv,
int(p_addr),
null_term=False,
memlen=(cmp_len if cmp_len else STR_LEN_THRESHOLD),
)
if len(params) >= 3 and func_alias == FunctionAlias.MEMCHR:
cmp_len = None
if isinstance(params[2], int):
cmp_len = params[2]
elif isinstance(params[2], str):
try:
cmp_len = int(params[2], 0)
except ValueError:
cmp_len = params[2]
if cmp_len is not None:
res = f"{instr.address:#x},{cmp_len},{params[0]},memchr,{params[1]}\n"
if "flag" not in res:
cmps.append(res)
if instr.operation in [
LowLevelILOperation.LLIL_CMP_E,
LowLevelILOperation.LLIL_CMP_NE,
LowLevelILOperation.LLIL_CMP_SLT,
LowLevelILOperation.LLIL_CMP_ULT,
LowLevelILOperation.LLIL_CMP_SLE,
LowLevelILOperation.LLIL_CMP_ULE,
LowLevelILOperation.LLIL_CMP_SGE,
LowLevelILOperation.LLIL_CMP_UGE,
LowLevelILOperation.LLIL_CMP_SGT,
LowLevelILOperation.LLIL_CMP_UGT,
LowLevelILOperation.LLIL_FCMP_E,
LowLevelILOperation.LLIL_FCMP_NE,
LowLevelILOperation.LLIL_FCMP_LT,
LowLevelILOperation.LLIL_FCMP_LE,
LowLevelILOperation.LLIL_FCMP_GE,
LowLevelILOperation.LLIL_FCMP_GT,
LowLevelILOperation.LLIL_INTRINSIC,
]:
is_float = False
if instr.operation in (
LowLevelILOperation.LLIL_FCMP_E,
LowLevelILOperation.LLIL_FCMP_NE,
LowLevelILOperation.LLIL_FCMP_LT,
LowLevelILOperation.LLIL_FCMP_LE,
LowLevelILOperation.LLIL_FCMP_GE,
LowLevelILOperation.LLIL_FCMP_GT,
):
is_float = True
find_ssa_defs = []
if instr.operation != LowLevelILOperation.LLIL_INTRINSIC:
for curr_instr in (instr.left, instr.right):
find_ssa_defs.append(curr_instr)