-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmega.py
More file actions
374 lines (303 loc) · 12.6 KB
/
mega.py
File metadata and controls
374 lines (303 loc) · 12.6 KB
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
import platform
import os
import collections
import argparse
import ctypes
from os.path import abspath, join, dirname
import re
import logging
try:
import capstone
except ImportError:
print 'install capstone python binarys'
exit(1)
try:
from pefile import PE
except ImportError as e:
print 'install pefile'
exit(2)
ARCH = ctypes.sizeof(ctypes.c_voidp)*8
DEFAULT_SRV = "srv*https://msdl.microsoft.com/download/symbols"
SYMBOL_SERVER_ENV_VAR = "_NT_SYMBOL_PATH"
MAX_PATH = 260
IMAGE_FILE_MACHINE_I386 = 0x014c
IMAGE_FILE_MACHINE_AMD64 = 0x8664
SSRVOPT_GUIDPTR = 0x00000008
class SymOpts(object):
SYMOPT_EXACT_SYMBOLS = 0x00000400
SYMOPT_DEBUG = 0x80000000
SYMOPT_UNDNAME = 0x00000002
class GUID(ctypes.Structure):
_fields_ = [
('Data1', ctypes.c_long),
('Data2', ctypes.c_short),
('Data3', ctypes.c_short),
('Data4', ctypes.c_char*8),
]
class SYMSRV_INDEX_INFO(ctypes.Structure):
_fields_ = [
('sizeofstruct', ctypes.c_uint),
('file', ctypes.c_char*(MAX_PATH+1)),
('stripped', ctypes.c_uint),
('timestamp', ctypes.c_uint),
('size', ctypes.c_uint),
('dbgfile', ctypes.c_char*(MAX_PATH+1)),
('pdbfile', ctypes.c_char*(MAX_PATH+1)),
('guid', GUID),
('sig', ctypes.c_uint),
('age', ctypes.c_uint)
]
class SYMBOL_INFO(ctypes.Structure):
_fields_ = [
('SizeOfStruct', ctypes.c_uint),
('TypeIndex', ctypes.c_uint),
('Reserved', ctypes.c_ulonglong*2),
('Index', ctypes.c_uint),
('Size', ctypes.c_uint),
('ModBase', ctypes.c_ulonglong),
('Flags', ctypes.c_uint),
('Value', ctypes.c_ulonglong),
('Address', ctypes.c_ulonglong),
('Register', ctypes.c_uint),
('Scope', ctypes.c_uint),
('Tag', ctypes.c_uint),
('NameLen', ctypes.c_uint),
('MaxNameLen', ctypes.c_uint),
('Name', ctypes.c_char*1)
]
class PeInfo(object):
def __init__(self, filepath, pdbpath, symbols=None):
self.filepath = filepath
self.pdbpath = pdbpath
self.symbols = symbols or []
class SymSession(object):
ctypes.windll.kernel32.LoadLibraryA(
join(dirname(abspath(__file__)), '%d' % ARCH, 'dbghelp.dll'))
ctypes.windll.kernel32.LoadLibraryA('symsrv')
dbghelp = ctypes.windll.dbghelp
sid = 1
def __init__(self, server=None, debug=False, opts=SymOpts.SYMOPT_EXACT_SYMBOLS):
self.h = SymSession.sid
SymSession.sid += 1
self.bases = {}
self.session = None
self.debug = debug
self.opts = opts
if self.debug:
self.opts |= SymOpts.SYMOPT_DEBUG
self.srv = server
if self.srv is None:
self.srv = os.getenv(SYMBOL_SERVER_ENV_VAR, DEFAULT_SRV)
def init(self):
self.dbghelp.SymInitialize(self.h, None, 0)
self.dbghelp.SymSetOptions(self.opts)
if self.srv:
self.dbghelp.SymSetSearchPath(self.h, self.srv)
def cleanup(self):
unl = self.dbghelp.SymUnloadModule64
unl.argtypes = [ctypes.c_uint, ctypes.c_ulonglong]
for baseofdll in self.bases:
self.dbghelp.SymUnloadModule64(self.h, baseofdll)
self.dbghelp.SymCleanup(self.h)
def load(self, filepath, machine, sizeofImage, imageBase):
# no need to worry about wow redirection because we must match file arch
if machine != {32: IMAGE_FILE_MACHINE_I386, 64:
IMAGE_FILE_MACHINE_AMD64}[ARCH]:
raise Exception('Architecture mismatch. Python: x{}; file: x{}'.format(
ARCH, {64: 86, 32: 64}[ARCH]))
idxinfo = SYMSRV_INDEX_INFO(ctypes.sizeof(SYMSRV_INDEX_INFO))
_f = self.dbghelp.SymSrvGetFileIndexInfo
_f.restype = ctypes.c_uint
_f.argtypes = [ctypes.c_char_p, ctypes.POINTER(
SYMSRV_INDEX_INFO), ctypes.c_uint]
if not _f(filepath, ctypes.byref(idxinfo), 0):
raise Exception(
'failed SymSrvGetFileIndexInfo last error: %d' % ctypes.GetLastError())
_f = self.dbghelp.SymFindFileInPath
_f.restype = ctypes.c_uint
pdbpath = ctypes.create_string_buffer(MAX_PATH + 1)
_f.argtypes = [ctypes.c_uint,
ctypes.c_uint,
ctypes.c_char_p,
ctypes.POINTER(GUID),
ctypes.c_uint,
ctypes.c_uint,
ctypes.c_uint,
ctypes.c_char_p,
ctypes.c_uint,
ctypes.c_uint
]
if not _f(self.h,
0,
ctypes.c_char_p(idxinfo.pdbfile),
ctypes.byref(idxinfo.guid),
idxinfo.age,
0,
SSRVOPT_GUIDPTR,
pdbpath,
0,
0
):
raise Exception(
'failed SymFindFileInPath last error: %d' % ctypes.GetLastError())
_f = self.dbghelp.SymLoadModuleEx
_f.restype = ctypes.c_size_t
_f.argtypes = [ctypes.c_uint,
ctypes.c_uint,
ctypes.c_char_p,
ctypes.c_uint,
ctypes.c_ulonglong,
ctypes.c_uint,
ctypes.c_uint,
ctypes.c_uint
]
dllbase = _f(self.h,
0,
ctypes.c_char_p(filepath),
0,
imageBase,
sizeofImage,
0,
0
)
if not dllbase:
raise Exception(
'failed SymLoadModuleEx last error: %d' % ctypes.GetLastError())
if dllbase in self.bases:
raise Exception(
'{} already in bases: {}'.format(dllbase, self.bases))
self.bases[dllbase] = PeInfo(filepath, pdbpath)
return dllbase
def _fix_syminfo(self, syminfo):
Sym = collections.namedtuple('Symbol', ['Name', 'NameLen', 'MaxNameLen', 'Tag', 'Scope',
'Register', 'Address', 'Value', 'Flags', 'ModBase', 'Size', 'Index', 'TypeIndex'])
return Sym(ctypes.string_at(ctypes.addressof(syminfo)+SYMBOL_INFO.Name.offset), syminfo.NameLen, syminfo.MaxNameLen, syminfo.Tag, syminfo.Scope, syminfo.Register, syminfo.Address, syminfo.Value, syminfo.Flags, syminfo.ModBase, syminfo.Size, syminfo.Index, syminfo.TypeIndex)
def _enum_symbol_callback(self, syminfo, symsize, dllbase):
fixed = self._fix_syminfo(syminfo)
self.bases[dllbase].symbols.append(fixed)
def _get_callback(self, dllbase):
CALLBACK = ctypes.WINFUNCTYPE(None, ctypes.POINTER(
SYMBOL_INFO), ctypes.c_ulong, ctypes.c_void_p)
def callbackwrapper(syminfo, symsize, opq):
self._enum_symbol_callback(syminfo.contents, symsize, dllbase)
return CALLBACK(callbackwrapper)
def _load_symbols(self, dllbase, mask):
_f = self.dbghelp.SymEnumSymbols
_f.restype = ctypes.c_uint
_f.argtypes = [
ctypes.c_uint,
ctypes.c_ulonglong,
ctypes.c_char_p,
ctypes.c_void_p,
ctypes.c_void_p,
]
_f(self.h, dllbase, mask, self._get_callback(dllbase), None)
def find(self, dllbase, target=None, mask='*'):
"""
dllbase: returned from load function
targets: regex rule to match symobl
mask: internal mask to pass to SymEnumSymbols (windbg format), will only be used the first time symbols are loaded
"""
if dllbase not in self.bases:
raise Exception(
'given base: {} does not exist in {}'.format(dllbase, self.bases))
if not self.bases[dllbase].symbols:
self._load_symbols(dllbase, mask)
if target is None:
return self.bases[dllbase].symbols
t = re.compile(target)
res = []
for sym in self.bases[dllbase].symbols:
if t.match(sym.Name):
res.append(sym)
return res
def patch(f, outfile, nav, stomp, stomp_is_isdirty):
nav_start = nav.Address - nav.ModBase
target_call_address = stomp.Address - stomp.ModBase
# physaddr = f.get_physical_by_rva(nav_start)
md = capstone.Cs(capstone.CS_ARCH_X86, {
64: capstone.CS_MODE_64, 32: capstone.CS_MODE_32}[ARCH])
md.detail = True
code = f.get_data(nav_start, 0x300) # should be more than enough
possible_addresses = []
for i in md.disasm(code, nav_start):
# print "{:X}:\t{}\t{}".format(i.address, i.mnemonic, i.op_str)
if i.mnemonic.lower() == 'call' and len(i.operands) == 1:
if target_call_address == i.operands[0].imm:
# print 'found it?', hex(i.address+ i.size)
possible_addresses.append(i.address + i.size-nav_start)
patch_addr = 0
for a in possible_addresses:
itr = iter(md.disasm(code[a:], nav_start+a))
i = itr.next()
# print "{:X}:\t{}\t{}".format(i.address, i.mnemonic, i.op_str)
if i.bytes != '\x85\xC0': # test eax,eax
continue
test_eaxeax_addr = i.address
i = itr.next()
# print "{:X}:\t{}\t{}".format(i.address, i.mnemonic, i.op_str)
if i.mnemonic.lower() not in (['jnz', 'jne'] if stomp_is_isdirty else ['jz', 'je']):
continue
patch = '\xff\xc0' if stomp_is_isdirty else '\x31'
patch_addr = test_eaxeax_addr
break
if not patch_addr:
raise Exception('failed finding address in any of the possible options: {}'.format(
possible_addresses))
print 'patching {:X}'.format(patch_addr)
f.set_bytes_at_rva(patch_addr, patch)
f.write(outfile)
print 'done'
def main(infile, outfile, dbg):
f = PE(infile)
s = SymSession(debug=dbg, opts=SymOpts.SYMOPT_UNDNAME)
s.init()
dllbase = s.load(infile, f.FILE_HEADER.Machine,
f.OPTIONAL_HEADER.SizeOfImage, f.OPTIONAL_HEADER.ImageBase)
# just to preload symbosl and filter out the irrelevant ones
s.find(dllbase, mask="*CAddressEditBox*")
stomp_is_isdirty = False
stomp_func = s.find(dllbase, target=".*_CanStompCurrentText.*")
if len(stomp_func) == 0:
stomp_func = s.find(dllbase, target=".*_IsDirty.*")
stomp_is_isdirty = True # this happens on win7 x64
if len(stomp_func) != 1:
raise Exception(
'found more/less funcs than unexpected for _CanStompCurrentText: {}'.format(stomp_func))
stomp_func = stomp_func[0]
nav_func = s.find(dllbase, target=".*_NavigateAfterParse.*")
if len(nav_func) != 1:
raise Exception(
'found more/less funcs than unexpected for _NavigateAfterParse: {}'.format(nav_func))
nav_func = nav_func[0]
s.cleanup()
if dbg or not outfile:
# TODO: print version and file info
print infile
print ' base: {:X}'.format(dllbase)
print ' | +0x{1:X}: {0}'.format(nav_func.Name,
nav_func.Address-dllbase)
print ' | +0x{1:X}: {0}'.format(
stomp_func.Name, stomp_func.Address-dllbase)
if outfile:
print 'trying to patching'
patch(f, outfile, nav_func, stomp_func, stomp_is_isdirty)
if __name__ == '__main__':
if platform.machine() == 'AMD64' and platform.architecture()[0] == '32bit':
print('this is a 64 bit windows, please run using a 64 bit python')
exit(1)
defpath = r'C:\windows\system32\explorerframe.dll'
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='infile',
default=defpath, help='(default: %s)' % defpath)
parser.add_argument('-o', dest='outfile')
parser.add_argument('-d', help='pass DEBUG option to dbghelp (use dbgview)',
dest='debug', default=False, action='store_true')
# TODO: add logging
args = parser.parse_args()
try:
main(args.infile, args.outfile, args.debug)
except Exception as e:
print 'to debug symbol loading pass `-d` and run dbgview'
print
raise