Пример #1
0
def main():
    parser = argparse.ArgumentParser(description='Follow a concrete trace')
    parser.add_argument('-f', '--explore_from', help='Value of PC from which to explore symbolically', type=str)
    parser.add_argument('-t', '--explore_to', type=str, default=sys.maxsize,
                        help="Value of PC until which to explore symbolically. (Probably don't want this set)")
    parser.add_argument('--verbose', '-v', action='count', default=0, help='Increase verbosity')
    parser.add_argument('cmd', type=str, nargs='+',
                        help='Program and arguments. Use "--" to separate script arguments from target arguments')
    args = parser.parse_args(sys.argv[1:])

    range = None
    if args.explore_from:
        range = (args.explore_from, args.explore_to)

    # Create a concrete Manticore and record it
    m1 = Manticore.linux(args.cmd[0], args.cmd[1:])
    t = ExtendedTracer()
    r = TraceReceiver(t)
    m1.verbosity(args.verbose)
    m1.register_plugin(t)
    m1.register_plugin(r)
    m1.run(procs=1)

    time.sleep(3)

    # Create a symbolic Manticore and follow last trace
    symbolic_args = ['+'*len(arg) for arg in args.cmd[1:]]
    m2 = Manticore.linux(args.cmd[0], symbolic_args)
    f = Follower(r.trace)
    if range:
        f.add_symbolic_range(*range)
    m2.verbosity(args.verbose)
    m2.register_plugin(f)
    m2.run()
Пример #2
0
def verify(argv):
    logger.debug("Verifying program \"{}\"".format(argv))

    # Address and stack_size are from linux.py
    # TODO(yan): Refactor these constants into a reachable value in platform
    qemu.start('arm', argv, va_size=stack_top, stack_size=stack_size)
    gdb.start('arm', argv)

    m = Manticore(argv[0], argv[1:])
    m.verbosity = 2

    init_logging()
    logger.setLevel(logging.DEBUG)

    @m.hook(None)
    def on_instruction(state):
        '''
        Handle all the hooks for each instruction executed. Ordered as:

        pre_qemu
         * qemu exec *
        post_qemu

        // svc synchronization happens here (mmap specifically)

        pre_mcore
         * mcore exec *
        post_mcore

        // all memory written in a mcore syscall gets moved to qemu here
        '''
        global initialized, last_instruction

        # Initialize our state to QEMU's
        if not initialized:
            initialize(state)
            initialized = True

        if last_instruction:
            post_mcore(state, last_instruction)

        # Kernel helpers are inline in QEMU; do nothing
        if (state.cpu.PC >> 16) == 0xffff:
            return

        pre_qemu(state)
        last_mnemonic = [x.strip() for x in gdb.getInstruction().split(':')
                         ][1].split('\t')[0]
        gdb.stepi()
        post_qemu(state, last_mnemonic)

        last_instruction = state.cpu.instruction
        pre_mcore(state)

    m.run()
Пример #3
0
def verify(argv):
    logger.debug("Verifying program \"{}\"".format(argv))

    # Address and stack_size are from linux.py
    # TODO(yan): Refactor these constants into a reachable value in platform
    qemu.start('arm', argv, va_size=stack_top, stack_size=stack_size)
    gdb.start('arm', argv)

    m = Manticore(argv[0], argv[1:])
    m.verbosity = 2

    init_logging()
    logger.setLevel(logging.DEBUG)

    @m.hook(None)
    def on_instruction(state):
        '''
        Handle all the hooks for each instruction executed. Ordered as:

        pre_qemu
         * qemu exec *
        post_qemu

        // svc synchronization happens here (mmap specifically)

        pre_mcore
         * mcore exec *
        post_mcore

        // all memory written in a mcore syscall gets moved to qemu here
        '''
        global initialized, last_instruction

        # Initialize our state to QEMU's
        if not initialized:
            initialize(state)
            initialized = True

        if last_instruction:
            post_mcore(state, last_instruction)

        # Kernel helpers are inline in QEMU; do nothing
        if (state.cpu.PC >> 16) == 0xffff:
            return

        pre_qemu(state)
        last_mnemonic = [x.strip() for x in gdb.getInstruction().split(':')][1].split('\t')[0]
        gdb.stepi()
        post_qemu(state, last_mnemonic)

        last_instruction = state.cpu.instruction
        pre_mcore(state)

    m.run()
Пример #4
0
def benchmark(program):
    print(f"[*] Benchmarking program \"{program}\"")

    m = Manticore(program)
    m.run(should_profile=True)

    results = m._executor.dump_stats()
    if results is None:
        print(f"[*] Failed to collect stats for program {program}")
        return

    display(results)
    return results
Пример #5
0
def benchmark(program):
    print("[*] Benchmarking program \"{}\"".format(program))

    m = Manticore(program)
    m.should_profile = True
    m.run()

    results = m._executor.dump_stats()
    if results is None:
        print("[*] Failed to collect stats for program {}".format(program))
        return

    display(results)
    return results
Пример #6
0
def benchmark(program):
    print "[*] Benchmarking program \"{}\"".format(program)

    m = Manticore(program)
    m.should_profile = True
    m.run()

    results = m._executor.dump_stats()
    if results is None:
        print "[*] Failed to collect stats for program {}".format(program)
        return

    display(results)
    return results
Пример #7
0
 def test_integration_basic_stdin(self):
     import os, struct
     self.m = Manticore('tests/binaries/basic_linux_amd64')
     self.m.run()
     workspace = os.path.join(os.getcwd(), self.m.workspace)
     with open(os.path.join(workspace, 'test_00000001.stdin')) as f:
         a = struct.unpack('<I', f.read())[0]
     with open(os.path.join(workspace, 'test_00000002.stdin')) as f:
         b = struct.unpack('<I', f.read())[0]
     if a > 0x41:
         self.assertTrue(a > 0x41)
         self.assertTrue(b <= 0x41)
     else:
         self.assertTrue(a <= 0x41)
         self.assertTrue(b > 0x41)
Пример #8
0
class ManticoreTest(unittest.TestCase):
    def setUp(self):
        self.m = Manticore('tests/binaries/arguments_linux_amd64')

    def test_add_hook(self):
        def tmp(state):
            pass

        entry = 0x00400e40
        self.m.add_hook(entry, tmp)
        self.assertTrue(tmp in self.m._hooks[entry])

    def test_hook_dec(self):
        entry = 0x00400e40

        @self.m.hook(entry)
        def tmp(state):
            pass

        self.assertTrue(tmp in self.m._hooks[entry])

    def test_hook(self):
        self.m.context['x'] = 0

        @self.m.hook(None)
        def tmp(state):
            self.m.context['x'] = 1
            self.m.terminate()

        self.m.run()

        self.assertEqual(self.m.context['x'], 1)

    def test_hook_dec_err(self):
        with self.assertRaises(TypeError):

            @self.m.hook('0x00400e40')
            def tmp(state):
                pass

    @unittest.skip(
        'TODO(mark): (#52) activating this test breaks something z3 related for following tests'
    )
    def test_integration_basic_stdin(self):
        import os, struct
        self.m = Manticore('tests/binaries/basic_linux_amd64')
        self.m.run()
        workspace = os.path.join(os.getcwd(), self.m.workspace)
        with open(os.path.join(workspace, 'test_00000001.stdin')) as f:
            a = struct.unpack('<I', f.read())[0]
        with open(os.path.join(workspace, 'test_00000002.stdin')) as f:
            b = struct.unpack('<I', f.read())[0]
        if a > 0x41:
            self.assertTrue(a > 0x41)
            self.assertTrue(b <= 0x41)
        else:
            self.assertTrue(a <= 0x41)
            self.assertTrue(b > 0x41)
Пример #9
0
def symbolic_run_get_cons(trace):
    '''
    Execute a symbolic run that follows a concrete run; return constraints generated
    and the stdin data produced
    '''

    m2 = Manticore.linux(prog, workspace_url='mem:')
    f = Follower(trace)
    m2.verbosity(VERBOSITY)
    m2.register_plugin(f)

    def on_term_testcase(mcore, state, stateid, err):
        with m2.locked_context() as ctx:
            readdata = []
            for name, fd, data in state.platform.syscall_trace:
                if name in ('_receive', '_read') and fd == 0:
                    readdata.append(data)
            ctx['readdata'] = readdata
            ctx['constraints'] = list(state.constraints.constraints)

    m2.subscribe('will_terminate_state', on_term_testcase)

    m2.run()

    constraints = m2.context['constraints']
    datas = m2.context['readdata']

    return constraints, datas
Пример #10
0
class ManticoreTest(unittest.TestCase):
    _multiprocess_can_split_ = True

    def setUp(self):
        self.m = Manticore('tests/binaries/arguments_linux_amd64')

    def test_add_hook(self):
        def tmp(state):
            pass

        entry = 0x00400e40
        self.m.add_hook(entry, tmp)
        self.assertTrue(tmp in self.m._hooks[entry])

    def test_hook_dec(self):
        entry = 0x00400e40

        @self.m.hook(entry)
        def tmp(state):
            pass

        self.assertTrue(tmp in self.m._hooks[entry])

    def test_hook(self):
        self.m.context['x'] = 0

        @self.m.hook(None)
        def tmp(state):
            self.m.context['x'] = 1
            self.m.terminate()

        self.m.run()

        self.assertEqual(self.m.context['x'], 1)

    def test_hook_dec_err(self):
        with self.assertRaises(TypeError):

            @self.m.hook('0x00400e40')
            def tmp(state):
                pass

    def test_integration_basic_stdin(self):
        import os, struct
        self.m = Manticore('tests/binaries/basic_linux_amd64')
        self.m.run()
        workspace = self.m._output.uri  # os.path.join(os.getcwd(), self.m.workspace)
        with open(os.path.join(workspace, 'test_00000000.stdin')) as f:
            a = struct.unpack('<I', f.read())[0]
        with open(os.path.join(workspace, 'test_00000001.stdin')) as f:
            b = struct.unpack('<I', f.read())[0]
        if a > 0x41:
            self.assertTrue(a > 0x41)
            self.assertTrue(b <= 0x41)
        else:
            self.assertTrue(a <= 0x41)
            self.assertTrue(b > 0x41)
Пример #11
0
 def test_integration_basic_stdin(self):
     import struct
     dirname = os.path.dirname(__file__)
     self.m = Manticore(
         os.path.join(dirname, 'binaries', 'basic_linux_amd64'))
     self.m.run()
     workspace = self.m._output.store.uri
     with open(os.path.join(workspace, 'test_00000000.stdin'), 'rb') as f:
         a = struct.unpack('<I', f.read())[0]
     with open(os.path.join(workspace, 'test_00000001.stdin'), 'rb') as f:
         b = struct.unpack('<I', f.read())[0]
     if a > 0x41:
         self.assertTrue(a > 0x41)
         self.assertTrue(b <= 0x41)
     else:
         self.assertTrue(a <= 0x41)
         self.assertTrue(b > 0x41)
Пример #12
0
def concrete_run_get_trace(inp):
    m1 = Manticore.linux(prog, concrete_start=inp, workspace_url='mem:')
    t = ExtendedTracer()
    r = TraceReceiver(t)
    m1.verbosity(VERBOSITY)
    m1.register_plugin(t)
    m1.register_plugin(r)
    m1.run(procs=1)
    return r.trace
Пример #13
0
class ManticoreTest(unittest.TestCase):
    _multiprocess_can_split_ = True
    def setUp(self):
        self.m = Manticore('tests/binaries/arguments_linux_amd64')

    def test_add_hook(self):
        def tmp(state):
            pass
        entry = 0x00400e40
        self.m.add_hook(entry, tmp)
        self.assertTrue(tmp in self.m._hooks[entry])

    def test_hook_dec(self):
        entry = 0x00400e40
        @self.m.hook(entry)
        def tmp(state):
            pass
        self.assertTrue(tmp in self.m._hooks[entry])

    def test_hook(self):
        self.m.context['x'] = 0

        @self.m.hook(None)
        def tmp(state):
            self.m.context['x'] = 1
            self.m.terminate()
        self.m.run()

        self.assertEqual(self.m.context['x'], 1)

    def test_hook_dec_err(self):
        with self.assertRaises(TypeError):
            @self.m.hook('0x00400e40')
            def tmp(state):
                pass

    def test_integration_basic_stdin(self):
        import os, struct
        self.m = Manticore('tests/binaries/basic_linux_amd64')
        self.m.run()
        workspace = self.m._output.uri# os.path.join(os.getcwd(), self.m.workspace)
        with open(os.path.join(workspace, 'test_00000000.stdin')) as f:
            a = struct.unpack('<I', f.read())[0]
        with open(os.path.join(workspace, 'test_00000001.stdin')) as f:
            b = struct.unpack('<I', f.read())[0]
        if a > 0x41:
            self.assertTrue(a > 0x41)
            self.assertTrue(b <= 0x41)
        else:
            self.assertTrue(a <= 0x41)
            self.assertTrue(b > 0x41)
Пример #14
0
def concrete_run(prog, params):
    print "Starting concrete execution"

    m = Manticore(prog, params)
    # 'trace' will contain the executed instructions
    m.context['trace'] = []

    # None: The hook will be applied to all the instructions
    @m.hook(None)
    def record_trace(state):
        pc = state.cpu.PC

        # Store the instruction
        m.context['trace'] += [pc]

    m.run()

    # Print number of instructions recorded
    print "%d instructions are recorded" % len(m.context['trace'])

    return m.context
Пример #15
0
def symbolic_run(prog, params, trace, pc_crash):
    print "Starting symbolic execution"

    trace_set = set(trace)
    m = Manticore(prog, params)

    # The hook will be applied only to the instruction @pc_crash
    @m.hook(pc_crash)
    def crash_analysis(state):
        # Add the constraint on eax
        state.constrain(state.cpu.EAX == 0x0804887c)  # 0x0804887c = @call_me
        # Retrieve the arguments corresponding to argv[1]
        argv_1 = next((i for i in state.input_symbols if i.name == 'ARGV1_1'),
                      None)
        if argv_1:
            # Ask the value of argv_1 to the solver
            val_argv_1 = state.solve_one(argv_1)
            # Pretty print of the solution
            print "The solution is:"
            print "\\x" + "\\x".join("{:02x}".format(ord(c))
                                     for c in val_argv_1)
        state.abandon()

    trace_set = set(trace)  # convert the list to a set

    # None: The hook will be applied to all the instructions
    @m.hook(None)
    def follow_trace(state):
        if 'visited' not in state.context:
            state.context['visited'] = set()
        state.context['visited'].add(state.cpu.PC)

        # We stop to explore the current path if it doesn't follow the targeted path
        if not state.context['visited'] <= trace_set:
            print "State diverge at 0x%x" % state.cpu.PC
            state.abandon()

    m.run()
Пример #16
0
 def test_integration_basic_stdin(self):
     import os, struct
     self.m = Manticore('tests/binaries/basic_linux_amd64')
     self.m.run()
     workspace = self.m._output.uri# os.path.join(os.getcwd(), self.m.workspace)
     with open(os.path.join(workspace, 'test_00000000.stdin')) as f:
         a = struct.unpack('<I', f.read())[0]
     with open(os.path.join(workspace, 'test_00000001.stdin')) as f:
         b = struct.unpack('<I', f.read())[0]
     if a > 0x41:
         self.assertTrue(a > 0x41)
         self.assertTrue(b <= 0x41)
     else:
         self.assertTrue(a <= 0x41)
         self.assertTrue(b > 0x41)
Пример #17
0
    def test_symbolic_argv_envp(self):

        self.m = Manticore.linux('tests/binaries/arguments_linux_amd64', argv=['+'],
                                 envp={'TEST': '+'})
        state = self.m.initial_state

        ptr = state.cpu.read_int(state.cpu.RSP + (8*2))  # get argv[1]
        mem = state.cpu.read_bytes(ptr, 2)
        self.assertTrue(issymbolic(mem[0]))
        self.assertEqual(mem[1], '\0')

        ptr = state.cpu.read_int(state.cpu.RSP + (8*4))  # get envp[0]
        mem = state.cpu.read_bytes(ptr, 7)
        self.assertEqual(''.join(mem[:5]), 'TEST=')
        self.assertEqual(mem[6], '\0')
        self.assertTrue(issymbolic(mem[5]))
Пример #18
0
    def test_symbolic_argv_envp(self):

        dirname = os.path.dirname(__file__)
        self.m = Manticore.linux(os.path.join(dirname, 'binaries',
                                              'arguments_linux_amd64'),
                                 argv=['+'],
                                 envp={'TEST': '+'})
        state = self.m.initial_state

        ptr = state.cpu.read_int(state.cpu.RSP + (8 * 2))  # get argv[1]
        mem = state.cpu.read_bytes(ptr, 2)
        self.assertTrue(issymbolic(mem[0]))
        self.assertEqual(mem[1], b'\0')

        ptr = state.cpu.read_int(state.cpu.RSP + (8 * 4))  # get envp[0]
        mem = state.cpu.read_bytes(ptr, 7)
        self.assertEqual(b''.join(mem[:5]), b'TEST=')
        self.assertEqual(mem[6], b'\0')
        self.assertTrue(issymbolic(mem[5]))
Пример #19
0
 def testCreating(self):
     m = Manticore('/bin/ls')
     m.log_file = '/dev/null'
Пример #20
0
from manticore import Manticore
import subprocess
import sys
import ctypes


def myexec(cmd):
    return subprocess.check_output(cmd, shell=True)


resp = myexec("objdump -M intel -D ./tmp | grep \"400837\"").split(
    "rbp-")[1].strip()[:-1:]
buf1_off = int(resp, 16)

m = Manticore('./tmp')


# hook strlen
@m.hook(0x400640)
def strlen_model(state):
    buf = state.cpu.read_register('RDI')
    cnt = 0
    while True:
        c = state.cpu.read_int(buf + cnt, 8)
        if c == 0:
            break
        else:
            cnt += 1
    state.cpu.RAX = cnt
    state.cpu.RIP = 0x4009ab  # ret gadget
Пример #21
0
from manticore import Manticore


def fixme():
    raise Exception("Fill in the blanks!")


# Let's initialize the manticore control object
m = Manticore('multiple-styles')


# Now, we can hook the success state and figure out the flag! `fixme()` here
# should be an address we'd like to get to
@m.hook(fixme())
def solve(state):
    # Where is the flag in memory? It's probably offset from the base pointer
    # somehow
    flag_base = state.cpu.RBP - fixme()

    # We're going to build a solution later
    solution = ''

    # How big is the flag? We should be able to figure this out from traditional
    # static analysis
    for i in xrange(fixme()):
        # We can get the symbolic flag out
        symbolic_character = state.cpu.read_int(flag_base + i, 8)
        # And now we just need to solve for it in z3. How might we do that?
        # Perhaps `grep -r "def solve" manticore` can help our case
        concrete_character = fixme()
        solution += chr(concrete_character)
Пример #22
0
#!/usr/bin/env python

import sys
from manticore import Manticore

'''
Demonstrates the ability to set a basic hook on a specific program counter and
the ability to read from memory.
'''

if __name__ == '__main__':
    path = sys.argv[1]
    pc = int(sys.argv[2], 0)

    m = Manticore(path)

    # Trigger an event when PC reaches a certain value
    @m.hook(pc)
    def reached_goal(state):
        cpu = state.cpu

        assert cpu.PC == pc

        instruction = cpu.read_int(cpu.PC)
        print "Execution goal reached."
        print "Instruction bytes: {:08x}".format(instruction)

    # Start path exploration. m.run() returns when Manticore
    # finishes
    m.run()
Пример #23
0
def main():
    args = parse_arguments()

    m = Manticore(args.programs[0], args.programs[1:])

    m.policy = args.policy
    m.args = args

    if args.workspace:
        m.workspace = args.workspace

    if args.profile:
        m.should_profile = args.profile

    if args.dumpafter != 0:
        m.dumpafter = args.dumpafter

    if args.maxstorage != 0:
        m.maxstorage = args.maxstorage

    if args.maxstates != 0:
        m.maxstates = args.maxstates

    if args.coverage:
        m.coverage_file = args.coverage

    if args.names is not None:
        m.apply_model_hooks(args.names)

    if args.procs:
        m.workers = args.procs

    if args.env:
        for entry in args.env:
            name, val = entry[0].split('=')
            m.env_add(name, val)

    if args.assertions:
        m.load_assertions(args.assertions)

    if args.verbose:
        m.verbosity = 4
    else:
        m.verbosity = 1

    logger.info('Loading program: {}'.format(args.programs))
    logger.info('Workspace: {}'.format(m.workspace))

    m.run(args.timeout)

    m.dump_stats()
Пример #24
0
def mcore_calloc(filename, call, seed = None):

	#FASTBINS 

        m = Manticore(filename)
	if seed:
		m.concrete_data = seed

        @m.hook(0x555555554000+call)
        def fastbin_hook(state):
                cpu = state.cpu
                state.add(cpu.RDI * cpu.RSI <= 0x80)

                rdi = state.solve_one(cpu.read_register("RDI"))
                rsi = state.solve_one(cpu.read_register("RSI"))

                print "Fastbin with calloc(%d, %d)" % (rdi, rsi)
                fastbins.append(call)
                m.terminate()

	#m.verbosity = 2
	m.workers = 8
        m.run()


	#SMALL BINS

        m = Manticore(filename)
	if seed:
		m.concrete_data = seed

        @m.hook(0x555555554000+call)
        def fastbin_hook(state):
                cpu = state.cpu
                state.add(cpu.RSI >= 0x80)
                state.add(cpu.RSI <= 0x400)

                rdi = state.solve_one(cpu.read_register("RDI"))
                rsi = state.solve_one(cpu.read_register("RSI"))

                print "Smallbins with calloc(%d, %d)" % (rdi, rsi)
                fastbins.append(call)
                m.terminate()

	m.verbosity = 2
	m.workers = 8
        m.run()

	exit(1)

	#LARGE BINS
        m = Manticore(filename)
	if seed:
		m.concrete_data = seed

        @m.hook(0x555555554000+call)
        def fastbin_hook(state):
                cpu = state.cpu
                state.add(cpu.RSI >= 0x400)
                state.add(cpu.RSI <= 0x4000)

                rdi = state.solve_one(cpu.read_register("RDI"))
                rsi = state.solve_one(cpu.read_register("RSI"))

                print "Largebins with calloc(%d, %d)" % (rdi, rsi)
                fastbins.append(call)
                m.terminate()

	#m.verbosity = 2
	m.workers = 8
        m.run()

	#LARGE BINS
        m = Manticore(filename)
	if seed:
		m.concrete_data = seed

        @m.hook(0x555555554000+call)
        def fastbin_hook(state):
                cpu = state.cpu
                state.add(cpu.RDI * cpu.RSI >= 0x400)
                state.add(cpu.RDI * cpu.RSI <= 0x4000)

                rdi = state.solve_one(cpu.read_register("RDI"))
                rsi = state.solve_one(cpu.read_register("RSI"))

                print "MMAPbins with calloc(%d, %d)" % (rdi, rsi)
                fastbins.append(call)
                m.terminate()

	#m.verbosity = 2
	m.workers = 8
        m.run()
Пример #25
0
from manticore import Manticore
"""
Leverages Manticore to solve the Google 2016 challenge: 
unbreakable-enterprise-product-activation

Author: @ctfhacker
Binary: https://github.com/ctfs/write-ups-2016/blob/master/google-ctf-2016/reverse/unbreakable-enterprise-product-activation-150/unbreakable-enterprise-product-activation.bz2
"""

m = Manticore('unbreakable')
"""
These values can be found at 0x4005b8
"""
input_addr = 0x6042c0
num_bytes = 0x43


# Entry point
@m.hook(0x400729)
def hook(state):
    """ CAUTION: HACK """
    """ From entry point, jump directly to code performing check """

    # Create a symbolic buffer for our input
    buffer = state.new_symbolic_buffer(0x43)

    # We are given in the challenge that the flag begins with CTF{
    # So we can apply constraints to ensure that is true
    state.constrain(buffer[0] == ord('C'))
    state.constrain(buffer[1] == ord('T'))
    state.constrain(buffer[2] == ord('F'))
Пример #26
0
user    0m50.272s
sys     0m2.340s
"""

addrs = []

def get_exits():
    """ Extract exit calls from each check function using r2 """
    r2 = r2pipe.open('manticore_challenge')
    r2.cmd('aaa')
    exits_disasm = r2.cmd('pdf @@ sym.check*~exit')
    exits = [int(line.split()[2], 16) for line in exits_disasm.split('\n')]
    for exit in exits:
        yield exit

m = Manticore('manticore_challenge')

buff_addr = None

@m.hook(0x4009a4)
def hook(state):
    """ Jump over `puts` and `fgets` calls """
    state.cpu.EIP = 0x4009c1

@m.hook(0x4009c8)
def hook(state):
    """ Inject symbolic buffer instead of fgets """
    global buff_addr
    buff_addr = state.cpu.RDI
    buffer = state.new_symbolic_buffer(12)
    state.cpu.write_bytes(buff_addr, buffer)
Пример #27
0
import sys
from manticore import Manticore

'''
Minimal example demonstrating setting execution hooks, the ability to target
multiple target architectures, and symbolicating memory.
'''

if __name__ == '__main__':

    if len(sys.argv) < 2:
        print "Usage: {} [binary] [arguments]".format(sys.argv[0])
        sys.exit(1)

    # Create a new Manticore object
    m = Manticore(sys.argv[1], sys.argv[2:])

    if m.arch == 'arm':
        target = (0x1082c, 'R4')
    else:
        target = (0x400a83, 'EBX')

    @m.hook(target[0])
    def entered_func(state):
        '''
        For ARM, Make R4 symbolic at 0x1082c, as r4 is used in a branch right
        after.
        '''
        sym_var = state.new_symbolic_value(32, label='from_callback')
        state.cpu.write_register(target[1], sym_var)
Пример #28
0
from manticore import Manticore
"""
Leverages Manticore to solve the Google 2016 challenge: 
unbreakable-enterprise-product-activation

Author: @ctfhacker
Binary: https://github.com/ctfs/write-ups-2016/blob/master/google-ctf-2016/reverse/unbreakable-enterprise-product-activation-150/unbreakable-enterprise-product-activation.bz2
"""

m = Manticore('unbreakable')
"""
These values can be found at 0x4005b8
"""
input_addr = 0x6042c0
num_bytes = 0x43


# Entry point
@m.hook(0x400729)
def hook(state):
    """ CAUTION: HACK """
    """ From entry point, jump directly to code performing check """

    # Create a symbolic buffer for our input
    buffer = state.new_symbolic_buffer(0x43)

    # We are given in the challenge that the flag begins with CTF{
    # So we can apply constraints to ensure that is true
    state.constrain(buffer[0] == ord('C'))
    state.constrain(buffer[1] == ord('T'))
    state.constrain(buffer[2] == ord('F'))
Пример #29
0
#!/usr/bin/env python

import sys
from manticore import Manticore

# This example demonstrates loading a simple binary in Manticore,
# running it to completion without any callbacks or instrumentation
# and producing basic information about the paths explored


if __name__ == '__main__':
    path = sys.argv[1]
    # Create a new Manticore object
    m = Manticore(path)
    # Start path exploration. start() returns when Manticore
    # finishes
    m.run()
    # Print high level statistics
    m.dump_stats()

Пример #30
0
import sys
from manticore import Manticore

prog = sys.argv[1]
params = sys.argv[2:]

m = Manticore(prog, params)
# 'trace' will contain the executed instructions
m.context['trace'] = []


# None: The hook will be applied to all the instructions
@m.hook(None)
def record_trace(state):
    pc = state.cpu.PC
    ins = state.cpu.instruction
    # Store the instruction
    with m.locked_context() as c:
        c['trace'] += [pc]

        # We manipulate directly capstone instruction
        c['last_ins'] = "%s %s" % (ins.mnemonic, ins.op_str)


m.run()

# Print number of instructions recorded and the last executed
print "%d instructions are recorded" % len(m.context['trace'])
print "Last instruction executed:"
print "0x%x: %s" % (m.context['trace'][-1], m.context['last_ins'])
Пример #31
0
 def setUp(self):
     self.m = Manticore('tests/binaries/arguments_linux_amd64')
Пример #32
0
 def setUp(self):
     self.m = Manticore('tests/binaries/arguments_linux_amd64')
Пример #33
0
import sys
from manticore import Manticore
'''
Minimal example demonstrating setting execution hooks, the ability to target
multiple target architectures, and symbolicating memory.
'''

if __name__ == '__main__':

    if len(sys.argv) < 2:
        print "Usage: {} [binary] [arguments]".format(sys.argv[0])
        sys.exit(1)

    # Create a new Manticore object
    m = Manticore(sys.argv[1], sys.argv[2:])
    m.verbosity = 2

    if m.arch == 'arm':
        target = (0x1082c, 'R4')
    else:
        target = (0x400a83, 'EBX')

    @m.hook(target[0])
    def entered_func(state):
        '''
        For ARM, Make R4 symbolic at 0x1082c, as r4 is used in a branch right
        after.
        '''
        sym_var = state.new_symbolic_value(32, label='from_callback')
        state.cpu.write_register(target[1], sym_var)
Пример #34
0
        if DEBUG: log.info("Reached end, solving...")
        with m.locked_context() as context:
            buff = state.cpu.read_bytes(
                context["buffer_addr"],
                11)  # read the address of the symbolic buffer
            flag = "".join(
                chr(state.solve_one(x))
                for x in buff)  # solve the symbolic values and join them
            if not DEBUG:
                p.success(
                    "Finished. Flag is: {0}".format(flag))  # print the flag :)
            else:
                log.success("Flag is: {0}".format(flag))
        m.terminate()  # terminate Manticore


if __name__ == "__main__":
    if not DEBUG:
        p = log.progress("Analysis status")
        p.status("Setting up hooks...")
    m = Manticore(FILE)

    m.context["branches"] = [
    ]  # create an entry in the context that will hold all the branches in the code
    m.context["buffer_addr"] = [
    ]  # create an entry in the context that will hold the address of the input

    mantify(m)  # analyze and set hooks
    if not DEBUG: p.status("Finished setting up hooks, starting Manticore...")
    m.run()  # start Manticore
Пример #35
0
#!/usr/bin/env python

import sys
from manticore import Manticore

'''
Count the number of emulated instructions.

This example uses the context property of the Manticore object to store data
that's updated by the hook function. Manticore.context is needed to properly
share data when running with multiple worker processes.
'''

if __name__ == '__main__':
    if len(sys.argv) < 2:
        sys.stderr.write("Usage: %s [binary]\n"%(sys.argv[0],))
        sys.exit(2)

    m = Manticore(sys.argv[1])
    with m.locked_context() as context:
        context['count'] = 0

    @m.hook(None)
    def explore(state):
        with m.locked_context() as context:
            context['count'] += 1

    m.run(procs=3)

    print "Executed ", m.context['count'], " instructions."
Пример #36
0
def main():
    global main_end
    #m1 = Manticore.linux(prog, concrete_start=inp, workspace_url='mem:')
    #m1 = Manticore.linux(prog, concrete_start="abc", workspace_url='mem:')
    #m1 = Manticore.barebones(prog, concrete_start="abc", workspace_url='mem:')

    m1 = Manticore.barebones("img.elf")
    m1.verbosity(VERBOSITY)

    # Now let's read the registers
    print "[+] Reading registers"
    initialize_registers(m1.initial_state)

    #m1.initial_state.cpu.PC = 0x800df0c4
    #m1.initial_state.cpu.STACK = 0xbf9f7fa8
    print "R15=", hex(m1.initial_state.cpu.R15)
    print "PC=", hex(m1.initial_state.cpu.PC)
    print "STACK=", hex(m1.initial_state.cpu.STACK)
    print "R13=", hex(m1.initial_state.cpu.R13)
    print "D24=", hex(m1.initial_state.cpu.D24)
    #exit(0)

    #m1._initial_state.cpu.PC = 0x00000000a0059050
    #print m1._initial_state.cpu
    #exit(0);
    # /* Register tracing plugins */
    #t = ExtendedTracer()
    #r = TraceReceiver(t)
    #m1.register_plugin(t)
    #m1.register_plugin(r)
    # NOTE: ./manticore/core/plugin.py:        state.cpu.RFLAGS = state.new_symbolic_value(state.cpu.address_bit_size)
    # NOTE: ./tests/test_state.py:138:         expr = self.state.new_symbolic_value(length)
    # NOTE: ./tests/test_unicorn.py:103:       self.mem.write(start, assemble(asm))

    #m1._initial_state.cpu.write_int(0x00601030, m1._initial_state.new_symbolic_value(8,label="myval"), size=8)
    #m1._initial_state.cpu.write_bytes(0x00601030, m1._initial_state.new_symbolic_value(8))
    #def write_int(self, where, expression, size=None, force=False):

    #m1.register_plugin(InstructionFollower())

    # Trigger an event when PC reaches a certain value
    end_address = 0x8000df00
    #end_address = 0x8000df00
    #end_address =  0x7f000070
    #end_address =  0x7f000034
    @m1.hook(end_address)
    def reached_goal(state):
        cpu = state.cpu
        assert cpu.PC == end_address
        #instruction = cpu.read_int(cpu.PC)
        print "Execution goal reached (pc={}). Terminating state".format(
            hex(end_address))
        #m1.terminate()
        state.abandon()
        #print "Instruction bytes: {:08x}".format(instruction)
        #print "0x{:016x}: {:08x}".format(cpu.PC,instruction)

    taint_id = 'taint_A'

    m1.initial_state.cpu.R1 = m1.initial_state.new_symbolic_value(
        32, taint=(taint_id, ))
    print "R1=", m1.initial_state.cpu.R1
    #exit(0)
    m1.run(procs=1)
    exit(0)
    #return r.trace

    # Read the address of main's `ret` from cmdline if we're passed it. Used for testing.
    if len(sys.argv) > 1:
        main_end = int(sys.argv[1], 0)
        log("Got end of main: {:x}".format(main_end))

    q = Queue.Queue()

    # todo randomly generated concrete start
    stdin = ints2inp(0, 5, 0)

    log('seed input generated ({}), running initial concrete run.'.format(
        inp2ints(stdin)))

    to_queue, datas = concrete_input_to_constraints(stdin)
    for each in to_queue:
        q.put(each)

    # hmmm probably issues with the datas stuff here? probably need to store
    # the datas in the q or something. what if there was a new read(2) deep in the program, changing the datas
    while not q.empty():
        log('get constraint set from queue, queue size: {}'.format(q.qsize()))
        cons = q.get()
        inp = input_from_cons(cons, datas)
        to_queue, new_datas = concrete_input_to_constraints(inp, cons)
        if len(new_datas) > 0:
            datas = new_datas

        for each in to_queue:
            q.put(each)

    log('paths found: {}'.format(len(traces)))
Пример #37
0
#!/usr/bin/env python

import sys
from manticore import Manticore

'''
Demonstrates the ability to set a basic hook on a specific program counter and
the ability to read from memory.
'''

if __name__ == '__main__':
    path = sys.argv[1]
    pc = int(sys.argv[2], 0)

    m = Manticore(path)

    # Trigger an event when PC reaches a certain value
    @m.hook(pc)
    def reached_goal(state):
        cpu = state.cpu

        assert cpu.PC == pc

        instruction = cpu.read_int(cpu.PC)
        print "Execution goal reached."
        print "Instruction bytes: {:08x}".format(instruction)

    m.run()

Пример #38
0
from manticore import Manticore


def fixme():
    raise Exception("Fill in the blanks!")


# Let's initialize the manticore control object
m = Manticore('multiple-styles')


# Now, we can hook the success state and figure out the flag! `fixme()` here
# should be an address we'd like to get to
@m.hook(fixme())
def solve(state):
    # Where is the flag in memory? It's probably offset from the base pointer
    # somehow
    flag_base = state.cpu.RBP - fixme()

    # We're going to build a solution later
    solution = ''

    # How big is the flag? We should be able to figure this out from traditional
    # static analysis
    for i in xrange(fixme()):
        # We can get the symbolic flag out
        symbolic_character = state.cpu.read_int(flag_base + i, 8)
        # And now we just need to solve for it in z3. How might we do that?
        # Perhaps `grep -r "def solve" manticore` can help our case
        concrete_character = fixme()
        solution += chr(concrete_character)
Пример #39
0
#!/usr/bin/env python

import sys
from manticore import Manticore

'''
Count the number of emulated instructions.

This example uses the context property of the Manticore object to store data
that's updated by the hook function. Manticore.context is needed to properly
share data when running with multiple worker processes.
'''

if __name__ == '__main__':
    if len(sys.argv) < 2:
        sys.stderr.write("Usage: %s [binary]\n"%(sys.argv[0],))
        sys.exit(2)

    m = Manticore(sys.argv[1])
    m.context['count'] = 0

    @m.hook(None)
    def explore(state):
        m.context['count'] += 1

    m.run(procs=3)

    print "Executed ", m.context['count'], " instructions."
Пример #40
0
 def testCreating(self):
     m = Manticore('/bin/ls')
     m.log_file = '/dev/null'
Пример #41
0
def main():
    args = parse_arguments()

    m = Manticore(args.programs[0], args.programs[1:])

    m.policy = args.policy
    m.args = args

    if args.workspace:
        m.workspace = args.workspace

    if args.profile:
        m.should_profile = args.profile

    if args.dumpafter != 0:
        m.dumpafter = args.dumpafter

    if args.maxstorage != 0:
        m.maxstorage = args.maxstorage

    if args.maxstates != 0:
        m.maxstates = args.maxstates

    if args.coverage:
        m.coverage_file = args.coverage

    if args.names is not None:
        m.apply_model_hooks(args.names)

    if args.env:
        for entry in args.env:
            name, val = entry[0].split('=')
            m.env_add(name, val)

    if args.files:
        for file in args.files:
            m.add_symbolic_file(file)

    if args.assertions:
        m.load_assertions(args.assertions)

    m.verbosity = args.v

    m.run(args.procs, args.timeout)
Пример #42
0
from manticore import Manticore

def fixme():
  raise Exception("Fill in the blanks!")

# Let's initialize the manticore control object
m = Manticore('multiple-styles')

# First, let's give it some fake data for the input. Anything the same size as
# the real flag should work fine!
m.concrete_data = "infiltrate miami!"

# Now we're going to want to execute a few different hooks and share data, so
# let's use the m.context dict to keep our solution in
m.context['solution'] = ''

# Now we want to hook that compare instruction that controls the main loop.
# Where is it again?
@m.hook(fixme())
def solve(state):
    # Our actual flag should have something to do with AL at this point, let's
    # just read it out real quick
    flag_byte = state.cpu.AL - fixme()

    m.context['solution'] += chr(flag_byte)

    # But how can we make the comparison pass? There are a couple solutions here
    fixme()

# play with these numbers!
m.verbosity = 0