-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathx64dbgpylib.py
executable file
·1860 lines (1594 loc) · 61.1 KB
/
x64dbgpylib.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
"""
Copyright (c) 2011-2017, Peter Van Eeckhoutte - Corelan GCV
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 GCV 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: 143 $
$Id: windbglib.py 143 2017-04-02 07:14:58Z corelanc0d3r $
"""
__VERSION__ = '1.0'
#
# Wrapper library around pykd
# (partial immlib logic port)
#
# This library allows you to run mona.py
# under WinDBG, using the pykd extension
#
import pykd
import os
import binascii
import struct
import traceback
import pickle
import ctypes
import array
import x64dbgpy.pluginsdk.x64dbg as x64dbg
import x64dbgpy.pluginsdk._scriptapi as script
global MemoryPages
global AsmCache
global OpcodeCache
global InstructionCache
global PageSections
global ModuleCache
global cpebaddress
global PEBModList
arch = 32
cpebaddress = 0
PageSections = {}
ModuleCache = {}
PEBModList = {}
Registers32BitsOrder = ["EAX", "ECX", "EDX", "EBX", "ESP", "EBP", "ESI", "EDI"]
Registers64BitsOrder = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI",
"R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"]
if pykd.is64bitSystem():
arch = 64
# Utility functions
def getOSVersion():
osversions = {}
osversions["5.0"] = "2000"
osversions["5.1"] = "xp"
osversions["5.2"] = "2003"
osversions["6.0"] = "vista"
osversions["6.1"] = "win7"
osversions["6.2"] = "win8"
osversions["6.3"] = "win8.1"
osversions["10.0"] = "win10"
peb = getPEBInfo()
majorversion = int(peb.OSMajorVersion)
minorversion = int(peb.OSMinorVersion)
thisversion = str(majorversion) + "." + str(minorversion)
if thisversion in osversions:
return osversions[thisversion]
else:
return "unknown"
def getArchitecture():
if not pykd.is64bitSystem():
return 32
else:
return 64
def getNtHeaders(modulebase):
# http://www.nirsoft.net/kernel_struct/vista/IMAGE_DOS_HEADER.html
# http://www.nirsoft.net/kernel_struct/vista/IMAGE_NT_HEADERS.html
if getArchitecture() == 64:
ntheaders = "_IMAGE_NT_HEADERS64"
else:
ntheaders = "_IMAGE_NT_HEADERS"
# modulebase + 0x3c = IMAGE_DOS_HEADER.e_lfanew
return pykd.module("ntdll").typedVar(ntheaders, modulebase + pykd.ptrDWord(modulebase + 0x3c))
def clearvars():
global MemoryPages
global AsmCache
global OpcodeCache
global InstructionCache
global PageSections
global ModuleCache
global cpebaddress
MemoryPages = None
AsmCache = None
OpcodeCache = None
InstructionCache = None
InstructionCache = None
PageSections = None
ModuleCache = None
cpebaddress = None
return
def getPEBInfo():
try:
return pykd.typedVar("ntdll!_PEB", pykd.getCurrentProcess())
except:
currversion = getPyKDVersion()
print ""
print " Oops - It seems that PyKD was unable problem to get the PEB object."
print " This usually means that"
print " 1. msdiaxxx.dll has not been registered correctly and/or"
print " 2. symbols are missing for ntdll.dll"
print ""
print " Possible solutions:"
print " -------------------"
print " 1. Re-register the VC runtime library:"
print " * For PyKd v%s:" % currversion
if currversion.startswith("0.2"):
print " (Re)Install the x86 VC++ Redistributable Package for Visual Studio 2008"
print " (https://www.microsoft.com/en-us/download/details.aspx?id=29)"
print " Next, run the following command from an administrator prompt:"
print " (x86) regsvr32.exe \"%ProgramFiles%\\Common Files\\microsoft shared\\VC\\msdia90.dll\"\n"
print " (x64) regsvr32.exe \"%ProgramFiles(x86)%\\Common Files\\microsoft shared\\VC\\msdia90.dll\"\n"
else:
print " Either install Visual Studio 2013, or get a copy of msdia120.dll and register it manually\n"
print " You can find a copy of msdia120.dll inside the pykd.zip file inside the github repository"
print " (Use at your own risk!). Place the file in the correct 'VC' folder and run regsvr32 from an administrative prompt:"
print " (x86) regsvr32.exe \"%ProgramFiles%\\Common Files\\microsoft shared\\VC\\msdia120.dll\"\n"
print " (x64) regsvr32.exe \"%ProgramFiles(x86)%\\Common Files\\microsoft shared\\VC\\msdia120.dll\"\n"
print " 2. Force download of the Symbols for ntdll.dll"
print " * Connect to the internet, and verify that the symbol path is configured correctly"
print " Assuming that the local symbol path is set to c:\\symbols,"
print " run the following command from within the windbg application folder"
print " symchk /r c:\\windows\\system32\\ntdll.dll /s SRV*c:\\symbols*http://msdl.microsoft.com/download/symbols"
print ""
print " Restart windbg and try again"
exit(1)
def getPEBAddress():
global cpebaddress
if cpebaddress == 0:
peb = getPEBInfo()
cpebaddress = peb.getAddress()
return cpebaddress
def getTEBInfo():
return pykd.typedVar("_TEB", pykd.getImplicitThread())
def getTEBAddress():
tebinfo = pykd.dbgCommand("!teb")
if len(tebinfo) > 0:
teblines = tebinfo.split("\n")
tebline = teblines[0]
tebparts = tebline.split(" ")
if len(tebparts) > 2:
return hexStrToInt(tebparts[2])
# slow
teb = getTEBInfo()
return int(teb.Self)
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 hexptr2bin(hexptr):
"""
Input must be a int
output : bytes in little endian
"""
return struct.pack('<L', hexptr)
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 addrToInt(address):
"""
Convert a textual address to an integer
Arguments:
address - the address
Return:
int - the address value
"""
address = address.replace("\\x", "")
return hexStrToInt(address)
def isAddress(address):
"""
Check if a string is an address / consists of hex chars only
Arguments:
string - the string to check
Return:
Boolean - True if the address string only contains hex bytes
"""
address = address.replace("\\x", "")
if len(address) > 16:
return False
return set(address.upper()) <= set("ABCDEF1234567890")
def intToHex(address):
if arch == 32:
return "0x%08x" % address
if arch == 64:
return "0x%016x" % address
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 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 getPyKDVersion():
currentversion = pykd.version
currversion = ""
for versionpart in currentversion:
if versionpart != " ":
if versionpart == ",":
currversion += "."
else:
currversion += str(versionpart)
currversion = currversion.strip(".")
return currversion
def isPyKDVersionCompatible(currentversion, requiredversion):
# current version should be at least requiredversion
if currentversion == requiredversion:
return True
else:
currentparts = currentversion.split(".")
requiredparts = requiredversion.split(".")
if len(requiredparts) > len(currentparts):
delta = len(requiredparts) - len(currentparts)
cnt = 0
while cnt < delta:
currentparts.append("0")
cnt += 1
cnt = 0
while cnt < len(requiredparts):
if int(currentparts[cnt]) < int(requiredparts[cnt]):
return False
if int(currentparts[cnt]) > int(requiredparts[cnt]):
return True
cnt += 1
return True
def checkVersion():
pykdurl = "https://github.com/corelan/windbglib/raw/master/pykd/pykd.zip"
pykdurl03 = "https://github.com/corelan/windbglib/raw/master/pykd/pykd03.zip"
pykdversion_needed = "0.2.0.29"
if arch == 64:
pykdversion_needed = "0.2.0.29"
currversion = getPyKDVersion()
if not isPyKDVersionCompatible(currversion, pykdversion_needed):
print "*******************************************************************************************"
print " You are running the wrong version of PyKD, please update "
print " Installed version : %s " % currversion
print " Required version : %s" % pykdversion_needed
print " You can get an updated PyKD version from one of the following sources:"
print " - %s (preferred)" % pykdurl
print " (unzip with 7zip)"
print " - http://pykd.codeplex.com (newer versions may not work !)"
print "*******************************************************************************************"
import sys
sys.exit()
return
if pykdversion_needed != currversion:
# version must be higher
print "*******************************************************************************************"
print " You are running a newer version of pykd.pyd"
print " mona.py was tested against v%s" % pykdversion_needed
print " and not against v%s" % currversion
print " This version may not work properly."
print " If you are having issues, I recommend to download the correct version from"
print " %s" % pykdurl
print " (unzip with 7zip)"
if currversion.startswith("0.3"):
print ""
print " NOTE: PyKD v%s requires msdia120.dll, which only gets installed via Visual Studio 2013 (yup, I know)" % currversion
print " Alternatively, you can use the copy of msdia120.dll from the pykd.pyd file"
print " (%s), but use this file at your own risk" % pykdurl03
print "*******************************************************************************************"
return
def getModulesFromPEB():
global PEBModList
PEBModList = {}
peb = getPEBInfo()
imagenames = []
# http://www.nirsoft.net/kernel_struct/vista/PEB.html
# http://www.nirsoft.net/kernel_struct/vista/PEB_LDR_DATA.html
# http://www.nirsoft.net/kernel_struct/vista/LDR_DATA_TABLE_ENTRY.html
# The usage of _LDR_DATA_TABLE_ENTRY.SizeOfImage is very confusing and appears to actually contain the module base
offset = 0x10
if arch == 64:
offset = 0x30
moduleLst = pykd.typedVarList(peb.Ldr.deref().InLoadOrderModuleList, "ntdll!_LDR_DATA_TABLE_ENTRY",
"InMemoryOrderLinks.Flink")
if len(PEBModList) == 0:
for mod in moduleLst:
thismod = pykd.loadUnicodeString(mod.BaseDllName).encode("utf8")
modparts = thismod.split("\\")
modulename = modparts[len(modparts) - 1]
fullpath = thismod
exename = modulename
addtolist = True
moduleparts = modulename.split(".")
imagename = ""
if len(moduleparts) == 1:
imagename = moduleparts[0]
cnt = 0
while cnt < len(moduleparts) - 1:
imagename = imagename + moduleparts[cnt] + "."
cnt += 1
imagename = imagename.strip(".")
# no windbg love for + - .
imagename = imagename.replace("+", "_")
imagename = imagename.replace("-", "_")
imagename = imagename.replace(".", "_")
if imagename in imagenames:
# duplicate name ? Append _<baseaddress>
# mod.getAddress() + offset = _LDR_DATA_TABLE_ENTRY.SizeOfImage
baseaddy = int(pykd.ptrPtr(mod.getAddress() + offset))
imagename = imagename + "_%08x" % baseaddy
# check if module can be loaded
try:
modcheck = pykd.module(imagename)
except:
# change to image+baseaddress
# mod.getAddress() + offset = _LDR_DATA_TABLE_ENTRY.SizeOfImage
baseaddy = int(pykd.ptrPtr(mod.getAddress() + offset))
imagename = "image%08x" % baseaddy
try:
modcheck = pykd.module(imagename)
except:
# try with base addy
try:
modcheck = pykd.module(baseaddy)
imagename = modcheck.name()
# print "Name: %s" % modcheck.name()
# print "Imagename: %s" % modcheck.image()
except:
# try finding it with windbg 'ln'
cmd2run = "ln 0x%08x" % baseaddy
output = pykd.dbgCommand(cmd2run)
if "!__ImageBase" in output:
outputlines = output.split("\n")
for l in outputlines:
if "!__ImageBase" in l:
lparts = l.split("!__ImageBase")
leftpart = lparts[0]
leftparts = leftpart.split(" ")
imagename = leftparts[len(leftparts) - 1]
try:
modcheck = pykd.module(imagename)
except:
print ""
print " *** Error parsing module '%s' ('%s') at 0x%08x ***" % (
imagename, modulename, baseaddy)
print " *** Please open a github issue ticket at https://github.com/corelan/windbglib ***"
print " *** and provide the output of the following 2 windbg commands in the ticket: ***"
print " lm"
print " !peb"
print " *** Thanks"
print ""
addtolist = False
if addtolist:
imagenames.append(imagename)
PEBModList[imagename] = [exename, fullpath]
return moduleLst
def getModuleFromAddress(address):
offset = 0x20
if arch == 64:
offset = 0x40
global ModuleCache
# try fastest way first
try:
thismod = pykd.module(address)
# if that worked, we could add it to the cache if needed
modbase = thismod.begin()
modsize = thismod.size()
modend = modbase + modsize
modulename = thismod.image()
ModuleCache[modulename] = [modbase, modsize]
if (address >= modbase) and (address <= modend):
return thismod
except:
pass
# maybe cached
for modname in ModuleCache:
modparts = ModuleCache[modname]
# 0 : base
# 1 : size
modbase = modparts[0]
modsize = modparts[1]
modend = modbase + modsize
if (address >= modbase) and (address <= modend):
# print "0x%08x belongs to %s" % (address,modname)
return pykd.module(modname)
# not cached, find it
moduleLst = getModulesFromPEB()
for mod in moduleLst:
thismod = pykd.loadUnicodeString(mod.BaseDllName).encode("utf8")
modparts = thismod.split("\\")
modulename = modparts[len(modparts) - 1].lower()
moduleparts = modulename.split(".")
modulename = ""
if len(moduleparts) == 1:
modulename = moduleparts[0]
cnt = 0
while cnt < len(moduleparts) - 1:
modulename = modulename + moduleparts[cnt] + "."
cnt += 1
modulename = modulename.strip(".")
thismod = ""
imagename = ""
try:
moduleLst = getModulesFromPEB()
for mod in moduleLst:
thismod = pykd.loadUnicodeString(mod.BaseDllName).encode("utf8")
modparts = thismod.split("\\")
thismodname = modparts[len(modparts) - 1]
moduleparts = thismodname.split(".")
if len(moduleparts) > 1:
thismodname = ""
cnt = 0
while cnt < len(moduleparts) - 1:
thismodname = thismodname + moduleparts[cnt] + "."
cnt += 1
thismodname = thismodname.strip(".")
if thismodname.lower() == modulename.lower():
# mod.getAddress() + offset = _LDR_DATA_TABLE_ENTRY.SizeOfImage
baseaddy = int(pykd.ptrPtr(mod.getAddress() + offset))
baseaddr = "%08x" % baseaddy
lmcommand = pykd.dbgCommand("lm")
lmlines = lmcommand.split("\n")
foundinlm = False
for lmline in lmlines:
linepieces = lmline.split(" ")
if linepieces[0].upper() == baseaddr.upper():
cnt = 2
while cnt < len(linepieces) and not foundinlm:
if linepieces[cnt].strip(" ") != "":
imagename = linepieces[cnt]
foundinlm = True
break
cnt += 1
if not foundinlm:
imagename = "image%s" % baseaddr.lower()
break
except:
pykd.dprintln(traceback.format_exc())
try:
modulename = imagename
thismod = pykd.module(imagename)
modbase = thismod.begin()
modsize = thismod.size()
modend = modbase + modsize
ModuleCache[modulename] = [modbase, modsize]
if (address >= modbase) and (address <= modend):
return thismod
except:
thismod = pykd.module(address)
modbase = thismod.begin()
modsize = thismod.size()
modend = modbase + modsize
modulename = thismod.image()
ModuleCache[modulename] = [modbase, modsize]
if (address >= modbase) and (address <= modend):
return thismod
return None
def getImageBaseOnDisk(fullpath):
with open(fullpath, "rb") as pe:
data = pe.read()
nt_header_offset = struct.unpack("<I", data[0x3c:0x40])[0]
optional_header_offset = nt_header_offset + 0x18
magic = struct.unpack("<H", data[optional_header_offset:optional_header_offset+2])[0]
if magic == 0x10b:
#32bit
imageBase = struct.unpack("<I", data[optional_header_offset+28:optional_header_offset+28+4])[0]
else:
# 64bit
imageBase = struct.unpack("<Q", data[optional_header_offset+24:optional_header_offset+24+8])[0]
return imageBase
# Classes
class Debugger:
MemoryPages = {}
AsmCache = {}
OpcodeCache = {}
def __init__(self):
self.MemoryPages = {}
self.AsmCache = {}
self.allmodules = {}
self.OpcodeCache = {}
self.ModCache = {}
self.fillAsmCache()
self.knowledgedb = "windbglib.db"
def setKBDB(self, filename="windbglib.db"):
self.knowledgedb = filename
return
def getKBDB(self):
return self.knowledgedb
def remoteVirtualAlloc(self, size=0x10000, interactive=False):
PAGE_EXECUTE_READWRITE = 0x40
VIRTUAL_MEM = (0x1000 | 0x2000)
vaddr = self.rVirtualAlloc(0, size, VIRTUAL_MEM, PAGE_EXECUTE_READWRITE)
return vaddr
def rVirtualAlloc(self, lpAddress, dwSize, flAllocationType, flProtect):
PROCESS_VM_OPERATION = 0x0008
kernel32 = ctypes.windll.kernel32
pid = self.getDebuggedPid()
hprocess = kernel32.OpenProcess(PROCESS_VM_OPERATION, False, pid)
vaddr = kernel32.VirtualAllocEx(hprocess, lpAddress, dwSize, flAllocationType, flProtect)
kernel32.CloseHandle(hprocess)
return vaddr
def rVirtualProtect(self, lpAddress, dwSize, flNewProtect, lpflOldProtect=0):
PROCESS_VM_OPERATION = 0x0008
kernel32 = ctypes.windll.kernel32
pid = self.getDebuggedPid()
hprocess = kernel32.OpenProcess(PROCESS_VM_OPERATION, False, pid)
pold_protect = ctypes.addressof(ctypes.c_int32(0))
returnval = kernel32.VirtualProtectEx(hprocess, lpAddress, dwSize, flNewProtect, pold_protect)
kernel32.CloseHandle(hprocess)
return returnval
def getAddress(self, functionname):
functionparts = functionname.split(".")
if len(functionparts) > 1:
modulename = functionparts[0]
functionname = functionparts[1]
funcref = "%s!%s" % (modulename, functionname)
cmd2run = "ln %s" % funcref
output = self.nativeCommand(cmd2run)
if "Exact matches" in output:
outputlines = output.split("\n")
for outputline in outputlines:
if "(" in outputline.lower():
lineparts = outputline.split(")")
address = lineparts[0].replace("(", "")
return hexStrToInt(address)
else:
return 0
else:
return 0
def getCurrentTEBAddress(self):
return getTEBAddress()
"""
AsmCache
"""
def fillAsmCache(self):
self.AsmCache["push eax"] = "\x50"
self.AsmCache["push ecx"] = "\x51"
self.AsmCache["push edx"] = "\x52"
self.AsmCache["push ebx"] = "\x53"
self.AsmCache["push esp"] = "\x54"
self.AsmCache["push ebp"] = "\x55"
self.AsmCache["push esi"] = "\x56"
self.AsmCache["push edi"] = "\x57"
self.AsmCache["pop eax"] = "\x58"
self.AsmCache["pop ecx"] = "\x59"
self.AsmCache["pop edx"] = "\x5a"
self.AsmCache["pop ebx"] = "\x5b"
self.AsmCache["pop esp"] = "\x5c"
self.AsmCache["pop ebp"] = "\x5d"
self.AsmCache["pop esi"] = "\x5e"
self.AsmCache["pop edi"] = "\x5f"
self.AsmCache["jmp eax"] = "\xff\xe0"
self.AsmCache["jmp ecx"] = "\xff\xe1"
self.AsmCache["jmp edx"] = "\xff\xe2"
self.AsmCache["jmp ebx"] = "\xff\xe3"
self.AsmCache["jmp esp"] = "\xff\xe4"
self.AsmCache["jmp ebp"] = "\xff\xe5"
self.AsmCache["jmp esi"] = "\xff\xe6"
self.AsmCache["jmp edi"] = "\xff\xe7"
self.AsmCache["call eax"] = "\xff\xd0"
self.AsmCache["call ecx"] = "\xff\xd1"
self.AsmCache["call edx"] = "\xff\xd2"
self.AsmCache["call ebx"] = "\xff\xd3"
self.AsmCache["call esp"] = "\xff\xd4"
self.AsmCache["call ebp"] = "\xff\xd5"
self.AsmCache["call esi"] = "\xff\xd6"
self.AsmCache["call edi"] = "\xff\xd7"
self.AsmCache["jmp [eax]"] = "\xff\x20"
self.AsmCache["jmp [ecx]"] = "\xff\x21"
self.AsmCache["jmp [edx]"] = "\xff\x22"
self.AsmCache["jmp [ebx]"] = "\xff\x23"
self.AsmCache["jmp [esp]"] = "\xff\x24"
self.AsmCache["jmp [ebp]"] = "\xff\x25"
self.AsmCache["jmp [esi]"] = "\xff\x26"
self.AsmCache["jmp [edi]"] = "\xff\x27"
self.AsmCache["call [eax]"] = "\xff\x10"
self.AsmCache["call [ecx]"] = "\xff\x11"
self.AsmCache["call [edx]"] = "\xff\x12"
self.AsmCache["call [ebx]"] = "\xff\x13"
self.AsmCache["call [esp]"] = "\xff\x14"
self.AsmCache["call [ebp]"] = "\xff\x15"
self.AsmCache["call [esi]"] = "\xff\x16"
self.AsmCache["call [edi]"] = "\xff\x17"
self.AsmCache["xchg eax,esp"] = "\x94"
self.AsmCache["xchg ecx,esp"] = "\x87\xcc"
self.AsmCache["xchg edx,esp"] = "\x87\xd4"
self.AsmCache["xchg ebx,esp"] = "\x87\xdc"
self.AsmCache["xchg ebp,esp"] = "\x87\xec"
self.AsmCache["xchg edi,esp"] = "\x87\xfc"
self.AsmCache["xchg esi,esp"] = "\x87\xf4"
self.AsmCache["xchg esp,eax"] = "\x94"
self.AsmCache["xchg esp,ecx"] = "\x87\xcc"
self.AsmCache["xchg esp,edx"] = "\x87\xd4"
self.AsmCache["xchg esp,ebx"] = "\x87\xdc"
self.AsmCache["xchg esp,ebp"] = "\x87\xec"
self.AsmCache["xchg esp,edi"] = "\x87\xfc"
self.AsmCache["xchg esp,esi"] = "\x87\xf4"
self.AsmCache["pushad"] = "\x60"
self.AsmCache["popad"] = "\x61"
for offset in xrange(4, 80, 4):
thisasm = "\x83\xc4" + hex2bin("%02x" % offset)
self.AsmCache["add esp,%02x" % offset] = thisasm
self.AsmCache["add esp,%x" % offset] = thisasm
self.AsmCache["retn"] = "\xc3"
self.AsmCache["retf"] = "\xdb"
for offset in xrange(0, 80, 2):
thisasm = "\xc2" + hex2bin("%02x" % offset) + "\x00"
self.AsmCache["retn %02x" % offset] = thisasm
self.AsmCache["retn %x" % offset] = thisasm
self.AsmCache["retn 0x%02x" % offset] = thisasm
return
"""
Knowledge
"""
def addKnowledge(self, id, object, force_add=0):
allk = self.readKnowledgeDB()
if not id in allk:
allk[id] = object
else:
if object.__class__.__name__ == "dict":
for odictkey in object:
allk[id][odictkey] = object[odictkey]
with open(self.knowledgedb, "wb") as fh:
pickle.dump(allk, fh, -1)
return
def getKnowledge(self, id):
allk = self.readKnowledgeDB()
if id in allk:
return allk[id]
else:
return None
def readKnowledgeDB(self):
allk = {}
try:
with open(self.knowledgedb, "rb") as fh:
allk = pickle.load(fh)
except:
pass
return allk
def listKnowledge(self):
allk = self.readKnowledgeDB()
allid = []
for thisk in allk:
allid.append(thisk)
return allid
def cleanKnowledge(self):
try:
os.remove(self.knowledgedb)
except:
try:
with open(self.knowledgedb, "wb") as fh:
pickle.dump({}, fh, -1)
except:
pass
pass
return
def forgetKnowledge(self, id, entry=""):
allk = self.readKnowledgeDB()
if entry == "":
if id in allk:
del allk[id]
else:
# find the entry
if id in allk:
thisidkb = allk[id]
if entry in thisidkb:
del thisidkb[entry]
allk[id] = thisidkb
with open(self.knowledgedb, "wb") as fh:
pickle.dump(allk, fh, -1)
return
def cleanUp(self):
self.cleanKnowledge()
return
"""
Placeholders
"""
def analysecode(self):
return
def isAnalysed(self):
return True
"""
LOGGING
"""
def toAsciiOnly(self, message):
newchar = []
for thischar in message:
if ord(thischar) >= 20 and ord(thischar) <= 126:
newchar.append(thischar)
else:
newchar.append(".")
return "".join(newchar)
def createLogWindow(self):
return
def log(self, message, highlight=0, address=None, focus=0):
if not address == None:
message = intToHex(address) + " | " + message
showdml = False
if highlight == 1:
showdml = True
message = "<b>" + message + "</b>"
pykd.dprintln(self.toAsciiOnly(message), showdml)
def logLines(self, message, highlight=0, address=None, focus=0):
allLines = message.split('\n')
linecnt = 0
messageprefix = ""
if not address == None:
messageprefix = " " * 10
messageprefix += " | "
for line in allLines:
if linecnt == 0:
self.log(line, highlight, address)
else:
self.log(messageprefix + line, highlight)
linecnt += 1
def updateLog(self):
return
def setStatusBar(self, message):
return
def error(self, message):
return
"""
Process stuff
"""
def getDebuggedName(self):
# http://www.nirsoft.net/kernel_struct/vista/PEB.html
# http://www.nirsoft.net/kernel_struct/vista/RTL_USER_PROCESS_PARAMETERS.html
peb = getPEBInfo()
ProcessParameters = peb.ProcessParameters
offset = 0x38
if arch == 64:
offset = 0x60
# ProcessParameters + offset = _RTL_USER_PROCESS_PARAMETERS.ImagePathName(_UNICODE_STRING)
sImageFile = pykd.loadUnicodeString(int(ProcessParameters) + offset).encode("utf8")
sImageFilepieces = sImageFile.split("\\")
return sImageFilepieces[len(sImageFilepieces) - 1]
def getDebuggedPid(self):
# http://www.nirsoft.net/kernel_struct/vista/TEB.html
# http://www.nirsoft.net/kernel_struct/vista/CLIENT_ID.html
teb = getTEBAddress()
offset = 0x20
if arch == 64:
offset = 0x40
# _TEB.ClientId(CLIENT_ID).UniqueProcess(PVOID)
pid = pykd.ptrDWord(teb + offset)
return pid
"""
OS stuff
"""
def getOsRelease(self):
peb = getPEBInfo()
majorversion = int(peb.OSMajorVersion)
minorversion = int(peb.OSMinorVersion)
buildversion = int(peb.OSBuildNumber)
osversion = str(majorversion) + "." + str(minorversion) + "." + str(buildversion)
return osversion
def getOsVersion(self):
return getOSVersion()
def getPyKDVersionNr(self):
return getPyKDVersion()
"""
Registers
"""
def getRegs(self):
regs = []
if arch == 32:
regs = Registers32BitsOrder
regs.append("EIP")
if arch == 64:
regs = Registers64BitsOrder
regs.append("RIP")
reginfo = {}
for thisreg in regs:
reginfo[thisreg.upper()] = int(pykd.reg(thisreg.lower()))
return reginfo
"""
Commands
"""
def nativeCommand(self, cmd2run):
try:
output = pykd.dbgCommand(cmd2run)
return output
except:
# dprintln(traceback.format_exc())
# dprintln(cmd2run)
return ""
"""
SEH
"""
def getSehChain(self):
# http://www.nirsoft.net/kernel_struct/vista/TEB.html
# http://www.nirsoft.net/kernel_struct/vista/NT_TIB.html
# http://www.nirsoft.net/kernel_struct/vista/EXCEPTION_REGISTRATION_RECORD.html
# x64 has no SEH chain
if arch == 64:
return []
sehchain = []
# get top of chain
teb = getTEBAddress()
# _TEB.NtTib(NT_TIB).ExceptionList(PEXCEPTION_REGISTRATION_RECORD)
nextrecord = pykd.ptrPtr(teb)
validrecord = True
while nextrecord != 0xffffffff and pykd.isValid(nextrecord):
# _EXCEPTION_REGISTRATION_RECORD.Next(PEXCEPTION_REGISTRATION_RECORD)
nseh = pykd.ptrPtr(nextrecord)
# _EXCEPTION_REGISTRATION_RECORD.Handler(PEXCEPTION_DISPOSITION)
seh = pykd.ptrPtr(nextrecord + 4)
sehrecord = [nextrecord, seh]
sehchain.append(sehrecord)
nextrecord = nseh
return sehchain
"""
Memory
"""
def readMemory(self, location, size):
try:
# return hex2bin(''.join(("%02X" % n) for n in loadBytes(location,size)))
return pykd.loadChars(location, size)
except:
return ""