Example #1
0
def emulate(Triton, pc):
    global variables
    global goodBranches

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

        # Create the Triton instruction
        instruction = Instruction()
        instruction.setOpcode(opcode)
        instruction.setAddress(pc)

        # Process
        Triton.processing(instruction)
        print instruction

        # End of the CheckSolution() function
        if pc == 0x4025E6:
            break

        if pc == 0x4025CC:
            print '[+] Win'
            break

        if pc in goodBranches:

            astCtxt = Triton.getAstContext()

            # Slice expressions
            rax   = Triton.getSymbolicExpressionFromId(Triton.getSymbolicRegisterId(Triton.registers.rax))
            eax   = astCtxt.extract(31, 0, rax.getAst())

            # Define constraint
            cstr  = astCtxt.land([
                        Triton.getPathConstraintsAst(),
                        astCtxt.equal(eax, astCtxt.bv(goodBranches[pc], 32))
                    ])

            print '[+] Asking for a model, please wait...'
            model = Triton.getModel(cstr)

            # Save new state
            for k, v in model.items():
                print '[+]', v
                variables[k] = v.getValue()

            # Go deeper
            del goodBranches[pc]

            # Restart emulation with a good input.
            Triton = initialize()

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

    print '[+] Emulation done.'
    return
Example #2
0
    def test_1(self):
        ctx = TritonContext()
        ctx.setArchitecture(ARCH.X86_64)
        ctx.enableMode(MODE.ONLY_ON_TAINTED, False)
        self.assertEqual(ctx.isModeEnabled(MODE.ONLY_ON_TAINTED), False)

        inst = Instruction("\x48\x89\xc3") # mov rbx, rax
        self.assertTrue(ctx.processing(inst))
        self.assertTrue(checkAstIntegrity(inst))

        self.assertEqual(len(inst.getReadRegisters()), 1)
        self.assertEqual(len(inst.getWrittenRegisters()), 2)

        ctx.enableMode(MODE.ONLY_ON_TAINTED, True)
        self.assertEqual(ctx.isModeEnabled(MODE.ONLY_ON_TAINTED), True)

        self.assertTrue(ctx.processing(inst))
        self.assertTrue(checkAstIntegrity(inst))

        self.assertEqual(len(inst.getSymbolicExpressions()), 0)
        self.assertEqual(len(inst.getReadRegisters()), 0)
        self.assertEqual(len(inst.getReadImmediates()), 0)
        self.assertEqual(len(inst.getWrittenRegisters()), 0)
        self.assertEqual(len(inst.getLoadAccess()), 0)
        self.assertEqual(len(inst.getStoreAccess()), 0)
Example #3
0
    def test_load_ds(self):
        """Check load from ds segment."""
        setArchitecture(ARCH.X86)

        inst = Instruction()
        # mov ax, ds:word_40213C
        inst.setOpcodes("\x66\xA1\x3C\x21\x40\x00")
        processing(inst)

        self.assertEqual(inst.getOperands()[1].getAddress(), 0x40213C)
        self.assertEqual(inst.getOperands()[1].getBitSize(), 16)
    def test_3(self):
        ctx = TritonContext()
        ctx.setArchitecture(ARCH.X86_64)

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

        self.assertEqual(len(inst.getReadRegisters()), 1)
        self.assertEqual(len(inst.getWrittenRegisters()), 2)
        self.assertEqual(len(inst.getLoadAccess()), 1)
        self.assertEqual(len(inst.getStoreAccess()), 0)
    def test_7(self):
        ctx = TritonContext()
        ctx.setArchitecture(ARCH.X86_64)
        ctx.enableMode(MODE.ONLY_ON_SYMBOLIZED, True)
        ctx.setConcreteRegisterValue(ctx.registers.rax, 0x1337)

        inst = Instruction("\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.assertIsNone(inst.getOperands()[1].getLeaAst())
Example #6
0
    def test_known_issues(self):
        """Check tainting result after processing."""
        setArchitecture(ARCH.X86)

        taintRegister(REG.EAX)
        inst = Instruction()
        # lea eax,[esi+eax*1]
        inst.setOpcodes("\x8D\x04\x06")
        processing(inst)

        self.assertTrue(isRegisterTainted(REG.EAX))
        self.assertFalse(isRegisterTainted(REG.EBX))
Example #7
0
    def test_known_issues(self):
        """Check tainting result after processing."""
        Triton = TritonContext()
        Triton.setArchitecture(ARCH.X86)

        Triton.taintRegister(Triton.registers.eax)
        inst = Instruction()
        # lea eax,[esi+eax*1]
        inst.setOpcode("\x8D\x04\x06")
        Triton.processing(inst)

        self.assertTrue(Triton.isRegisterTainted(Triton.registers.eax))
        self.assertFalse(Triton.isRegisterTainted(Triton.registers.ebx))
Example #8
0
    def test_emulate(self, concretize=False):
        """Run a dumped simulation and check output registers."""
        # Get dumped data
        dump = os.path.join(os.path.dirname(__file__), "misc", "emu_1.dump")
        with open(dump) as f:
            regs, mems = eval(f.read())

        # Load memory
        for mem in mems:
            start = mem['start']
            if mem['memory'] is not None:
                self.Triton.setConcreteMemoryAreaValue(start, bytearray(mem['memory']))

        # self.Triton.setup registers
        for reg_name in ("rax", "rbx", "rcx", "rdx", "rdi", "rsi", "rbp",
                         "rsp", "rip", "r8", "r9", "r10", "r11", "r12", "r13",
                         "r14", "eflags", "xmm0", "xmm1", "xmm2", "xmm3",
                         "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9",
                         "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"):
            self.Triton.setConcreteRegisterValue(self.Triton.getRegister(getattr(REG.X86_64, reg_name.upper())), regs[reg_name])

        # run the code
        pc = self.Triton.getConcreteRegisterValue(self.Triton.registers.rip)
        while pc != 0x409A18:
            opcode = self.Triton.getConcreteMemoryAreaValue(pc, 20)

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

            # Check if triton doesn't supports this instruction
            self.assertTrue(self.Triton.processing(instruction))
            self.assertTrue(checkAstIntegrity(instruction))

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

            if concretize:
                self.Triton.concretizeAllMemory()
                self.Triton.concretizeAllRegister()

        rax = self.Triton.getConcreteRegisterValue(self.Triton.registers.rax)
        rbx = self.Triton.getConcreteRegisterValue(self.Triton.registers.rbx)
        rcx = self.Triton.getConcreteRegisterValue(self.Triton.registers.rcx)
        rdx = self.Triton.getConcreteRegisterValue(self.Triton.registers.rdx)
        rsi = self.Triton.getConcreteRegisterValue(self.Triton.registers.rsi)

        self.assertEqual(rax, 0)
        self.assertEqual(rbx, 0)
        self.assertEqual(rcx, 0)
        self.assertEqual(rdx, 0x4d2)
        self.assertEqual(rsi, 0x3669000000000000)
    def test_2(self):
        ctx = TritonContext()
        ctx.setArchitecture(ARCH.X86_64)
        ctx.enableMode(MODE.ONLY_ON_TAINTED, True)
        ctx.taintRegister(ctx.registers.rax)

        inst = Instruction("\x48\x89\xc3") # mov rbx, rax
        self.assertTrue(ctx.processing(inst))
        self.assertTrue(checkAstIntegrity(inst))

        self.assertEqual(len(inst.getReadRegisters()), 1)
        self.assertEqual(len(inst.getWrittenRegisters()), 2)
        self.assertEqual(len(inst.getLoadAccess()), 0)
        self.assertEqual(len(inst.getStoreAccess()), 0)
    def test_4(self):
        ctx = TritonContext()
        ctx.setArchitecture(ARCH.X86_64)
        ctx.enableMode(MODE.ONLY_ON_SYMBOLIZED, True)
        ctx.convertRegisterToSymbolicVariable(ctx.registers.rax)

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

        self.assertEqual(len(inst.getReadRegisters()), 1)
        self.assertEqual(len(inst.getWrittenRegisters()), 0)
        self.assertEqual(len(inst.getLoadAccess()), 0)
        self.assertEqual(len(inst.getStoreAccess()), 0)
    def setUp(self):
        """Define the arch."""
        self.ctx = TritonContext()
        self.ctx.setArchitecture(ARCH.X86_64)

        self.inst1 = Instruction("\x48\x31\xd8") # xor rax, rbx
        self.ctx.setConcreteRegisterValue(self.ctx.registers.al, 0x10)
        self.ctx.setConcreteRegisterValue(self.ctx.registers.bl, 0x55)

        self.inst2 = Instruction("\x48\x89\x03") # mov [rbx], rax

        self.ctx.processing(self.inst1)
        self.ctx.processing(self.inst2)

        self.expr1 = self.inst1.getSymbolicExpressions()[0]
        self.expr2 = self.inst2.getSymbolicExpressions()[8]
def test_trace(trace):
    Triton.setArchitecture(ARCH.X86)
    symbolization_init()

    astCtxt = Triton.getAstContext()

    for opcode in trace:
        instruction = Instruction()
        instruction.setOpcode(opcode)
        Triton.processing(instruction)
        print instruction.getDisassembly()

        if instruction.isBranch():
            # Opaque Predicate AST
            op_ast = Triton.getPathConstraintsAst()
            # Try another model
            model = Triton.getModel(astCtxt.lnot(op_ast))
            if model:
                print "not an opaque predicate"
            else:
                if instruction.isConditionTaken():
                    print "opaque predicate: always taken"
                else:
                    print "opaque predicate: never taken"

    print '----------------------------------'
    return
Example #13
0
    def test_pop_esp(self):
        """Check pop on esp processing."""
        self.Triton = TritonContext()
        self.Triton.setArchitecture(ARCH.X86)

        # mov esp, 0x19fe00
        inst1 = Instruction('\xBC\x00\xFE\x19\x00')
        # mov dword ptr [esp], 0x11111111
        inst2 = Instruction('\xC7\x04\x24\x11\x11\x11\x11')
        # pop dword ptr [esp]
        inst3 = Instruction('\x8F\x04\x24')
        self.Triton.processing(inst1)
        self.Triton.processing(inst2)
        self.Triton.processing(inst3)

        self.assertEqual(inst3.getOperands()[0].getAddress(), 0x19fe04, "esp has been poped")
        self.assertEqual(inst3.getStoreAccess()[0][0].getAddress(), 0x19fe04, "inst3 set the value in 0x19fe04")
        self.assertEqual(inst3.getStoreAccess()[0][1].evaluate(), 0x11111111, "And this value is 0x11111111")
Example #14
0
 def setUp(self):
     """Define and process the instruction to test."""
     setArchitecture(ARCH.X86_64)
     self.inst = Instruction()
     self.inst.setOpcodes("\x48\x01\xd8")  # add rax, rbx
     self.inst.setAddress(0x400000)
     self.inst.updateContext(Register(REG.RAX, 0x1122334455667788))
     self.inst.updateContext(Register(REG.RBX, 0x8877665544332211))
     processing(self.inst)
Example #15
0
 def setUp(self):
     """Define and process the instruction to test."""
     self.Triton = TritonContext()
     self.Triton.setArchitecture(ARCH.X86_64)
     self.inst = Instruction()
     self.inst.setOpcode("\x48\x01\xd8")  # add rax, rbx
     self.inst.setAddress(0x400000)
     self.Triton.setConcreteRegisterValue(self.Triton.registers.rax, 0x1122334455667788)
     self.Triton.setConcreteRegisterValue(self.Triton.registers.rbx, 0x8877665544332211)
     self.Triton.processing(self.inst)
def run(ip):
    while ip in function:
        # Build an instruction
        inst = Instruction()

        # Setup opcode
        inst.setOpcode(function[ip])

        # Setup Address
        inst.setAddress(ip)

        # Process everything
        Triton.processing(inst)

        # Display instruction
        #print inst

        # Next instruction
        ip = Triton.getRegisterAst(Triton.registers.rip).evaluate()
    return
Example #17
0
    def test_pop(self):
        """Check the pop instruction processing."""
        self.Triton = TritonContext()
        self.Triton.setArchitecture(ARCH.X86)

        # mov esp, 0x19fe00
        inst1 = Instruction('\xBC\x00\xFE\x19\x00')
        # mov edi, 0x19fe00
        inst2 = Instruction('\xBF\x00\xFE\x19\x00')
        # mov dword ptr [esp], 0x11111111
        inst3 = Instruction('\xC7\x04\x24\x11\x11\x11\x11')
        # pop dword ptr [edi]
        inst4 = Instruction('\x8F\x07')
        self.Triton.processing(inst1)
        self.Triton.processing(inst2)
        self.Triton.processing(inst3)
        self.Triton.processing(inst4)

        self.assertEqual(inst4.getOperands()[0].getAddress(), 0x19fe00, "poping edi doesn't change it")
        self.assertEqual(inst4.getStoreAccess()[0][0].getAddress(), 0x19fe00, "inst4 store the new value in 0x19fe00 (edi value)")
        self.assertEqual(inst4.getStoreAccess()[0][1].evaluate(), 0x11111111, "The stored value is 0x11111111")
Example #18
0
def emulate(pc):
    print '[+] Starting emulation.'

    while pc:
        # Fetch opcode
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)

        # Create the Triton instruction
        instruction = Instruction()
        instruction.setOpcode(opcode)
        instruction.setAddress(pc)

        # Process
        Triton.processing(instruction)
        print instruction

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

        # Simulate routines
        hookingHandler()

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

    print '[+] Emulation done.'
    return
Example #19
0
    def test_backup(self):
        """
        Check Symbolics value are saved when engine is disable.

        * Also check reseting a disable symbolic engines doesn't crash.
        """
        inst = Instruction()
        # update RAX
        inst.setOpcode("\x48\xFF\xC0")
        self.Triton.processing(inst)

        self.assertEqual(self.Triton.getSymbolicRegisterValue(self.Triton.registers.rax), 1)

        # This call triton::api.backupSymbolicEngine()
        self.Triton.enableSymbolicEngine(False)

        inst = Instruction()
        # update RAX again
        inst.setOpcode("\x48\xFF\xC0")
        self.Triton.processing(inst)

        self.assertEqual(self.Triton.getConcreteRegisterValue(self.Triton.registers.rax), 2, "concrete value is updated")
        self.assertEqual(self.Triton.getSymbolicRegisterValue(self.Triton.registers.rax), 1)
        self.assertEqual(self.Triton.getSymbolicRegisterValue(self.Triton.registers.rax), 1, "Symbolic value is not update")

        # Try to reset engine after a backup to test if the bug #385 is fixed.
        self.Triton.resetEngines()
def emulate(pc):
    count = 0
    while pc:
        # Fetch opcode
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)

        # Create the Triton instruction
        instruction = Instruction()
        instruction.setOpcode(opcode)
        instruction.setAddress(pc)

        # Process
        Triton.processing(instruction)
        count += 1

        #print instruction

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

        # Simulate routines
        hookingHandler()

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

    debug('Instruction executed: %d' %(count))
    return
Example #21
0
    def emulate(self, pc):
        """
        Emulate every opcode from pc.
        Process instruction until the end
        """
        while pc:
            # Fetch opcode
            opcode = self.Triton.getConcreteMemoryAreaValue(pc, 16)

            # Create the Triton instruction
            instruction = Instruction()
            instruction.setOpcode(opcode)
            instruction.setAddress(pc)

            # Process
            ret = self.Triton.processing(instruction)

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

            self.assertTrue(ret)
            self.assertTrue(checkAstIntegrity(instruction))

            # Simulate routines
            self.hooking_handler()

            # Next
            pc = self.Triton.getConcreteRegisterValue(self.Triton.registers.rip)

        return
Example #22
0
    def emulate(self, pc):
        """
        Emulate every opcode from pc.

        Process instruction until the end
        """
        while pc:
            # Fetch opcode
            opcode = self.Triton.getConcreteMemoryAreaValue(pc, 16)

            # Create the Triton instruction
            instruction = Instruction()
            instruction.setOpcode(opcode)
            instruction.setAddress(pc)

            # Process
            self.assertTrue(self.Triton.processing(instruction))

            # Next
            pc = self.Triton.getConcreteRegisterValue(self.Triton.registers.rip)

        return
Example #23
0
def run(ip):
    while ip in function:
        # Build an instruction
        inst = Instruction()

        # Setup opcode
        inst.setOpcode(function[ip])

        # Setup Address
        inst.setAddress(ip)

        # Process everything
        Triton.processing(inst)

        # Display instruction
        print 'Curr ip:', inst

        # Next instruction
        ip = Triton.buildSymbolicRegister(Triton.registers.rip).evaluate()
        print 'Next ip:', hex(ip)
        print
    return
Example #24
0
    def test_load_immediate_fs(self):
        """Check load from fs segment with immediate."""
        setArchitecture(ARCH.X86_64)

        inst = Instruction()
        # mov eax, DWORD PTR fs:0xffffffffffffdf98
        inst.setOpcodes("\x64\x8B\x04\x25\x98\xDF\xFF\xFF")
        inst.setAddress(0x400000)

        setConcreteRegisterValue(Register(REG.FS, 0x7fffda8ab700))
        processing(inst)

        self.assertTrue(inst.getLoadAccess())

        load, _ = inst.getLoadAccess()[0]
        self.assertEqual(load.getAddress(), 0x7fffda8a9698)
        self.assertEqual(load.getBitSize(), 32)
Example #25
0
    def test_mov_xmm_to_memory(self):
        """Check move and xmm register to memory do not crash."""
        self.Triton = TritonContext()
        self.Triton.setArchitecture(ARCH.X86_64)

        # movhpd QWORD PTR [rax], xmm1
        self.Triton.processing(Instruction(b"\x66\x0F\x17\x08"))
        # movhpd xmm1, QWORD PTR [rax]
        self.Triton.processing(Instruction(b"\x66\x0F\x16\x08"))
        # movhps QWORD PTR [rax], xmm1
        self.Triton.processing(Instruction(b"\x0F\x17\x08"))
        # movhps xmm1, QWORD PTR [rax]
        self.Triton.processing(Instruction(b"\x0F\x16\x08"))
        # movlpd QWORD PTR [rax], xmm1
        self.Triton.processing(Instruction(b"\x66\x0F\x13\x08"))
        # movlpd xmm1, QWORD PTR [rax]
        self.Triton.processing(Instruction(b"\x66\x0F\x12\x08"))
        # movlps QWORD PTR [rax], xmm1
        self.Triton.processing(Instruction(b"\x0F\x13\x08"))
        # movlps xmm1, QWORD PTR [rax]
        self.Triton.processing(Instruction(b"\x0F\x12\x08"))
Example #26
0
    def test_pop(self):
        """Check the pop instruction processing."""
        self.Triton = TritonContext()
        self.Triton.setArchitecture(ARCH.X86)

        # mov esp, 0x19fe00
        inst1 = Instruction(b'\xBC\x00\xFE\x19\x00')
        # mov edi, 0x19fe00
        inst2 = Instruction(b'\xBF\x00\xFE\x19\x00')
        # mov dword ptr [esp], 0x11111111
        inst3 = Instruction(b'\xC7\x04\x24\x11\x11\x11\x11')
        # pop dword ptr [edi]
        inst4 = Instruction(b'\x8F\x07')
        self.Triton.processing(inst1)
        self.Triton.processing(inst2)
        self.Triton.processing(inst3)
        self.Triton.processing(inst4)

        self.assertEqual(inst4.getOperands()[0].getAddress(), 0x19fe00, "poping edi doesn't change it")
        self.assertEqual(inst4.getStoreAccess()[0][0].getAddress(), 0x19fe00, "inst4 store the new value in 0x19fe00 (edi value)")
        self.assertEqual(inst4.getStoreAccess()[0][1].evaluate(), 0x11111111, "The stored value is 0x11111111")
Example #27
0
    def test_1(self):
        ctx = TritonContext()
        ctx.setArchitecture(ARCH.X86_64)
        ctx.setMode(MODE.ONLY_ON_SYMBOLIZED, False)

        inst = Instruction(b"\x48\x89\xc3")  # mov rbx, rax
        self.assertTrue(ctx.processing(inst))
        self.assertTrue(checkAstIntegrity(inst))

        self.assertEqual(len(inst.getReadRegisters()), 1)
        self.assertEqual(len(inst.getWrittenRegisters()), 2)

        ctx.setMode(MODE.ONLY_ON_SYMBOLIZED, True)

        self.assertTrue(ctx.processing(inst))
        self.assertTrue(checkAstIntegrity(inst))

        self.assertEqual(len(inst.getReadRegisters()), 0)
        self.assertEqual(len(inst.getWrittenRegisters()), 0)
        self.assertEqual(len(inst.getLoadAccess()), 0)
        self.assertEqual(len(inst.getStoreAccess()), 0)
Example #28
0
    def test_load_indirect_fs(self):
        """Check load from fs with indirect address."""
        self.Triton = TritonContext()
        self.Triton.setArchitecture(ARCH.X86_64)

        inst = Instruction()
        # mov rax, QWORD PTR fs:[rax]
        inst.setOpcode("\x64\x48\x8B\x00")
        inst.setAddress(0x400000)

        self.Triton.setConcreteRegisterValue(self.Triton.registers.fs,
                                             0x7fffda8ab700)
        self.Triton.setConcreteRegisterValue(self.Triton.registers.rax,
                                             0xffffffffffffdf90)
        self.Triton.processing(inst)

        self.assertTrue(inst.getLoadAccess())

        load, _ = inst.getLoadAccess()[0]
        self.assertEqual(load.getAddress(), 0x7fffda8a9690)
        self.assertEqual(load.getBitSize(), 64)
Example #29
0
    def setUp(self):
        """Define the arch."""
        self.ctx = TritonContext()
        self.ctx.setArchitecture(ARCH.X86)

        trace = [
            "\x25\xff\xff\xff\x3f",      # and eax, 0x3fffffff
            "\x81\xe3\xff\xff\xff\x3f",  # and ebx, 0x3fffffff
            "\x31\xd1",                  # xor ecx, edx
            "\x31\xfa",                  # xor edx, edi
            "\x31\xD8",                  # xor eax, ebx
            "\x0F\x84\x55\x00\x00\x00",  # je 0x55
        ]

        self.ctx.convertRegisterToSymbolicVariable(self.ctx.registers.eax)
        self.ctx.convertRegisterToSymbolicVariable(self.ctx.registers.ebx)

        for opcodes in trace:
            self.ctx.processing(Instruction(opcodes))
Example #30
0
    def test_5(self):
        ctx = TritonContext()
        ctx.setArchitecture(ARCH.X86_64)
        ctx.setMode(MODE.ONLY_ON_SYMBOLIZED, True)
        ctx.symbolizeMemory(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)
Example #31
0
    def test_4(self):
        ctx = TritonContext()
        ctx.setArchitecture(ARCH.X86_64)
        ctx.enableMode(MODE.ONLY_ON_SYMBOLIZED, True)
        ctx.convertRegisterToSymbolicVariable(ctx.registers.rax)

        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()), 1)
        self.assertEqual(len(inst.getWrittenRegisters()), 0)
        self.assertEqual(len(inst.getLoadAccess()), 0)
        self.assertEqual(len(inst.getStoreAccess()), 0)
Example #32
0
    def test_2(self):
        ctx = TritonContext()
        ctx.setArchitecture(ARCH.X86_64)
        ctx.enableMode(MODE.ONLY_ON_TAINTED, True)
        ctx.taintRegister(ctx.registers.rax)

        inst = Instruction("\x48\x89\xc3")  # mov rbx, rax
        self.assertTrue(ctx.processing(inst))
        self.assertTrue(checkAstIntegrity(inst))

        self.assertEqual(len(inst.getReadRegisters()), 1)
        self.assertEqual(len(inst.getWrittenRegisters()), 2)
        self.assertEqual(len(inst.getLoadAccess()), 0)
        self.assertEqual(len(inst.getStoreAccess()), 0)
Example #33
0
    def test_load_indirect_fs(self):
        """Check load from fs with indirect address."""
        setArchitecture(ARCH.X86_64)

        inst = Instruction()
        # mov rax, QWORD PTR fs:[rax]
        inst.setOpcodes("\x64\x48\x8B\x00")
        inst.setAddress(0x400000)

        setConcreteRegisterValue(Register(REG.FS, 0x7fffda8ab700))
        setConcreteRegisterValue(Register(REG.RAX, 0xffffffffffffdf90))
        processing(inst)

        self.assertTrue(inst.getLoadAccess())

        load, _ = inst.getLoadAccess()[0]
        self.assertEqual(load.getAddress(), 0x7fffda8a9690)
        self.assertEqual(load.getBitSize(), 64)
Example #34
0
    def test_pop_esp(self):
        """Check pop on esp processing."""
        self.Triton = TritonContext()
        self.Triton.setArchitecture(ARCH.X86)

        # mov esp, 0x19fe00
        inst1 = Instruction(b'\xBC\x00\xFE\x19\x00')
        # mov dword ptr [esp], 0x11111111
        inst2 = Instruction(b'\xC7\x04\x24\x11\x11\x11\x11')
        # pop dword ptr [esp]
        inst3 = Instruction(b'\x8F\x04\x24')
        self.Triton.processing(inst1)
        self.Triton.processing(inst2)
        self.Triton.processing(inst3)

        self.assertEqual(inst3.getOperands()[0].getAddress(), 0x19fe04, "esp has been poped")
        self.assertEqual(inst3.getStoreAccess()[0][0].getAddress(), 0x19fe04, "inst3 set the value in 0x19fe04")
        self.assertEqual(inst3.getStoreAccess()[0][1].evaluate(), 0x11111111, "And this value is 0x11111111")
Example #35
0
def test5():
    Triton = TritonContext()
    Triton.setArchitecture(ARCH.X86)
    astCtxt = Triton.getAstContext()

    # rax is now symbolic
    Triton.symbolizeRegister(Triton.registers.eax)

    # process instruction
    Triton.processing(Instruction(b"\x83\xc0\x07"))  # add eax, 0x7

    # get rax ast
    eaxAst = Triton.getSymbolicRegister(Triton.registers.eax).getAst()

    # constraint
    c = eaxAst ^ 0x11223344 == 0xdeadbeaf

    print('Test 5:', Triton.getModel(c)[0])

    return
Example #36
0
def test6():
    Triton = TritonContext()
    Triton.setArchitecture(ARCH.X86)
    astCtxt = Triton.getAstContext()

    # rax is now symbolic
    var = Triton.convertRegisterToSymbolicVariable(Triton.registers.eax)
    var.setAlias("eax")

    # process instruction
    Triton.processing(Instruction("\x83\xc0\x07"))  # add eax, 0x7

    # get rax ast
    eaxAst = Triton.getSymbolicRegister(Triton.registers.eax).getAst()

    # constraint
    c = eaxAst ^ 0x11223344 == 0xdeadbeaf

    print 'Test 6:', Triton.getModel(c)[0]

    return
Example #37
0
def emulate(pc):
    astCtxt = Triton.getAstContext()
    print '[+] Starting emulation.'
    while pc:
        # Fetch opcode
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)

        # Create the Triton instruction
        instruction = Instruction()
        instruction.setOpcode(opcode)
        instruction.setAddress(pc)

        # Process
        Triton.processing(instruction)
        print instruction

        # 40078B: cmp eax, 1
        # eax must be equal to 1 at each round.
        if instruction.getAddress() == 0x40078B:
            # Slice expressions
            rax = Triton.getSymbolicRegister(Triton.registers.rax)
            eax = astCtxt.extract(31, 0, rax.getAst())

            # Define constraint
            cstr = astCtxt.land([
                Triton.getPathConstraintsAst(),
                astCtxt.equal(eax, astCtxt.bv(1, 32))
            ])

            print '[+] Asking for a model, please wait...'
            model = Triton.getModel(cstr)
            for k, v in model.items():
                value = v.getValue()
                Triton.setConcreteVariableValue(
                    Triton.getSymbolicVariableFromId(k), value)
                print '[+] Symbolic variable %02d = %02x (%c)' % (k, value,
                                                                  chr(value))

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

    print '[+] Emulation done.'
    return
Example #38
0
    def emulate(self, pc):
        """
        Emulate every opcodes from pc.

        * Process instruction until the end and search for constraint
        resolution on cmp eax, 1 then set the new correct value and keep going.
        """
        while pc:
            # Fetch opcodes
            opcodes = getConcreteMemoryAreaValue(pc, 16)

            # Create the Triton instruction
            instruction = Instruction()
            instruction.setOpcodes(opcodes)
            instruction.setAddress(pc)

            # Process
            processing(instruction)

            # 40078B: cmp eax, 1
            # eax must be equal to 1 at each round.
            if instruction.getAddress() == 0x40078B:
                # Slice expressions
                rax = getSymbolicExpressionFromId(
                    getSymbolicRegisterId(REG.RAX))
                eax = ast.extract(31, 0, rax.getAst())

                # Define constraint
                cstr = ast.assert_(
                    ast.land(getPathConstraintsAst(),
                             ast.equal(eax, ast.bv(1, 32))))

                model = getModel(cstr)
                solution = str()
                for k, v in model.items():
                    value = v.getValue()
                    solution += chr(value)
                    getSymbolicVariableFromId(k).setConcreteValue(value)

            # Next
            pc = getConcreteRegisterValue(REG.RIP)
        return solution
Example #39
0
def run(pc, seed):
    global seeds
    while pc:
        if pc in seeds and seeds[pc] == 0:
            print("get one")
            seeds[pc] = seed

        flag = 0

        # Build an instruction
        inst = Instruction()

        # Setup opcode
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)

        inst.setOpcode(opcode)
        inst.setAddress(pc)

        arr = [elem.encode("hex") for elem in inst.getOpcode()]
        if arr[:4] == ['f3', '0f', '1e', 'fa']:
            pc += 4
            continue
        if arr[:3] == ['0f', '01', 'd0']:
            pc += 3
            continue
        if arr[0] == 'f4':
            print("abort")
            break

        # Setup Address

        Triton.processing(inst)

        # hookingHandler(Triton)
        pc = Triton.getConcreteRegisterValue(Triton.registers.rip)
        for seedr in seeds.values():
            if seedr == 0:
                flag = 1
                break
        if flag == 0:
            break
Example #40
0
def emulate(pc):
    count = 0
    while pc:
        # Fetch opcode
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)

        # Create the Triton instruction
        instruction = Instruction()
        instruction.setOpcode(opcode)
        instruction.setAddress(pc)

        # Process
        Triton.processing(instruction)
        count += 1

        #print(instruction)

        # NOTE: Here is the solution of the challenge. The flag is decoded
        # and written into the memory. So, let's track all memory STORE of
        # 1 byte.
        for mem, memAst in instruction.getStoreAccess():
            if mem.getSize() == CPUSIZE.BYTE:
                sys.stdout.write(chr(Triton.getConcreteMemoryValue(mem)))
        # End of solution

        if instruction.getType() == OPCODE.X86.HLT:
            break

        # Simulate routines
        hookingHandler()

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

    debug('Instruction executed: %d' % (count))
    return
def emulate(pc, w):
    while pc:
        opcodes = Triton.getConcreteMemoryAreaValue(pc, 16)
        instruction = Instruction()
        instruction.setOpcode(opcodes)
        instruction.setAddress(pc)
        Triton.processing(instruction)
        symvar = [
            chr(0x41),
            chr(0x41),
            chr(0x41),
            chr(0x41),
            chr(0x41),
            chr(0x41),
            chr(0x0b),
            chr(0x84),
            chr(0),
            chr(0x04),
            chr(0),
            chr(0x08)
        ]
        if sys.argv[3].startswith("0x"):
            target = int(sys.argv[3][2:], 16)
            #print 'tahrget',target
        i = 1

        if pc == target:
            print '=======================================Address found with following seeds================================================'
            for address, value in seed.items():
                print 'i won'
                if (address == 1879048195):
                    print 'argc ', value
                else:
                    x = address - 22528 - 16383
                    y = int(x / 100)
                    z = int(x % 100)

                    print 'argv[', y, '][', z, '] ', value
                    i = i + 1
            w = 11
            break
        #else:
        #print 'chill'''

    #print '[+] Emulation done.'
    return w
Example #42
0
    def emulate(self, pc):
        """
        Emulate every opcode from pc.

        * Process instruction until the end and search for constraint
        resolution on cmp eax, 1 then self.Triton.set the new correct value and keep going.
        """
        astCtxt = self.Triton.getAstContext()
        while pc:
            # Fetch opcode
            opcode = self.Triton.getConcreteMemoryAreaValue(pc, 16)

            # Create the Triton instruction
            instruction = Instruction()
            instruction.setOpcode(opcode)
            instruction.setAddress(pc)

            # Process
            self.Triton.processing(instruction)
            self.assertTrue(checkAstIntegrity(instruction))

            # 40078B: cmp eax, 1
            # eax must be equal to 1 at each round.
            if instruction.getAddress() == 0x40078B:
                # Slice expressions
                rax = self.Triton.getSymbolicRegister(self.Triton.registers.rax)
                eax = astCtxt.extract(31, 0, rax.getAst())

                # Define constraint
                cstr = astCtxt.land([self.Triton.getPathPredicate(), astCtxt.equal(eax, astCtxt.bv(1, 32))])

                model = self.Triton.getModel(cstr)
                solution = str()
                for k, v in list(sorted(model.items())):
                    value = v.getValue()
                    solution += chr(value)
                    self.Triton.setConcreteVariableValue(self.Triton.getSymbolicVariable(k), value)

            # Next
            pc = self.Triton.getConcreteRegisterValue(self.Triton.registers.rip)
        return solution
Example #43
0
def process(code):
    Triton = TritonContext()
    Triton.setArchitecture(ARCH.X86_64)
    for (addr, opcode) in code:
        # Build an instruction
        inst = Instruction()

        # Setup opcode
        inst.setOpcode(opcode)

        # Setup Address
        inst.setAddress(addr)

        # Process everything
        Triton.processing(inst)

        print(inst)
        for expr in inst.getSymbolicExpressions():
            print('\t', expr)

    for k, v in list(Triton.getSymbolicRegisters().items()):
        if 'rax' in str(Triton.getRegister(k)):
            print(Triton.getRegister(k), v)
def run(ip):
    while ip in function:
        # Build an instruction
        inst = Instruction()

        # Setup opcode
        inst.setOpcode(function[ip])

        # Setup Address
        inst.setAddress(ip)

        # Process everything
        Triton.processing(inst)

        # Display instruction
        #print(inst)

        # Next instruction
        ip = Triton.getRegisterAst(Triton.registers.rip).evaluate()
    return
Example #45
0
def emulate(pc):
    astCtxt = Triton.getAstContext()
    print '[+] Starting emulation.'
    while pc:
        # Fetch opcode
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)

        # Create the Triton instruction
        instruction = Instruction()
        instruction.setOpcode(opcode)
        instruction.setAddress(pc)

        # Process
        Triton.processing(instruction)
        print instruction

        # 40078B: cmp eax, 1
        # eax must be equal to 1 at each round.
        if instruction.getAddress() == 0x40078B:
            # Slice expressions
            rax   = Triton.getSymbolicRegister(Triton.registers.rax)
            eax   = astCtxt.extract(31, 0, rax.getAst())

            # Define constraint
            cstr  = astCtxt.land([
                        Triton.getPathConstraintsAst(),
                        astCtxt.equal(eax, astCtxt.bv(1, 32))
                    ])

            print '[+] Asking for a model, please wait...'
            model = Triton.getModel(cstr)
            for k, v in model.items():
                value = v.getValue()
                Triton.setConcreteVariableValue(Triton.getSymbolicVariableFromId(k), value)
                print '[+] Symbolic variable %02d = %02x (%c)' %(k, value, chr(value))

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

    print '[+] Emulation done.'
    return
Example #46
0
    def emulate(self, pc):
        """
        Emulate every opcode from pc.

        * Process instruction until the end and search for constraint
        resolution on cmp eax, 1 then self.Triton.set the new correct value and keep going.
        """
        astCtxt = self.Triton.getAstContext()
        while pc:
            # Fetch opcode
            opcode = self.Triton.getConcreteMemoryAreaValue(pc, 16)

            # Create the Triton instruction
            instruction = Instruction()
            instruction.setOpcode(opcode)
            instruction.setAddress(pc)

            # Process
            self.Triton.processing(instruction)
            self.assertTrue(checkAstIntegrity(instruction))

            # 40078B: cmp eax, 1
            # eax must be equal to 1 at each round.
            if instruction.getAddress() == 0x40078B:
                # Slice expressions
                rax = self.Triton.getSymbolicRegister(self.Triton.registers.rax)
                eax = astCtxt.extract(31, 0, rax.getAst())

                # Define constraint
                cstr = astCtxt.land([self.Triton.getPathConstraintsAst(), astCtxt.equal(eax, astCtxt.bv(1, 32))])

                model = self.Triton.getModel(cstr)
                solution = str()
                for k, v in model.items():
                    value = v.getValue()
                    solution += chr(value)
                    self.Triton.setConcreteVariableValue(self.Triton.getSymbolicVariableFromId(k), value)

            # Next
            pc = self.Triton.getConcreteRegisterValue(self.Triton.registers.rip)
        return solution
Example #47
0
    def emulate(self, pc):
        """
        Emulate every opcode from pc.

        Process instruction until the end
        """
        while pc:
            # Fetch opcode
            opcode = self.Triton.getConcreteMemoryAreaValue(pc, 16)

            # Create the Triton instruction
            instruction = Instruction()
            instruction.setOpcode(opcode)
            instruction.setAddress(pc)

            # Process
            self.assertTrue(self.Triton.processing(instruction))

            # Next
            pc = self.Triton.getConcreteRegisterValue(self.Triton.registers.rip)

        return
Example #48
0
    def emulate(self, pc):
        """
        Emulate every opcodes from pc.

        * Process instruction until the end and search for constraint
        resolution on cmp eax, 1 then set the new correct value and keep going.
        """
        while pc:
            # Fetch opcodes
            opcodes = getConcreteMemoryAreaValue(pc, 16)

            # Create the Triton instruction
            instruction = Instruction()
            instruction.setOpcodes(opcodes)
            instruction.setAddress(pc)

            # Process
            processing(instruction)

            # 40078B: cmp eax, 1
            # eax must be equal to 1 at each round.
            if instruction.getAddress() == 0x40078B:
                # Slice expressions
                rax = getSymbolicExpressionFromId(getSymbolicRegisterId(REG.RAX))
                eax = ast.extract(31, 0, rax.getAst())

                # Define constraint
                cstr = ast.assert_(ast.land(getPathConstraintsAst(), ast.equal(eax, ast.bv(1, 32))))

                model = getModel(cstr)
                solution = str()
                for k, v in model.items():
                    value = v.getValue()
                    solution += chr(value)
                    getSymbolicVariableFromId(k).setConcreteValue(value)

            # Next
            pc = getConcreteRegisterValue(REG.RIP)
        return solution
Example #49
0
def run(ip):
    while ip in function:
        # Build an instruction
        inst = Instruction()

        # Setup opcode
        inst.setOpcode(function[ip])

        # Setup Address
        inst.setAddress(ip)

        # Process everything
        Triton.processing(inst)

        # Display instruction
        print 'Curr ip:', inst

        # Next instruction
        ip = Triton.buildSymbolicRegister(Triton.registers.rip).evaluate()
        print 'Next ip:', hex(ip)
        print
    return
Example #50
0
def runR(pc, binary):
    seed = {}
    while pc:
        # Build an instruction
        inst = Instruction()

        # Setup opcode
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)

        inst.setOpcode(opcode)
        inst.setAddress(pc)

        arr = [elem.encode("hex") for elem in inst.getOpcode()]
        # endbr64
        if arr[:4] == ['f3', '0f', '1e', 'fa']:
            pc += 4
            continue
        if arr[:3] == ['0f', '01', 'd0']:
            pc += 3
            continue
        if arr[0] == 'f4':
            print("abort")
            break

        if arr[0] == 'e8':
            offset = 0
            offset += int(arr[4], 16)
            offset = offset << 8
            offset += int(arr[3], 16)
            offset = offset << 8
            offset += int(arr[2], 16)
            offset = offset << 8
            offset += int(arr[1], 16)
            faddr = offset + pc + 5
            faddr = faddr & 0xffffffff
            print(str(hex(pc)) + " calling: " + str(hex(faddr)))

            try:
                fclose_addr = binary.get_function_address("fclose")
                if fclose_addr == faddr:
                    pc += 5
                    continue
            except:
                pass

            try:
                fgets_addr = binary.get_function_address("fgets")
                if fgets_addr == faddr:
                    adr = Triton.getConcreteRegisterValue(Triton.registers.rdi)
                    num = Triton.getConcreteRegisterValue(Triton.registers.rsi)
                    for i in range(num):
                        seed[adr + i] = 0

                    pc += 5
                    continue
            except:
                pass

            try:
                fread_addr = binary.get_function_address("fread")
                if fread_addr == faddr:
                    print("fread at " + str(hex(pc)))
                    adr = Triton.getConcreteRegisterValue(Triton.registers.rdi)
                    num = Triton.getConcreteRegisterValue(
                        Triton.registers.rsi
                    ) * Triton.getConcreteRegisterValue(Triton.registers.rdx)
                    for i in range(num):
                        seed[adr + i] = 0

                    pc += 5
                    continue
            except:
                pass
            try:
                printf_addr = binary.get_function_address("printf")
                if printf_addr == faddr:
                    pc += 5
                    continue
            except:
                pass

            try:
                fprintf_addr = binary.get_function_address("fprintf")
                if fprintf_addr == faddr:
                    pc += 5
                    continue
            except:
                pass

        Triton.processing(inst)

        # Setup Address

        # hookingHandler(Triton)
        pc = Triton.getConcreteRegisterValue(Triton.registers.rip)
    return seed
Example #51
0
 def test_mix_high_low_register(self):
     """Check operation on lower and higher register."""
     self.Triton = TritonContext()
     self.Triton.setArchitecture(ARCH.X86_64)
     inst = Instruction(b"\x00\xDC")  # add ah,bl
     self.Triton.processing(inst)
Example #52
0
    def test_address(self):
        """Check instruction current and next address."""
        self.assertEqual(self.inst.getAddress(), 0x400000)
        self.assertEqual(self.inst.getNextAddress(), 0x400003)

        inst = Instruction()
        inst.setAddress(-1)
        self.assertEqual(inst.getAddress(), 0xffffffffffffffff)

        inst.setAddress(-2)
        self.assertEqual(inst.getAddress(), 0xfffffffffffffffe)

        inst.setAddress(-3)
        self.assertEqual(inst.getAddress(), 0xfffffffffffffffd)
Example #53
0
class TestInstruction(unittest.TestCase):

    """Testing the Instruction class."""

    def setUp(self):
        """Define and process the instruction to test."""
        self.Triton = TritonContext()
        self.Triton.setArchitecture(ARCH.X86_64)
        self.inst = Instruction()
        self.inst.setOpcode(b"\x48\x01\xd8")  # add rax, rbx
        self.inst.setAddress(0x400000)
        self.Triton.setConcreteRegisterValue(self.Triton.registers.rax, 0x1122334455667788)
        self.Triton.setConcreteRegisterValue(self.Triton.registers.rbx, 0x8877665544332211)
        self.Triton.processing(self.inst)

    def test_address(self):
        """Check instruction current and next address."""
        self.assertEqual(self.inst.getAddress(), 0x400000)
        self.assertEqual(self.inst.getNextAddress(), 0x400003)

        inst = Instruction()
        inst.setAddress(-1)
        self.assertEqual(inst.getAddress(), 0xffffffffffffffff)

        inst.setAddress(-2)
        self.assertEqual(inst.getAddress(), 0xfffffffffffffffe)

        inst.setAddress(-3)
        self.assertEqual(inst.getAddress(), 0xfffffffffffffffd)

    def test_memory(self):
        """Check memory access."""
        self.assertListEqual(self.inst.getLoadAccess(), [])
        self.assertListEqual(self.inst.getStoreAccess(), [])
        self.assertFalse(self.inst.isMemoryWrite())
        self.assertFalse(self.inst.isMemoryRead())

    def test_registers(self):
        """Check register access."""
        self.assertEqual(len(self.inst.getReadRegisters()), 2, "access RAX and RBX")
        self.assertEqual(len(self.inst.getWrittenRegisters()), 8, "write in RAX, RIP, AF, XF, OF, PF, SF and ZF")

    def test_taints(self):
        """Check taints attributes."""
        self.assertFalse(self.inst.isTainted())

    def test_prefix(self):
        """Check prefix data."""
        self.assertFalse(self.inst.isPrefixed())
        self.assertEqual(self.inst.getPrefix(), PREFIX.X86.INVALID)

    def test_control_flow(self):
        """Check control flow flags."""
        self.assertFalse(self.inst.isControlFlow(), "It is not a jmp, ret or call")
        self.assertFalse(self.inst.isBranch(), "It is not a jmp")

    def test_condition(self):
        """Check condition flags."""
        self.assertFalse(self.inst.isConditionTaken())

    def test_opcode(self):
        """Check opcode informations."""
        self.assertEqual(self.inst.getOpcode(), b"\x48\x01\xd8")
        self.assertEqual(self.inst.getType(), OPCODE.X86.ADD)

    def test_thread(self):
        """Check threads information."""
        self.assertEqual(self.inst.getThreadId(), 0)

    def test_operand(self):
        """Check operand information."""
        self.assertEqual(len(self.inst.getOperands()), 2)
        self.assertEqual(self.inst.getOperands()[0].getName(), "rax")
        self.assertEqual(self.inst.getOperands()[1].getName(), "rbx")
        with self.assertRaises(Exception):
            self.inst.getOperands()[2]

    def test_symbolic(self):
        """Check symbolic information."""
        self.assertEqual(len(self.inst.getSymbolicExpressions()), 8)

    def test_size(self):
        """Check size information."""
        self.assertEqual(self.inst.getSize(), 3)

    def test_disassembly(self):
        """Check disassembly equivalent."""
        self.assertEqual(self.inst.getDisassembly(), "add rax, rbx")
Example #54
0
def run(pc, func_spec, seed):
    global addrs
    flag = 0
    while pc:
        inst = Instruction()

        # Setup opcode
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)

        inst.setOpcode(opcode)
        inst.setAddress(pc)
        arr = [elem.encode("hex") for elem in inst.getOpcode()]
        if arr[:4] == ['f3', '0f', '1e', 'fa']:
            pc += 4
            continue
        if arr[:3] == ['0f', '01', 'd0']:
            pc += 3
            continue
        if arr[0] == 'f4':
            print("abort")
            break

        if arr[0] == 'e8':
            offset = 0
            offset += int(arr[4], 16)
            offset = offset << 8
            offset += int(arr[3], 16)
            offset = offset << 8
            offset += int(arr[2], 16)
            offset = offset << 8
            offset += int(arr[1], 16)
            faddr = offset + pc + 5
            faddr = faddr & 0xffffffff

            try:
                fclose_addr = gbinary.get_function_address("fclose")
                if fclose_addr == faddr:
                    pc += 5
                    continue
            except:
                pass

            try:
                fgets_addr = gbinary.get_function_address("fgets")
                if fgets_addr == faddr:
                    adr = Triton.getConcreteRegisterValue(Triton.registers.rdi)
                    num = Triton.getConcreteRegisterValue(Triton.registers.rsi)
                    for i in range(num):
                        if adr + i not in seed:
                            seed[adr + i] = 0

                    pc += 5
                    continue
            except:
                pass

            try:
                fread_addr = gbinary.get_function_address("fread")
                if fread_addr == faddr:
                    adr = Triton.getConcreteRegisterValue(Triton.registers.rdi)
                    num = Triton.getConcreteRegisterValue(
                        Triton.registers.rsi
                    ) * Triton.getConcreteRegisterValue(Triton.registers.rdx)
                    for i in range(num):
                        if adr + i not in seed:
                            print("new fread")
                            seed[adr + i] = 0

                    pc += 5
                    continue
            except:
                pass

            try:
                printf_addr = gbinary.get_function_address("printf")
                if printf_addr == faddr:
                    pc += 5
                    continue
            except:
                pass

            try:
                fprintf_addr = gbinary.get_function_address("fprintf")
                if fprintf_addr == faddr:
                    pc += 5
                    continue
            except:
                pass

        if arr[0] == 'e8' and flag == 0:
            offset = 0
            offset += int(arr[4], 16)
            offset = offset << 8
            offset += int(arr[3], 16)
            offset = offset << 8
            offset += int(arr[2], 16)
            offset = offset << 8
            offset += int(arr[1], 16)
            addr = offset + pc + 5
            addr = addr & 0xffffffff

            if addr in func_spec:
                last_op = addr
                if func_spec[addr][0] in ["==", ">=", "<="]:
                    Triton.setConcreteRegisterValue(Triton.registers.rax,
                                                    func_spec[addr][1])
                if func_spec[addr][0] == '>':
                    Triton.setConcreteRegisterValue(Triton.registers.rax,
                                                    func_spec[addr][1] + 1)
                if func_spec[addr][0] == '!=':
                    Triton.setConcreteRegisterValue(Triton.registers.rax,
                                                    func_spec[addr][1] + 1)
                if func_spec[addr][0] == '<':
                    Triton.setConcreteRegisterValue(Triton.registers.rax,
                                                    func_spec[addr][1] - 1)
                flag = 1
                pc += 5
                continue
        Triton.processing(inst)

        gflag = 0
        for addr in func_spec:
            if addr not in addrs:
                gflag = 1
                break
        if gflag == 0:
            break

        if flag == 2:
            addrs[last_op] = pc
            flag = 0
        if flag == 1:
            if inst.isBranch():
                flag = 2

        # hookingHandler(Triton)
        pc = Triton.getConcreteRegisterValue(Triton.registers.rip)
Example #55
0
def emulate(Triton, pc):
    count = 0
    while pc:
        # Fetch opcode
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)

        # Create the Triton instruction
        instruction = Instruction()
        instruction.setOpcode(opcode)
        instruction.setAddress(pc)

        # Process
        Triton.processing(instruction)
        count += 1

        # Handle nested memory reads
        if instruction.isMemoryRead():
            memory_access, read__memory_ast_node = instruction.getLoadAccess()[0]
            read_register, read_register_ast_node = instruction.getReadRegisters()[0]
            written_register, write_register_ast_node = instruction.getWrittenRegisters()[0]
            if read_register.getName() != "unknown":
                expression = read_register_ast_node.getSymbolicExpression()
                expression_ast = expression.getAst()
                #import pdb
                #pdb.set_trace()
                if expression_ast.getType() == AST_NODE.VARIABLE:
                    variable = expression_ast.getSymbolicVariable()
                    alias = variable.getAlias()
                    displacement = memory_access.getDisplacement().getValue()
                    newalias = "(%s)[0x%x]" % (alias, displacement)
                    #newalias = "(%s)[0]" % alias
                    Triton.symbolizeRegister(written_register, newalias)
                elif expression_ast.getType() == AST_NODE.CONCAT:
                    import pdb
                    pdb.set_trace()
                    pass
                else:
                    import pdb
                    pdb.set_trace()
                    raise Exception("Unexpected ast node")

        print("Emulating %s" % (instruction))

        #print instruction

        if instruction.getType() == OPCODE.X86.RET:
            break

        # Next
        pc = Triton.getConcreteRegisterValue(Triton.registers.eip)

    print('Instructions executed: %d' %(count))
    return
Example #56
0
    (0x400011, b"\x66\x0F\xD7\xD1"),             # pmovmskb   edx, xmm1
    (0x400015, b"\x89\xd0"),                     # mov        eax, edx
    (0x400017, b"\x80\xf4\x99"),                 # xor        ah, 0x99
    (0x40001a, b"\xC5\xFD\x6F\xCA"),             # vmovdqa    ymm1, ymm2
]



if __name__ == '__main__':

    Triton = TritonContext()
    Triton.setArchitecture(ARCH.X86_64)

    for (addr, opcode) in code:
        # Build an instruction
        inst = Instruction()

        # Setup opcode
        inst.setOpcode(opcode)

        # Setup Address
        inst.setAddress(addr)

        # Process everything
        Triton.processing(inst)

        # Display instruction
        print(inst)

        # Display symbolic expressions
        for expr in inst.getSymbolicExpressions():
Example #57
0
def run(pc, seed):
    global flagr
    prev=None
    prevpc=0
    while pc:
        inst = Instruction()

        # Setup opcode
        opcode = Triton.getConcreteMemoryAreaValue(pc, 16)

        inst.setOpcode(opcode)
        inst.setAddress(pc)
        arr = [elem.encode("hex") for elem in inst.getOpcode()]


        Triton.processing(inst)
        if pc==0x403cec:
            print("new ok")

        if prevpc not in visited_branch and prev!=None and prev.isBranch():
            visited_branch.add(prevpc)
            print("new branch "+str(hex(prevpc)))
            break
        prev=inst
        prevpc=pc


        print("inst: "+str(inst))

        if arr[:4] == ['f3', '0f', '1e', 'fa']:
            pc += 4
            continue
        if arr[:3] == ['0f', '01', 'd0']:
            pc += 3
            continue
        if arr[0] == 'f4':
            print("abort")
            break

        if arr[0] == 'e8':
            offset = 0
            offset += int(arr[4], 16)
            offset = offset << 8
            offset += int(arr[3], 16)
            offset = offset << 8
            offset += int(arr[2], 16)
            offset = offset << 8
            offset += int(arr[1], 16)
            faddr = offset + pc + 5
            faddr = faddr & 0xffffffff

            # print(str(hex(pc))+ " calling "+str(hex(faddr)))

            try:
                printf_addr = gbinary.get_function_address("printf")
                if printf_addr == faddr:
                    pc += 5
                    continue
            except:
                pass

            try:
                fprintf_addr = gbinary.get_function_address("fprintf")
                if fprintf_addr == faddr:
                    pc += 5
                    continue
            except:
                pass

            try:
                fread_addr = gbinary.get_function_address("fread")
                if fread_addr == faddr:
                    adr = Triton.getConcreteRegisterValue(Triton.registers.rdi)
                    num = Triton.getConcreteRegisterValue(
                        Triton.registers.rsi
                    ) * Triton.getConcreteRegisterValue(Triton.registers.rdx)
                    for i in range(num):
                        if adr + i not in seed:
                            # Triton.symbolizeMemory(MemoryAccess(adr + i, 1))
                            seed[adr + i] = 0
                    pc += 5

                    Triton.setConcreteRegisterValue(Triton.registers.rax, num)
                    continue
            except:
                pass

            try:
                fseek_addr = gbinary.get_function_address("fseek")
                if fseek_addr == faddr:
                    Triton.setConcreteRegisterValue(Triton.registers.rax, 0)
                    pc += 5
                    continue
            except:
                pass
        pc = Triton.getRegisterAst(Triton.registers.rip).evaluate()
    return seed
Example #58
0
    def seed_emulate(self, ip):
        """Emulate one run of the function with already self.Triton.setup memory."""
        function = {
            #   <serial> function
            #   push    rbp
            0x40056d: b"\x55",
            #   mov     rbp,rsp
            0x40056e: b"\x48\x89\xe5",
            #   mov     QWORD PTR [rbp-0x18],rdi
            0x400571: b"\x48\x89\x7d\xe8",
            #   mov     DWORD PTR [rbp-0x4],0x0
            0x400575: b"\xc7\x45\xfc\x00\x00\x00\x00",
            #   jmp     4005bd <check+0x50>
            0x40057c: b"\xeb\x3f",
            #   mov     eax,DWORD PTR [rbp-0x4]
            0x40057e: b"\x8b\x45\xfc",
            #   movsxd  rdx,eax
            0x400581: b"\x48\x63\xd0",
            #   mov     rax,QWORD PTR [rbp-0x18]
            0x400584: b"\x48\x8b\x45\xe8",
            #   add     rax,rdx
            0x400588: b"\x48\x01\xd0",
            #   movzx   eax,BYTE PTR [rax]
            0x40058b: b"\x0f\xb6\x00",
            #   movsx   eax,al
            0x40058e: b"\x0f\xbe\xc0",
            #   sub     eax,0x1
            0x400591: b"\x83\xe8\x01",
            #   xor     eax,0x55
            0x400594: b"\x83\xf0\x55",
            #   mov     ecx,eax
            0x400597: b"\x89\xc1",
            #   mov     rdx,QWORD PTR [rip+0x200aa0]        # 601040 <serial>
            0x400599: b"\x48\x8b\x15\xa0\x0a\x20\x00",
            #   mov     eax,DWORD PTR [rbp-0x4]
            0x4005a0: b"\x8b\x45\xfc",
            #   cdqe
            0x4005a3: b"\x48\x98",
            #   add     rax,rdx
            0x4005a5: b"\x48\x01\xd0",
            #   movzx   eax,BYTE PTR [rax]
            0x4005a8: b"\x0f\xb6\x00",
            #   movsx   eax,al
            0x4005ab: b"\x0f\xbe\xc0",
            #   cmp     ecx,eax
            0x4005ae: b"\x39\xc1",
            #   je      4005b9 <check+0x4c>
            0x4005b0: b"\x74\x07",
            #   mov     eax,0x1
            0x4005b2: b"\xb8\x01\x00\x00\x00",
            #   jmp     4005c8 <check+0x5b>
            0x4005b7: b"\xeb\x0f",
            #   add     DWORD PTR [rbp-0x4],0x1
            0x4005b9: b"\x83\x45\xfc\x01",
            #   cmp     DWORD PTR [rbp-0x4],0x4
            0x4005bd: b"\x83\x7d\xfc\x04",
            #   jle     40057e <check+0x11>
            0x4005c1: b"\x7e\xbb",
            #   mov     eax,0x0
            0x4005c3: b"\xb8\x00\x00\x00\x00",
            #   pop     rbp
            0x4005c8: b"\x5d",
            #   ret
            0x4005c9: b"\xc3",
        }
        while ip in function:
            # Build an instruction
            inst = Instruction()

            # Setup opcode
            inst.setOpcode(function[ip])

            # Setup Address
            inst.setAddress(ip)

            # Process everything
            self.Triton.processing(inst)
            self.assertTrue(checkAstIntegrity(inst))

            # Next instruction
            ip = self.Triton.getRegisterAst(self.Triton.registers.rip).evaluate()
Example #59
0
class TestInstruction(unittest.TestCase):

    """Testing the Instruction class."""

    def setUp(self):
        """Define and process the instruction to test."""
        self.Triton = TritonContext()
        self.Triton.setArchitecture(ARCH.X86_64)
        self.inst = Instruction()
        self.inst.setOpcode("\x48\x01\xd8")  # add rax, rbx
        self.inst.setAddress(0x400000)
        self.Triton.setConcreteRegisterValue(self.Triton.registers.rax, 0x1122334455667788)
        self.Triton.setConcreteRegisterValue(self.Triton.registers.rbx, 0x8877665544332211)
        self.Triton.processing(self.inst)

    def test_address(self):
        """Check instruction current and next address."""
        self.assertEqual(self.inst.getAddress(), 0x400000)
        self.assertEqual(self.inst.getNextAddress(), 0x400003)

    def test_memory(self):
        """Check memory access."""
        self.assertListEqual(self.inst.getLoadAccess(), [])
        self.assertListEqual(self.inst.getStoreAccess(), [])
        self.assertFalse(self.inst.isMemoryWrite())
        self.assertFalse(self.inst.isMemoryRead())

    def test_registers(self):
        """Check register access."""
        self.assertEqual(len(self.inst.getReadRegisters()), 2, "access RAX and RBX")
        self.assertEqual(len(self.inst.getWrittenRegisters()), 8, "write in RAX, RIP, AF, XF, OF, PF, SF and ZF")

    def test_taints(self):
        """Check taints attributes."""
        self.assertFalse(self.inst.isTainted())

    def test_prefix(self):
        """Check prefix data."""
        self.assertFalse(self.inst.isPrefixed())
        self.assertEqual(self.inst.getPrefix(), PREFIX.INVALID)

    def test_control_flow(self):
        """Check control flow flags."""
        self.assertFalse(self.inst.isControlFlow(), "It is not a jmp, ret or call")
        self.assertFalse(self.inst.isBranch(), "It is not a jmp")

    def test_condition(self):
        """Check condition flags."""
        self.assertFalse(self.inst.isConditionTaken())

    def test_opcode(self):
        """Check opcode informations."""
        self.assertEqual(self.inst.getOpcode(), "\x48\x01\xd8")
        self.assertEqual(self.inst.getType(), OPCODE.ADD)

    def test_thread(self):
        """Check threads information."""
        self.assertEqual(self.inst.getThreadId(), 0)

    def test_operand(self):
        """Check operand information."""
        self.assertEqual(len(self.inst.getOperands()), 2)
        self.assertEqual(self.inst.getOperands()[0].getName(), "rax")
        self.assertEqual(self.inst.getOperands()[1].getName(), "rbx")
        with self.assertRaises(Exception):
            self.inst.getOperands()[2]

    def test_symbolic(self):
        """Check symbolic information."""
        self.assertEqual(len(self.inst.getSymbolicExpressions()), 8)

    def test_size(self):
        """Check size information."""
        self.assertEqual(self.inst.getSize(), 3)

    def test_disassembly(self):
        """Check disassembly equivalent."""
        self.assertEqual(self.inst.getDisassembly(), "add rax, rbx")
Example #60
0
    def seed_emulate(self, ip):
        """Emulate one run of the function with already self.Triton.setup memory."""
        function = {
            #   <serial> function
            #   push    rbp
            0x40056d: "\x55",
            #   mov     rbp,rsp
            0x40056e: "\x48\x89\xe5",
            #   mov     QWORD PTR [rbp-0x18],rdi
            0x400571: "\x48\x89\x7d\xe8",
            #   mov     DWORD PTR [rbp-0x4],0x0
            0x400575: "\xc7\x45\xfc\x00\x00\x00\x00",
            #   jmp     4005bd <check+0x50>
            0x40057c: "\xeb\x3f",
            #   mov     eax,DWORD PTR [rbp-0x4]
            0x40057e: "\x8b\x45\xfc",
            #   movsxd  rdx,eax
            0x400581: "\x48\x63\xd0",
            #   mov     rax,QWORD PTR [rbp-0x18]
            0x400584: "\x48\x8b\x45\xe8",
            #   add     rax,rdx
            0x400588: "\x48\x01\xd0",
            #   movzx   eax,BYTE PTR [rax]
            0x40058b: "\x0f\xb6\x00",
            #   movsx   eax,al
            0x40058e: "\x0f\xbe\xc0",
            #   sub     eax,0x1
            0x400591: "\x83\xe8\x01",
            #   xor     eax,0x55
            0x400594: "\x83\xf0\x55",
            #   mov     ecx,eax
            0x400597: "\x89\xc1",
            #   mov     rdx,QWORD PTR [rip+0x200aa0]        # 601040 <serial>
            0x400599: "\x48\x8b\x15\xa0\x0a\x20\x00",
            #   mov     eax,DWORD PTR [rbp-0x4]
            0x4005a0: "\x8b\x45\xfc",
            #   cdqe
            0x4005a3: "\x48\x98",
            #   add     rax,rdx
            0x4005a5: "\x48\x01\xd0",
            #   movzx   eax,BYTE PTR [rax]
            0x4005a8: "\x0f\xb6\x00",
            #   movsx   eax,al
            0x4005ab: "\x0f\xbe\xc0",
            #   cmp     ecx,eax
            0x4005ae: "\x39\xc1",
            #   je      4005b9 <check+0x4c>
            0x4005b0: "\x74\x07",
            #   mov     eax,0x1
            0x4005b2: "\xb8\x01\x00\x00\x00",
            #   jmp     4005c8 <check+0x5b>
            0x4005b7: "\xeb\x0f",
            #   add     DWORD PTR [rbp-0x4],0x1
            0x4005b9: "\x83\x45\xfc\x01",
            #   cmp     DWORD PTR [rbp-0x4],0x4
            0x4005bd: "\x83\x7d\xfc\x04",
            #   jle     40057e <check+0x11>
            0x4005c1: "\x7e\xbb",
            #   mov     eax,0x0
            0x4005c3: "\xb8\x00\x00\x00\x00",
            #   pop     rbp
            0x4005c8: "\x5d",
            #   ret
            0x4005c9: "\xc3",
        }
        while ip in function:
            # Build an instruction
            inst = Instruction()

            # Setup opcode
            inst.setOpcode(function[ip])

            # Setup Address
            inst.setAddress(ip)

            # Process everything
            self.Triton.processing(inst)
            self.assertTrue(checkAstIntegrity(inst))

            # Next instruction
            ip = self.Triton.getRegisterAst(self.Triton.registers.rip).evaluate()