-
Notifications
You must be signed in to change notification settings - Fork 564
/
mona.py
19306 lines (17205 loc) · 642 KB
/
mona.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 python2.7
"""
U{Corelan<https://www.corelan.be>}
Copyright (c) 2011-2024, Peter Van Eeckhoutte - Corelan Consulting bv
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Corelan nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL PETER VAN EECKHOUTTE OR CORELAN CONSULTING BV
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
$Revision: 636 $
$Id: mona.py 636 2024-03-26 14:49:00Z corelanc0d3r $
"""
__VERSION__ = '2.0'
__REV__ = filter(str.isdigit, '$Revision: 636 $')
__IMM__ = '1.8'
__DEBUGGERAPP__ = ''
arch = 32
win7mode = False
# try:
# import debugger
# except:
# pass
try:
import immlib as dbglib
from immlib import LogBpHook
__DEBUGGERAPP__ = "Immunity Debugger"
except:
try:
import pykd
import windbglib as dbglib
from windbglib import LogBpHook
dbglib.checkVersion()
arch = dbglib.getArchitecture()
__DEBUGGERAPP__ = "WinDBG"
except SystemExit:
print("-Exit.")
import sys
sys.exit(1)
except Exception:
#import traceback
print("Do not run this script outside of a debugger !")
#print traceback.format_exc()
import sys
sys.exit(1)
import getopt
try:
#import debugtypes
#import libdatatype
from immutils import *
except:
pass
import os
import re
import sys
import types
import random
import shutil
import struct
import string
import types
import urllib
import inspect
import datetime
import binascii
import itertools
import traceback
import pickle
import json
from operator import itemgetter
from collections import defaultdict, namedtuple
import cProfile
import pstats
import copy
DESC = "Corelan Consulting bv exploit development swiss army knife"
#---------------------------------------#
# Global stuff #
#---------------------------------------#
TOP_USERLAND = 0x7fffffff if arch == 32 else 0x7FFFFFFFFFFF
STACK_POINTER = "ESP" if arch == 32 else "RSP"
PTR_SIZE_DIRECTIVE = "DWORD PTR" if arch == 32 else "QWORD PTR"
g_modules={}
MemoryPageACL={}
global CritCache
global vtableCache
global stacklistCache
global segmentlistCache
global VACache
global IATCache
global NtGlobalFlag
global FreeListBitmap
global memProtConstants
global currentArgs
global disasmUpperChecked
global disasmIsUpper
global configFileCache
global configwarningshown
NtGlobalFlag = -1
FreeListBitmap = {}
memProtConstants = {}
CritCache={}
IATCache={}
vtableCache={}
stacklistCache={}
segmentlistCache={}
configFileCache={}
VACache={}
ptr_counter = 0
ptr_to_get = -1
silent = False
ignoremodules = False
noheader = False
dbg = dbglib.Debugger()
disasmUpperChecked = False
disasmIsUpper = False
configwarningshown = False
if __DEBUGGERAPP__ == "WinDBG":
if pykd.getSymbolPath().replace(" ","") == "":
dbg.log("")
dbg.log("** Warning, no symbol path set ! ** ",highlight=1)
sympath = "srv*c:\symbols*http://msdl.microsoft.com/download/symbols"
dbg.log(" I'll set the symbol path to %s" % sympath)
pykd.setSymbolPath(sympath)
dbg.log(" Symbol path set, now reloading symbols...")
dbg.nativeCommand(".reload")
dbg.log(" All set. Please restart WinDBG.")
dbg.log("")
osver = dbg.getOsVersion()
if osver in ["6", "7", "8", "vista", "win7", "2008server", "win8", "win8.1", "win10", "win11"]:
win7mode = True
heapgranularity = 8
if arch == 64:
heapgranularity = 16
offset_categories = ["xp", "vista", "win7", "win8", "win10", "win11"]
# offset = [x86,x64]
offsets = {
"FrontEndHeap" : {
"xp" : [0x580,0xad8],
"vista" : [0x0d4,0x178],
"win8" : [0x0d0,0x170],
"win10" : {
14393 : [0x0d4,0x178]
},
"win11" : {
14393 : [0x0d4,0x178]
}
},
"FrontEndHeapType" : {
"xp" : [0x586,0xae2],
"vista" : [0x0da,0x182],
"win8" : [0x0d6,0x17a],
"win10" : {
14393 : [0x0da,0x182]
},
"win11" : {
14393 : [0x0da,0x182]
}
},
"VirtualAllocdBlocks" : {
"xp" : [0x050,0x090],
"vista" : [0x0a0,0x118],
"win8" : [0x09c,0x110]
},
"SegmentList" : {
"vista" : [0x0a8,0x128],
"win8" : [0x0a4,0x120]
}
}
#---------------------------------------#
# Populate constants #
#---------------------------------------#
memProtConstants["X"] = ["PAGE_EXECUTE",0x10]
memProtConstants["RX"] = ["PAGE_EXECUTE_READ",0x20]
memProtConstants["RWX"] = ["PAGE_EXECUTE_READWRITE",0x40]
memProtConstants["N"] = ["PAGE_NOACCESS",0x1]
memProtConstants["R"] = ["PAGE_READONLY",0x2]
memProtConstants["RW"] = ["PAGE_READWRITE",0x4]
memProtConstants["GUARD"] = ["PAGE_GUARD",0x100]
memProtConstants["NOCACHE"] = ["PAGE_NOCACHE",0x200]
memProtConstants["WC"] = ["PAGE_WRITECOMBINE",0x400]
#---------------------------------------#
# Utility functions #
#---------------------------------------#
def resetGlobals():
"""
Clears all global variables
"""
global CritCache
global vtableCache
global stacklistCache
global segmentlistCache
global VACache
global NtGlobalFlag
global FreeListBitmap
global memProtConstants
global currentArgs
CritCache = None
vtableCache = None
stacklistCache = None
segmentlistCache = None
VACache = None
NtGlobalFlag = None
FreeListBitmap = None
memProtConstants = None
currentArgs = None
disasmUpperChecked = False
return
def getPythonVersion():
versioninfo = sys.version
versioninfolines = versioninfo.split('\n')
return versioninfolines[0]
def toHex(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)
"""
if arch == 32:
return "%08x" % n
if arch == 64:
return "%016x" % n
def sanitize_module_name(modname):
"""
Sanitizes a module name so it can be used as a variable
"""
return modname.replace(".", "_")
def DwordToBits(srcDword):
"""
Converts a dword into an array of 32 bits
"""
bit_array = []
h_str = "%08x" % srcDword
h_size = len(h_str) * 4
bits = (bin(int(h_str,16))[2:]).zfill(h_size)[::-1]
for bit in bits:
bit_array.append(int(bit))
return bit_array
def getDisasmInstruction(disasmentry):
""" returns instruction string, checks if ASM is uppercase and converts to upper if needed """
instrline = disasmentry.getDisasm()
global disasmUpperChecked
global disasmIsUpper
if disasmUpperChecked:
if not disasmIsUpper:
instrline = instrline.upper()
else:
disasmUpperChecked = True
interim_instr = instrline.upper()
if interim_instr == instrline:
disasmIsUpper = True
else:
disasmIsUpper = False
dbg.log("** It looks like you've configured the debugger to produce lowercase disassembly. Got it, all good **", highlight=1)
instrline = instrline.upper()
return instrline
def multiSplit(thisarg,delimchars):
""" splits a string into an array, based on provided delimeters"""
splitparts = []
thispart = ""
for c in str(thisarg):
if c in delimchars:
thispart = thispart.replace(" ","")
if thispart != "":
splitparts.append(thispart)
splitparts.append(c)
thispart = ""
else:
thispart += c
if thispart != "":
splitparts.append(thispart)
return splitparts
def getAddyArg(argaddy):
"""
Tries to extract an address from a specified argument
addresses and values will be considered hex
(unless you specify 0n before a value)
registers are allowed too
"""
findaddy = 0
addyok = True
addyparts = []
addypartsint = []
delimchars = ["-","+","*","/","(",")","&","|",">","<"]
regs = dbg.getRegs()
thispart = ""
for c in str(argaddy):
if c in delimchars:
thispart = thispart.replace(" ","")
if thispart != "":
addyparts.append(thispart)
addyparts.append(c)
thispart = ""
else:
thispart += c
if thispart != "":
addyparts.append(thispart)
partok = False
for part in addyparts:
cleaned = part
if not part in delimchars:
for x in delimchars:
cleaned = cleaned.replace(x,"")
if cleaned.startswith("[") and cleaned.endswith("]"):
partval,partok = getIntForPart(cleaned.replace("[","").replace("]",""))
if partok:
try:
partval = struct.unpack('<L',dbg.readMemory(partval,4))[0]
except:
partval = 0
partok = False
break
else:
partval,partok = getIntForPart(cleaned)
if not partok:
break
addypartsint.append(partval)
else:
addypartsint.append(part)
if not partok:
break
if not partok:
addyok = False
findval = 0
else:
calcstr = "".join(str(x) for x in addypartsint)
try:
findval = eval(calcstr)
addyok = True
except:
findval = 0
addyok = False
return findval, addyok
def getIntForPart(part):
"""
Returns the int value associated with an input string
The input string can be a hex value, decimal value, register, modulename, or modulee!functionname
"""
partclean = part
partclean = partclean.upper()
addyok = True
partval = 0
regs = dbg.getRegs()
if partclean in regs:
partval = regs[partclean]
elif partclean.lower() == "heap" or partclean.lower() == "processheap":
partval = getDefaultProcessHeap()
else:
if partclean.lower().startswith("0n"):
partclean = partclean.lower().replace("0n","")
try:
partval = int(partclean)
except:
addyok = False
partval = 0
else:
try:
if not "0x" in partclean.lower():
partclean = "0x" + partclean
partval = int(partclean,16)
except:
addyok = False
partval = 0
if not addyok:
if not "!" in part:
m = getModuleObj(part)
if not m == None:
partval = m.moduleBase
addyok = True
else:
modparts = part.split("!")
modname = modparts[0]
funcname = modparts[1]
m = getFunctionAddress(modname,funcname)
if m > 0:
partval = m
addyok = True
return partval,addyok
def getHeapAllocSize(requested_size, granularity = 8):
"""
Returns the expected allocated size for a request of X bytes of heap memory
taking a certain granularity into account
"""
requested_size_int = to_int(requested_size)
interimval = (requested_size_int / granularity) * granularity
interimtimes = (requested_size_int / granularity)
if (interimval < requested_size_int):
interimtimes += 1
allocated_size = granularity * interimtimes
return allocated_size
def getFunctionAddress(modname,funcname):
"""
Returns the addres of the function inside a given module
Relies on EAT data
Returns 0 if nothing found
"""
funcaddy = 0
m = getModuleObj(modname)
if not m == None:
eatlist = m.getEAT()
for f in eatlist:
if funcname == eatlist[f]:
return f
for f in eatlist:
if funcname.lower() == eatlist[f].lower():
return f
return funcaddy
def getFunctionName(addy):
"""
Returns symbol name closest to the specified address
Only works in WinDBG
Returns function name and optional offset
"""
fname = ""
foffset = ""
cmd2run = "ln 0x%08x" % addy
output = dbg.nativeCommand(cmd2run)
for line in output.split("\n"):
if "|" in line:
lineparts = line.split(" ")
partcnt = 0
for p in lineparts:
if not p == "":
if partcnt == 1:
fname = p
break
partcnt += 1
if "+" in fname:
fnameparts = fname.split("+")
if len(fnameparts) > 1:
return fnameparts[0],fnameparts[1]
return fname,foffset
def printDataArray(data,charsperline=16,prefix=""):
maxlen = len(data)
charcnt = 0
charlinecnt = 0
linecnt = 0
thisline = prefix
lineprefix = "%04d - %04d " % (charcnt,charcnt+charsperline-1)
thisline += lineprefix
while charcnt < maxlen:
thisline += data[charcnt:charcnt+1]
charlinecnt += 1
charcnt += 1
if charlinecnt == charsperline or charlinecnt == maxlen:
dbg.log(thisline)
thisline = prefix
lineprefix = "%04d - %04d " % (charcnt,charcnt+charsperline-1)
thisline += lineprefix
charlinecnt = 0
return None
def find_all_copies(tofind,data):
"""
Finds all occurences of a string in a longer string
Arguments:
tofind - the string to find
data - contains the data to look for all occurences of 'tofind'
Return:
An array with all locations
"""
position = 0
positions = []
searchstringlen = len(tofind)
maxlen = len(data)
while position < maxlen:
position = data.find(tofind,position)
if position == -1:
break
positions.append(position)
position += searchstringlen
return positions
def getAllStringOffsets(data,minlen,offsetstart = 0):
asciistrings = {}
for match in re.finditer("(([\x20-\x7e]){%d,})" % minlen,data):
thisloc = match.start() + offsetstart
thisend = match.end() + offsetstart
asciistrings[thisloc] = thisend
return asciistrings
def getAllUnicodeStringOffsets(data,minlen,offsetstart = 0):
unicodestrings = {}
for match in re.finditer("((\x00[\x20-\x7e]){%d,})" % (minlen*2),data):
unicodestrings[offsetstart + match.start()] = (offsetstart + match.end())
return unicodestrings
def stripExtension(fullname):
"""
Removes extension from a filename
(will only remove the last extension)
Arguments :
fullname - the original string
Return:
A string, containing the original string without the last extension
"""
nameparts = str(fullname).split(".")
if len(nameparts) > 1:
cnt = 0
modname = ""
while cnt < len(nameparts)-1:
modname = modname + nameparts[cnt] + "."
cnt += 1
return modname.strip(".")
return fullname
def toHexByte(n):
"""
Converts a numeric value to a hex byte
Arguments:
n - the vale to convert (max 255)
Return:
A string, representing the value in hex (1 byte)
"""
return "%02X" % n
def toAsciiOnly(inputstr):
return "".join(i for i in inputstr if ord(i)<128 and ord(i) > 31)
def toAscii(n):
"""
Converts a byte to its ascii equivalent. Null byte = space
Arguments:
n - A string (2 chars) representing the byte to convert to ascii
Return:
A string (one character), representing the ascii equivalent
"""
asciiequival = " "
if n.__class__.__name__ == "int":
n = "%02x" % n
try:
if n != "00":
asciiequival=binascii.a2b_hex(n)
else:
asciiequival = " "
except TypeError:
asciiequival=" "
return asciiequival
def hex2bin(pattern):
"""
Converts a hex string (\\x??\\x??\\x??\\x??) to real hex bytes
Arguments:
pattern - A string representing the bytes to convert
Return:
the bytes
"""
pattern = pattern.replace("\\x", "")
pattern = pattern.replace("\"", "")
pattern = pattern.replace("\'", "")
return ''.join([binascii.a2b_hex(i+j) for i,j in zip(pattern[0::2],pattern[1::2])])
def cleanHex(hex):
hex = hex.replace("'","")
hex = hex.replace('"',"")
hex = hex.replace("\\x","")
hex = hex.replace("0x","")
return hex
def hex2int(hex):
return int(hex,16)
def getVariantType(typenr):
varianttypes = {}
varianttypes[0x0] = "VT_EMPTY"
varianttypes[0x1] = "VT_NULL"
varianttypes[0x2] = "VT_I2"
varianttypes[0x3] = "VT_I4"
varianttypes[0x4] = "VT_R4"
varianttypes[0x5] = "VT_R8"
varianttypes[0x6] = "VT_CY"
varianttypes[0x7] = "VT_DATE"
varianttypes[0x8] = "VT_BSTR"
varianttypes[0x9] = "VT_DISPATCH"
varianttypes[0xA] = "VT_ERROR"
varianttypes[0xB] = "VT_BOOL"
varianttypes[0xC] = "VT_VARIANT"
varianttypes[0xD] = "VT_UNKNOWN"
varianttypes[0xE] = "VT_DECIMAL"
varianttypes[0x10] = "VT_I1"
varianttypes[0x11] = "VT_UI1"
varianttypes[0x12] = "VT_UI2"
varianttypes[0x13] = "VT_UI4"
varianttypes[0x14] = "VT_I8"
varianttypes[0x15] = "VT_UI8"
varianttypes[0x16] = "VT_INT"
varianttypes[0x17] = "VT_UINT"
varianttypes[0x18] = "VT_VOID"
varianttypes[0x19] = "VT_HRESULT"
varianttypes[0x1A] = "VT_PTR"
varianttypes[0x1B] = "VT_SAFEARRAY"
varianttypes[0x1C] = "VT_CARRAY"
varianttypes[0x1D] = "VT_USERDEFINED"
varianttypes[0x1E] = "VT_LPSTR"
varianttypes[0x1F] = "VT_LPWSTR"
varianttypes[0x24] = "VT_RECORD"
varianttypes[0x25] = "VT_INT_PTR"
varianttypes[0x26] = "VT_UINT_PTR"
varianttypes[0x2000] = "VT_ARRAY"
varianttypes[0x4000] = "VT_BYREF"
if typenr in varianttypes:
return varianttypes[typenr]
else:
return ""
def bin2hex(binbytes):
"""
Converts a binary string to a string of space-separated hexadecimal bytes.
"""
return ' '.join('%02x' % ord(c) for c in binbytes)
def bin2hexstr(binbytes):
"""
Converts bytes to a string with hex
Arguments:
binbytes - the input to convert to hex
Return :
string with hex
"""
return ''.join('\\x%02x' % ord(c) for c in binbytes)
def str2js(inputstring):
"""
Converts a string to a javascript string
Arguments:
inputstring - the input string to convert
Return :
string in javascript format
"""
length = len(inputstring)
if length % 2 == 1:
jsmsg = "Warning : odd size given, js pattern will be truncated to " + str(length - 1) + " bytes, it's better use an even size\n"
if not silent:
dbg.logLines(jsmsg,highlight=1)
toreturn=""
for thismatch in re.compile("..").findall(inputstring):
thisunibyte = ""
for thisbyte in thismatch:
thisunibyte = "%02x" % ord(thisbyte) + thisunibyte
toreturn += "%u" + thisunibyte
return toreturn
def readJSONDict(filename):
"""
Retrieve stored dict from JSON file
"""
jsondict = {}
with open(filename, 'rb') as infile:
jsondata = infile.read()
jsondict = json.loads(jsondata)
return jsondict
def writeJSONDict(filename, dicttosave):
"""
Write dict as JSON to file
"""
with open(filename, 'wb') as outfile:
json.dump(dicttosave, outfile)
return
def readPickleDict(filename):
"""
Retrieve stored dict from file (pickle load)
"""
pdict = {}
pdict = pickle.load( open(filename,"rb"))
return pdict
def writePickleDict(filename, dicttosave):
"""
Write a dict to file as a pickle
"""
pickle.dump(dicttosave, open(filename, "wb"))
return
def opcodesToHex(opcodes):
"""
Converts pairs of chars (opcode bytes) to hex string notation
Arguments :
opcodes : pairs of chars
Return :
string with hex
"""
toreturn = []
opcodes = opcodes.replace(" ","")
for cnt in range(0, len(opcodes), 2):
thisbyte = opcodes[cnt:cnt+2]
toreturn.append("\\x" + thisbyte)
toreturn = ''.join(toreturn)
return toreturn
def rmLeading(input,toremove,toignore=""):
"""
Removes leading characters from an input string
Arguments:
input - the input string
toremove - the character to remove from the begin of the string
toignore - ignore this character
Return:
the input string without the leading character(s)
"""
newstring = ""
cnt = 0
while cnt < len(input):
if input[cnt] != toremove and input[cnt] != toignore:
break
cnt += 1
newstring = input[cnt:]
return newstring
def getVersionInfo(filename):
"""Retrieves version and revision numbers from a mona file
Arguments : filename
Return :
version - string with version (or empty if not found)
revision - string with revision (or empty if not found)
"""
file = open(filename,"rb")
content = file.readlines()
file.close()
revision = ""
version = ""
for line in content:
if line.startswith("$Revision"):
parts = line.split(" ")
if len(parts) > 1:
revision = parts[1].replace("$","")
if line.startswith("__VERSION__"):
parts = line.split("=")
if len(parts) > 1:
version = parts[1].strip()
return version,revision
def toniceHex(data,size):
"""
Converts a series of bytes into a hex string,
newline after 'size' nr of bytes
Arguments :
data - the bytes to convert
size - the number of bytes to show per linecache
Return :
a multiline string
"""
flip = 1
thisline = "\""
block = ""
try:
# Python 2
xrange
except NameError:
# Python 3, xrange is now named range
xrange = range
for cnt in xrange(len(data)):
thisline += "\\x%s" % toHexByte(ord(data[cnt]))
if (flip == size) or (cnt == len(data)-1):
thisline += "\""
flip = 0
block += thisline
block += "\n"
thisline = "\""
cnt += 1
flip += 1
return block.lower()
def hexStrToInt(inputstr):
"""
Converts a string with hex bytes to a numeric value
Arguments:
inputstr - A string representing the bytes to convert. Example : 41414141
Return:
the numeric value
"""
valtoreturn = 0
try:
valtoreturn = int(inputstr, 16)
except:
valtoreturn = 0
return valtoreturn
def to_int(inputstr):
"""
Converts a string to int, whether it's hex or decimal
Arguments:
inputstr - A string representation of a number. Example: 0xFFFF, 2345
Return:
the numeric value
"""
if str(inputstr).lower().startswith("0x"):
return hexStrToInt(inputstr)
else:
return int(inputstr)
def toSize(toPad,size):
"""
Adds spaces to a string until the string reaches a certain length
Arguments:
input - A string
size - the destination size of the string
Return:
the expanded string of length <size>
"""
padded = toPad + " " * (size - len(toPad))
return padded.ljust(size," ")
def toUnicode(input):
"""
Converts a series of bytes to unicode (UTF-16) bytes
Arguments :
input - the source bytes
Return:
the unicode expanded version of the input
"""
unicodebytes = ""
# try/except, just in case .encode bails out
try:
unicodebytes = input.encode('UTF-16LE')
except:
inputlst = list(input)
for inputchar in inputlst:
unicodebytes += inputchar + '\x00'
return unicodebytes
def toJavaScript(input):
"""
Extracts pointers from lines of text
and returns a javascript friendly version
"""
alllines = input.split("\n")
javascriptversion = ""
allbytes = ""
for eachline in alllines:
thisline = eachline.replace("\t","").lower().strip()
if not(thisline.startswith("#")):
if thisline.startswith("0x"):
theptr = thisline.split(",")[0].replace("0x","")
# change order to unescape format
if arch == 32:
ptrstr = ""
byte1 = theptr[0] + theptr[1]
ptrstr = "\\x" + byte1
byte2 = theptr[2] + theptr[3]
ptrstr = "\\x" + byte2 + ptrstr
try:
byte3 = theptr[4] + theptr[5]
ptrstr = "\\x" + byte3 + ptrstr
except:
pass
try:
byte4 = theptr[6] + theptr[7]
ptrstr = "\\x" + byte4 + ptrstr
except:
pass
allbytes += hex2bin(ptrstr)
if arch == 64:
byte1 = theptr[0] + theptr[1]
byte2 = theptr[2] + theptr[3]
byte3 = theptr[4] + theptr[5]
byte4 = theptr[6] + theptr[7]
byte5 = theptr[8] + theptr[9]
byte6 = theptr[10] + theptr[11]
byte7 = theptr[12] + theptr[13]
byte8 = theptr[14] + theptr[15]
allbytes += hex2bin("\\x" + byte8 + "\\x" + byte7 + "\\x" + byte6 + "\\x" + byte5)
allbytes += hex2bin("\\x" + byte4 + "\\x" + byte3 + "\\x" + byte2 + "\\x" + byte1)
javascriptversion = str2js(allbytes)
return javascriptversion
def getSourceDest(instruction):
"""
Determines source and destination register for a given instruction
"""
src = []
dst = []
srcp = []