Search is not available for this dataset
text
stringlengths
75
104k
def new_symbolic_buffer(self, nbytes, **options): """Create and return a symbolic buffer of length `nbytes`. The buffer is not written into State's memory; write it to the state's memory to introduce it into the program state. :param int nbytes: Length of the new buffer :param s...
def new_symbolic_value(self, nbits, label=None, taint=frozenset()): """Create and return a symbolic value that is `nbits` bits wide. Assign the value to a register or write it into the address space to introduce it into the program state. :param int nbits: The bitwidth of the value retu...
def concretize(self, symbolic, policy, maxcount=7): """ This finds a set of solutions for symbolic using policy. This raises TooManySolutions if more solutions than maxcount """ assert self.constraints == self.platform.constraints symbolic = self.migrate_expression(symbolic) ...
def solve_one(self, expr, constrain=False): """ Concretize a symbolic :class:`~manticore.core.smtlib.expression.Expression` into one solution. :param manticore.core.smtlib.Expression expr: Symbolic value to concretize :param bool constrain: If True, constrain expr to concretized...
def solve_n(self, expr, nsolves): """ Concretize a symbolic :class:`~manticore.core.smtlib.expression.Expression` into `nsolves` solutions. :param manticore.core.smtlib.Expression expr: Symbolic value to concretize :return: Concrete value :rtype: list[int] """ ...
def solve_max(self, expr): """ Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into its maximum solution :param manticore.core.smtlib.Expression expr: Symbolic value to solve :return: Concrete value :rtype: list[int] """ if isinsta...
def solve_min(self, expr): """ Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into its minimum solution :param manticore.core.smtlib.Expression expr: Symbolic value to solve :return: Concrete value :rtype: list[int] """ if isinsta...
def solve_minmax(self, expr): """ Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into its minimum and maximun solution. Only defined for bitvects. :param manticore.core.smtlib.Expression expr: Symbolic value to solve :return: Concrete value :rtyp...
def solve_buffer(self, addr, nbytes, constrain=False): """ Reads `nbytes` of symbolic data from a buffer in memory at `addr` and attempts to concretize it :param int address: Address of buffer to concretize :param int nbytes: Size of buffer to concretize :param bool cons...
def symbolicate_buffer(self, data, label='INPUT', wildcard='+', string=False, taint=frozenset()): """Mark parts of a buffer as symbolic (demarked by the wildcard byte) :param str data: The string to symbolicate. If no wildcard bytes are provided, this is the identity function on the fir...
def _create_emulated_mapping(self, uc, address): """ Create a mapping in Unicorn and note that we'll need it if we retry. :param uc: The Unicorn instance. :param address: The address which is contained by the mapping. :rtype Map """ m = self._cpu.memory.map_conta...
def _hook_xfer_mem(self, uc, access, address, size, value, data): """ Handle memory operations from unicorn. """ assert access in (UC_MEM_WRITE, UC_MEM_READ, UC_MEM_FETCH) if access == UC_MEM_WRITE: self._cpu.write_int(address, value, size * 8) # If client c...
def _hook_unmapped(self, uc, access, address, size, value, data): """ We hit an unmapped region; map it into unicorn. """ try: m = self._create_emulated_mapping(uc, address) except MemoryException as e: self._to_raise = e self._should_try_agai...
def _interrupt(self, uc, number, data): """ Handle software interrupt (SVC/INT) """ from ..native.cpu.abstractcpu import Interruption # prevent circular imports self._to_raise = Interruption(number) return True
def emulate(self, instruction): """ Emulate a single instruction. """ # The emulation might restart if Unicorn needs to bring in a memory map # or bring a value from Manticore state. while True: self.reset() # Establish Manticore state, potentia...
def _step(self, instruction): """ A single attempt at executing an instruction. """ logger.debug("0x%x:\t%s\t%s" % (instruction.address, instruction.mnemonic, instruction.op_str)) registers = set(self._cpu.canonical_registers) # Refer to EFLAGS inst...
def rlp_encode(item): r""" Recursive Length Prefix Encoding :param item: the object to encode, either a string, bytes, bytearray, int, long, or sequence https://github.com/ethereum/wiki/wiki/RLP >>> rlp_encode('dog') b'\x83dog' >>> rlp_encode([ 'cat', 'dog' ]) b'\xc8\x83cat\x83dog' ...
def must_be_true(self, constraints, expression) -> bool: """Check if expression is True and that it can not be False with current constraints""" solutions = self.get_all_values(constraints, expression, maxcnt=2, silent=True) return solutions == [True]
def max(self, constraints, X: BitVec, M=10000): """ Iteratively finds the maximum value for a symbol within given constraints. :param X: a symbol or expression :param M: maximum number of iterations allowed """ assert isinstance(X, BitVec) return self.optimize(con...
def min(self, constraints, X: BitVec, M=10000): """ Iteratively finds the minimum value for a symbol within given constraints. :param constraints: constraints that the expression must fulfil :param X: a symbol or expression :param M: maximum number of iterations allowed ...
def minmax(self, constraints, x, iters=10000): """Returns the min and max possible values for x within given constraints""" if issymbolic(x): m = self.min(constraints, x, iters) M = self.max(constraints, x, iters) return m, M else: return x, x
def _solver_version(self) -> Version: """ If we fail to parse the version, we assume z3's output has changed, meaning it's a newer version than what's used now, and therefore ok. Anticipated version_cmd_output format: 'Z3 version 4.4.2' 'Z3...
def _start_proc(self): """Spawns z3 solver process""" assert '_proc' not in dir(self) or self._proc is None try: self._proc = Popen(shlex.split(self._command), stdin=PIPE, stdout=PIPE, bufsize=0, universal_newlines=True) except OSError as e: print(e, "Probably too...
def _stop_proc(self): """ Stops the z3 solver process by: - sending an exit command to it, - sending a SIGKILL signal, - waiting till the process terminates (so we don't leave a zombie process) """ if self._proc is None: return if self._proc.re...
def _reset(self, constraints=None): """Auxiliary method to reset the smtlib external solver to initial defaults""" if self._proc is None: self._start_proc() else: if self.support_reset: self._send("(reset)") for cfg in self._init: ...
def _send(self, cmd: str): """ Send a string to the solver. :param cmd: a SMTLIBv2 command (ex. (check-sat)) """ logger.debug('>%s', cmd) try: self._proc.stdout.flush() self._proc.stdin.write(f'{cmd}\n') except IOError as e: ra...
def _recv(self) -> str: """Reads the response from the solver""" buf, left, right = self.__readline_and_count() bufl = [buf] while left != right: buf, l, r = self.__readline_and_count() bufl.append(buf) left += l right += r buf = ...
def _is_sat(self) -> bool: """ Check the satisfiability of the current state :return: whether current state is satisfiable or not. """ logger.debug("Solver.check() ") start = time.time() self._send('(check-sat)') status = self._recv() logger.debug...
def _assert(self, expression: Bool): """Auxiliary method to send an assert""" assert isinstance(expression, Bool) smtlib = translate_to_smtlib(expression) self._send('(assert %s)' % smtlib)
def _getvalue(self, expression): """ Ask the solver for one possible assignment for given expression using current set of constraints. The current set of expressions must be sat. NOTE: This is an internal method: it uses the current solver state (set of constraints!). """ ...
def can_be_true(self, constraints, expression): """Check if two potentially symbolic values can be equal""" if isinstance(expression, bool): if not expression: return expression else: # if True check if constraints are feasible self...
def get_all_values(self, constraints, expression, maxcnt=None, silent=False): """Returns a list with all the possible values for the symbol x""" if not isinstance(expression, Expression): return [expression] assert isinstance(constraints, ConstraintSet) assert isinstance(expr...
def optimize(self, constraints: ConstraintSet, x: BitVec, goal: str, M=10000): """ Iteratively finds the maximum or minimum value for the operation (Normally Operators.UGT or Operators.ULT) :param constraints: constraints to take into account :param x: a symbol or expression ...
def get_value(self, constraints, expression): """ Ask the solver for one possible result of given expression using given set of constraints. """ if not issymbolic(expression): return expression assert isinstance(expression, (Bool, BitVec, Array)) with constrai...
def summarized_name(self, name): """ Produce a summarized record name i.e. manticore.core.executor -> m.c.executor """ components = name.split('.') prefix = '.'.join(c[0] for c in components[:-1]) return f'{prefix}.{components[-1]}'
def colored_level_name(self, levelname): """ Colors the logging level in the logging record """ if self.colors_disabled: return self.plain_levelname_format.format(levelname) else: return self.colored_levelname_format.format(self.color_map[levelname], level...
def _find_zero(cpu, constrs, ptr): """ Helper for finding the closest NULL or, effectively NULL byte from a starting address. :param Cpu cpu: :param ConstraintSet constrs: Constraints for current `State` :param int ptr: Address to start searching for a zero from :return: Offset from `ptr` to fi...
def strcmp(state, s1, s2): """ strcmp symbolic model. Algorithm: Walks from end of string (minimum offset to NULL in either string) to beginning building tree of ITEs each time either of the bytes at current offset is symbolic. Points of Interest: - We've been building up a symbolic tree b...
def strlen(state, s): """ strlen symbolic model. Algorithm: Walks from end of string not including NULL building ITE tree when current byte is symbolic. :param State state: current program state :param int s: Address of string :return: Symbolic strlen result :rtype: Expression or int "...
def all_events(cls): """ Return all events that all subclasses have so far registered to publish. """ all_evts = set() for cls, evts in cls.__all_events__.items(): all_evts.update(evts) return all_evts
def forward_events_to(self, sink, include_source=False): """This forwards signal to sink""" assert isinstance(sink, Eventful), f'{sink.__class__.__name__} is not Eventful' self._forwards[sink] = include_source
def context(self): """ Convenient access to shared context """ if self._context is not None: return self._context else: logger.warning("Using shared context without a lock") return self._executor._shared_context
def locked_context(self, key=None, value_type=list): """ A context manager that provides safe parallel access to the global Manticore context. This should be used to access the global Manticore context when parallel analysis is activated. Code within the `with` block is executed ...
def get_profiling_stats(self): """ Returns a pstat.Stats instance with profiling results if `run` was called with `should_profile=True`. Otherwise, returns `None`. """ profile_file_path = os.path.join(self.workspace, 'profiling.bin') try: return pstats.Stats(p...
def run(self, procs=1, timeout=None, should_profile=False): """ Runs analysis. :param int procs: Number of parallel worker processes :param timeout: Analysis timeout, in seconds """ assert not self.running, "Manticore is already running." self._start_run() ...
def main(): """ Dispatches execution into one of Manticore's engines: evm or native. """ args = parse_arguments() if args.no_colors: log.disable_colors() sys.setrecursionlimit(consts.recursionlimit) ManticoreBase.verbosity(args.v) if args.argv[0].endswith('.sol'): eth...
def GetNBits(value, nbits): """ Get the first `nbits` from `value`. :param value: Source value from which to extract :type value: int or long or BitVec :param int nbits: How many bits to extract :return: Low `nbits` bits of `value`. :rtype int or long or BitVec """ # NOP if sizes ar...
def SInt(value, width): """ Convert a bitstring `value` of `width` bits to a signed integer representation. :param value: The value to convert. :type value: int or long or BitVec :param int width: The width of the bitstring to consider :return: The converted value :rtype int or long or ...
def LSL_C(value, amount, width): """ The ARM LSL_C (logical left shift with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value and the carry result ...
def LSL(value, amount, width): """ The ARM LSL (logical left shift) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value :rtype int or BitVec """ if ...
def LSR_C(value, amount, width): """ The ARM LSR_C (logical shift right with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value and carry result :rt...
def LSR(value, amount, width): """ The ARM LSR (logical shift right) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value :rtype int or BitVec """ if...
def ASR_C(value, amount, width): """ The ARM ASR_C (arithmetic shift right with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value and carry result ...
def ASR(value, amount, width): """ The ARM ASR (arithmetic shift right) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to shift it. :param int width: Width of the value :return: Resultant value :rtype int or BitVec """ ...
def ROR_C(value, amount, width): """ The ARM ROR_C (rotate right with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to rotate it. :param int width: Width of the value :return: Resultant value and carry result :rtype tu...
def ROR(value, amount, width): """ The ARM ROR (rotate right) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to rotate it. :param int width: Width of the value :return: Resultant value :rtype int or BitVec """ if amoun...
def RRX_C(value, carry, width): """ The ARM RRX (rotate right with extend and with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to rotate it. :param int width: Width of the value :return: Resultant value and carry result ...
def RRX(value, carry, width): """ The ARM RRX (rotate right with extend) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to rotate it. :param int width: Width of the value :return: Resultant value :rtype int or BitVec """ ...
def locked_context(self, key=None, default=dict): """ Policy shared context dictionary """ keys = ['policy'] if key is not None: keys.append(key) with self._executor.locked_context('.'.join(keys), default) as policy_context: yield policy_context
def _add_state_callback(self, state_id, state): """ Save summarize(state) on policy shared context before the state is stored """ summary = self.summarize(state) if summary is None: return with self.locked_context('summaries', dict) as ctx: ctx...
def _visited_callback(self, state, pc, instr): """ Maintain our own copy of the visited set """ with self.locked_context('visited', set) as ctx: ctx.add(pc)
def _visited_callback(self, state, pc, instr): """ Maintain our own copy of the visited set """ pc = state.platform.current.PC with self.locked_context('visited', dict) as ctx: ctx[pc] = ctx.get(pc, 0) + 1
def locked_context(self, key=None, default=dict): """ Executor context is a shared memory object. All workers share this. It needs a lock. Its used like this: with executor.context() as context: visited = context['visited'] visited.append(state.cpu.PC) ...
def enqueue(self, state): """ Enqueue state. Save state on storage, assigns an id to it, then add it to the priority queue """ # save the state to secondary storage state_id = self._workspace.save_state(state) self.put(state_id) self._p...
def put(self, state_id): """ Enqueue it for processing """ self._states.append(state_id) self._lock.notify_all() return state_id
def get(self): """ Dequeue a state with the max priority """ # A shutdown has been requested if self.is_shutdown(): return None # if not more states in the queue, let's wait for some forks while len(self._states) == 0: # if no worker is running, bail out...
def fork(self, state, expression, policy='ALL', setstate=None): """ Fork state on expression concretizations. Using policy build a list of solutions for expression. For the state on each solution setting the new state with setstate For example if expression is a Bool it may have...
def run(self): """ Entry point of the Executor; called by workers to start analysis. """ # policy_order=self.policy_order # policy=self.policy current_state = None current_state_id = None with WithKeyboardInterruptAs(self.shutdown): # notify s...
def linux(cls, path, argv=None, envp=None, entry_symbol=None, symbolic_files=None, concrete_start='', pure_symbolic=False, stdin_size=None, **kwargs): """ Constructor for Linux binary analysis. :param str path: Path to binary to analyze :param argv: Arguments to provide to the binary ...
def decree(cls, path, concrete_start='', **kwargs): """ Constructor for Decree binary analysis. :param str path: Path to binary to analyze :param str concrete_start: Concrete stdin to use before symbolic input :param kwargs: Forwarded to the Manticore constructor :return...
def init(self, f): """ A decorator used to register a hook function to run before analysis begins. Hook function takes one :class:`~manticore.core.state.State` argument. """ def callback(manticore_obj, state): f(state) self.subscribe('will_start_run', types.Me...
def hook(self, pc): """ A decorator used to register a hook function for a given instruction address. Equivalent to calling :func:`~add_hook`. :param pc: Address of instruction to hook :type pc: int or None """ def decorator(f): self.add_hook(pc, f) ...
def add_hook(self, pc, callback): """ Add a callback to be invoked on executing a program counter. Pass `None` for pc to invoke callback on every instruction. `callback` should be a callable that takes one :class:`~manticore.core.state.State` argument. :param pc: Address of inst...
def _hook_callback(self, state, pc, instruction): 'Invoke all registered generic hooks' # Ignore symbolic pc. # TODO(yan): Should we ask the solver if any of the hooks are possible, # and execute those that are? if issymbolic(pc): return # Invoke all pc-spe...
def resolve(self, symbol): """ A helper method used to resolve a symbol name into a memory address when injecting hooks for analysis. :param symbol: function name to be resolved :type symbol: string :param line: if more functions present, optional line number can be inc...
def binary_arch(binary): """ helper method for determining binary architecture :param binary: str for binary to introspect. :rtype bool: True for x86_64, False otherwise """ with open(binary, 'rb') as f: elffile = ELFFile(f) if elffile['e_machine'] == 'EM_X86_64': r...
def binary_symbols(binary): """ helper method for getting all binary symbols with SANDSHREW_ prepended. We do this in order to provide the symbols Manticore should hook on to perform main analysis. :param binary: str for binary to instrospect. :rtype list: list of symbols from binary """ ...
def get_group(name: str) -> _Group: """ Get a configuration variable group named |name| """ global _groups if name in _groups: return _groups[name] group = _Group(name) _groups[name] = group return group
def save(f): """ Save current config state to an yml file stream identified by |f| :param f: where to write the config file """ global _groups c = {} for group_name, group in _groups.items(): section = {var.name: var.value for var in group.updated_vars()} if not section: ...
def parse_config(f): """ Load an yml-formatted configuration from file stream |f| :param file f: Where to read the config. """ try: c = yaml.safe_load(f) for section_name, section in c.items(): group = get_group(section_name) for key, val in section.items()...
def load_overrides(path=None): """ Load config overrides from the yml file at |path|, or from default paths. If a path is provided and it does not exist, raise an exception Default paths: ./mcore.yml, ./.mcore.yml, ./manticore.yml, ./.manticore.yml. """ if path is not None: names = [pa...
def add_config_vars_to_argparse(args): """ Import all defined config vars into |args|, for parsing command line. :param args: A container for argparse vars :type args: argparse.ArgumentParser or argparse._ArgumentGroup :return: """ global _groups for group_name, group in _groups.items():...
def process_config_values(parser: argparse.ArgumentParser, args: argparse.Namespace): """ Bring in provided config values to the args parser, and import entries to the config from all arguments that were actually passed on the command line :param parser: The arg parser :param args: The value that p...
def add(self, name: str, default=None, description: str=None): """ Add a variable named |name| to this value group, optionally giving it a default value and a description. Variables must be added with this method before they can be set or read. Reading a variable replaces the va...
def update(self, name: str, value=None, default=None, description: str=None): """ Like add, but can tolerate existing values; also updates the value. Mostly used for setting fields from imported INI files and modified CLI flags. """ if name in self._vars: description...
def get_description(self, name: str) -> str: """ Return the description, or a help string of variable identified by |name|. """ if name not in self._vars: raise ConfigError(f"{self.name}.{name} not defined.") return self._vars[name].description
def correspond(text): """Communicate with the child process without closing stdin.""" subproc.stdin.write(text) subproc.stdin.flush() return drain()
def function_signature_for_name_and_inputs(name: str, inputs: Sequence[Mapping[str, Any]]) -> str: """Returns the function signature for the specified name and Solidity JSON metadata inputs array. The ABI specification defines the function signature as the function name followed by the parenthesised li...
def tuple_signature_for_components(components: Sequence[Mapping[str, Any]]) -> str: """Equivalent to ``function_signature_for_name_and_inputs('', components)``.""" ts = [] for c in components: t: str = c['type'] if t.startswith('tuple'): assert len(t) == 5...
def get_constructor_arguments(self) -> str: """Returns the tuple type signature for the arguments of the contract constructor.""" item = self._constructor_abi_item return '()' if item is None else self.tuple_signature_for_components(item['inputs'])
def get_source_for(self, asm_offset, runtime=True): """ Solidity source code snippet related to `asm_pos` evm bytecode offset. If runtime is False, initialization bytecode source map is used """ srcmap = self.get_srcmap(runtime) try: beg, size, _, _ = srcmap[asm_...
def constructor_abi(self) -> Dict[str, Any]: """Returns a copy of the Solidity JSON ABI item for the contract constructor. The content of the returned dict is described at https://solidity.readthedocs.io/en/latest/abi-spec.html#json_ """ item = self._constructor_abi_item if item...
def get_abi(self, hsh: bytes) -> Dict[str, Any]: """Returns a copy of the Solidity JSON ABI item for the function associated with the selector ``hsh``. If no normal contract function has the specified selector, a dict describing the default or non-default fallback function is returned. ...
def get_func_argument_types(self, hsh: bytes): """Returns the tuple type signature for the arguments of the function associated with the selector ``hsh``. If no normal contract function has the specified selector, the empty tuple type signature ``'()'`` is returned. """ if not i...
def get_func_return_types(self, hsh: bytes) -> str: """Returns the tuple type signature for the output values of the function associated with the selector ``hsh``. If no normal contract function has the specified selector, the empty tuple type signature ``'()'`` is returned. """...
def get_func_name(self, hsh: bytes) -> str: """Returns the name of the normal function with the selector ``hsh``, or ``'{fallback}'`` if no such function exists. """ if not isinstance(hsh, (bytes, bytearray)): raise TypeError('The selector argument must be a concrete byte arr...
def get_func_signature(self, hsh: bytes) -> Optional[str]: """Returns the signature of the normal function with the selector ``hsh``, or ``None`` if no such function exists. This function returns ``None`` for any selector that will be dispatched to a fallback function. """ if no...
def function_selectors(self) -> Iterable[bytes]: """The selectors of all normal contract functions, plus ``self.fallback_function_selector`` if the contract has a non-default fallback function. """ selectors = self._function_signatures_by_selector.keys() if self._fallback_functio...
def hashes(self) -> Tuple[bytes, ...]: """The selectors of all normal contract functions, plus ``self.fallback_function_selector``.""" selectors = self._function_signatures_by_selector.keys() return (*selectors, self.fallback_function_selector)
def convert_permissions(m_perms): """ Converts a Manticore permission string into a Unicorn permission :param m_perms: Manticore perm string ('rwx') :return: Unicorn Permissions """ permissions = UC_PROT_NONE if 'r' in m_perms: permissions |= UC_PROT_READ if 'w' in m_perms: ...