forked from pwndbg/pwndbg
/
ida_script.py
151 lines (113 loc) · 4.01 KB
/
ida_script.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import datetime
import threading
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
from xml.sax.saxutils import escape
import idaapi
import idautils
import idc
# Wait for any processing to get done
idaapi.autoWait()
# On Windows with NTFS filesystem a filepath with ':'
# is treated as NTFS ADS (Alternative Data Stream)
# and so saving file with such name fails
dt = datetime.datetime.now().isoformat().replace(':', '-')
# Save the database so nothing gets lost.
if idaapi.IDA_SDK_VERSION >= 700:
idaapi.save_database(idc.GetIdbPath() + '.' + dt)
else:
idc.SaveBase(idc.GetIdbPath() + '.' + dt)
DEBUG_MARSHALLING = False
def create_marshaller(use_format=None, just_to_str=False):
assert use_format or just_to_str, 'Either pass format to use or make it converting the value to str.'
def wrapper(_marshaller, value, appender):
if use_format:
marshalled = use_format % value
elif just_to_str:
marshalled = '<value><string>%s</string></value>' % escape(str(value))
if DEBUG_MARSHALLING:
print("Marshalled: '%s'" % marshalled)
appender(marshalled)
return wrapper
xmlrpclib.Marshaller.dispatch[type(0L)] = create_marshaller("<value><i8>%d</i8></value>")
xmlrpclib.Marshaller.dispatch[type(0)] = create_marshaller("<value><i8>%d</i8></value>")
xmlrpclib.Marshaller.dispatch[idaapi.cfuncptr_t] = create_marshaller(just_to_str=True)
host = '127.0.0.1'
port = 31337
orig_LineA = idc.LineA
def LineA(*a, **kw):
v = orig_LineA(*a, **kw)
if v and v.startswith('\x01\x04; '):
v = v[4:]
return v
idc.LineA = LineA
mutex = threading.Condition()
def wrap(f):
def wrapper(*a, **kw):
rv = []
error = []
def work():
try:
result = f(*a, **kw)
rv.append(result)
except Exception as e:
error.append(e)
with mutex:
flags = idaapi.MFF_WRITE
if f == idc.SetColor:
flags |= idaapi.MFF_NOWAIT
rv.append(None)
idaapi.execute_sync(work, flags)
if error:
msg = 'Failed on calling {}.{} with args: {}, kwargs: {}\nException: {}' \
.format(f.__module__, f.__name__, a, kw, str(error[0]))
print('[!!!] ERROR:', msg)
raise error[0]
return rv[0]
return wrapper
def register_module(module):
for name, function in module.__dict__.items():
if hasattr(function, '__call__'):
server.register_function(wrap(function), name)
def decompile(addr):
"""
Function that overwrites `idaapi.decompile` for xmlrpc so that instead
of throwing an exception on `idaapi.DecompilationFailure` it just returns `None`.
(so that we don't have to parse xmlrpc Fault's exception string on pwndbg side
as it differs between IDA versions).
"""
try:
return idaapi.decompile(addr)
except idaapi.DecompilationFailure:
return None
def versions():
"""Returns IDA & Python versions"""
import sys
return {
'python': sys.version,
'ida': idaapi.get_kernel_version(),
'hexrays': idaapi.get_hexrays_version() if idaapi.init_hexrays_plugin() else None
}
server = SimpleXMLRPCServer((host, port), logRequests=True, allow_none=True)
register_module(idc)
register_module(idautils)
register_module(idaapi)
server.register_function(lambda a: eval(a, globals(), locals()), 'eval')
server.register_function(decompile) # overwrites idaapi/ida_hexrays.decompie
server.register_function(versions)
server.register_introspection_functions()
print('IDA Pro xmlrpc hosted on http://%s:%s' % (host, port))
print('Call `shutdown()` to shutdown the IDA Pro xmlrpc server.')
thread = threading.Thread(target=server.serve_forever)
thread.daemon = True
thread.start()
def shutdown():
global server
global thread
server.shutdown()
server.server_close()
del server
del thread