INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Determine validity of a Canadian Social Insurance Number. Validation is performed using a modified Luhn Algorithm. To check the Every second digit of the SIN is doubled and the result is summed. If the result is a multiple of ten, the Social Insurance Number is considered valid. https://en.wikipe...
def checksum(sin): """ Determine validity of a Canadian Social Insurance Number. Validation is performed using a modified Luhn Algorithm. To check the Every second digit of the SIN is doubled and the result is summed. If the result is a multiple of ten, the Social Insurance Number is considere...
Produce a hostname with specified number of subdomain levels. >>> hostname() db-01.nichols-phillips.com >>> hostname(0) laptop-56 >>> hostname(2) web-12.williamson-hopkins.jackson.com
def hostname(self, levels=1): """ Produce a hostname with specified number of subdomain levels. >>> hostname() db-01.nichols-phillips.com >>> hostname(0) laptop-56 >>> hostname(2) web-12.williamson-hopkins.jackson.com """ if levels < 1: ...
Produce an Internet domain name with the specified number of subdomain levels. >>> domain_name() nichols-phillips.com >>> domain_name(2) williamson-hopkins.jackson.com
def domain_name(self, levels=1): """ Produce an Internet domain name with the specified number of subdomain levels. >>> domain_name() nichols-phillips.com >>> domain_name(2) williamson-hopkins.jackson.com """ if levels < 1: raise Value...
:param schemes: a list of strings to use as schemes, one will chosen randomly. If None, it will generate http and https urls. Passing an empty list will result in schemeless url generation like "://domain.com". :returns: a random url string.
def url(self, schemes=None): """ :param schemes: a list of strings to use as schemes, one will chosen randomly. If None, it will generate http and https urls. Passing an empty list will result in schemeless url generation like "://domain.com". :returns: a random url string. ...
Produces a random IPv4 address or network with a valid CIDR from within a given subnet. :param subnet: IPv4Network to choose from within :param network: Return a network address, and not an IP address
def _random_ipv4_address_from_subnet(self, subnet, network=False): """ Produces a random IPv4 address or network with a valid CIDR from within a given subnet. :param subnet: IPv4Network to choose from within :param network: Return a network address, and not an IP address ...
Exclude the list of networks from another list of networks and return a flat list of new networks. :param networks: List of IPv4 networks to exclude from :param networks_to_exclude: List of IPv4 networks to exclude :returns: Flat list of IPv4 networks
def _exclude_ipv4_networks(self, networks, networks_to_exclude): """ Exclude the list of networks from another list of networks and return a flat list of new networks. :param networks: List of IPv4 networks to exclude from :param networks_to_exclude: List of IPv4 networks to exc...
Produce a random IPv4 address or network with a valid CIDR. :param network: Network address :param address_class: IPv4 address class (a, b, or c) :param private: Public or private :returns: IPv4
def ipv4(self, network=False, address_class=None, private=None): """ Produce a random IPv4 address or network with a valid CIDR. :param network: Network address :param address_class: IPv4 address class (a, b, or c) :param private: Public or private :returns: IPv4 ...
Returns a private IPv4. :param network: Network address :param address_class: IPv4 address class (a, b, or c) :returns: Private IPv4
def ipv4_private(self, network=False, address_class=None): """ Returns a private IPv4. :param network: Network address :param address_class: IPv4 address class (a, b, or c) :returns: Private IPv4 """ # compute private networks from given class supernet = ...
Returns a public IPv4 excluding private blocks. :param network: Network address :param address_class: IPv4 address class (a, b, or c) :returns: Public IPv4
def ipv4_public(self, network=False, address_class=None): """ Returns a public IPv4 excluding private blocks. :param network: Network address :param address_class: IPv4 address class (a, b, or c) :returns: Public IPv4 """ # compute public networks public_...
Produce a random IPv6 address or network with a valid CIDR
def ipv6(self, network=False): """Produce a random IPv6 address or network with a valid CIDR""" address = str(ip_address(self.generator.random.randint( 2 ** IPV4LENGTH, (2 ** IPV6LENGTH) - 1))) if network: address += '/' + str(self.generator.random.randint(0, IPV6LENGTH))...
Returns URL to placeholder image Example: http://placehold.it/640x480
def image_url(self, width=None, height=None): """ Returns URL to placeholder image Example: http://placehold.it/640x480 """ width_ = width or self.random_int(max=1024) height_ = height or self.random_int(max=1024) placeholder_url = self.random_element(self.image_p...
Calls random.seed
def seed_instance(self, seed=None): """Calls random.seed""" if self.__random == random: # create per-instance random obj when first time seed_instance() is # called self.__random = random_module.Random() self.__random.seed(seed) return self
This is a secure way to make a fake from another Provider.
def format(self, formatter, *args, **kwargs): """ This is a secure way to make a fake from another Provider. """ # TODO: data export? return self.get_formatter(formatter)(*args, **kwargs)
Perform a forward execution and perform alias analysis. Note that this analysis is fast, light-weight, and by no means complete. For instance, most arithmetic operations are not supported. - Depending on user settings, stack pointer and stack base pointer will be mocked and propagated to individual ...
def _alias_analysis(self, mock_sp=True, mock_bp=True): """ Perform a forward execution and perform alias analysis. Note that this analysis is fast, light-weight, and by no means complete. For instance, most arithmetic operations are not supported. - Depending on user settings, stack poi...
Slice it!
def _slice(self): """ Slice it! """ regs = set(self._target_regs) tmps = set(self._target_tmps) stack_offsets = set(self._target_stack_offsets) state = SimLightState(regs=regs, temps=tmps, stack_offsets=stack_offsets) for stmt_idx, stmt in reversed(list...
Prepare the address space with the data necessary to perform relocations pointing to the given symbol. Returns a 2-tuple. The first item is the address of the function code, the second is the address of the relocation target.
def prepare_function_symbol(self, symbol_name, basic_addr=None): """ Prepare the address space with the data necessary to perform relocations pointing to the given symbol. Returns a 2-tuple. The first item is the address of the function code, the second is the address of the relocation ...
Create a GDT in the state memory and populate the segment registers. Rehook the vsyscall address using the real value in the concrete process memory :param state: state which will be modified :param concrete_target: concrete target that will be used to read the fs register ...
def initialize_gdt_x86(self,state,concrete_target): """ Create a GDT in the state memory and populate the segment registers. Rehook the vsyscall address using the real value in the concrete process memory :param state: state which will be modified :param concrete_t...
Set the fs register in the angr to the value of the fs register in the concrete process :param state: state which will be modified :param concrete_target: concrete target that will be used to read the fs register :return: None
def initialize_segment_register_x64(self, state, concrete_target): """ Set the fs register in the angr to the value of the fs register in the concrete process :param state: state which will be modified :param concrete_target: concrete target that will be used to read t...
Merges this node with the other, returning a new node that spans the both.
def merge(self, other): """ Merges this node with the other, returning a new node that spans the both. """ new_node = self.copy() new_node.size += other.size new_node.instruction_addrs += other.instruction_addrs # FIXME: byte_string should never be none, but it is...
Allocates a new array in memory and returns the reference to the base.
def new_array(state, element_type, size): """ Allocates a new array in memory and returns the reference to the base. """ size_bounded = SimSootExpr_NewArray._bound_array_size(state, size) # return the reference of the array base # => elements getting lazy initialized in t...
Convert recovered reaching conditions from claripy ASTs to ailment Expressions :return: None
def _convert_claripy_bool_ast(self, cond): """ Convert recovered reaching conditions from claripy ASTs to ailment Expressions :return: None """ if isinstance(cond, ailment.Expr.Expression): return cond if cond.op == "BoolS" and claripy.is_true(cond): ...
Extract goto targets from a Jump or a ConditionalJump statement. :param stmt: The statement to analyze. :return: A list of known concrete jump targets. :rtype: list
def _extract_jump_targets(stmt): """ Extract goto targets from a Jump or a ConditionalJump statement. :param stmt: The statement to analyze. :return: A list of known concrete jump targets. :rtype: list """ targets = [ ] # FIXME: We are...
A somewhat faithful implementation of libc `malloc`. :param sim_size: the amount of memory (in bytes) to be allocated :returns: the address of the allocation, or a NULL pointer if the allocation failed
def malloc(self, sim_size): """ A somewhat faithful implementation of libc `malloc`. :param sim_size: the amount of memory (in bytes) to be allocated :returns: the address of the allocation, or a NULL pointer if the allocation failed """ raise NotImplementedError(...
A somewhat faithful implementation of libc `free`. :param ptr: the location in memory to be freed
def free(self, ptr): #pylint:disable=unused-argument """ A somewhat faithful implementation of libc `free`. :param ptr: the location in memory to be freed """ raise NotImplementedError("%s not implemented for %s" % (self.free.__func__.__name__, ...
A somewhat faithful implementation of libc `calloc`. :param sim_nmemb: the number of elements to allocated :param sim_size: the size of each element (in bytes) :returns: the address of the allocation, or a NULL pointer if the allocation failed
def calloc(self, sim_nmemb, sim_size): """ A somewhat faithful implementation of libc `calloc`. :param sim_nmemb: the number of elements to allocated :param sim_size: the size of each element (in bytes) :returns: the address of the allocation, or a NULL pointer if the a...
A somewhat faithful implementation of libc `realloc`. :param ptr: the location in memory to be reallocated :param size: the new size desired for the allocation :returns: the address of the allocation, or a NULL pointer if the allocation was freed or if no new allocation ...
def realloc(self, ptr, size): """ A somewhat faithful implementation of libc `realloc`. :param ptr: the location in memory to be reallocated :param size: the new size desired for the allocation :returns: the address of the allocation, or a NULL pointer if the allocation was ...
Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command : ``dump binary memory [stack_dump] [begin_addr] [end_addr]`` We set the stack to the same addresses as the gdb session to avoid pointers corruption. :param stack_dump: The dump file. :param stac...
def set_stack(self, stack_dump, stack_top): """ Stack dump is a dump of the stack from gdb, i.e. the result of the following gdb command : ``dump binary memory [stack_dump] [begin_addr] [end_addr]`` We set the stack to the same addresses as the gdb session to avoid pointers corruption....
Heap dump is a dump of the heap from gdb, i.e. the result of the following gdb command: ``dump binary memory [stack_dump] [begin] [end]`` :param heap_dump: The dump file. :param heap_base: The start address of the heap in the gdb session.
def set_heap(self, heap_dump, heap_base): """ Heap dump is a dump of the heap from gdb, i.e. the result of the following gdb command: ``dump binary memory [stack_dump] [begin] [end]`` :param heap_dump: The dump file. :param heap_base: The start address of the heap i...
Update any data range (most likely use is the data segments of loaded objects)
def set_data(self, addr, data_dump): """ Update any data range (most likely use is the data segments of loaded objects) """ data = self._read_data(data_dump) l.info("Set data from 0x%x to %#x", addr, addr+len(data)) self._write(addr, data)
Initialize register values within the state :param regs_dump: The output of ``info registers`` in gdb.
def set_regs(self, regs_dump): """ Initialize register values within the state :param regs_dump: The output of ``info registers`` in gdb. """ if self.real_stack_top == 0 and self.adjust_stack is True: raise SimStateError("You need to set the stack first, or set" ...
Adjust bp and sp w.r.t. stack difference between GDB session and angr. This matches sp and bp registers, but there is a high risk of pointers inconsistencies.
def _adjust_regs(self): """ Adjust bp and sp w.r.t. stack difference between GDB session and angr. This matches sp and bp registers, but there is a high risk of pointers inconsistencies. """ if not self.adjust_stack: return bp = self.state.arch.register_names...
Create a Loop object for a strongly connected graph, and any strongly connected subgraphs, if possible. :param subg: A strongly connected subgraph. :param bigg: The graph which subg is a subgraph of. :return: A list of Loop objects, some of which may be inside others, ...
def _parse_loop_graph(self, subg, bigg): """ Create a Loop object for a strongly connected graph, and any strongly connected subgraphs, if possible. :param subg: A strongly connected subgraph. :param bigg: The graph which subg is a subgraph of. :return: A l...
Return all Loop instances that can be extracted from a graph. :param graph: The graph to analyze. :return: A list of all the Loop instances that were found in the graph.
def _parse_loops_from_graph(self, graph): """ Return all Loop instances that can be extracted from a graph. :param graph: The graph to analyze. :return: A list of all the Loop instances that were found in the graph. """ outtop = [] outall = [] f...
Resolve the field within the given state.
def get_ref(cls, state, obj_alloc_id, field_class_name, field_name, field_type): """ Resolve the field within the given state. """ # resolve field field_class = state.javavm_classloader.get_class(field_class_name) field_id = resolve_field(state, field_class, field_name, f...
:param vector_a: A list of numbers. :param vector_b: A list of numbers. :returns: The euclidean distance between the two vectors.
def _euclidean_dist(vector_a, vector_b): """ :param vector_a: A list of numbers. :param vector_b: A list of numbers. :returns: The euclidean distance between the two vectors. """ dist = 0 for (x, y) in zip(vector_a, vector_b): dist += (x-y)*(x-y) return math.sqrt(...
:param input_attributes: First dictionary of objects to attribute tuples. :param target_attributes: Second dictionary of blocks to attribute tuples. :returns: A dictionary of objects in the input_attributes to the closest objects in the target_attributes.
def _get_closest_matches(input_attributes, target_attributes): """ :param input_attributes: First dictionary of objects to attribute tuples. :param target_attributes: Second dictionary of blocks to attribute tuples. :returns: A dictionary of objects in the input_attributes to the ...
:param s1: A list or string :param s2: Another list or string :returns: The levenshtein distance between the two
def _levenshtein_distance(s1, s2): """ :param s1: A list or string :param s2: Another list or string :returns: The levenshtein distance between the two """ if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for index2, num2 in enumerate(s2): new_dis...
This function calculates the levenshtein distance but allows for elements in the lists to be different by any number in the set acceptable_differences. :param s1: A list. :param s2: Another list. :param acceptable_differences: A set of numbers. If (s2[i]-s1[i]...
def _normalized_levenshtein_distance(s1, s2, acceptable_differences): """ This function calculates the levenshtein distance but allows for elements in the lists to be different by any number in the set acceptable_differences. :param s1: A list. :param s2: A...
:param x: The first element of a possible match. :param y: The second element of a possible match. :param matched_a: The current matches for the first set. :param matched_b: The current matches for the second set. :param attributes_dict_a: The at...
def _is_better_match(x, y, matched_a, matched_b, attributes_dict_a, attributes_dict_b): """ :param x: The first element of a possible match. :param y: The second element of a possible match. :param matched_a: The current matches for the first set. :param...
Compares two basic blocks and finds all the constants that differ from the first block to the second. :param block_a: The first block to compare. :param block_b: The second block to compare. :returns: Returns a list of differing constants in the form of ConstantChange, which has the offset in the ...
def differing_constants(block_a, block_b): """ Compares two basic blocks and finds all the constants that differ from the first block to the second. :param block_a: The first block to compare. :param block_b: The second block to compare. :returns: Returns a list of differing constants in the ...
:returns: Whether or not these two functions are identical.
def probably_identical(self): """ :returns: Whether or not these two functions are identical. """ if len(self._unmatched_blocks_from_a | self._unmatched_blocks_from_b) > 0: return False for (a, b) in self._block_matches: if not self.blocks_probably_identic...
:returns: A list of block matches which appear to be identical
def identical_blocks(self): """ :returns: A list of block matches which appear to be identical """ identical_blocks = [] for (block_a, block_b) in self._block_matches: if self.blocks_probably_identical(block_a, block_b): identical_blocks.append((block_...
:returns: A list of block matches which appear to differ
def differing_blocks(self): """ :returns: A list of block matches which appear to differ """ differing_blocks = [] for (block_a, block_b) in self._block_matches: if not self.blocks_probably_identical(block_a, block_b): differing_blocks.append((block_a,...
:return: A list of block matches which appear to differ
def blocks_with_differing_constants(self): """ :return: A list of block matches which appear to differ """ differing_blocks = [] diffs = dict() for (block_a, block_b) in self._block_matches: if self.blocks_probably_identical(block_a, block_b) and \ ...
:param block_a: The first block address. :param block_b: The second block address. :returns: The similarity of the basic blocks, normalized for the base address of the block and function call addresses.
def block_similarity(self, block_a, block_b): """ :param block_a: The first block address. :param block_b: The second block address. :returns: The similarity of the basic blocks, normalized for the base address of the block and function call addresses. ...
:param block_a: The first block address. :param block_b: The second block address. :param check_constants: Whether or not to require matching constants in blocks. :returns: Whether or not the blocks appear to be identical.
def blocks_probably_identical(self, block_a, block_b, check_constants=False): """ :param block_a: The first block address. :param block_b: The second block address. :param check_constants: Whether or not to require matching constants in blocks. :returns: ...
:param function: A normalized function object. :returns: A dictionary of basic block addresses to tuples of attributes.
def _compute_block_attributes(function): """ :param function: A normalized function object. :returns: A dictionary of basic block addresses to tuples of attributes. """ # The attributes we use are the distance form function start, distance from function exit and whet...
:param function: A normalized Function object. :returns: A dictionary of basic block addresses and their distance to the exit of the function.
def _distances_from_function_exit(function): """ :param function: A normalized Function object. :returns: A dictionary of basic block addresses and their distance to the exit of the function. """ reverse_graph = function.graph.reverse() # we aren't guaranteed...
Computes the diff of the functions and saves the result.
def _compute_diff(self): """ Computes the diff of the functions and saves the result. """ # get the attributes for all blocks l.debug("Computing diff of functions: %s, %s", ("%#x" % self._function_a.startpoint.addr) if self._function_a.startpoint is not None else ...
:param attributes_a: A dict of blocks to their attributes :param attributes_b: A dict of blocks to their attributes The following parameters are optional. :param filter_set_a: A set to limit attributes_a to the blocks in this set. :param filter_set_b: A set to limit attribu...
def _get_block_matches(self, attributes_a, attributes_b, filter_set_a=None, filter_set_b=None, delta=(0, 0, 0), tiebreak_with_block_similarity=False): """ :param attributes_a: A dict of blocks to their attributes :param attributes_b: A dict of blocks to their att...
Compare two functions and return True if they appear identical. :param func_a_addr: The address of the first function (in the first binary). :param func_b_addr: The address of the second function (in the second binary). :returns: Whether or not the functions appear to be identical.
def functions_probably_identical(self, func_a_addr, func_b_addr, check_consts=False): """ Compare two functions and return True if they appear identical. :param func_a_addr: The address of the first function (in the first binary). :param func_b_addr: The address of the second function (...
:returns: A list of function matches that appear to be identical
def identical_functions(self): """ :returns: A list of function matches that appear to be identical """ identical_funcs = [] for (func_a, func_b) in self.function_matches: if self.functions_probably_identical(func_a, func_b): identical_funcs.append((fu...
:returns: A list of function matches that appear to differ
def differing_functions(self): """ :returns: A list of function matches that appear to differ """ different_funcs = [] for (func_a, func_b) in self.function_matches: if not self.functions_probably_identical(func_a, func_b): different_funcs.append((func...
:return: A list of function matches that appear to differ including just by constants
def differing_functions_with_consts(self): """ :return: A list of function matches that appear to differ including just by constants """ different_funcs = [] for (func_a, func_b) in self.function_matches: if not self.functions_probably_identical(func_a, func_b, check_...
:returns: A list of block matches that appear to differ
def differing_blocks(self): """ :returns: A list of block matches that appear to differ """ differing_blocks = [] for (func_a, func_b) in self.function_matches: differing_blocks.extend(self.get_function_diff(func_a, func_b).differing_blocks) return differing_b...
:return A list of all block matches that appear to be identical
def identical_blocks(self): """ :return A list of all block matches that appear to be identical """ identical_blocks = [] for (func_a, func_b) in self.function_matches: identical_blocks.extend(self.get_function_diff(func_a, func_b).identical_blocks) return ide...
:return: A dict of block matches with differing constants to the tuple of constants
def blocks_with_differing_constants(self): """ :return: A dict of block matches with differing constants to the tuple of constants """ diffs = dict() for (func_a, func_b) in self.function_matches: diffs.update(self.get_function_diff(func_a, func_b).blocks_with_differi...
:param function_addr_a: The address of the first function (in the first binary) :param function_addr_b: The address of the second function (in the second binary) :returns: the FunctionDiff of the two functions
def get_function_diff(self, function_addr_a, function_addr_b): """ :param function_addr_a: The address of the first function (in the first binary) :param function_addr_b: The address of the second function (in the second binary) :returns: the FunctionDiff of the two functions """...
:param cfg: An angr CFG object :returns: a dictionary of function addresses to tuples of attributes
def _compute_function_attributes(cfg): """ :param cfg: An angr CFG object :returns: a dictionary of function addresses to tuples of attributes """ # the attributes we use are the number of basic blocks, number of edges, and number of subfunction calls attributes = dict...
:param attributes_a: A dict of functions to their attributes :param attributes_b: A dict of functions to their attributes The following parameters are optional. :param filter_set_a: A set to limit attributes_a to the functions in this set. :param filter_set_b: A set to limi...
def _get_function_matches(attributes_a, attributes_b, filter_set_a=None, filter_set_b=None): """ :param attributes_a: A dict of functions to their attributes :param attributes_b: A dict of functions to their attributes The following parameters are optional. :param filter_...
Load a new project based on a string of raw bytecode. :param shellcode: The data to load :param arch: The name of the arch to use, or an archinfo class :param start_offset: The offset into the data to start analysis (default 0) :param load_address: The address to place the data i...
def load_shellcode(shellcode, arch, start_offset=0, load_address=0): """ Load a new project based on a string of raw bytecode. :param shellcode: The data to load :param arch: The name of the arch to use, or an archinfo class :param start_offset: The offset into the data to start...
This scans through an objects imports and hooks them with simprocedures from our library whenever possible
def _register_object(self, obj, sim_proc_arch): """ This scans through an objects imports and hooks them with simprocedures from our library whenever possible """ # Step 1: get the set of libraries we are allowed to use to resolve unresolved symbols missing_libs = [] for...
Does symbol name `f` exist as a SIM_PROCEDURE? If so, return it, else return None. Narrows down the set of libraries to search based on hint. Part of the hack to enable Binary Ninja support. Remove if _register_objects() stops using it.
def _guess_simprocedure(self, f, hint): """ Does symbol name `f` exist as a SIM_PROCEDURE? If so, return it, else return None. Narrows down the set of libraries to search based on hint. Part of the hack to enable Binary Ninja support. Remove if _register_objects() stops using it. ...
Has symbol name `f` been marked for exclusion by any of the user parameters?
def _check_user_blacklists(self, f): """ Has symbol name `f` been marked for exclusion by any of the user parameters? """ return not self._should_use_sim_procedures or \ f in self._exclude_sim_procedures_list or \ f in self._ignore_functions or \ ...
Hook a section of code with a custom function. This is used internally to provide symbolic summaries of library functions, and can be used to instrument execution or to modify control flow. When hook is not specified, it returns a function decorator that allows easy hooking. Usage:: ...
def hook(self, addr, hook=None, length=0, kwargs=None, replace=False): """ Hook a section of code with a custom function. This is used internally to provide symbolic summaries of library functions, and can be used to instrument execution or to modify control flow. When hook is n...
Returns the current hook for `addr`. :param addr: An address. :returns: None if the address is not hooked.
def hooked_by(self, addr): """ Returns the current hook for `addr`. :param addr: An address. :returns: None if the address is not hooked. """ if not self.is_hooked(addr): l.warning("Address %s is not hooked", self._addr_to_str(addr)) return N...
Remove a hook. :param addr: The address of the hook.
def unhook(self, addr): """ Remove a hook. :param addr: The address of the hook. """ if not self.is_hooked(addr): l.warning("Address %s not hooked", self._addr_to_str(addr)) return del self._sim_procedures[addr]
Resolve a dependency in a binary. Looks up the address of the given symbol, and then hooks that address. If the symbol was not available in the loaded libraries, this address may be provided by the CLE externs object. Additionally, if instead of a symbol name you provide an address, some secret...
def hook_symbol(self, symbol_name, simproc, kwargs=None, replace=None): """ Resolve a dependency in a binary. Looks up the address of the given symbol, and then hooks that address. If the symbol was not available in the loaded libraries, this address may be provided by the CLE externs ob...
Check if a symbol is already hooked. :param str symbol_name: Name of the symbol. :return: True if the symbol can be resolved and is hooked, False otherwise. :rtype: bool
def is_symbol_hooked(self, symbol_name): """ Check if a symbol is already hooked. :param str symbol_name: Name of the symbol. :return: True if the symbol can be resolved and is hooked, False otherwise. :rtype: bool """ sym = self.loader.find_symbol(symbol_name) ...
Remove the hook on a symbol. This function will fail if the symbol is provided by the extern object, as that would result in a state where analysis would be unable to cope with a call to this symbol.
def unhook_symbol(self, symbol_name): """ Remove the hook on a symbol. This function will fail if the symbol is provided by the extern object, as that would result in a state where analysis would be unable to cope with a call to this symbol. """ sym = self.loader.find_sym...
Move the hook for a symbol to a specific address :param new_address: the new address that will trigger the SimProc execution :param symbol_name: the name of the symbol (f.i. strcmp ) :return: None
def rehook_symbol(self, new_address, symbol_name): """ Move the hook for a symbol to a specific address :param new_address: the new address that will trigger the SimProc execution :param symbol_name: the name of the symbol (f.i. strcmp ) :return: None """ new_sim_...
This function is a symbolic execution helper in the simple style supported by triton and manticore. It designed to be run after setting up hooks (see Project.hook), in which the symbolic state can be checked. This function can be run in three different ways: - When run with...
def execute(self, *args, **kwargs): """ This function is a symbolic execution helper in the simple style supported by triton and manticore. It designed to be run after setting up hooks (see Project.hook), in which the symbolic state can be checked. This function can be r...
Return a function decorator that allows easy hooking. Please refer to hook() for its usage. :return: The function decorator.
def _hook_decorator(self, addr, length=0, kwargs=None): """ Return a function decorator that allows easy hooking. Please refer to hook() for its usage. :return: The function decorator. """ def hook_decorator(func): self.hook(addr, func, length=length, kwargs=kwargs)...
Indicates if the project's main binary is a Java Archive.
def is_java_project(self): """ Indicates if the project's main binary is a Java Archive. """ if self._is_java_project is None: self._is_java_project = isinstance(self.arch, ArchSoot) return self._is_java_project
Indicates if the project's main binary is a Java Archive, which interacts during its execution with native libraries (via JNI).
def is_java_jni_project(self): """ Indicates if the project's main binary is a Java Archive, which interacts during its execution with native libraries (via JNI). """ if self._is_java_jni_project is None: self._is_java_jni_project = isinstance(self.arch, ArchSoot) and...
Register a preset instance with the class of the hub it corresponds to. This allows individual plugin objects to automatically register themselves with a preset by using a classmethod of their own with only the name of the preset to register with.
def register_preset(cls, name, preset): """ Register a preset instance with the class of the hub it corresponds to. This allows individual plugin objects to automatically register themselves with a preset by using a classmethod of their own with only the name of the preset to register wi...
Apply a preset to the hub. If there was a previously active preset, discard it. Preset can be either the string name of a preset or a PluginPreset instance.
def use_plugin_preset(self, preset): """ Apply a preset to the hub. If there was a previously active preset, discard it. Preset can be either the string name of a preset or a PluginPreset instance. """ if isinstance(preset, str): try: preset = self._p...
Discard the current active preset. Will release any active plugins that could have come from the old preset.
def discard_plugin_preset(self): """ Discard the current active preset. Will release any active plugins that could have come from the old preset. """ if self.has_plugin_preset: for name, plugin in list(self._active_plugins.items()): if id(plugin) in self._prov...
Get the plugin named ``name``. If no such plugin is currently active, try to activate a new one using the current preset.
def get_plugin(self, name): """ Get the plugin named ``name``. If no such plugin is currently active, try to activate a new one using the current preset. """ if name in self._active_plugins: return self._active_plugins[name] elif self.has_plugin_preset: ...
Add a new plugin ``plugin`` with name ``name`` to the active plugins.
def register_plugin(self, name, plugin): """ Add a new plugin ``plugin`` with name ``name`` to the active plugins. """ if self.has_plugin(name): self.release_plugin(name) self._active_plugins[name] = plugin setattr(self, name, plugin) return plugin
Deactivate and remove the plugin with name ``name``.
def release_plugin(self, name): """ Deactivate and remove the plugin with name ``name``. """ plugin = self._active_plugins[name] if id(plugin) in self._provided_by_preset: self._provided_by_preset.remove(id(plugin)) del self._active_plugins[name] dela...
Return a copy of self.
def copy(self): """ Return a copy of self. """ cls = self.__class__ result = cls.__new__(cls) result._default_plugins = dict(self._default_plugins) # pylint:disable=protected-access return result
Grabs the concretized result so we can add the constraint ourselves.
def _grab_concretization_results(cls, state): """ Grabs the concretized result so we can add the constraint ourselves. """ # only grab ones that match the constrained addrs if cls._should_add_constraints(state): addr = state.inspect.address_concretization_expr ...
Check to see if the current address concretization variable is any of the registered constrained_addrs we want to allow concretization for
def _should_add_constraints(cls, state): """ Check to see if the current address concretization variable is any of the registered constrained_addrs we want to allow concretization for """ expr = state.inspect.address_concretization_expr hit_indices = cls._to_indices(state...
The memory release primitive for this heap implementation. Decreases the position of the break to deallocate space. Guards against releasing beyond the initial heap base. :param sim_size: a size specifying how much to decrease the break pointer by (may be symbolic or not)
def release(self, sim_size): """ The memory release primitive for this heap implementation. Decreases the position of the break to deallocate space. Guards against releasing beyond the initial heap base. :param sim_size: a size specifying how much to decrease the break pointer by (may b...
The actual allocation primitive for this heap implementation. Increases the position of the break to allocate space. Has no guards against the heap growing too large. :param sim_size: a size specifying how much to increase the break pointer by :returns: a pointer to the previous break position,...
def allocate(self, sim_size): """ The actual allocation primitive for this heap implementation. Increases the position of the break to allocate space. Has no guards against the heap growing too large. :param sim_size: a size specifying how much to increase the break pointer by :...
Get the function name from a C-style function declaration string. :param str s: A C-style function declaration string. :return: The function name. :rtype: str
def get_function_name(s): """ Get the function name from a C-style function declaration string. :param str s: A C-style function declaration string. :return: The function name. :rtype: str """ s = s.strip() if s.startswith("__attribute__"): # Remove "__attribute__ ((...
Convert a C-style function declaration string to its corresponding SimTypes-based Python representation. :param str c_decl: The C-style function declaration string. :return: A tuple of the function name, the prototype, and a string representing the ...
def convert_cproto_to_py(c_decl): """ Convert a C-style function declaration string to its corresponding SimTypes-based Python representation. :param str c_decl: The C-style function declaration string. :return: A tuple of the function name, the prototype, and a stri...
Use this to set the size on a chunk. When the chunk is new (such as when a free chunk is shrunk to form an allocated chunk and a remainder free chunk) it is recommended that the is_free hint be used since setting the size depends on the chunk's freeness, and vice versa. :param size: size of the...
def set_size(self, size, is_free=None): #pylint:disable=arguments-differ """ Use this to set the size on a chunk. When the chunk is new (such as when a free chunk is shrunk to form an allocated chunk and a remainder free chunk) it is recommended that the is_free hint be used since setting the ...
Sets (or unsets) the flag controlling whether the previous chunk is free. :param is_free: if True, sets the previous chunk to be free; if False, sets it to be allocated
def set_prev_freeness(self, is_free): """ Sets (or unsets) the flag controlling whether the previous chunk is free. :param is_free: if True, sets the previous chunk to be free; if False, sets it to be allocated """ level = silence_logger() size_field = self.state.memory....
Returns a concrete state of the flag indicating whether the previous chunk is free or not. Issues a warning if that flag is symbolic and has multiple solutions, and then assumes that the previous chunk is free. :returns: True if the previous chunk is free; False otherwise
def is_prev_free(self): """ Returns a concrete state of the flag indicating whether the previous chunk is free or not. Issues a warning if that flag is symbolic and has multiple solutions, and then assumes that the previous chunk is free. :returns: True if the previous chunk is free; Fa...
Returns the size of the previous chunk, masking off what would be the flag bits if it were in the actual size field. Performs NO CHECKING to determine whether the previous chunk size is valid (for example, when the previous chunk is not free, its size cannot be determined).
def prev_size(self): """ Returns the size of the previous chunk, masking off what would be the flag bits if it were in the actual size field. Performs NO CHECKING to determine whether the previous chunk size is valid (for example, when the previous chunk is not free, its size cannot be d...
Returns the chunk immediately following (and adjacent to) this one, if it exists. :returns: The following chunk, or None if applicable
def next_chunk(self): """ Returns the chunk immediately following (and adjacent to) this one, if it exists. :returns: The following chunk, or None if applicable """ def sym_base_handler(base): l.warning("A computed chunk base is symbolic; maximizing it") ...
Returns the chunk immediately prior (and adjacent) to this one, if that chunk is free. If the prior chunk is not free, then its base cannot be located and this method raises an error. :returns: If possible, the previous chunk; otherwise, raises an error
def prev_chunk(self): """ Returns the chunk immediately prior (and adjacent) to this one, if that chunk is free. If the prior chunk is not free, then its base cannot be located and this method raises an error. :returns: If possible, the previous chunk; otherwise, raises an error ...
Returns the chunk following this chunk in the list of free chunks. If this chunk is not free, then it resides in no such list and this method raises an error. :returns: If possible, the forward chunk; otherwise, raises an error
def fwd_chunk(self): """ Returns the chunk following this chunk in the list of free chunks. If this chunk is not free, then it resides in no such list and this method raises an error. :returns: If possible, the forward chunk; otherwise, raises an error """ if self.is_fre...
Given a pointer to a user payload, return the base of the chunk associated with that payload (i.e. the chunk pointer). Returns None if ptr is null. :param ptr: a pointer to the base of a user payload in the heap :returns: a pointer to the base of the associated heap chunk, or None if ptr is nul...
def chunk_from_mem(self, ptr): """ Given a pointer to a user payload, return the base of the chunk associated with that payload (i.e. the chunk pointer). Returns None if ptr is null. :param ptr: a pointer to the base of a user payload in the heap :returns: a pointer to the base ...
Simply finds the free chunk that would be the backwards chunk relative to the chunk at ptr. Hence, the free head and all other metadata are unaltered by this function.
def _find_bck(self, chunk): """ Simply finds the free chunk that would be the backwards chunk relative to the chunk at ptr. Hence, the free head and all other metadata are unaltered by this function. """ cur = self.free_head_chunk if cur is None: return None ...
Sets the freedom of the final chunk. Since no proper chunk follows the final chunk, the heap itself manages this. Nonetheless, for now it is implemented as if an additional chunk followed the final chunk.
def _set_final_freeness(self, flag): """ Sets the freedom of the final chunk. Since no proper chunk follows the final chunk, the heap itself manages this. Nonetheless, for now it is implemented as if an additional chunk followed the final chunk. """ if flag: self.stat...
Takes an allocation size as requested by the user and modifies it to be a suitable chunk size.
def _make_chunk_size(self, req_size): """ Takes an allocation size as requested by the user and modifies it to be a suitable chunk size. """ size = req_size size += 2 * self._chunk_size_t_size # Two size fields size = self._chunk_min_size if size < self._chunk_min_size e...
Allocate and initialize a new string in the context of the state passed. The method returns the reference to the newly allocated string :param state: angr state where we want to allocate the string :type SimState :param value: value of the string to initialize :type claripy.Str...
def new_string(state, value): """ Allocate and initialize a new string in the context of the state passed. The method returns the reference to the newly allocated string :param state: angr state where we want to allocate the string :type SimState :param value: value of ...