-
Notifications
You must be signed in to change notification settings - Fork 1k
/
simos.py
1255 lines (1031 loc) · 55.3 KB
/
simos.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
"""
Manage OS-level configuration.
"""
import os
import logging
from collections import defaultdict
from archinfo import ArchARM, ArchMIPS32, ArchMIPS64, ArchX86, ArchAMD64, ArchPPC32, ArchPPC64, ArchAArch64
from cle import MetaELF, BackedCGC
from cle.address_translator import AT
from elftools.elf.descriptions import _DESCR_EI_OSABI
import claripy
from .errors import (
AngrUnsupportedSyscallError,
AngrCallableError,
AngrCallableMultistateError,
AngrSimOSError,
SimUnsupportedError,
SimSegfaultException,
SimZeroDivisionException,
TracerEnvironmentError
)
from .tablespecs import StringTableSpec
from .sim_state import SimState
from .state_plugins import SimStateSystem, SimActionData, SimStatePreconstrainer
from .calling_conventions import DEFAULT_CC, SYSCALL_CC
from .procedures import SIM_PROCEDURES as P, SIM_LIBRARIES as L
from . import sim_options as o
from .storage.file import SimFile, SimDialogue
l = logging.getLogger("angr.simos")
class IRange(object):
"""
A simple range object for testing inclusion. Like xrange but works for huge numbers.
"""
__slots__ = ('start', 'end')
def __init__(self, start, end):
self.start = start
self.end = end
def __contains__(self, k):
if type(k) in (int, long):
return k >= self.start and k < self.end
return False
def __getstate__(self):
return self.start, self.end
def __setstate__(self, state):
self.start, self.end = state
class SimOS(object):
"""
A class describing OS/arch-level configuration.
"""
def __init__(self, project, name=None):
self.arch = project.arch
self.project = project
self.name = name
self.return_deadend = None
def configure_project(self):
"""
Configure the project to set up global settings (like SimProcedures).
"""
self.return_deadend = self.project.loader.extern_object.allocate()
self.project.hook(self.return_deadend, P['stubs']['CallReturn']())
def irelative_resolver(resolver_addr):
# autohooking runs before this does, might have provided this already
# in that case, we want to advertise the _resolver_ address, since it is now
# providing the behavior of the actual function
if self.project.is_hooked(resolver_addr):
return resolver_addr
resolver = self.project.factory.callable(resolver_addr, concrete_only=True)
try:
val = resolver()
except AngrCallableMultistateError:
l.error("Resolver at %#x failed to resolve! (multivalued)", resolver_addr)
return None
except AngrCallableError:
l.error("Resolver at %#x failed to resolve!", resolver_addr)
return None
return val._model_concrete.value
self.project.loader.perform_irelative_relocs(irelative_resolver)
def _weak_hook_symbol(self, name, hook, scope=None):
if scope is None:
sym = self.project.loader.find_symbol(name)
else:
sym = scope.get_symbol(name)
if sym is not None:
if self.project.is_hooked(sym.rebased_addr):
if not self.project.hooked_by(sym.rebased_addr).is_stub:
return
self.project.hook(sym.rebased_addr, hook)
def state_blank(self, addr=None, initial_prefix=None, stack_size=1024*1024*8, **kwargs):
"""
Initialize a blank state.
All parameters are optional.
:param addr: The execution start address.
:param initial_prefix:
:param stack_size: The number of bytes to allocate for stack space
:return: The initialized SimState.
Any additional arguments will be passed to the SimState constructor
"""
# TODO: move ALL of this into the SimState constructor
if kwargs.get('mode', None) is None:
kwargs['mode'] = self.project._default_analysis_mode
if kwargs.get('permissions_backer', None) is None:
# just a dict of address ranges to permission bits
permission_map = { }
for obj in self.project.loader.all_objects:
for seg in obj.segments:
perms = 0
# bit values based off of protection bit values from sys/mman.h
if seg.is_readable:
perms |= 1 # PROT_READ
if seg.is_writable:
perms |= 2 # PROT_WRITE
if seg.is_executable:
perms |= 4 # PROT_EXEC
permission_map[(seg.min_addr, seg.max_addr)] = perms
permissions_backer = (self.project.loader.main_object.execstack, permission_map)
kwargs['permissions_backer'] = permissions_backer
if kwargs.get('memory_backer', None) is None:
kwargs['memory_backer'] = self.project.loader.memory
if kwargs.get('os_name', None) is None:
kwargs['os_name'] = self.name
state = SimState(self.project, **kwargs)
stack_end = state.arch.initial_sp
if o.ABSTRACT_MEMORY not in state.options:
state.memory.mem._preapproved_stack = IRange(stack_end - stack_size, stack_end)
if o.INITIALIZE_ZERO_REGISTERS in state.options:
highest_reg_offset, reg_size = max(state.arch.registers.values())
for i in range(0, highest_reg_offset + reg_size, state.arch.bytes):
state.registers.store(i, state.se.BVV(0, state.arch.bits))
if state.arch.sp_offset is not None:
state.regs.sp = stack_end
if initial_prefix is not None:
for reg in state.arch.default_symbolic_registers:
state.registers.store(reg, claripy.BVS(initial_prefix + "_" + reg,
state.arch.bits,
explicit_name=True))
for reg, val, is_addr, mem_region in state.arch.default_register_values:
region_base = None # so pycharm does not complain
if is_addr:
if isinstance(mem_region, tuple):
# unpack it
mem_region, region_base = mem_region
elif mem_region == 'global':
# Backward compatibility
region_base = 0
else:
raise AngrSimOSError('You must specify the base address for memory region "%s". ' % mem_region)
if o.ABSTRACT_MEMORY in state.options and is_addr:
address = claripy.ValueSet(state.arch.bits, mem_region, region_base, val)
state.registers.store(reg, address)
else:
state.registers.store(reg, val)
if addr is None: addr = self.project.entry
state.regs.ip = addr
# set up the "root history" node
state.scratch.ins_addr = addr
state.scratch.bbl_addr = addr
state.scratch.stmt_idx = 0
state.history.jumpkind = 'Ijk_Boring'
return state
def state_entry(self, **kwargs):
return self.state_blank(**kwargs)
def state_full_init(self, **kwargs):
return self.state_entry(**kwargs)
def state_call(self, addr, *args, **kwargs):
cc = kwargs.pop('cc', DEFAULT_CC[self.arch.name](self.project.arch))
state = kwargs.pop('base_state', None)
toc = kwargs.pop('toc', None)
ret_addr = kwargs.pop('ret_addr', self.return_deadend)
stack_base = kwargs.pop('stack_base', None)
alloc_base = kwargs.pop('alloc_base', None)
grow_like_stack = kwargs.pop('grow_like_stack', True)
if state is None:
state = self.state_blank(addr=addr, **kwargs)
else:
state = state.copy()
state.regs.ip = addr
cc.setup_callsite(state, ret_addr, args, stack_base, alloc_base, grow_like_stack)
if state.arch.name == 'PPC64' and toc is not None:
state.regs.r2 = toc
return state
def state_tracer(self, input_content=None, magic_content=None, preconstrain_input=True,
preconstrain_flag=True, constrained_addrs=None, **kwargs):
if input_content is None:
return self.state_full_init(**kwargs)
if type(input_content) == str:
fs = {'/dev/stdin': SimFile("/dev/stdin", "r", size=len(input_content))}
elif type(input_content) != SimDialogue:
raise TracerEnvironmentError("Input for tracer should be either a string or a TracerPoV for CGC binaries.")
kwargs['fs'] = kwargs.get('fs', fs)
kwargs['add_options'] |= {o.CGC_ZERO_FILL_UNCONSTRAINED_MEMORY,
o.REPLACEMENT_SOLVER,
o.UNICORN,
o.UNICORN_HANDLE_TRANSMIT_SYSCALL}
kwargs['remove_options'] |= {o.EFFICIENT_STATE_MERGING} | o.simplification
state = self.state_full_init(**kwargs)
# Create the preconstrainer plugin
state.register_plugin('preconstrainer',
SimStatePreconstrainer(input_content=input_content,
magic_content=magic_content,
preconstrain_input=preconstrain_input,
preconstrain_flag=preconstrain_flag,
constrained_addrs=constrained_addrs))
# Preconstrain
state.preconstrainer.preconstrain_state()
state.cgc.flag_bytes = [claripy.BVS("cgc-flag-byte-%d" % i, 8) for i in xrange(0x1000)]
return state
def prepare_call_state(self, calling_state, initial_state=None,
preserve_registers=(), preserve_memory=()):
"""
This function prepares a state that is executing a call instruction.
If given an initial_state, it copies over all of the critical registers to it from the
calling_state. Otherwise, it prepares the calling_state for action.
This is mostly used to create minimalistic for CFG generation. Some ABIs, such as MIPS PIE and
x86 PIE, require certain information to be maintained in certain registers. For example, for
PIE MIPS, this function transfer t9, gp, and ra to the new state.
"""
if isinstance(self.arch, ArchMIPS32):
if initial_state is not None:
initial_state = self.state_blank()
mips_caller_saves = ('s0', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 'gp', 'sp', 'bp', 'ra')
preserve_registers = preserve_registers + mips_caller_saves + ('t9',)
if initial_state is None:
new_state = calling_state.copy()
else:
new_state = initial_state.copy()
for reg in set(preserve_registers):
new_state.registers.store(reg, calling_state.registers.load(reg))
for addr, val in set(preserve_memory):
new_state.memory.store(addr, calling_state.memory.load(addr, val))
return new_state
def prepare_function_symbol(self, symbol_name, basic_addr=None):
"""
Prepare the address space with the data necessary to perform relocations pointing to the given symbol
Returns a 2-tuple. The first item is the address of the function code, the second is the address of the
relocation target.
"""
if basic_addr is None:
basic_addr = self.project.loader.extern_object.get_pseudo_addr(symbol_name)
return basic_addr, basic_addr
def handle_exception(self, successors, engine, exc_type, exc_value, exc_traceback):
"""
Perform exception handling. This method will be called when, during execution, a SimException is thrown.
Currently, this can only indicate a segfault, but in the future it could indicate any unexpected exceptional
behavior that can't be handled by ordinary control flow.
The method may mutate the provided SimSuccessors object in any way it likes, or re-raise the exception.
:param successors: The SimSuccessors object currently being executed on
:param engine: The engine that was processing this step
:param exc_type: The value of sys.exc_info()[0] from the error, the type of the exception that was raised
:param exc_value: The value of sys.exc_info()[1] from the error, the actual exception object
:param exc_traceback: The value of sys.exc_info()[2] from the error, the traceback from the exception
"""
raise exc_type, exc_value, exc_traceback
# Dummy stuff to allow this API to be used freely
# pylint: disable=unused-argument, no-self-use
def syscall(self, state, allow_unsupported=True):
return None
def is_syscall_addr(self, addr):
return False
def syscall_from_addr(self, addr, allow_unsupported=True):
return None
def syscall_from_number(self, number, allow_unsupported=True):
return None
class SimUserland(SimOS):
"""
This is a base class for any SimOS that wants to support syscalls.
It uses the CLE kernel object to provide addresses for syscalls. Syscalls will be emulated as a jump to one of these
addresses, where a SimProcedure from the syscall library provided at construction time will be executed.
"""
def __init__(self, project, syscall_library=None, **kwargs):
super(SimUserland, self).__init__(project, **kwargs)
self.syscall_library = syscall_library.copy()
self.kernel_base = None
def configure_project(self):
super(SimUserland, self).configure_project()
self.kernel_base = self.project.loader.kernel_object.mapped_base
def syscall(self, state, allow_unsupported=True):
"""
Given a state, return the procedure corresponding to the current syscall.
This procedure will have .syscall_number, .display_name, and .addr set.
:param state: The state to get the syscall number from
:param allow_unsupported: Whether to return a "dummy" sycall instead of raising an unsupported exception
"""
if state.os_name in SYSCALL_CC[state.arch.name]:
cc = SYSCALL_CC[state.arch.name][state.os_name](state.arch)
else:
# Use the default syscall calling convention - it may bring problems
l.warning("No syscall calling convention available for %s/%s", state.arch.name, state.os_name)
cc = SYSCALL_CC[state.arch.name]['default'](state.arch)
sym_num = cc.syscall_num(state)
possible = state.solver.eval_upto(sym_num, 2)
if len(possible) == 0:
raise AngrUnsupportedSyscallError("The program state is not satisfiable")
elif len(possible) == 1:
num = possible[0]
elif allow_unsupported:
num = self.syscall_library.maximum_syscall_number(self.arch.name) + 1 if self.syscall_library else 0
else:
raise AngrUnsupportedSyscallError("Got a symbolic syscall number")
proc = self.syscall_from_number(num, allow_unsupported=allow_unsupported)
proc.cc = cc
return proc
def is_syscall_addr(self, addr):
"""
Return whether or not the given address corresponds to a syscall.
"""
if self.kernel_base is None:
return False
addr -= self.kernel_base
return 0 <= addr < 0x4000 # TODO: make this number come from somewhere
def syscall_from_addr(self, addr, allow_unsupported=True):
"""
Get a syscall SimProcedure from an address.
:param addr: The address to convert to a syscall SimProcedure
:param allow_unsupported: Whether to return a dummy procedure for an unsupported syscall instead of raising an
exception.
:return: The SimProcedure for the syscall, or None if the address is not a syscall address.
"""
if not self.is_syscall_addr(addr):
return None
number = addr - self.kernel_base
return self.syscall_from_number(number, allow_unsupported=allow_unsupported)
def syscall_from_number(self, number, allow_unsupported=True):
if not allow_unsupported and not self.syscall_library:
raise AngrUnsupportedSyscallError("%s does not have a library of syscalls implemented" % self.name)
addr = number + self.kernel_base
if self.syscall_library is None:
proc = P['stubs']['syscall']()
elif not allow_unsupported and not self.syscall_library.has_implementation(number, self.arch):
raise AngrUnsupportedSyscallError("No implementation for syscall %d" % number)
else:
proc = self.syscall_library.get(number, self.arch)
proc.addr = addr
return proc
class SimLinux(SimUserland):
"""
OS-specific configuration for \\*nix-y OSes.
"""
def __init__(self, project, **kwargs):
super(SimLinux, self).__init__(project, syscall_library=L['linux'], name="Linux", **kwargs)
self._loader_addr = None
self._loader_lock_addr = None
self._loader_unlock_addr = None
self._error_catch_tsd_addr = None
self._vsyscall_addr = None
def configure_project(self):
self._loader_addr = self.project.loader.extern_object.allocate()
self._loader_lock_addr = self.project.loader.extern_object.allocate()
self._loader_unlock_addr = self.project.loader.extern_object.allocate()
self._error_catch_tsd_addr = self.project.loader.extern_object.allocate()
self._vsyscall_addr = self.project.loader.extern_object.allocate()
self.project.hook(self._loader_addr, P['linux_loader']['LinuxLoader']())
self.project.hook(self._loader_lock_addr, P['linux_loader']['_dl_rtld_lock_recursive']())
self.project.hook(self._loader_unlock_addr, P['linux_loader']['_dl_rtld_unlock_recursive']())
self.project.hook(self._error_catch_tsd_addr, P['linux_loader']['_dl_initial_error_catch_tsd'](static_addr=self.project.loader.extern_object.allocate()))
self.project.hook(self._vsyscall_addr, P['linux_kernel']['_vsyscall']())
ld_obj = self.project.loader.linux_loader_object
if ld_obj is not None:
# there are some functions we MUST use the simprocedures for, regardless of what the user wants
self._weak_hook_symbol('__tls_get_addr', L['ld.so'].get('__tls_get_addr', self.arch), ld_obj)
self._weak_hook_symbol('___tls_get_addr', L['ld.so'].get('___tls_get_addr', self.arch), ld_obj)
# set up some static data in the loader object...
_rtld_global = ld_obj.get_symbol('_rtld_global')
if _rtld_global is not None:
if isinstance(self.project.arch, ArchAMD64):
self.project.loader.memory.write_addr_at(_rtld_global.rebased_addr + 0xF08, self._loader_lock_addr)
self.project.loader.memory.write_addr_at(_rtld_global.rebased_addr + 0xF10, self._loader_unlock_addr)
self.project.loader.memory.write_addr_at(_rtld_global.rebased_addr + 0x990, self._error_catch_tsd_addr)
# TODO: what the hell is this
_rtld_global_ro = ld_obj.get_symbol('_rtld_global_ro')
if _rtld_global_ro is not None:
pass
libc_obj = self.project.loader.find_object('libc.so.6')
if libc_obj:
self._weak_hook_symbol('_dl_vdso_vsym', L['libc.so.6'].get('_dl_vdso_vsym', self.arch), libc_obj)
tls_obj = self.project.loader.tls_object
if tls_obj is not None:
if isinstance(self.project.arch, ArchAMD64):
self.project.loader.memory.write_addr_at(tls_obj.thread_pointer + 0x28, 0x5f43414e4152595f)
self.project.loader.memory.write_addr_at(tls_obj.thread_pointer + 0x30, 0x5054524755415244)
elif isinstance(self.project.arch, ArchX86):
self.project.loader.memory.write_addr_at(tls_obj.thread_pointer + 0x10, self._vsyscall_addr)
elif isinstance(self.project.arch, ArchARM):
self.project.hook(0xffff0fe0, P['linux_kernel']['_kernel_user_helper_get_tls']())
# Only set up ifunc resolution if we are using the ELF backend on AMD64
if isinstance(self.project.loader.main_object, MetaELF):
if isinstance(self.project.arch, ArchAMD64):
for binary in self.project.loader.all_objects:
if not isinstance(binary, MetaELF):
continue
for reloc in binary.relocs:
if reloc.symbol is None or reloc.resolvedby is None:
continue
try:
if reloc.resolvedby.elftype != 'STT_GNU_IFUNC':
continue
except AttributeError:
continue
gotaddr = reloc.rebased_addr
gotvalue = self.project.loader.memory.read_addr_at(gotaddr)
if self.project.is_hooked(gotvalue):
continue
# Replace it with a ifunc-resolve simprocedure!
kwargs = {
'funcaddr': gotvalue,
'gotaddr': gotaddr,
'funcname': reloc.symbol.name
}
# TODO: should this be replaced with hook_symbol?
randaddr = self.project.loader.extern_object.allocate()
self.project.hook(randaddr, P['linux_loader']['IFuncResolver'](**kwargs))
self.project.loader.memory.write_addr_at(gotaddr, randaddr)
super(SimLinux, self).configure_project()
# pylint: disable=arguments-differ
def state_blank(self, fs=None, concrete_fs=False, chroot=None, **kwargs):
state = super(SimLinux, self).state_blank(**kwargs)
if self.project.loader.tls_object is not None:
if isinstance(state.arch, ArchAMD64):
state.regs.fs = self.project.loader.tls_object.user_thread_pointer
elif isinstance(state.arch, ArchX86):
state.regs.gs = self.project.loader.tls_object.user_thread_pointer >> 16
elif isinstance(state.arch, (ArchMIPS32, ArchMIPS64)):
state.regs.ulr = self.project.loader.tls_object.user_thread_pointer
elif isinstance(state.arch, ArchPPC32):
state.regs.r2 = self.project.loader.tls_object.user_thread_pointer
elif isinstance(state.arch, ArchPPC64):
state.regs.r13 = self.project.loader.tls_object.user_thread_pointer
elif isinstance(state.arch, ArchAArch64):
state.regs.tpidr_el0 = self.project.loader.tls_object.user_thread_pointer
last_addr = self.project.loader.main_object.max_addr
brk = last_addr - last_addr % 0x1000 + 0x1000
state.register_plugin('posix', SimStateSystem(fs=fs, concrete_fs=concrete_fs, chroot=chroot, brk=brk))
if self.project.loader.main_object.is_ppc64_abiv1:
state.libc.ppc64_abiv = 'ppc64_1'
return state
def state_entry(self, args=None, env=None, argc=None, **kwargs):
state = super(SimLinux, self).state_entry(**kwargs)
# Handle default values
if args is None:
args = []
if env is None:
env = {}
# Prepare argc
if argc is None:
argc = claripy.BVV(len(args), state.arch.bits)
elif type(argc) in (int, long): # pylint: disable=unidiomatic-typecheck
argc = claripy.BVV(argc, state.arch.bits)
# Make string table for args/env/auxv
table = StringTableSpec()
# Add args to string table
table.append_args(args)
# Add environment to string table
table.append_env(env)
# Prepare the auxiliary vector and add it to the end of the string table
# TODO: Actually construct a real auxiliary vector
# current vector is an AT_RANDOM entry where the "random" value is 0xaec0aec0aec0...
aux = [(25, ("AEC0"*8).decode('hex'))]
for a, b in aux:
table.add_pointer(a)
if isinstance(b, str):
table.add_string(b)
else:
table.add_pointer(b)
table.add_null()
table.add_null()
# Dump the table onto the stack, calculate pointers to args, env, and auxv
state.memory.store(state.regs.sp - 16, claripy.BVV(0, 8*16))
argv = table.dump(state, state.regs.sp - 16)
envp = argv + ((len(args) + 1) * state.arch.bytes)
auxv = argv + ((len(args) + len(env) + 2) * state.arch.bytes)
# Put argc on stack and fix the stack pointer
newsp = argv - state.arch.bytes
state.memory.store(newsp, argc, endness=state.arch.memory_endness)
state.regs.sp = newsp
if state.arch.name in ('PPC32',):
state.stack_push(claripy.BVV(0, 32))
state.stack_push(claripy.BVV(0, 32))
state.stack_push(claripy.BVV(0, 32))
state.stack_push(claripy.BVV(0, 32))
# store argc argv envp auxv in the posix plugin
state.posix.argv = argv
state.posix.argc = argc
state.posix.environ = envp
state.posix.auxv = auxv
self.set_entry_register_values(state)
return state
def set_entry_register_values(self, state):
for reg, val in state.arch.entry_register_values.iteritems():
if isinstance(val, (int, long)):
state.registers.store(reg, val, size=state.arch.bytes)
elif isinstance(val, (str,)):
if val == 'argc':
state.registers.store(reg, state.posix.argc, size=state.arch.bytes)
elif val == 'argv':
state.registers.store(reg, state.posix.argv)
elif val == 'envp':
state.registers.store(reg, state.posix.environ)
elif val == 'auxv':
state.registers.store(reg, state.posix.auxv)
elif val == 'ld_destructor':
# a pointer to the dynamic linker's destructor routine, to be called at exit
# or NULL. We like NULL. It makes things easier.
state.registers.store(reg, 0)
elif val == 'toc':
if self.project.loader.main_object.is_ppc64_abiv1:
state.registers.store(reg, self.project.loader.main_object.ppc64_initial_rtoc)
elif val == 'thread_pointer':
state.registers.store(reg, self.project.loader.tls_object.user_thread_pointer)
else:
l.warning('Unknown entry point register value indicator "%s"', val)
else:
l.error('What the ass kind of default value is %s?', val)
def state_full_init(self, **kwargs):
kwargs['addr'] = self._loader_addr
return super(SimLinux, self).state_full_init(**kwargs)
def state_tracer(self, input_content=None, magic_content=None, preconstrain_input=True,
preconstrain_flag=True, constrained_addrs=None, **kwargs):
l.warning("Tracer has been heavily tested only for CGC. If you find it buggy for Linux binaries, we are sorry!")
options = kwargs.get('add_options', set())
options.add(o.BYPASS_UNSUPPORTED_SYSCALL)
kwargs['add_options'] = options
kwargs['remove_options'] = kwargs.get('remove_options', set())
kwargs['concrete_fs'] = kwargs.get('concrete_fs', True)
state = super(SimLinux, self).state_tracer(input_content=input_content,
magic_content=magic_content,
preconstrain_input=preconstrain_input,
preconstrain_flag=preconstrain_flag,
constrained_addrs=constrained_addrs,
**kwargs)
# Increase size of libc limits
state.libc.buf_symbolic_bytes = 1024
state.libc.max_str_len = 1024
return state
def prepare_function_symbol(self, symbol_name, basic_addr=None):
"""
Prepare the address space with the data necessary to perform relocations pointing to the given symbol.
Returns a 2-tuple. The first item is the address of the function code, the second is the address of the
relocation target.
"""
if self.project.loader.main_object.is_ppc64_abiv1:
if basic_addr is not None:
pointer = self.project.loader.memory.read_addr_at(basic_addr)
return pointer, basic_addr
pseudo_hookaddr = self.project.loader.extern_object.get_pseudo_addr(symbol_name)
pseudo_toc = self.project.loader.extern_object.allocate(size=0x18)
self.project.loader.extern_object.memory.write_addr_at(AT.from_mva(pseudo_toc, self.project.loader.extern_object).to_rva(), pseudo_hookaddr)
return pseudo_hookaddr, pseudo_toc
else:
if basic_addr is None:
basic_addr = self.project.loader.extern_object.get_pseudo_addr(symbol_name)
return basic_addr, basic_addr
class SimCGC(SimUserland):
"""
Environment configuration for the CGC DECREE platform
"""
def __init__(self, project, **kwargs):
super(SimCGC, self).__init__(project, syscall_library=L['cgcabi'], name="CGC", **kwargs)
# pylint: disable=arguments-differ
def state_blank(self, fs=None, **kwargs):
s = super(SimCGC, self).state_blank(**kwargs) # pylint:disable=invalid-name
# Special stack base for CGC binaries to work with Shellphish CRS
s.regs.sp = 0xbaaaaffc
# Map the special cgc memory
if o.ABSTRACT_MEMORY not in s.options:
s.memory.mem._preapproved_stack = IRange(0xbaaab000 - 1024*1024*8, 0xbaaab000)
s.memory.map_region(0x4347c000, 4096, 1)
s.register_plugin('posix', SimStateSystem(fs=fs))
# Create the CGC plugin
s.get_plugin('cgc')
# set up the address for concrete transmits
s.unicorn.transmit_addr = self.syscall_from_number(2).addr
return s
def state_entry(self, **kwargs):
if isinstance(self.project.loader.main_object, BackedCGC):
kwargs['permissions_backer'] = (True, self.project.loader.main_object.permissions_map)
kwargs['add_options'] = {o.CGC_ZERO_FILL_UNCONSTRAINED_MEMORY} | kwargs.get('add_options', set())
state = super(SimCGC, self).state_entry(**kwargs)
if isinstance(self.project.loader.main_object, BackedCGC):
for reg, val in self.project.loader.main_object.initial_register_values():
if reg in state.arch.registers:
setattr(state.regs, reg, val)
elif reg == 'eflags':
pass
elif reg == 'fctrl':
state.regs.fpround = (val & 0xC00) >> 10
elif reg == 'fstat':
state.regs.fc3210 = (val & 0x4700)
elif reg == 'ftag':
empty_bools = [((val >> (x*2)) & 3) == 3 for x in xrange(8)]
tag_chars = [claripy.BVV(0 if x else 1, 8) for x in empty_bools]
for i, tag in enumerate(tag_chars):
setattr(state.regs, 'fpu_t%d' % i, tag)
elif reg in ('fiseg', 'fioff', 'foseg', 'fooff', 'fop'):
pass
elif reg == 'mxcsr':
state.regs.sseround = (val & 0x600) >> 9
else:
l.error("What is this register %s I have to translate?", reg)
# Update allocation base
state.cgc.allocation_base = self.project.loader.main_object.current_allocation_base
# Do all the writes
writes_backer = self.project.loader.main_object.writes_backer
stdout = 1
for size in writes_backer:
if size == 0:
continue
str_to_write = state.posix.files[1].content.load(state.posix.files[1].pos, size)
a = SimActionData(state, 'file_1_0', 'write', addr=claripy.BVV(state.posix.files[1].pos, state.arch.bits), data=str_to_write, size=size)
state.posix.write(stdout, str_to_write, size)
state.history.add_action(a)
else:
# Set CGC-specific variables
state.regs.eax = 0
state.regs.ebx = 0
state.regs.ecx = 0x4347c000
state.regs.edx = 0
state.regs.edi = 0
state.regs.esi = 0
state.regs.esp = 0xbaaaaffc
state.regs.ebp = 0
state.regs.cc_dep1 = 0x202 # default eflags
state.regs.cc_op = 0 # OP_COPY
state.regs.cc_dep2 = 0 # doesn't matter
state.regs.cc_ndep = 0 # doesn't matter
# fpu values
state.regs.mm0 = 0
state.regs.mm1 = 0
state.regs.mm2 = 0
state.regs.mm3 = 0
state.regs.mm4 = 0
state.regs.mm5 = 0
state.regs.mm6 = 0
state.regs.mm7 = 0
state.regs.fpu_tags = 0
state.regs.fpround = 0
state.regs.fc3210 = 0x0300
state.regs.ftop = 0
# sse values
state.regs.sseround = 0
state.regs.xmm0 = 0
state.regs.xmm1 = 0
state.regs.xmm2 = 0
state.regs.xmm3 = 0
state.regs.xmm4 = 0
state.regs.xmm5 = 0
state.regs.xmm6 = 0
state.regs.xmm7 = 0
# segmentation registers
state.regs.ds = 0
state.regs.es = 0
state.regs.fs = 0
state.regs.gs = 0
state.regs.ss = 0
state.regs.cs = 0
return state
def state_tracer(self, input_content=None, magic_content=None, preconstrain_input=True,
preconstrain_flag=True, constrained_addrs=None, **kwargs):
options = kwargs.get('add_options', set())
options.add(o.CGC_NO_SYMBOLIC_RECEIVE_LENGTH)
options.add(o.UNICORN_THRESHOLD_CONCRETIZATION)
# try to enable unicorn, continue if it doesn't exist
try:
options.add(o.UNICORN_SYM_REGS_SUPPORT)
l.debug("unicorn tracing enabled")
except AttributeError:
pass
kwargs['add_options'] = options
kwargs['remove_options'] = kwargs.get('remove_options', set()) | {o.LAZY_SOLVES, o.SUPPORT_FLOATING_POINT}
state = super(SimCGC, self).state_tracer(input_content=input_content,
magic_content=magic_content,
preconstrain_input=preconstrain_input,
preconstrain_flag=preconstrain_flag,
constrained_addrs=constrained_addrs,
**kwargs)
csr = state.unicorn.cooldown_symbolic_registers
state.unicorn.concretization_threshold_registers = 25000 / csr
state.unicorn.concretization_threshold_memory = 25000 / csr
if type(input_content) == str:
state.cgc.input_size = len(input_content)
self._set_simproc_limits(state)
state.preconstrainer.preconstrain_flag_page()
state.memory.store(0x4347c000, claripy.Concat(*state.cgc.flag_bytes))
return state
@staticmethod
def _set_simproc_limits(state):
state.libc.max_str_len = 1000000
state.libc.max_strtol_len = 10
state.libc.max_memcpy_size = 0x100000
state.libc.max_symbolic_bytes = 100
state.libc.max_buffer_size = 0x100000
class SimWindows(SimOS):
"""
Environemnt for the Windows Win32 subsystem. Does not support syscalls currently.
"""
def __init__(self, project, **kwargs):
super(SimWindows, self).__init__(project, name='Win32', **kwargs)
self._exception_handler = None
self.fmode_ptr = None
self.commode_ptr = None
self.acmdln_ptr = None
self.wcmdln_ptr = None
def configure_project(self):
super(SimWindows, self).configure_project()
# here are some symbols which we MUST hook, regardless of what the user wants
self._weak_hook_symbol('GetProcAddress', L['kernel32.dll'].get('GetProcAddress', self.arch))
self._weak_hook_symbol('LoadLibraryA', L['kernel32.dll'].get('LoadLibraryA', self.arch))
self._weak_hook_symbol('LoadLibraryExW', L['kernel32.dll'].get('LoadLibraryExW', self.arch))
self._exception_handler = self._find_or_make('KiUserExceptionDispatcher')
self.project.hook(self._exception_handler, L['ntdll.dll'].get('KiUserExceptionDispatcher', self.arch), replace=True)
self.fmode_ptr = self._find_or_make('_fmode')
self.commode_ptr = self._find_or_make('_commode')
self.acmdln_ptr = self._find_or_make('_acmdln')
self.wcmdln_ptr = self._find_or_make('_wcmdln')
def _find_or_make(self, name):
sym = self.project.loader.find_symbol(name)
if sym is None:
return self.project.loader.extern_object.get_pseudo_addr(name)
else:
return sym.rebased_addr
# pylint: disable=arguments-differ
def state_entry(self, args=None, env=None, argc=None, **kwargs):
state = super(SimWindows, self).state_entry(**kwargs)
if args is None: args = []
if env is None: env = {}
# Prepare argc
if argc is None:
argc = claripy.BVV(len(args), state.arch.bits)
elif type(argc) in (int, long): # pylint: disable=unidiomatic-typecheck
argc = claripy.BVV(argc, state.arch.bits)
# Make string table for args and env
table = StringTableSpec()
table.append_args(args)
table.append_env(env)
# calculate full command line, since this is windows and that's how everything works
cmdline = claripy.BVV(0, 0)
for arg in args:
if cmdline.length != 0:
cmdline = cmdline.concat(claripy.BVV(' '))
if type(arg) is str:
if '"' in arg or '\0' in arg:
raise AngrSimOSError("Can't handle windows args with quotes or nulls in them")
arg = claripy.BVV(arg)
elif isinstance(arg, claripy.ast.BV):
for byte in arg.chop(8):
state.solver.add(byte != claripy.BVV('"'))
state.solver.add(byte != claripy.BVV(0, 8))
else:
raise TypeError("Argument must be str or bitvector")
cmdline = cmdline.concat(claripy.BVV('"'), arg, claripy.BVV('"'))
cmdline = cmdline.concat(claripy.BVV(0, 8))
wcmdline = claripy.Concat(*(x.concat(0, 8) for x in cmdline.chop(8)))
if not state.satisfiable():
raise AngrSimOSError("Can't handle windows args with quotes or nulls in them")
# Dump the table onto the stack, calculate pointers to args, env
stack_ptr = state.regs.sp
stack_ptr -= 16
state.memory.store(stack_ptr, claripy.BVV(0, 8*16))
stack_ptr -= cmdline.length / 8
state.memory.store(stack_ptr, cmdline)
state.mem[self.acmdln_ptr].long = stack_ptr
stack_ptr -= wcmdline.length / 8
state.memory.store(stack_ptr, wcmdline)
state.mem[self.wcmdln_ptr].long = stack_ptr
argv = table.dump(state, stack_ptr)
envp = argv + ((len(args) + 1) * state.arch.bytes)
# Put argc on stack and fix the stack pointer
newsp = argv - state.arch.bytes
state.memory.store(newsp, argc, endness=state.arch.memory_endness)
state.regs.sp = newsp
# store argc argv envp in the posix plugin
state.posix.argv = argv
state.posix.argc = argc
state.posix.environ = envp
state.regs.sp = state.regs.sp - 0x80 # give us some stack space to work with
# fake return address from entry point
return_addr = self.return_deadend
kernel32 = self.project.loader.shared_objects.get('kernel32.dll', None)
if kernel32:
# some programs will use the return address from start to find the kernel32 base
return_addr = kernel32.get_symbol('ExitProcess').rebased_addr
if state.arch.name == 'X86':
state.mem[state.regs.sp].dword = return_addr
# first argument appears to be PEB
tib_addr = state.regs.fs.concat(state.solver.BVV(0, 16))
peb_addr = state.mem[tib_addr + 0x30].dword.resolved
state.mem[state.regs.sp + 4].dword = peb_addr
return state
def state_blank(self, **kwargs):
if self.project.loader.main_object.supports_nx:
add_options = kwargs.get('add_options', set())
add_options.add(o.ENABLE_NX)
kwargs['add_options'] = add_options
state = super(SimWindows, self).state_blank(**kwargs)
# yikes!!!
fun_stuff_addr = state.libc.mmap_base
if fun_stuff_addr & 0xffff != 0:
fun_stuff_addr += 0x10000 - (fun_stuff_addr & 0xffff)
state.memory.map_region(fun_stuff_addr, 0x2000, claripy.BVV(3, 3))
TIB_addr = fun_stuff_addr
PEB_addr = fun_stuff_addr + 0x1000
if state.arch.name == 'X86':
LDR_addr = fun_stuff_addr + 0x2000
state.mem[TIB_addr + 0].dword = -1 # Initial SEH frame
state.mem[TIB_addr + 4].dword = state.regs.sp # stack base (high addr)
state.mem[TIB_addr + 8].dword = state.regs.sp - 0x100000 # stack limit (low addr)
state.mem[TIB_addr + 0x18].dword = TIB_addr # myself!
state.mem[TIB_addr + 0x24].dword = 0xbad76ead # thread id
if self.project.loader.tls_object is not None:
state.mem[TIB_addr + 0x2c].dword = self.project.loader.tls_object.user_thread_pointer # tls array pointer
state.mem[TIB_addr + 0x30].dword = PEB_addr # PEB addr, of course