This repository has been archived by the owner on Feb 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 250
/
api.py
1390 lines (1149 loc) · 49.4 KB
/
api.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
# -------------------------------------------------------------------------
#
# Copyright (C) 2017 Cisco Talos Security Intelligence and Research Group
#
# PyREBox: Python scriptable Reverse Engineering Sandbox
# Author: Xabier Ugarte-Pedrero
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# -------------------------------------------------------------------------
"""
.. module:: api
:platform: Unix
:synopsis: PyREbox API
.. moduleauthor:: Xabier Ugarte-Pedrero
"""
from cpus import X86CPU
from cpus import X64CPU
from api_internal import bp_func
from api_internal import register_callback
from api_internal import unregister_callback
from api_internal import add_trigger
from api_internal import remove_trigger
from api_internal import set_trigger_uint32
from api_internal import set_trigger_uint64
from api_internal import set_trigger_str
from api_internal import get_trigger_var as internal_get_trigger_var
from api_internal import call_trigger_function
from api_internal import unregister_module_load_callback
from api_internal import unregister_module_remove_callback
from api_internal import register_module_load_callback
from api_internal import register_module_remove_callback
import functools
DISABLE_DEPRECATION_WARNINGS = False
# ================================================== API FUNCTIONS ========
# This python script wraps the c based API, and also provides new API
# functionality such as module/symbol info retrieval
def get_num_cpus():
""" Returns the number of CPUs on the emulated system
:return: The number of CPUs on the emulated system
:rtype: int
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
return c_api.get_num_cpus()
def r_pa(addr, length):
""" Read physical address
:param addr: The address to read
:type addr: int
:param length: The length to read
:type length: int
:return: The read content
:rtype: str
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
offset = addr
ret_buffer = ""
while offset < (addr + length):
read_length = 0x2000 if (addr + length - offset) > 0x2000 else (addr + length - offset)
ret_buffer += c_api.r_pa(offset, read_length)
offset += read_length
return ret_buffer
def r_va(pgd, addr, length):
"""Read virtual address
:param pgd: The PGD (address space) to read from
:type pgd: int
:param addr: The address to read
:type addr: int
:param length: The length to read
:type length: int
:return: The read content
:rtype: str
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
offset = addr
ret_buffer = ""
while offset < (addr + length):
read_length = 0x2000 if (addr + length - offset) > 0x2000 else (addr + length - offset)
ret_buffer += c_api.r_va(pgd, offset, read_length)
offset += read_length
return ret_buffer
def r_cpu(cpu_index=0):
"""Read CPU register values
:param cpu_index: The CPU index to read. 0 by default.
:type cpu_index: int
:return: The CPU
:rtype: X64CPU | X86CPU | ...
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
if cpu_index >= get_num_cpus():
raise ValueError("Incorrect cpu index specified")
return c_api.r_cpu(cpu_index)
def w_pa(addr, buff, length=None):
"""Write physical address
:param addr: The address to write
:type addr: int
:param buff: The buffer to write
:type buffer: str
:return: None
:rtype: None
"""
import c_api
# The length parameter is not used at this moment,
# but is kept to avoid breaking old scripts.
if length is not None and len(buff) != length:
raise ValueError(
"Length of the buffer does not match the declared length")
else:
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it
# propagate upwards
offset = addr
length = len(buff)
while offset < (addr + length):
write_length = 0x2000 if (addr + length - offset) > 0x2000 else (addr + length - offset)
c_api.w_pa(offset, buff[(offset - addr):(offset - addr + write_length)])
offset += write_length
return None
def w_va(pgd, addr, buff, length=None):
"""Write virtual address
:param pgd: The PGD (address space) to write to.
:type pgd: int
:param addr: The address to write
:type addr: int
:param buff: The buffer to write
:type buffer: str
:return: None
:rtype: None
"""
import c_api
# The length parameter is not used at this moment,
# but is kept to avoid breaking old scripts.
if length is not None and len(buff) != length:
raise ValueError(
"Length of the buffer does not match the declared length")
else:
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it
# propagate upwards
offset = addr
length = len(buff)
while offset < (addr + length):
write_length = 0x2000 if (addr + length - offset) > 0x2000 else (addr + length - offset)
c_api.w_va(pgd, offset, buff[(offset - addr):(offset - addr + write_length)])
offset += write_length
return None
def r_ioport(address, size):
"""Read I/O port
:param address: The port address to read, from 0 to 65536
:type address: int
:param size: The size to read (1, 2, or 4)
:type size: int
:return: The value read
:rtype: int
"""
import c_api
if size not in [1, 2, 4]:
raise ValueError("Incorrect size to read: it must be 1, 2 or 4")
if address < 0 or address > 65536:
raise ValueError("Incorrect port address: it must be between 0-65536")
return c_api.r_ioport(address, size)
def w_ioport(address, size, value):
"""Write I/O port
:param address: The port address to write, from 0 to 65536
:type address: int
:param size: The size to read (1, 2, or 4)
:type size: int
:return: The value written
:rtype: int
"""
import c_api
if size not in [1, 2, 4]:
raise ValueError("Incorrect size to read: it must be 1, 2 or 4")
if address < 0 or address > 65536:
raise ValueError("Incorrect port address: it must be between 0-65536")
return c_api.w_ioport(address, size, value)
def w_r(cpu_index, regname, val):
"""Write register
:param cpu_index: CPU index of the register to write
:type cpu_index: int
:param regname: Name of the register to write
:type regname: str
:param val: Value to write
:type val: int
:return: None
:rtype: None
"""
from utils import ConfigurationManager as conf_m
import c_api
if cpu_index >= get_num_cpus():
raise ValueError("Incorrect cpu index specified")
if conf_m.platform == "i386-softmmu":
if regname in X86CPU.reg_nums:
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it
# propagate upwards
return c_api.w_r(cpu_index, X86CPU.reg_nums[regname], val)
else:
raise ValueError("[w_r] Wrong register specification")
elif conf_m.platform == "x86_64-softmmu":
if regname in X64CPU.reg_nums:
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it
# propagate upwards
return c_api.w_r(cpu_index, X64CPU.reg_nums[regname], val)
else:
raise ValueError("[w_r] Wrong register specification")
else:
raise ValueError("[w_r] Wrong platform specification")
def w_sr(cpu_index, regname, selector, base, limit, flags):
"""Write segment register. Only applies to x86 / x86-64
:param cpu_index: CPU index of the register to write
:type cpu_index: int
:param regname: Name of the register to write
:type regname: str
:param selector: Value (selector) to write
:type selector: int
:param base: Value (base) to write
:type selector: int
:param limit: Value (limit) to write
:type selector: int
:return: None
:rtype: None
"""
from utils import ConfigurationManager as conf_m
import c_api
if cpu_index >= get_num_cpus():
raise ValueError("Incorrect cpu index specified")
if conf_m.platform == "i386-softmmu":
if regname in X86CPU.reg_nums:
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it
# propagate upwards
return c_api.w_sr(
cpu_index,
X86CPU.reg_nums[regname],
selector,
base,
limit,
flags)
else:
raise ValueError("[w_r] Wrong register specification")
elif conf_m.platform == "x86_64-softmmu":
if regname in X64CPU.reg_nums:
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it
# propagate upwards
return c_api.w_sr(
cpu_index,
X64CPU.reg_nums[regname],
selector,
base,
limit,
flags)
else:
raise ValueError("[w_r] Wrong register specification")
else:
raise ValueError("[w_r] Wrong platform specification")
def va_to_pa(pgd, addr):
""" Virtual to physical address.
:param pgd: PGD, or address space of the address to translate
:type addr: int
:param addr: Virtual address to translate
:type addr: int
:return: The translated physical address
:rtype: int
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
return c_api.va_to_pa(pgd, addr)
def start_monitoring_process(pgd):
""" Start monitoring a process. Process-wide callbacks will be called for every process that is being monitored
:param pgd: PGD, or address space of the process to check
:type pgd: int
:return: None
:rtype: None
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
return c_api.start_monitoring_process(pgd)
def is_monitored_process(pgd):
"""Returns true of a given process is being monitored. Process-wide callbacks will be called for every
process that is being monitored
:param pgd: PGD, or address space of the process to monitor
:type pgd: int
:return: True of the process is being monitored, False otherwise
:rtype: bool
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
return c_api.is_monitored_process(pgd)
def stop_monitoring_process(pgd, force=False):
""" Start monitoring a process. Process-wide callbacks will be called for every process that is being monitored
:param pgd: PGD, or address space of the process to stop monitoring
:type pgd: int
:return: None
:rtype: None
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
return c_api.stop_monitoring_process(pgd, 1 if force else 0)
def get_running_process(cpu_index=0):
"""Returns the PGD or address space of the process that is being executed at this moment
:param cpu_index: CPU index that we want to query. Each CPU might be executing a different address space
:type cpu_index: int
:return: The PGD or address space for the process that is executing on the indicated CPU
:rtype: int
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
if cpu_index >= get_num_cpus():
raise ValueError("Incorrect cpu index specified")
return c_api.get_running_process(cpu_index)
def is_kernel_running(cpu_index=0):
""" Returns True if the corresponding CPU is executing in Ring 0
:param cpu_index: CPU index that we want to query. Each CPU might be executing a different address space
:type cpu_index: int
:return: True if the corresponding CPU is executing in Ring 0, False otherwise
:rtype: bool
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
if cpu_index >= get_num_cpus():
raise ValueError("Incorrect cpu index specified")
return c_api.is_kernel_running(cpu_index)
def save_vm(name):
"""Save the state of the virtual machine so that it can be restored later
:param name: Name of the snapshot to save
:type name: str
:return: None
:rtype: None
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
return c_api.save_vm(name)
def load_vm(name):
"""Load a previously saved snapshot of the virtual machine.
:param name: Name of the snapshot to load
:type name: str
:return: None
:rtype: None
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
return c_api.load_vm(name)
def get_process_list():
""" Return list of processes.
:return: List of processes. List of dictionaries with keys: "pid", "pgd", "name", "kaddr", where kaddr
stands for the kernel address representing the process (e.g.: EPROCESS)
:rtype: list
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
return c_api.get_process_list()
def get_os_bits():
""" Return the bitness of the system / O.S. being emulated
:return: The bitness of the system / O.S. being emualated
:rtype: int
"""
import c_api
# If this function call fails, it will raise an exception.
# Given that the exception is self explanatory, we just let it propagate
# upwards
return c_api.get_os_bits()
# Rest of API functions
def get_module_list(pgd):
""" Return list of modules for a given PGD
:param pgd: The PGD of the process for which we want to extract the modules, or 0 to extract kernel modules
:type pgd: int
:return: List of modules, each element is a dictionary with keys: "name", "base", "size", and "symbols_resolved"
:rtype: list
"""
import vmi
proc_list = get_process_list()
mods = []
found = False
if pgd == 0:
proc_pid = 0
proc_pgd = 0
found = True
else:
for proc in proc_list:
proc_pid = proc["pid"]
proc_pgd = proc["pgd"]
if proc_pgd == pgd:
found = True
break
if found:
vmi.update_modules(proc_pgd, update_symbols=False)
if (proc_pid, proc_pgd) in vmi.modules:
for mod in vmi.modules[(proc_pid, proc_pgd)].values():
mods.append({"name": mod.get_name(),
"base": mod.get_base(),
"size": mod.get_size(),
"symbols_resolved" : mod.are_symbols_resolved()})
return mods
else:
raise ValueError("Process with PGD %x not found" % pgd)
def get_symbol_list(pgd = None):
""" Return list of symbols
:param pgd: The pgd to obtain the symbols from. 0 to get kernel symbols
:type pgd: int
:return: List of symbols, each element is a dictionary with keys: "mod", "name", and "addr"
:rtype: list
"""
import vmi
from utils import pp_print
res_syms = []
diff_modules = {}
if pgd is None:
proc_list = get_process_list()
pp_print("[*] Updating symbol list... Be patient, this may take a while\n")
for proc in proc_list:
proc_pid = proc["pid"]
proc_pgd = proc["pgd"]
if proc_pgd != 0:
vmi.update_modules(proc_pgd, update_symbols=True)
if (proc_pid, proc_pgd) in vmi.modules:
for module in vmi.modules[proc_pid, proc_pgd].values():
c = module.get_checksum()
n = module.get_fullname()
if (c, n) not in diff_modules:
diff_modules[(c, n)] = [module]
else:
diff_modules[(c, n)].append(module)
# Include kernel modules too
vmi.update_modules(0, update_symbols=True)
if (0, 0) in vmi.modules:
for module in vmi.modules[0, 0].values():
c = module.get_checksum()
n = module.get_fullname()
if (c, n) not in diff_modules:
diff_modules[(c, n)] = [module]
else:
diff_modules[(c, n)].append(module)
else:
pp_print("[*] Updating symbol list for one process... Be patient, this may take a while\n")
vmi.update_modules(pgd, update_symbols=True)
for proc_pid, proc_pgd in vmi.modules:
if proc_pgd == pgd:
for module in vmi.modules[proc_pid, proc_pgd].values():
c = module.get_checksum()
n = module.get_fullname()
if (c, n) not in diff_modules:
diff_modules[(c, n)] = [module]
else:
diff_modules[(c, n)].append(module)
for mod_list in diff_modules.values():
added_names = []
for mod in mod_list:
syms = mod.get_symbols()
for name in syms:
if name not in added_names:
res_syms.append({"mod": mod.get_name(), "name": name, "addr": syms[name]})
added_names.append(name)
return res_syms
def sym_to_va(pgd, mod_name, func_name):
""" Resolve an address given a symbol name
:param pgd: The PGD or address space for the process for which we want to search the symbol
:type pgd: int
:param mod_name: The module name that contains the symbol
:type mod_name: str
:param func_name: The function name to resolve
:type func_name: str
:return: The address, or None if the symbol is not found
:rtype: str
"""
import vmi
# First, check if the process exists
process_found = False
for proc in get_process_list():
if pgd == proc["pgd"]:
process_found = True
break
if not process_found:
raise ValueError("Process with PGD %x not found" % pgd)
mod_name = mod_name.lower()
func_name = func_name.lower()
for proc_pid, proc_pgd in vmi.modules:
if proc_pgd == pgd:
for module in vmi.modules[proc_pid, proc_pgd].values():
if mod_name in module.get_name().lower():
syms = module.get_symbols()
for name in syms:
symbol_offset = syms[name]
if func_name == name.lower():
return (module.get_base() + symbol_offset)
# Finally, return None if the symbol is not found
return None
def va_to_sym(pgd, addr):
""" Find symbols for a particular virtual address
:param pgd: The PGD or address space for the process for which we want to search the symbol
:type pgd: int
:param addr: The virtual address to search
:type addr: int
:return: A tuple containing the module name and the function name, None if nothing found
:rtype: tuple
"""
import vmi
# First, check if the process exists
process_found = False
for proc in get_process_list():
if pgd == proc["pgd"]:
process_found = True
break
if not process_found:
raise ValueError("Process with PGD %x not found" % pgd)
for proc_pid, proc_pgd in vmi.modules:
if proc_pgd == pgd:
for module in vmi.modules[proc_pid, proc_pgd].values():
offset = (addr - module.get_base())
if offset > 0 and offset < module.get_size():
syms = module.get_symbols()
for name in syms:
symbol_offset = syms[name]
if offset == symbol_offset:
return (module.get_name(), name)
# Finally, return None if the symbol is not found
return None
def import_module(module_name):
""" Import a module given its name (e.g. scripts.script_example)
:param module_name: The module name following python notation.
E.g.: scripts.script_example
:type module_name: str
:return: None
:rtype: None
"""
import c_api
c_api.import_module(module_name)
def unload_module(module_handle):
""" Unload a module given its handle.
:param module_handle: The module handle.
:type module_name: int
:return: None
:rtype: None
"""
import c_api
c_api.unload_module(module_handle)
def reload_module(module_handle):
""" Reload a module given its handle.
:param module_handle: The module handle.
:type module_handle: int
:return: None
:rtype: None
"""
import c_api
c_api.reload_module(module_handle)
def get_loaded_modules():
""" Returns a dictionary of modules loaded in pyrebox.
:return: Dictionary with the keys: "module_handle", "module_name", "is_loaded"
:rtype: dict
"""
import c_api
return c_api.get_loaded_modules()
# ================================================== CLASSES =============
# These wrappers are helpers for the callback manager
# that deal with the 2 possible callback parameter conventions
def function_wrapper_old(f, callback_type, *args, **kwargs):
global DISABLE_DEPRECATION_WARNINGS
try:
if not DISABLE_DEPRECATION_WARNINGS:
from utils import pp_warning
pp_warning("You are using a deprecated callback format.\n" + \
"Switch to new style callback format, that will become the default in the future.\n" + \
"See the documentation of CallbackManager for further reference.\n")
# Set to True, so that we don't repeat the same message again and again
DISABLE_DEPRECATION_WARNINGS = True
# We need to treat each callback separately
if callback_type == CallbackManager.BLOCK_BEGIN_CB:
f(kwargs["cpu_index"], kwargs["cpu"], kwargs["tb"])
elif callback_type == CallbackManager.BLOCK_END_CB:
f(kwargs["cpu_index"], kwargs["cpu"], kwargs["tb"], kwargs["cur_pc"], kwargs["next_pc"])
elif callback_type == CallbackManager.INSN_BEGIN_CB:
f(kwargs["cpu_index"], kwargs["cpu"])
elif callback_type == CallbackManager.INSN_END_CB:
f(kwargs["cpu_index"], kwargs["cpu"])
elif callback_type == CallbackManager.MEM_READ_CB:
f(kwargs["cpu_index"], kwargs["vaddr"], kwargs["size"], kwargs["haddr"])
elif callback_type == CallbackManager.MEM_WRITE_CB:
f(kwargs["cpu_index"], kwargs["vaddr"], kwargs["size"], kwargs["haddr"], kwargs["data"])
elif callback_type == CallbackManager.KEYSTROKE_CB:
f(kwargs["keycode"])
elif callback_type == CallbackManager.NIC_REC_CB:
f(kwargs["buf"], kwargs["size"], kwargs["cur_pos"], kwargs["start"], kwargs["stop"])
elif callback_type == CallbackManager.NIC_SEND_CB:
f(kwargs["addr"], kwargs["size"], kwargs["buf"])
elif callback_type == CallbackManager.OPCODE_RANGE_CB:
f(kwargs["cpu_index"], kwargs["cpu"], kwargs["cur_pc"], kwargs["next_pc"])
elif callback_type == CallbackManager.TLB_EXEC_CB:
f(kwargs["cpu"], kwargs["vaddr"])
elif callback_type == CallbackManager.CREATEPROC_CB:
f(kwargs["pid"], kwargs["pgd"], kwargs["name"])
elif callback_type == CallbackManager.REMOVEPROC_CB:
f(kwargs["pid"], kwargs["pgd"], kwargs["name"])
elif callback_type == CallbackManager.CONTEXTCHANGE_CB:
f(kwargs["old_pgd"], kwargs["new_pgd"])
elif callback_type == CallbackManager.LOADMODULE_CB:
f(kwargs["pid"], kwargs["pgd"], kwargs["base"], kwargs["size"], kwargs["name"], kwargs["fullname"])
elif callback_type == CallbackManager.REMOVEMODULE_CB:
f(kwargs["pid"], kwargs["pgd"], kwargs["base"], kwargs["size"], kwargs["name"], kwargs["fullname"])
else:
raise Exception("Unsupported callback type!")
except Exception as e:
from utils import pp_error
pp_error("\nException occurred when calling callback function %s - %s\n\n" % (str(f), str(e)))
finally:
return
def wrap_old(f, callback_type):
return lambda *args, **kwargs: function_wrapper_old(f, callback_type, *args, **kwargs)
def function_wrapper_new(f, *args, **kwargs):
try:
f(kwargs)
except Exception as e:
from utils import pp_error
pp_error("\nException occurred when calling callback function %s - %s" % (repr(f), str(e)))
finally:
return
def wrap_new(f, callback_type):
return lambda *args, **kwargs: function_wrapper_new(f, *args, **kwargs)
class CallbackManager:
'''
Class that abstracts callback management,optionally associating names to callbacks, and registering the list of
added callbacks so that we can remove them all with a single call to "clean()" after we are done.
'''
INV0_CB = 0 # Shadow optimized callbacks for block and insn begin
INV1_CB = 1 # Shadow optimized callbacks for block and insn begin
BLOCK_BEGIN_CB = 2
BLOCK_END_CB = 3
INSN_BEGIN_CB = 4
INSN_END_CB = 5
MEM_READ_CB = 6
MEM_WRITE_CB = 7
KEYSTROKE_CB = 8
NIC_REC_CB = 9
NIC_SEND_CB = 10
OPCODE_RANGE_CB = 11
TLB_EXEC_CB = 12
CREATEPROC_CB = 13
REMOVEPROC_CB = 14
CONTEXTCHANGE_CB = 15
LOADMODULE_CB = 16
REMOVEMODULE_CB = 17
def __init__(self, module_hdl, new_style = False):
""" Constructor of the class
:param module_hdl: The module handle provided to the script as parameter to the initialize_callbacks
function. Use 0 if it doesn't apply.
:type module_hdl: int
:param new_style: Enables the new-style callback parameter format. New-style callback functions accept
a single parameter (dictionary), with a key (str) per parameter, and a value (value of
the parameter), instead of positional arguments.
:type new_style: bool
"""
self.callbacks = {}
self.load_module_callbacks = {}
self.remove_module_callbacks = {}
self.module_hdl = module_hdl
self.new_style = new_style
def get_module_handle(self):
""" Returns the module handle associated to this callback manager
:return: The handle of the module this callback manager is bound to.
:rtype: int
"""
return self.module_hdl
def generate_callback_name(self, name):
""" Generates a unique callback name given an initial name
:param name: The initial name
:type name: str
:return: The new generated name
:rtype: str
"""
subname = name
counter = 0
while subname in self.callbacks or \
subname in self.load_module_callbacks or \
subname in self.remove_module_callbacks:
subname = "%s_%d" % (name, counter)
counter += 1
return subname
def add_callback(
self,
callback_type,
func,
name=None,
addr=None,
pgd=None,
start_opcode=None,
end_opcode=None,
new_style=None):
""" Add a callback to the module, given a name, so that we can refer to it later.
If the name is repeated, it will provide back a new name based on the one passed as argument,
that can be used later for removing it or attaching triggers to it.
:param name: The name of the callback
:type name: str
:param callback_type: The callback type to insert. One of INSN_BEGIN_CB, BLOCK_BEGIN_CB, etc... See help(api)
from a pyrebox shell to get a complete listing of constants ending in _CB
:type callback_type: int
:param func: The callback function (python function)
:type func: function
:param addr: Optional. The address where we want to place the callback. Only applies
eo INSN_BEGIN_CB, BLOCK_BEGIN_CB
:type addr: int
:param pgd: Optional. The PGD (addr space) where we want to place the callback. Only applies
to INSN_BEGIN_CB, BLOCK_BEGIN_CB
:type pgd: int
:param new_style: Optional. Enables the new-style callback parameter format. New-style callback functions accept
a single parameter (dictionary), with a key (str) per parameter, and a value (value of
the parameter), instead of positional arguments. This parameter overrides the class-wide
new_style parameter in the CallbackManager __init__ function.
:type new_style: bool
:return: The actual inserted callback name. If the callback name indicated already existed,
this name will be updated to make it unique. This name can be used as a handle to the callback
:rtype: str
"""
import random
import string
import time
# Old style vs new style callbacks:
# Old style is maintained for backwards compatibility,
# but will be removed at some point. For the moment,
# we use old style by default to avoid breaking
# user's scripts, but print a deprecation warning
# to let users know that this style will be removed
# in the future, so that they can adapt their scripts
# to the new style.
# Old style means position based parameters, while new
# style means one single parameter (dictionary), with a
# str key, and a value, for each of the parameters.
# This new approach allows to add new parameters in the future
# without breaking script compatibility.
# If not specified, apply the class default
if new_style is None:
new_style = self.new_style
if new_style is True:
wrap = wrap_new
else:
wrap = wrap_old
# If a name was not provided, just provide a 16 lowercase letter random
# name
if name is None:
random.seed(time.time())
name = "".join(random.choice(string.lowercase) for i in range(16))
name = self.generate_callback_name(name)
# If the callback_type is a module callback, register it with specific API
if callback_type == CallbackManager.LOADMODULE_CB:
self.load_module_callbacks[name] = register_module_load_callback(pgd, name, wrap(func, callback_type))
return name
if callback_type == CallbackManager.REMOVEMODULE_CB:
self.remove_module_callbacks[name] = register_module_remove_callback(pgd, name, wrap(func, callback_type))
return name
# addr,pgd and start_opcode,end_opcode are exclusive, so we join them
# together to call register_callback
first_param = start_opcode if addr is None else addr
second_param = end_opcode if pgd is None else pgd
self.callbacks[name] = register_callback(
self.module_hdl, callback_type, wrap(func, callback_type), first_param, second_param)
return name
def rm_callback(self, name):
""" Remove a callback given its name. Associated triggers will get unloaded too.
:param name: The name of the callback to remove
:type name: str
:return: None
:rtype: None
"""
if name in self.callbacks:
unregister_callback(self.callbacks[name])
del(self.callbacks[name])
return
if name in self.load_module_callbacks:
unregister_module_load_callback(self.load_module_callbacks[name])
del(self.load_module_callbacks[name])
return
if name in self.remove_module_callbacks:
unregister_module_remove_callback(self.remove_module_callbacks[name])
del(self.remove_module_callbacks[name])
return
raise ValueError(
"[!] CallbackManager: A callback with name %s does not exist and cannot be removed\n" %
(name))