forked from stevenseeley/heaper
-
Notifications
You must be signed in to change notification settings - Fork 3
/
heaper.py
executable file
·3538 lines (3177 loc) · 208 KB
/
heaper.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
'''
__
/ / ___ ___ ____ ___ ____
/ _ \/ -_) _ `/ _ \/ -_) __/
/_//_/\__/\_,_/ .__/\__/_/
/_/ v0.01
Copyright (C) 2011 Steven Seeley
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Created on: Oct 4, 2011
author: mr_me <[email protected]>
Note: you will need pydot, pyparser and graphviz for the graphing functionality
'''
__VERSION__ = '0.01'
__IMM__ = '1.8'
DESC="""heaper - an advanced heap analysis plugin."""
import immlib
from immlib import LogBpHook
import immutils
import libdatatype
try:
import pydot
except:
pydot = False
import struct
import re
from hashlib import sha1
import urllib2
import inspect
from immlib import AccessViolationHook
# GLOBAL VARIABLES
# ================
# all available functions
# ========================
available_commands = ["dumppeb", "dp", "dumpheaps", "dh", "analyseheap", "ah", "dumpteb", "dt",
"analysefrontend", "af", "analysebackend", "ab", "analysechunks", "ac",
"dumpfunctionpointers", "dfp", "help", "-h", "analysesegments", "as", "-f",
"-m", "-p", "freelistinuse", "fliu", "hook", "analyseheapcache", "ahc", "h",
"exploit","exp","u","update", "patch", "p"]
# graphiz engine needs this under windows 7
paths = {"dot":"C:\\Program Files\\Graphviz 2.28\\bin\\dot.exe",
"twopi":"C:\\Program Files\\Graphviz 2.28\\bin\\twopi.exe",
"neato":"C:\\Program Files\\Graphviz 2.28\\bin\\neato.exe",
"circo":"C:\\Program Files\\Graphviz 2.28\\bin\\circo.exe",
"fdp":"C:\\Program Files\\Graphviz 2.28\\bin\\fdp.exe"}
# 8 byte block
# ============
block = 8
# window management
# =================
opennewwindow = False
# graphic flag
# ============
graphic_structure = False
# heap restore
restore = False
# hook tags
# =========
tag = "display_box"
ALLOCLABEL = "RtlAllocateHeap Hook"
FREELABEL = "RtlFreeHeap Hook"
CREATELABEL = "RtlCreateHeap Hook"
DESTROYLABEL = "RtlDestroyHeap Hook"
REALLOCLABEL = "RtlReAllocateHeap Hook"
SIZELABEL = "RtlSizeHeap Hook"
CREATECSLABEL = "RtlInitializeCriticalSection Hook"
DELETECSLABEL = "RtlDeleteCriticalSection Hook"
SETUEFLABEL = "SetUnhandledExceptionFilter Hook"
VIRALLOCLABEL = "VirtualAlloc Hook"
VIRFREELABEL = "VirtualFree Hook"
# hook flags
# ==========
FilterHeap = False
Disable = False
AllocFlag = False
FreeFlag = False
CreateFlag = False
DestroyFlag = False
ReAllocFlag = False
sizeFlag = False
CreateCSFlag = False
DeleteCSFlag = False
setuefFlag = False
setVAllocFlag = False
setVFreeFlag = False
# valid functions too hook
# ========================
valid_functions = ["alloc", "free", "create", "destroy", "realloc", "size", "createcs", "deletecs",
"all", "setuef", "va", "vf"]
# return heap for hooking
# =======================
rheap = False
# for hooking function pointers
# =============================
INDEXER = 0xb4000000
INDEX_MASK = 0xFF000000
FNDX_MASK = 0x00FFFFFF
# The OS version
# ==============
OS = None
##################################################################################
# Utility functions
def to_hex(n):
"""
Converts a numeric value to hex (pointer to hex)
Arguments:
n - the value to convert
Return:
A string, representing the value in hex (8 characters long)
"""
return "%08x" % n
def bin_to_dec(binary):
"""Converts a binary list to decimal number"""
dec = 0
binary_list = []
for b in binary:
binary_list.append(int(b))
#reverse list:
rev_bin = []
for item in binary_list:
rev_bin.insert(0,item)
#calculate decimal
for index in xrange(len(binary_list)):
dec += rev_bin[index] * 2**index
return dec
def to_hex_byte(n):
"""
Converts a numeric value to a hex byte
Arguments:
n - the value to convert (max 255)
Return:
A string, representing the value in hex (1 byte)
"""
return "%02x" % n
def chr_to_dword(n):
"""
Converts a character variable to hex value
Arguments:
n - the value to convert
Return:
A string, representing the value in hex (8 characters long)
"""
if len(n) == 4:
myvalue = []
for x in n:
myvalue.append(hex(ord(x))[2:])
else:
return "(-) Value too big!"
return "0x%s" % ("".join(myvalue))
def chr_to_pretty_hex(n):
"""
Converts a character variable to hex value
Arguments:
n - the value to convert
Return:
A string, representing the value in hex (8 characters long)
"""
myvalue = []
for x in n:
tempval = hex(ord(x)).replace("0x", "\\x")
if len(tempval) <= 3:
if tempval[2:3] != "0":
tempval = "\\x" + tempval[2:3] + "0"
else:
tempval += "0"
myvalue.append(tempval)
return "".join(myvalue)
def chr_to_hex(n):
"""
Converts a character variable to hex value
Arguments:
n - the value to convert
Return:
A string, representing the value in hex (8 characters long)
"""
myvalue = []
for x in n:
tempval = hex(ord(x))[2:]
if len(tempval) <= 1:
if tempval != "0":
tempval = "0" + tempval
elif tempval == "0":
tempval += "0"
myvalue.append(tempval)
return "".join(myvalue)
# just incase we will need this
def reverse(text):
return ''.join([text[i] for i in range(len(text)-1,-1,-1)])
# patch the PEB
# thanks to BoB from Team PEiD
def patch_PEB(imm, window):
peb_struct = imm.getPEB()
if not peb_struct.BeingDebugged and not peb_struct.NtGlobalFlag:
window.Log("(!) This process has already been patched!")
window.Log("------------------------------------------")
return False
PEB = imm.getPEBAddress()
# Just incase .. ;)
if PEB == 0:
window.Log("(-) No PEB to patch .. !?" )
return
window.Log("(+) Patching PEB.IsDebugged ..", address = PEB + 0x02 )
imm.writeMemory(PEB + 0x02, imm.assemble( "db 0" ) )
a = imm.readLong(PEB + 0x18)
a += 0x10
window.Log("(+) Patching PEB.ProcessHeap.Flag ..", address = a )
imm.writeLong( a, 0 )
window.Log("(+) Patching PEB.NtGlobalFlag ..", address = PEB + 0x68 )
imm.writeLong(PEB + 0x68, 0)
# Patch PEB_LDR_DATA 0xFEEEFEEE fill bytes .. (about 3000 of them ..)
a = imm.readLong(PEB + 0x0C)
window.Log("(+) Patching PEB.LDR_DATA filling ..", address = a)
while a != 0:
a += 1
try:
b = imm.readLong(a)
c = imm.readLong(a + 4)
# Only patch the filling runs ..
if (b == 0xFEEEFEEE) and (c == 0xFEEEFEEE):
imm.writeLong(a, 0)
imm.writeLong(a + 4, 0)
a += 7
except:
break
window.Log("----------------------------------------")
return True
def githash(data):
s = sha1()
s.update("blob %u\0" % len(data))
s.update(data)
return s.hexdigest()
class set_command:
"""
Class to call commands, show usage and parse arguments
"""
def __init__(self, name, description, usage, parseProc, alias=""):
self.name = name
self.description = description
self.usage = usage
self.parseProc = parseProc
self.alias = alias
# RtlFreeHeap Hook class
class function_hook(LogBpHook):
"""
Class to get the particular functions arguments for a debug instance
Return
"""
def __init__(self, window, function_name, heap=False):
LogBpHook.__init__(self)
self.window = window
self.fname = function_name
self.heap = heap
self.rheap = None
def run(self,regs):
"""This will be executed when hooktype happens"""
imm = immlib.Debugger()
# get the return address of the hooked function
offset = 0x0
if self.fname == "VirtualAllocEx":
offset = 0x1c
elif self.fname == "VirtualFreeEx":
offset = 0x18
elif self.fname == "RtlDestroyHeap" or self.fname == "RtlInitializeCriticalSection":
offset = 0x0c
ret = imm.readMemory( regs['ESP']+offset, 0x4)
ret = struct.unpack("L", ret)
# find the module with the ret address
module_list = imm.getAllModules()
for mod in module_list.iterkeys():
find = False
# make sure we cycle through the IAT (import database)
for addy in range(module_list[mod].getCodebase(),module_list[mod].getIdatabase()):
if int(ret[0]) == addy:
find = True
break
if find:
break
if self.fname == "RtlFreeHeap":
res=imm.readMemory( regs['ESP'] + 4, 0xc)
if len(res) != 0xc:
self.window.Log("(-) RtlFreeHeap: the stack seems to broken, unable to get args")
return 0x0
(self.rheap, flags, size) = struct.unpack("LLL", res)
if self.heap:
if self.heap == self.rheap:
rheap = True
self.window.Log("(+) RtlFreeHeap(0x%08x, 0x%08x, 0x%08x)" % (self.rheap, flags, size))
else:
self.window.Log("(+) RtlFreeHeap(0x%08x, 0x%08x, 0x%08x)" % (self.rheap, flags, size))
elif self.fname == "RtlAllocateHeap":
res=imm.readMemory( regs['ESP'] + 4, 0xc)
if len(res) != 0xc:
self.window.Log("RtlAllocateHeap: ESP seems to broken, unable to get args")
return 0x0
(self.rheap, flags, size) = struct.unpack("LLL", res)
if self.heap:
if self.heap == self.rheap:
rheap = True
self.window.Log("(+) RtlAllocateHeap(0x%08x, 0x%08x, 0x%08x)" % (self.rheap, flags, size))
else:
self.window.Log("(+) RtlAllocateHeap(0x%08x, 0x%08x, 0x%08x)" % (self.rheap, flags, size))
elif self.fname == "RtlCreateHeap":
res=imm.readMemory( regs['ESP'] + 4, 0xc)
if len(res) != 0xc:
self.window.Log("(-) RtlCreateHeap: the stack seems to broken, unable to get args")
return 0x0
(flags, InitialSize, MaximumSize) = struct.unpack("LLL", res)
self.window.Log("(+) RtlCreateHeap(0x%08x, 0x%08x, 0x%08x)" % (flags, InitialSize, MaximumSize))
elif self.fname == "RtlDestroyHeap":
res=imm.readMemory( regs['ESP'] + 4, 0x4)
if len(res) != 0x4:
self.window.Log("(-) RtlDestroyHeap: the stack seems to broken, unable to get args")
return 0x0
(heap) = struct.unpack("L", res)
self.window.Log("(+) RtlDestroyHeap(0x%08x)" % (heap))
elif self.fname == "RtlReAllocateHeap":
res=imm.readMemory( regs['ESP'] + 4, 0x10)
if len(res) != 0x10:
self.window.Log("(-) RtlReAllocateHeap: the stack seems to broken, unable to get args")
return 0x0
(heap, dwFlags, lpMem, dwBytes) = struct.unpack("LLLL", res)
self.window.Log("(+) RtlReAllocateHeap(0x%08x, 0x%08x, 0x%08x, 0x%08x)" % (heap, dwFlags, lpMem, dwBytes))
elif self.fname == "RtlSizeHeap":
res=imm.readMemory( regs['ESP'] + 4, 0xc)
if len(res) != 0xc:
self.window.Log("(-) RtlSizeHeap: the stack seems to broken, unable to get args")
return 0x0
(heap, dwFlags, lpMem) = struct.unpack("LLL", res)
self.window.Log("(+) RtlSizeHeap(0x%08x, 0x%08x, 0x%08x)" % (heap, dwFlags, lpMem))
elif self.fname == "RtlInitializeCriticalSection" or self.fname == "RtlDeleteCriticalSection":
res=imm.readMemory( regs['ESP'] + 4, 0x4)
if len(res) != 0x4:
self.window.Log("(-) %s: the stack seems to broken, unable to get args" % self.fname)
return 0x0
(cs) = struct.unpack("L", res)
self.window.Log("(+) %s(0x%08x)" % (self.fname,cs[0]))
elif self.fname == "SetUnhandledExceptionFilter":
res=imm.readMemory( regs['ESP'] + 4, 0x4)
if len(res) != 0x4:
self.window.Log("(-) SetUnhandledExceptionFilter: the stack seems to broken, unable to get args")
return 0x0
(pTopLevelFilter) = struct.unpack("L", res)
self.window.Log("(+) SetUnhandledExceptionFilter(0x%08x)" % (pTopLevelFilter))
elif self.fname == "VirtualAllocEx":
res=imm.readMemory( regs['ESP'] + 0x8, 0x10)
if len(res) != 0x10:
self.window.Log("(-) VirtualAllocEx: the stack seems to broken, unable to get args")
return 0x0
(address, size, AllocationType, Protect) = struct.unpack("LLLL", res)
self.window.Log("(+) VirtualAllocEx(0x%08x, 0x%08x, 0x%08x, 0x%08x)" % (address, size, AllocationType, Protect))
elif self.fname == "VirtualFreeEx":
res=imm.readMemory( regs['ESP'] + 0x8, 0x0c)
if len(res) != 0x0c:
self.window.Log("(-) VirtualFreeEx: the stack seems to broken, unable to get args")
return 0x0
(lpAddress, dwSize, dwFreeType) = struct.unpack("LLL", res)
self.window.Log("(+) VirtualFreeEx(0x%08x, 0x%08x, 0x%08x)" % (lpAddress, dwSize, dwFreeType))
if find:
self.window.Log("(+) Called from 0x%08x - module: %s" % (ret[0],module_list[mod].getPath()),ret[0])
elif not find:
self.window.Log("(+) Called from 0x%08x - from an unknown module" % (ret[0]),ret[0])
def is_heap_alloc_free_matching(self):
return self.heap == self.rheap
class function_hook_return(LogBpHook):
def __init__(self, window, function_name, heap=False):
LogBpHook.__init__(self)
self.window = window
self.fname = function_name
self.heap = heap
def run(self,regs):
"""This will be executed when hooktype happens"""
return_value = regs['EAX']
self.window.Log("(+) %s() heapbase returned: 0x%08x" % (self.fname, return_value),return_value)
border_len = len("(+) %s() heapbase returned: 0x%08x" % (self.fname, return_value))
self.window.Log("=" * border_len)
class function_hook_seed(LogBpHook):
def __init__(self, window, function_name, heap=False):
LogBpHook.__init__(self)
self.window = window
self.fname = function_name
self.heap = heap
def run(self,regs):
"""This will be executed when hooktype happens"""
# our flag is set for each call
return_value = regs['EAX']
self.window.Log("(+) %s() returned random seed value: 0x%08x" % (self.fname, return_value),return_value)
self.window.Log("(!) To calculate the real heapbase, do: heapbase - random seed = x")
# Access Violation Hook class
# thanks to the immunity team
class FunctionTriggeredHook(AccessViolationHook):
def __init__( self, fn_ptr, window):
AccessViolationHook.__init__( self )
self.fn_ptr = fn_ptr
self.window = window
# found the access violation we force by patching every function pointer.
def run(self, regs):
imm = immlib.Debugger()
eip = regs['EIP']
# Checking if we are on the correct Access Violation
if ( eip & INDEX_MASK ) != INDEXER:
return ""
fndx = eip & FNDX_MASK
if fndx >= len( self.fn_ptr ) :
return ""
obj = self.fn_ptr[ fndx ] # it shouldn't be out of index
# Print info and Unhook
self.window.Log("Found a pointer at 0x%08x that triggers: " % obj.address, address = obj.address, focus =1 )
self.window.Log(" %s: %s" % ( obj.name, obj.Print() ), address = obj.address)
imm.setReg("EIP", int(obj.data) )
imm.run()
# HeapHook_vals, HeapHook_ret,
def hook_on(imm, LABEL, bp_address, function_name, bp_retaddress, Disable, window, heap=False, seed_address=False):
"""
This function creates the hooks and adds/deletes them to the Debugger object depending on
if they exist in immunities knowledge database
@type imm: Debugger Object
@param imm: initialized debugger object
@type LABEL: String
@param LABEL: Hook label, depending on the operation
@type bp_address: long
@param bp_address: The break point function entry address
@type function_name: String
@param function_name: The function name to hook
"""
if not heap:
heap = 0x00000000
hook_values = imm.getKnowledge( LABEL + "%x_values" % heap)
hook_ret_address = imm.getKnowledge( LABEL + "%x_ret" % heap)
#if OS >= 6.0:
if OS >= 6.0:
hook_seed = imm.getKnowledge( LABEL + "%x_seed" % heap)
if Disable:
if not hook_values:
window.Log("(-) Error %s, no hook to disable for the API" % (LABEL))
#return "No hook to disable on"
if not hook_ret_address:
window.Log("(-) Error %s, no hook to disable for the return address!" % (LABEL))
# if its debugged under windows xp, return from here
#if imm.getOsVersion() != "7":
if OS >= 6.0:
return "No hook to disable on"
#if OS >= 6.0 and not hook_seed:
if OS >= 6.0 and not hook_seed:
window.Log("(-) Error %s, no hook to disable for the random seed value!" % (LABEL))
return "No hook to disable on"
elif hook_values or hook_ret_address or hook_seed:
hook_values.UnHook()
hook_ret_address.UnHook()
window.Log("(+) Unhooked %s" % LABEL)
imm.forgetKnowledge( LABEL + "%x_values" % heap)
imm.forgetKnowledge( LABEL + "%x_ret" % heap)
if OS >= 6.0 and hook_seed:
imm.forgetKnowledge( LABEL + "%x_seed" % heap)
return "Unhooked"
# else we are not disabling...
elif not Disable:
if not hook_values:
if heap != 0:
hook_values= function_hook( window, function_name, heap)
else:
hook_values= function_hook( window, function_name)
hook_values.add( LABEL + "%x_values" % heap, bp_address)
window.Log("(+) Placed %s to retrieve the variables" % LABEL)
imm.addKnowledge( LABEL + "%x_values" % heap, hook_values)
elif hook_values:
if heap != 0:
window.Log("(!) %s for heap 0x%08x was ran previously, re-hooking" % (LABEL,heap))
hook_values= function_hook( window, function_name, heap)
else:
window.Log("(!) %s was ran previously, re-hooking" % (LABEL))
hook_values= function_hook( window, function_name)
hook_values.add( LABEL + "%x_values" % heap, bp_address)
if OS >= 6.0 and not hook_seed:
if heap != 0:
hook_seed = function_hook_seed( window, function_name, heap)
else:
hook_seed = function_hook_seed( window, function_name)
hook_seed.add( LABEL + "%x_seed" % heap, seed_address)
window.Log("(+) Placed %s to retrieve the seed value" % LABEL)
imm.addKnowledge( LABEL + "%x_seed" % heap, hook_seed)
elif OS >= 6.0 and hook_seed:
if heap != 0:
window.Log("(!) %s for the seed value on heap 0x%08x was ran previously, re-hooking" % (LABEL,heap))
hook_seed = function_hook_seed( window, function_name, heap)
else:
window.Log("(!) %s for the seed value was ran previously, re-hooking" % (LABEL))
hook_seed = function_hook_seed( window, function_name)
hook_seed.add( LABEL + "%x_seed" % heap, seed_address)
if not hook_ret_address:
if heap != 0:
hook_ret_address = function_hook_return( window, function_name, heap)
else:
hook_ret_address = function_hook_return( window, function_name)
hook_ret_address.add( LABEL + "%x_ret" % heap, bp_retaddress)
window.Log("(+) Placed %s to retrieve the return value" % LABEL)
imm.addKnowledge( LABEL + "%x_ret" % heap, hook_ret_address )
else:
if heap != 0:
window.Log("(!) %s for the return address on heap 0x%08x was ran previously, re-hooking" % (LABEL,heap))
hook_ret_address= function_hook_return( window, function_name, heap)
elif heap == 0:
window.Log("(!) %s for the return address was ran previously, re-hooking" % (LABEL))
hook_ret_address= function_hook_return( window, function_name)
hook_ret_address.add( LABEL + "%x_ret" % heap, bp_retaddress)
return "Hooked"
# banner
# ======
def banner(win):
win.Log("----------------------------------------")
win.Log(" __ ")
win.Log(" / / ___ ___ ____ ___ ____ ")
win.Log(" / _ \/ -_) _ `/ _ \/ -_) __/ ")
win.Log(" /_//_/\__/\_,_/ .__/\__/_/ ")
win.Log(" /_/ ")
win.Log("----------------------------------------")
win.Log("by mr_me :: [email protected]")
# usage
# =====
def usage(window, imm):
window.Log("")
window.Log("**** available commands ****")
window.Log("")
window.Log("dumppeb / dp : Dump the PEB pointers")
window.Log("dumpteb / dt : Dump the TEB pointers")
window.Log("dumpheaps / dh : Dump the heaps")
window.Log("dumpfunctionpointers / dfp : Dump all the processes function pointers")
window.Log("analyseheap <heap> / ah <heap> : Analyse a particular heap")
window.Log("analysefrontend <heap> / af <heap> : Analyse a particular heap's frontend data structure")
window.Log("analysebackend <heap> / ab <heap> : Analyse a particular heap's backend data structure")
window.Log("analysesegments <heap> / as <heap> : Analyse a particular heap's segments")
window.Log("analysechunks <heap> / ac <heap> : Analyse a particular heap's chunks")
window.Log("analyseheapcache <heap> / ahc <heap> : Analyse a particular heap's cache (FreeList[0])")
window.Log("freelistinuse <heap> / fliu <heap> : Analyse/patch the FreeListInUse structure")
window.Log("hook <heap> / h -h <func> : Hook various functions that create/destroy/manipulate a heap")
window.Log("patch <function/data structure> / p : Patch a function or datastructure")
window.Log("update / u : Update to the latest version")
window.Log("exploit <heap> / exp <heap> : Perform heuristics against the FrontEnd and BackEnd allocators")
window.Log(" to determine exploitable conditions")
window.Log("")
window.Log("Want more info about a given command? Run !heaper help <command>")
window.Log("Detected the operating system to be windows %s, keep this in mind." % (imm.getOsVersion()))
window.Log("")
return "eg: !heaper al 00480000"
# runtime detection of avaliable functions
def get_extended_usage():
extusage = {}
extusage["freelistinuse"] = "\nfreelistinuse <heap> / fliu <heap> : analyse/patch the FreeListInUse structure\n"
extusage["freelistinuse"] += "---------------------------------------------\n"
extusage["freelistinuse"] += "Use -p <byte entry> to patch the FreeListInUse entry and set its bit\n"
extusage["freelistinuse"] += "eg !heaper 0x00a80000 -p 0x7c\n"
extusage["dumppeb"] = "\ndumppeb / dp : Return the PEB entry address\n"
extusage["dumppeb"] += "---------------------------------------------\n"
extusage["dumppeb"] += "Use -m to view the PEB management structure\n"
extusage["hook"] = "\nhook <heap> / h : Hook various functions that create/destroy/manipulate a heap\n"
extusage["hook"] += "------------------------------------------------------------------------------\n"
extusage["hook"] += "Use -h to hook any function.\n"
extusage["hook"] += "Use -u to unhook any function.\n"
extusage["hook"] += "Available functions to hook are: \n"
extusage["hook"] += "- RtlAllocateHeap() [alloc]\n"
extusage["hook"] += "- RtlFreeHeap() [free]\n"
extusage["hook"] += "- RtlCreateHeap() [create]\n"
extusage["hook"] += "- RtlDestroyHeap() [destroy]\n"
extusage["hook"] += "- RtlReAllocateHeap() [realloc]\n"
extusage["hook"] += "- RtlSizeHeap() [size]\n"
extusage["hook"] += "- RtlInitializeCriticalSection() [createcs]\n"
extusage["hook"] += "- RtlDeleteCriticalSection() [deletecs]\n"
extusage["hook"] += "- SetUnhandledExceptionFilter() [setuef]\n"
extusage["hook"] += "- VirtualAllocEx() [va]\n"
extusage["hook"] += "- VirtualFreeEx() [vf]\n"
extusage["hook"] += "- Hook all! [all]\n"
extusage["hook"] += "Examples:\n"
extusage["hook"] += "~~~~~~~~~\n"
extusage["hook"] += "Hook RtlReAllocateHeap() on heap 0x00150000 '!heaper hook 0x00150000 -h realloc'\n"
extusage["hook"] += "Hook all heap functions '!heaper hook -u all'\n"
extusage["hook"] += "Hook RtlCreateHeap() '!heaper hook -h create'\n"
extusage["dumpteb"] = "\ndumpteb / dt : List all of the TEB entry addresses\n"
extusage["dumpteb"] += "--------------------------------------------------------\n"
extusage["dumpheaps"] = "\ndumpheaps / dh : Dump all the heaps for a given process\n"
extusage["dumpheaps"] += "-------------------------------------------------------\n"
extusage["analyseheap"] = "\nanalyseheap <heap> / ah <heap> : Analyse a particular heap\n"
extusage["analyseheap"] += "----------------------------------------------------------\n"
extusage["analysesegments"] = "\nanalysesegments <heap> / as <heap> : Analyse a particular heap's segment stucture(s)\n"
extusage["analysesegments"] += "------------------------------------------------------------------------------------\n"
extusage["analysesegments"] += "Use -g to view a graphical representation of the heap structure\n"
extusage["analysefrontend"] = "\nanalysefrontend <heap> / af <heap> : Analyse a particular heap's frontend free structure\n"
extusage["analysefrontend"] += "----------------------------------------------------------------------------------------\n"
if OS >= 6.0:
extusage["analysefrontend"] += "Use -u to dump the UserBlocks that are activated in the LFH\n"
extusage["analysefrontend"] += "Use -s to specify a sized bin to dump\n"
extusage["analysefrontend"] += "Use -c to dump the UserBlockCache structure\n"
extusage["analysefrontend"] += "Use -b to dump the buckets in the LFH\n"
extusage["analysefrontend"] += "Use -g to view a graphical representation of the UserBlocks in the LFH\n"
extusage["analysefrontend"] += "Use -o to specify a filename for the graph\n"
extusage["analysefrontend"] += "Examples:\n"
extusage["analysefrontend"] += "~~~~~~~~~\n"
extusage["analysefrontend"] += "Dump the UserBlocks '!heaper af 0x00260000 -u'\n"
extusage["analysefrontend"] += "Dump the UserBlocks for size 0x40 '!heaper af 0x00260000 -u -s 0x40'\n"
extusage["analysefrontend"] += "Dump the UserBlockCache '!heaper af 0x00260000 -c'\n"
extusage["analysefrontend"] += "Dump the buckets '!heaper af 0x00260000 -b'\n"
extusage["analysefrontend"] += "Dump the UserBlocks and graph it '!heaper af 0x00260000 -u -g -o UserBlocks-example'\n"
elif OS < 6.0:
extusage["analysefrontend"] += "Use -l to dump the Lookaside Lists\n"
extusage["analysefrontend"] += "Use -g to view a graphical representation of the Lookaside Lists\n"
extusage["analysefrontend"] += "Use -o to specify a filename for the graph\n"
extusage["analysefrontend"] += "Examples:\n"
extusage["analysefrontend"] += "~~~~~~~~~\n"
extusage["analysefrontend"] += "Dump the Lookaside Lists '!heaper af 0x00260000 -l'\n"
extusage["analysefrontend"] += "Dump the Lookaside Lists and graph it '!heaper af 0x00260000 -l -g -o lookaside'\n"
extusage["analysebackend"] = "\nanalysebackend <heap> / ab <heap> : Analyse a particular heap's backend free structure\n"
extusage["analysebackend"] += "------------------------------------------------------------------------------------\n"
if OS >= 6.0:
extusage["analysebackend"] += "Use -l to view the ListHints\n"
extusage["analysebackend"] += "Use -f to view the FreeList chunks\n"
extusage["analysebackend"] += "Use -g to view a graphical representation of the ListHint/FreeList\n"
elif OS < 6.0:
extusage["analysebackend"] += "Use -h to view the HeapCache (if its activated)\n"
extusage["analysebackend"] += "Use -f to view the FreeList chunks\n"
extusage["analysebackend"] += "Use -g to view a graphical representation of the FreeLists\n"
extusage["analysebackend"] += "Use -o to specify a filename for the graph\n"
extusage["analysesegments"] = "\nanalysesegment(s) <heap> / as <heap> : Analyse a particular heap's segment structure(s)\n"
extusage["analysesegments"] += "------------------------------------------------------------------------------------\n"
extusage["patch"] = "\npatch <function/data structures> / p <function/data structures> : patch memory for the heap\n"
extusage["patch"] += "-------------------------------------------------------------------------------------------\n"
extusage["patch"] += "Use 'PEB' to patch the following areas:\n"
extusage["patch"] += " - PEB.IsDebugged\n"
extusage["patch"] += " - PEB.ProcessHeap.Flag\n"
extusage["patch"] += " - PEB.NtGlobalFlag\n"
extusage["patch"] += " - PEB.LDR_DATA\n"
extusage["patch"] += "Example: '!heaper patch PEB'\n"
extusage["analyseheapcache"] = "\nanalyseheapcache <heap> / ahc <heap> : Analyse a particular heap's cache (FreeList[0])\n"
extusage["analyseheapcache"] += "------------------------------------------------------------------------------------\n"
extusage["analysechunks"] = "\nanalysechunks <heap> / ac <heap> : Analyse a particular heap's chunks\n"
extusage["analysechunks"] += "---------------------------------------------------------------------\n"
extusage["analysechunks"] += "Use -r <start address> <end address> to view all the chunks between those ranges\n"
extusage["analysechunks"] += "Use -f to chunk_filter chunks by type (free/busy) eg: !heaper ac d20000 -f busy\n"
extusage["analysechunks"] += "Use -v to view the first 16 bytes of each chunk\n"
extusage["dumpfunctionpointers"] = "\ndumpfunctionpointers / dfp : Dump all the function pointers of the current process\n"
extusage["dumpfunctionpointers"] += "-----------------------------------------------------------------------------------\n"
extusage["dumpfunctionpointers"] += "Use -a <address> to specify where to start looking for function pointers\n"
extusage["dumpfunctionpointers"] += "Use -s <size> to specify the amount of data to search from the address\n"
extusage["dumpfunctionpointers"] += "Use -p <address/all> to patch a function pointer or all function pointers\n"
extusage["dumpfunctionpointers"] += "Use -r <address/all> to restore a function pointer or all function pointers\n"
extusage["dumpfunctionpointers"] += "Use -e <address,address,address> comma seperated list of addresses to exclude from patching/restoring\n"
extusage["dumpfunctionpointers"] += "Examples:\n"
extusage["dumpfunctionpointers"] += "~~~~~~~~~\n"
extusage["dumpfunctionpointers"] += "locate pointers - '!heaper dfp -s 3000 -a 0x00c55000'\n"
extusage["dumpfunctionpointers"] += "patch pointer - '!heaper dfp -p 0x00c56120'\n"
extusage["dumpfunctionpointers"] += "patch all pointers - '!heaper dfp -s 2000 -a 6ed86000 -p all -e 6ed86290,6ed86294'\n"
extusage["dumpfunctionpointers"] += "restore pointer - '!heaper dfp -r 0x00c56120'\n"
extusage["dumpfunctionpointers"] += "restore all pointers - '!heaper dfp -s 3000 -a 0x00c55000 -r all'\n"
extusage["exploit"] = "\nexploit / exp : Perform heuristics against the FrontEnd and BackEnd allocators to determine exploitable conditions\n"
extusage["exploit"] += "-----------------------------------------------------------------------------------\n"
extusage["exploit"] += "Use -f to analyse the FrontEnd allocator\n"
extusage["exploit"] += "Use -b to analyse the BackEnd allocator\n"
extusage["exploit"] += "eg: !heaper exploit 00490000 -f\n"
return extusage
def set_up_usage():
cmds = {}
cmds["dumppeb"] = set_command("dumppeb", "Dump the PEB pointers",get_extended_usage()["dumppeb"], "dp")
cmds["dp"] = set_command("dumppeb", "Dump the PEB pointers",get_extended_usage()["dumppeb"], "dp")
cmds["dumpteb"] = set_command("dumpteb", "Dump the TEB pointers",get_extended_usage()["dumpteb"], "dt")
cmds["dt"] = set_command("dumpteb", "Dump the TEB pointers",get_extended_usage()["dumpteb"], "dt")
cmds["dumpheaps"] = set_command("dumpheaps", "Dump all the heaps of a process",get_extended_usage()["dumpheaps"], "dh")
cmds["dh"] = set_command("dumpheaps", "Dump all the heaps of a process",get_extended_usage()["dumpheaps"], "dh")
cmds["dumpfunctionpointers"] = set_command("dumpfunctionpointers", "Dump all the function pointers of the current process",get_extended_usage()["dumpfunctionpointers"], "dfp")
cmds["dfp"] = set_command("dumpfunctionpointers", "Dump all the function pointers of the current process",get_extended_usage()["dumpfunctionpointers"], "dfp")
cmds["analyseheap"] = set_command("analyseheap", "analyse a particular heap",get_extended_usage()["analyseheap"], "ah")
cmds["ah"] = set_command("analyseheap", "analyse a particular heap",get_extended_usage()["analyseheap"], "ah")
cmds["analysefrontend"] = set_command("analysefrontend", "analyse a particular heap's frontend",get_extended_usage()["analysefrontend"], "af")
cmds["af"] = set_command("analyselal", "analyse a particular heap's lookaside list",get_extended_usage()["analysefrontend"], "af")
cmds["analysebackend"] = set_command("analysebackend", "analyse a particular heap's backend",get_extended_usage()["analysebackend"], "ab")
cmds["ab"] = set_command("analysefreelist", "analyse a particular heap's freelist",get_extended_usage()["analysebackend"], "ab")
cmds["analysechunks"] = set_command("analysechunks", "analyse a particular heap's list of chunks",get_extended_usage()["analysechunks"], "ac")
cmds["ac"] = set_command("analysechunks", "analyse a particular heap's list of chunks",get_extended_usage()["analysechunks"], "ac")
cmds["analysesegments"] = set_command("analysesegments", "analyse a particular heap's segment(s)",get_extended_usage()["analysesegments"], "as")
cmds["as"] = set_command("analysesegments", "analyse a particular heap's segment(s)",get_extended_usage()["analysesegments"], "as")
cmds["analyseheapcache"] = set_command("analyseheapcache", "analyse a particular heap's cache (FreeList[0])",get_extended_usage()["analyseheapcache"], "ahc")
cmds["ahc"] = set_command("analyseheapcache", "analyse a particular heap's cache (FreeList[0])",get_extended_usage()["analyseheapcache"], "ahc")
cmds["freelistinuse"] = set_command("freelistinuse", "analyse/patch the FreeListInUse structure",get_extended_usage()["freelistinuse"], "fliu")
cmds["fliu"] = set_command("freelistinuse", "analyse/patch the FreeListInUse structure",get_extended_usage()["freelistinuse"], "fliu")
cmds["hook"] = set_command("hook", "Hook various functions that create/destroy/manipulate a heap",get_extended_usage()["hook"], "h")
cmds["h"] = set_command("hook", "Hook various functions that create/destroy/manipulate a heap",get_extended_usage()["hook"], "h")
cmds["patch"] = set_command("patch", "Patch various data structures and functions",get_extended_usage()["patch"], "p")
cmds["p"] = set_command("patch", "Patch various data structures and functions",get_extended_usage()["patch"], "p")
cmds["exploit"] = set_command("exploit", "Perform heuristics against the FrontEnd and BackEnd allocators to determine exploitable conditions",get_extended_usage()["exploit"], "exp")
cmds["exp"] = set_command("exploit", "Perform heuristics against the FrontEnd and BackEnd allocators to determine exploitable conditions",get_extended_usage()["exploit"], "exp")
return cmds
# detects exploitable conditions..
def freelist_and_lookaside_heuristics(window, chunk_data, pheap, imm, data_structure, vuln_chunks):
# check for FreeList
if data_structure == "freelistn" or data_structure == "freelist0":
# extract the corrupt data
corrupt_chunk_data = imm.getKnowledge(chunk_data)
corrupt_chunk_size = corrupt_chunk_data[0]
corrupt_chunk_address = corrupt_chunk_data[1]
corrupt_chunk_blink = corrupt_chunk_data[2]
corrupt_chunk_flink = corrupt_chunk_data[3]
entry_offset = corrupt_chunk_data[4]
# real values
blink = corrupt_chunk_data[4]
flink = corrupt_chunk_data[5]
# ensure that we are dealing with FreeList[0]
if corrupt_chunk_size == 0:
# search all the chunks
for index, chunk in enumerate(pheap.chunks):
# compare chunk addresses and if the sizes are the same,
# i suspect at least a 4 byte overwrite..
if (corrupt_chunk_address-0x8) == chunk.addr:
# if its the last chunk in the freelist[0] we can only check if we modify past
# 2 bytes, else we just have to check the 1st byte!
# this check can be inhanced further for freelist[n]
if ((flink == 1 and pheap.chunks[index-1].size != chunk.psize)
or (flink != 1 and pheap.chunks[index+1].psize != chunk.size
and pheap.chunks[index-1].size != chunk.psize)):
window.Log("")
window.Log("(+) Detected corrupted chunk in FreeList[0x%02x] chunk address 0x%08x" % (corrupt_chunk_size,corrupt_chunk_address-0x8))
window.Log("")
if flink == 1:
window.Log(" -> This chunk is the last entry in FreeList[0]")
elif flink != 1:
window.Log(" -> This chunk is number %d in FreeList[0]" % index)
# 1st lets check for freelist insert attack vector
window.Log("")
window.Log(" > Freelist[0] insert attack:")
window.Log(" - Free a chunk of size > %d (0x%02x) < %d (0x%02x)" %
(pheap.chunks[index-1].size, pheap.chunks[index-1].size, pheap.chunks[index].size, pheap.chunks[index].size))
# blink checks
if corrupt_chunk_blink != blink:
window.Log(" - Blink was detected to be overwritten (0x%08x), try setting it to a lookaside[n] entry or a function pointer table" % corrupt_chunk_blink)
else:
window.Log(" - Try to overwrite the blink for this chunk so you can control what the address that points to the inserted chunk or try another attack")
window.Log("")
window.Log(" > Freelist[0] search attack:")
window.Log(" - Overwrite with a size you can allocate. Current size: %d (0x%02x)" % (pheap.chunks[index].size, pheap.chunks[index].size))
# if flink == 0x1, its the last chunk in the list entry
if (flink == 0x1 and entry_offset != corrupt_chunk_flink) or (flink != 0x1 and flink != corrupt_chunk_flink):
window.Log(" - Flink was detected to be overwritten (0x%08x), try setting it to a fake chunk structure" % corrupt_chunk_flink)
else:
window.Log(" - Try to overwrite the flink for this chunk so you can point it to a fake chunk or try another attack")
window.Log("")
window.Log(" > Freelist[0] relinking attack:")
window.Log(" - Overwrite with a size you can allocate. Current size: %d (0x%02x)" % (pheap.chunks[index].size, pheap.chunks[index].size))
# if flink == 0x1, its the last chunk in the list entry
if (flink == 0x1 and corrupt_chunk_address != corrupt_chunk_flink) or (flink != 0x1 and flink != corrupt_chunk_flink):
window.Log(" - Flink was detected to be overwritten (0x%08x), try setting it to a fake chunk structure (heapbase+0x057c)." % corrupt_chunk_flink)
else:
window.Log(" - Try to overwrite the flink for this chunk so you can point it to a fake chunk structure (heapbase+0x057c).")
window.Log(" - This will allocate a pointer from the base and may allow you to take control by overwriting the heapbase using the RtlCommitRoutine")
# information for the user..
vuln_chunks += 1
# Validate the HeapCache
# ======================
if pheap.HeapCache:
bit_list, chunk_dict = get_heapCache_bitmap(pheap, True)
if chunk.size in range (0x80, 0x400):
if bit_list[chunk.size] != 1:
window.Log("(+) Detected corrupted chunk in HeapCache bitmap[0x%04x] chunk address 0x%08x" % (chunk_dict[corrupt_chunk_address-0x8],corrupt_chunk_address-0x8),corrupt_chunk_address-0x8)
window.Log("")
# last chunk so we can get the size by
if flink == 1:
window.Log(" -> This chunk is the last entry in FreeList[0]")
elif flink != 1:
window.Log(" -> This chunk is number %d in FreeList[0]" % index)
window.Log("")
window.Log(" > HeapCache de-synchronization attack:")
if chunk.size > chunk_dict[corrupt_chunk_address-0x8]:
window.Log(" - Size has been overwritten with a larger value! %d (0x%04x) try to overwrite the chunk with a size < %d (0x%04x)" % (chunk.size, chunk.size, chunk_dict[corrupt_chunk_address-0x8],chunk_dict[corrupt_chunk_address-0x8]))
elif chunk.size < chunk_dict[corrupt_chunk_address-0x8]:
window.Log(" - Excellant! Size has been overwritten with a smaller value! ")
# if the bitmask before our corrupted size is set, were fucked.
if bit_list[chunk_dict[corrupt_chunk_address-0x8]-0x1] == 1:
window.Log("(-) HeapCache de-synchronization size attack will not work because there are no avalaible ")
window.Log(" chunk sizes between the last set bucket entry and this chunks bucket entry!")
window.Log("")
window.Log(" -> bitmap[0x%04x] MUST be 0" % (chunk_dict[corrupt_chunk_address-0x8]-0x1))
# else, we have a chance to exploit it...
else:
window.Log(" - Allocate a chunk of size %d (0x%02x) or overwrite another size" % ((chunk.size-0x1 * 0x8), chunk.size))
for size in range (chunk_dict[corrupt_chunk_address-0x8]-0x1, 0x7f, -1):
if bit_list[size] == 1:
break
if size+0x1 < chunk_dict[corrupt_chunk_address-0x8]:
window.Log(" -> Available chunk sizes to overwrite with:")
window.Log("")
for ow_size in range(size+0x1, chunk_dict[corrupt_chunk_address-0x8]):
window.Log(" HEAP_CACHE[0x%04x]" % ow_size)
vuln_chunks += 1
# else its overwritten with a value outside of FreeList[0] possible values
elif chunk.size not in range (0x80, 0x400):
window.Log("")
window.Log("(+) Detected corrupted chunk in HeapCache bitmap[0x%04x] chunk address 0x%08x" % (chunk_dict[corrupt_chunk_address-0x8],corrupt_chunk_address-0x8),corrupt_chunk_address-0x8)
window.Log("")
if flink == 1:
window.Log(" -> This chunk is the last entry in FreeList[0]")
elif flink != 1:
window.Log(" -> This chunk is number %d in FreeList[0]" % index)
window.Log("")
window.Log("(!) This chunk was overwritten with a size value (0x%04x) that is outside of the range of FreeList[0]" % chunk.size)
elif corrupt_chunk_size != 0:
for index, chunk in enumerate(pheap.chunks):
if (corrupt_chunk_address-0x8) == chunk.addr:
# check on size only incase of an off by one
if (corrupt_chunk_size != chunk.size):
vuln_chunks += 1
window.Log("(!) Detected FreeList[0x%x] chunk (0x%08x) overwrite!" % (corrupt_chunk_size,chunk.addr), chunk.addr)
if chunk.size < 0x80:
window.Log("(+) Chunk is set to size 0x%04x so next allocation of size 0x%04x" % (chunk.size,pheap.chunks[index-1].size),chunk.addr)
window.Log(" will flip the FreeListInUse[0x%04x] entry" % (chunk.size),chunk.addr)
else:
window.Log("(+) Chunk is set to size 0x%04x, try setting it < 0x80" % (chunk.size))
if ((pheap.chunks[index-1].nextchunk == 0) and (pheap.chunks[index+1].prevchunk == 0)):
window.Log("(+) Detected the chunk to be lonely!",chunk.addr)
else:
window.Log("(-) This chunk is not lonely :( try overwriting blink and flink")
# remove the obj for next run
imm.forgetKnowledge(chunk_data)
return vuln_chunks
elif data_structure == "lookaside":
if pheap.Lookaside:
for ndx in range(0, len(pheap.Lookaside)):
entry = pheap.Lookaside[ndx]
if not entry.isEmpty():
#window.Log("Lookaside[0x%03x] No. of chunks: %d, ListEntry: 0x%08x, Size: (%d+8=%d)" %
#(ndx, entry.Depth, entry.addr, (ndx*8), (ndx*8+8)), address = entry.addr)
no_chunk = 0
for a in entry.getList():
no_chunk += 1
chunk_size = ""
try:
# size
chunk_size = imm.readMemory(a, 0x2)
chunk_size = struct.unpack("H", chunk_size)[0]
# flink
chunk_flink = imm.readMemory(a+0x8, 0x4)
chunk_flink = struct.unpack("L", chunk_flink)[0]
except:
window.Log("(-) Cannot read chunk address: 0x%08x" % a)
pass
lookaside_chunk_list = entry.getList()
try:
next_chunk = lookaside_chunk_list[lookaside_chunk_list.index(a)+1]
except:
next_chunk = 0
try:
prev_chunk = lookaside_chunk_list[lookaside_chunk_list.index(a)-1]
except:
prev_chunk = 0
# first lets check the size
if chunk_size != ndx and (next_chunk == 0 or next_chunk == (chunk_flink-0x8)):
vuln_chunks += 1
window.Log("")
window.Log("(!) Size has not been set for chunk 0x%08x, possibly because it doesnt exist" % a)
window.Log("(+) This is likley the previous chunks flink! (0x%08x)" % prev_chunk, prev_chunk)
alloc_size = (ndx-0x01)*0x8
window.Log("(+) Try to set the address to a controlled pointer and make %d allocations using size %d (0x%04x)" % (no_chunk,alloc_size,alloc_size))
window.Log("(!) This will set the allocation pointer to the function pointer and allow you to overwrite its value.. ")
window.Log("")
# overwrite the size, but not the flink..
elif chunk_size != ndx and (next_chunk != (chunk_flink-0x8) or next_chunk != 0):
vuln_chunks += 1
window.Log("")
window.Log("(!) Size has been overwritten for chunk 0x%08x" % a)
window.Log("(+) Try to overwrite the flink for this chunk")
window.Log("")
# remove the obj for next run
imm.forgetKnowledge(chunk_data)
return vuln_chunks
def dump_heap(imm, window):
window.Log("Listing available heaps: ")
window.Log("")