desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Primitive that contains static content. @type value: Raw @param value: Raw static data @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive'
def __init__(self, value, name=None):
self.value = self.original_value = value self.name = name self.fuzzable = False self.mutant_index = 0 self.s_type = 'static' self.rendered = '' self.fuzz_complete = True
'Do nothing. @rtype: False @return: False'
def mutate(self):
return False
'Return 0. @rtype: 0 @return: 0'
def num_mutations(self):
return 0
'Primitive that cycles through a library of "bad" strings. The class variable \'fuzz_library\' contains a list of smart fuzz values global across all instances. The \'this_library\' variable contains fuzz values specific to the instantiated primitive. This allows us to avoid copying the near ~70MB fuzz_library data str...
def __init__(self, value, size=(-1), padding='\x00', encoding='ascii', fuzzable=True, max_len=0, name=None):
self.value = self.original_value = value self.size = size self.padding = padding self.encoding = encoding self.fuzzable = fuzzable self.name = name self.s_type = 'string' self.rendered = '' self.fuzz_complete = False self.mutant_index = 0 self.this_library = [(self.value * 2)...
'Given a sequence, generate a number of selectively chosen strings lengths of the given sequence and add to the string heuristic library. @type sequence: String @param sequence: Sequence to repeat for creation of fuzz strings.'
def add_long_strings(self, sequence):
for length in [128, 255, 256, 257, 511, 512, 513, 1023, 1024, 2048, 2049, 4095, 4096, 4097, 5000, 10000, 20000, 32762, 32763, 32764, 32765, 32766, 32767, 32768, 32769, (65535 - 2), (65535 - 1), 65535, (65535 + 1), (65535 + 2), 99999, 100000, 500000, 1000000]: long_string = (sequence * length) string...
'Mutate the primitive by stepping through the fuzz library extended with the "this" library, return False on completion. @rtype: Boolean @return: True on success, False otherwise.'
def mutate(self):
while 1: if (self.mutant_index == self.num_mutations()): self.fuzz_complete = True if ((not self.fuzzable) or self.fuzz_complete): self.value = self.original_value return False self.value = (self.fuzz_library + self.this_library)[self.mutant_index] ...
'Calculate and return the total number of mutations for this individual primitive. @rtype: Integer @return: Number of mutated forms this primitive can take'
def num_mutations(self):
return (len(self.fuzz_library) + len(self.this_library))
'Render the primitive, encode the string according to the specified encoding.'
def render(self):
try: self.rendered = str(self.value).encode(self.encoding) except: self.rendered = self.value return self.rendered
'The bit field primitive represents a number of variable length and is used to define all other integer types. @type value: Integer @param value: Default integer value @type width: Integer @param width: Width of bit fields @type endian: Character @param endian: (Optional, def=LITTLE_ENDIA...
def __init__(self, value, width, max_num=None, endian='<', format='binary', signed=False, full_range=False, fuzzable=True, name=None):
assert ((type(width) is int) or (type(value) is long)) if (type(value) in [int, long, list, tuple]): self.value = self.original_value = value else: raise ValueError('The supplied value must be either an Int, Long, List or Tuple.') self.width = width s...
'Add the supplied integer and border cases to the integer fuzz heuristics library. @type integer: Int @param integer: Integer to append to fuzz heuristics'
def add_integer_boundaries(self, integer):
for i in xrange((-10), 10): case = (integer + i) if (0 <= case < self.max_num): if (case not in self.fuzz_library): self.fuzz_library.append(case)
'Render the primitive.'
def render(self):
if (self.format == 'binary'): bit_stream = '' rendered = '' if ((self.width % 8) == 0): bit_stream += self.to_binary() else: bit_stream = ('0' * (8 - (self.width % 8))) bit_stream += self.to_binary() for i in xrange((len(bit_stream) / 8)): ...
'Convert a number to a binary string. @type number: Integer @param number: (Optional, def=self.value) Number to convert @type bit_count: Integer @param bit_count: (Optional, def=self.width) Width of bit string @rtype: String @return: Bit string'
def to_binary(self, number=None, bit_count=None):
if (number == None): if (type(self.value) in [list, tuple]): if (self.cyclic_index == len(self.value)): self.cyclic_index = 0 number = self.value[self.cyclic_index] self.cyclic_index += 1 else: number = self.value if (bit_count == N...
'Convert a binary string to a decimal number. @type binary: String @param binary: Binary string @rtype: Integer @return: Converted bit string'
def to_decimal(self, binary):
return int(binary, 2)
'@type host: String @param host: Hostname or IP address of target system @type port: Integer @param port: Port of target service'
def __init__(self, host, port, **kwargs):
self.host = host self.port = port self.netmon = None self.procmon = None self.vmcontrol = None self.netmon_options = {} self.procmon_options = {} self.vmcontrol_options = {}
'Pass specified target parameters to the PED-RPC server.'
def pedrpc_connect(self):
if self.procmon: while 1: try: if self.procmon.alive(): break except: pass time.sleep(1) for key in self.procmon_options.keys(): eval(('self.procmon.set_%s(self.procmon_options["%s"])' % (key, key))) ...
'Extends pgraph.edge with a callback option. This allows us to register a function to call between node transmissions to implement functionality such as challenge response systems. The callback method must follow this prototype:: def callback(session, node, edge, sock) Where node is the node about to be sent, edge is t...
def __init__(self, src, dst, callback=None):
pgraph.edge.edge.__init__(self, src, dst) self.callback = callback
'Extends pgraph.graph and provides a container for architecting protocol dialogs. @type session_filename: String @kwarg session_filename: (Optional, def=None) Filename to serialize persistant data to @type skip: Integer @kwarg skip: (Optional, def=0) Number of test cases to skip @type ...
def __init__(self, session_filename=None, skip=0, sleep_time=1.0, log_level=logging.INFO, logfile=None, logfile_level=logging.DEBUG, proto='tcp', bind=None, restart_interval=0, timeout=5.0, web_port=26000, crash_threshold=3, restart_sleep_time=300):
pgraph.graph.__init__(self) self.session_filename = session_filename self.skip = skip self.sleep_time = sleep_time self.proto = proto.lower() self.bind = bind self.ssl = False self.restart_interval = restart_interval self.timeout = timeout self.web_port = web_port self.crash_...
'Add a pgraph node to the graph. We overload this routine to automatically generate and assign an ID whenever a node is added. @type node: pGRAPH Node @param node: Node to add to session graph'
def add_node(self, node):
node.number = len(self.nodes) node.id = len(self.nodes) if (not self.nodes.has_key(node.id)): self.nodes[node.id] = node return self
'Add a target to the session. Multiple targets can be added for parallel fuzzing. @type target: session.target @param target: Target to add to session'
def add_target(self, target):
target.pedrpc_connect() self.targets.append(target)
'Create a connection between the two requests (nodes) and register an optional callback to process in between transmissions of the source and destination request. Leverage this functionality to handle situations such as challenge response systems. The session class maintains a top level node that all initial requests m...
def connect(self, src, dst=None, callback=None):
if (not dst): dst = src src = self.root if (type(src) is str): src = self.find_node('name', src) if (type(dst) is str): dst = self.find_node('name', dst) if ((src != self.root) and (not self.find_node('name', src.name))): self.add_node(src) if (not self.find_n...
'Dump various object values to disk. @see: import_file()'
def export_file(self):
if (not self.session_filename): return data = {} data['session_filename'] = self.session_filename data['skip'] = self.total_mutant_index data['sleep_time'] = self.sleep_time data['restart_sleep_time'] = self.restart_sleep_time data['proto'] = self.proto data['restart_interval'] =...
'Call this routine to get the ball rolling. No arguments are necessary as they are both utilized internally during the recursive traversal of the session graph. @type this_node: request (node) @param this_node: (Optional, def=None) Current node that is being fuzzed. @type path: List @param path: (Optional, ...
def fuzz(self, this_node=None, path=[]):
if (not this_node): if (not self.targets): raise sex.SullyRuntimeError('NO TARGETS SPECIFIED IN SESSION') if (not self.edges_from(self.root.id)): raise sex.SullyRuntimeError('NO REQUESTS SPECIFIED IN SESSION') this_node = self.root try:...
'Load varous object values from disk. @see: export_file()'
def import_file(self):
try: fh = open(self.session_filename, 'rb') data = cPickle.loads(zlib.decompress(fh.read())) fh.close() except: return self.skip = data['total_mutant_index'] self.session_filename = data['session_filename'] self.sleep_time = data['sleep_time'] self.restart_sleep_t...
'Number of total mutations in the graph. The logic of this routine is identical to that of fuzz(). See fuzz() for inline comments. The member varialbe self.total_num_mutations is updated appropriately by this routine. @type this_node: request (node) @param this_node: (Optional, def=None) Current node that is being fuz...
def num_mutations(self, this_node=None, path=[]):
if (not this_node): this_node = self.root self.total_num_mutations = 0 for edge in self.edges_from(this_node.id): next_node = self.nodes[edge.dst] self.total_num_mutations += next_node.num_mutations() if (edge.src != self.root.id): path.append(edge) se...
'If thet pause flag is raised, enter an endless loop until it is lowered.'
def pause(self):
while 1: if self.pause_flag: time.sleep(1) else: break
'Poll the PED-RPC endpoints (netmon, procmon etc...) for the target. @type target: session.target @param target: Session target whose PED-RPC services we are polling'
def poll_pedrpc(self, target):
if target.netmon: bytes = target.netmon.post_send() self.logger.info(('netmon captured %d bytes for test case #%d' % (bytes, self.total_mutant_index))) self.netmon_results[self.total_mutant_index] = bytes if (target.procmon and (not target.procmon.post_send())): ...
'Overload or replace this routine to specify actions to run after to each fuzz request. The order of events is as follows:: pre_send() - req - callback ... req - callback - post_send() When fuzzing RPC for example, register this method to tear down the RPC request. @see: pre_send() @type sock: Socket @param sock: Conn...
def post_send(self, sock):
pass
'Overload or replace this routine to specify actions to run prior to each fuzz request. The order of events is as follows:: pre_send() - req - callback ... req - callback - post_send() When fuzzing RPC for example, register this method to establish the RPC bind. @see: pre_send() @type sock: Socket @param sock: Connect...
def pre_send(self, sock):
pass
'Restart the fuzz target. If a VMControl is available revert the snapshot, if a process monitor is available restart the target process. Otherwise, do nothing. @type target: session.target @param target: Target we are restarting'
def restart_target(self, target, stop_first=True):
if target.vmcontrol: self.logger.warning('restarting target virtual machine') target.vmcontrol.restart_target() elif target.procmon: self.logger.warning('restarting target process') if stop_first: target.procmon.stop_target() if (not target.proc...
'Called by fuzz() on first run (not on recursive re-entry) to initialize variables, web interface, etc...'
def server_init(self):
self.total_mutant_index = 0 self.total_num_mutations = self.num_mutations() try: import signal self.signal_module = True except: self.signal_module = False if self.signal_module: def exit_abruptly(signal, frame): 'Save current settings (just in...
'Render and transmit a node, process callbacks accordingly. @type sock: Socket @param sock: Socket to transmit node on @type node: Request (Node) @param node: Request/Node to transmit @type edge: Connection (pgraph.edge) @param edge: Edge along the current fuzz path from "node" to next node. @type targe...
def transmit(self, sock, node, edge, target):
data = None if edge.callback: data = edge.callback(self, node, edge, sock) self.logger.info(('xmitting: [%d.%d]' % (node.id, self.total_mutant_index))) if (not data): data = node.render() if (self.proto == socket.SOCK_DGRAM): MAX_UDP = 65507 if ((os.name != 'nt') a...
'This routine is called by default when a requested attribute (or method) is accessed that has no definition. Unfortunately __getattr__ only passes the requested method name and not the arguments. So we extend the functionality with a little lambda magic to the routine method_missing(). Which is actually how Ruby handl...
def __getattr__(self, method_name):
return (lambda *args, **kwargs: self.__method_missing(method_name, *args, **kwargs))
'Connect to the PED-RPC server.'
def __connect(self):
self.__disconnect() try: self.__server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__server_sock.settimeout(3.0) self.__server_sock.connect((self.__host, self.__port)) except: if (self.__retry != 5): self.__retry += 1 time.sleep(5) ...
'Ensure the socket is torn down.'
def __disconnect(self):
if (self.__server_sock != None): self.__debug('closing server socket') self.__server_sock.close() self.__server_sock = None
'See the notes for __getattr__ for related notes. This method is called, in the Ruby fashion, with the method name and arguments for any requested but undefined class method. @type method_name: String @param method_name: The name of the requested and undefined attribute (or method in our case). @type *args: Tup...
def __method_missing(self, method_name, *args, **kwargs):
if (method_name == '__nonzero__'): return 1 if method_name.startswith('__'): return self.__connect() while 1: try: self.__pickle_send((method_name, (args, kwargs))) break except: self.__connect() ret = self.__pickle_recv() self....
'This routine is used for marshaling arbitrary data from the PyDbg server. We can send pretty much anything here. For example a tuple containing integers, strings, arbitrary objects and structures. Our "protocol" is a simple length-value protocol where each datagram is prefixed by a 4-byte length of the data to be rece...
def __pickle_recv(self):
try: length = struct.unpack('<L', self.__server_sock.recv(4))[0] except: return try: received = '' while length: chunk = self.__server_sock.recv(length) received += chunk length -= len(chunk) except: sys.stderr.write('PED-RPC> ...
'This routine is used for marshaling arbitrary data to the PyDbg server. We can send pretty much anything here. For example a tuple containing integers, strings, arbitrary objects and structures. Our "protocol" is a simple length-value protocol where each datagram is prefixed by a 4-byte length of the data to be receiv...
def __pickle_send(self, data):
data = cPickle.dumps(data, protocol=2) self.__debug(('sending %d bytes' % len(data))) try: self.__server_sock.send(struct.pack('<L', len(data))) self.__server_sock.send(data) except: sys.stderr.write('PED-RPC> connection to server severed during send()\n')...
'Ensure the socket is torn down.'
def __disconnect(self):
if (self.__client_sock != None): self.__debug('closing client socket') self.__client_sock.close() self.__client_sock = None
'This routine is used for marshaling arbitrary data from the PyDbg server. We can send pretty much anything here. For example a tuple containing integers, strings, arbitrary objects and structures. Our "protocol" is a simple length-value protocol where each datagram is prefixed by a 4-byte length of the data to be rece...
def __pickle_recv(self):
try: length = struct.unpack('<L', self.__client_sock.recv(4))[0] received = '' while length: chunk = self.__client_sock.recv(length) received += chunk length -= len(chunk) except: sys.stderr.write('PED-RPC> connection client severed ...
'This routine is used for marshaling arbitrary data to the PyDbg server. We can send pretty much anything here. For example a tuple containing integers, strings, arbitrary objects and structures. Our "protocol" is a simple length-value protocol where each datagram is prefixed by a 4-byte length of the data to be receiv...
def __pickle_send(self, data):
data = cPickle.dumps(data, protocol=2) self.__debug(('sending %d bytes' % len(data))) try: self.__client_sock.send(struct.pack('<L', len(data))) self.__client_sock.send(data) except: sys.stderr.write('PED-RPC> connection to client severed during send()\n')...
'Class constructor.'
def __init__(self, id=None):
self.id = id self.nodes = []
'Add a node to the cluster. @type node: pGRAPH Node @param node: Node to add to cluster'
def add_node(self, node):
self.nodes.append(node) return self
'Remove a node from the cluster. @type node: pGRAPH Node @param node: Node to remove from cluster'
def del_node(self, node_id):
for node in self.nodes: if (node.id == node_id): self.nodes.remove(node) break return self
'Find and return the node with the specified attribute / value pair. @type attribute: String @param attribute: Attribute name we are looking for @type value: Mixed @param value: Value of attribute we are looking for @rtype: Mixed @return: Node, if attribute / value pair is matched. None otherwise.'
def find_node(self, attribute, value):
for node in self.nodes: if hasattr(node, attribute): if (getattr(node, attribute) == value): return node return None
''
def __init__(self, id=None):
self.id = id self.number = 0 self.color = 15661055 self.border_color = 15658734 self.label = '' self.shape = 'box' self.gml_width = 0.0 self.gml_height = 0.0 self.gml_pattern = '1' self.gml_stipple = 1 self.gml_line_width = 1.0 self.gml_type = 'rectangle' self.gml_wid...
'Render a node description suitable for use in a GML file using the set internal attributes. @type graph: pgraph.graph @param graph: Top level graph object containing the current node @rtype: String @return: GML node description.'
def render_node_gml(self, graph):
chunked_label = '' cursor = 0 while (cursor < len(self.label)): amount = 200 if ((cursor + amount) < len(self.label)): while ((self.label[(cursor + amount)] == '\\') or (self.label[(cursor + amount)] == '"')): amount -= 1 chunked_label += (self.label[curso...
'Render a node suitable for use in a Pydot graph using the set internal attributes. @type graph: pgraph.graph @param graph: Top level graph object containing the current node @rtype: pydot.Node @return: Pydot object representing node'
def render_node_graphviz(self, graph):
import pydot dot_node = pydot.Node(self.id) dot_node.label = ('<<font face="lucida console">%s</font>>' % self.label.rstrip('\r\n')) dot_node.label = dot_node.label.replace('\\n', '<br/>') dot_node.shape = self.shape dot_node.color = ('#%06x' % self.color) dot_node.fillcolor = ('#%06x'...
'Render a node description suitable for use in a uDraw file using the set internal attributes. @type graph: pgraph.graph @param graph: Top level graph object containing the current node @rtype: String @return: uDraw node description.'
def render_node_udraw(self, graph):
self.label = self.label.replace('\n', '\\n') if self.udraw_image: self.shape = 'image' udraw_image = ('a("IMAGE","%s"),' % self.udraw_image) else: udraw_image = '' udraw = ('l("%08x",' % self.id) udraw += 'n("",' udraw += '[' udraw += udraw_image udraw += ('a("_GO...
'Render a node update description suitable for use in a uDraw file using the set internal attributes. @rtype: String @return: uDraw node update description.'
def render_node_udraw_update(self):
self.label = self.label.replace('\n', '\\n') if self.udraw_image: self.shape = 'image' udraw_image = ('a("IMAGE","%s"),' % self.udraw_image) else: udraw_image = '' udraw = ('new_node("%08x","",' % self.id) udraw += '[' udraw += udraw_image udraw += ('a("_GO","%s"),' %...
''
def __init__(self, id=None):
self.id = id self.clusters = [] self.edges = {} self.nodes = {}
'Add a pgraph cluster to the graph. @type cluster: pGRAPH Cluster @param cluster: Cluster to add to graph'
def add_cluster(self, cluster):
self.clusters.append(cluster) return self
'Add a pgraph edge to the graph. Ensures a node exists for both the source and destination of the edge. @type edge: pGRAPH Edge @param edge: Edge to add to graph @type prevent_dups: Boolean @param prevent_dups: (Optional, Def=True) Flag controlling whether or not the addition of duplicate edges is ok'...
def add_edge(self, edge, prevent_dups=True):
if prevent_dups: if self.edges.has_key(edge.id): return self if (self.find_node('id', edge.src) and self.find_node('id', edge.dst)): self.edges[edge.id] = edge return self
'Alias of graph_cat(). Concatenate the other graph into the current one. @todo: Add support for clusters @see: graph_cat() @type other_graph: pgraph.graph @param other_graph: Graph to concatenate into this one.'
def add_graph(self, other_graph):
return self.graph_cat(other_graph)
'Add a pgraph node to the graph. Ensures a node with the same id does not already exist in the graph. @type node: pGRAPH Node @param node: Node to add to graph'
def add_node(self, node):
node.number = len(self.nodes) if (not self.nodes.has_key(node.id)): self.nodes[node.id] = node return self
'Remove a cluster from the graph. @type id: Mixed @param id: Identifier of cluster to remove from graph'
def del_cluster(self, id):
for cluster in self.clusters: if (cluster.id == id): self.clusters.remove(cluster) break return self
'Remove an edge from the graph. There are two ways to call this routine, with an edge id:: graph.del_edge(id) or by specifying the edge source and destination:: graph.del_edge(src=source, dst=destination) @type id: Mixed @param id: (Optional) Identifier of edge to remove from graph @type src: Mixed @param src: (Opt...
def del_edge(self, id=None, src=None, dst=None):
if (not id): id = ((src << 32) + dst) if self.edges.has_key(id): del self.edges[id] return self
'Alias of graph_sub(). Remove the elements shared between the current graph and other graph from the current graph. @todo: Add support for clusters @see: graph_sub() @type other_graph: pgraph.graph @param other_graph: Graph to diff/remove against'
def del_graph(self, other_graph):
return self.graph_sub(other_graph)
'Remove a node from the graph. @type node_id: Mixed @param node_id: Identifier of node to remove from graph'
def del_node(self, id):
if self.nodes.has_key(id): del self.nodes[id] return self
'Enumerate the edges from the specified node. @type id: Mixed @param id: Identifier of node to enumerate edges from @rtype: List @return: List of edges from the specified node'
def edges_from(self, id):
return [edge for edge in self.edges.values() if (edge.src == id)]
'Enumerate the edges to the specified node. @type id: Mixed @param id: Identifier of node to enumerate edges to @rtype: List @return: List of edges to the specified node'
def edges_to(self, id):
return [edge for edge in self.edges.values() if (edge.dst == id)]
'Find and return the cluster with the specified attribute / value pair. @type attribute: String @param attribute: Attribute name we are looking for @type value: Mixed @param value: Value of attribute we are looking for @rtype: Mixed @return: Cluster, if attribute / value pair is matched. None otherwise.'
def find_cluster(self, attribute, value):
for cluster in self.clusters: if hasattr(cluster, attribute): if (getattr(cluster, attribute) == value): return cluster return None
'Find and return the cluster that contains the node with the specified attribute / value pair. @type attribute: String @param attribute: Attribute name we are looking for @type value: Mixed @param value: Value of attribute we are looking for @rtype: Mixed @return: Cluster, if node with attribute / value pair...
def find_cluster_by_node(self, attribute, value):
for cluster in self.clusters: for node in cluster: if hasattr(node, attribute): if (getattr(node, attribute) == value): return cluster return None
'Find and return the edge with the specified attribute / value pair. @type attribute: String @param attribute: Attribute name we are looking for @type value: Mixed @param value: Value of attribute we are looking for @rtype: Mixed @return: Edge, if attribute / value pair is matched. None otherwise.'
def find_edge(self, attribute, value):
if ((attribute == 'id') and self.edges.has_key(value)): return self.edges[value] else: for edge in self.edges.values(): if hasattr(edge, attribute): if (getattr(edge, attribute) == value): return edge return None
'Find and return the node with the specified attribute / value pair. @type attribute: String @param attribute: Attribute name we are looking for @type value: Mixed @param value: Value of attribute we are looking for @rtype: Mixed @return: Node, if attribute / value pair is matched. None otherwise.'
def find_node(self, attribute, value):
if ((attribute == 'id') and self.nodes.has_key(value)): return self.nodes[value] else: for node in self.nodes.values(): if hasattr(node, attribute): if (getattr(node, attribute) == value): return node return None
'Concatenate the other graph into the current one. @todo: Add support for clusters @type other_graph: pgraph.graph @param other_graph: Graph to concatenate into this one.'
def graph_cat(self, other_graph):
for other_node in other_graph.nodes.values(): self.add_node(other_node) for other_edge in other_graph.edges.values(): self.add_edge(other_edge) return self
'Create a new graph, looking down, from the specified node id to the specified depth. @type from_node_id: pgraph.node @param from_node_id: Node to use as start of down graph @type max_depth: Integer @param max_depth: (Optional, Def=-1) Number of levels to include in down graph (-1 for infinite) @rtype: pgraph....
def graph_down(self, from_node_id, max_depth=(-1)):
down_graph = graph() from_node = self.find_node('id', from_node_id) if (not from_node): print ('unable to resolve node %08x' % from_node_id) raise Exception levels_to_process = [] current_depth = 1 levels_to_process.append([from_node]) for level in levels_to_proce...
'Remove all elements from the current graph that do not exist in the other graph. @todo: Add support for clusters @type other_graph: pgraph.graph @param other_graph: Graph to intersect with'
def graph_intersect(self, other_graph):
for node in self.nodes.values(): if (not other_graph.find_node('id', node.id)): self.del_node(node.id) for edge in self.edges.values(): if (not other_graph.find_edge('id', edge.id)): self.del_edge(edge.id) return self
'Create a proximity graph centered around the specified node. @type center_node_id: pgraph.node @param center_node_id: Node to use as center of proximity graph @type max_depth_up: Integer @param max_depth_up: (Optional, Def=2) Number of upward levels to include in proximity graph @type max_depth_down: Integer @p...
def graph_proximity(self, center_node_id, max_depth_up=2, max_depth_down=2):
prox_graph = self.graph_down(center_node_id, max_depth_down) prox_graph.add_graph(self.graph_up(center_node_id, max_depth_up)) return prox_graph
'Remove the elements shared between the current graph and other graph from the current graph. @todo: Add support for clusters @type other_graph: pgraph.graph @param other_graph: Graph to diff/remove against'
def graph_sub(self, other_graph):
for other_node in other_graph.nodes.values(): self.del_node(other_node.id) for other_edge in other_graph.edges.values(): self.del_edge(None, other_edge.src, other_edge.dst) return self
'Create a new graph, looking up, from the specified node id to the specified depth. @type from_node_id: pgraph.node @param from_node_id: Node to use as start of up graph @type max_depth: Integer @param max_depth: (Optional, Def=-1) Number of levels to include in up graph (-1 for infinite) @rtype: pgraph.graph ...
def graph_up(self, from_node_id, max_depth=(-1)):
up_graph = graph() from_node = self.find_node('id', from_node_id) levels_to_process = [] current_depth = 1 levels_to_process.append([from_node]) for level in levels_to_process: next_level = [] if ((current_depth > max_depth) and (max_depth != (-1))): break for...
'Render the GML graph description. @rtype: String @return: GML graph description.'
def render_graph_gml(self):
gml = 'Creator "pGRAPH - Pedram Amini <pedram.amini@gmail.com>"\n' gml += 'directed 1\n' gml += 'graph [\n' for node in self.nodes.values(): gml += node.render_node_gml(self) for edge in self.edges.values(): gml += edge.render_edge_gml(self) gml += ']\n' ...
'Render the graphviz graph structure. @rtype: pydot.Dot @return: Pydot object representing entire graph'
def render_graph_graphviz(self):
import pydot dot_graph = pydot.Dot() for node in self.nodes.values(): dot_graph.add_node(node.render_node_graphviz(self)) for edge in self.edges.values(): dot_graph.add_edge(edge.render_edge_graphviz(self)) return dot_graph
'Render the uDraw graph description. @rtype: String @return: uDraw graph description.'
def render_graph_udraw(self):
udraw = '[' for node in self.nodes.values(): udraw += node.render_node_udraw(self) udraw += ',' udraw = (udraw[0:(-1)] + ']') return udraw
'Render the uDraw graph update description. @rtype: String @return: uDraw graph description.'
def render_graph_udraw_update(self):
udraw = '[' for node in self.nodes.values(): udraw += node.render_node_udraw_update() udraw += ',' for edge in self.edges.values(): udraw += edge.render_edge_udraw_update() udraw += ',' udraw = (udraw[0:(-1)] + ']') return udraw
'Simply updating the id attribute of a node will sever the edges to / from the given node. This routine will correctly update the edges as well. @type current_id: Long @param current_id: Current ID of node whose ID we want to update @type new_id: Long @param new_id: New ID to update to.'
def update_node_id(self, current_id, new_id):
if (not self.nodes.has_key(current_id)): return node = self.nodes[current_id] del self.nodes[current_id] node.id = new_id self.nodes[node.id] = node for edge in [edge for edge in self.edges.values() if (current_id in (edge.src, edge.dst))]: del self.edges[edge.id] if (edg...
'Return a list of the nodes within the graph, sorted by id. @rtype: List @return: List of nodes, sorted by id.'
def sorted_nodes(self):
node_keys = self.nodes.keys() node_keys.sort() return [self.nodes[key] for key in node_keys]
'Class constructor. @type src: Mixed @param src: Edge source @type dst: Mixed @param dst: Edge destination'
def __init__(self, src, dst):
self.id = ((src << 32) + dst) self.src = src self.dst = dst self.color = 0 self.label = '' self.gml_arrow = 'none' self.gml_stipple = 1 self.gml_line_width = 1.0
'Render an edge description suitable for use in a GML file using the set internal attributes. @type graph: pgraph.graph @param graph: Top level graph object containing the current edge @rtype: String @return: GML edge description'
def render_edge_gml(self, graph):
src = graph.find_node('id', self.src) dst = graph.find_node('id', self.dst) if ((not src) or (not dst)): return '' edge = ' edge [\n' edge += (' source %d\n' % src.number) edge += (' target %d\n' % dst.number) edge += ' gen...
'Render an edge suitable for use in a Pydot graph using the set internal attributes. @type graph: pgraph.graph @param graph: Top level graph object containing the current edge @rtype: pydot.Edge() @return: Pydot object representing edge'
def render_edge_graphviz(self, graph):
import pydot dot_edge = pydot.Edge(self.src, self.dst) if self.label: dot_edge.label = self.label dot_edge.color = ('#%06x' % self.color) return dot_edge
'Render an edge description suitable for use in a GML file using the set internal attributes. @type graph: pgraph.graph @param graph: Top level graph object containing the current edge @rtype: String @return: GML edge description'
def render_edge_udraw(self, graph):
src = graph.find_node('id', self.src) dst = graph.find_node('id', self.dst) if ((not src) or (not dst)): return '' self.label = self.label.replace('\n', '\\n') udraw = ('l("%08x->%08x",' % (self.src, self.dst)) udraw += 'e("",' udraw += '[' udraw += ('a("EDGECOLOR","#%06x"),' % s...
'Render an edge update description suitable for use in a GML file using the set internal attributes. @rtype: String @return: GML edge update description'
def render_edge_udraw_update(self):
self.label = self.label.replace('\n', '\\n') udraw = ('new_edge("%08x->%08x","",' % (self.src, self.dst)) udraw += '[' udraw += ('a("EDGECOLOR","#%06x"),' % self.color) udraw += ('a("OBJECT","%s")' % self.label) udraw += '],' udraw += ('"%08x","%08x"' % (self.src, self.dst)) udraw += ')'...
'@type pre: Function @param pre: Callback called before each test case @type post: Function @param post: Callback called after each test case for instrumentation. Must return True if the target is still active, False otherwise. @type start: Function @param start: Callback called to start the target @type stop...
def __init__(self, pre=None, post=None, start=None, stop=None):
self.pre = pre self.post = post self.start = start self.stop = stop self.__dbg_flag = False
'Check if this script is alive. Always True.'
def alive(self):
return True
'Print a debug mesage.'
def debug(self, msg):
if self.__dbg_flag: print ('EXT-INSTR> %s' % msg)
'This routine is called before the fuzzer transmits a test case and ensure the target is alive. @type test_number: Integer @param test_number: Test number.'
def pre_send(self, test_number):
if self.pre: self.pre()
'This routine is called after the fuzzer transmits a test case and returns the status of the target. @rtype: Boolean @return: Return True if the target is still active, False otherwise.'
def post_send(self):
if self.post: return self.post() else: return True
'Start up the target. Called when post_send failed. Returns success of failure of the action If no method defined, false is returned'
def start_target(self):
if self.start: return self.start() else: return False
'Stop the target.'
def stop_target(self):
if self.stop: self.stop()
'Return the last recorded crash synopsis. @rtype: String @return: Synopsis of last recorded crash.'
def get_crash_synopsis(self):
return 'External instrumentation detects a crash...\n'
''
def __init__(self):
self.bins = {} self.last_crash = None self.pydbg = None
'Given a PyDbg instantiation that at the current time is assumed to have "crashed" (access violation for example) record various details such as the disassemly around the violating address, the ID of the offending thread, the call stack and the SEH unwind. Store the recorded data in an internal dictionary, binning them...
def record_crash(self, pydbg, extra=None):
self.pydbg = pydbg crash = __crash_bin_struct__() exception_module = pydbg.addr_to_module(pydbg.dbg.u.Exception.ExceptionRecord.ExceptionAddress) if exception_module: exception_module = exception_module.szModule else: exception_module = '[INVALID]' crash.exception_module = except...
'For the supplied crash, generate and return a report containing the disassemly around the violating address, the ID of the offending thread, the call stack and the SEH unwind. If not crash is specified, then call through to last_crash_synopsis() which returns the same information for the last recorded crash. @see: cra...
def crash_synopsis(self, crash=None):
if (not crash): return self.last_crash_synopsis() if crash.write_violation: direction = 'write to' else: direction = 'read from' synopsis = ('%s:%08x %s from thread %d caused access violation\nwhen attempting to %s 0x%08x\n\n' % (crash.excep...
'Dump the entire object structure to disk. @see: import_file() @type file_name: str @param file_name: File name to export to @rtype: crash_binning @return: self'
def export_file(self, file_name):
last_crash = self.last_crash pydbg = self.pydbg self.last_crash = self.pydbg = None fh = open(file_name, 'wb+') fh.write(zlib.compress(cPickle.dumps(self, protocol=2))) fh.close() self.last_crash = last_crash self.pydbg = pydbg return self
'Load the entire object structure from disk. @see: export_file() @type file_name: str @param file_name: File name to import from @rtype: crash_binning @return: self'
def import_file(self, file_name):
fh = open(file_name, 'rb') tmp = cPickle.loads(zlib.decompress(fh.read())) fh.close() self.bins = tmp.bins return self
'For the last recorded crash, generate and return a report containing the disassemly around the violating address, the ID of the offending thread, the call stack and the SEH unwind. @see: crash_synopsis() @rtype: String @return: Crash report'
def last_crash_synopsis(self):
if self.last_crash.write_violation: direction = 'write to' else: direction = 'read from' synopsis = ('%s:%08x %s from thread %d caused access violation\nwhen attempting to %s 0x%08x\n\n' % (self.last_crash.exception_module, self.last_crash.exception_add...
':arg name: name of the index :arg using: connection alias to use, defaults to ``\'default\'``'
def __init__(self, name, using='default'):
self._name = name self._doc_types = {} self._mappings = {} self._using = using self._settings = {} self._aliases = {} self._analysis = {}
'Create a copy of the instance with another name or connection alias. Useful for creating multiple indices with shared configuration:: i = Index(\'base-index\') i.settings(number_of_shards=1) i.create() i2 = i.clone(\'other-index\') i2.create() :arg name: name of the index :arg using: connection alias to use, defaults ...
def clone(self, name, using=None):
i = Index(name, using=(using or self._using)) for attr in ('_doc_types', '_mappings', '_settings', '_aliases', '_analysis'): setattr(i, attr, getattr(self, attr).copy()) return i
'Associate a mapping (an instance of :class:`~elasticsearch_dsl.Mapping`) with this index. This means that, when this index is created, it will contain the mappings for the document type defined by those mappings.'
def mapping(self, mapping):
self._mappings[mapping.doc_type] = mapping
'Associate a :class:`~elasticsearch_dsl.DocType` subclass with an index. This means that, when this index is created, it will contain the mappings for the ``DocType``. If the ``DocType`` class doesn\'t have a default index yet, name of the ``Index`` instance will be used. Can be used as a decorator:: i = Index(\'blog\'...
def doc_type(self, doc_type):
name = doc_type._doc_type.name self._doc_types[name] = doc_type self._mappings[name] = doc_type._doc_type.mapping if (not doc_type._doc_type.index): doc_type._doc_type.index = self._name return doc_type
'Add settings to the index:: i = Index(\'i\') i.settings(number_of_shards=1, number_of_replicas=0) Multiple calls to ``settings`` will merge the keys, later overriding the earlier.'
def settings(self, **kwargs):
self._settings.update(kwargs) return self