-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrz-ida.py
executable file
·570 lines (465 loc) · 15.5 KB
/
rz-ida.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
#!/usr/bin/env python
""" Convert IDB and IDC from IDA Pro into a Rizin script
$ rz-ida.py -h
usage: rz-ida.py [-h] (-idb IDB_FILE | -idc IDC_FILE) -o OUT_FILE [-nc | -nf | -nn]
Export IDB or IDC from IDA into a Rizin initialization script
optional arguments:
-h, --help show this help message and exit
-idb IDB_FILE, --IDBFile IDB_FILE
Path to the IDB file
-idc IDC_FILE, --IDCFile IDC_FILE
Path to the IDC file
-o OUT_FILE, --OutputFile OUT_FILE
Export to a specified file path
-nc, --no-comments Don't convert comments
-nf, --no-functions Don't convert functions
-nn, --no-names Don't convert names
"""
__author__ = (
"Itay Cohen (@megabeets_), Maxime Morin (@maijin), Sergi Alvarez (@pancake)"
)
import argparse
import re
import base64
import idb
# CONSTANTS
FLAG_PREFIX = "ida."
def get_args():
""" Handle arguments using argparse
"""
arg_parser = argparse.ArgumentParser(
description="Export IDB or IDC from IDA into a radare2 initialization script"
)
arg_group_files = arg_parser.add_mutually_exclusive_group(required=True)
arg_group_files.add_argument(
"-idb",
"--IDBFile",
action="store",
dest="idb_file",
help="Path to the IDB file",
)
arg_group_files.add_argument(
"-idc",
"--IDCFile",
action="store",
dest="idc_file",
help="Path to the IDC file",
)
arg_parser.add_argument(
"-o",
"--OutputFile",
action="store",
dest="out_file",
required=True,
help="Export to a specified file path",
)
arg_parser.add_argument(
"-nc",
"--no-comments",
dest="is_comments",
action="store_false",
help="Don't convert comments",
)
arg_parser.add_argument(
"-nf",
"--no-functions",
dest="is_functions",
action="store_false",
help="Don't convert functions",
)
arg_parser.add_argument(
"-nn",
"--no-names",
dest="is_names",
action="store_false",
help="Don't convert names",
)
arg_parser.set_defaults(is_comments=True, is_functions=True, is_names=True)
args = arg_parser.parse_args()
return args
def write_header():
outfile.write(
"""########################################################
#
# This file was generated by the rz-ida.py script.
# Source: https://github.com/rizin/rizin-extras
#
########################################################
"""
)
###
# IDB Parsing
#
def idb_to_rizin_comments(api, textseg):
""" Convert comments from a specific text segments in the IDB
"""
for ea in range(textseg, api.idc.SegEnd(textseg)):
try:
flags = api.ida_bytes.get_cmt(ea, True)
if flags != "":
outfile.write(
"CCu base64:{b64} @ {addr}\n".format(
b64=base64.b64encode(flags.encode(encoding="UTF-8")).decode(
"utf-8"
),
addr=str(ea),
)
)
except Exception as e:
try:
flags = api.ida_bytes.get_cmt(ea, False)
outfile.write(
"CCu base64:{b64} @ {addr}\n".format(
b64=base64.b64encode(flags.encode(encoding="UTF-8")).decode(
"utf-8"
),
addr=str(ea),
)
)
except:
pass
def idb_to_rizin_functions(api):
""" Convert all functions from the IDB
"""
outfile.write("\n# IDB Functions\n")
for ea in api.idautils.Functions():
outfile.write(
"f {prefix}{name} @ {addr}\n".format(
prefix=FLAG_PREFIX,
name=api.idc.GetFunctionName(ea).replace("@", "_"),
addr=str(ea),
)
)
# Write the command responsible to analyze these functions
outfile.write("af @@f:{prefix}*\n".format(prefix=FLAG_PREFIX))
def idb_to_rizin_names(api):
""" Convert all names from the IDB
"""
outfile.write("\n# IDB Names\n")
for ea, name in api.idautils.Names():
outfile.write(
"f {prefix}{name} @ {addr}\n".format(
prefix=FLAG_PREFIX, name=name.replace("@", "_"), addr=str(ea)
)
)
def idb_parse(args):
global outfile
with idb.from_file(args.idb_file) as db:
api = idb.IDAPython(db)
# Compatability check for those who install python-idb from pip
try:
baddr = hex(api.ida_nalt.get_imagebase())
except:
baddr = "[base address]"
outfile = open(args.out_file, "w")
write_header()
print(
"[+] Starting conversion from '%s' to '%s'" % (args.idb_file, args.out_file)
)
if args.is_functions:
idb_to_rizin_functions(api)
if args.is_names:
idb_to_rizin_names(api)
if args.is_comments:
segs = idb.analysis.Segments(db).segments
outfile.write("\n# IDB Comments\n")
for segment in segs.values():
idb_to_rizin_comments(api, segment.startEA)
print("[+] Conversion done.\n")
print("[!] Execute: rizin -i %s -B %s [program]\n" % (args.out_file, baddr))
#
# End of IDB Parsing
###
# -------------------------------------------------------------------
###
# IDC Parsing
#
class Func(object):
# FIXME: parse ftype into params and values
def __init__(
self, name="unknown", params=[], values=[], address=0, size=0, ftype=""
):
self.name = name
self.params = params
self.values = values
self.address = address
self.size = size
self.ftype = ftype
class Llabel(object):
def __init__(self, name="unknown", address=0):
self.name = name
self.address = address
class Comm(object):
def __init__(self, text="", address=0):
self.text = text
self.address = address
class Enum(object):
def __init__(self, name="unknown", members=[]):
self.name = name
self.members = members
class Struct(object):
def __init__(self, name="unknown", members=[]):
self.name = name
self.members = members
class Union(object):
def __init__(self, name="unknown", members=[]):
self.name = name
self.members = members
class Type(object):
def __init__(self, name="unknown"):
self.name = name
self.members = members
# ----------------------------------------------------------------------
functions = []
llabels = []
comments = []
structs = []
enums = []
types = []
def idc_functions_parse(idc):
# MakeFunction (0XF3C99,0XF3CA8);
mkfun_re = re.compile(
"""
(?m) # Multiline
^[ \t]*MakeFunction[ \t]*\(
(?P<fstart>0[xX][\dA-Fa-f]{1,8}) # Function start
[ \t]*\,[ \t]*
(?P<fend>0[xX][\dA-Fa-f]{1,8}) # Function end
[ \t]*\);[ \t]*$
""",
re.VERBOSE,
)
mkfun_group_name = dict([(v, k) for k, v in mkfun_re.groupindex.items()])
mkfun = mkfun_re.finditer(idc)
for match in mkfun:
fun = Func()
for group_index, group in enumerate(match.groups()):
if group:
if mkfun_group_name[group_index + 1] == "fstart":
fun.address = int(group, 16)
if mkfun_group_name[group_index + 1] == "fend":
fun.size = int(group, 16) - fun.address
functions.append(fun)
# SetFunctionFlags (0XF3C99, 0x400);
mkfunflags_re = re.compile(
"""
(?m) # Multiline
^[ \t]*SetFunctionFlags[ \t*]\(
(?P<fstart>0[xX][\dA-Fa-f]{1,8}) # Function start
[ \t]*\,[ \t]*
(?P<flags>0[xX][\dA-Fa-f]{1,8}) # Flags
[ \t]*\);[ \t]*$
""",
re.VERBOSE,
)
mkfunflags_group_name = dict([(v, k) for k, v in mkfunflags_re.groupindex.items()])
mkfunflags = mkfunflags_re.finditer(idc)
for match in mkfunflags:
for group_index, group in enumerate(match.groups()):
if group:
if mkfunflags_group_name[group_index + 1] == "fstart":
addr = int(group, 16)
if mkfunflags_group_name[group_index + 1] == "flags":
for fun in functions:
if fun.address == addr:
pass # TODO: parse flags
# MakeFrame (0XF3C99, 0, 0, 0);
# MakeName (0XF3C99, "SIO_port_setup_S");
mkname_re = re.compile(
"""
(?m) # Multiline
^[ \t]*MakeName[ \t]*\(
(?P<fstart>0[xX][\dA-Fa-f]{1,8}) # Function start
[ \t]*\,[ \t]*
"(?P<fname>.*)" # Function name
[ \t]*\);[ \t]*$
""",
re.VERBOSE,
)
mkname_group_name = dict([(v, k) for k, v in mkname_re.groupindex.items()])
mkname = mkname_re.finditer(idc)
for match in mkname:
for group_index, group in enumerate(match.groups()):
if group:
if mkname_group_name[group_index + 1] == "fstart":
addr = int(group, 16)
if mkname_group_name[group_index + 1] == "fname":
for fun in functions:
if fun.address == addr:
fun.name = group
# SetType (0XFFF72, "__int32 __cdecl PCI_ByteWrite_SL(__int32 address, __int32 value)");
mkftype_re = re.compile(
"""
(?m) # Multiline
^[ \t]*SetType[ \t]*\(
(?P<fstart>0[xX][\dA-Fa-f]{1,8}) # Function start
[ \t]*\,[ \t]*
"(?P<ftype>.*)" # Function type
[ \t]*\);[ \t]*$
""",
re.VERBOSE,
)
mkftype_group_name = dict([(v, k) for k, v in mkftype_re.groupindex.items()])
mkftype = mkftype_re.finditer(idc)
for match in mkftype:
for group_index, group in enumerate(match.groups()):
if group:
if mkftype_group_name[group_index + 1] == "fstart":
addr = int(group, 16)
if mkftype_group_name[group_index + 1] == "ftype":
for fun in functions:
if fun.address == addr:
fun.ftype = group
# MakeNameEx (0xF3CA0, "return", SN_LOCAL);
mklocal_re = re.compile(
"""
(?m) # Multiline
^[ \t]*MakeNameEx[ \t]*\(
(?P<laddr>0[xX][\dA-Fa-f]{1,8}) # Local label address
[ \t]*\,[ \t]*
"(?P<lname>.*)" # Local label name
[ \t]*\,[ \t]*SN_LOCAL
[ \t]*\);[ \t]*$
""",
re.VERBOSE,
)
mklocal_group_name = dict([(v, k) for k, v in mklocal_re.groupindex.items()])
mklocal = mklocal_re.finditer(idc)
for match in mklocal:
lab = Llabel()
for group_index, group in enumerate(match.groups()):
if group:
if mklocal_group_name[group_index + 1] == "laddr":
lab.address = int(group, 16)
if mklocal_group_name[group_index + 1] == "lname":
lab.name = group
llabels.append(lab)
# ----------------------------------------------------------------------
def idc_enums_parse(idc):
pass
# ----------------------------------------------------------------------
def idc_structs_parse(idc):
# id = AddStrucEx (-1, "struct_MTRR", 0);
mkstruct_re = re.compile(
"""
(?m) # Multiline
^[ \t]*id[ \t]*=[ \t]*AddStrucEx[ \t]*\(
[ \t]*-1[ \t]*,[ \t]*
"(?P<sname>.*)" # Structure name
[ \t]*\,[ \t]*0
[ \t]*\);[ \t]*$
""",
re.VERBOSE,
)
mkstruct_group_name = dict([(v, k) for k, v in mkstruct_re.groupindex.items()])
mkstruct = mkstruct_re.finditer(idc)
for match in mkstruct:
s = Struct()
for group_index, group in enumerate(match.groups()):
if group:
if mkstruct_group_name[group_index + 1] == "sname":
s.name = group
structs.append(s)
# Case 1: not nested structures
# =============================
# id = GetStrucIdByName ("struct_header");
# mid = AddStructMember(id,"BCPNV", 0, 0x5000c500, 0, 7);
# mid = AddStructMember(id,"_", 0X7, 0x00500, -1, 1);
# mid = AddStructMember(id, "BCPNV_size",0X8, 0x004500, -1, 1);
mkstruct_re = re.compile(
"""
(?m) # Multiline
^[ \t]*id[ \t]*=[ \t]*GetStrucIdByName[ \t]*\(
[ \t]*-1[ \t]*,[ \t]*
"(?P<sname>.*)" # Structure name
[ \t]*\,[ \t]*0
[ \t]*\);[ \t]*$
""",
re.VERBOSE,
)
# ----------------------------------------------------------------------
def idc_comments_parse(idc):
# MakeComm (0XFED3D, "PCI class 0x600 - Host/PCI bridge");
mkcomm_re = re.compile(
"""
(?m) # Multiline
^[ \t]*MakeComm[ \t]*\(
(?P<caddr>0[xX][\dA-Fa-f]{1,8}) # Comment address
[ \t]*\,[ \t]*
"(?P<ctext>.*)" # Comment
[ \t]*\);[ \t]*$
""",
re.VERBOSE,
)
mkcomm_group_name = dict([(v, k) for k, v in mkcomm_re.groupindex.items()])
mkcomm = mkcomm_re.finditer(idc)
for match in mkcomm:
for group_index, group in enumerate(match.groups()):
if group:
if mkcomm_group_name[group_index + 1] == "caddr":
address = int(group, 16)
if mkcomm_group_name[group_index + 1] == "ctext":
com_multi = group.split("\\n")
for a in com_multi:
com = Comm()
com.address = address
com.text = a
comments.append(com)
# ----------------------------------------------------------------------
# print("af+ 0x%08lx %d %s" % (func.address, func.size, func.name))
def idc_generate_rizin(out_file):
global outfile
outfile = open(out_file, "w")
write_header()
for f in functions:
if f.name != "unknown":
outfile.write(
"af+ {addr} {size} {name}\n".format(
addr=hex(f.address), size=f.size, name=f.name
)
)
outfile.write(
'"CCa {addr} {type}"\n'.format(addr=hex(f.address), type=f.ftype)
)
for l in llabels:
if l.name != "unknown":
for f in functions:
if (l.address > f.address) and (l.address < (f.address + f.size)):
outfile.write(
"f. {name} @ {addr}\n".format(name=l.name, addr=hex(l.address))
)
for c in comments:
if c.text != "":
outfile.write('"CCa {addr} {text}"\n'.format(addr=c.address, text=c.text))
outfile.seek(0, 2)
if outfile.tell() == 0:
print("[-] Found nothing to convert :-(")
exit()
# ----------------------------------------------------------------------
def idc_parse(args):
print("[+] Starting convertion from '%s' to '%s'" % (args.idc_file, args.out_file))
idc_file = open(args.idc_file, "r")
idc = idc_file.read()
idc_enums_parse(idc)
idc_structs_parse(idc)
if args.is_functions:
idc_functions_parse(idc)
if args.is_comments:
idc_comments_parse(idc)
idc_generate_rizin(args.out_file)
print("[+] Convertion done.\n")
print("[!] Execute: rizin -i %s [program]\n" % (args.out_file))
#
# End of IDC Parsing
###
# ----------------------------------------------------------------------
def main():
""" Gets arguments from the user. Perform convertion of the chosen data from the IDB into a radare2 initialization script
"""
args = get_args()
if args.idb_file:
idb_parse(args)
elif args.idc_file:
idc_parse(args)
if __name__ == "__main__":
main()