Ejemplo n.º 1
0
def set_delayed_mem_value(target_mem, fn_name, param_pos, mem_size,
                          init_seed_flag):
    mem_addr = target_mem.getAddress()

    if init_seed_flag:
        data = []
        for d in range(0, mem_size):
            seed_mem_layout[mem_addr + d] = 0x0
            data.append(0x0)
    else:
        sym_addr = fn_param_seed_map[(fn_name, param_pos, 0,
                                      Triton.getConcreteRegisterValue(
                                          Triton.registers.rip))]
        data = []
        for d in range(0, mem_size):
            data.append(seed_mem_layout[sym_addr + d])

    fn_param_seed_map[(fn_name, param_pos, 0,
                       Triton.getConcreteRegisterValue(
                           Triton.registers.rip))] = mem_addr

    Triton.setConcreteMemoryAreaValue(mem_addr, data)

    for d in range(0, mem_size):
        Triton.symbolizeMemory(MemoryAccess(mem_addr + d, CPUSIZE.BYTE))
Ejemplo n.º 2
0
def config_hook_table(binary):
    for pltIndex in range(len(interface_hook_fn)):
        if (interface_hook_fn[pltIndex][1] == None):
            interface_hook_fn[pltIndex][1] = BASE_PLT + pltIndex

    for pltgot_item in binary.pltgot_relocations:
        pltgot_item_name = pltgot_item.symbol.name
        pltgot_item_addr = pltgot_item.address
        for hook_fn in interface_hook_fn:
            hook_fn_addr = binary.get_function_address(hook_fn[0])
            if (hook_fn_addr == 0x0 and pltgot_item_name == hook_fn[0]):
                Triton.setConcreteMemoryValue(
                    MemoryAccess(pltgot_item_addr, CPUSIZE.QWORD), hook_fn[1])
                if CONFIG_DEBUG:
                    print('[CONFIG-H] relocated %s from %x to %x' %
                          (pltgot_item_name, pltgot_item_addr, hook_fn[1]))
                break

    for sgx_fn in sgx_implicit_fn:
        sgx_fn_addr = binary.get_function_address(sgx_fn)
        sgx_implicit_fn[sgx_fn] = (sgx_fn_addr, sgx_implicit_fn[sgx_fn][1])
        if CONFIG_DEBUG:
            print(
                '[CONFIG-H] create hooker for memory allocated method %s at 0x%x'
                % (sgx_fn, sgx_fn_addr))

    for warn_fn in sgx_warn_tag:
        warn_fn_addr = binary.get_function_address(warn_fn)
        sgx_warn_tag[warn_fn] = warn_fn_addr
        if CONFIG_DEBUG:
            print('[CONFIG-H] create hooker for warning method %s at 0x%x' %
                  (warn_fn, warn_fn_addr))

    return
Ejemplo n.º 3
0
    def test_defcamp_2015(self):
        """Load binary, self.Triton.setup environment and solve challenge with sym eval."""
        # Load the binary
        binary_file = os.path.join(os.path.dirname(__file__), "misc",
                                   "defcamp-2015-r100.bin")
        self.load_binary(binary_file)

        # Define a fake stack
        self.Triton.setConcreteRegisterValue(self.Triton.registers.rbp,
                                             0x7fffffff)
        self.Triton.setConcreteRegisterValue(self.Triton.registers.rsp,
                                             0x6fffffff)

        # Define an user input
        self.Triton.setConcreteRegisterValue(self.Triton.registers.rdi,
                                             0x10000000)

        # Symbolize user inputs (30 bytes)
        for index in range(30):
            self.Triton.convertMemoryToSymbolicVariable(
                MemoryAccess(0x10000000 + index, CPUSIZE.BYTE))

        # Emulate from the verification function
        solution = self.emulate(0x4006FD)
        self.assertEqual(solution, 'Code_Talkers')
Ejemplo n.º 4
0
def hookingHandler():
    pc = Triton.getConcreteRegisterValue(Triton.registers.rip)
    for rel in customRelocation:
        if rel[2] == pc:
            # Emulate the routine and the return value
            ret_value = rel[1]()
            Triton.concretizeRegister(Triton.registers.rax)
            Triton.setConcreteRegisterValue(Triton.registers.rax, ret_value)

            # Get the return address
            ret_addr = Triton.getConcreteMemoryValue(
                MemoryAccess(
                    Triton.getConcreteRegisterValue(Triton.registers.rsp),
                    CPUSIZE.QWORD))

            # Hijack RIP to skip the call
            Triton.concretizeRegister(Triton.registers.rip)
            Triton.setConcreteRegisterValue(Triton.registers.rip, ret_addr)

            # Restore RSP (simulate the ret)
            Triton.concretizeRegister(Triton.registers.rsp)
            Triton.setConcreteRegisterValue(
                Triton.registers.rsp,
                Triton.getConcreteRegisterValue(Triton.registers.rsp) +
                CPUSIZE.QWORD)
    return
Ejemplo n.º 5
0
def initContext(ctx, seed):
    # Clean symbolic state
    ctx.concretizeAllRegister()
    ctx.concretizeAllMemory()

    # Symbolize the inputs in the seed.
    # Todo: do the proper buffer version
    seed = seed.copy()
    inputLen = max(seed.keys()) + 1
    for sentinelByteIndex in range(inputLen,
                                   inputLen + RiverUtils.SENTINEL_SIZE):
        seed[sentinelByteIndex] = 0

    inputLen = max(seed.keys()) + 1
    for byteIndex, value in seed.items():
        byteAddr = INPUT_BUFFER_ADDRESS + byteIndex
        ctx.setConcreteMemoryValue(byteAddr, value)
        ctx.symbolizeMemory(MemoryAccess(byteAddr, CPUSIZE.BYTE))

    # The commented version is the generic one
    """
    for index in range(30):
        ctx.symbolizeMemory(MemoryAccess(0x10000000+index, CPUSIZE.BYTE))
    """

    # Point RDI on our buffer. The address of our buffer is arbitrary. We just need
    # to point the RDI register on it as first argument of our targeted function.
    ctx.setConcreteRegisterValue(ctx.registers.rdi, INPUT_BUFFER_ADDRESS)
    ctx.setConcreteRegisterValue(ctx.registers.rsi, inputLen)

    # Setup fake stack on an abitrary address.
    ctx.setConcreteRegisterValue(ctx.registers.rsp, 0x7fffffff)
    ctx.setConcreteRegisterValue(ctx.registers.rbp, 0x7fffffff)
    return
Ejemplo n.º 6
0
def __atoi(instruction):
    debug('atoi hooked')

    # 2文字以上だと解なしになってしまう
    atoi_argv_len = 1

    # Get arguments
    arg1_ptr = Triton.getConcreteRegisterValue(Triton.registers.rdi)
    arg1 = getMemoryString(arg1_ptr)
    # print('atoi("{}")'.format(arg1))

    if Triton.getMemoryAst(MemoryAccess(arg1_ptr,
                                        CPUSIZE.BYTE)).isSymbolized():
        debug("atoi is symbolized")
        sym_arg1_offset = []
        for i in range(atoi_argv_len):
            sym_arg1_offset.append(
                Triton.getMemoryAst(MemoryAccess(arg1_ptr + i, CPUSIZE.BYTE)))

        # Symbolize return register
        Triton.convertRegisterToSymbolicVariable(Triton.registers.rax)
        reg_rax = Triton.getSymbolicRegister(Triton.registers.rax)

        ast = Triton.getAstContext()

        ret_value = 0
        for i in range(atoi_argv_len):
            ret_value += (sym_arg1_offset[atoi_argv_len - i - 1] -
                          ord('0')) * (10**i)
            conditional_branch_constraints.append(
                ast.land([
                    sym_arg1_offset[i] >= ord('0'),
                    sym_arg1_offset[i] <= ord('9')
                ]))

        padding_size = reg_rax.getAst().getBitvectorSize() - CPUSIZE.BYTE_BIT
        rax_ast = ast.sx(padding_size, ret_value)
        Triton.createSymbolicRegisterExpression(instruction, rax_ast,
                                                Triton.registers.rax,
                                                "assgin return value")

        # import ipdb; ipdb.set_trace()
        return 0
    else:
        # Return value
        return int(arg1)
Ejemplo n.º 7
0
def libcMainHandler():
    print '[+] __libc_start_main hooked'

    # Get arguments
    main = Triton.getConcreteRegisterValue(Triton.registers.rdi)

    # Push the return value to jump into the main() function
    Triton.concretizeRegister(Triton.registers.rsp)
    Triton.setConcreteRegisterValue(
        Triton.registers.rsp,
        Triton.getConcreteRegisterValue(Triton.registers.rsp) - CPUSIZE.QWORD)

    ret2main = MemoryAccess(
        Triton.getConcreteRegisterValue(Triton.registers.rsp), CPUSIZE.QWORD)
    Triton.concretizeMemory(ret2main)
    Triton.setConcreteMemoryValue(ret2main, main)

    # Setup argc / argv
    Triton.concretizeRegister(Triton.registers.rdi)
    Triton.concretizeRegister(Triton.registers.rsi)

    argvs = [
        "sample_1",  # argv[0]
        "my_first_arg",  # argv[1]
    ]

    # Define argc / argv
    base = 0x20000000
    addrs = list()

    for argv in argvs:
        addrs.append(base)
        Triton.setConcreteMemoryAreaValue(base, argv + '\x00')
        base += len(argv) + 1

    argc = len(argvs)
    argv = base
    for addr in addrs:
        Triton.setConcreteMemoryValue(MemoryAccess(base, CPUSIZE.QWORD), addr)
        base += CPUSIZE.QWORD

    Triton.setConcreteRegisterValue(Triton.registers.rdi, argc)
    Triton.setConcreteRegisterValue(Triton.registers.rsi, argv)

    return 0
Ejemplo n.º 8
0
    def __libc_start_main(self):
        # Get arguments
        main = self.Triton.getConcreteRegisterValue(self.Triton.registers.rdi)

        # Push the return value to jump into the main() function
        self.Triton.concretizeRegister(self.Triton.registers.rsp)
        self.Triton.setConcreteRegisterValue(self.Triton.registers.rsp, self.Triton.getConcreteRegisterValue(self.Triton.registers.rsp)-CPUSIZE.QWORD)

        ret2main = MemoryAccess(self.Triton.getConcreteRegisterValue(self.Triton.registers.rsp), CPUSIZE.QWORD)
        self.Triton.concretizeMemory(ret2main)
        self.Triton.setConcreteMemoryValue(ret2main, main)

        # Setup argc / argv
        self.Triton.concretizeRegister(self.Triton.registers.rdi)
        self.Triton.concretizeRegister(self.Triton.registers.rsi)

        # Setup target argvs
        argvs = list()

        # Define argc / argv
        base  = self.BASE_ARGV
        addrs = list()

        index = 0
        for argv in argvs:
            addrs.append(base)
            self.Triton.setConcreteMemoryAreaValue(base, argv+'\x00')

            # Tainting argvs
            for i in range(len(argv)):
                self.Triton.taintMemory(base + i)

            base += len(argv)+1
            index += 1

        argc = len(argvs)
        argv = base
        for addr in addrs:
            self.Triton.setConcreteMemoryValue(MemoryAccess(base, CPUSIZE.QWORD), addr)
            base += CPUSIZE.QWORD

        self.Triton.setConcreteRegisterValue(self.Triton.registers.rdi, argc)
        self.Triton.setConcreteRegisterValue(self.Triton.registers.rsi, argv)

        return 0
Ejemplo n.º 9
0
def symbolizeInputs(seed,w):
        Triton.concretizeAllRegister()
        Triton.concretizeAllMemory()            
        Triton.setConcreteRegisterValue(Triton.registers.ebp, 0x6ffffffb)
        Triton.setConcreteRegisterValue(Triton.registers.esp, 0x6fffffff)       
        esp=Triton.getConcreteRegisterValue(Triton.registers.ebp)       
        
        Triton.convertMemoryToSymbolicVariable(MemoryAccess(esp+8, CPUSIZE.DWORD))
        Triton.setConcreteMemoryValue(esp+8,0x12)
        Triton.setConcreteRegisterValue(Triton.registers.edi, esp+8)
        address=328
        addressv=0x5800
        Triton.setConcreteMemoryValue(MemoryAccess(esp+12,CPUSIZE.WORD),address) 
                
        for i in range(10):
            Triton.setConcreteMemoryValue(MemoryAccess(address,CPUSIZE.WORD),addressv)
            address=address+4             
            for j in range(100):
               
               Triton.convertMemoryToSymbolicVariable(MemoryAccess(addressv, CPUSIZE.WORD))
               Triton.setConcreteMemoryValue(addressv,0x12)
               addressv=addressv+1       
        for address, value in seed.items():   
                Triton.setConcreteMemoryValue(MemoryAccess(address,CPUSIZE.DWORD),value)
                #Triton.setConcreteMemoryValue(address,value)
		Triton.convertMemoryToSymbolicVariable(MemoryAccess(address, CPUSIZE.WORD))
                #Triton.setConcreteMemoryValue(MemoryAccess(address,CPUSIZE.DWORD),value)    
                Triton.convertMemoryToSymbolicVariable(MemoryAccess(address+1, CPUSIZE.WORD))
        return
Ejemplo n.º 10
0
def makeRelocation(binary):
    # Perform our own relocations
    for rel in binary.pltgot_relocations:
        symbolName = rel.symbol.name
        symbolRelo = rel.address
        for crel in customRelocation:
            if symbolName == crel[0]:
                print('[+] Hooking %s' %(symbolName))
                Triton.setConcreteMemoryValue(MemoryAccess(symbolRelo, CPUSIZE.QWORD), crel[2])
    return
Ejemplo n.º 11
0
    def test_taint_assignement_register_memory(self):
        """Check tainting assignment register <- memory."""
        setArchitecture(ARCH.X86_64)

        self.assertFalse(isRegisterTainted(REG.RAX))
        taintRegister(REG.RAX)
        self.assertTrue(isRegisterTainted(REG.RAX))

        taintAssignmentRegisterMemory(REG.RAX, MemoryAccess(0x2000, 8))
        self.assertFalse(isRegisterTainted(REG.RAX))

        taintMemory(MemoryAccess(0x2000, 8))
        self.assertTrue(isMemoryTainted(MemoryAccess(0x2000, 8)))

        taintAssignmentRegisterMemory(REG.RAX, MemoryAccess(0x2000, 8))
        self.assertTrue(isRegisterTainted(REG.RAX))

        taintAssignmentRegisterMemory(REG.RAX, MemoryAccess(0x3000, 8))
        self.assertFalse(isRegisterTainted(REG.RAX))
Ejemplo n.º 12
0
    def test_bind_expr_to_memory(self):
        """Check symbolic expression binded to memory can be retrieve."""
        # Bind expr1 to 0x100
        expr1 = self.Triton.newSymbolicExpression(self.astCtxt.bv(0x11, 8))
        mem = MemoryAccess(0x100, CPUSIZE.BYTE)
        self.Triton.assignSymbolicExpressionToMemory(expr1, mem)

        # Get expr from memory
        expr2 = self.Triton.getSymbolicMemory(0x100)

        self.assertEqual(expr1.getAst().evaluate(), expr2.getAst().evaluate())
def getNewInput():
    inputs = list()
    pco = Triton.getPathConstraints()
    astCtxt = Triton.getAstContext()
    '''****************
    e= astCtxt.land(e,
                        Triton.getPathConstraintsAst()
                        )
    f = simplify(e,usingZ3)
    cstr = ast.assert_(
                f
            )
    '*******************************'''
    previousConstraints = astCtxt.equal(astCtxt.bvtrue(), astCtxt.bvtrue())
    for pc in pco:
        if pc.isMultipleBranches():
            branches = pc.getBranchConstraints()
            pc = Triton.getConcreteRegisterValue(Triton.registers.eip)
            zfId = Triton.getSymbolicRegisterId(Triton.registers.zf)
            zf = getFullAstFromId(zfId)
            e = ast.equal(zf, ast.bv(1, 1))
            for branch in branches:
                if branch['isTaken'] == False:
                    models = Triton.getModel(
                        astCtxt.land(
                            [previousConstraints, branch['constraint']]))
                    seed = dict()
                    for k, v in models.items():
                        symVar = Triton.getSymbolicVariableFromId(k)
                        seed.update({symVar.getKindValue(): v.getValue()})
                        Triton.convertMemoryToSymbolicVariable(
                            MemoryAccess(k, CPUSIZE.DWORD))
                        Triton.convertMemoryToSymbolicVariable(
                            MemoryAccess(k + 1, CPUSIZE.DWORD))
                    if seed:
                        inputs.append(seed)
        previousConstraints = astCtxt.land(
            [previousConstraints,
             pc.getTakenPathConstraintAst()])
    Triton.clearPathConstraints()
    return inputs
Ejemplo n.º 14
0
def makeRelocation(ctx, binary):
    # Perform our own relocations
    try:
        for rel in binary.pltgot_relocations:
            symbolName = rel.symbol.name
            symbolRelo = rel.address
            for crel in customRelocation:
                if symbolName == crel[0]:
                    ctx.setConcreteMemoryValue(
                        MemoryAccess(symbolRelo, CPUSIZE.QWORD), crel[2])
    except:
        pass
Ejemplo n.º 15
0
    def test_taint_assignement_register_memory(self):
        """Check tainting assignment register <- memory."""
        Triton = TritonContext()
        Triton.setArchitecture(ARCH.X86_64)

        self.assertFalse(Triton.isRegisterTainted(Triton.registers.rax))
        Triton.taintRegister(Triton.registers.rax)
        self.assertTrue(Triton.isRegisterTainted(Triton.registers.rax))

        Triton.taintAssignmentRegisterMemory(Triton.registers.rax,
                                             MemoryAccess(0x2000, 8))
        self.assertFalse(Triton.isRegisterTainted(Triton.registers.rax))

        Triton.taintMemory(MemoryAccess(0x2000, 8))
        self.assertTrue(Triton.isMemoryTainted(MemoryAccess(0x2000, 8)))

        Triton.taintAssignmentRegisterMemory(Triton.registers.rax,
                                             MemoryAccess(0x2000, 8))
        self.assertTrue(Triton.isRegisterTainted(Triton.registers.rax))

        Triton.taintAssignmentRegisterMemory(Triton.registers.rax,
                                             MemoryAccess(0x3000, 8))
        self.assertFalse(Triton.isRegisterTainted(Triton.registers.rax))
Ejemplo n.º 16
0
    def test_taint_union_memory_register(self):
        """Check tainting union memory U register."""
        setArchitecture(ARCH.X86_64)

        taintMemory(MemoryAccess(0x2000, 4))
        self.assertTrue(isMemoryTainted(MemoryAccess(0x2000, 4)))

        taintUnionMemoryRegister(MemoryAccess(0x2000, 4), REG.RAX)
        self.assertTrue(isMemoryTainted(MemoryAccess(0x2000, 4)))
        self.assertFalse(isRegisterTainted(REG.RAX))

        untaintMemory(MemoryAccess(0x2000, 4))
        self.assertFalse(isMemoryTainted(MemoryAccess(0x2000, 4)))
        self.assertFalse(isRegisterTainted(REG.RAX))

        taintUnionMemoryRegister(MemoryAccess(0x2000, 4), REG.RAX)
        self.assertFalse(isMemoryTainted(MemoryAccess(0x2000, 4)))
        self.assertFalse(isRegisterTainted(REG.RAX))

        taintRegister(REG.RAX)
        taintUnionMemoryRegister(MemoryAccess(0x2000, 4), REG.RAX)
        self.assertTrue(isMemoryTainted(MemoryAccess(0x2000, 4)))
        self.assertTrue(isRegisterTainted(REG.RAX))
Ejemplo n.º 17
0
    def make_relocation(self, binary):
        # Setup plt
        for pltIndex in range(len(self.RELO)):
            self.RELO[pltIndex][2] = self.BASE_PLT + pltIndex

        # Perform our own relocations
        for rel in binary.pltgot_relocations:
            symbolName = rel.symbol.name
            symbolRelo = rel.address
            for crel in self.RELO:
                if symbolName == crel[0]:
                    self.Triton.setConcreteMemoryValue(MemoryAccess(symbolRelo, CPUSIZE.QWORD), crel[2])
                    break
        return
Ejemplo n.º 18
0
    def test_8(self):
        ctx = TritonContext()
        ctx.setArchitecture(ARCH.X86_64)
        ctx.enableMode(MODE.ONLY_ON_SYMBOLIZED, True)
        ctx.setConcreteRegisterValue(ctx.registers.rax, 0x1337)
        ctx.convertRegisterToSymbolicVariable(ctx.registers.rax)
        ctx.convertMemoryToSymbolicVariable(MemoryAccess(0, CPUSIZE.QWORD))

        inst = Instruction(b"\x48\x8b\x18") # mov rbx, qword ptr [rax]
        self.assertTrue(ctx.processing(inst))
        self.assertTrue(checkAstIntegrity(inst))

        self.assertEqual(inst.getOperands()[1].getAddress(), 0x1337)
        self.assertIsNotNone(inst.getOperands()[1].getLeaAst())
Ejemplo n.º 19
0
    def test_5(self):
        ctx = TritonContext()
        ctx.setArchitecture(ARCH.X86_64)
        ctx.enableMode(MODE.ONLY_ON_SYMBOLIZED, True)
        ctx.convertMemoryToSymbolicVariable(MemoryAccess(0, CPUSIZE.QWORD))

        inst = Instruction(b"\x48\x8b\x18") # mov rbx, qword ptr [rax]
        self.assertTrue(ctx.processing(inst))
        self.assertTrue(checkAstIntegrity(inst))

        self.assertEqual(len(inst.getReadRegisters()), 0)
        self.assertEqual(len(inst.getWrittenRegisters()), 1)
        self.assertEqual(len(inst.getLoadAccess()), 1)
        self.assertEqual(len(inst.getStoreAccess()), 0)
Ejemplo n.º 20
0
    def test_taint_union_register_memory(self):
        """Check tainting union register U memory."""
        Triton = TritonContext()
        Triton.setArchitecture(ARCH.X86_64)

        self.assertFalse(Triton.isRegisterTainted(Triton.registers.rax))
        Triton.taintRegister(Triton.registers.rax)
        self.assertTrue(Triton.isRegisterTainted(Triton.registers.rax))

        Triton.taintUnionRegisterMemory(Triton.registers.rax,
                                        MemoryAccess(0x2000, 4))
        self.assertTrue(Triton.isRegisterTainted(Triton.registers.rax))
        self.assertFalse(Triton.isMemoryTainted(MemoryAccess(0x2000, 4)))

        Triton.untaintRegister(Triton.registers.rax)
        self.assertFalse(Triton.isRegisterTainted(Triton.registers.rax))

        Triton.taintUnionRegisterMemory(Triton.registers.rax,
                                        MemoryAccess(0x2000, 4))
        self.assertFalse(Triton.isRegisterTainted(Triton.registers.rax))
        self.assertFalse(Triton.isMemoryTainted(MemoryAccess(0x2000, 4)))

        # !T U T
        Triton.untaintRegister(Triton.registers.rax)
        Triton.taintMemory(MemoryAccess(0x2000, 4))
        Triton.taintUnionRegisterMemory(Triton.registers.rax,
                                        MemoryAccess(0x2000, 4))
        self.assertTrue(Triton.isRegisterTainted(Triton.registers.rax))
        self.assertTrue(Triton.isMemoryTainted(MemoryAccess(0x2000, 4)))

        # T U T
        Triton.taintRegister(Triton.registers.rax)
        Triton.taintMemory(MemoryAccess(0x2000, 4))
        Triton.taintUnionRegisterMemory(Triton.registers.rax,
                                        MemoryAccess(0x2000, 4))
        self.assertTrue(Triton.isRegisterTainted(Triton.registers.rax))
        self.assertTrue(Triton.isMemoryTainted(MemoryAccess(0x2000, 4)))
Ejemplo n.º 21
0
def emulate(pc):
    global instCount
    global taintCount

    astCtxt = Triton.getAstContext()
    print('[+] Starting emulation.')
    while pc:
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)

        instruction = Instruction()
        instruction.setOpcode(opcode)
        instruction.setAddress(pc)

        if instruction.getAddress() == 0x400a74:
            Triton.taintRegister(Triton.registers.rdi)

        Triton.processing(instruction)

        hookingHandler(Triton)

        if "call" in str(instruction):
            print('[call] %s' % (str(instruction)))
            print("skipping...")

            ret_addr = Triton.getConcreteMemoryValue(
                MemoryAccess(
                    Triton.getConcreteRegisterValue(Triton.registers.rsp),
                    CPUSIZE.QWORD))

            Triton.setConcreteRegisterValue(Triton.registers.rip, ret_addr)

            Triton.setConcreteRegisterValue(
                Triton.registers.rsp,
                Triton.getConcreteRegisterValue(Triton.registers.rsp) +
                CPUSIZE.QWORD)

        instCount += 1
        if instruction.isTainted():
            print('[tainted] %s' % (str(instruction)))
            taintCount += 1
        else:
            #print(instruction)
            pass

        pc = Triton.getConcreteRegisterValue(Triton.registers.rip)

    print('[*] ' + str(instCount) + ' instructions emulated')
    print('[*] ' + str(taintCount) + ' instructions tainted')
    return
Ejemplo n.º 22
0
 def symbolizeAndConcretizeArea(addr, values):
     if symbolized:
         if self.resetSymbolicMemoryAtEachRun:  # Not used anymore
             self.context.setConcreteMemoryAreaValue(addr, values)
             for byteIndex, value in enumerate(values):
                 byteAddr = INPUT_BUFFER_ADDRESS + byteIndex
                 self.context.symbolizeMemory(
                     MemoryAccess(byteAddr, CPUSIZE.BYTE))
         else:
             # If not needed to reset symbolic state, just take the variable from the cache store and set its current value
             # This will update both the symbolic state and concrete memory
             for byteIndex, value in enumerate(values):
                 byteAddr = INPUT_BUFFER_ADDRESS + byteIndex
                 self.context.setConcreteVariableValue(
                     self.symbolicVariablesCache[byteIndex], value)
def makeRelocation(binary):
    # Setup plt
    for pltIndex in range(len(customRelocation)):
        customRelocation[pltIndex][2] = BASE_PLT + pltIndex

    # Perform our own relocations
    for rel in binary.pltgot_relocations:
        symbolName = rel.symbol.name
        symbolRelo = rel.address
        for crel in customRelocation:
            if symbolName == crel[0]:
                debug('Hooking %s' %(symbolName))
                Triton.setConcreteMemoryValue(MemoryAccess(symbolRelo, CPUSIZE.QWORD), crel[2])
                break
    return
Ejemplo n.º 24
0
def emulate(pc):
    global frameDepth

    while (True):
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)
        inst = Instruction()
        inst.setOpcode(opcode)
        inst.setAddress(pc)

        Triton.processing(inst)
        # if(inst.getAddress() == int(sys.argv[2],16)):
        #     dumpInput()
        #     exit(0)
        print inst,
        print "size: " + str(format(inst.getSize(), 'x'))

        if (inst.getType() == OPCODE.CALL):
            frameDepth += 1
            esp = Triton.getConcreteRegisterValue(Triton.registers.rsp)
            retAddr = Triton.getConcreteMemoryValue(MemoryAccess(esp, 4))
            returnStack.append(retAddr)
            for ret in returnStack:
                print format(ret, 'x')

        # printStack()
        if inst.getAddress() == 0x804849b or inst.getAddress(
        ) == 0x804847a or inst.getAddress() == 0x804844c:
            print "EAX:"+str(format(Triton.getConcreteRegisterValue(Triton.registers.rax),'x')) + \
                  "    EDX:"+str(format(Triton.getConcreteRegisterValue(Triton.registers.rdx),'x')) + \
                  "    EBP : "+ str(format(Triton.getConcreteRegisterValue(Triton.registers.rbp),'x')) + \
                  "    EIP : "+ str(format(Triton.getConcreteRegisterValue(Triton.registers.rip),'x'))

        id = Triton.getSymbolicRegisterId(Triton.registers.rax)
        currentEBP = Triton.getConcreteRegisterValue(Triton.registers.rbp)

        if (inst.getType() == OPCODE.HLT):
            break

        hookingHandler()

        if inst.getType() == OPCODE.RET:
            frameDepth -= 1
            evaluatepc()
        if (inst.getAddress() == 0):
            exit(0)
        pc = Triton.getConcreteRegisterValue(Triton.registers.rip)
Ejemplo n.º 25
0
def __fgets():
    debug('fgets hooked')

    # Get arguments
    arg1 = Triton.getConcreteRegisterValue(Triton.registers.rdi)
    arg2 = Triton.getConcreteRegisterValue(Triton.registers.rsi)

    indx = 0
    user = "******"

    for c in user:
        mem = MemoryAccess(arg1 + indx, CPUSIZE.BYTE)
        Triton.setConcreteMemoryValue(mem, ord(c))
        indx += 1

    # Return value
    return arg1
Ejemplo n.º 26
0
def __fgets(ctx):

    # Get arguments
    arg1 = ctx.getConcreteRegisterValue(ctx.registers.rdi)
    arg2 = ctx.getConcreteRegisterValue(ctx.registers.rsi)

    indx = 0
    #user = raw_input("")[:arg2]
    user = "******"

    for c in user:
        mem = MemoryAccess(arg1 + indx, CPUSIZE.BYTE)
        ctx.setConcreteMemoryValue(mem, ord(c))
        indx += 1

    # Return value
    return arg1
Ejemplo n.º 27
0
    def test_taint_union_memory_immediate(self):
        """Check tainting union memory U immediate."""
        setArchitecture(ARCH.X86_64)

        taintMemory(MemoryAccess(0x2000, 4))
        self.assertTrue(isMemoryTainted(MemoryAccess(0x2000, 4)))

        taintUnionMemoryImmediate(MemoryAccess(0x2000, 4))
        self.assertTrue(isMemoryTainted(MemoryAccess(0x2000, 4)))

        untaintMemory(MemoryAccess(0x2000, 4))
        self.assertFalse(isMemoryTainted(MemoryAccess(0x2000, 4)))
Ejemplo n.º 28
0
def tainting(threadId):

    rdi = getCurrentRegisterValue(Triton.registers.rdi) # argc
    rsi = getCurrentRegisterValue(Triton.registers.rsi) # argv

    while rdi > 1:
        argv = getCurrentMemoryValue(rsi + ((rdi-1) * CPUSIZE.QWORD), CPUSIZE.QWORD)
        offset = 0
        while offset != STRLEN_ASSERT_LEN+5:
            Triton.taintMemory(argv + offset)
            concreteValue = getCurrentMemoryValue(argv + offset)
            Triton.setConcreteMemoryValue(argv + offset, concreteValue)
            Triton.convertMemoryToSymbolicVariable(MemoryAccess(argv + offset, CPUSIZE.BYTE))
            offset += 1
        print '[+] %03d bytes tainted from the argv[%d] (%#x) pointer' %(offset, rdi-1, argv)
        rdi -= 1

    return
Ejemplo n.º 29
0
def hookingHandler(ctx):
    pc = ctx.getConcreteRegisterValue(ctx.registers.rip)
    for rel in customRelocation:
        if rel[2] == pc:
            # Emulate the routine and the return value
            ret_value = rel[1](ctx)
            if ret_value is not None:
                ctx.setConcreteRegisterValue(ctx.registers.rax, ret_value)

            # Get the return address
            ret_addr = ctx.getConcreteMemoryValue(MemoryAccess(ctx.getConcreteRegisterValue(ctx.registers.rsp), CPUSIZE.QWORD))

            # Hijack RIP to skip the call
            ctx.setConcreteRegisterValue(ctx.registers.rip, ret_addr)

            # Restore RSP (simulate the ret)
            ctx.setConcreteRegisterValue(ctx.registers.rsp, ctx.getConcreteRegisterValue(ctx.registers.rsp)+CPUSIZE.QWORD)
    return
Ejemplo n.º 30
0
    def test_taint_union_memory_immediate(self):
        """Check tainting union memory U immediate."""
        Triton = TritonContext()
        Triton.setArchitecture(ARCH.X86_64)

        Triton.taintMemory(MemoryAccess(0x2000, 4))
        self.assertTrue(Triton.isMemoryTainted(MemoryAccess(0x2000, 4)))

        Triton.taintUnionMemoryImmediate(MemoryAccess(0x2000, 4))
        self.assertTrue(Triton.isMemoryTainted(MemoryAccess(0x2000, 4)))

        Triton.untaintMemory(MemoryAccess(0x2000, 4))
        self.assertFalse(Triton.isMemoryTainted(MemoryAccess(0x2000, 4)))
Ejemplo n.º 31
0
class TestMemory(unittest.TestCase):

    """Testing the MemoryAccess class."""

    def setUp(self):
        """Define the architecture and memory access to check."""
        setArchitecture(ARCH.X86_64)
        self.mem = MemoryAccess(0x400f4d3, 8, 0x6162636465666768)

    def test_address(self):
        """Check address data is correct."""
        mem = MemoryAccess(0x1122334455667788, 8, 0x6162636465666768)
        self.assertEqual(mem.getAddress(), 0x1122334455667788)
        self.assertEqual(self.mem.getAddress(), 0x400f4d3)

    def test_bit_size(self):
        """Check bit size of the accessed memory."""
        self.assertEqual(self.mem.getBitSize(), 64)

    def test_size(self):
        """Check size of the accessed memory."""
        self.assertEqual(self.mem.getSize(), 8)

    def test_type(self):
        """Check type of a memory access."""
        self.assertEqual(self.mem.getType(), OPERAND.MEM)

    def test_set_concrete_value(self):
        """Check memory is correctly set."""
        self.mem.setConcreteValue(0x1000)
        self.assertEqual(self.mem.getConcreteValue(), 0x1000)
        self.assertEqual(self.mem.getSize(), 8)

    def test_base_register(self):
        """Check base register modification."""
        self.assertFalse(isRegisterValid(self.mem.getBaseRegister()))
        self.mem.setBaseRegister(REG.RAX)
        self.assertEqual(self.mem.getBaseRegister().getName(), "rax")

    def test_index_register(self):
        """Check index register modification."""
        self.assertFalse(isRegisterValid(self.mem.getIndexRegister()))
        self.mem.setIndexRegister(REG.RCX)
        self.assertEqual(self.mem.getIndexRegister().getName(), "rcx")

    def test_segment_register(self):
        """Check segment register modification."""
        self.assertFalse(isRegisterValid(self.mem.getSegmentRegister()))
        self.mem.setSegmentRegister(REG.FS)
        self.assertEqual(self.mem.getSegmentRegister().getName(), "fs")

    def test_scale(self):
        """Check scale information."""
        self.assertEqual(self.mem.getScale().getValue(), 0)
        self.assertEqual(self.mem.getScale().getBitSize(), 1)

    def test_displacement(self):
        """Check displacement information."""
        self.assertEqual(self.mem.getDisplacement().getValue(), 0)

    def test_ast_gen(self):
        """Check LeaAst."""
        self.assertIsNone(self.mem.getLeaAst())

    def test_overlaping(self):
        """Check overlaping."""
        self.assertTrue(MemoryAccess(0x1000, 2).isOverlapWith(MemoryAccess(0x1001, 2)))
        self.assertTrue(MemoryAccess(0xfff, 2).isOverlapWith(MemoryAccess(0x1000, 2)))
        self.assertTrue(MemoryAccess(0x1000, 4).isOverlapWith(MemoryAccess(0x1003, 2)))
        self.assertTrue(MemoryAccess(0x1000, 4).isOverlapWith(MemoryAccess(0x1002, 1)))
        self.assertTrue(MemoryAccess(0x1002, 1).isOverlapWith(MemoryAccess(0x1000, 4)))

        self.assertFalse(MemoryAccess(0x1000, 4).isOverlapWith(MemoryAccess(0x1004, 4)))
        self.assertFalse(MemoryAccess(0x1000, 4).isOverlapWith(MemoryAccess(0x10000, 4)))
        self.assertFalse(MemoryAccess(0x10000, 4).isOverlapWith(MemoryAccess(0x1000, 4)))
Ejemplo n.º 32
0
 def test_address(self):
     """Check address data is correct."""
     mem = MemoryAccess(0x1122334455667788, 8, 0x6162636465666768)
     self.assertEqual(mem.getAddress(), 0x1122334455667788)
     self.assertEqual(self.mem.getAddress(), 0x400f4d3)
Ejemplo n.º 33
0
 def setUp(self):
     """Define the architecture and memory access to check."""
     setArchitecture(ARCH.X86_64)
     self.mem = MemoryAccess(0x400f4d3, 8, 0x6162636465666768)
Ejemplo n.º 34
0
 def setUp(self):
     """Define the architecture and memory access to check."""
     self.Triton = TritonContext()
     self.Triton.setArchitecture(ARCH.X86_64)
     self.mem = MemoryAccess(0x400f4d3, 8)