forked from inaz2/roputils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
roputils.py
executable file
·1537 lines (1322 loc) · 57.6 KB
/
roputils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import sys
import os
import re
import struct
import socket
import select
import random
import tempfile
from subprocess import Popen, PIPE
from threading import Thread, Event
from telnetlib import Telnet
from contextlib import contextmanager
def int16(x):
if isinstance(x, (list, tuple)):
return [int(n, 16) for n in x]
else:
return int(x, 16)
def p32(x):
if isinstance(x, str):
return struct.unpack('<I', x)[0]
elif isinstance(x, (list, tuple)):
return struct.pack('<' + ('I'*len(x)), *x)
else:
return struct.pack('<I', x)
def p64(x):
if isinstance(x, str):
return struct.unpack('<Q', x)[0]
elif isinstance(x, (list, tuple)):
return struct.pack('<' + ('Q'*len(x)), *x)
else:
return struct.pack('<Q', x)
class ELF(object):
def __init__(self, fpath, base=0):
def env_with(d):
env = os.environ.copy()
env.update(d)
return env
self.fpath = fpath
self.base = base
self.sec = dict(relro=False, bind_now=False, stack_canary=False, nx=False, pie=False, rpath=False, runpath=False, dt_debug=False)
if not os.path.exists(fpath):
raise Exception("file not found: %r" % fpath)
self._entry_point = None
self._section = {}
self._dynamic = {}
self._got = {}
self._plt = {}
self._symbol = {}
self._load_blobs = []
self._string = {}
regexp = {
'section': r'^\s*\[(?P<Nr>[^\]]+)\]\s+(?P<Name>\S+)\s+(?P<Type>\S+)\s+(?P<Address>\S+)\s+(?P<Off>\S+)\s+(?P<Size>\S+)\s+(?P<ES>\S+)\s+(?P<Flg>\S+)\s+(?P<Lk>\S+)\s+(?P<Inf>\S+)\s+(?P<Al>\S+)$',
'program': r'^\s*(?P<Type>\S+)\s+(?P<Offset>\S+)\s+(?P<VirtAddr>\S+)\s+(?P<PhysAddr>\S+)\s+(?P<FileSiz>\S+)\s+(?P<MemSiz>\S+)\s+(?P<Flg>.{3})\s+(?P<Align>\S+)$',
'dynamic': r'^\s*(?P<Tag>\S+)\s+\((?P<Type>[^)]+)\)\s+(?P<Value>.+)$',
'reloc': r'^\s*(?P<Offset>\S+)\s+(?P<Info>\S+)\s+(?P<Type>\S+)\s+(?P<Value>\S+)\s+(?P<Name>\S+)(?: \+ (?P<AddEnd>\S+))?$',
'symbol': r'^\s*(?P<Num>[^:]+):\s+(?P<Value>\S+)\s+(?P<Size>\S+)\s+(?P<Type>\S+)\s+(?P<Bind>\S+)\s+(?P<Vis>\S+)\s+(?P<Ndx>\S+)\s+(?P<Name>\S+)',
'string': r'([\s\x21-\x7e]{4,})\x00',
}
plt_size_map = {
'i386': (0x10, 0x10),
'x86-64': (0x10, 0x10),
'arm': (0x14, 0xc),
}
has_dynamic_section = True
has_symbol_table = True
p = Popen(['readelf', '-W', '-a', fpath], env=env_with({"LC_MESSAGES": "C"}), stdout=PIPE)
# read ELF Header
while True:
line = p.stdout.readline()
if line == 'Section Headers:\n':
break
m = re.search(r'^\s*(?P<key>[^:]+):\s+(?P<value>.+)$', line)
if not m:
continue
key, value = m.group('key', 'value')
if key == 'Class':
if value == 'ELF64':
self.wordsize = 8
elif value == 'ELF32':
self.wordsize = 4
else:
raise Exception("unsupported ELF Class: %r" % value)
elif key == 'Type':
if value == 'DYN (Shared object file)':
self.sec['pie'] = True
elif value == 'EXEC (Executable file)':
self.sec['pie'] = False
else:
raise Exception("unsupported ELF Type: %r" % value)
elif key == 'Machine':
if value == 'Advanced Micro Devices X86-64':
self.arch = 'x86-64'
elif value == 'Intel 80386':
self.arch = 'i386'
elif value == 'ARM':
self.arch = 'arm'
else:
raise Exception("unsupported ELF Machine: %r" % value)
elif key == 'Entry point address':
self._entry_point = int16(value)
# read Section Headers
while True:
line = p.stdout.readline()
if line == 'Program Headers:\n':
break
m = re.search(regexp['section'], line)
if not m or m.group('Nr') == 'Nr':
continue
name = m.group('Name')
address, size = int16(m.group('Address', 'Size'))
self._section[name] = (address, size)
# read Program Headers
while True:
line = p.stdout.readline()
if line.startswith('Dynamic section'):
has_dynamic_section = True
break
elif line == 'There is no dynamic section in this file.\n':
has_dynamic_section = False
break
m = re.search(regexp['program'], line)
if not m or m.group('Type') == 'Type':
continue
type_, flg = m.group('Type', 'Flg')
offset, virtaddr, filesiz = int16(m.group('Offset', 'VirtAddr', 'FileSiz'))
if type_ == 'GNU_RELRO':
self.sec['relro'] = True
elif type_ == 'GNU_STACK':
if not 'E' in flg:
self.sec['nx'] = True
elif type_ == 'LOAD':
with open(fpath, 'rb') as f:
f.seek(offset)
blob = f.read(filesiz)
is_executable = ('E' in flg)
self._load_blobs.append((virtaddr, blob, is_executable))
for m in re.finditer(regexp['string'], blob):
self._string[virtaddr+m.start()] = m.group(1)
# read Dynamic section
while has_dynamic_section:
line = p.stdout.readline()
if line.startswith('Relocation section'):
break
m = re.search(regexp['dynamic'], line)
if not m or m.group('Tag') == 'Tag':
continue
type_, value = m.group('Type', 'Value')
if type_ == 'BIND_NOW':
self.sec['bind_now'] = True
elif type_ == 'RPATH':
self.sec['rpath'] = True
elif type_ == 'RUNPATH':
self.sec['runpath'] = True
elif type_ == 'DEBUG':
self.sec['dt_debug'] = True
if value.startswith('0x'):
self._dynamic[type_] = int16(value)
elif value.endswith(' (bytes)'):
self._dynamic[type_] = int(value.split()[0])
# read Relocation section (.rel.plt/.rela.plt)
in_unwind_table_index = False
plt_header_size, plt_entry_size = plt_size_map[self.arch]
while True:
line = p.stdout.readline()
if line.startswith('Symbol table'):
has_symbol_table = True
break
elif line == 'No version information found in this file.\n':
has_symbol_table = False
break
elif in_unwind_table_index or line.startswith('Unwind table index'):
in_unwind_table_index = True
continue
m = re.search(regexp['reloc'], line)
if not m or m.group('Offset') == 'Offset':
continue
type_, name = m.group('Type', 'Name')
offset, info = int16(m.group('Offset', 'Info'))
if not type_.endswith('JUMP_SLOT'):
continue
name = name.split('@')[0]
self._got[name] = offset
self._plt[name] = self._section['.plt'][0] + plt_header_size + plt_entry_size * len(self._plt)
if name == '__stack_chk_fail':
self.sec['stack_canary'] = True
# read Symbol table
while has_symbol_table:
line = p.stdout.readline()
if line.startswith('Version symbols section') or line == 'No version information found in this file.\n':
break
m = re.search(regexp['symbol'], line)
if not m or m.group('Num') == 'Num':
continue
if m.group('Ndx') == 'UND':
continue
name, value = m.group('Name'), int16(m.group('Value'))
self._symbol[name] = value
if '@@' in name:
default_name = name.split('@@')[0]
self._symbol[default_name] = value
p.wait()
def set_base(self, addr, ref_symbol=None):
self.base = addr
if ref_symbol:
self.base -= self._symbol[ref_symbol]
def offset(self, offset):
return self.base + offset
def section(self, name):
return self.offset(self._section[name][0])
def dynamic(self, name):
return self.offset(self._dynamic[name])
def got(self, name=None):
if name:
return self.offset(self._got[name])
else:
return self.dynamic('PLTGOT')
def plt(self, name=None):
if name:
return self.offset(self._plt[name])
else:
return self.offset(self._section['.plt'][0])
def addr(self, name):
return self.offset(self._symbol[name])
def str(self, name):
return self.search(name + '\x00')
def search(self, s, xonly=False):
if isinstance(s, int):
s = self.p(s)
for virtaddr, blob, is_executable in self._load_blobs:
if xonly and not is_executable:
continue
if isinstance(s, re._pattern_type):
for m in re.finditer(s, blob):
addr = self.offset(virtaddr + m.start())
if self.arch == 'arm' and xonly and addr % 2 != 0:
continue
return addr
else:
i = -1
while True:
i = blob.find(s, i+1)
if i == -1:
break
addr = self.offset(virtaddr + i)
if self.arch == 'arm' and xonly and addr % 2 != 0:
continue
return addr
else:
raise ValueError()
def checksec(self):
result = ''
if self.sec['relro']:
result += '\033[32mFull RELRO \033[m ' if self.sec['bind_now'] else '\033[33mPartial RELRO\033[m '
else:
result += '\033[31mNo RELRO \033[m '
result += '\033[32mCanary found \033[m ' if self.sec['stack_canary'] else '\033[31mNo canary found\033[m '
result += '\033[32mNX enabled \033[m ' if self.sec['nx'] else '\033[31mNX disabled\033[m '
result += '\033[32mPIE enabled \033[m ' if self.sec['pie'] else '\033[31mNo PIE \033[m '
result += '\033[31mRPATH \033[m ' if self.sec['rpath'] else '\033[32mNo RPATH \033[m '
result += '\033[31mRUNPATH \033[m ' if self.sec['runpath'] else '\033[32mNo RUNPATH \033[m '
result += self.fpath
print 'RELRO STACK CANARY NX PIE RPATH RUNPATH FILE'
print "%s\n" % result
fortified_funcs = [name for name in self._plt if re.search(r'^__\w+_chk$', name)]
if fortified_funcs:
print "FORTIFY_SOURCE: \033[32mFortified\033[m (%s)" % ', '.join(fortified_funcs)
else:
print 'FORTIFY_SOURCE: \033[31mNo\033[m'
def objdump(self):
p = Popen(Asm.cmd[self.arch]['objdump'] + [self.fpath], stdout=PIPE)
stdout, stderr = p.communicate()
rev_symbol = {}
rev_plt = {}
for k, v in self._symbol.iteritems():
rev_symbol.setdefault(v, []).append(k)
for k, v in self._plt.iteritems():
rev_plt.setdefault(v, []).append(k)
lines = []
labels = {}
code_xrefs = {}
data_xrefs = {}
# collect addresses
for line in stdout.splitlines():
ary = line.strip().split(':', 1)
try:
addr, expr = int16(ary[0]), ary[1]
labels[addr] = None
except ValueError:
addr, expr = None, None
lines.append((line, addr, expr))
# collect references
for line, addr, expr in lines:
if addr is None:
continue
if addr == self._entry_point:
labels[addr] = '_start'
m = re.search(r'call\s+(?:0x)?([\dA-Fa-f]+)\b', line)
if m:
ref = int16(m.group(1))
labels[ref] = "sub_%x" % ref
code_xrefs.setdefault(ref, set()).add(addr)
m = re.search(r'j\w{1,2}\s+(?:0x)?([\dA-Fa-f]+)\b', line)
if m:
ref = int16(m.group(1))
labels[ref] = "loc_%x" % ref
code_xrefs.setdefault(ref, set()).add(addr)
for m in re.finditer(r',0x([\dA-Fa-f]{3,})\b', expr):
ref = int16(m.group(1))
if ref in labels:
labels[ref] = "loc_%x" % ref
data_xrefs.setdefault(ref, set()).add(addr)
for k, v in code_xrefs.iteritems():
code_xrefs[k] = sorted(list(v))
for k, v in data_xrefs.iteritems():
data_xrefs[k] = sorted(list(v))
# output with annotations
def repl_func1(addr):
def _f(m):
op = m.group(1)
ref = int16(m.group(2))
if op.startswith('call'):
color = 33
else:
color = 32 if ref > addr else 35
return "\x1b[%dm%s%s [%+#x]\x1b[0m" % (color, m.group(1), labels[ref], ref-addr)
return _f
def repl_func2(color):
def _f(m):
addr = int16(m.group(1))
if addr in labels and not addr in rev_symbol:
return ",\x1b[%dm%s\x1b[0m" % (color, labels[addr])
else:
return m.group(0)
return _f
arrows = {}
for k, v in [(True, u'\u25b2'), (False, u'\u25bc')]:
arrows[k] = v.encode('utf-8')
for line, addr, expr in lines:
if addr is None:
print line
continue
line = re.sub(r'(call\s+)[\dA-Fa-f]{3,}\s+<([\w@\.]+)>', '\x1b[33m\\1\\2\x1b[0m', line)
line = re.sub(r'(call\s+)(?:0x)?([\dA-Fa-f]{3,})\b.*', repl_func1(addr), line)
line = re.sub(r'(j\w{1,2}\s+)[\dA-Fa-f]{3,}\s+<([\w@\.]+)>', '\x1b[32m\\1\\2\x1b[0m', line)
line = re.sub(r'(j\w{1,2}\s+)(?:0x)?([\dA-Fa-f]{3,})\b.*', repl_func1(addr), line)
line = re.sub(r',0x([\dA-Fa-f]{3,})\b', repl_func2(36), line)
expr = line.split(':', 1)[1]
label = ''
if labels[addr]:
if not addr in rev_symbol and not addr in rev_plt:
if labels[addr].startswith('loc_'):
label += "\x1b[38;1m%s:\x1b[0m" % labels[addr]
label = label.ljust(78+11)
else:
label += "\x1b[33m%s:\x1b[0m" % labels[addr]
label = label.ljust(78+9)
else:
label = label.ljust(78)
if addr in code_xrefs:
ary = ["%x%s" % (x, arrows[x < addr]) for x in code_xrefs[addr]]
label += " \x1b[30;1m; CODE XREF: %s\x1b[0m" % ', '.join(ary)
if addr in data_xrefs:
ary = ["%x%s" % (x, arrows[x < addr]) for x in data_xrefs[addr]]
label += " \x1b[30;1m; DATA XREF: %s\x1b[0m" % ', '.join(ary)
if addr == self._entry_point:
label += ' \x1b[30;1m; ENTRY POINT\x1b[0m'
if label:
print label
annotations = []
for m in re.finditer(r'([\dA-Fa-f]{3,})\b', expr):
ref = int16(m.group(1))
if 0 <= ref - self._section['.data'][0] < self._section['.data'][1]:
annotations.append('[.data]')
elif 0 <= ref - self._section['.bss'][0] < self._section['.bss'][1]:
annotations.append('[.bss]')
if ref in rev_symbol:
annotations.append(', '.join(rev_symbol[ref]))
if ref in self._string:
annotations.append(repr(self._string[ref]))
if annotations:
print "%-70s \x1b[30;1m; %s\x1b[0m" % (line, ' '.join(annotations))
else:
print line
if re.search(r'\t(?:ret|jmp)', line):
print "\x1b[30;1m; %s\x1b[0m" % ('-' * 78)
class ROP(ELF):
def __init__(self, *args, **kwargs):
ELF.__init__(self, *args, **kwargs)
if self.arch == 'i386':
self.__class__ = type('ROP_I386', (ROP_I386,), {})
elif self.arch == 'x86-64':
self.__class__ = type('ROP_X86_64', (ROP_X86_64,), {})
elif self.arch == 'arm':
self.__class__ = type('ROP_ARM', (ROP_ARM,), {})
else:
raise Exception("unknown architecture: %r" % self.arch)
def p(self, x):
if self.wordsize == 8:
return p64(x)
else:
return p32(x)
def gadget(self, s):
return self.search(s, xonly=True)
def string(self, s):
return s + '\x00'
def junk(self, n=1):
return self.fill(self.wordsize * n)
def fill(self, size, buf=''):
chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
buflen = size - len(buf)
assert buflen >= 0, "%d bytes over" % (-buflen,)
return ''.join(random.choice(chars) for i in xrange(buflen))
def align(self, addr, origin, size):
padlen = size - ((addr-origin) % size)
return (addr+padlen, padlen)
def load(self, blob, base=0):
self._load_blobs += [(base, blob, True)]
def scan_gadgets(self, regexp):
for virtaddr, blob, is_executable in self._load_blobs:
if not is_executable:
continue
for m in re.finditer(regexp, blob):
if self.arch == 'arm':
arch = 'thumb'
else:
arch = self.arch
p = Popen(Asm.cmd[arch]['objdump_binary'] + ["--adjust-vma=%d" % virtaddr, "--start-address=%d" % (virtaddr+m.start()), self.fpath], stdout=PIPE)
stdout, stderr = p.communicate()
lines = stdout.splitlines()[7:]
if '\t(bad)' in lines[0]:
continue
for line in lines:
print line
if re.search(r'\t(?:ret|jmp|\(bad\)|; <UNDEFINED> instruction|\.\.\.)', line):
print '-' * 80
break
def list_gadgets(self):
raise NotImplementedError("not implemented for this architecture: %r" % self.arch)
class ROP_I386(ROP):
regs = ['eax', 'ecx', 'edx', 'ebx', 'esp', 'ebp', 'esi', 'edi']
def gadget(self, keyword, reg=None, n=1):
def regexp_or(*args):
return re.compile('(?:' + '|'.join(map(re.escape, args)) + ')')
table = {
'pushad': '\x60\xc3',
'popad': '\x61\xc3',
'leave': '\xc9\xc3',
'ret': '\xc3',
'int3': '\xcc',
'int80': '\xcd\x80',
'call_gs10': '\x65\xff\x15\x10\x00\x00\x00',
'syscall': '\x0f\x05',
}
if keyword in table:
return self.search(table[keyword], xonly=True)
if reg:
try:
r = self.regs.index(reg)
except ValueError:
raise Exception("unexpected register: %r" % reg)
else:
r = self.regs.index('esp')
if keyword == 'pop':
if reg:
chunk1 = chr(0x58+r) + '\xc3'
chunk2 = '\x8f' + chr(0xc0+r) + '\xc3'
return self.search(regexp_or(chunk1, chunk2), xonly=True)
else:
# skip esp
return self.search(re.compile(r"(?:[\x58-\x5b\x5d-\x5f]|\x8f[\xc0-\xc3\xc5-\xc7]){%d}\xc3" % n), xonly=True)
elif keyword == 'call':
chunk = '\xff' + chr(0xd0+r)
return self.search(chunk, xonly=True)
elif keyword == 'jmp':
chunk = '\xff' + chr(0xe0+r)
return self.search(chunk, xonly=True)
elif keyword == 'jmp_ptr':
chunk = '\xff' + chr(0x20+r)
return self.search(chunk, xonly=True)
elif keyword == 'push':
chunk1 = chr(0x50+r) + '\xc3'
chunk2 = '\xff' + chr(0xf0+r) + '\xc3'
return self.search(regexp_or(chunk1, chunk2), xonly=True)
elif keyword == 'pivot':
# chunk1: xchg REG, esp
# chunk2: xchg esp, REG
if r == 0:
chunk1 = '\x94\xc3'
else:
chunk1 = '\x87' + chr(0xe0+r) + '\xc3'
chunk2 = '\x87' + chr(0xc4+8*r) + '\xc3'
return self.search(regexp_or(chunk1, chunk2), xonly=True)
elif keyword == 'loop':
chunk1 = '\xeb\xfe'
chunk2 = '\xe9\xfb\xff\xff\xff'
return self.search(regexp_or(chunk1, chunk2), xonly=True)
else:
# search directly
return ROP.gadget(self, keyword)
def call(self, addr, *args):
if isinstance(addr, str):
addr = self.plt(addr)
buf = self.p(addr)
buf += self.p(self.gadget('pop', n=len(args)))
buf += self.p(args)
return buf
def call_chain_ptr(self, *calls, **kwargs):
raise Exception('support x86-64 only')
def dl_resolve_data(self, base, name):
jmprel = self.dynamic('JMPREL')
relent = self.dynamic('RELENT')
symtab = self.dynamic('SYMTAB')
syment = self.dynamic('SYMENT')
strtab = self.dynamic('STRTAB')
addr_reloc, padlen_reloc = self.align(base, jmprel, relent)
addr_sym, padlen_sym = self.align(addr_reloc+relent, symtab, syment)
addr_symstr = addr_sym + syment
r_info = (((addr_sym - symtab) / syment) << 8) | 0x7
st_name = addr_symstr - strtab
buf = self.fill(padlen_reloc)
buf += struct.pack('<II', base, r_info) # Elf32_Rel
buf += self.fill(padlen_sym)
buf += struct.pack('<IIII', st_name, 0, 0, 0x12) # Elf32_Sym
buf += self.string(name)
return buf
def dl_resolve_call(self, base, *args):
jmprel = self.dynamic('JMPREL')
relent = self.dynamic('RELENT')
addr_reloc, padlen_reloc = self.align(base, jmprel, relent)
reloc_offset = addr_reloc - jmprel
buf = self.p(self.plt())
buf += self.p(reloc_offset)
buf += self.p(self.gadget('pop', n=len(args)))
buf += self.p(args)
return buf
def syscall(self, number, *args):
try:
arg_regs = ['ebx', 'ecx', 'edx', 'esi', 'edi', 'ebp']
buf = self.p([self.gadget('pop', 'eax'), number])
for arg_reg, arg in zip(arg_regs, args):
buf += self.p([self.gadget('pop', arg_reg), arg])
except ValueError:
# popad = pop edi, esi, ebp, esp, ebx, edx, ecx, eax
args = list(args) + [0] * (6-len(args))
buf = self.p([self.gadget('popad'), args[4], args[3], args[5], 0, args[0], args[2], args[1], number])
buf += self.p(self.gadget('int80'))
return buf
def pivot(self, rsp):
buf = self.p([self.gadget('pop', 'ebp'), rsp-self.wordsize])
buf += self.p(self.gadget('leave'))
return buf
def retfill(self, size, buf=''):
buflen = size - len(buf)
assert buflen >= 0, "%d bytes over" % (-buflen,)
s = self.fill(buflen % self.wordsize)
s += self.p(self.gadget('ret')) * (buflen // self.wordsize)
return s
def list_gadgets(self):
print "%8s" % 'pop',
for i in range(6):
try:
self.gadget('pop', n=i+1)
print "\033[32m%d\033[m" % (i+1),
except ValueError:
print "\033[31m%d\033[m" % (i+1),
print
for keyword in ['pop', 'jmp', 'jmp_ptr', 'call', 'push', 'pivot']:
print "%8s" % keyword,
for reg in self.regs:
try:
self.gadget(keyword, reg)
print "\033[32m%s\033[m" % reg,
except ValueError:
print "\033[31m%s\033[m" % reg,
print
print "%8s" % 'etc',
for keyword in ['pushad', 'popad', 'leave', 'ret', 'int3', 'int80', 'call_gs10', 'syscall', 'loop']:
try:
self.gadget(keyword)
print "\033[32m%s\033[m" % keyword,
except ValueError:
print "\033[31m%s\033[m" % keyword,
print
class ROP_X86_64(ROP):
regs = ['rax', 'rcx', 'rdx', 'rbx', 'rsp', 'rbp', 'rsi', 'rdi', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15']
def gadget(self, keyword, reg=None, n=1):
def regexp_or(*args):
return re.compile('(?:' + '|'.join(map(re.escape, args)) + ')')
table = {
'leave': '\xc9\xc3',
'ret': '\xc3',
'int3': '\xcc',
'int80': '\xcd\x80',
'call_gs10': '\x65\xff\x15\x10\x00\x00\x00',
'syscall': '\x0f\x05',
}
if keyword in table:
return self.search(table[keyword], xonly=True)
if reg:
try:
r = self.regs.index(reg)
need_prefix = bool(r >= 8)
if need_prefix:
r -= 8
except ValueError:
raise Exception("unexpected register: %r" % reg)
else:
r = self.regs.index('rsp')
need_prefix = False
if keyword == 'pop':
if reg:
prefix = '\x41' if need_prefix else ''
chunk1 = prefix + chr(0x58+r) + '\xc3'
chunk2 = prefix + '\x8f' + chr(0xc0+r) + '\xc3'
return self.search(regexp_or(chunk1, chunk2), xonly=True)
else:
# skip rsp
return self.search(re.compile(r"(?:[\x58-\x5b\x5d-\x5f]|\x8f[\xc0-\xc3\xc5-\xc7]|\x41(?:[\x58-\x5f]|\x8f[\xc0-\xc7])){%d}\xc3" % n), xonly=True)
elif keyword == 'call':
prefix = '\x41' if need_prefix else ''
chunk = prefix + '\xff' + chr(0xd0+r)
return self.search(chunk, xonly=True)
elif keyword == 'jmp':
prefix = '\x41' if need_prefix else ''
chunk = prefix + '\xff' + chr(0xe0+r)
return self.search(chunk, xonly=True)
elif keyword == 'jmp_ptr':
prefix = '\x41' if need_prefix else ''
chunk = prefix + '\xff' + chr(0x20+r)
return self.search(chunk, xonly=True)
elif keyword == 'push':
prefix = '\x41' if need_prefix else ''
chunk1 = prefix + chr(0x50+r) + '\xc3'
chunk2 = prefix + '\xff' + chr(0xf0+r) + '\xc3'
return self.search(regexp_or(chunk1, chunk2), xonly=True)
elif keyword == 'pivot':
# chunk1: xchg REG, rsp
# chunk2: xchg rsp, REG
if need_prefix:
chunk1 = '\x49\x87' + chr(0xe0+r) + '\xc3'
chunk2 = '\x4c\x87' + chr(0xc4+8*r) + '\xc3'
else:
if r == 0:
chunk1 = '\x48\x94\xc3'
else:
chunk1 = '\x48\x87' + chr(0xe0+r) + '\xc3'
chunk2 = '\x48\x87' + chr(0xc4+8*r) + '\xc3'
return self.search(regexp_or(chunk1, chunk2), xonly=True)
elif keyword == 'loop':
chunk1 = '\xeb\xfe'
chunk2 = '\xe9\xfb\xff\xff\xff'
return self.search(regexp_or(chunk1, chunk2), xonly=True)
else:
# search directly
return ROP.gadget(self, keyword)
def call(self, addr, *args):
if isinstance(addr, str):
addr = self.plt(addr)
regs = ['rdi', 'rsi', 'rdx', 'rcx', 'r8', 'r9']
buf = ''
for i, arg in enumerate(args):
buf += self.p([self.gadget('pop', regs[i]), arg])
buf += self.p(addr)
buf += self.p(args[6:])
return buf
def call_chain_ptr(self, *calls, **kwargs):
gadget_candidates = [
# gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
# Ubuntu clang version 3.0-6ubuntu3 (tags/RELEASE_30/final) (based on LLVM 3.0)
('\x4c\x89\xfa\x4c\x89\xf6\x44\x89\xef\x41\xff\x14\xdc\x48\x83\xc3\x01\x48\x39\xeb\x75\xea', '\x48\x8b\x5c\x24\x08\x48\x8b\x6c\x24\x10\x4c\x8b\x64\x24\x18\x4c\x8b\x6c\x24\x20\x4c\x8b\x74\x24\x28\x4c\x8b\x7c\x24\x30\x48\x83\xc4\x38\xc3', False),
# gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-4)
('\x4c\x89\xfa\x4c\x89\xf6\x44\x89\xef\x41\xff\x14\xdc\x48\x83\xc3\x01\x48\x39\xeb\x72\xea', '\x48\x8b\x5c\x24\x08\x48\x8b\x6c\x24\x10\x4c\x8b\x64\x24\x18\x4c\x8b\x6c\x24\x20\x4c\x8b\x74\x24\x28\x4c\x8b\x7c\x24\x30\x48\x83\xc4\x38\xc3', False),
# gcc 4.8.2-19ubuntu1
('\x4c\x89\xea\x4c\x89\xf6\x44\x89\xff\x41\xff\x14\xdc\x48\x83\xc3\x01\x48\x39\xeb\x75\xea', '\x48\x8b\x5c\x24\x08\x48\x8b\x6c\x24\x10\x4c\x8b\x64\x24\x18\x4c\x8b\x6c\x24\x20\x4c\x8b\x74\x24\x28\x4c\x8b\x7c\x24\x30\x48\x83\xc4\x38\xc3', True),
# gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2
('\x4c\x89\xea\x4c\x89\xf6\x44\x89\xff\x41\xff\x14\xdc\x48\x83\xc3\x01\x48\x39\xeb\x75\xea', '\x48\x83\xc4\x08\x5b\x5d\x41\x5c\x41\x5d\x41\x5e\x41\x5f\xc3', True),
]
for chunk1, chunk2, _args_reversed in gadget_candidates:
try:
set_regs = self.gadget(chunk2)
call_ptr = self.gadget(chunk1 + chunk2)
args_reversed = _args_reversed
break
except ValueError:
pass
else:
raise Exception('gadget not found')
buf = self.p(set_regs)
for args in calls:
if len(args) > 4:
raise Exception('4th argument and latter should be set in advance')
elif args[1] >= (1<<32):
raise Exception("1st argument should be less than 2^32: %x" % args[1])
ptr = args.pop(0)
if isinstance(ptr, str):
ptr = self.got(ptr)
buf += self.junk()
buf += self.p([0, 1, ptr])
if not args_reversed:
for arg in args:
buf += self.p(arg)
buf += self.p(0) * (3-len(args))
else:
buf += self.p(0) * (3-len(args))
for arg in reversed(args):
buf += self.p(arg)
buf += self.p(call_ptr)
buf += self.junk()
if 'pivot' in kwargs:
buf += self.p(0)
buf += self.p(kwargs['pivot'] - self.wordsize)
buf += self.p(0) * 4
buf += self.p(self.gadget('leave'))
else:
buf += self.p(0) * 6
return buf
def dl_resolve_data(self, base, name):
jmprel = self.dynamic('JMPREL')
relaent = self.dynamic('RELAENT')
symtab = self.dynamic('SYMTAB')
syment = self.dynamic('SYMENT')
strtab = self.dynamic('STRTAB')
addr_reloc, padlen_reloc = self.align(base, jmprel, relaent)
addr_sym, padlen_sym = self.align(addr_reloc+relaent, symtab, syment)
addr_symstr = addr_sym + syment
r_info = (((addr_sym - symtab) / syment) << 32) | 0x7
st_name = addr_symstr - strtab
buf = self.fill(padlen_reloc)
buf += struct.pack('<QQQ', base, r_info, 0) # Elf64_Rela
buf += self.fill(padlen_sym)
buf += struct.pack('<IIQQ', st_name, 0x12, 0, 0) # Elf64_Sym
buf += self.string(name)
return buf
def dl_resolve_call(self, base, *args):
# prerequisite:
# 1) overwrite (link_map + 0x1c8) with NULL
# 2) set registers for arguments
if args:
raise Exception('arguments must be set to the registers beforehand')
jmprel = self.dynamic('JMPREL')
relaent = self.dynamic('RELAENT')
addr_reloc, padlen_reloc = self.align(base, jmprel, relaent)
reloc_offset = (addr_reloc - jmprel) / relaent
buf = self.p(self.plt())
buf += self.p(reloc_offset)
return buf
def syscall(self, number, *args):
arg_regs = ['rdi', 'rsi', 'rdx', 'r10', 'r8', 'r9']
buf = self.p([self.gadget('pop', 'rax'), number])
for arg_reg, arg in zip(arg_regs, args):
buf += self.p([self.gadget('pop', arg_reg), arg])
buf += self.p(self.gadget('syscall'))
return buf
def pivot(self, rsp):
buf = self.p([self.gadget('pop', 'rbp'), rsp-self.wordsize])
buf += self.p(self.gadget('leave'))
return buf
def retfill(self, size, buf=''):
buflen = size - len(buf)
assert buflen >= 0, "%d bytes over" % (-buflen,)
s = self.fill(buflen % self.wordsize)
s += self.p(self.gadget('ret')) * (buflen // self.wordsize)
return s
def list_gadgets(self):
print "%8s" % 'pop',
for i in range(6):
try:
self.gadget('pop', n=i+1)
print "\033[32m%d\033[m" % (i+1),
except ValueError:
print "\033[31m%d\033[m" % (i+1),
print
for keyword in ['pop', 'jmp', 'jmp_ptr', 'call', 'push', 'pivot']:
print "%8s" % keyword,
for reg in self.regs:
try:
self.gadget(keyword, reg)
print "\033[32m%s\033[m" % reg,
except ValueError:
print "\033[31m%s\033[m" % reg,
print
print "%8s" % 'etc',
for keyword in ['leave', 'ret', 'int3', 'int80', 'call_gs10', 'syscall', 'loop']:
try:
self.gadget(keyword)
print "\033[32m%s\033[m" % keyword,
except ValueError:
print "\033[31m%s\033[m" % keyword,
print
class ROP_ARM(ROP):
def pt(self, x):
if isinstance(x, str):
return (self(x) | 1)
else:
return self.p(x | 1)
def gadget(self, keyword, reg=None, n=1):
table = {
'pivot_r7': '\xbd\x46\x80\xbd', # mov sp, r7; pop {r7, pc}
'pivot_fp': '\x0b\xd0\xa0\xe1\x00\x88\xbd\xe8', # mov sp, fp; pop {fp, pc}
'pop_r0_3fp': '\xbd\xe8\x0f\x88', # ldmia.w sp!, {r0, r1, r2, r3, fp, pc}
'pop_r4_7': '\xf0\xbd', # pop {r4, r5, r6, r7, pc}
'svc0': '\x00\xdf', # svc 0
}
if keyword in table:
return self.search(table[keyword], xonly=True)
# search directly
return ROP.gadget(self, keyword)
def call_chain(self, *calls, **kwargs):
gadget_candidates = [
# gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
('\x30\x46\x39\x46\x42\x46\x01\x34\x98\x47\x4c\x45\xf6\xd1', '\xbd\xe8\xf8\x83', True),
# gcc (Ubuntu/Linaro 4.8.2-19ubuntu1) 4.8.2
('\x38\x46\x41\x46\x4a\x46\x98\x47\xb4\x42\xf6\xd1', '\xbd\xe8\xf8\x83', False),
]
for chunk1, chunk2, _is_4_6 in gadget_candidates:
try:
set_regs = self.gadget(chunk2)
call_reg = self.gadget(chunk1 + chunk2)
is_4_6 = _is_4_6
break
except ValueError:
pass
else:
raise Exception('gadget not found')
buf = self.pt(set_regs)
for args in calls:
if len(args) > 4:
raise Exception('4th argument and latter should be set in advance')
addr = args.pop(0)
if isinstance(addr, str):
addr = self.plt(addr)
if is_4_6:
buf += self.p(addr)
buf += self.p([0, 0])
for arg in args:
buf += self.p(arg)
buf += self.p(0) * (3-len(args))
buf += self.p(1)
buf += self.pt(call_reg)
else:
buf += self.p(addr)
buf += self.p([0, 0, 0])
for arg in args:
buf += self.p(arg)
buf += self.p(0) * (3-len(args))
buf += self.pt(call_reg)
if 'pivot' in kwargs:
try:
pivot_r7 = self.gadget('pivot_r7')
buf += self.p(0) * 4
buf += self.p(kwargs['pivot'] - self.wordsize)
buf += self.p(0) * 2
buf += self.pt(pivot_r7)
except ValueError:
buf += self.p(0) * 7
buf += self.pivot(kwargs['pivot'])
else:
buf += self.p(0) * 7
return buf
def syscall(self, number, *args):
args0_3, args4_6 = args[:4], args[4:7]
buf = self.pt(self.gadget('pop_r0_3fp'))
for arg in args0_3:
buf += self.p(arg)
buf += self.p(0) * (4-len(args0_3))
buf += self.p(0)
buf += self.pt(self.gadget('pop_r4_7'))
for arg in args4_6: