File: unicorn_dumper_ida.py

package info (click to toggle)
aflplusplus 4.33c-0.2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,740 kB
  • sloc: ansic: 111,574; cpp: 16,019; sh: 4,766; python: 4,546; makefile: 1,000; javascript: 521; java: 43; sql: 3; xml: 1
file content (308 lines) | stat: -rw-r--r-- 7,709 bytes parent folder | download | duplicates (3)
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
"""
    unicorn_dumper_ida.py
    
    When run with IDA (<v7) sitting at a debug breakpoint, 
    dumps the current state (registers/memory/etc) of
    the process to a directory consisting of an index 
    file with register and segment information and 
    sub-files containing all actual process memory.
    
    The output of this script is expected to be used 
    to initialize context for Unicorn emulation.
"""

import datetime
import hashlib
import json
import os
import sys
import time
import zlib

# IDA Python SDK
from idaapi import *
from idc import *

# Maximum segment size that we'll store
# Yep, this could break stuff pretty quickly if we
# omit something that's used during emulation.
MAX_SEG_SIZE = 128 * 1024 * 1024

# Name of the index file
INDEX_FILE_NAME = "_index.json"

# ----------------------
# ---- Helper Functions


def get_arch():
    if ph.id == PLFM_386 and ph.flag & PR_USE64:
        return "x64"
    elif ph.id == PLFM_386 and ph.flag & PR_USE32:
        return "x86"
    elif ph.id == PLFM_ARM and ph.flag & PR_USE64:
        if cvar.inf.is_be():
            return "arm64be"
        else:
            return "arm64le"
    elif ph.id == PLFM_ARM and ph.flag & PR_USE32:
        if cvar.inf.is_be():
            return "armbe"
        else:
            return "armle"
    else:
        return ""


def get_register_list(arch):
    if arch == "arm64le" or arch == "arm64be":
        arch = "arm64"
    elif arch == "armle" or arch == "armbe":
        arch = "arm"

    registers = {
        "x64": [
            "rax",
            "rbx",
            "rcx",
            "rdx",
            "rsi",
            "rdi",
            "rbp",
            "rsp",
            "r8",
            "r9",
            "r10",
            "r11",
            "r12",
            "r13",
            "r14",
            "r15",
            "rip",
            "rsp",
            "efl",
            "cs",
            "ds",
            "es",
            "fs",
            "gs",
            "ss",
        ],
        "x86": [
            "eax",
            "ebx",
            "ecx",
            "edx",
            "esi",
            "edi",
            "ebp",
            "esp",
            "eip",
            "esp",
            "efl",
            "cs",
            "ds",
            "es",
            "fs",
            "gs",
            "ss",
        ],
        "arm": [
            "R0",
            "R1",
            "R2",
            "R3",
            "R4",
            "R5",
            "R6",
            "R7",
            "R8",
            "R9",
            "R10",
            "R11",
            "R12",
            "PC",
            "SP",
            "LR",
            "PSR",
        ],
        "arm64": [
            "X0",
            "X1",
            "X2",
            "X3",
            "X4",
            "X5",
            "X6",
            "X7",
            "X8",
            "X9",
            "X10",
            "X11",
            "X12",
            "X13",
            "X14",
            "X15",
            "X16",
            "X17",
            "X18",
            "X19",
            "X20",
            "X21",
            "X22",
            "X23",
            "X24",
            "X25",
            "X26",
            "X27",
            "X28",
            "PC",
            "SP",
            "FP",
            "LR",
            "CPSR"
            #    "NZCV",
        ],
    }
    return registers[arch]


# -----------------------
# ---- Dumping functions


def dump_arch_info():
    arch_info = {}
    arch_info["arch"] = get_arch()
    return arch_info


def dump_regs():
    reg_state = {}
    for reg in get_register_list(get_arch()):
        reg_state[reg] = GetRegValue(reg)
    return reg_state


def dump_process_memory(output_dir):
    # Segment information dictionary
    segment_list = []

    # Loop over the segments, fill in the info dictionary
    for seg_ea in Segments():
        seg_start = SegStart(seg_ea)
        seg_end = SegEnd(seg_ea)
        seg_size = seg_end - seg_start

        seg_info = {}
        seg_info["name"] = SegName(seg_ea)
        seg_info["start"] = seg_start
        seg_info["end"] = seg_end

        perms = getseg(seg_ea).perm
        seg_info["permissions"] = {
            "r": False if (perms & SEGPERM_READ) == 0 else True,
            "w": False if (perms & SEGPERM_WRITE) == 0 else True,
            "x": False if (perms & SEGPERM_EXEC) == 0 else True,
        }

        if (perms & SEGPERM_READ) and seg_size <= MAX_SEG_SIZE and isLoaded(seg_start):
            try:
                # Compress and dump the content to a file
                seg_content = get_many_bytes(seg_start, seg_end - seg_start)
                if seg_content == None:
                    print(
                        "Segment empty: {0}@0x{1:016x} (size:UNKNOWN)".format(
                            SegName(seg_ea), seg_ea
                        )
                    )
                    seg_info["content_file"] = ""
                else:
                    print(
                        "Dumping segment {0}@0x{1:016x} (size:{2})".format(
                            SegName(seg_ea), seg_ea, len(seg_content)
                        )
                    )
                    compressed_seg_content = zlib.compress(seg_content)
                    md5_sum = hashlib.md5(compressed_seg_content).hexdigest() + ".bin"
                    seg_info["content_file"] = md5_sum

                    # Write the compressed contents to disk
                    out_file = open(os.path.join(output_dir, md5_sum), "wb")
                    out_file.write(compressed_seg_content)
                    out_file.close()
            except:
                print("Exception reading segment: {}".format(sys.exc_info()[0]))
                seg_info["content_file"] = ""
        else:
            print("Skipping segment {0}@0x{1:016x}".format(SegName(seg_ea), seg_ea))
            seg_info["content_file"] = ""

        # Add the segment to the list
        segment_list.append(seg_info)

    return segment_list


"""
    TODO: FINISH IMPORT DUMPING
def import_callback(ea, name, ord):
    if not name:
    else:
    
    # True -> Continue enumeration
    # False -> End enumeration
    return True
    
def dump_imports():
    import_dict = {}
    
    for i in xrange(0, number_of_import_modules):
        enum_import_names(i, import_callback)
    
    return import_dict
"""

# ----------
# ---- Main


def main():

    try:
        print("----- Unicorn Context Dumper -----")
        print("You must be actively debugging before running this!")
        print(
            "If it fails, double check that you are actively debugging before running."
        )

        # Create the output directory
        timestamp = datetime.datetime.fromtimestamp(time.time()).strftime(
            "%Y%m%d_%H%M%S"
        )
        output_path = os.path.dirname(os.path.abspath(GetIdbPath()))
        output_path = os.path.join(output_path, "UnicornContext_" + timestamp)
        if not os.path.exists(output_path):
            os.makedirs(output_path)
        print("Process context will be output to {}".format(output_path))

        # Get the context
        context = {
            "arch": dump_arch_info(),
            "regs": dump_regs(),
            "segments": dump_process_memory(output_path),
            # "imports": dump_imports(),
        }

        # Write the index file
        index_file = open(os.path.join(output_path, INDEX_FILE_NAME), "w")
        index_file.write(json.dumps(context, indent=4))
        index_file.close()
        print("Done.")

    except Exception, e:
        print("!!! ERROR:\n\t{}".format(str(e)))


if __name__ == "__main__":
    main()