File: unicorn_dumper_pwndbg.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 (251 lines) | stat: -rw-r--r-- 7,290 bytes parent folder | download
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
"""
    unicorn_dumper_pwndbg.py
    
    When run with GDB sitting at a debug breakpoint, this
    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.

    -----------

    In order to run this script, PWNDBG needs to be running in the GDB session (gdbinit.py)
    # HELPERS from: https://github.com/pwndbg/pwndbg
    It can be loaded with:
      source <path_to_pwndbg>/gdbinit.py

    Call this function when at a breakpoint in your process with:
      source unicorn_dumper_pwndbg.py

    -----------


"""

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

# GDB Python SDK
import gdb

pwndbg_loaded = False

try:
    import pwndbg.gdblib.arch
    import pwndbg.gdblib.regs
    import pwndbg.gdblib.vmmap
    import pwndbg.gdblib.memory

    pwndbg_loaded = True

except ImportError:
    print("!!! PWNGDB not running in GDB.  Please run gdbinit.py by executing:")
    print('\tpython execfile ("<path_to_pwndbg>/gdbinit.py")')

# 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 map_arch():
    arch = pwndbg.gdblib.arch.current  # from PWNDBG
    if "x86_64" in arch or "x86-64" in arch:
        return "x64"
    elif "x86" in arch or "i386" in arch:
        return "x86"
    elif "aarch64" in arch or "arm64" in arch:
        return "arm64le"
    elif "aarch64_be" in arch:
        return "arm64be"
    elif "arm" in arch:
        cpsr = pwndbg.gdblib.regs["cpsr"]
        # check endianness
        if pwndbg.gdblib.arch.endian == "big":
            # check for THUMB mode
            if cpsr & (1 << 5):
                return "armbethumb"
            else:
                return "armbe"
        else:
            # check for THUMB mode
            if cpsr & (1 << 5):
                return "armlethumb"
            else:
                return "armle"
    elif "mips" in arch:
        if pwndbg.gdblib.arch.endian == "little":
            return "mipsel"
        else:
            return "mips"
    else:
        return ""


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


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


def dump_regs():
    reg_state = {}
    for reg in pwndbg.gdblib.regs.all:
        reg_val = pwndbg.gdblib.regs[reg]
        if reg_val is None:
            continue
        # current dumper script looks for register values to be hex strings
        #         reg_str = "0x{:08x}".format(reg_val)
        #         if "64" in get_arch():
        #             reg_str = "0x{:016x}".format(reg_val)
        #         reg_state[reg.strip().strip('$')] = reg_str
        reg_state[reg.strip().strip("$")] = int(reg_val)
    return reg_state


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

    # PWNDBG:
    vmmap = pwndbg.gdblib.vmmap.get()

    # Pointer to end of last dumped memory segment
    segment_last_addr = 0x0

    start = None
    end = None

    if not vmmap:
        print("No address mapping information found")
        return final_segment_list

    # Assume segment entries are sorted by start address
    for entry in vmmap:
        if entry.start == entry.end:
            continue

        start = entry.start
        end = entry.end

        if segment_last_addr > entry.start:  # indicates overlap
            if (
                segment_last_addr > entry.end
            ):  # indicates complete overlap, so we skip the segment entirely
                continue
            else:
                start = segment_last_addr

        seg_info = {
            "start": start,
            "end": end,
            "name": entry.objfile,
            "permissions": {"r": entry.read, "w": entry.write, "x": entry.execute},
            "content_file": "",
        }

        # "(deleted)" may or may not be valid, but don't push it.
        if entry.read and not "(deleted)" in entry.objfile:
            try:
                # Compress and dump the content to a file
                seg_content = pwndbg.gdblib.memory.read(start, end - start)
                if seg_content == None:
                    print(
                        "Segment empty: @0x{0:016x} (size:UNKNOWN) {1}".format(
                            entry.start, entry.objfile
                        )
                    )
                else:
                    print(
                        "Dumping segment @0x{0:016x} (size:0x{1:x}): {2} [{3}]".format(
                            entry.start,
                            len(seg_content),
                            entry.objfile,
                            repr(seg_info["permissions"]),
                        )
                    )
                    compressed_seg_content = zlib.compress(bytes(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 Exception as e:
                traceback.print_exc()
                print(
                    "Exception reading segment ({}): {}".format(
                        entry.objfile, sys.exc_info()[0]
                    )
                )
        else:
            print("Skipping segment {0}@0x{1:016x}".format(entry.objfile, entry.start))

        segment_last_addr = end

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

    return final_segment_list


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


def main():
    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.")

    try:

        # Create the output directory
        timestamp = datetime.datetime.fromtimestamp(time.time()).strftime(
            "%Y%m%d_%H%M%S"
        )
        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),
        }

        # 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 as e:
        print("!!! ERROR:\n\t{}".format(repr(e)))


if __name__ == "__main__" and pwndbg_loaded:
    main()