This repository has been archived by the owner on Aug 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 341
/
get_cfg.py
1823 lines (1462 loc) · 60.8 KB
/
get_cfg.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 python
# Copyright (c) 2020 Trail of Bits, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import idautils
import idaapi
import ida_funcs
import idc
import sys
import os
import argparse
import struct
import traceback
import collections
import itertools
import pprint
# Bring in utility libraries.
from util import *
from table import *
from flow import *
from refs import *
from segment import *
from exception import *
# Bring in Anvill
try:
import anvill
except:
import anvill_compat as anvill
ANVILL_PROGRAM = None
#hack for IDAPython to see google protobuf lib
_VERSION_NUM = "{}.{}".format(sys.version_info[0], sys.version_info[1])
if os.path.isdir('/usr/lib/python{}/dist-packages'.format(_VERSION_NUM)):
sys.path.append('/usr/lib/python{}/dist-packages'.format(_VERSION_NUM))
if os.path.isdir('/usr/local/lib/python{}/dist-packages'.format(_VERSION_NUM)):
sys.path.append('/usr/local/lib/python{}/dist-packages'.format(_VERSION_NUM))
tools_disass_ida_dir = os.path.dirname(__file__)
tools_disass_dir = os.path.dirname(tools_disass_ida_dir)
# Note: The bootstrap file will copy CFG_pb2.py into this dir!!
import CFG_pb2
EXTERNAL_FUNCS_TO_RECOVER = {}
EXTERNAL_VARS_TO_RECOVER = {}
RECOVERED_EAS = set()
ACCESSED_VIA_JMP = set()
TO_RECOVER = {
"stack_var" : False,
}
RECOVER_EHTABLE = False
PERSONALITY_FUNCTIONS = [
"__gxx_personality_v0",
"__gnat_personality_v0"
]
# Map of external functions names to a tuple containing information like the
# number of arguments and calling convention of the function.
EMAP = {}
# Map of external variable names to their sizes, in bytes.
EMAP_DATA = {}
# Map of the functions which are forced to be extern and does not require to
# be recovered.
FORCED_EXTERNAL_EMAP = {}
# `True` if we are getting the CFG of a position independent executable. This
# affects heuristics like trying to turn immediate operands in instructions
# into references into the data.
PIE_MODE = False
# Name of the operating system that runs the program being lifted. E.g. if
# we're lifting an ELF then this will typically be `linux`.
OS_NAME = ""
# Set of substrings that can be found inside of symbol names that are usually
# signs that the symbol is external. For example, `stderr@@GLIBC_2.2.5` is
# really the external `stderr`, so we want to be able to chop out the `@@...`
# part to resolve the "true" name. There are a lot of `@@` variants in PE files,
# e.g. `@@QEAU_..`, `@@AEAV..`, though these are likely for name mangling.
EXTERNAL_NAMES = ("@@GLIBC_", "@@GLIBCXX_", "@@CXXABI_", "@@GCC_")
_NOT_ELF_BEGIN_EAS = (0xffffffff, 0xffffffffffffffff)
# Returns `True` if this is an ELF binary (as opposed to an ELF object file).
def is_linked_ELF_program():
global _NOT_ELF_BEGIN_EAS
return IS_ELF and idc.get_inf_attr(INF_START_EA) not in _NOT_ELF_BEGIN_EAS
def is_ELF_got_pointer(ea):
"""Returns `True` if this is a pointer to a pointer stored in the
`.got` section of an ELF binary. For example, `__gmon_start___ptr` is
a pointer in the `.got` that will be fixed up to contain the address of
the external function `__gmon_start__`. We don't want to treat
`__gmon_start___ptr` as external because it is really a sort of local
variable that will will resolve with a data cross-reference."""
seg_name = idc.get_segm_name(ea).lower()
if ".got" not in seg_name:
return False
name = get_symbol_name(ea)
target_ea = get_reference_target(ea)
target_name = get_true_external_name(get_symbol_name(target_ea))
if target_name not in name:
return False
return is_referenced_by(target_ea, ea)
def is_ELF_got_pointer_to_external(ea):
"""Similar to `is_ELF_got_pointer`, but requires that the eventual target
of the pointer is an external."""
if not is_ELF_got_pointer(ea):
return False
target_ea = get_reference_target(ea)
return is_external_segment(target_ea)
_FIXED_EXTERNAL_NAMES = {}
def demangled_name(name):
"""Tries to demangle a functin name."""
try:
dname = idc.demangle_name(name, idc.get_inf_attr(INF_SHORT_DN))
if dname and len(dname) and "::" not in dname:
dname = dname.split("(")[0]
dname = dname.split(" ")[-1]
if re.match(r"^[a-zA-Z0-9_]+$", dname):
return dname
return name
except:
return name
def get_true_external_name(fn, demangle=True):
"""Tries to get the 'true' name of `fn`. This removes things like
ELF-versioning from symbols."""
if not fn:
return ""
orig_fn = fn
if fn in _FIXED_EXTERNAL_NAMES:
return _FIXED_EXTERNAL_NAMES[orig_fn]
if fn in EMAP:
return fn
if fn in EMAP_DATA:
return fn
# Try to demangle the name, but don't do it if looks like there's a C++
# namespace.
if demangle:
fn = demangled_name(fn)
# TODO(pag): Is this a macOS or Windows thing?
if not is_linked_ELF_program() and fn[0] == '_':
return fn[1:]
if fn.endswith("_0"):
newfn = fn[:-2]
if newfn in EMAP:
return newfn
# Go and strip off things like the `@@GLIBC_*` symbol suffixes.
for en in EXTERNAL_NAMES:
if en in fn:
fn = fn[:fn.find(en)]
break
if orig_fn != fn:
DEBUG("True name of {} is {}".format(orig_fn, fn))
_FIXED_EXTERNAL_NAMES[orig_fn] = fn
return fn
# Set of symbols that IDA identifies as being "weak" symbols. In ELF binaries,
# a weak symbol is kind of an optional linking thing. For example, the
# `__gmon_start__` function is referenced as a weak symbol. This function is
# used for gcov-based profiling. If gcov is available, then this symbol will
# be resolved to a real function, but if not, it will be NULL and programs
# will detect it as such. An example use of a weak symbol in C would be:
#
# extern void __gmon_start__(void) __attribute__((weak));
# ...
# if (__gmon_start__) {
# __gmon_start__();
# }
WEAK_SYMS = set()
# Used to track thunks that are actually implemented. For example, in a static
# binary, you might have a bunch of calls to `strcpy` in the `.plt` section
# that go through the `.plt.got` to call the implementation of `strcpy` compiled
# into the binary.
INTERNALLY_DEFINED_EXTERNALS = {} # Name external to EA of internal.
INTERNAL_THUNK_EAS = {} # EA of thunk to EA of implementation.
def parse_os_defs_file(df):
"""Parse the file containing external function and variable
specifications."""
global OS_NAME, WEAK_SYMS, EMAP, EMAP_DATA
global _FIXED_EXTERNAL_NAMES, INTERNALLY_DEFINED_EXTERNALS
is_linux = OS_NAME == "linux"
for l in df.readlines():
#skip comments / empty lines
l = l.strip()
if not l or l[0] == "#":
continue
if l.startswith('DATA:'):
# process as data
(marker, symname, dsize) = l.split()
if 'PTR' in dsize:
dsize = get_address_size_in_bytes()
EMAP_DATA[symname] = int(dsize)
else:
fname = args = conv = ret = sign = None
line_args = l.split()
if len(line_args) == 4:
(fname, args, conv, ret) = line_args
elif len(line_args) == 5:
(fname, args, conv, ret, sign) = line_args
if conv == "C":
realconv = CFG_pb2.ExternalFunction.CallerCleanup
elif conv == "E":
realconv = CFG_pb2.ExternalFunction.CalleeCleanup
elif conv == "F":
realconv = CFG_pb2.ExternalFunction.FastCall
else:
DEBUG("ERROR: Unknown calling convention: {}".format(l))
continue
if ret not in "YN":
DEBUG("ERROR: Unknown return type {} in {}".format(ret, l))
continue
ea = idc.get_name_ea_simple(fname)
if not is_invalid_ea(ea):
if not is_external_segment(ea) and not is_thunk(ea):
DEBUG("Not treating {} as external, it is defined at {:x}".format(
fname, ea))
INTERNALLY_DEFINED_EXTERNALS[fname] = ea
continue
# Misidentified and external. This comes up often in PE binaries, for
# example, we will have the following:
#
# .idata:01400110E8 ; void __stdcall EnterCriticalSection(...)
# .idata:01400110E8 extrn EnterCriticalSection:qword
#
# Really, we want to try this as code.
flags = idc.get_full_flags(ea)
if not idc.is_code(flags) and not idaapi.is_weak_name(ea):
seg_name = idc.get_segm_name(ea).lower()
if ".idata" in seg_name:
EXTERNAL_FUNCS_TO_RECOVER[ea] = fname
# Refer to issue #308
else:
DEBUG("WARNING: External {} at {:x} from definitions file may not be a function".format(
fname, ea))
EMAP[fname] = (int(args), realconv, ret, sign)
if ret == 'Y':
noreturn_external_function(fname, int(args), realconv, ret, sign)
# Sometimes there will be things like `__imp___gmon_start__` which
# is really the implementation of `__gmon_start__`, where that is
# a weak symbol.
if is_linux:
imp_name = "__imp_{}".format(fname)
if idc.get_name_ea_simple(imp_name):
_FIXED_EXTERNAL_NAMES[imp_name] = fname
WEAK_SYMS.add(fname)
WEAK_SYMS.add(imp_name)
df.close()
def parse_fextern_defs_file(df):
"""Parse the file containing forced external function which
does not need to be recovered.
"""
global FORCED_EXTERNAL_EMAP
for l in df.readlines():
#skip comments / empty lines
l = l.strip()
if not l or l[0] == "#":
continue
fname = args = conv = ret = None
line_args = l.split()
if len(line_args) == 4:
(fname, args, conv, ret) = line_args
if conv == "C":
realconv = CFG_pb2.ExternalFunction.CallerCleanup
elif conv == "E":
realconv = CFG_pb2.ExternalFunction.CalleeCleanup
elif conv == "F":
realconv = CFG_pb2.ExternalFunction.FastCall
else:
DEBUG("ERROR: Unknown calling convention for forced extern : {}".format(l))
continue
if ret not in "YN":
DEBUG("ERROR: Unknown return type {} in {}".format(ret, l))
continue
ea = idc.get_name_ea_simple(fname)
FORCED_EXTERNAL_EMAP[fname] = (int(args), realconv, ret, None)
df.close()
def is_external_reference(ea):
"""Returns `True` if `ea` references external data."""
return is_external_segment(ea) \
or ea in EXTERNAL_VARS_TO_RECOVER \
or ea in EXTERNAL_FUNCS_TO_RECOVER
def get_function_name(ea):
"""Return name of a function, as IDA sees it. This includes allowing
dummy names, e.g. `sub_abc123`."""
return get_symbol_name(ea, ea, allow_dummy=True)
def undecorate_external_name(fn):
# Don't mangle symbols for fully linked ELFs... yet
in_a_map = fn in EMAP or fn in EMAP_DATA
if not is_linked_ELF_program():
if fn.startswith("__imp_"):
fn = fn[6:]
if fn.endswith("_0"):
fn = fn[:-2]
# name could have been modified by the above tests
in_a_map = fn in EMAP or fn in EMAP_DATA
if fn.startswith("_") and not in_a_map:
fn = fn[1:]
if fn.startswith("@") and not in_a_map:
fn = fn[1:]
if IS_ELF and '@' in fn:
fn = fn[:fn.find('@')]
fixfn = get_true_external_name(fn)
return fixfn
_ELF_THUNKS = {}
_NOT_ELF_THUNKS = set()
_INVALID_THUNK = (False, idc.BADADDR, "")
_INVALID_THUNK_ADDR = (False, idc.BADADDR)
# NOTE(pag): `is_ELF_thunk_by_structure` is arch-specific.
def is_thunk_by_flags(ea):
"""Try to identify a thunk based off of the IDA flags. This isn't actually
specific to ELFs.
IDA seems to have a kind of thunk-propagation. So if one thunk calls
another thunk, then the former thing is treated as a thunk. The former
thing will not actually follow the 'structured' form matched above, so
we'll try to recursively match to the 'final' referenced thunk."""
global _INVALID_THUNK_ADDR
if not is_thunk(ea):
return _INVALID_THUNK_ADDR
ea_name = get_function_name(ea)
inst, _ = decode_instruction(ea)
if not inst:
DEBUG("WARNING: {} at {:x} is a thunk with no code??".format(ea_name, ea))
return _INVALID_THUNK_ADDR
# Recursively find thunk-to-thunks.
if is_direct_jump(inst) or is_direct_function_call(inst):
targ_ea = get_direct_branch_target(inst)
targ_is_thunk = is_thunk(targ_ea)
if targ_is_thunk:
targ_thunk_name = get_symbol_name(ea, targ_ea)
DEBUG("Found thunk-to-thunk {:x} -> {:x}: {} to {}".format(
ea, targ_ea, ea_name, targ_thunk_name))
return True, targ_ea
DEBUG("ERROR? targ_ea={:x} is not thunk".format(targ_ea))
if not is_external_reference(ea):
return _INVALID_THUNK_ADDR
return True, targ_ea
def try_get_thunk_name(ea):
"""Try to figure out if a function is actually a thunk, i.e. a function
that represents a 'local' definition for an external function. Thunks work
by having the local function jump through a function pointer that is
resolved at runtime."""
global _ELF_THUNKS, _NOT_ELF_THUNKS, _INVALID_THUNK
if ea in _ELF_THUNKS:
return _ELF_THUNKS[ea]
if ea in _NOT_ELF_THUNKS:
_NOT_ELF_THUNKS.add(ea)
return _INVALID_THUNK
# Try two approaches to detecting whether or not
# something is a thunk.
is_thunk = False
target_ea = idc.BADADDR
if IS_ELF:
is_thunk, target_ea = is_ELF_thunk_by_structure(ea)
if not is_thunk:
is_thunk, target_ea = is_thunk_by_flags(ea)
if not is_thunk:
_NOT_ELF_THUNKS.add(ea)
return _INVALID_THUNK
else:
name = get_function_name(target_ea)
name = undecorate_external_name(name)
name = get_true_external_name(name)
# if the elf thunk name is not in external table
if name not in EMAP:
DEBUG("WARNING: Adding {} as external function".format(name))
EMAP[name] = (16, CFG_pb2.ExternalFunction.CallerCleanup, "N", None)
ret = (is_thunk, target_ea, name)
_ELF_THUNKS[ea] = ret
return ret
_REFERENCE_OPERAND_TYPE = {
Reference.IMMEDIATE: CFG_pb2.CodeReference.ImmediateOperand,
Reference.DISPLACEMENT: CFG_pb2.CodeReference.MemoryDisplacementOperand,
Reference.MEMORY: CFG_pb2.CodeReference.MemoryOperand,
Reference.CODE: CFG_pb2.CodeReference.ControlFlowOperand,
}
def reference_operand_type(ref):
global _REFERENCE_OPERAND_TYPE
return _REFERENCE_OPERAND_TYPE[ref.type]
def referenced_name(ref):
if ref.ea in EXTERNAL_VARS_TO_RECOVER:
return EXTERNAL_VARS_TO_RECOVER[ref.ea]
elif ref.ea in EXTERNAL_FUNCS_TO_RECOVER:
return EXTERNAL_FUNCS_TO_RECOVER[ref.ea]
else:
return get_true_external_name(ref.symbol)
_OPERAND_NAME = {
CFG_pb2.CodeReference.ImmediateOperand: "imm",
CFG_pb2.CodeReference.MemoryDisplacementOperand: "disp",
CFG_pb2.CodeReference.MemoryOperand: "mem",
CFG_pb2.CodeReference.ControlFlowOperand: "flow",
}
def format_instruction_reference(ref):
"""Returns a string representation of a cross reference contained
in an instruction."""
mask_begin = ""
mask_end = ""
if ref.mask:
mask_begin = "("
mask_end = " & {:x})".format(ref.mask)
return "({} {}{:x}{})".format(
_OPERAND_NAME[ref.operand_type],
mask_begin,
ref.ea,
mask_end)
def recover_instruction_references(I, inst, addr, refs):
"""Add the memory/code reference information from this instruction
into the CFG format. The LLVM side of things needs to be able to
match instruction operands to references to internal/external
code/data.
The `get_instruction_references` gives us an accurate picture of the
references as they are, but in practice we want a higher-level perspective
that resolves things like thunks to their true external representations.
Note: References are a kind of gotcha that need special explaining. We kind
of 'devirtualize' references. An example of this is:
extern:00000000002010A8 extrn stderr@@GLIBC_2_2_5
extern:00000000002010D8 ; struct _IO_FILE *stderr
extern:00000000002010D8 extrn stderr
| ; DATA XREF: .got:stderr_ptr
`-------------------------------.
|
.got:0000000000200FF0 stderr_ptr dq offset stderr
| ; DATA XREF: main+12
`-------------------------------.
|
.text:0000000000000932 mov rax, cs:stderr_ptr
.text:0000000000000939 mov rdi, [rax] ; stream
...
.text:0000000000000949 call _fprintf
So above we see that the `mov` instruction is dereferencing `stderr_ptr`,
and from there it's getting the address of `stderr`. Then it dereferences
that, which is the value of `stderr, getting us the address of the `FILE *`.
That is passed at the first argument to `fprintf`.
Now, what we see in the `mcseam-disass` log is a bit different.
Variable at 200ff0 is the external stderr
Variable at 2010a8 is the external stderr
Variable at 2010d8 is the external stderr
...
I: 932 (data mem external 200ff0 stderr)
So even though the `mov` instruction uses `stderr_ptr` and an extra level
of indirection, we devirtualize that to `stderr`. But, how could this work?
It seems like it's removing a layer of indirection. The answer is on the
LLVM side of things.
On the LLVM side, `stderr` is a global variable:
@stderr = external global %struct._IO_FILE*, align 8
And the corresponding call is:
%4 = load %struct._IO_FILE*, %struct._IO_FILE** @stderr, align 8
%5 = call i32 (...) @fprintf(%struct._IO_FILE* %4, i8* ...)
So now we see that by declaring the global variable `stderr` on the LLVM
side, we regain this extra level of indirection because all global variables
are really pointers to their type (i.e. `%struct._IO_FILE**`), thus we
preserve the intent of the original assembly.
"""
DEBUG_PUSH()
debug_info = ["I: {:x}".format(addr)]
for ref in refs:
if not ref.is_valid():
DEBUG("POSSIBLE ERROR: Invalid reference {} at instruction {:x}".format(
str(ref), inst.ea))
continue
# Redirect the thunk target to the internal target.
if ref.ea in INTERNAL_THUNK_EAS:
ref.ea = INTERNAL_THUNK_EAS[ref.ea]
ref.symbol = get_symbol_name(ref.ea)
if Reference.CODE == ref.type:
is_thunk, thunk_target_ea, thunk_name = try_get_thunk_name(ref.ea)
if is_thunk:
ref.ea = thunk_target_ea
ref.symbol = thunk_name
R = I.xrefs.add()
R.ea = ref.ea
if ref.mask:
R.mask = ref.mask
if ref.imm_val:
R.ea = ref.imm_val
R.operand_type = reference_operand_type(ref)
debug_info.append(format_instruction_reference(R))
DEBUG_POP()
DEBUG(" ".join(debug_info))
def recover_instruction_offset_table(I, table):
"""Recovers an offset table as a kind of reference."""
DEBUG("Offset-based jump table")
R = I.xrefs.add()
R.ea = table.offset
R.operand_type = CFG_pb2.CodeReference.OffsetTable
def try_recovery_external_flow(I, inst, refs):
"""We have somehting like:
jmp cs:EnterCriticalSection
Where `EnterCriticalSection` is in the `.idata` section and is filled in at
load time to contain the real address of the external
`EnterCriticalSection`."""
if not (is_indirect_jump(inst) or is_indirect_function_call(inst)) or \
not refs or len(refs) > 1:
return
ref = refs[0]
if ref.type == Reference.CODE or ref.ea not in EXTERNAL_FUNCS_TO_RECOVER:
return
R = I.xrefs.add()
R.ea = ref.ea
R.operand_type = CFG_pb2.CodeReference.ControlFlowOperand
if is_indirect_jump(inst):
DEBUG("Tail-calls external {}".format(R.ea))
else:
DEBUG("Calls external {}".format(R.ea))
# Groups preserved register sets that save/restore the same set of registers.
_REG_SETS = {}
def recover_instruction(M, F, B, ea):
"""Recover an instruction, adding it to its parent block in the CFG."""
global _REG_SETS
inst, inst_bytes = decode_instruction(ea)
I = B.instructions.add()
I.ea = ea # May not be `inst.ea` because of prefix coalescing.
xrefs = get_instruction_references(inst, PIE_MODE)
recover_instruction_references(I, inst, ea, xrefs)
regs_saved = recover_preserved_regs(M, F, inst, xrefs, _REG_SETS)
DEBUG_PUSH()
table = get_jump_table(inst, PIE_MODE)
if table and table.offset and \
not is_invalid_ea(table.offset * table.offset_mult):
recover_instruction_offset_table(I, table)
if not table:
try_recovery_external_flow(I, inst, xrefs)
if regs_saved and len(regs_saved):
DEBUG("Added save record: {}".format(regs_saved))
DEBUG_POP()
return I
def recover_basic_block(M, F, block_ea):
"""Add in a basic block to a specific function in the CFG."""
if is_external_segment_by_flags(block_ea):
DEBUG("BB: {:x} in func {:x} is an external".format(block_ea, F.ea))
return
inst_eas, succ_eas = analyse_block(F.ea, block_ea, PIE_MODE)
DEBUG("BB: {:x} in func {:x} with {} insts".format(
block_ea, F.ea, len(inst_eas)))
B = F.blocks.add()
B.ea = block_ea
DEBUG_PUSH()
B.is_referenced_by_data = False
if is_jump_table_target(block_ea) or \
idaapi.get_first_dref_to(block_ea) != idc.BADADDR or \
has_our_dref_to(block_ea):
DEBUG("Referenced by data")
B.is_referenced_by_data = True
I = None
for inst_ea in inst_eas:
I = recover_instruction(M, F, B, inst_ea)
# Get the landing pad associated with the instructions;
# 0 if no landing pad associated
if RECOVER_EHTABLE is True and I:
I.lp_ea = get_exception_landingpad(F, inst_ea)
DEBUG_PUSH()
if len(succ_eas) > 0:
B.successor_eas.extend(succ_eas)
DEBUG("Successors: {}".format(", ".join("{0:x}".format(i) for i in succ_eas)))
else:
DEBUG("No successors")
DEBUG_POP()
DEBUG_POP()
def analyze_jump_table_targets(inst, new_eas, new_func_eas):
"""Function recovery is an iterative process. Sometimes we'll find things
in the entries of the jump table that we need to go mark as code to be
added into the CFG."""
table = get_jump_table(inst, PIE_MODE)
if not table:
return
for entry_addr, entry_target in table.entries.items():
new_eas.add(entry_target)
if is_start_of_function(entry_target):
DEBUG(" Jump table {:x} entry at {:x} references function at {:x}".format(
table.table_ea, entry_addr, entry_target))
new_func_eas.append(entry_target)
else:
DEBUG(" Jump table {:x} entry at {:x} references block at {:x}".format(
table.table_ea, entry_addr, entry_target))
def recover_value_spec(V, spec):
"""Recovers an Anvill value specification into the CFG proto format."""
V.type = spec["type"]
if "name" in spec and len(spec["name"]):
V.name = spec["name"]
if "register" in spec:
V.register = spec["register"]
elif "memory" in spec:
mem_spec = spec["memory"]
V.memory.register = mem_spec["register"]
if mem_spec["offset"]:
V.memory.offset = mem_spec["offset"]
def recover_function_spec(F, spec):
"""Recovers most of an Anvill function specification into the CFG proto format."""
D = F.decl
if "is_noreturn" in spec:
D.is_noreturn = spec["is_noreturn"]
else:
D.is_noreturn = False
if "is_variadic" in spec:
D.is_variadic = spec["is_variadic"]
else:
D.is_variadic = False
if "parameters" in spec:
for param in spec["parameters"]:
P = D.parameters.add()
recover_value_spec(P, param)
if "return_values" in spec:
for ret_val in spec["return_values"]:
V = D.return_values.add()
recover_value_spec(V, ret_val)
if "calling_convention" in spec:
D.calling_convention = spec["calling_convention"]
else:
D.calling_convention = 0
recover_value_spec(D.return_address, spec["return_address"])
recover_value_spec(D.return_stack_pointer, spec["return_stack_pointer"])
def try_get_anvill_func(func_ea, is_thunk, thunk_target_ea):
"""Try to get the Anvill Function object for the function associated with
`func_ea`, and if it's a thunk, then `thunk_target_ea`."""
if is_thunk:
try:
if ANVILL_PROGRAM.add_function_declaration(thunk_target_ea):
return ANVILL_PROGRAM.get_function(thunk_target_ea)
except Exception as e:
pass
try:
if ANVILL_PROGRAM.add_function_declaration(func_ea):
return ANVILL_PROGRAM.get_function(func_ea)
except:
pass
return None
_RECOVERED_FUNCS = set()
def recover_function(M, func_ea, new_func_eas, entrypoints, prev_F, processed_blocks):
"""Decode a function and store it, all of its basic blocks, and all of
their instructions into the CFG file."""
global _RECOVERED_FUNCS
global ANVILL_PROGRAM
global EXTERNAL_FUNCS_TO_RECOVER
if func_ea in _RECOVERED_FUNCS:
return prev_F
_RECOVERED_FUNCS.add(func_ea)
# `func_ea` could be the entrypoint but may not be identified
# as the start of the function.
if not is_start_of_function(func_ea): # and func_ea not in entrypoints:
DEBUG("{:x} is not a function! Not recovering.".format(func_ea))
return prev_F
# Double check to see if it looks like a thunk, and if so, we'll just
# re-direct to that.
is_thunk, thunk_target_ea, name = try_get_thunk_name(func_ea)
if is_thunk and name and is_external_segment(thunk_target_ea):
EXTERNAL_FUNCS_TO_RECOVER[func_ea] = name
DEBUG("Deferring recovery of thunk {:x}, resolved to external {}".format(
func_ea, name))
return prev_F
name = get_symbol_name(func_ea)
processed_blocks.clear()
F = M.funcs.add()
F.ea = func_ea
F.is_entrypoint = (func_ea in entrypoints)
if not name:
DEBUG("Recovering {:x}".format(func_ea))
else:
F.name = name.format('utf-8')
DEBUG("Recovering {} at {:x}".format(F.name, func_ea))
# Try to get the Anvill representation of this function.
anvill_func = try_get_anvill_func(func_ea, is_thunk, thunk_target_ea)
if anvill_func:
recover_function_spec(F, anvill_func.proto())
DEBUG_PUSH()
# Update the protobuf with the recovered eh_frame entries
if RECOVER_EHTABLE is True:
recover_exception_entries(F, func_ea)
block_eas, term_insts = analyse_subroutine(func_ea, PIE_MODE)
for term_inst in term_insts:
if get_jump_table(term_inst, PIE_MODE):
DEBUG("Terminator inst {:x} in func {:x} is a jump table".format(
term_inst.ea, func_ea))
analyze_jump_table_targets(term_inst, block_eas, new_func_eas)
while len(block_eas) > 0:
block_ea = block_eas.pop()
if block_ea in processed_blocks:
DEBUG("ERROR: Attempting to add same block twice: {0:x}".format(block_ea))
continue
processed_blocks.add(block_ea)
recover_basic_block(M, F, block_ea)
DEBUG_POP()
return F
def find_default_function_heads():
"""Loop through every function, to discover the heads of all blocks that
IDA recognizes. This will populate some global sets in `flow.py` that
will help distinguish block heads."""
func_eas = []
for seg_ea in idautils.Segments():
seg_type = idc.get_segm_attr(seg_ea, idc.SEGATTR_TYPE)
if seg_type != idc.SEG_CODE:
continue
for func_ea in idautils.Functions(seg_ea, idc.get_segm_end(seg_ea)):
if is_code_by_flags(func_ea):
func_eas.append(func_ea)
return func_eas
def recover_region_variables(M, S, seg_ea, seg_end_ea, exported_vars):
"""Look for named locations pointing into the data of this segment, and
add them to the protobuf."""
is_code_seg = is_code(seg_ea)
for ea, name in idautils.Names():
if ea < seg_ea or ea >= seg_end_ea:
continue
if is_external_segment_by_flags(ea) or ea in EXTERNAL_VARS_TO_RECOVER:
continue
if is_code_seg and is_code_by_flags(ea):
continue
# Only add named internal variables if they are referenced or exported.
if is_referenced(ea) or ea in exported_vars:
DEBUG("Variable {} at {:x}".format(name, ea))
V = S.vars.add()
V.ea = ea
V.name = name.format('utf-8')
def recover_region_cross_references(M, S, seg_ea, seg_end_ea):
"""Goes through the segment and identifies fixups that need to be
handled by the LLVM side of things."""
# Go through and look for the fixups. We start at `seg_ea - 1` because we
# always try to find the *next* fixup/heads, and if there's one right at
# the beginning of the segment then we don't want to jump to the second one.
global PIE_MODE
max_xref_width = get_address_size_in_bytes()
min_xref_width = PIE_MODE and max_xref_width or 4
is_code_seg = is_code(seg_ea)
seg_name = idc.get_segm_name(seg_ea)
has_func_pointers = segment_contains_external_function_pointers(seg_ea)
ea, next_ea = seg_ea, seg_ea
while next_ea < seg_end_ea:
ea = next_ea
# The item size is 1 in some of the cases where it refer to the external data. The
# references in such cases get ignored. Assign the address size if there is reference
# to the external data.
item_size = idc.get_item_size(ea)
xref_width = min(max(item_size, 4), max_xref_width)
next_ea = min(ea + xref_width,
# idc.GetNextFixupEA(ea),
idc.next_head(ea, seg_end_ea))
# This data is a copy of shared data.
if is_runtime_external_data_reference(ea):
continue
# We don't want to fill the jump table bytes with their actual
# code cross-references. This is because we can't get the address
# of a basic block. Our goal is thus to preserve the original values,
# and implement the switch in terms of those original values on the
# LLVM side of things.
#if is_jump_table_entry(ea):
# continue
# Skip over instructions.
if is_code_seg:
flags = idc.get_full_flags(ea)
if idc.is_code(flags):
next_ea = idc.next_head(ea, seg_end_ea)
continue
target_ea = get_reference_target(ea)
# Handle entries in the `.got.plt` and `.idata` segments. In ELF binaries,
# this looks like:
#
# .got.plt:000000000032E058 off_32E058 dq offset getenv
#
# In PE binaries, this looks like:
#
# .idata:00000001400110D8 ; DWORD __stdcall GetLastError()
# .idata:00000001400110D8 extrn GetLastError:qword
if is_invalid_ea(target_ea):
if has_func_pointers and ea in EXTERNAL_FUNCS_TO_RECOVER:
target_ea = ea
# Note: it's possible that `ea == target_ea`. This happens with
# external references to things like `stderr`, where there's
# an internal slot, whose value is filled in at runtime.
if is_invalid_ea(target_ea):
continue
elif (ea % 4) != 0:
DEBUG("WARNING: Unaligned reference at {:x} to {:x}".format(ea, target_ea))
continue
elif item_size < min_xref_width:
DEBUG("WARNING: Ingorning {}-byte item that looks like at reference from {:x} to {:x}; it needs to be at least {} bytes".format(
item_size, ea, target_ea, min_xref_width))
continue
# Probably some really small number.
elif not idc.get_full_flags(target_ea):
DEBUG("WARNING: No information about target {:x} from {:x}".format(
target_ea, ea))
continue
else:
X = S.xrefs.add()
X.ea = ea
X.width = xref_width
X.target_ea = target_ea
target_name = get_symbol_name(target_ea)
if is_external_segment(X.target_ea):
target_name = get_true_external_name(target_name)
# A cross-reference to some TLS data. Because each thread has its own
# instance of the data, this reference ends up actually being an offset
# from a thread base pointer. In x86, this tends to be the base of one of
# the segment registers, e.g. `fs` or `gs`. On the McSema side, we fill in
# this xref lazily by computing the offset.
if is_tls(target_ea):
X.target_fixup_kind = CFG_pb2.DataReference.OffsetFromThreadBase
DEBUG("{}-byte TLS offset at {:x} to {:x} ({})".format(
X.width, ea, target_ea, target_name))