Ejemplo n.º 1
0
    def test(self):

        # Disassemble & assemble unit tests
        unit_tests = [("ADD R1, 2", "6108")]
        unit_tests += [("JMP 0xC3FA38", "d9c8c3fa")]
        unit_tests += [("SLT3 R0, R8, R10", "08a2")]
        unit_tests += [("SB R9, (R4)", "0948")]
        unit_tests += [("SSARB 3(GP)", "13ec")]
        unit_tests += [("SWCPI C13, (R2+)", "3d20")]
        unit_tests += [("ADD3 R2, SP, 0x1C", "421c")]
        unit_tests += [("SW R7, 0x50(SP)", "4752")]

        for mn_str, mn_hex in unit_tests:
            print("-" * 49)  # Tests separation

            # Dissassemble
            mn_bin = decode_hex(mn_hex)
            mn = mn_mep.dis(mn_bin, "b")

            print("dis: %s -> %s" % (mn_hex.rjust(20), str(mn).rjust(20)))
            assert(str(mn) == mn_str)  # dissassemble assertion

            # Assemble and return all possible candidates
            instr = mn_mep.fromstring(str(mn), "b")
            instr.mode = "b"
            asm_list = [encode_hex(i).decode() for i in mn_mep.asm(instr)]

            # Print the results
            print("asm: %s -> %s" % (
                mn_str.rjust(20),
                ", ".join(asm_list).rjust(20))
            )
            assert(mn_hex in asm_list)  # assemble assertion
Ejemplo n.º 2
0
    def test(self):

        # Disassemble & assemble unit tests
        unit_tests = [("ADD R1, 2", "6108")]
        unit_tests += [("JMP 0xC3FA38", "d9c8c3fa")]
        unit_tests += [("SLT3 R0, R8, R10", "08a2")]
        unit_tests += [("SB R9, (R4)", "0948")]
        unit_tests += [("SSARB 3(GP)", "13ec")]
        unit_tests += [("SWCPI C13, (R2+)", "3d20")]
        unit_tests += [("ADD3 R2, SP, 0x1C", "421c")]
        unit_tests += [("SW R7, 0x50(SP)", "4752")]

        for mn_str, mn_hex in unit_tests:
            print("-" * 49)  # Tests separation

            # Disassemble
            mn_bin = decode_hex(mn_hex)
            mn = mn_mep.dis(mn_bin, "b")

            print("dis: %s -> %s" % (mn_hex.rjust(20), str(mn).rjust(20)))
            assert (str(mn) == mn_str)  # disassemble assertion

            # Assemble and return all possible candidates
            instr = mn_mep.fromstring(str(mn), "b")
            instr.mode = "b"
            asm_list = [encode_hex(i).decode() for i in mn_mep.asm(instr)]

            # Print the results
            print("asm: %s -> %s" %
                  (mn_str.rjust(20), ", ".join(asm_list).rjust(20)))
            assert (mn_hex in asm_list)  # assemble assertion
Ejemplo n.º 3
0
def test():
    unit_tests = [('CLS', '00')]
    unit_tests += [('STRD R0', '0100')]
    unit_tests += [('STRB R0', '0200')]
    unit_tests += [('STRW R0', '0300')]
    unit_tests += [('LDRD R0', '0400')]
    unit_tests += [('LDRB R0', '0500')]
    unit_tests += [('LDRW R0', '0600')]
    unit_tests += [('MOV 0x68, R0', '076800')]
    unit_tests += [('MOV R1, R0', '080100')]
    unit_tests += [('ADD R2, R3', '090203')]
    unit_tests += [('SUB R0, R2', '0A0002')]
    unit_tests += [('MUL R0, R2', '0B0002')]
    unit_tests += [('DIV R0, R2', '0C0002')]
    unit_tests += [('MOD R0, R2', '0D0002')]
    unit_tests += [('AND R0, R2', '0E0002')]
    unit_tests += [('OR R0, R2', '0F0002')]
    unit_tests += [('XOR R0, R2', '100002')]
    unit_tests += [('JMP 0x69', '1169')]
    unit_tests += [('JE R0, R1, 0x32', '1200000132')]
    unit_tests += [('JNE R0, R1, 0x32', '1201000132')]
    unit_tests += [('JGE R0, R1, 0x32', '1202000132')]
    unit_tests += [('JL R0, R1, 0x32', '1203000132')]
    unit_tests += [('READ_INPUT 0x20', '1320')]
    unit_tests += [('PRN', '14')]
    unit_tests += [('VMEXIT', '15')]

    for mn_str, mn_hex in unit_tests:
        # print("-" * 49)  # Tests separation
        mn_bin = decode_hex(mn_hex)
        mn = mn_spacez.dis(mn_bin)
        print("dis: %s -> %s" % (mn_hex.ljust(10), str(mn).ljust(20)))
        assert (str(mn) == mn_str)  # disassemble assertion
Ejemplo n.º 4
0
def dis(mn_hex):
    """Disassembly helper"""
    mn_bin = decode_hex(mn_hex)
    try:
        return mn_mep.dis(mn_bin, "b")
    except Disasm_Exception:
        assert(False)  # miasm don't know what to do
Ejemplo n.º 5
0
        def exec_instruction(hex_asm, init_values):
            """Symbolically execute an instruction"""

            print("Hex:", hex_asm)

            # Disassemble an instruction
            mn = mn_mep.dis(decode_hex(hex_asm), "b")
            print("Dis:", mn)

            loc_db = LocationDB()

            # Get the IR
            im = ir_mepb(loc_db)
            iir, eiir, = im.get_ir(mn)
            print("\nInternal representation:", iir)

            # Symbolic execution
            sb = SymbolicExecutionEngine(ir_a_mepb(loc_db), regs_init)

            # Assign register values before symbolic evaluation
            for reg_expr_id, reg_expr_value in init_values:
                sb.symbols[reg_expr_id] = reg_expr_value

            print("\nModified registers:", [reg for reg in sb.modified(mems=False)])
            print("Modified memories:", [mem for mem in sb.modified()])

            print("\nFinal registers:")
            sb.dump(mems=False)

            print("\nFinal mems:")
            sb.dump()
Ejemplo n.º 6
0
 def tostring(self):
     if len(self.bits) % 8:
         raise ValueError('num bits must be 8 bit aligned: %d' %
                          len(self.bits))
     b = int("".join(str(x) for x in self.bits), 2)
     b = "%X" % b
     b = '0' * (len(self.bits) // 4 - len(b)) + b
     b = decode_hex(b.encode())
     return b
Ejemplo n.º 7
0
Archivo: cpu.py Proyecto: cea-sec/miasm
 def tostring(self):
     if len(self.bits) % 8:
         raise ValueError(
             'num bits must be 8 bit aligned: %d' % len(self.bits)
         )
     b = int("".join(str(x) for x in self.bits), 2)
     b = "%X" % b
     b = '0' * (len(self.bits) // 4 - len(b)) + b
     b = decode_hex(b.encode())
     return b
Ejemplo n.º 8
0
    def mem_write(self, dest, data):
        """Memory read wrapper for symbolic execution
        @dest: ExprMem instance
        @data: Expr instance"""

        # Get the content to write
        data = self.expr_simp(data)
        if not isinstance(data, m2_expr.ExprInt):
            raise RuntimeError("A simplification is missing: %s" % data)
        to_write = int(data)

        # Format information
        addr = int(dest.ptr)
        size = data.size // 8
        content = hex(to_write).replace("0x", "").replace("L", "")
        content = "0" * (size * 2 - len(content)) + content
        content = decode_hex(content)

        if self.vm.is_little_endian():
            content = content[::-1]

        # Write in VmMngr context
        self.vm.set_mem(addr, content)
Ejemplo n.º 9
0
    def mem_write(self, dest, data):
        """Memory read wrapper for symbolic execution
        @dest: ExprMem instance
        @data: Expr instance"""

        # Get the content to write
        data = self.expr_simp(data)
        if not isinstance(data, m2_expr.ExprInt):
            raise RuntimeError("A simplification is missing: %s" % data)
        to_write = data.arg.arg

        # Format information
        addr = dest.ptr.arg.arg
        size = data.size // 8
        content = hex(to_write).replace("0x", "").replace("L", "")
        content = "0" * (size * 2 - len(content)) + content
        content = decode_hex(content)

        if self.vm.is_little_endian():
            content = content[::-1]

        # Write in VmMngr context
        self.cpu.set_mem(addr, content)
        self.vm.add_mem_write(addr, len(content))
Ejemplo n.º 10
0
def h2i(s):
    return decode_hex(s.replace(' ', ''))
Ejemplo n.º 11
0
def code_sentinelle(jitter):
    jitter.running = False
    jitter.pc = 0
    return True


machine = Machine("x86_32")
loc_db = LocationDB()
jitter = machine.jitter(loc_db, sys.argv[1])

jitter.init_stack()

# nop
# mov eax, 0x42
# XX
data = decode_hex("90b842000000ffff90909090")

# Will raise memory error at 0x40000006

error_raised = False


def raise_me(jitter):
    global error_raised
    error_raised = True
    assert jitter.pc == 0x40000006
    return False


jitter.add_exception_handler(EXCEPT_UNK_MNEMO, raise_me)
Ejemplo n.º 12
0
FFFFFF800901EBF8 A2 63 00 91                 ADD             X2, X29, #0x18
FFFFFF800901EBFC 00 00 80 52                 MOV             W0, 1
FFFFFF800901EC00 C0 00 00 35                 CBNZ            W0, loc_FFFFFF800901EC18
FFFFFF800901EC04 A0 0F 40 F9                 LDR             X0, [X29,#0x20+var_8]
FFFFFF800901EC08 1F 00 1F EB                 CMP             X0, XZR
FFFFFF800901EC0C 60 19 00 90                 ADRP            X0, #0xFFFFFF800934A6C4@PAGE
FFFFFF800901EC10 E1 07 9F 1A                 CSET            W1, NE
FFFFFF800901EC14 01 C4 06 B9                 STR             W1, [X0,#0xFFFFFF800934A6C4@PAGEOFF]
FFFFFF800901EC18 20 00 80 52                 MOV             W0, #1
FFFFFF800901EC1C FD 7B C2 A8                 LDP             X29, X30, [SP+0x20+var_20],#0x20
FFFFFF800901EC20 C0 03 5F D6                 RET
'''
jitter.vm.set_mem(
    0xFFFFFF800901EBEC,
    decode_hex(
        "FD7BBEA901008052FD030091A263009100008052C0000035A00F40F91F001FEB60190090E1079F1A01C406B920008052FD7BC2A8C0035FD6"
    ))

# print(jitter.vm)

jitter.set_trace_log()

jitter.exceptions_handler.callbacks[EXCEPT_BREAKPOINT_MEMORY] = []
jitter.add_exception_handler(EXCEPT_BREAKPOINT_MEMORY, mem_breakpoint_handler)
jitter.vm.add_memory_breakpoint(0xFFFFFF8009080000, 0x8000000,
                                PAGE_READ | PAGE_WRITE)

jitter.init_run(0xFFFFFF800901EBEC)

try:
    jitter.continue_run()
Ejemplo n.º 13
0
from miasm.core.locationdb import LocationDB
from pdb import pm

# Shellcode
# main:
#       MOV    EAX, 0x10
#       MOV    EBX, 0x1
# loop_main:
#       SUB    EAX, 0x1
#       CMOVZ  ECX, EBX
#       JNZ    loop_main
# loop_end:
#       RET


data = decode_hex("b810000000bb0100000083e8010f44cb75f8c3")
run_addr = 0x40000000
loc_db = LocationDB()

def code_sentinelle(jitter):
    jitter.running = False
    jitter.pc = 0
    return True

def init_jitter(loc_db):
    global data, run_addr
    # Create jitter
    myjit = Machine("x86_32").jitter(loc_db, sys.argv[1])

    myjit.vm.add_memory_page(run_addr, PAGE_READ | PAGE_WRITE, data)
Ejemplo n.º 14
0
import sys
from pdb import pm

from miasm.core.utils import decode_hex, encode_hex
from miasm.jitter.csts import PAGE_READ, PAGE_WRITE
from miasm.analysis.machine import Machine
from miasm.expression.expression import ExprId, ExprAssign, ExprInt, ExprMem

# Initial data: from 'example/samples/x86_32_sc.bin'
data = decode_hex("8d49048d5b0180f90174058d5bffeb038d5b0189d8c3")

# Init jitter
myjit = Machine("x86_32").jitter(sys.argv[1])
myjit.init_stack()

run_addr = 0x40000000
myjit.vm.add_memory_page(run_addr, PAGE_READ | PAGE_WRITE, data)

# Sentinelle called on terminate
def code_sentinelle(jitter):
    jitter.run = False
    jitter.pc = 0
    return True

myjit.push_uint32_t(0x1337beef)
myjit.add_breakpoint(0x1337beef, code_sentinelle)

# Run
myjit.init_run(run_addr)
myjit.continue_run()
Ejemplo n.º 15
0
    def process_messages(self):

        while self.recv_queue:
            msg = self.recv_queue.pop(0)
            buf = BytesIO(msg)
            msg_type = buf.read(1)

            self.send_queue.append(b"+")

            if msg_type == b"q":
                if msg.startswith(b"qSupported"):
                    self.send_queue.append(b"PacketSize=3fff")
                elif msg.startswith(b"qC"):
                    # Current thread
                    self.send_queue.append(b"")
                elif msg.startswith(b"qAttached"):
                    # Not supported
                    self.send_queue.append(b"")
                elif msg.startswith(b"qTStatus"):
                    # Not supported
                    self.send_queue.append(b"")
                elif msg.startswith(b"qfThreadInfo"):
                    # Not supported
                    self.send_queue.append(b"")
                else:
                    raise NotImplementedError()

            elif msg_type == b"H":
                # Set current thread
                self.send_queue.append(b"OK")

            elif msg_type == b"?":
                # Report why the target halted
                self.send_queue.append(self.status)  # TRAP signal

            elif msg_type == b"g":
                # Report all general register values
                self.send_queue.append(self.report_general_register_values())

            elif msg_type == b"p":
                # Read a specific register
                reg_num = int(buf.read(), 16)
                self.send_queue.append(self.read_register(reg_num))

            elif msg_type == b"P":
                # Set a specific register
                reg_num, value = buf.read().split(b"=")
                reg_num = int(reg_num, 16)
                value = int(encode_hex(decode_hex(value)[::-1]), 16)
                self.set_register(reg_num, value)
                self.send_queue.append(b"OK")

            elif msg_type == b"m":
                # Read memory
                addr, size = (int(x, 16) for x in buf.read().split(b",", 1))
                self.send_queue.append(self.read_memory(addr, size))

            elif msg_type == b"k":
                # Kill
                self.sock.close()
                self.send_queue = []
                self.sock = None

            elif msg_type == b"!":
                # Extending debugging will be used
                self.send_queue.append(b"OK")

            elif msg_type == b"v":
                if msg == b"vCont?":
                    # Is vCont supported ?
                    self.send_queue.append(b"")

            elif msg_type == b"s":
                # Step
                self.dbg.step()
                self.send_queue.append(b"S05")  # TRAP signal

            elif msg_type == b"Z":
                # Add breakpoint or watchpoint
                bp_type = buf.read(1)
                if bp_type == b"0":
                    # Exec breakpoint
                    assert (buf.read(1) == b",")
                    addr, size = (int(x, 16)
                                  for x in buf.read().split(b",", 1))

                    if size != 1:
                        raise NotImplementedError("Bigger size")
                    self.dbg.add_breakpoint(addr)
                    self.send_queue.append(b"OK")

                elif bp_type == b"1":
                    # Hardware BP
                    assert (buf.read(1) == b",")
                    addr, size = (int(x, 16)
                                  for x in buf.read().split(b",", 1))

                    self.dbg.add_memory_breakpoint(addr,
                                                   size,
                                                   read=True,
                                                   write=True)
                    self.send_queue.append(b"OK")

                elif bp_type in [b"2", b"3", b"4"]:
                    # Memory breakpoint
                    assert (buf.read(1) == b",")
                    read = bp_type in [b"3", b"4"]
                    write = bp_type in [b"2", b"4"]
                    addr, size = (int(x, 16)
                                  for x in buf.read().split(b",", 1))

                    self.dbg.add_memory_breakpoint(addr,
                                                   size,
                                                   read=read,
                                                   write=write)
                    self.send_queue.append(b"OK")

                else:
                    raise ValueError("Impossible value")

            elif msg_type == b"z":
                # Remove breakpoint or watchpoint
                bp_type = buf.read(1)
                if bp_type == b"0":
                    # Exec breakpoint
                    assert (buf.read(1) == b",")
                    addr, size = (int(x, 16)
                                  for x in buf.read().split(b",", 1))

                    if size != 1:
                        raise NotImplementedError("Bigger size")
                    dbgsoft = self.dbg.get_breakpoint_by_addr(addr)
                    assert (len(dbgsoft) == 1)
                    self.dbg.remove_breakpoint(dbgsoft[0])
                    self.send_queue.append(b"OK")

                elif bp_type == b"1":
                    # Hardware BP
                    assert (buf.read(1) == b",")
                    addr, size = (int(x, 16)
                                  for x in buf.read().split(b",", 1))
                    self.dbg.remove_memory_breakpoint_by_addr_access(
                        addr, read=True, write=True)
                    self.send_queue.append(b"OK")

                elif bp_type in [b"2", b"3", b"4"]:
                    # Memory breakpoint
                    assert (buf.read(1) == b",")
                    read = bp_type in [b"3", b"4"]
                    write = bp_type in [b"2", b"4"]
                    addr, size = (int(x, 16)
                                  for x in buf.read().split(b",", 1))

                    self.dbg.remove_memory_breakpoint_by_addr_access(
                        addr, read=read, write=write)
                    self.send_queue.append(b"OK")

                else:
                    raise ValueError("Impossible value")

            elif msg_type == b"c":
                # Continue
                self.status = b""
                self.send_messages()
                ret = self.dbg.run()
                if isinstance(ret, debugging.DebugBreakpointSoft):
                    self.status = b"S05"
                    self.send_queue.append(b"S05")  # TRAP signal
                elif isinstance(ret, ExceptionHandle):
                    if ret == ExceptionHandle.memoryBreakpoint():
                        self.status = b"S05"
                        self.send_queue.append(b"S05")
                    else:
                        raise NotImplementedError("Unknown Except")
                elif isinstance(ret, debugging.DebugBreakpointTerminate):
                    # Connection should close, but keep it running as a TRAP
                    # The connection will be close on instance destruction
                    print(ret)
                    self.status = b"S05"
                    self.send_queue.append(b"S05")
                else:
                    raise NotImplementedError()

            else:
                raise NotImplementedError("Not implemented: message type %r" %
                                          msg_type)
Ejemplo n.º 16
0
print(jitter.vm)

jitter.cpu.ESP = 0x10000 + 0x1000
jitter.push_uint32_t(0x0)
jitter.push_uint32_t(0x1337beef)

jitter.vm.reset_memory_access()
print(hex(jitter.vm.get_exception()))

# Add code, and keep memory write pending
jitter.vm.add_memory_page(0x1000, PAGE_READ | PAGE_WRITE, b"\x00" * 0x1000,
                          "code page")

# MOV EAX, 0x11223344
# RET
jitter.vm.set_mem(0x1000, decode_hex("B844332211C3"))

jitter.set_trace_log()


def do_not_raise_me(jitter):
    raise ValueError("Should not be here")


jitter.exceptions_handler.callbacks[EXCEPT_BREAKPOINT_MEMORY] = []
jitter.add_exception_handler(EXCEPT_BREAKPOINT_MEMORY, do_not_raise_me)
jitter.vm.add_memory_breakpoint(0x11000 - 4, 4, PAGE_READ | PAGE_WRITE)

# The memory write pending will raise automod exception
# The RET should not re evaluate PC @ [ESP+4]
jitter.init_run(0x1000)
Ejemplo n.º 17
0
def code_sentinelle(jitter):
    jitter.run = False
    jitter.pc = 0
    return True


machine = Machine("x86_32")
jitter = machine.jitter(sys.argv[1])

jitter.init_stack()

# nop
# mov eax, 0x42
# jmp 0x20

data = decode_hex("90b842000000eb20")

# Will raise memory error at 0x40000028

error_raised = False
def raise_me(jitter):
    global error_raised
    error_raised = True
    assert jitter.pc == 0x40000028
    return False

jitter.add_exception_handler(EXCEPT_ACCESS_VIOL, raise_me)


run_addr = 0x40000000
Ejemplo n.º 18
0
from builtins import map
from pdb import pm

from future.utils import viewitems

from miasm.core.utils import decode_hex
from miasm.analysis.machine import Machine
from miasm.analysis.binary import Container
from miasm.core.asmblock import AsmCFG, AsmConstraint, AsmBlock, \
    AsmBlockBad, AsmConstraintTo, AsmConstraintNext, \
    bbl_simplifier
from miasm.core.graph import DiGraphSimplifier, MatchGraphJoker
from miasm.expression.expression import ExprId

# Initial data: from 'samples/simple_test.bin'
data = decode_hex("5589e583ec10837d08007509c745fc01100000eb73837d08017709c745fc02100000eb64837d08057709c745fc03100000eb55837d080774138b450801c083f80e7509c745fc04100000eb3c8b450801c083f80e7509c745fc05100000eb298b450883e03085c07409c745fc06100000eb16837d08427509c745fc07100000eb07c745fc081000008b45fcc9c3")
cont = Container.from_string(data)

# Test Disasm engine
machine = Machine("x86_32")
mdis = machine.dis_engine(cont.bin_stream, loc_db=cont.loc_db)
## Disassembly of one block
first_block = mdis.dis_block(0)
assert len(first_block.lines) == 5
print(first_block)

## Test redisassemble asmcfg
first_block_bis = mdis.dis_block(0)
assert len(first_block.lines) == len(first_block_bis.lines)
print(first_block_bis)
Ejemplo n.º 19
0
from miasm.analysis.machine import Machine
from pdb import pm

# Shellcode
# main:
#       MOV    EAX, 0x10
#       MOV    EBX, 0x1
# loop_main:
#       SUB    EAX, 0x1
#       CMOVZ  ECX, EBX
#       JNZ    loop_main
# loop_end:
#       RET


data = decode_hex("b810000000bb0100000083e8010f44cb75f8c3")
run_addr = 0x40000000

def code_sentinelle(jitter):
    jitter.run = False
    jitter.pc = 0
    return True

def init_jitter():
    global data, run_addr
    # Create jitter
    myjit = Machine("x86_32").jitter(sys.argv[1])

    myjit.vm.add_memory_page(run_addr, PAGE_READ | PAGE_WRITE, data)

    # Init jitter
Ejemplo n.º 20
0
    def process_messages(self):

        while self.recv_queue:
            msg = self.recv_queue.pop(0)
            buf = BytesIO(msg)
            msg_type = buf.read(1)

            self.send_queue.append(b"+")

            if msg_type == b"q":
                if msg.startswith(b"qSupported"):
                    self.send_queue.append(b"PacketSize=3fff")
                elif msg.startswith(b"qC"):
                    # Current thread
                    self.send_queue.append(b"")
                elif msg.startswith(b"qAttached"):
                    # Not supported
                    self.send_queue.append(b"")
                elif msg.startswith(b"qTStatus"):
                    # Not supported
                    self.send_queue.append(b"")
                elif msg.startswith(b"qfThreadInfo"):
                    # Not supported
                    self.send_queue.append(b"")
                else:
                    raise NotImplementedError()

            elif msg_type == b"H":
                # Set current thread
                self.send_queue.append(b"OK")

            elif msg_type == b"?":
                # Report why the target halted
                self.send_queue.append(self.status)  # TRAP signal

            elif msg_type == b"g":
                # Report all general register values
                self.send_queue.append(self.report_general_register_values())

            elif msg_type == b"p":
                # Read a specific register
                reg_num = int(buf.read(), 16)
                self.send_queue.append(self.read_register(reg_num))

            elif msg_type == b"P":
                # Set a specific register
                reg_num, value = buf.read().split(b"=")
                reg_num = int(reg_num, 16)
                value = int(encode_hex(decode_hex(value)[::-1]), 16)
                self.set_register(reg_num, value)
                self.send_queue.append(b"OK")

            elif msg_type == b"m":
                # Read memory
                addr, size = (int(x, 16) for x in buf.read().split(b",", 1))
                self.send_queue.append(self.read_memory(addr, size))

            elif msg_type == b"k":
                # Kill
                self.sock.close()
                self.send_queue = []
                self.sock = None

            elif msg_type == b"!":
                # Extending debugging will be used
                self.send_queue.append(b"OK")

            elif msg_type == b"v":
                if msg == b"vCont?":
                    # Is vCont supported ?
                    self.send_queue.append(b"")

            elif msg_type == b"s":
                # Step
                self.dbg.step()
                self.send_queue.append(b"S05")  # TRAP signal

            elif msg_type == b"Z":
                # Add breakpoint or watchpoint
                bp_type = buf.read(1)
                if bp_type == b"0":
                    # Exec breakpoint
                    assert(buf.read(1) == b",")
                    addr, size = (int(x, 16) for x in buf.read().split(b",", 1))

                    if size != 1:
                        raise NotImplementedError("Bigger size")
                    self.dbg.add_breakpoint(addr)
                    self.send_queue.append(b"OK")

                elif bp_type == b"1":
                    # Hardware BP
                    assert(buf.read(1) == b",")
                    addr, size = (int(x, 16) for x in buf.read().split(b",", 1))

                    self.dbg.add_memory_breakpoint(
                        addr,
                        size,
                        read=True,
                        write=True
                    )
                    self.send_queue.append(b"OK")

                elif bp_type in [b"2", b"3", b"4"]:
                    # Memory breakpoint
                    assert(buf.read(1) == b",")
                    read = bp_type in [b"3", b"4"]
                    write = bp_type in [b"2", b"4"]
                    addr, size = (int(x, 16) for x in buf.read().split(b",", 1))

                    self.dbg.add_memory_breakpoint(
                        addr,
                        size,
                        read=read,
                        write=write
                    )
                    self.send_queue.append(b"OK")

                else:
                    raise ValueError("Impossible value")

            elif msg_type == b"z":
                # Remove breakpoint or watchpoint
                bp_type = buf.read(1)
                if bp_type == b"0":
                    # Exec breakpoint
                    assert(buf.read(1) == b",")
                    addr, size = (int(x, 16) for x in buf.read().split(b",", 1))

                    if size != 1:
                        raise NotImplementedError("Bigger size")
                    dbgsoft = self.dbg.get_breakpoint_by_addr(addr)
                    assert(len(dbgsoft) == 1)
                    self.dbg.remove_breakpoint(dbgsoft[0])
                    self.send_queue.append(b"OK")

                elif bp_type == b"1":
                    # Hardware BP
                    assert(buf.read(1) == b",")
                    addr, size = (int(x, 16) for x in buf.read().split(b",", 1))
                    self.dbg.remove_memory_breakpoint_by_addr_access(
                        addr,
                        read=True,
                        write=True
                    )
                    self.send_queue.append(b"OK")

                elif bp_type in [b"2", b"3", b"4"]:
                    # Memory breakpoint
                    assert(buf.read(1) == b",")
                    read = bp_type in [b"3", b"4"]
                    write = bp_type in [b"2", b"4"]
                    addr, size = (int(x, 16) for x in buf.read().split(b",", 1))

                    self.dbg.remove_memory_breakpoint_by_addr_access(
                        addr,
                        read=read,
                        write=write
                    )
                    self.send_queue.append(b"OK")

                else:
                    raise ValueError("Impossible value")

            elif msg_type == b"c":
                # Continue
                self.status = b""
                self.send_messages()
                ret = self.dbg.run()
                if isinstance(ret, debugging.DebugBreakpointSoft):
                    self.status = b"S05"
                    self.send_queue.append(b"S05")  # TRAP signal
                elif isinstance(ret, ExceptionHandle):
                    if ret == ExceptionHandle.memoryBreakpoint():
                        self.status = b"S05"
                        self.send_queue.append(b"S05")
                    else:
                        raise NotImplementedError("Unknown Except")
                elif isinstance(ret, debugging.DebugBreakpointTerminate):
                    # Connexion should close, but keep it running as a TRAP
                    # The connexion will be close on instance destruction
                    print(ret)
                    self.status = b"S05"
                    self.send_queue.append(b"S05")
                else:
                    raise NotImplementedError()

            else:
                raise NotImplementedError(
                    "Not implemented: message type %r" % msg_type
                )
Ejemplo n.º 21
0
import sys
from pdb import pm

from miasm.core.utils import decode_hex, encode_hex
from miasm.jitter.csts import PAGE_READ, PAGE_WRITE
from miasm.analysis.machine import Machine
from miasm.expression.expression import ExprId, ExprAssign, ExprInt, ExprMem
from miasm.core.locationdb import LocationDB

# Initial data: from 'example/samples/x86_32_sc.bin'
data = decode_hex("8d49048d5b0180f90174058d5bffeb038d5b0189d8c3")
loc_db = LocationDB()

# Init jitter
myjit = Machine("x86_32").jitter(loc_db, sys.argv[1])
myjit.init_stack()

run_addr = 0x40000000
myjit.vm.add_memory_page(run_addr, PAGE_READ | PAGE_WRITE, data)


# Sentinelle called on terminate
def code_sentinelle(jitter):
    jitter.running = False
    jitter.pc = 0
    return True


myjit.push_uint32_t(0x1337beef)
myjit.add_breakpoint(0x1337beef, code_sentinelle)
Ejemplo n.º 22
0
def code_sentinelle(jitter):
    jitter.run = False
    jitter.pc = 0
    return True


machine = Machine("x86_32")
jitter = machine.jitter(sys.argv[1])

jitter.init_stack()

# nop
# mov eax, 0x42
# jmp 0x20

data = decode_hex("90b842000000eb20")

# Will raise memory error at 0x40000028

error_raised = False


def raise_me(jitter):
    global error_raised
    error_raised = True
    assert jitter.pc == 0x40000028
    return False


jitter.add_exception_handler(EXCEPT_ACCESS_VIOL, raise_me)
Ejemplo n.º 23
0
def h2i(s):
    return decode_hex(s.replace(' ', ''))
Ejemplo n.º 24
0
from builtins import map
from pdb import pm

from future.utils import viewitems

from miasm.core.utils import decode_hex
from miasm.analysis.machine import Machine
from miasm.analysis.binary import Container
from miasm.core.asmblock import AsmCFG, AsmConstraint, AsmBlock, \
    AsmBlockBad, AsmConstraintTo, AsmConstraintNext, \
    bbl_simplifier
from miasm.core.graph import DiGraphSimplifier, MatchGraphJoker
from miasm.expression.expression import ExprId

# Initial data: from 'samples/simple_test.bin'
data = decode_hex("5589e583ec10837d08007509c745fc01100000eb73837d08017709c745fc02100000eb64837d08057709c745fc03100000eb55837d080774138b450801c083f80e7509c745fc04100000eb3c8b450801c083f80e7509c745fc05100000eb298b450883e03085c07409c745fc06100000eb16837d08427509c745fc07100000eb07c745fc081000008b45fcc9c3")
cont = Container.from_string(data)

# Test Disasm engine
machine = Machine("x86_32")
mdis = machine.dis_engine(cont.bin_stream, loc_db=cont.loc_db)
## Disassembly of one block
first_block = mdis.dis_block(0)
assert len(first_block.lines) == 5
print(first_block)

## Test redisassemble asmcfg
first_block_bis = mdis.dis_block(0)
assert len(first_block.lines) == len(first_block_bis.lines)
print(first_block_bis)