-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangelheap.py
1450 lines (1336 loc) · 58.4 KB
/
angelheap.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
from __future__ import print_function
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# import gdb
import subprocess
import re
import copy
import struct
import os
# main_arena
main_arena = 0
main_arena_off = 0
# thread
thread_arena = 0
enable_thread = False
tcache_enable = False
tcache = None
tcache_max_bin = 0
tcache_counts_size = 1
# chunks
top = {}
fastbinsize = 13
fastbin = []
fastchunk = [] #save fastchunk address for chunkinfo check
tcache_entry = []
tcache_count = []
all_tcache_entry = [] #save tcache address for chunkinfo check
last_remainder = {}
unsortbin = []
smallbin = {} #{size:bin}
largebin = {}
system_mem = 0x21000
# chunk recording
freememoryarea = {} #using in parse
allocmemoryarea = {}
freerecord = {} # using in trace
# setting for tracing memory allocation
tracelargebin = True
inmemalign = False
inrealloc = False
print_overlap = True
DEBUG = True #debug msg (free and malloc) if you want
# breakpoints for tracing
mallocbp = None
freebp = None
memalignbp = None
reallocbp = None
# architecture setting
capsize = 0
word = ""
arch = ""
#condition
corruptbin = False
# fake gdb library
class GDB():
def __init__(self):
self.msg = "to overwrite gdb library"
def execute(self, cmd, to_string):
print(cmd) # just echo cmd
return "0x0"
gdb = GDB()
def u32(data,fmt="<I"):
return struct.unpack(fmt,data)[0]
def u64(data,fmt="<Q"):
return struct.unpack(fmt,data)[0]
def init_angelheap():
global allocmemoryarea
global freerecord
dis_trace_malloc()
allocmemoryarea = {}
freerecord = {}
# class Malloc_bp_ret(gdb.FinishBreakpoint):
# global allocmemoryarea
# global freerecord
# def __init__(self,arg):
# gdb.FinishBreakpoint.__init__(self,gdb.newest_frame(),internal=True)
# self.silent = True
# self.arg = arg
# def stop(self):
# chunk = {}
# if len(arch) == 0 :
# getarch()
# if arch == "x86-64" :
# value = int(self.return_value)
# chunk["addr"] = value - capsize*2
# else :
# cmd = "info register $eax"
# value = int(gdb.execute(cmd,to_string=True).split()[1].strip(),16)
# chunk["addr"] = value - capsize*2
# if value == 0 :
# return False
# cmd = "x/" + word + hex(chunk["addr"] + capsize)
# chunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
# overlap,status = check_overlap(chunk["addr"],chunk["size"],allocmemoryarea)
# if overlap and status == "error" :
# if DEBUG :
# print("\033[34m>--------------------------------------------------------------------------------------<\033[37m")
# msg = "\033[33mmalloc(0x%x)\033[37m" % self.arg
# print("%-40s = 0x%x \033[31m overlap detected !! (0x%x)\033[37m" % (msg,chunk["addr"]+capsize*2,overlap["addr"]))
# print("\033[34m>--------------------------------------------------------------------------------------<\033[37m")
# else :
# print("\033[31moverlap detected !! (0x%x)\033[37m" % overlap["addr"])
# del allocmemoryarea[hex(overlap["addr"])]
# else :
# if DEBUG:
# msg = "\033[33mmalloc(0x%x)\033[37m" % self.arg
# print("%-40s = 0x%x" % (msg,chunk["addr"] + capsize*2))
# allocmemoryarea[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"],chunk["addr"]+chunk["size"],chunk))
# if hex(chunk["addr"]) in freerecord :
# freechunktuple = freerecord[hex(chunk["addr"])]
# freechunk = freechunktuple[2]
# splitchunk = {}
# del freerecord[hex(chunk["addr"])]
# if chunk["size"] != freechunk["size"] :
# splitchunk["addr"] = chunk["addr"] + chunk["size"]
# splitchunk["size"] = freechunk["size"] - chunk["size"]
# freerecord[hex(splitchunk["addr"])] = copy.deepcopy((splitchunk["addr"],splitchunk["addr"]+splitchunk["size"],splitchunk))
# if self.arg >= 128*capsize :
# Malloc_consolidate()
# class Malloc_Bp_handler(gdb.Breakpoint):
# def stop(self):
# if len(arch) == 0 :
# getarch()
# if arch == "x86-64":
# reg = "$rsi"
# arg = int(gdb.execute("info register " + reg,to_string=True).split()[1].strip(),16)
# else :
# # for _int_malloc in x86's glibc (unbuntu 14.04 & 16.04), size is stored in edx
# reg = "$edx"
# arg = int(gdb.execute("info register " + reg,to_string=True).split()[1].strip(),16)
# Malloc_bp_ret(arg)
# return False
# class Free_bp_ret(gdb.FinishBreakpoint):
# def __init__(self):
# gdb.FinishBreakpoint.__init__(self,gdb.newest_frame(),internal=True)
# self.silent = True
# def stop(self):
# Malloc_consolidate()
# return False
# class Free_Bp_handler(gdb.Breakpoint):
# def stop(self):
# global allocmemoryarea
# global freerecord
# global inmemalign
# global inrealloc
# get_top_lastremainder()
# if len(arch) == 0 :
# getarch()
# if arch == "x86-64":
# reg = "$rsi"
# result = int(gdb.execute("info register " + reg,to_string=True).split()[1].strip(),16) + 0x10
# else :
# # for _int_free in x86's glibc (unbuntu 14.04 & 16.04), chunk address is stored in edx
# reg = "$edx"
# result = int(gdb.execute("info register " + reg,to_string=True).split()[1].strip(),16) + 0x8
# chunk = {}
# if inmemalign or inrealloc:
# Update_alloca()
# inmemalign = False
# inrealloc = False
# prevfreed = False
# chunk["addr"] = result - capsize*2
# cmd = "x/" +word + hex(chunk["addr"] + capsize)
# size = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
# chunk["size"] = size & 0xfffffffffffffff8
# if (size & 1) == 0 :
# prevfreed = True
# # overlap,status = check_overlap(chunk["addr"],chunk["size"],freememoryarea)
# overlap,status = check_overlap(chunk["addr"],chunk["size"],freerecord)
# if overlap and status == "error" :
# if DEBUG :
# msg = "\033[32mfree(0x%x)\033[37m (size = 0x%x)" % (result,chunk["size"])
# print("\033[34m>--------------------------------------------------------------------------------------<\033[37m")
# print("%-25s \033[31m double free detected !! (0x%x(size:0x%x))\033[37m" % (msg,overlap["addr"],overlap["size"]))
# print("\033[34m>--------------------------------------------------------------------------------------<\033[37m",end="")
# else :
# print("\033[31mdouble free detected !! (0x%x)\033[37m" % overlap["addr"])
# del freerecord[hex(overlap["addr"])]
# else :
# if DEBUG :
# msg = "\033[32mfree(0x%x)\033[37m" % result
# print("%-40s (size = 0x%x)" % (msg,chunk["size"]),end="")
# if chunk["size"] <= 0x80 :
# freerecord[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"],chunk["addr"]+chunk["size"],chunk))
# if DEBUG :
# print("")
# if hex(chunk["addr"]) in allocmemoryarea :
# del allocmemoryarea[hex(chunk["addr"])]
# return False
# prevchunk = {}
# if prevfreed :
# cmd = "x/" +word + hex(chunk["addr"])
# prevchunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
# prevchunk["addr"] = chunk["addr"] - prevchunk["size"]
# if hex(prevchunk["addr"]) not in freerecord :
# print("\033[31m confuse in prevchunk 0x%x" % prevchunk["addr"])
# else :
# prevchunk["size"] += chunk["size"]
# del freerecord[hex(prevchunk["addr"])]
# nextchunk = {}
# nextchunk["addr"] = chunk["addr"] + chunk["size"]
# if nextchunk["addr"] == top["addr"] :
# if hex(chunk["addr"]) in allocmemoryarea :
# del allocmemoryarea[hex(chunk["addr"])]
# Free_bp_ret()
# if DEBUG :
# print("")
# return False
# cmd = "x/" + word + hex(nextchunk["addr"] + capsize)
# nextchunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
# cmd = "x/" + word + hex(nextchunk["addr"] + nextchunk["size"] + capsize)
# nextinused = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 1
# if nextinused == 0 and prevfreed: #next chunk is freed
# if hex(nextchunk["addr"]) not in freerecord :
# print("\033[31m confuse in nextchunk 0x%x" % nextchunk["addr"])
# else :
# prevchunk["size"] += nextchunk["size"]
# del freerecord[hex(nextchunk["addr"])]
# if nextinused == 0 and not prevfreed:
# if hex(nextchunk["addr"]) not in freerecord :
# print("\033[31m confuse in nextchunk 0x%x" % nextchunk["addr"])
# else :
# chunk["size"] += nextchunk["size"]
# del freerecord[hex(nextchunk["addr"])]
# if prevfreed :
# if hex(chunk["addr"]) in allocmemoryarea :
# del allocmemoryarea[hex(chunk["addr"])]
# chunk = prevchunk
# if DEBUG :
# print("")
# freerecord[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"],chunk["addr"]+chunk["size"],chunk))
# if hex(chunk["addr"]) in allocmemoryarea :
# del allocmemoryarea[hex(chunk["addr"])]
# if chunk["size"] > 65536 :
# Malloc_consolidate()
# return False
# class Memalign_Bp_handler(gdb.Breakpoint):
# def stop(self):
# global inmemalign
# inmemalign = True
# return False
# class Realloc_Bp_handler(gdb.Breakpoint):
# def stop(self):
# global inrealloc
# inrealloc = True
# return False
def Update_alloca():
global allocmemoryarea
if capsize == 0:
getarch()
for addr,(start,end,chunk) in allocmemoryarea.items():
cmd = "x/" + word + hex(chunk["addr"] + capsize*1)
cursize = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
if cursize != chunk["size"]:
chunk["size"] = cursize
allocmemoryarea[hex(chunk["addr"])]= copy.deepcopy((start,start + cursize,chunk))
def Malloc_consolidate(): #merge fastbin when malloc a large chunk or free a very large chunk
global fastbin
global freerecord
if capsize == 0 :
getarch()
freerecord = {}
if not get_heap_info():
print("Can't find heap info")
return
freerecord = copy.deepcopy(freememoryarea)
def getarch():
global capsize
global word
global arch
data = gdb.execute('show arch',to_string = True)
tmp = re.search("currently.*",data)
if tmp :
info = tmp.group()
if "x86-64" in info:
capsize = 8
word = "gx "
arch = "x86-64"
return "x86-64"
elif "aarch64" in info :
capsize = 8
word = "gx "
arch = "aarch64"
return "aarch64"
elif "arm" in info :
capsize = 4
word = "wx "
arch = "arm"
return "arm"
else :
word = "wx "
capsize = 4
arch = "i386"
return "i386"
else :
return "error"
def infoprocmap():
""" Use gdb command 'info proc map' to get the memory mapping """
""" Notice: No permission info """
resp = gdb.execute("info proc map", to_string=True).split("\n")
resp = '\n'.join(resp[i] for i in range(4, len(resp))).strip().split("\n")
infomap = ""
for l in resp:
line = ""
first = True
for sep in l.split(" "):
if len(sep) != 0:
if first: # start address
line += sep + "-"
first = False
else:
line += sep + " "
line = line.strip() + "\n"
infomap += line
return infomap
def procmap():
data = gdb.execute('info proc exe',to_string = True)
pid = re.search('process.*',data)
if pid :
pid = pid.group()
pid = pid.split()[1]
fpath = "/proc/" + pid + "/maps"
if os.path.isfile(fpath): # if file exist, read memory mapping directly from file
maps = open(fpath)
infomap = maps.read()
maps.close()
return infomap
else: # if file doesn't exist, use 'info proc map' to get the memory mapping
return infoprocmap()
else :
return "error"
def libcbase():
infomap = procmap()
data = re.search(".*libc.*\.so",infomap)
if data :
libcaddr = data.group().split("-")[0]
return int(libcaddr,16)
else :
return 0
def getoff(sym):
libc = libcbase()
if type(sym) is int :
return sym-libc
else :
try :
data = gdb.execute("x/x " + sym ,to_string=True)
if "No symbol" in data:
return 0
else :
data = re.search("0x.*[0-9a-f] ",data)
data = data.group()
symaddr = int(data[:-1] ,16)
return symaddr-libc
except :
return 0
def set_thread_arena():
global thread_arena
global main_arena
global enable_thread
if capsize == 0 :
arch = getarch()
try :
data = gdb.execute("x/" + word +"&thread_arena",to_string=True)
except :
return
enable_thread = True
if "main_arena" in data :
thread_arena = main_arena
return
thread_arena = int(data.split(":")[1].strip(),16)
def set_main_arena():
global main_arena
global main_arena_off
offset = getoff("&main_arena")
if offset == 0: # no main_arena symbol
print("Cannot get main_arena's symbol address. Make sure you install libc debug file (libc6-dbg & libc6-dbg:i386 for debian package).")
return
libc = libcbase()
arch = getarch()
main_arena_off = offset
main_arena = libc + main_arena_off
def check_overlap(addr,size,data = None):
if data :
for key,(start,end,chunk) in data.items() :
if (addr >= start and addr < end) or ((addr+size) > start and (addr+size) < end ) or ((addr < start) and ((addr + size) >= end)):
return chunk,"error"
else :
for key,(start,end,chunk) in freememoryarea.items() :
if (addr >= start and addr < end) or ((addr+size) > start and (addr+size) < end ) or ((addr < start) and ((addr + size) >= end)):
return chunk,"freed"
for key,(start,end,chunk) in allocmemoryarea.items() :
if (addr >= start and addr < end) or ((addr+size) > start and (addr+size) < end ) or ((addr < start) and ((addr + size) >= end)) :
return chunk,"inused"
return None,None
def get_top_lastremainder(arena=None):
global fastbinsize
global top
global last_remainder
if not arena :
arena = main_arena
chunk = {}
if capsize == 0 :
arch = getarch()
#get top
cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").top"
chunk["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
chunk["size"] = 0
if chunk["addr"] :
cmd = "x/" + word + hex(chunk["addr"]+capsize*1)
try :
chunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
if chunk["size"] > system_mem :
chunk["memerror"] = "top is broken ?"
except :
chunk["memerror"] = "invaild memory"
top = copy.deepcopy(chunk)
#get last_remainder
chunk = {}
cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").last_remainder"
chunk["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
chunk["size"] = 0
if chunk["addr"] :
cmd = "x/" + word + hex(chunk["addr"]+capsize*1)
try :
chunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
except :
chunk["memerror"] = "invaild memory"
last_remainder = copy.deepcopy(chunk)
def get_fast_bin(arena=None):
global fastbin
global fastchunk
global fastbinsize
global freememoryarea
if not arena :
arena = main_arena
fastbin = []
fastchunk = []
#freememoryarea = []
if capsize == 0 :
arch = getarch()
cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").fastbinsY"
fastbinsY = int(gdb.execute(cmd,to_string=True).split(":")[0].split()[0].strip(),16)
for i in range(fastbinsize-3):
fastbin.append([])
chunk = {}
is_overlap = (None,None)
cmd = "x/" + word + hex(fastbinsY + i*capsize)
chunk["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
while chunk["addr"] and not is_overlap[0]:
cmd = "x/" + word + hex(chunk["addr"]+capsize*1)
try :
chunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
except :
chunk["memerror"] = "invaild memory"
break
is_overlap = check_overlap(chunk["addr"], (capsize*2)*(i+2))
chunk["overlap"] = is_overlap
freememoryarea[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"],chunk["addr"] + (capsize*2)*(i+2) ,chunk))
fastbin[i].append(copy.deepcopy(chunk))
fastchunk.append(chunk["addr"])
cmd = "x/" + word + hex(chunk["addr"]+capsize*2)
chunk = {}
chunk["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
if not is_overlap[0]:
chunk["size"] = 0
chunk["overlap"] = None
fastbin[i].append(copy.deepcopy(chunk))
def get_curthread():
cmd = "thread"
thread_id = int(gdb.execute(cmd,to_string=True).split("thread is")[1].split()[0].strip())
return thread_id
def get_all_threads():
cmd = "info threads"
all_threads = [int(line.split()[0].strip()) for line in gdb.execute(cmd, to_string=True).replace("*", "").split("\n")[1:-1]]
return all_threads
def thread_cmd_execute(thread_id,thread_cmd):
cmd = "thread apply %d %s" % (thread_id,thread_cmd)
result = gdb.execute(cmd,to_string=True)
return result
def get_tcache():
global tcache
global tcache_enable
global tcache_max_bin
global tcache_counts_size
if capsize == 0 :
arch = getarch()
try :
tcache_max_bin = int(gdb.execute("x/" + word + " &mp_.tcache_bins",to_string=True).split(":")[1].strip(),16)
try :
tcache_enable = True
tcache = int(gdb.execute("x/" + word + "&tcache",to_string=True).split(":")[1].strip(),16)
tps_size = int(gdb.execute("p sizeof(*tcache)",to_string=True).split("=")[1].strip())
if tps_size > 0x240:
tcache_counts_size = 2
except :
heapbase = get_heapbase()
if heapbase != 0 :
cmd = "x/" + word + hex(heapbase + capsize*1)
f_size = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
while(f_size == 0):
heapbase += capsize*2
cmd = "x/" + word + hex(heapbase + capsize*1)
f_size = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
tcache = heapbase + capsize*2
if (f_size & ~7) - 0x10 > 0x240:
tcache_counts_size = 2
else :
tcache = 0
except :
tcache_enable = False
tcache = 0
def get_tcache_count() :
global tcache_count
tcache_count = []
if not tcache_enable :
return
if capsize == 0 :
arch = getarch()
count_size = int(tcache_max_bin * tcache_counts_size / capsize)
for i in range(count_size):
cmd = "x/" + word + hex(tcache + i*capsize)
c = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
for j in range(int(capsize / tcache_counts_size)):
tcache_count.append((c >> j * 8*tcache_counts_size) & 0xff)
def get_tcache_entry():
global tcache_entry
get_tcache()
if not tcache_enable :
return
tcache_entry = []
get_tcache_count()
if capsize == 0 :
arch = getarch()
if tcache and tcache_max_bin :
entry_start = tcache + tcache_max_bin * tcache_counts_size
for i in range(tcache_max_bin):
tcache_entry.append([])
chunk = {}
is_overlap = (None,None)
cmd = "x/" + word + hex(entry_start + i*capsize)
entry = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
while entry and not is_overlap[0] :
chunk["addr"] = entry - capsize*2
cmd = "x/" + word + hex(chunk["addr"] + capsize)
try :
chunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
except :
chunk["memerror"] = "invaild memory"
tcache_entry[i].append(copy.deepcopy(chunk))
break
is_overlap = check_overlap(chunk["addr"],capsize*2*(i+2))
chunk["overlap"] = is_overlap
freememoryarea[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"],chunk["addr"] + (capsize*2)*(i+2) ,chunk))
tcache_entry[i].append(copy.deepcopy(chunk))
all_tcache_entry.append(chunk["addr"])
cmd = "x/" + word + hex(chunk["addr"]+capsize*2)
chunk = {}
entry = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
def trace_normal_bin(chunkhead,arena=None):
global freememoryarea
if not arena :
arena = main_arena
libc = libcbase()
bins = []
if capsize == 0 :
arch = getarch()
if chunkhead["addr"] == 0 : # main_arena not initial
return None
chunk = {}
cmd = "x/" + word + hex(chunkhead["addr"] + capsize*2) #fd
chunk["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) #get fd chunk
if (chunk["addr"] == chunkhead["addr"]) : #no chunk in the bin
if (chunkhead["addr"] > arena) :
return bins
else :
try :
cmd = "x/" + word + hex(chunk["addr"]+capsize*1)
chunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
is_overlap = check_overlap(chunk["addr"],chunk["size"])
chunk["overlap"] = is_overlap
chunk["memerror"] = "\033[31mbad fd (" + hex(chunk["addr"]) + ")\033[37m"
except :
chunk["memerror"] = "invaild memory"
bins.append(copy.deepcopy(chunk))
return bins
else :
try :
cmd = "x/" + word + hex(chunkhead["addr"]+capsize*3)
bk = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
cmd = "x/" + word + hex(bk+capsize*2)
bk_fd = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
if bk_fd != chunkhead["addr"]:
chunkhead["memerror"] = "\033[31mdoubly linked list corruption {0} != {1} and \033[36m{2}\033[31m is broken".format(hex(chunkhead["addr"]),hex(bk_fd),hex(chunkhead["addr"]))
bins.append(copy.deepcopy(chunkhead))
return bins
fd = chunkhead["addr"]
chunkhead = {}
chunkhead["addr"] = bk #bins addr
chunk["addr"] = fd #first chunk
except :
chunkhead["memerror"] = "invaild memory"
bins.append(copy.deepcopy(chunkhead))
return bins
while chunk["addr"] != chunkhead["addr"] :
try :
cmd = "x/" + word + hex(chunk["addr"])
chunk["prev_size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
cmd = "x/" + word + hex(chunk["addr"]+capsize*1)
chunk["size"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
except :
chunk["memerror"] = "invaild memory"
break
try :
cmd = "x/" + word + hex(chunk["addr"]+capsize*2)
fd = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
if fd == chunk["addr"] :
chunk["memerror"] = "\033[31mbad fd (" + hex(fd) + ")\033[37m"
bins.append(copy.deepcopy(chunk))
break
cmd = "x/" + word + hex(fd + capsize*3)
fd_bk = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
if chunk["addr"] != fd_bk :
chunk["memerror"] = "\033[31mdoubly linked list corruption {0} != {1} and \033[36m{2}\033[31m or \033[36m{3}\033[31m is broken".format(hex(chunk["addr"]),hex(fd_bk),hex(fd),hex(chunk["addr"]))
bins.append(copy.deepcopy(chunk))
break
except :
chunk["memerror"] = "invaild memory"
bins.append(copy.deepcopy(chunk))
break
is_overlap = check_overlap(chunk["addr"],chunk["size"])
chunk["overlap"] = is_overlap
freememoryarea[hex(chunk["addr"])] = copy.deepcopy((chunk["addr"],chunk["addr"] + chunk["size"] ,chunk))
bins.append(copy.deepcopy(chunk))
cmd = "x/" + word + hex(chunk["addr"]+capsize*2) #find next
chunk = {}
chunk["addr"] = fd
return bins
def get_unsortbin(arena=None):
global unsortbin
if not arena :
arena = main_arena
unsortbin = []
if capsize == 0 :
arch = getarch()
chunkhead = {}
cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").bins"
chunkhead["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
unsortbin = trace_normal_bin(chunkhead,arena)
def get_smallbin(arena=None):
global smallbin
if not arena :
arena = main_arena
smallbin = {}
if capsize == 0 :
arch = getarch()
max_smallbin_size = 512*int(capsize/4)
cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").bins"
bins_addr = int(gdb.execute(cmd,to_string=True).split(":")[0].split()[0].strip(),16)
for size in range(capsize*4,max_smallbin_size,capsize*2):
chunkhead = {}
idx = int((size/(capsize*2)))-1
cmd = "x/" + word + hex(bins_addr + idx*capsize*2) # calc the smallbin index
chunkhead["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
try :
bins = trace_normal_bin(chunkhead,arena)
except:
corruptbin = True
bins = None
if bins and len(bins) > 0 :
smallbin[hex(size)] = copy.deepcopy(bins)
def largbin_index(size):
if capsize == 0 :
arch = getarch()
if capsize == 8 :
if (size >> 6) <= 48 :
idx = 48 + (size >> 6)
elif (size >> 9) <= 20 :
idx = 91 + (size >> 9)
elif (size >> 12) <= 10:
idx = 110 + (size >> 12)
elif (size >> 15) <= 4 :
idx = 119 + (size >> 15)
elif (size >> 18) <= 2:
idx = 124 + (size >> 18)
else :
idx = 126
else :
if (size >> 6) <= 38 :
idx = 56 + (size >> 6)
elif (size >> 9) <= 20 :
idx = 91 + (size >> 9)
elif (size >> 12) <= 10:
idx = 110 + (size >> 12)
elif (size >> 15) <= 4 :
idx = 119 + (size >> 15)
elif (size >> 18) <= 2:
idx = 124 + (size >> 18)
else :
idx = 126
return idx
def get_largebin(arena=None):
global largebin
global corruptbin
if not arena :
arena = main_arena
largebin = {}
if capsize == 0 :
arch = getarch()
min_largebin = 512*int(capsize/4)
cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").bins"
bins_addr = int(gdb.execute(cmd,to_string=True).split(":")[0].split()[0].strip(),16)
for idx in range(64,128):
chunkhead = {}
cmd = "x/" + word + hex(bins_addr + idx*capsize*2 - 2*capsize) # calc the largbin index
chunkhead["addr"] = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
try :
bins = trace_normal_bin(chunkhead,arena)
except :
corruptbin = True
bins = None
if bins and len(bins) > 0 :
largebin[idx] = copy.deepcopy(bins)
def get_system_mem(arena=None):
global system_mem
if not arena :
arena = main_arena
if capsize == 0 :
arch = getarch()
cmd = "x/" + word + "&((struct malloc_state *)" + hex(arena) + ").system_mem"
system_mem = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
def get_heap_info(arena=None):
global main_arena
global thread_arena
global freememoryarea
global top
global tcache_enable
global tcache
top = {}
freememoryarea = {}
corruptbin = False
if arena :
get_system_mem(arena)
get_unsortbin(arena)
get_smallbin(arena)
if tracelargebin :
get_largebin(arena)
get_fast_bin(arena)
get_top_lastremainder(arena)
get_tcache_entry()
return True
set_main_arena()
set_thread_arena()
if thread_arena and enable_thread :
get_system_mem(thread_arena)
get_unsortbin(thread_arena)
get_smallbin(thread_arena)
if tracelargebin :
get_largebin(thread_arena)
get_fast_bin(thread_arena)
get_top_lastremainder(thread_arena)
get_tcache_entry()
return True
elif main_arena and not enable_thread:
get_system_mem()
get_unsortbin()
get_smallbin()
if tracelargebin :
get_largebin()
get_fast_bin()
get_top_lastremainder()
get_tcache_entry()
return True
return False
def get_reg(reg):
cmd = "info register " + reg
result = int(gdb.execute(cmd,to_string=True).split()[1].strip(),16)
return result
def trace_malloc():
global mallocbp
global freebp
global memalignbp
global reallocbp
mallocbp = Malloc_Bp_handler("*" + "_int_malloc")
freebp = Free_Bp_handler("*" + "_int_free")
memalignbp = Memalign_Bp_handler("*" + "_int_memalign")
reallocbp = Realloc_Bp_handler("*" + "_int_realloc")
if not get_heap_info() :
print("Can't find heap info")
return
def dis_trace_malloc():
global mallocbp
global freebp
global memalignbp
global reallocbp
if mallocbp :
mallocbp.delete()
mallocbp = None
if freebp :
freebp.delete()
freebp = None
if memalignbp :
memalignbp.delete()
memalignbp = None
if reallocbp :
reallocbp.delete()
reallocbp = None
def find_overlap(chunk,bins):
is_overlap = False
count = 0
for current in bins :
if chunk["addr"] == current["addr"] :
count += 1
if count > 1 :
is_overlap = True
return is_overlap
def unlinkable(chunkaddr,fd = None ,bk = None):
if capsize == 0 :
arch = getarch()
try :
cmd = "x/" + word + hex(chunkaddr + capsize)
chunk_size = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16) & 0xfffffffffffffff8
cmd = "x/" + word + hex(chunkaddr + chunk_size)
next_prev_size = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
if not fd :
cmd = "x/" + word + hex(chunkaddr + capsize*2)
fd = int(gdb.execute(cmd,to_string=true).split(":")[1].strip(),16)
if not bk :
cmd = "x/" + word + hex(chunkaddr + capsize*3)
bk = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
cmd = "x/" + word + hex(fd + capsize*3)
fd_bk = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
cmd = "x/" + word + hex(bk + capsize*2)
bk_fd = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
if chunk_size != next_prev_size :
print("\033[32mUnlinkable :\033[1;31m False (corrupted size chunksize(0x%x) != prev_size(0x%x)) ) \033[37m " % (chunk_size,next_prev_size))
elif (chunkaddr == fd_bk ) and (chunkaddr == bk_fd) :
print("\033[32mUnlinkable :\033[1;33m True\033[37m")
print("\033[32mResult of unlink :\033[37m")
print("\033[32m \033[1;34m FD->bk (\033[1;33m*0x%x\033[1;34m) = BK (\033[1;37m0x%x ->\033[1;33m 0x%x\033[1;34m)\033[37m " % (fd+capsize*3,fd_bk,bk))
print("\033[32m \033[1;34m BK->fd (\033[1;33m*0x%x\033[1;34m) = FD (\033[1;37m0x%x ->\033[1;33m 0x%x\033[1;34m)\033[37m " % (bk+capsize*2,bk_fd,fd))
else :
if chunkaddr != fd_bk :
print("\033[32mUnlinkable :\033[1;31m False (FD->bk(0x%x) != (0x%x)) \033[37m " % (fd_bk,chunkaddr))
else :
print("\033[32mUnlinkable :\033[1;31m False (BK->fd(0x%x) != (0x%x)) \033[37m " % (bk_fd,chunkaddr))
except :
print("\033[32mUnlinkable :\033[1;31m False (FD or BK is corruption) \033[37m ")
def freeable(victim):
global fastchunk
global system_mem
if capsize == 0 :
arch = getarch()
chunkaddr = victim
try :
if not get_heap_info() :
print("Can't find heap info")
return
cmd = "x/" + word + hex(chunkaddr)
prev_size = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
cmd = "x/" + word + hex(chunkaddr + capsize*1)
size = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
cmd = "x/" + word + hex(chunkaddr + capsize*2)
fd = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
cmd = "x/" + word + hex(chunkaddr + capsize*3)
bk = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
prev_inuse = size & 1
is_mmapd = (size >> 1) & 1
non_main_arena = (size >> 2) & 1
size = size & 0xfffffffffffffff8
if is_mmapd :
block = chunkaddr - prev_size
total_size = prev_size + size
if ((block | total_size) & (0xfff)) != 0 :
print("\033[32mFreeable :\033[1;31m False -> Invalid pointer (((chunkaddr(0x%x) - prev_size(0x%x))|(prev_size(0x%x) + size(0x%x)))) & 0xfff != 0 \033[37m" % (chunkaddr,prev_size,prev_size,size))
return
else :
if chunkaddr > (2**(capsize*8) - (size & 0xfffffffffffffff8)):
print("\033[32mFreeable :\033[1;31m False -> Invalid pointer chunkaddr (0x%x) > -size (0x%x)\033[37m" % (chunkaddr,(2**(capsize*8) - (size & 0xfffffffffffffff8))))
return
if (chunkaddr & (capsize*2 - 1)) != 0 :
print("\033[32mFreeable :\033[1;31m False -> Invalid pointer misaligned chunkaddr (0x%x) & (0x%x) != 0\033[37m" % (chunkaddr,(capsize*2 - 1)))
return
if (size < capsize*4) :
print("\033[32mFreeable :\033[1;31m False -> Chunkaddr (0x%x) invalid size (size(0x%x) < 0x%x )\033[37m" % (chunkaddr,size,capsize*4))
return
if (size & (capsize)) !=0 :
print("\033[32mFreeable :\033[1;31m False -> Chunkaddr (0x%x) invalid size (size(0x%x) & 0x%x != 0 )\033[37m" % (chunkaddr,size,capsize))
return
cmd = "x/" + word + hex(chunkaddr + size + capsize)
nextsize = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
nextchunk = chunkaddr + size
status = nextsize & 1
if size <= capsize*0x10 : #fastbin
if nextsize < capsize*4 :
print("\033[32mFreeable :\033[1;31m False -> Chunkaddr (0x%x) invalid next size (size(0x%x) < 0x%x )\033[37m" % (chunkaddr,size,capsize*4))
return
if nextsize >= system_mem :
print("\033[32mFreeable :\033[1;31m False -> Chunkaddr (0x%x) invalid next size (size(0x%x) > system_mem(0x%x) )\033[37m" % (chunkaddr,size,system_mem))
return
old = fastbin[int(size/0x10)-2][0]["addr"]
if chunkaddr == old :
print("\033[32mFreeable :\033[1;31m false -> Double free chunkaddr(0x%x) == 0x%x )\033[37m" % (chunkaddr,old))
return
else :
if chunkaddr == top["addr"]:
print("\033[32mFreeable :\033[1;31m False -> Free top chunkaddr(0x%x) == 0x%x )\033[37m" % (chunkaddr,top["addr"]))
return
cmd = "x/" + word + hex(top["addr"] + capsize)
topsize = int(gdb.execute(cmd,to_string=True).split(":")[1].strip(),16)
if nextchunk >= top["addr"] + topsize :
print("\033[32mFreeable :\033[1;31m False -> Out of top chunkaddr(0x%x) > 0x%x )\033[37m" % (chunkaddr,top["addr"] + topsize))
return
if status == 0 :
print("\033[32mFreeable :\033[1;31m false -> Double free chunkaddr(0x%x) inused bit is not seted )\033[37m" % (chunkaddr))
return
if nextsize < capsize*4 :
print("\033[32mFreeable :\033[1;31m False -> Chunkaddr (0x%x) invalid next size (size(0x%x) < 0x%x )\033[37m" % (chunkaddr,size,capsize*4))