forked from longld/peda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peda.py
6125 lines (5251 loc) · 193 KB
/
peda.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
#
# PEDA - Python Exploit Development Assistance for GDB
#
# Copyright (C) 2012 Long Le Dinh <longld at vnsecurity.net>
#
# License: see LICENSE file for details
#
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import os
import sys
import shlex
import string
import time
import signal
import traceback
import codecs
# point to absolute path of peda.py
PEDAFILE = os.path.abspath(os.path.expanduser(__file__))
if os.path.islink(PEDAFILE):
PEDAFILE = os.readlink(PEDAFILE)
sys.path.insert(0, os.path.dirname(PEDAFILE) + "/lib/")
# Use six library to provide Python 2/3 compatibility
import six
from six.moves import range
from six.moves import input
try:
import six.moves.cPickle as pickle
except ImportError:
import pickle
from skeleton import *
from shellcode import *
from utils import *
import config
from nasm import *
if sys.version_info.major is 3:
from urllib.request import urlopen
from urllib.parse import urlencode
pyversion = 3
else:
from urllib import urlopen
from urllib import urlencode
pyversion = 2
REGISTERS = {
8 : ["al", "ah", "bl", "bh", "cl", "ch", "dl", "dh"],
16: ["ax", "bx", "cx", "dx"],
32: ["eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp", "eip"],
64: ["rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp", "rsp", "rip",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"]
}
###########################################################################
class PEDA(object):
"""
Class for actual functions of PEDA commands
"""
def __init__(self):
self.SAVED_COMMANDS = {} # saved GDB user's commands
####################################
# GDB Interaction / Misc Utils #
####################################
def execute(self, gdb_command):
"""
Wrapper for gdb.execute, catch the exception so it will not stop python script
Args:
- gdb_command (String)
Returns:
- True if execution succeed (Bool)
"""
try:
gdb.execute(gdb_command)
return True
except Exception as e:
if config.Option.get("debug") == "on":
msg('Exception (%s): %s' % (gdb_command, e), "red")
traceback.print_exc()
return False
def execute_redirect(self, gdb_command, silent=False):
"""
Execute a gdb command and capture its output
Args:
- gdb_command (String)
- silent: discard command's output, redirect to /dev/null (Bool)
Returns:
- output of command (String)
"""
result = None
#init redirection
if silent:
logfd = open(os.path.devnull, "r+")
else:
logfd = tmpfile()
logname = logfd.name
gdb.execute('set logging off') # prevent nested call
gdb.execute('set height 0') # disable paging
gdb.execute('set logging file %s' % logname)
gdb.execute('set logging overwrite on')
gdb.execute('set logging redirect on')
gdb.execute('set logging on')
try:
gdb.execute(gdb_command)
gdb.flush()
gdb.execute('set logging off')
if not silent:
logfd.flush()
result = logfd.read()
logfd.close()
except Exception as e:
gdb.execute('set logging off') #to be sure
if config.Option.get("debug") == "on":
msg('Exception (%s): %s' % (gdb_command, e), "red")
traceback.print_exc()
logfd.close()
if config.Option.get("verbose") == "on":
msg(result)
return result
def parse_and_eval(self, exp):
"""
Work around implementation for gdb.parse_and_eval with enhancements
Args:
- exp: expression to evaluate (String)
Returns:
- value of expression
"""
regs = sum(REGISTERS.values(), [])
for r in regs:
if "$"+r not in exp and "e"+r not in exp and "r"+r not in exp:
exp = exp.replace(r, "$%s" % r)
p = re.compile("(.*)\[(.*)\]") # DWORD PTR [esi+eax*1]
matches = p.search(exp)
if not matches:
p = re.compile("(.*).s:(0x.*)") # DWORD PTR ds:0xdeadbeef
matches = p.search(exp)
if matches:
mod = "w"
if "BYTE" in matches.group(1):
mod = "b"
elif "QWORD" in matches.group(1):
mod = "g"
elif "DWORD" in matches.group(1):
mod = "w"
elif "WORD" in matches.group(1):
mod = "h"
out = self.execute_redirect("x/%sx %s" % (mod, matches.group(2)))
if not out:
return None
else:
return out.split(":\t")[-1].strip()
else:
out = self.execute_redirect("print %s" % exp)
if not out:
return None
else:
out = gdb.history(0).__str__()
out = out.encode('ascii', 'ignore')
out = decode_string_escape(out)
return out.strip()
def string_to_argv(self, str):
"""
Convert a string to argv list, pre-processing register and variable values
Args:
- str: input string (String)
Returns:
- argv list (List)
"""
try:
str = str.encode('ascii', 'ignore')
except:
pass
str = decode_string_escape(str)
args = shlex.split(str)
# need more processing here
for idx, a in enumerate(args):
a = a.strip(",")
if a.startswith("$"): # try to get register/variable value
v = self.parse_and_eval(a)
if v != None and v != "void":
if v.startswith("0x"): # int
args[idx] = v.split()[0] # workaround for 0xdeadbeef <symbol+x>
else: # string, complex data
args[idx] = v
elif a.startswith("+"): # relative value to prev arg
adder = to_int(self.parse_and_eval(a[1:]))
if adder is not None:
args[idx] = "%s" % to_hex(to_int(args[idx-1]) + adder)
elif is_math_exp(a):
try:
v = eval("%s" % a)
# XXX hack to avoid builtin functions/types
if not isinstance(v, six.string_types + six.integer_types):
continue
args[idx] = "%s" % (to_hex(v) if to_int(v) != None else v)
except:
pass
if config.Option.get("verbose") == "on":
msg(args)
return args
################################
# GDB User-Defined Helpers #
################################
def save_user_command(self, cmd):
"""
Save user-defined command and deactivate it
Args:
- cmd: user-defined command (String)
Returns:
- True if success to save (Bool)
"""
commands = self.execute_redirect("show user %s" % cmd)
if not commands:
return False
commands = "\n".join(commands.splitlines()[1:])
commands = "define %s\n" % cmd + commands + "end\n"
self.SAVED_COMMANDS[cmd] = commands
tmp = tmpfile()
tmp.write("define %s\nend\n" % cmd)
tmp.flush()
result = self.execute("source %s" % tmp.name)
tmp.close()
return result
def define_user_command(self, cmd, code):
"""
Define a user-defined command, overwrite the old content
Args:
- cmd: user-defined command (String)
- code: gdb script code to append (String)
Returns:
- True if success to define (Bool)
"""
commands = "define %s\n" % cmd + code + "\nend\n"
tmp = tmpfile(is_binary_file=False)
tmp.write(commands)
tmp.flush()
result = self.execute("source %s" % tmp.name)
tmp.close()
return result
def append_user_command(self, cmd, code):
"""
Append code to a user-defined command, define new command if not exist
Args:
- cmd: user-defined command (String)
- code: gdb script code to append (String)
Returns:
- True if success to append (Bool)
"""
commands = self.execute_redirect("show user %s" % cmd)
if not commands:
return self.define_user_command(cmd, code)
# else
commands = "\n".join(commands.splitlines()[1:])
if code in commands:
return True
commands = "define %s\n" % cmd + commands + code + "\nend\n"
tmp = tmpfile()
tmp.write(commands)
tmp.flush()
result = self.execute("source %s" % tmp.name)
tmp.close()
return result
def restore_user_command(self, cmd):
"""
Restore saved user-defined command
Args:
- cmd: user-defined command (String)
Returns:
- True if success to restore (Bool)
"""
if cmd == "all":
commands = "\n".join(self.SAVED_COMMANDS.values())
self.SAVED_COMMANDS = {}
else:
if cmd not in self.SAVED_COMMANDS:
return False
else:
commands = self.SAVED_COMMANDS[cmd]
self.SAVED_COMMANDS.pop(cmd)
tmp = tmpfile()
tmp.write(commands)
tmp.flush()
result = self.execute("source %s" % tmp.name)
tmp.close()
return result
def run_gdbscript_code(self, code):
"""
Run basic gdbscript code as it is typed in interactively
Args:
- code: gdbscript code, lines are splitted by "\n" or ";" (String)
Returns:
- True if success to run (Bool)
"""
tmp = tmpfile()
tmp.write(code.replace(";", "\n"))
tmp.flush()
result = self.execute("source %s" % tmp.name)
tmp.close()
return result
#########################
# Debugging Helpers #
#########################
@memoized
def is_target_remote(self):
"""
Check if current target is remote
Returns:
- True if target is remote (Bool)
"""
out = self.execute_redirect("info program")
if out and "serial line" in out: # remote target
return True
return False
@memoized
def getfile(self):
"""
Get exec file of debugged program
Returns:
- full path to executable file (String)
"""
result = None
out = self.execute_redirect('info files')
if out and '"' in out:
p = re.compile(".*exec file:\s*`(.*)'")
m = p.search(out)
if m:
result = m.group(1)
else: # stripped file, get symbol file
p = re.compile("Symbols from \"([^\"]*)")
m = p.search(out)
if m:
result = m.group(1)
return result
def get_status(self):
"""
Get execution status of debugged program
Returns:
- current status of program (String)
STOPPED - not being run
BREAKPOINT - breakpoint hit
SIGXXX - stopped by signal XXX
UNKNOWN - unknown, not implemented
"""
status = "UNKNOWN"
out = self.execute_redirect("info program")
for line in out.splitlines():
if line.startswith("It stopped"):
if "signal" in line: # stopped by signal
status = line.split("signal")[1].split(",")[0].strip()
break
if "breakpoint" in line: # breakpoint hit
status = "BREAKPOINT"
break
if "not being run" in line:
status = "STOPPED"
break
return status
@memoized
def getpid(self):
"""
Get PID of the debugged process
Returns:
- pid (Int)
"""
out = None
status = self.get_status()
if not status or status == "STOPPED":
return None
if self.is_target_remote(): # remote target
ctx = config.Option.get("context")
config.Option.set("context", None)
try:
out = self.execute_redirect("call getpid()")
except:
pass
config.Option.set("context", ctx)
if out is None:
return None
else:
out = self.execute_redirect("print $")
if out:
return to_int(out.split("=")[1])
else:
return None
if self.getos() == "Linux":
out = self.execute_redirect('info proc')
if out is None: # non-Linux or cannot access /proc, fallback
out = self.execute_redirect('info program')
out = out.splitlines()[0]
if "process" in out or "Thread" in out:
pid = out.split()[-1].strip(".)")
return int(pid)
else:
return None
def getos(self):
"""
Get running OS info
Returns:
- os version (String)
"""
# TODO: get remote os by calling uname()
return os.uname()[0]
@memoized
def getarch(self):
"""
Get architecture of debugged program
Returns:
- tuple of architecture info (arch (String), bits (Int))
"""
arch = "unknown"
bits = 32
out = self.execute_redirect('maintenance info sections ?').splitlines()
for line in out:
if "file type" in line:
arch = line.split()[-1][:-1]
break
if "64" in arch:
bits = 64
return (arch, bits)
def intsize(self):
"""
Get dword size of debugged program
Returns:
- size (Int)
+ intsize = 4/8 for 32/64-bits arch
"""
(arch, bits) = self.getarch()
return bits // 8
def getregs(self, reglist=None):
"""
Get value of some or all registers
Returns:
- dictionary of {regname(String) : value(Int)}
"""
if reglist:
reglist = reglist.replace(",", " ")
else:
reglist = ""
regs = self.execute_redirect("info registers %s" % reglist)
if not regs:
return None
result = {}
if regs:
for r in regs.splitlines():
r = r.split()
if len(r) > 1 and to_int(r[1]) is not None:
result[r[0]] = to_int(r[1])
return result
def getreg(self, register):
"""
Get value of a specific register
Args:
- register: register name (String)
Returns:
- register value (Int)
"""
r = register.lower()
regs = self.execute_redirect("info registers %s" % r)
if regs:
regs = regs.splitlines()
if len(regs) > 1:
return None
else:
result = to_int(regs[0].split()[1])
return result
return None
def set_breakpoint(self, location, temp=0, hard=0):
"""
Wrapper for GDB break command
- location: target function or address (String ot Int)
Returns:
- True if can set breakpoint
"""
cmd = "break"
if hard:
cmd = "h" + cmd
if temp:
cmd = "t" + cmd
if to_int(location) is not None:
return peda.execute("%s *0x%x" % (cmd, to_int(location)))
else:
return peda.execute("%s %s" % (cmd, location))
def get_breakpoint(self, num):
"""
Get info of a specific breakpoint
TODO: support catchpoint, watchpoint
Args:
- num: breakpoint number
Returns:
- tuple (Num(Int), Type(String), Disp(Bool), Enb(Bool), Address(Int), What(String), commands(String))
"""
out = self.execute_redirect("info breakpoints %d" % num)
if not out or "No breakpoint" in out:
return None
lines = out.splitlines()[1:]
# breakpoint regex
p = re.compile("^(\d*)\s*(.*breakpoint)\s*(keep|del)\s*(y|n)\s*(0x[^ ]*)\s*(.*)")
m = p.match(lines[0])
if not m:
# catchpoint/watchpoint regex
p = re.compile("^(\d*)\s*(.*point)\s*(keep|del)\s*(y|n)\s*(.*)")
m = p.match(lines[0])
if not m:
return None
else:
(num, type, disp, enb, what) = m.groups()
addr = ''
else:
(num, type, disp, enb, addr, what) = m.groups()
disp = True if disp == "keep" else False
enb = True if enb == "y" else False
addr = to_int(addr)
m = re.match("in.*at(.*:\d*)", what)
if m:
what = m.group(1)
else:
if addr: # breakpoint
what = ""
commands = ""
if len(lines) > 1:
for line in lines[1:]:
if "already hit" in line: continue
commands += line + "\n"
return (num, type, disp, enb, addr, what, commands.rstrip())
def get_breakpoints(self):
"""
Get list of current breakpoints
Returns:
- list of tuple (Num(Int), Type(String), Disp(Bool), Nnb(Bool), Address(Int), commands(String))
"""
result = []
out = self.execute_redirect("info breakpoints")
if not out:
return []
bplist = []
for line in out.splitlines():
m = re.match("^(\d*).*", line)
if m and to_int(m.group(1)):
bplist += [to_int(m.group(1))]
for num in bplist:
r = self.get_breakpoint(num)
if r:
result += [r]
return result
def save_breakpoints(self, filename):
"""
Save current breakpoints to file as a script
Args:
- filename: target file (String)
Returns:
- True if success to save (Bool)
"""
# use built-in command for gdb 7.2+
result = self.execute_redirect("save breakpoints %s" % filename)
if result == '':
return True
bplist = self.get_breakpoints()
if not bplist:
return False
try:
fd = open(filename, "w")
for (num, type, disp, enb, addr, what, commands) in bplist:
m = re.match("(.*)point", type)
if m:
cmd = m.group(1).split()[-1]
else:
cmd = "break"
if "hw" in type and cmd == "break":
cmd = "h" + cmd
if "read" in type:
cmd = "r" + cmd
if "acc" in type:
cmd = "a" + cmd
if not disp:
cmd = "t" + cmd
if what:
location = what
else:
location = "*0x%x" % addr
text = "%s %s" % (cmd, location)
if commands:
if "stop only" not in commands:
text += "\ncommands\n%s\nend" % commands
else:
text += commands.split("stop only", 1)[1]
fd.write(text + "\n")
fd.close()
return True
except:
return False
def get_config_filename(self, name):
filename = peda.getfile()
if not filename:
filename = peda.getpid()
if not filename:
filename = 'unknown'
filename = os.path.basename("%s" % filename)
tmpl_name = config.Option.get(name)
if tmpl_name:
return tmpl_name.replace("#FILENAME#", filename)
else:
return "peda-%s-%s" % (name, filename)
def save_session(self, filename=None):
"""
Save current working gdb session to file as a script
Args:
- filename: target file (String)
Returns:
- True if success to save (Bool)
"""
session = ""
if not filename:
filename = self.get_config_filename("session")
# exec-wrapper
out = self.execute_redirect("show exec-wrapper")
wrapper = out.split('"')[1]
if wrapper:
session += "set exec-wrapper %s\n" % wrapper
try:
# save breakpoints
self.save_breakpoints(filename)
fd = open(filename, "a+")
fd.write("\n" + session)
fd.close()
return True
except:
return False
def restore_session(self, filename=None):
"""
Restore previous saved working gdb session from file
Args:
- filename: source file (String)
Returns:
- True if success to restore (Bool)
"""
if not filename:
filename = self.get_config_filename("session")
# temporarily save and clear breakpoints
tmp = tmpfile()
self.save_breakpoints(tmp.name)
self.execute("delete")
result = self.execute("source %s" % filename)
if not result:
self.execute("source %s" % tmp.name)
tmp.close()
return result
@memoized
def assemble(self, asmcode, bits=None):
"""
Assemble ASM instructions using NASM
- asmcode: input ASM instructions, multiple instructions are separated by ";" (String)
Returns:
- bin code (raw bytes)
"""
if bits is None:
(arch, bits) = self.getarch()
return Nasm.assemble(asmcode, bits)
def disassemble(self, *arg):
"""
Wrapper for disassemble command
- arg: args for disassemble command
Returns:
- text code (String)
"""
code = ""
modif = ""
arg = list(arg)
if len(arg) > 1:
if "/" in arg[0]:
modif = arg[0]
arg = arg[1:]
if len(arg) == 1 and to_int(arg[0]) != None:
arg += [to_hex(to_int(arg[0]) + 32)]
self.execute("set disassembly-flavor intel")
out = self.execute_redirect("disassemble %s %s" % (modif, ",".join(arg)))
if not out:
return None
else:
code = out
return code
@memoized
def prev_inst(self, address, count=1):
"""
Get previous instructions at an address
Args:
- address: address to get previous instruction (Int)
- count: number of instructions to read (Int)
Returns:
- list of tuple (address(Int), code(String))
"""
result = []
backward = 64+16*count
for i in range(backward):
if self.getpid() and not self.is_address(address-backward+i):
continue
code = self.execute_redirect("disassemble %s, %s" % (to_hex(address-backward+i), to_hex(address+1)))
if code and ("%x" % address) in code:
lines = code.strip().splitlines()[1:-1]
if len(lines) > count and "(bad)" not in " ".join(lines):
for line in lines[-count-1:-1]:
(addr, code) = line.split(":", 1)
addr = re.search("(0x[^ ]*)", addr).group(1)
result += [(to_int(addr), code)]
return result
return None
@memoized
def current_inst(self, address):
"""
Parse instruction at an address
Args:
- address: address to get next instruction (Int)
Returns:
- tuple of (address(Int), code(String))
"""
out = self.execute_redirect("x/i 0x%x" % address)
if not out:
return None
(addr, code) = out.split(":", 1)
addr = re.search("(0x[^ ]*)", addr).group(1)
addr = to_int(addr)
code = code.strip()
return (addr, code)
@memoized
def next_inst(self, address, count=1):
"""
Get next instructions at an address
Args:
- address: address to get next instruction (Int)
- count: number of instructions to read (Int)
Returns:
- - list of tuple (address(Int), code(String))
"""
result = []
code = self.execute_redirect("x/%di 0x%x" % (count+1, address))
if not code:
return None
lines = code.strip().splitlines()
for i in range(1, count+1):
(addr, code) = lines[i].split(":", 1)
addr = re.search("(0x[^ ]*)", addr).group(1)
result += [(to_int(addr), code)]
return result
@memoized
def disassemble_around(self, address, count=8):
"""
Disassemble instructions nearby current PC or an address
Args:
- address: start address to disassemble around (Int)
- count: number of instructions to disassemble
Returns:
- text code (String)
"""
count = min(count, 256)
pc = address
if pc is None:
return None
# check if address is reachable
if not self.execute_redirect("x/x 0x%x" % pc):
return None
prev_code = self.prev_inst(pc, count//2-1)
if prev_code:
start = prev_code[0][0]
else:
start = pc
if start == pc:
count = count//2
code = self.execute_redirect("x/%di 0x%x" % (count, start))
if "0x%x" % pc not in code:
code = self.execute_redirect("x/%di 0x%x" % (count//2, pc))
return code.rstrip()
@memoized
def xrefs(self, search="", filename=None):
"""
Search for all call references or data access to a function/variable
Args:
- search: function or variable to search for (String)
- filename: binary/library to search (String)
Returns:
- list of tuple (address(Int), asm instruction(String))
"""
result = []
if not filename:
filename = self.getfile()
if not filename:
return None
vmap = self.get_vmmap(filename)
elfbase = vmap[0][0] if vmap else 0
if to_int(search) is not None:
search = "%x" % to_int(search)
search_data = 1
if search == "":
search_data = 0
out = execute_external_command("%s -M intel -z --prefix-address -d '%s' | grep '%s'" % (config.OBJDUMP, filename, search))
for line in out.splitlines():
if not line: continue
addr = to_int("0x" + line.split()[0].strip())
if not addr: continue
# update with runtime values
if addr < elfbase:
addr += elfbase
out = self.execute_redirect("x/i 0x%x" % addr)
if out:
line = out
p = re.compile("\s*(0x[^ ]*).*?:\s*([^ ]*)\s*(.*)")
else:
p = re.compile("(.*?)\s*<.*?>\s*([^ ]*)\s*(.*)")
m = p.search(line)
if m:
(address, opcode, opers) = m.groups()
if "call" in opcode and search in opers:
result += [(addr, line.strip())]
if search_data:
if "mov" in opcode and search in opers:
result += [(addr, line.strip())]
return result
def _get_function_args_32(self, code, argc=None):
"""
Guess the number of arguments passed to a function - i386
"""
if not argc:
argc = 0
p = re.compile(".*mov.*\[esp(.*)\],")
matches = p.findall(code)
if matches:
l = len(matches)
for v in matches:
if v.startswith("+"):
offset = to_int(v[1:])
if offset is not None and (offset//4) > l:
continue
argc += 1
else: # try with push style
argc = code.count("push")
argc = min(argc, 6)
if argc == 0:
return []
args = []
sp = self.getreg("sp")
mem = self.dumpmem(sp, sp+4*argc)
for i in range(argc):
args += [struct.unpack("<L", mem[i*4:(i+1)*4])[0]]
return args
def _get_function_args_64(self, code, argc=None):
"""
Guess the number of arguments passed to a function - x86_64
"""
# just retrieve max 6 args
arg_order = ["rdi", "rsi", "rdx", "rcx", "r8", "r9"]
p = re.compile(":\s*([^ ]*)\s*(.*),")