def trace(self, ip): self.setup() while True: if len(self.instructions) > 1000: break op = idc.GetManyBytes(ip, idc.ItemSize(ip)) prev_esp = self.tx.buildSymbolicRegister( self.tx.registers.esp).evaluate() ins = Instruction() ins.setOpcode(op) ins.setAddress(ip) self.tx.processing(ins) ins_id = self.add_instruction(ins, prev_esp) if self.debug: reads = " ".join( map(lambda x: x.getName(), self.get_side_reads(ins))) writes = " ".join( map(lambda x: x.getName(), self.get_side_writes(ins))) mem_writes = " ".join( map(lambda x: "%08x" % x.getAddress(), self.get_side_mem_writes(ins))) #print "%08x [%03d] %-30s %-20s %-20s %s" % (ip,ins_id,ins.getDisassembly(),reads,writes,self.instructions[-1]['state']) print "%08x [%03d] %-40s %-30s %-30s (mem writes: %s)" % ( ip, ins_id, ins.getDisassembly(), reads, writes, mem_writes) next_ip = self.follow_flow() if not next_ip: break ip = next_ip good = self.extract_good() print "Good instructions: %s" % sorted(good) svar_lookup = dict() num = 0 for i in sorted(good): esp = "" for op in self.instructions[i]['ins'].getOperands(): if op.getType() == OPERAND.MEM and op.getBaseRegister( ).getName() == "esp": esp = "%08x" % op.getAddress() line = "[%03d] %s" % ( i, self.instructions[i]['ins'].getDisassembly()) if esp: line = re.sub(r"\[esp.*\]", "[%s]" % esp, line) if int(esp, 16) not in svar_lookup: svar_lookup[int(esp, 16)] = "svar%d" % num num += 1 line = line.replace("[%s]" % esp, "[%s]" % svar_lookup[int(esp, 16)]) print line
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 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
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
def emulate(ctx, pc): targetFound = False astCtxt = ctx.getAstContext() logging.info('[+] Starting emulation.') while pc: # Fetch opcode opcode = ctx.getConcreteMemoryAreaValue(pc, 16) # Create the ctx instruction instruction = Instruction() instruction.setOpcode(opcode) instruction.setAddress(pc) # Process ctx.processing(instruction) logging.info(instruction) # Next pc = ctx.getConcreteRegisterValue(ctx.registers.rip) if TARGET_TO_REACH is not None and pc == TARGET_TO_REACH: targetFound = True logging.info('[+] Emulation done.') return targetFound
def emulate(pc, w): while pc: #print 'pc1',pc opcodes = Triton.getConcreteMemoryAreaValue(pc, 16) #print 'opcodes',opcodes instruction = Instruction() instruction.setOpcode(opcodes) instruction.setAddress(pc) Triton.processing(instruction) #pc = hex(eip.evaluate()) pc = Triton.getConcreteRegisterValue(Triton.registers.eip) if sys.argv[3].startswith("0x"): target = int(sys.argv[3][2:], 16) #print 'target',target i = 1 if pc == target: print '==================Address found with following seeds=============' for address, value in seed.items(): if (address == 1879048195): print 'argc ', value else: x = address - 22528 y = int(x / 100) z = int(x % 100) print 'argv[', y, '][', z, '] ', value i = i + 1 w = 11 break return w
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
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
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.X86.HLT: break # Simulate routines hookingHandler() # Next pc = Triton.getConcreteRegisterValue(Triton.registers.rip) debug('Instruction executed: %d' % (count)) return
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 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 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
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.getPathPredicate() # 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
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
def __emulate(self, pc: int, countBBlocks: bool): targetAddressFound = False currentBBlockAddr = pc # The basic block address that we started to analyze currently numNewBasicBlocks = 0 # The number of new basic blocks found by this function (only if countBBlocks was activated) newBasicBlocksFound = set() basicBlocksPathFoundThisRun = [] def onBasicBlockFound(addr): nonlocal numNewBasicBlocks nonlocal newBasicBlocksFound nonlocal basicBlocksPathFoundThisRun basicBlocksPathFoundThisRun.append(addr) # Is this a new basic block ? if addr not in self.allBlocksFound: numNewBasicBlocks += 1 newBasicBlocksFound.add(addr) self.allBlocksFound.add(addr) onBasicBlockFound(currentBBlockAddr) logging.info('[+] Starting emulation.') while pc and (pc >= self.codeSection_begin and pc <= self.codeSection_end): # Fetch opcode opcode = self.context.getConcreteMemoryAreaValue(pc, 16) # Create the ctx instruction instruction = Instruction() instruction.setOpcode(opcode) instruction.setAddress(pc) # Process self.context.processing(instruction) logging.info(instruction) # Next prevpc = pc pc = self.context.getConcreteRegisterValue( self.context.registers.rip) if instruction.isControlFlow(): currentBBlockAddr = pc onBasicBlockFound(currentBBlockAddr) logging.info( f"Instruction is control flow of type {instruction.getType()}. Addr of the new Basic block {hex(currentBBlockAddr)}" ) if self.TARGET_TO_REACH is not None and pc == self.TARGET_TO_REACH: targetAddressFound = True logging.info('[+] Emulation done.') if countBBlocks: logging.info( f'===== New basic blocks found: {[hex(intBlock) for intBlock in newBasicBlocksFound]}' ) if basicBlocksPathFoundThisRun[-1] == 0: # ret instruction basicBlocksPathFoundThisRun = basicBlocksPathFoundThisRun[:-1] return targetAddressFound, numNewBasicBlocks, basicBlocksPathFoundThisRun
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.X86.HLT: break # Simulate routines hookingHandler() # Next pc = Triton.getConcreteRegisterValue(Triton.registers.rip) print('[+] Emulation done.') return
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
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.getSymbolicRegister(Triton.registers.rax) eax = astCtxt.extract(31, 0, rax.getAst()) # Push a new constraint to the current path predicate Triton.pushPathConstraint(eax == goodBranches[pc]) # Solve the path predicate cstr = Triton.getPathPredicate() print('[+] Asking for a model, please wait...') model = Triton.getModel(cstr) # Save new state for k, v in list(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
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_load_ds(self): """Check load from ds segment.""" self.Triton = TritonContext() self.Triton.setArchitecture(ARCH.X86) inst = Instruction() # mov ax, ds:word_40213C inst.setOpcode("\x66\xA1\x3C\x21\x40\x00") self.Triton.processing(inst) self.assertEqual(inst.getOperands()[1].getAddress(), 0x40213C) self.assertEqual(inst.getOperands()[1].getBitSize(), 16)
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
def test_load_ds(self): """Check load from ds segment.""" self.Triton = TritonContext() self.Triton.setArchitecture(ARCH.X86) inst = Instruction() # mov ax, ds:word_40213C inst.setOpcode(b"\x66\xA1\x3C\x21\x40\x00") self.Triton.processing(inst) self.assertEqual(inst.getOperands()[1].getAddress(), 0x40213C) self.assertEqual(inst.getOperands()[1].getBitSize(), 16)
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))
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(b"\x8D\x04\x06") Triton.processing(inst) self.assertTrue(Triton.isRegisterTainted(Triton.registers.eax)) self.assertFalse(Triton.isRegisterTainted(Triton.registers.ebx))
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 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
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.getSymbolicExpressionFromId( self.Triton.getSymbolicRegisterId( 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.setConcreteSymbolicVariableValue( self.Triton.getSymbolicVariableFromId(k), value) # Next pc = self.Triton.getConcreteRegisterValue( self.Triton.registers.rip) return solution
def main(): code = [(0x1000, "\x83\xc4\x08"), (0x1003, "\x5b"), (0x1004, "\xc3")] ctxt = TritonContext() ctxt.setArchitecture(ARCH.X86) #load instructions for (addr, opcode) in code: inst = Instruction() inst.setOpcode(opcode) inst.setAddress(addr) if not ctxt.processing(inst): print "Fail an instruction" print inst expr = inst.getSymbolicExpressions()[0] print expr
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
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)
def emulate(pc, index, y, targetadd): Triton.concretizeAllRegister() Triton.concretizeAllMemory() flag = 0 Triton.setConcreteRegisterValue(Triton.registers.ebp, 0x6ffffffb) Triton.setConcreteRegisterValue(Triton.registers.ebp, 0x6fffffff) esp = Triton.buildSymbolicRegister(Triton.registers.ebp).evaluate() address = 28 addressv = 200 Triton.setConcreteMemoryValue(esp + 12, address) Triton.setConcreteMemoryValue(address, addressv) for i in range(index + 1): Triton.setConcreteMemoryValue(addressv, ord('S')) addressv = addressv + 1 if (y == 1): #strin= "" for j in range(index): print 'F' #strin = strin+'F' #print strin,hex(targetadd) print hex(targetadd) while pc: opcodes = Triton.getConcreteMemoryAreaValue(pc, 16) instruction = Instruction() instruction.setOpcode(opcodes) instruction.setAddress(pc) Triton.processing(instruction) if (instruction.isControlFlow()): flag = flag + 1 if instruction.getType() == OPCODE.INT: pc = instruction.getNextAddress() y = Triton.buildSymbolicRegister(Triton.registers.eax).evaluate() if y == 1: break continue pc = Triton.buildSymbolicRegister(Triton.registers.eip).evaluate() if (pc == 28): return 5 return 1
def test_load_immediate_fs(self): """Check load from fs segment with immediate.""" self.Triton = TritonContext() self.Triton.setArchitecture(ARCH.X86_64) inst = Instruction() # mov eax, DWORD PTR fs:0xffffffffffffdf98 inst.setOpcode(b"\x64\x8B\x04\x25\x98\xDF\xFF\xFF") inst.setAddress(0x400000) self.Triton.setConcreteRegisterValue(self.Triton.registers.fs, 0x7fffda8ab700) self.Triton.processing(inst) self.assertTrue(inst.getLoadAccess()) load, _ = inst.getLoadAccess()[0] self.assertEqual(load.getAddress(), 0x7fffda8a9698) self.assertEqual(load.getBitSize(), 32)
def test_load_immediate_fs(self): """Check load from fs segment with immediate.""" self.Triton = TritonContext() self.Triton.setArchitecture(ARCH.X86_64) inst = Instruction() # mov eax, DWORD PTR fs:0xffffffffffffdf98 inst.setOpcode("\x64\x8B\x04\x25\x98\xDF\xFF\xFF") inst.setAddress(0x400000) self.Triton.setConcreteRegisterValue(self.Triton.registers.fs, 0x7fffda8ab700) self.Triton.processing(inst) self.assertTrue(inst.getLoadAccess()) load, _ = inst.getLoadAccess()[0] self.assertEqual(load.getAddress(), 0x7fffda8a9698) self.assertEqual(load.getBitSize(), 32)
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)
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
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(b"\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)
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
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
def emulate(pc): flag = bytearray(39) 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) #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: value = Triton.getConcreteMemoryValue(mem) if value: flag[count] = value count += 1 if instruction.getType() == OPCODE.X86.HLT: break # Simulate routines hookingHandler() # Next pc = Triton.getConcreteRegisterValue(Triton.registers.rip) print(' %s' % flag) if flag == b"hackover15{I_USE_GOTO_WHEREEVER_I_W4NT}": return 0 return -1
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
def emulate(pc,w): while pc: #print 'pc1',pc opcodes = Triton.getConcreteMemoryAreaValue(pc, 16) #print 'opcodes',opcodes instruction = Instruction() instruction.setOpcode(opcodes) instruction.setAddress(pc) Triton.processing(instruction) if instruction.getType()== OPCODE.INT : if Triton.getConcreteRegisterValue(Triton.registers.eax)==1: break pc=pc+2 continue if instruction.getType() == OPCODE.HLT: break pc = Triton.buildSymbolicRegister(Triton.registers.eip).evaluate() if sys.argv[3].startswith("0x"): target = int(sys.argv[3][2:],16) #print 'target',target i=1 if pc == target: #printoutput() '''for address, value in seed.items(): #print 'address',address print chr(value) if(address==1879048195): print 'argc ',value else: x=address-22528 y=int(x/100) z=int(x%100) print 'argv[',y,'][',z,'] ',value i=i+1''' w=11 break return w
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
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
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
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
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()
if __name__ == '__main__': Triton = TritonContext() #Set the arch 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 print ' ---------------' print ' Is memory read :', inst.isMemoryRead() print ' Is memory write:', inst.isMemoryWrite() print ' ---------------' for op in inst.getOperands(): print ' Operand:', op
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")
triton = TritonContext() triton.setArchitecture(ARCH.X86_64) triton.enableMode(MODE.ALIGNED_MEMORY, True) triton.setConcreteRegisterValue(triton.registers.rsp, 0x7fffffff) return triton if __name__ == '__main__': for i in range(10): triton = initialize() pc = 0x400080 while pc in function: inst = Instruction() inst.setOpcode(function[pc]) inst.setAddress(pc) if before_processing(inst, triton): sys.exit(0) triton.processing(inst) print(inst) after_processing(inst, triton) pc = triton.getRegisterAst(triton.registers.rip).evaluate() print("pc: %16x" % (pc)) print("give up")