Python angr.SIM_PROCEDURES Examples

The following are 30 code examples of angr.SIM_PROCEDURES(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module angr , or try the search function .
Example #1
Source File: syscall.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def process_successors(self, successors, **kwargs):
        state = self.state
        # we have at this point entered the next step so we need to check the previous jumpkind
        if not state.history or not state.history.parent or not state.history.parent.jumpkind or not state.history.parent.jumpkind.startswith('Ijk_Sys'):
            return super().process_successors(successors, **kwargs)

        l.debug("Invoking system call handler")
        sys_procedure = self.project.simos.syscall(state)

        if sys_procedure is None:
            if angr.sim_options.BYPASS_UNSUPPORTED_SYSCALL not in state.options:
                raise AngrUnsupportedSyscallError("Trying to perform a syscall on an emulated system which is not currently cofigured to support syscalls. To resolve this, make sure that your SimOS is a subclass of SimUserspace, or set the BYPASS_UNSUPPORTED_SYSCALL state option.")
            else:
                try:
                    cc = angr.SYSCALL_CC[state.arch.name][state.os_name](state.arch)
                except KeyError:
                    try:
                        l.warning("No syscall calling convention available for %s/%s", state.arch.name, state.os_name)
                        cc = angr.SYSCALL_CC[state.arch.name]['default'](state.arch)
                    except KeyError:
                        cc = None # some default will get picked down the line...

                sys_procedure = angr.SIM_PROCEDURES['stubs']['syscall'](cc=cc)

        return self.process_procedure(state, successors, sys_procedure, **kwargs) 
Example #2
Source File: solve.py    From angr-doc with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setup_project():
    project = angr.Project('crypto.mod')

    # use libc functions as stand-ins for grub functions
    memset = angr.SIM_PROCEDURES['libc']['memset']
    getchar = angr.SIM_PROCEDURES['libc']['getchar']
    do_nothing = angr.SIM_PROCEDURES['stubs']['ReturnUnconstrained']

    project.hook_symbol('grub_memset', memset())
    project.hook_symbol('grub_getkey', getchar())

    # I don't know why, but grub_xputs is apparently not the function but a pointer to it?
    xputs_pointer_addr = project.loader.find_symbol('grub_xputs').rebased_addr
    xputs_func_addr = project.loader.extern_object.allocate()
    project.hook(xputs_func_addr, do_nothing())
    project.loader.memory.pack_word(xputs_pointer_addr, xputs_func_addr)

    return project 
Example #3
Source File: dep_view.py    From angr-management with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _convert_node(self, node: Definition, converted: Dict[Definition,QDepGraphBlock]) -> Optional[QDepGraphBlock]:
        if node in converted:
            return converted[node]

        # skip external
        if isinstance(node.codeloc, ExternalCodeLocation):
            return None

        if self.workspace.instance.project.is_hooked(node.codeloc.block_addr):
            hook = self.workspace.instance.project.hooked_by(node.codeloc.block_addr)
            if isinstance(hook, (SIM_PROCEDURES['stubs']['UnresolvableJumpTarget'],
                                 SIM_PROCEDURES['stubs']['UnresolvableCallTarget'])):
                return None

        new_node = QDepGraphBlock(False, self, definition=node, addr=node.codeloc.ins_addr)
        converted[node] = new_node
        return new_node 
Example #4
Source File: test_driller.py    From driller with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_simproc_drilling():
    """
    Test drilling on the cgc binary palindrome with simprocedures.
    """

    binary = "tests/i386/driller_simproc"
    memcmp = angr.SIM_PROCEDURES['libc']['memcmp']()
    simprocs = {0x8048200: memcmp}

    # fuzzbitmap says every transition is worth satisfying.
    d = driller.Driller(os.path.join(bin_location, binary), b"A"*0x80, b"\xff"*65535, "whatever~", hooks=simprocs)

    new_inputs = d.drill()

    # Make sure driller produced a new input which satisfies the memcmp.
    password = b"the_secret_password_is_here_you_will_never_guess_it_especially_since_it_is_going_to_be_made_lower_case"
    nose.tools.assert_true(any(filter(lambda x: x[1].startswith(password), new_inputs))) 
Example #5
Source File: test_pwrite_pread.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_pread():
    pwrite = SIM_PROCEDURES['posix']['pread64']()

    state = SimState(arch="AMD64", mode='symbolic')
    simfile = SimFile('concrete_file', content='hello world!\n')
    state.fs.insert('test', simfile)
    fd = state.posix.open(b"test", 1)

    buf1_addr = 0xd0000000
    buf2_addr = 0xd0001000
    pwrite.execute(state, arguments=[fd, buf1_addr, 6, 6])
    pwrite.execute(state, arguments=[fd, buf2_addr, 5, 0])

    data1 = state.solver.eval(state.mem[buf1_addr].string.resolved, cast_to=bytes)
    data2 = state.solver.eval(state.mem[buf2_addr].string.resolved, cast_to=bytes)

    nose.tools.assert_true(data1 == b'world!')
    nose.tools.assert_true(data2 == b'hello')

    state.posix.close(fd) 
Example #6
Source File: crazy_scanf.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def run(self, src, fmt, one, two, three): #pylint:disable=unused-argument
        memcpy = angr.SIM_PROCEDURES['libc']['memcpy']

        self.inline_call(memcpy, one, src, 5)
        self.state.memory.store(one+4, self.state.solver.BVV(0, 8))
        self.inline_call(memcpy, two, src+6, 8192)
        self.state.memory.store(two+8191, self.state.solver.BVV(0, 8))
        self.inline_call(memcpy, three, src+6+8193, 12)
        self.state.memory.store(three+11, self.state.solver.BVV(0, 8))

        #if angr.o.SYMBOLIC in self.state.options:
        #     #crazy_str = "index.asp?authorization=M3NhZG1pbjoyNzk4ODMwMw==&yan=yes\x00"
        #     #crazy_str = "index.asp?authorization=3sadmin:27988303&yan=yes\x00"
        #     crazy_str = "authorization=3sadmin:27988303\x00"
        #     self.state.add_constraints(self.state.memory.load(two, len(crazy_str)) == self.state.solver.BVV(crazy_str))

        return self.state.solver.BVV(3) 
Example #7
Source File: test_pwrite_pread.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_pwrite():
    pwrite = SIM_PROCEDURES['posix']['pwrite64']()

    state = SimState(arch="AMD64", mode='symbolic')
    simfile = SimFile('concrete_file', content='hello world!\n')
    state.fs.insert('test', simfile)
    fd = state.posix.open(b"test", 1)

    buf_addr = 0xd0000000
    state.memory.store(buf_addr, b'test!')
    pwrite.execute(state, arguments=[fd, buf_addr, 5, 6])

    simfd = state.posix.get_fd(fd)
    simfd.seek(0)
    res = 0xc0000000
    simfd.read(res, 13)
    data = state.solver.eval(state.mem[res].string.resolved, cast_to=bytes)

    nose.tools.assert_true(data == b'hello test!!\n')

    state.posix.close(fd) 
Example #8
Source File: test_sim_time.py    From angr with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_clock_gettime():
    proc = angr.SIM_PROCEDURES['posix']['clock_gettime']()

    s = angr.SimState(arch='amd64')
    s.regs.rdi = 0
    s.regs.rsi = 0x8000

    s.options.add(angr.options.USE_SYSTEM_TIMES)
    proc.execute(s)
    assert not s.mem[0x8000].qword.resolved.symbolic
    assert not s.mem[0x8008].qword.resolved.symbolic

    s.options.discard(angr.options.USE_SYSTEM_TIMES)
    proc.execute(s)
    assert s.mem[0x8000].qword.resolved.symbolic
    assert s.mem[0x8008].qword.resolved.symbolic 
Example #9
Source File: test_memory.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_copy():
    s = SimState(arch="AMD64")
    s.memory.store(0x100, b"ABCDEFGHIJKLMNOP")
    s.memory.store(0x200, b"XXXXXXXXXXXXXXXX")
    x = s.solver.BVS('size', s.arch.bits)
    s.add_constraints(s.solver.ULT(x, 10))
    s.memory.copy_contents(0x200, 0x100, x)

    nose.tools.assert_equal(sorted(s.solver.eval_upto(x, 100)), list(range(10)))
    result = s.memory.load(0x200, 5)
    nose.tools.assert_equal(sorted(s.solver.eval_upto(result, 100, cast_to=bytes)), [ b"ABCDE", b"ABCDX", b"ABCXX", b"ABXXX", b"AXXXX", b"XXXXX" ])
    nose.tools.assert_equal(sorted(s.solver.eval_upto(result, 100, cast_to=bytes, extra_constraints=[x==3])), [ b"ABCXX" ])

    s = SimState(arch="AMD64")
    s.register_plugin('posix', SimSystemPosix(stdin=SimFile(name='stdin', content=b'ABCDEFGHIJKLMNOP', has_end=True)))
    s.memory.store(0x200, b"XXXXXXXXXXXXXXXX")
    x = s.solver.BVS('size', s.arch.bits)
    s.add_constraints(s.solver.ULT(x, 10))

    s.posix.get_fd(0).read(0x200, x)
    nose.tools.assert_equal(sorted(s.solver.eval_upto(x, 100)), list(range(10)))
    result = s.memory.load(0x200, 5)
    nose.tools.assert_equal(sorted(s.solver.eval_upto(result, 100, cast_to=bytes)), [ b"ABCDE", b"ABCDX", b"ABCXX", b"ABXXX", b"AXXXX", b"XXXXX" ])
    nose.tools.assert_equal(sorted(s.solver.eval_upto(result, 100, cast_to=bytes, extra_constraints=[x==3])), [ b"ABCXX" ])

    s = SimState(arch="AMD64")
    s.register_plugin('posix', SimSystemPosix(stdin=SimFile(name='stdin', content=b'ABCDEFGHIJKLMNOP')))
    s.memory.store(0x200, b"XXXXXXXXXXXXXXXX")
    x = s.solver.BVS('size', s.arch.bits)
    s.add_constraints(s.solver.ULT(x, 10))

    read_proc = SIM_PROCEDURES['posix']['read']()
    ret_x = read_proc.execute(s, arguments=(0, 0x200, x)).ret_expr
    nose.tools.assert_equal(sorted(s.solver.eval_upto(x, 100)), list(range(10)))
    result = s.memory.load(0x200, 5)
    nose.tools.assert_equal(sorted(s.solver.eval_upto(result, 100, cast_to=bytes)), [ b"ABCDE", b"ABCDX", b"ABCXX", b"ABXXX", b"AXXXX", b"XXXXX" ])
    nose.tools.assert_equal(sorted(s.solver.eval_upto(result, 100, cast_to=bytes, extra_constraints=[x==3])), [ b"ABCXX" ])

    nose.tools.assert_equal(sorted(s.solver.eval_upto(ret_x, 100)), list(range(10)))
    nose.tools.assert_equal(sorted(s.solver.eval_upto(result, 100, cast_to=bytes, extra_constraints=[ret_x==3])), [ b"ABCXX" ]) 
Example #10
Source File: test_static_hooker.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_static_hooker():
    test_file = os.path.join(test_location, 'x86_64', 'static')
    p = angr.Project(test_file)
    sh = p.analyses.StaticHooker('libc.so.6')

    nose.tools.assert_in(4197616, sh.results)
    nose.tools.assert_is(type(sh.results[4197616]), angr.SIM_PROCEDURES['glibc']['__libc_start_main'])
    nose.tools.assert_is(type(p.hooked_by(4197616)), angr.SIM_PROCEDURES['glibc']['__libc_start_main']) 
Example #11
Source File: getchar.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self):
        fgetc = angr.SIM_PROCEDURES['libc']['fgetc']
        stdin = self.state.posix.get_fd(0)
        data = self.inline_call(fgetc, 0, simfd=stdin).ret_expr
        return data 
Example #12
Source File: fopen.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, p_addr, m_addr):
        strlen = angr.SIM_PROCEDURES['libc']['strlen']

        p_strlen = self.inline_call(strlen, p_addr)
        m_strlen = self.inline_call(strlen, m_addr)
        p_expr = self.state.memory.load(p_addr, p_strlen.max_null_index, endness='Iend_BE')
        m_expr = self.state.memory.load(m_addr, m_strlen.max_null_index, endness='Iend_BE')
        path = self.state.solver.eval(p_expr, cast_to=bytes)
        mode = self.state.solver.eval(m_expr, cast_to=bytes)

        # TODO: handle append
        fd = self.state.posix.open(path, mode_to_flag(mode))

        if fd is None:
            # if open failed return NULL
            return 0
        else:
            # Allocate a FILE struct in heap
            malloc = angr.SIM_PROCEDURES['libc']['malloc']
            io_file_data = io_file_data_for_arch(self.state.arch)
            file_struct_ptr = self.inline_call(malloc, io_file_data['size']).ret_expr

            # Write the fd
            fd_bvv = self.state.solver.BVV(fd, 4 * 8) # int
            self.state.memory.store(file_struct_ptr + io_file_data['fd'],
                                    fd_bvv,
                                    endness=self.state.arch.memory_endness)

            return file_struct_ptr 
Example #13
Source File: atol.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, s):
        strtol = angr.SIM_PROCEDURES['libc']['strtol']
        return strtol.strtol_inner(s, self.state, self.state.memory, 10, True)[1] 
Example #14
Source File: rewind.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, file_ptr):
        fseek = angr.SIM_PROCEDURES['libc']['fseek']
        self.inline_call(fseek, file_ptr, 0, 0)

        return None 
Example #15
Source File: strchr.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, s_addr, c_int, s_strlen=None):
        c = c_int[7:0]
        s_strlen = self.inline_call(angr.SIM_PROCEDURES['libc']['strlen'], s_addr)

        chunk_size = None
        if MEMORY_CHUNK_INDIVIDUAL_READS in self.state.options:
            chunk_size = 1

        if self.state.solver.symbolic(s_strlen.ret_expr):
            l.debug("symbolic strlen")
            # TODO: more constraints here to make sure we don't search too little
            max_sym = min(self.state.solver.max_int(s_strlen.ret_expr)+1, self.state.libc.max_symbolic_strchr)
            a, c, i = self.state.memory.find(s_addr, c, s_strlen.max_null_index, max_symbolic_bytes=max_sym, default=0)
        else:
            l.debug("concrete strlen")
            max_search = self.state.solver.eval(s_strlen.ret_expr)+1
            a, c, i = self.state.memory.find(s_addr, c, max_search, default=0, chunk_size=chunk_size)

        if len(i) > 1:
            a = a.annotate(MultiwriteAnnotation())
            self.state.add_constraints(*c)

        return a
        #self.state.add_constraints(self.state.solver.ULT(a - s_addr, s_strlen.ret_expr))
        #self.max_chr_index = max(i)
        #return a 
Example #16
Source File: wchar.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, lpString1, lpString2):
        strcmp = angr.SIM_PROCEDURES['libc']['strcmp']
        return self.inline_call(strcmp, lpString1, lpString2, wchar=True).ret_expr 
Example #17
Source File: strncat.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, dst, src, limit):
        strncpy = angr.SIM_PROCEDURES['libc']['strncpy']
        strlen = angr.SIM_PROCEDURES['libc']['strlen']
        dst_len = self.inline_call(strlen, dst).ret_expr
        src_len = self.inline_call(strlen, src).ret_expr

        self.inline_call(strncpy, dst + dst_len, src, limit, src_len=src_len)

        return dst 
Example #18
Source File: atoi.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, s):
        strtol = angr.SIM_PROCEDURES['libc']['strtol']
        return strtol.strtol_inner(s, self.state, self.state.memory, 10, True)[1] 
Example #19
Source File: test_memory.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_concrete_memset():
    def _individual_test(state, base, val, size):
        # time it
        start = time.time()
        memset = SIM_PROCEDURES['libc']['memset']().execute(
            state, arguments=[base, state.solver.BVV(val, 8), size]
        )
        elapsed = time.time() - start

        # should be done within 1 second
        nose.tools.assert_less_equal(elapsed, 5)
        # the result should be good
        byt_0 = memset.state.memory.load(base, 1)
        nose.tools.assert_equal(s.solver.eval_upto(byt_0, 10), [val])
        byt_1 = memset.state.memory.load(base+1, 1)
        nose.tools.assert_equal(s.solver.eval_upto(byt_1, 10), [val])
        byt_2 = memset.state.memory.load(base+size-1, 1)
        nose.tools.assert_equal(s.solver.eval_upto(byt_2, 10), [val])

    BASE = 0x800000
    SIZE = 0x200000

    # Writes many zeros
    VAL = 0
    s = SimState(arch='AMD64')
    _individual_test(s, BASE, VAL, SIZE)

    # Writes many ones
    VAL = 1
    s = SimState(arch='AMD64')
    _individual_test(s, BASE, VAL, SIZE) 
Example #20
Source File: test_unlink.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_file_unlink():
    # Initialize a blank state with an arbitrary errno location
    state = angr.SimState(arch="AMD64", mode="symbolic")
    state.libc.errno_location = 0xa0000000
    state.libc.errno = 0

    # Create a file 'test'
    fd = state.posix.open(b'test', 1)
    state.posix.close(fd)

    # Ensure 'test' was in fact created
    nose.tools.assert_in(b'/test', state.fs._files)

    # Store the filename in memory
    path_addr = 0xb0000000
    state.memory.store(path_addr, b'test\x00')

    # Unlink 'test': should return 0 and leave ERRNO unchanged
    unlink = angr.SIM_PROCEDURES['posix']['unlink']()
    state.scratch.sim_procedure = unlink
    rval = unlink.execute(state, arguments=[path_addr]).ret_expr
    nose.tools.assert_equal(rval, 0)
    nose.tools.assert_equal(state.solver.eval(state.libc.errno), 0)

    # Check that 'test' was in fact deleted
    nose.tools.assert_equal(state.fs._files, {})

    # Unlink again: should return -1 and set ERRNO to ENOENT
    unlink = angr.SIM_PROCEDURES['posix']['unlink']()
    state.scratch.sim_procedure = unlink
    rval = unlink.execute(state, arguments=[path_addr]).ret_expr
    nose.tools.assert_equal(rval, -1)
    nose.tools.assert_equal(state.solver.eval(state.libc.errno), state.posix.ENOENT) 
Example #21
Source File: test_driller_core.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_simprocs():
    binary = os.path.join(bin_location, 'tests', 'i386', 'driller_simproc')
    memcmp = angr.SIM_PROCEDURES['libc']['memcmp']()

    simgr, tracer = tracer_cgc(binary, 'driller_core_simprocs', b'A'*128, copy_states=True)
    p = simgr._project
    p.hook(0x8048200, memcmp)

    d = angr.exploration_techniques.DrillerCore(tracer._trace)
    simgr.use_technique(d)

    simgr.run()
    nose.tools.assert_in('diverted', simgr.stashes)
    nose.tools.assert_greater(len(simgr.diverted), 0) 
Example #22
Source File: test_sim_procedure.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_syscall_and_simprocedure():
    bin_path = os.path.join(BIN_PATH, 'tests', 'cgc', 'CADET_00002')
    proj = angr.Project(bin_path)
    cfg = proj.analyses.CFGFast(normalize=True)

    # check syscall
    node = cfg.get_any_node(proj.loader.kernel_object.mapped_base + 1)
    func = proj.kb.functions[node.addr]

    nose.tools.assert_true(node.is_simprocedure)
    nose.tools.assert_true(node.is_syscall)
    nose.tools.assert_false(node.to_codenode().is_hook)
    nose.tools.assert_false(proj.is_hooked(node.addr))
    nose.tools.assert_true(func.is_syscall)
    nose.tools.assert_true(func.is_simprocedure)
    nose.tools.assert_equal(type(proj.factory.snippet(node.addr)), SyscallNode)

    # check normal functions
    node = cfg.get_any_node(0x80480a0)
    func = proj.kb.functions[node.addr]

    nose.tools.assert_false(node.is_simprocedure)
    nose.tools.assert_false(node.is_syscall)
    nose.tools.assert_false(proj.is_hooked(node.addr))
    nose.tools.assert_false(func.is_syscall)
    nose.tools.assert_false(func.is_simprocedure)
    nose.tools.assert_equal(type(proj.factory.snippet(node.addr)), BlockNode)

    # check hooked functions
    proj.hook(0x80480a0, angr.SIM_PROCEDURES['libc']['puts']())
    cfg = proj.analyses.CFGFast(normalize=True)# rebuild cfg to updated nodes
    node = cfg.get_any_node(0x80480a0)
    func = proj.kb.functions[node.addr]

    nose.tools.assert_true(node.is_simprocedure)
    nose.tools.assert_false(node.is_syscall)
    nose.tools.assert_true(proj.is_hooked(node.addr))
    nose.tools.assert_false(func.is_syscall)
    nose.tools.assert_true(func.is_simprocedure)
    nose.tools.assert_equal(type(proj.factory.snippet(node.addr)), HookNode) 
Example #23
Source File: hook_lib_funcs.py    From IDAngr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def search_simproc(name):
    import angr
    for libname in angr.SIM_PROCEDURES:
        if name in angr.SIM_PROCEDURES[libname]:
            return angr.SIM_PROCEDURES[libname][name]
        elif name.startswith("_") and name[1:] in angr.SIM_PROCEDURES[libname]:
            return angr.SIM_PROCEDURES[libname][name[1:]] 
Example #24
Source File: test_cc.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_calling_conventions():

    #
    # SimProcedures
    #

    from angr.calling_conventions import SimCCCdecl

    args = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000, 100000, 1000000, 2000000, 14, 15, 16 ]
    arches = [
        ('X86', SimCCCdecl),
        ('AMD64', None),
        ('ARMEL', None),
        ('MIPS32', None),
        ('PPC32', None),
        ('PPC64', None),
    ]

    # x86, cdecl
    for arch, cc in arches:
        s = SimState(arch=arch)
        for reg, val, _, _ in s.arch.default_register_values:
            s.registers.store(reg, val)

        if cc is not None:
            manyargs = SIM_PROCEDURES['testing']['manyargs'](cc=cc(s.arch)).execute(s)
        else:
            manyargs = SIM_PROCEDURES['testing']['manyargs']().execute(s)

        # Simulate a call
        if s.arch.call_pushes_ret:
            s.regs.sp = s.regs.sp + s.arch.stack_change
        manyargs.set_args(args)


        for index, arg in enumerate(args):
            nose.tools.assert_true(s.solver.is_true(manyargs.arg(index) == arg)) 
Example #25
Source File: test_inspect.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_inspect_syscall():
    class counts: #pylint:disable=no-init
        exit_before = 0
        exit_after = 0

    def handle_syscall_before(state):
        counts.exit_before += 1
        syscall_name = state.inspect.syscall_name
        nose.tools.assert_equal(syscall_name, "close")

    def handle_syscall_after(state):
        counts.exit_after += 1
        syscall_name = state.inspect.syscall_name
        nose.tools.assert_equal(syscall_name, "close")

    s = SimState(arch="AMD64", mode="symbolic")
    # set up to call so syscall close
    s.regs.rax = 3
    s.regs.rdi = 2

    # break on syscall
    s.inspect.b('syscall', BP_BEFORE, action=handle_syscall_before)
    s.inspect.b('syscall', BP_AFTER, action=handle_syscall_after)

    # step it
    proc = SIM_PROCEDURES['posix']['close'](is_syscall=True)
    ProcedureEngine(None).process(s, procedure=proc, ret_to=s.ip)

    # check counts
    nose.tools.assert_equal(counts.exit_before, 1)
    nose.tools.assert_equal(counts.exit_after, 1) 
Example #26
Source File: test_actions.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_procedure_actions():
    s = SimState(arch='AMD64')

    s.registers.store('rbx', 2)
    proc = SIM_PROCEDURES['testing']['retreg'](reg='rbx')
    succ = ProcedureEngine(None).process(s, procedure=proc)
    rbx = succ.artifacts['procedure'].ret_expr
    nose.tools.assert_is(type(rbx), angr.state_plugins.SimActionObject)
    nose.tools.assert_equal(s.solver.eval(rbx), 2)
    nose.tools.assert_equal(rbx.reg_deps, { s.arch.registers['rbx'][0] }) 
Example #27
Source File: util.py    From angr-utils with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hook0(project):
    try:
        project.hook(0x0, angr.SIM_PROCEDURES['stubs']['PathTerminator'](project=project))
        yield
    finally:
        project.unhook(0x0) 
Example #28
Source File: solve.py    From angr-doc with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def solve_flag_1():

    # shutdown some warning produced by this example
    #logging.getLogger('angr.engines.vex.irsb').setLevel(logging.ERROR)

    proj = angr.Project('bomb', auto_load_libs=False)


    start = 0x400ee0
    bomb_explode = 0x40143a
    end = 0x400ef7

    # `strings_not_equal` behaves exactly the same as `strcmp` to us, so we simply hook it
    proj.hook(0x0401338, angr.SIM_PROCEDURES['libc']['strcmp']())

    # initial state is at the beginning of phase_one()
    state = proj.factory.blank_state(addr=start)

    # a symbolic input string with a length up to 128 bytes
    arg = state.solver.BVS("input_string", 8 * 128)

    # read_line() reads a line from stdin and stores it a this address
    bind_addr = 0x603780

    # bind the symbolic string at this address
    state.memory.store(bind_addr, arg)

    # phase_one reads the string [rdi]
    state.add_constraints(state.regs.rdi == bind_addr)

    # Attempt to find a path to the end of the phase_1 function while avoiding the bomb_explode
    simgr = proj.factory.simulation_manager(state)
    simgr.explore(find=end, avoid=bomb_explode)

    if simgr.found:
        found = simgr.found[0]
        flag = found.solver.eval(arg, cast_to=bytes)
        return flag[:flag.index(b'\x00')].decode() # remove everyting after \x00 because they won't be compared
    else:
        raise Exception("angr failed to find a path to the solution :(") 
Example #29
Source File: fputs.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self, str_addr, file_ptr):
        # TODO handle errors
        fd_offset = io_file_data_for_arch(self.state.arch)['fd']
        fileno = self.state.mem[file_ptr + fd_offset:].int.resolved
        simfd = self.state.posix.get_fd(fileno)
        if simfd is None:
            return -1

        strlen = angr.SIM_PROCEDURES['libc']['strlen']
        p_strlen = self.inline_call(strlen, str_addr)
        simfd.write(str_addr, p_strlen.max_null_index)
        return 1 
Example #30
Source File: solve13.py    From angr_ctf with GNU General Public License v3.0 5 votes vote down vote up
def main(argv):
  path_to_binary = argv[1]
  project = angr.Project(path_to_binary)

  initial_state = project.factory.entry_state()
 
  project.hook(0x804ed40, angr.SIM_PROCEDURES['libc']['printf']())
  project.hook(0x804ed80, angr.SIM_PROCEDURES['libc']['scanf']())
  project.hook(0x804f350, angr.SIM_PROCEDURES['libc']['puts']())
  project.hook(0x8048d10, angr.SIM_PROCEDURES['glibc']['__libc_start_main']())

  simulation = project.factory.simgr(initial_state)

  # Define a function that checks if you have found the state you are looking
  # for.
  def is_successful(state):
    # Dump whatever has been printed out by the binary so far into a string.
    stdout_output = state.posix.dumps(sys.stdout.fileno())

    # Return whether 'Good Job.' has been printed yet.
    # (!)
    return 'Good Job.' in stdout_output  # :boolean

  # Same as above, but this time check if the state should abort. If you return
  # False, Angr will continue to step the state. In this specific challenge, the
  # only time at which you will know you should abort is when the program prints
  # "Try again."
  def should_abort(state):
    stdout_output = state.posix.dumps(sys.stdout.fileno())
    return 'Try again.' in stdout_output  # :boolean

  # Tell Angr to explore the binary and find any state that is_successful identfies
  # as a successful state by returning True.
  simulation.explore(find=is_successful, avoid=should_abort)
  
  if simulation.found:
    solution_state = simulation.found[0]
    print solution_state.posix.dumps(sys.stdin.fileno())
  else:
    raise Exception('Could not find the solution')