def test_laser_result(self): for input_file in TESTDATA_INPUTS_CONTRACTS.iterdir(): if input_file.name in ["weak_random.sol", "environments.sol"]: continue output_expected = TESTDATA_OUTPUTS_EXPECTED_LASER_RESULT / ( input_file.name + ".json") output_current = TESTDATA_OUTPUTS_CURRENT_LASER_RESULT / ( input_file.name + ".json") disassembly = SolidityContract(str(input_file)).disassembly account = Account("0x0000000000000000000000000000000000000000", disassembly) accounts = {account.address: account} laser = svm.LaserEVM(accounts, max_depth=22, transaction_count=1) laser.register_hooks(hook_type="post", hook_dict=get_detection_module_hooks()) laser.sym_exec(account.address) laser_info = _all_info(laser) output_current.write_text( json.dumps(laser_info, cls=LaserEncoder, indent=4)) if not (output_expected.read_text() == output_expected.read_text()): self.found_changed_files(input_file, output_expected, output_current) self.assert_and_show_changed_files()
def __init__(self, contract, address, strategy, dynloader=None, max_depth=22, execution_timeout=None, create_timeout=None, transaction_count=2, priority=None): if strategy == "dfs": s_strategy = DepthFirstSearchStrategy elif strategy == "bfs": s_strategy = BreadthFirstSearchStrategy elif strategy == "naive-random": s_strategy = ReturnRandomNaivelyStrategy elif strategy == "weighted-random": s_strategy = ReturnWeightedRandomStrategy else: raise ValueError("Invalid strategy argument supplied") account = Account( address, contract.disassembly, dynamic_loader=dynloader, contract_name=contract.name, ) self.accounts = {address: account} self.laser = svm.LaserEVM( self.accounts, dynamic_loader=dynloader, max_depth=max_depth, execution_timeout=execution_timeout, strategy=s_strategy, create_timeout=create_timeout, transaction_count=transaction_count, ) self.laser.register_hooks(hook_type="pre", hook_dict=get_detection_module_hooks()) if isinstance(contract, SolidityContract): self.laser.sym_exec(creation_code=contract.creation_code, contract_name=contract.name, priority=priority) elif isinstance(contract, EVMContract) and contract.creation_code: self.laser.sym_exec(creation_code=contract.creation_code, contract_name=contract.name, priority=priority) else: self.laser.sym_exec(address, priority=priority) self.nodes = self.laser.nodes self.edges = self.laser.edges print('total states: ' + str(self.laser.total_states)) # Generate lists of interesting operations self.calls = [] self.sstors = {} for key in self.nodes: state_index = 0 for state in self.nodes[key].states: instruction = state.get_current_instruction() op = instruction["opcode"] if op in ("CALL", "CALLCODE", "DELEGATECALL", "STATICCALL"): stack = state.mstate.stack if op in ("CALL", "CALLCODE"): gas, to, value, meminstart, meminsz, memoutstart, memoutsz = ( get_variable(stack[-1]), get_variable(stack[-2]), get_variable(stack[-3]), get_variable(stack[-4]), get_variable(stack[-5]), get_variable(stack[-6]), get_variable(stack[-7]), ) if to.type == VarType.CONCRETE and to.val < 5: # ignore prebuilts continue if (meminstart.type == VarType.CONCRETE and meminsz.type == VarType.CONCRETE): self.calls.append( Call( self.nodes[key], state, state_index, op, to, gas, value, state.mstate.memory[meminstart. val:meminsz.val * 4], )) else: self.calls.append( Call( self.nodes[key], state, state_index, op, to, gas, value, )) else: gas, to, meminstart, meminsz, memoutstart, memoutsz = ( get_variable(stack[-1]), get_variable(stack[-2]), get_variable(stack[-3]), get_variable(stack[-4]), get_variable(stack[-5]), get_variable(stack[-6]), ) self.calls.append( Call(self.nodes[key], state, state_index, op, to, gas)) elif op == "SSTORE": stack = copy.deepcopy(state.mstate.stack) address = state.environment.active_account.address index, value = stack.pop(), stack.pop() try: self.sstors[address] except KeyError: self.sstors[address] = {} try: self.sstors[address][str(index)].append( SStore(self.nodes[key], state, state_index, value)) except KeyError: self.sstors[address][str(index)] = [ SStore(self.nodes[key], state, state_index, value) ] state_index += 1
def __init__( self, contract, address: Union[int, str, BitVec], strategy, dynloader=None, max_depth=22, execution_timeout=None, loop_bound=2, create_timeout=None, transaction_count=2, modules=(), compulsory_statespace=True, enable_iprof=False, disable_dependency_pruning=False, run_analysis_modules=True, ): """ :param contract: :param address: :param strategy: :param dynloader: :param max_depth: :param execution_timeout: :param create_timeout: :param transaction_count: :param modules: """ if isinstance(address, str): address = symbol_factory.BitVecVal(int(address, 16), 256) if isinstance(address, int): address = symbol_factory.BitVecVal(address, 256) if strategy == "dfs": s_strategy = DepthFirstSearchStrategy # type: Type[BasicSearchStrategy] elif strategy == "bfs": s_strategy = BreadthFirstSearchStrategy elif strategy == "naive-random": s_strategy = ReturnRandomNaivelyStrategy elif strategy == "weighted-random": s_strategy = ReturnWeightedRandomStrategy else: raise ValueError("Invalid strategy argument supplied") creator_account = Account(hex(CREATOR_ADDRESS), "", dynamic_loader=dynloader, contract_name=None) attacker_account = Account(hex(ATTACKER_ADDRESS), "", dynamic_loader=dynloader, contract_name=None) requires_statespace = (compulsory_statespace or len(get_detection_modules("post", modules)) > 0) if not contract.creation_code: self.accounts = {hex(ATTACKER_ADDRESS): attacker_account} else: self.accounts = { hex(CREATOR_ADDRESS): creator_account, hex(ATTACKER_ADDRESS): attacker_account, } self.laser = svm.LaserEVM( dynamic_loader=dynloader, max_depth=max_depth, execution_timeout=execution_timeout, strategy=s_strategy, create_timeout=create_timeout, transaction_count=transaction_count, requires_statespace=requires_statespace, enable_iprof=enable_iprof, ) if loop_bound is not None: self.laser.extend_strategy(BoundedLoopsStrategy, loop_bound) plugin_loader = LaserPluginLoader(self.laser) plugin_loader.load(PluginFactory.build_mutation_pruner_plugin()) plugin_loader.load(PluginFactory.build_instruction_coverage_plugin()) if not disable_dependency_pruning: plugin_loader.load(PluginFactory.build_dependency_pruner_plugin()) world_state = WorldState() for account in self.accounts.values(): world_state.put_account(account) if run_analysis_modules: self.laser.register_hooks( hook_type="pre", hook_dict=get_detection_module_hooks(modules, hook_type="pre"), ) self.laser.register_hooks( hook_type="post", hook_dict=get_detection_module_hooks(modules, hook_type="post"), ) if isinstance(contract, SolidityContract): self.laser.sym_exec( creation_code=contract.creation_code, contract_name=contract.name, world_state=world_state, ) elif isinstance(contract, EVMContract) and contract.creation_code: self.laser.sym_exec( creation_code=contract.creation_code, contract_name=contract.name, world_state=world_state, ) else: account = Account( address, contract.disassembly, dynamic_loader=dynloader, contract_name=contract.name, concrete_storage=True if (dynloader is not None and dynloader.storage_loading) else False, ) world_state.put_account(account) self.laser.sym_exec(world_state=world_state, target_address=address.value) if not requires_statespace: return self.nodes = self.laser.nodes self.edges = self.laser.edges # Parse calls to make them easily accessible self.calls = [] # type: List[Call] for key in self.nodes: state_index = 0 for state in self.nodes[key].states: instruction = state.get_current_instruction() op = instruction["opcode"] if op in ("CALL", "CALLCODE", "DELEGATECALL", "STATICCALL"): stack = state.mstate.stack if op in ("CALL", "CALLCODE"): gas, to, value, meminstart, meminsz, memoutstart, memoutsz = ( get_variable(stack[-1]), get_variable(stack[-2]), get_variable(stack[-3]), get_variable(stack[-4]), get_variable(stack[-5]), get_variable(stack[-6]), get_variable(stack[-7]), ) if to.type == VarType.CONCRETE and to.val < 5: # ignore prebuilts continue if (meminstart.type == VarType.CONCRETE and meminsz.type == VarType.CONCRETE): self.calls.append( Call( self.nodes[key], state, state_index, op, to, gas, value, state.mstate.memory[meminstart. val:meminsz.val * 4], )) else: self.calls.append( Call( self.nodes[key], state, state_index, op, to, gas, value, )) else: gas, to, meminstart, meminsz, memoutstart, memoutsz = ( get_variable(stack[-1]), get_variable(stack[-2]), get_variable(stack[-3]), get_variable(stack[-4]), get_variable(stack[-5]), get_variable(stack[-6]), ) self.calls.append( Call(self.nodes[key], state, state_index, op, to, gas)) state_index += 1
def __init__( self, contract, address: Union[int, str, BitVec], strategy: str, dynloader=None, max_depth: int = 22, execution_timeout: Optional[int] = None, loop_bound: int = 3, create_timeout: Optional[int] = None, transaction_count: int = 2, modules=(), compulsory_statespace: bool = True, iprof: Optional[InstructionProfiler] = None, disable_dependency_pruning: bool = False, run_analysis_modules: bool = True, enable_coverage_strategy: bool = False, custom_modules_directory: str = "", ): """ :param contract: Contract to symbolically execute :param address: Address of the contract to symbolically execute :param strategy: Execution strategy to use (bfs, dfs, etc) :param dynloader: Dynamic Loader :param max_depth: Max analysis depth :param execution_timeout: Timeout for the entire analysis :param create_timeout: Timeout for the creation transaction :param transaction_count: Number of transactions to symbolically execute :param modules: Analysis modules to run during analysis :param compulsory_statespace: Boolean indicating whether or not the statespace should be saved :param iprof: Instruction Profiler :param disable_dependency_pruning: Boolean indicating whether dependency pruning should be disabled :param run_analysis_modules: Boolean indicating whether analysis modules should be executed :param enable_coverage_strategy: Boolean indicating whether the coverage strategy should be enabled :param custom_modules_directory: The directory to read custom analysis modules from """ if isinstance(address, str): address = symbol_factory.BitVecVal(int(address, 16), 256) if isinstance(address, int): address = symbol_factory.BitVecVal(address, 256) if strategy == "dfs": s_strategy = DepthFirstSearchStrategy # type: Type[BasicSearchStrategy] elif strategy == "bfs": s_strategy = BreadthFirstSearchStrategy elif strategy == "naive-random": s_strategy = ReturnRandomNaivelyStrategy elif strategy == "weighted-random": s_strategy = ReturnWeightedRandomStrategy else: raise ValueError("Invalid strategy argument supplied") creator_account = Account( hex(CREATOR_ADDRESS), "", dynamic_loader=dynloader, contract_name=None ) attacker_account = Account( hex(ATTACKER_ADDRESS), "", dynamic_loader=dynloader, contract_name=None ) requires_statespace = ( compulsory_statespace or len(get_detection_modules("post", modules, custom_modules_directory)) > 0 ) if not contract.creation_code: self.accounts = {hex(ATTACKER_ADDRESS): attacker_account} else: self.accounts = { hex(CREATOR_ADDRESS): creator_account, hex(ATTACKER_ADDRESS): attacker_account, } instruction_laser_plugin = PluginFactory.build_instruction_coverage_plugin() self.laser = svm.LaserEVM( dynamic_loader=dynloader, max_depth=max_depth, execution_timeout=execution_timeout, strategy=s_strategy, create_timeout=create_timeout, transaction_count=transaction_count, requires_statespace=requires_statespace, iprof=iprof, enable_coverage_strategy=enable_coverage_strategy, instruction_laser_plugin=instruction_laser_plugin, ) if loop_bound is not None: self.laser.extend_strategy(BoundedLoopsStrategy, loop_bound) plugin_loader = LaserPluginLoader(self.laser) plugin_loader.load(PluginFactory.build_mutation_pruner_plugin()) plugin_loader.load(instruction_laser_plugin) if not disable_dependency_pruning: plugin_loader.load(PluginFactory.build_dependency_pruner_plugin()) world_state = WorldState() for account in self.accounts.values(): world_state.put_account(account) if run_analysis_modules: self.laser.register_hooks( hook_type="pre", hook_dict=get_detection_module_hooks( modules, hook_type="pre", custom_modules_directory=custom_modules_directory, ), ) self.laser.register_hooks( hook_type="post", hook_dict=get_detection_module_hooks( modules, hook_type="post", custom_modules_directory=custom_modules_directory, ), ) if isinstance(contract, SolidityContract): self.laser.sym_exec( creation_code=contract.creation_code, contract_name=contract.name, world_state=world_state, ) elif isinstance(contract, EVMContract) and contract.creation_code: self.laser.sym_exec( creation_code=contract.creation_code, contract_name=contract.name, world_state=world_state, ) else: account = Account( address, contract.disassembly, dynamic_loader=dynloader, contract_name=contract.name, concrete_storage=True if (dynloader is not None and dynloader.storage_loading) else False, ) world_state.put_account(account) self.laser.sym_exec(world_state=world_state, target_address=address.value) if not requires_statespace: return self.nodes = self.laser.nodes self.edges = self.laser.edges # Parse calls to make them easily accessible self.calls = [] # type: List[Call] for key in self.nodes: state_index = 0 for state in self.nodes[key].states: instruction = state.get_current_instruction() op = instruction["opcode"] if op in ("CALL", "CALLCODE", "DELEGATECALL", "STATICCALL"): stack = state.mstate.stack if op in ("CALL", "CALLCODE"): gas, to, value, meminstart, meminsz, memoutstart, memoutsz = ( get_variable(stack[-1]), get_variable(stack[-2]), get_variable(stack[-3]), get_variable(stack[-4]), get_variable(stack[-5]), get_variable(stack[-6]), get_variable(stack[-7]), ) if ( to.type == VarType.CONCRETE and 0 < to.val <= PRECOMPILE_COUNT ): # ignore prebuilts continue if ( meminstart.type == VarType.CONCRETE and meminsz.type == VarType.CONCRETE ): self.calls.append( Call( self.nodes[key], state, state_index, op, to, gas, value, state.mstate.memory[ meminstart.val : meminsz.val + meminstart.val ], ) ) else: self.calls.append( Call( self.nodes[key], state, state_index, op, to, gas, value, ) ) else: gas, to, meminstart, meminsz, memoutstart, memoutsz = ( get_variable(stack[-1]), get_variable(stack[-2]), get_variable(stack[-3]), get_variable(stack[-4]), get_variable(stack[-5]), get_variable(stack[-6]), ) self.calls.append( Call(self.nodes[key], state, state_index, op, to, gas) ) state_index += 1
def __init__( self, contract, address, strategy, dynloader=None, max_depth=22, execution_timeout=None, create_timeout=None, transaction_count=2, modules=(), compulsory_statespace=True, enable_iprof=False, ): """ :param contract: :param address: :param strategy: :param dynloader: :param max_depth: :param execution_timeout: :param create_timeout: :param transaction_count: :param modules: """ if strategy == "dfs": s_strategy = DepthFirstSearchStrategy elif strategy == "bfs": s_strategy = BreadthFirstSearchStrategy elif strategy == "naive-random": s_strategy = ReturnRandomNaivelyStrategy elif strategy == "weighted-random": s_strategy = ReturnWeightedRandomStrategy else: raise ValueError("Invalid strategy argument supplied") account = Account( address, contract.disassembly, dynamic_loader=dynloader, contract_name=contract.name, ) requires_statespace = (compulsory_statespace or len(get_detection_modules("post", modules)) > 0) self.accounts = {address: account} self.laser = svm.LaserEVM( self.accounts, dynamic_loader=dynloader, max_depth=max_depth, execution_timeout=execution_timeout, strategy=s_strategy, create_timeout=create_timeout, transaction_count=transaction_count, requires_statespace=requires_statespace, enable_iprof=enable_iprof, ) plugin_loader = LaserPluginLoader(self.laser) plugin_loader.load(PluginFactory.build_mutation_pruner_plugin()) plugin_loader.load(PluginFactory.build_instruction_coverage_plugin()) self.laser.register_hooks( hook_type="pre", hook_dict=get_detection_module_hooks(modules, hook_type="pre"), ) self.laser.register_hooks( hook_type="post", hook_dict=get_detection_module_hooks(modules, hook_type="post"), ) if isinstance(contract, SolidityContract): self.laser.sym_exec(creation_code=contract.creation_code, contract_name=contract.name) elif isinstance(contract, EVMContract) and contract.creation_code: self.laser.sym_exec(creation_code=contract.creation_code, contract_name=contract.name) else: self.laser.sym_exec(address) created_address = "0x" + str( mk_contract_address(CREATOR_ADDRESS, 0).hex()) for key, value in self.laser.world_state.accounts.items(): if created_address == value.address: contract.code = value.code.bytecode break if not requires_statespace: return self.nodes = self.laser.nodes self.edges = self.laser.edges # Generate lists of interesting operations self.calls = [] self.sstors = {} for key in self.nodes: state_index = 0 for state in self.nodes[key].states: instruction = state.get_current_instruction() op = instruction["opcode"] if op in ("CALL", "CALLCODE", "DELEGATECALL", "STATICCALL"): stack = state.mstate.stack if op in ("CALL", "CALLCODE"): gas, to, value, meminstart, meminsz, memoutstart, memoutsz = ( get_variable(stack[-1]), get_variable(stack[-2]), get_variable(stack[-3]), get_variable(stack[-4]), get_variable(stack[-5]), get_variable(stack[-6]), get_variable(stack[-7]), ) if to.type == VarType.CONCRETE and to.val < 5: # ignore prebuilts continue if (meminstart.type == VarType.CONCRETE and meminsz.type == VarType.CONCRETE): self.calls.append( Call( self.nodes[key], state, state_index, op, to, gas, value, state.mstate.memory[meminstart. val:meminsz.val * 4], )) else: self.calls.append( Call( self.nodes[key], state, state_index, op, to, gas, value, )) else: gas, to, meminstart, meminsz, memoutstart, memoutsz = ( get_variable(stack[-1]), get_variable(stack[-2]), get_variable(stack[-3]), get_variable(stack[-4]), get_variable(stack[-5]), get_variable(stack[-6]), ) self.calls.append( Call(self.nodes[key], state, state_index, op, to, gas)) elif op == "SSTORE": stack = copy.copy(state.mstate.stack) address = state.environment.active_account.address index, value = stack.pop(), stack.pop() try: self.sstors[address] except KeyError: self.sstors[address] = {} try: self.sstors[address][str(index)].append( SStore(self.nodes[key], state, state_index, value)) except KeyError: self.sstors[address][str(index)] = [ SStore(self.nodes[key], state, state_index, value) ] state_index += 1