id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
19,900
sessions.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/sessions.py
import re import sys import zlib import time import socket import cPickle import threading import BaseHTTPServer import pedrpc import pgraph import sex import primitives ######################################################################################################################## class target: ''' Target descriptor container. ''' def __init__ (self, host, port, **kwargs): ''' @type host: String @param host: Hostname or IP address of target system @type port: Integer @param port: Port of target service ''' self.host = host self.port = port # set these manually once target is instantiated. self.netmon = None self.procmon = None self.vmcontrol = None self.netmon_options = {} self.procmon_options = {} self.vmcontrol_options = {} self.running_flag = True def pedrpc_connect (self): ''' # pass specified target parameters to the PED-RPC server. ''' # wait for the process monitor to come alive and then set its options. if self.procmon: while self.running_flag: try: if self.procmon.alive(): break except: sys.stderr.write("Procmon exception in sessions.py : self.procmon.alive()\n") time.sleep(1) # connection established. if self.running_flag: for key in self.procmon_options.keys(): eval('self.procmon.set_%s(self.procmon_options["%s"])' % (key, key)) # wait for the network monitor to come alive and then set its options. if self.netmon: while self.running_flag: try: if self.netmon.alive(): break except: sys.stderr.write("Netmon exception in sessions.py : self.netmon.alive()\n") time.sleep(1) # connection established. if self.running_flag: for key in self.netmon_options.keys(): eval('self.netmon.set_%s(self.netmon_options["%s"])' % (key, key)) ######################################################################################################################## class connection (pgraph.edge.edge): def __init__ (self, src, dst, callback=None): ''' 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 the last edge along the current fuzz path to "node", session is a pointer to the session instance which is useful for snagging data such as sesson.last_recv which contains the data returned from the last socket transmission and sock is the live socket. A callback is also useful in situations where, for example, the size of the next packet is specified in the first packet. @type src: Integer @param src: Edge source ID @type dst: Integer @param dst: Edge destination ID @type callback: Function @param callback: (Optional, def=None) Callback function to pass received data to between node xmits ''' # run the parent classes initialization routine first. pgraph.edge.edge.__init__(self, src, dst) self.callback = callback ######################################################################################################################## class session (pgraph.graph): def __init__ (self, session_filename=None, audit_folder=None,skip=0, sleep_time=.2, log_level=2, proto="tcp", restart_interval=0, timeout=5.0, web_port=26001, crash_threshold=3, trans_in_q=None): ''' 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 sleep_time: Float @kwarg sleep_time: (Optional, def=1.0) Time to sleep in between tests @type log_level: Integer @kwarg log_level: (Optional, def=2) Set the log level, higher number == more log messages @type proto: String @kwarg proto: (Optional, def="tcp") Communication protocol @type timeout: Float @kwarg timeout: (Optional, def=5.0) Seconds to wait for a send/recv prior to timing out @type restart_interval: Integer @kwarg restart_interval (Optional, def=0) Restart the target after n test cases, disable by setting to 0 @type crash_threshold: Integer @kwarg crash_threshold (Optional, def=3) Maximum number of crashes allowed before a node is exhaust ''' # run the parent classes initialization routine first. pgraph.graph.__init__(self) self.session_filename = session_filename self.audit_folder = audit_folder self.skip = skip self.sleep_time = sleep_time self.log_level = log_level self.proto = proto self.restart_interval = restart_interval self.timeout = timeout self.web_port = web_port self.crash_threshold = crash_threshold self.trans_in_q = trans_in_q self.total_num_mutations = 0 self.total_mutant_index = 0 self.crashes_detected = 0 self.fuzz_node = None self.targets = [] self.netmon_results = {} self.procmon_results = {} self.pause_flag = False self.running_flag = True self.crashing_primitives = {} if self.proto == "tcp": self.proto = socket.SOCK_STREAM elif self.proto == "udp": self.proto = socket.SOCK_DGRAM else: raise sex.error("INVALID PROTOCOL SPECIFIED: %s" % self.proto) # import settings if they exist. self.import_file() # create a root node. we do this because we need to start fuzzing from a single point and the user may want # to specify a number of initial requests. self.root = pgraph.node() self.root.name = "__ROOT_NODE__" self.root.label = self.root.name self.last_recv = None self.add_node(self.root) #################################################################################################################### def decrement_total_mutant_index(self, val): if self.total_mutant_index - val > 0: self.total_mutant_index -= val else: self.total_mutant_index = 0 def add_node (self, node): ''' 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 ''' 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 #################################################################################################################### def add_target (self, target): ''' 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 ''' # pass specified target parameters to the PED-RPC server. target.pedrpc_connect() # add target to internal list. self.targets.append(target) #################################################################################################################### def connect (self, src, dst=None, callback=None): ''' 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 must be connected to. Example:: sess = sessions.session() sess.connect(sess.root, s_get("HTTP")) If given only a single parameter, sess.connect() will default to attaching the supplied node to the root node. This is a convenient alias and is identical to the second line from the above example:: sess.connect(s_get("HTTP")) If you register callback method, it must follow this prototype:: def callback(session, node, edge, sock) Where node is the node about to be sent, edge is the last edge along the current fuzz path to "node", session is a pointer to the session instance which is useful for snagging data such as sesson.last_recv which contains the data returned from the last socket transmission and sock is the live socket. A callback is also useful in situations where, for example, the size of the next packet is specified in the first packet. As another example, if you need to fill in the dynamic IP address of the target register a callback that snags the IP from sock.getpeername()[0]. @type src: String or Request (Node) @param src: Source request name or request node @type dst: String or Request (Node) @param dst: Destination request name or request node @type callback: Function @param callback: (Optional, def=None) Callback function to pass received data to between node xmits @rtype: pgraph.edge @return: The edge between the src and dst. ''' # if only a source was provided, then make it the destination and set the source to the root node. if not dst: dst = src src = self.root # if source or destination is a name, resolve the actual node. if type(src) is str: src = self.find_node("name", src) if type(dst) is str: dst = self.find_node("name", dst) # if source or destination is not in the graph, add it. if src != self.root and not self.find_node("name", src.name): self.add_node(src) if not self.find_node("name", dst.name): self.add_node(dst) # create an edge between the two nodes and add it to the graph. edge = connection(src.id, dst.id, callback) self.add_edge(edge) return edge #################################################################################################################### def export_file (self): ''' Dump various object values to disk. @see: import_file() ''' 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["log_level"] = self.log_level data["proto"] = self.proto data["crashes_detected"] = self.crashes_detected data["restart_interval"] = self.restart_interval data["timeout"] = self.timeout data["web_port"] = self.web_port data["crash_threshold"] = self.crash_threshold data["total_num_mutations"] = self.total_num_mutations data["total_mutant_index"] = self.total_mutant_index data["netmon_results"] = self.netmon_results data["procmon_results"] = self.procmon_results data["pause_flag"] = self.pause_flag fh = open(self.session_filename, "wb+") fh.write(zlib.compress(cPickle.dumps(data, protocol=2))) fh.close() #################################################################################################################### def waitForRegister(self): ''' This method should be overwritten by any fuzzer that needs to wait for the client to register after it has restarted ''' pass #################################################################################################################### def updateProgressBar(self, x, y): ''' This method should be overridden by the GUI ''' pass #################################################################################################################### def fuzz (self, this_node=None, path=[]): ''' 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=[]) Nodes along the path to the current one being fuzzed. ''' # if no node is specified, then we start from the root node and initialize the session. if not this_node: # we can't fuzz if we don't have at least one target and one request. if not self.targets: raise sex.error("NO TARGETS SPECIFIED IN SESSION") if not self.edges_from(self.root.id): raise sex.error("NO REQUESTS SPECIFIED IN SESSION") this_node = self.root try: self.server_init() except: return # XXX - TODO - complete parallel fuzzing, will likely have to thread out each target target = self.targets[0] # step through every edge from the current node. for edge in self.edges_from(this_node.id): # the destination node is the one actually being fuzzed. self.fuzz_node = self.nodes[edge.dst] num_mutations = self.fuzz_node.num_mutations() # keep track of the path as we fuzz through it, don't count the root node. # we keep track of edges as opposed to nodes because if there is more then one path through a set of # given nodes we don't want any ambiguity. if edge.src != self.root.id: path.append(edge) current_path = " -> ".join([self.nodes[e.src].name for e in path]) current_path += " -> %s" % self.fuzz_node.name self.log("current fuzz path: %s" % current_path, 2) self.log("fuzzed %d of %d total cases" % (self.total_mutant_index, self.total_num_mutations), 2) self.updateProgressBar(self.total_mutant_index, self.total_num_mutations) self.update_GUI_crashes(self.crashes_detected) done_with_fuzz_node = False crash_count = 0 # loop through all possible mutations of the fuzz node. while not done_with_fuzz_node: # the GUI sets unsets this flag when it wants the fuzzer to die # command line users can just ctrl-c/z or ctrl-alt-delete if not self.running_flag: break # if we need to pause, do so. self.pause() # if we have exhausted the mutations of the fuzz node, break out of the while(1). # note: when mutate() returns False, the node has been reverted to the default (valid) state. if not self.fuzz_node.mutate(): self.log("all possible mutations for current fuzz node exhausted", 2) done_with_fuzz_node = True continue # make a record in the session that a mutation was made. self.total_mutant_index += 1 # if we don't need to skip the current test case. if self.total_mutant_index > self.skip: # if we've hit the restart interval, restart the target. if self.restart_interval and self.total_mutant_index % self.restart_interval == 0: self.log("restart interval of %d reached" % self.restart_interval) self.restart_target(target) # call this method in case we should wait for the client app to register with us after a restart self.waitForRegister() self.log("fuzzing %d of %d" % (self.fuzz_node.mutant_index, num_mutations), 2) # attempt to complete a fuzz transmission. keep trying until we are successful, whenever a failure # occurs, restart the target. while 1: try: # instruct the debugger/sniffer that we are about to send a new fuzz. if target.procmon: target.procmon.pre_send(self.total_mutant_index) if target.netmon: target.netmon.pre_send(self.total_mutant_index) # establish a connection to the target. self.host = target.host self.port = target.port sock = socket.socket(socket.AF_INET, self.proto) sock.settimeout(self.timeout) # if the user registered a pre-send function, pass it the sock and let it do the deed. self.pre_send(sock) # send out valid requests for each node in the current path up to the node we are fuzzing. for e in path: node = self.nodes[e.src] self.transmit(sock, node, e, target) # now send the current node we are fuzzing. self.transmit(sock, self.fuzz_node, edge, target) self.updateProgressBar(self.total_mutant_index, self.total_num_mutations) # if we reach this point the send was successful for break out of the while(1). break except sex.error, e: sys.stderr.write("CAUGHT SULLEY EXCEPTION\n") sys.stderr.write("\t" + e.__str__() + "\n") sys.exit(1) # close the socket. self.close_socket(sock) self.log("failed connecting to %s:%d" % (target.host, target.port)) self.log("restarting target and trying again") self.restart_target(target) # if the user registered a post-send function, pass it the sock and let it do the deed. # we do this outside the try/except loop because if our fuzz causes a crash then the post_send() # will likely fail and we don't want to sit in an endless loop. self.post_send(sock) # done with the socket. # The following is necessary because in the case of a # CANCEL being sent to an INVITE we need the socket to live # for a little longer # sock.close() self.close_socket(sock) # delay in between test cases. self.log("sleeping for %f seconds" % self.sleep_time, 5) time.sleep(self.sleep_time) # poll the PED-RPC endpoints (netmon, procmon etc...) for the target. self.poll_pedrpc(target) # serialize the current session state to disk. self.export_file() # recursively fuzz the remainder of the nodes in the session graph. if not self.running_flag: break self.fuzz(self.fuzz_node, path) # finished with the last node on the path, pop it off the path stack. if path: path.pop() #################################################################################################################### def close_socket(self, sock): ''' Closes a given socket. Meant to be overridden by VoIPER @type sock: Socket @param sock: The socket to be closed ''' sock.close() #################################################################################################################### def import_file (self): ''' Load varous object values from disk. @see: export_file() ''' try: fh = open(self.session_filename, "rb") data = cPickle.loads(zlib.decompress(fh.read())) fh.close() except: return # update the skip variable to pick up fuzzing from last test case. self.skip = data["total_mutant_index"] self.session_filename = data["session_filename"] self.sleep_time = data["sleep_time"] self.log_level = data["log_level"] self.proto = data["proto"] self.restart_interval = data["restart_interval"] self.timeout = data["timeout"] self.web_port = data["web_port"] self.crash_threshold = data["crash_threshold"] self.total_num_mutations = data["total_num_mutations"] self.total_mutant_index = data["total_mutant_index"] self.netmon_results = data["netmon_results"] self.procmon_results = data["procmon_results"] self.pause_flag = data["pause_flag"] self.crashes_detected = data["crashes_detected"] #################################################################################################################### def log (self, msg, level=1): ''' If the supplied message falls under the current log level, print the specified message to screen. @type msg: String @param msg: Message to log ''' if self.log_level >= level: print "[%s] %s" % (time.strftime("%I:%M.%S"), msg) #################################################################################################################### def num_mutations (self, this_node=None, path=[]): ''' 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 fuzzed. @type path: List @param path: (Optional, def=[]) Nodes along the path to the current one being fuzzed. @rtype: Integer @return: Total number of mutations in this session. ''' 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) self.num_mutations(next_node, path) # finished with the last node on the path, pop it off the path stack. if path: path.pop() return self.total_num_mutations #################################################################################################################### def pause (self): ''' If thet pause flag is raised, enter an endless loop until it is lowered. ''' while 1: if self.pause_flag: time.sleep(1) else: break #################################################################################################################### def poll_pedrpc (self, target): ''' 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 ''' # kill the pcap thread and see how many bytes the sniffer recorded. if target.netmon: bytes = target.netmon.post_send() self.log("netmon captured %d bytes for test case #%d" % (bytes, self.total_mutant_index), 2) self.netmon_results[self.total_mutant_index] = bytes # check if our fuzz crashed the target. procmon.post_send() returns False if the target access violated. if target.procmon: # had to include this because an error in the connection can result in nothing being returned. Which is # annoying ret_val = None while not ret_val: ret_val = target.procmon.post_send() alive = ret_val[0] crash_type = ret_val[1] if not alive: self.log("procmon detected %s on test case #%d" % (crash_type, self.total_mutant_index)) self.crashes_detected += 1 self.update_GUI_crashes(self.crashes_detected) # retrieve the primitive that caused the crash and increment it's individual crash count. self.crashing_primitives[self.fuzz_node.mutant] = self.crashing_primitives.get(self.fuzz_node.mutant, 0) + 1 # notify with as much information as possible. if not self.fuzz_node.mutant.name: msg = "primitive lacks a name, " else: msg = "primitive name: %s, " % self.fuzz_node.mutant.name msg += "type: %s, default value: %s" % (self.fuzz_node.mutant.s_type, self.fuzz_node.mutant.original_value) self.log(msg) # print crash synopsis if access violation if crash_type == "access violation": self.procmon_results[self.total_mutant_index] = target.procmon.get_crash_synopsis() self.log(self.procmon_results[self.total_mutant_index].split("\n")[0], 2) # log the sent data to disk if self.audit_folder != None: crash_log_name = self.audit_folder + '/' + \ str(self.fuzz_node.id) + '_' + \ str(self.total_mutant_index) + '.crashlog' crash_log = open(crash_log_name, 'w') crash_log.write(self.fuzz_node.sent_data) crash_log.close() self.log('Fuzz request logged to ' + crash_log_name, 2) # if the user-supplied crash threshold is reached, exhaust this node. if self.crashing_primitives[self.fuzz_node.mutant] >= self.crash_threshold: # as long as we're not a group if not isinstance(self.crashing_primitives[self.fuzz_node.mutant], primitives.group): skipped = self.fuzz_node.mutant.exhaust() self.log("crash threshold reached for this primitive, exhausting %d mutants." % skipped) self.total_mutant_index += skipped # start the target back up. self.restart_target(target, stop_first=False) #################################################################################################################### def update_GUI_crashes(self, num_crashes): ''' Method to be overridden by a GUI that wants and update of the number of crashes detected ''' pass #################################################################################################################### def post_send (self, sock): ''' 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: Connected socket to target ''' # default to doing nothing. pass #################################################################################################################### def pre_send (self, sock): ''' 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: Connected socket to target ''' # default to doing nothing. pass #################################################################################################################### def restart_target (self, target, stop_first=True): ''' 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 ''' # vm restarting is the preferred method so try that first. if target.vmcontrol: self.log("restarting target virtual machine") target.vmcontrol.restart_target() # if we have a connected process monitor, restart the target process. elif target.procmon: self.log("restarting target process") if stop_first: target.procmon.stop_target() target.procmon.start_target() # give the process a few seconds to settle in. time.sleep(3) # otherwise all we can do is wait a while for the target to recover on its own. else: self.log("no vmcontrol or procmon channel available ... sleeping for 5 minutes") time.sleep(300) # pass specified target parameters to the PED-RPC server to re-establish connections. target.pedrpc_connect() #################################################################################################################### def server_init (self): ''' Called by fuzz() on first run (not on recursive re-entry) to initialize variables, web interface, etc... ''' self.total_mutant_index = 0 self.total_num_mutations = self.num_mutations() # spawn the web interface. t = web_interface_thread(self) t.start() #################################################################################################################### def transmit (self, sock, node, edge, target): ''' 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 target: session.target @param target: Target we are transmitting to ''' data = None self.log("xmitting: [%d.%d]" % (node.id, self.total_mutant_index), level=2) # if the edge has a callback, process it. the callback has the option to render the node, modify it and return. if edge.callback: data = edge.callback(self, node, edge, sock) # if not data was returned by the callback, render the node here. if not data: data = node.render() # if data length is > 65507 and proto is UDP, truncate it. # XXX - this logic does not prevent duplicate test cases, need to address this in the future. if self.proto == socket.SOCK_DGRAM: # max UDP packet size. if len(data) > 65507: #self.log("Too much data for UDP, truncating to 65507 bytes") data = data[:65507] # pass the data off to the transaction manager to be added to a transaction if self.trans_in_q: self.trans_in_q.put((True, data, 2, (self.host, self.port), 1.5, sock)) try: sock.sendto(data, (self.host, self.port)) node.sent_data = data except Exception, inst: self.log("Socket error, send: %s" % inst[1]) if self.proto == socket.SOCK_STREAM: # XXX - might have a need to increase this at some point. (possibly make it a class parameter) try: self.last_recv = sock.recv(10000) except Exception, e: self.log("Nothing received on socket.", 5) self.last_recv = "" else: self.last_recv = "" if len(self.last_recv) > 0: self.log("received: [%d] %s" % (len(self.last_recv), self.last_recv), level=10) ######################################################################################################################## class web_interface_handler (BaseHTTPServer.BaseHTTPRequestHandler): def __init__(self, request, client_address, server): BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server) self.session = None def commify (self, number): number = str(number) processing = 1 regex = re.compile(r"^(-?\d+)(\d{3})") while processing: (number, processing) = regex.subn(r"\1,\2",number) return number def do_GET (self): self.do_everything() def do_HEAD (self): self.do_everything() def do_POST (self): self.do_everything() def do_everything (self): if "pause" in self.path: self.session.pause_flag = True if "resume" in self.path: self.session.pause_flag = False self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() if "view_crash" in self.path: response = self.view_crash(self.path) elif "view_pcap" in self.path: response = self.view_pcap(self.path) else: response = self.view_index() self.wfile.write(response) def log_error (self, *args, **kwargs): pass def log_message (self, *args, **kwargs): pass def version_string (self): return "Sulley Fuzz Session" def view_crash (self, path): test_number = int(path.split("/")[-1]) return "<html><pre>%s</pre></html>" % self.session.procmon_results[test_number] def view_pcap (self, path): return path def view_index (self): response = """ <html> <head> <title>Sulley Fuzz Control</title> <style> a:link {color: #FF8200; text-decoration: none;} a:visited {color: #FF8200; text-decoration: none;} a:hover {color: #C5C5C5; text-decoration: none;} body { background-color: #000000; font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #FFFFFF; } td { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #A0B0B0; } .fixed { font-family: Courier New; font-size: 12px; color: #A0B0B0; } .input { font-family: Arial, Helvetica, sans-serif; font-size: 11px; color: #FFFFFF; background-color: #333333; border: thin none; height: 20px; } </style> </head> <body> <center> <table border=0 cellpadding=5 cellspacing=0 width=750><tr><td> <!-- begin bounding table --> <table border=0 cellpadding=5 cellspacing=0 width="100%%"> <tr bgcolor="#333333"> <td><div style="font-size: 20px;">Sulley Fuzz Control</div></td> <td align=right><div style="font-weight: bold; font-size: 20px;">%(status)s</div></td> </tr> <tr bgcolor="#111111"> <td colspan=2 align="center"> <table border=0 cellpadding=0 cellspacing=5> <tr bgcolor="#111111"> <td><b>Total:</b></td> <td>%(total_mutant_index)s</td> <td>of</td> <td>%(total_num_mutations)s</td> <td class="fixed">%(progress_total_bar)s</td> <td>%(progress_total)s</td> </tr> <tr bgcolor="#111111"> <td><b>%(current_name)s:</b></td> <td>%(current_mutant_index)s</td> <td>of</td> <td>%(current_num_mutations)s</td> <td class="fixed">%(progress_current_bar)s</td> <td>%(progress_current)s</td> </tr> </table> </td> </tr> <tr> <td> <form method=get action="/pause"> <input class="input" type="submit" value="Pause"> </form> </td> <td align=right> <form method=get action="/resume"> <input class="input" type="submit" value="Resume"> </form> </td> </tr> </table> <!-- begin procmon results --> <table border=0 cellpadding=5 cellspacing=0 width="100%%"> <tr bgcolor="#333333"> <td nowrap>Test Case #</td> <td>Crash Synopsis</td> <td nowrap>Captured Bytes</td> </tr> """ keys = self.session.procmon_results.keys() keys.sort() for key in keys: val = self.session.procmon_results[key] bytes = "&nbsp;" if self.session.netmon_results.has_key(key): bytes = self.commify(self.session.netmon_results[key]) response += '<tr><td class="fixed"><a href="/view_crash/%d">%06d</a></td><td>%s</td><td align=right>%s</td></tr>' % (key, key, val.split("\n")[0], bytes) response += """ <!-- end procmon results --> </table> <!-- end bounding table --> </td></tr></table> </center> </body> </html> """ # what is the fuzzing status. if self.session.pause_flag: status = "<font color=red>PAUSED</font>" else: status = "<font color=green>RUNNING</font>" # if there is a current fuzz node. if self.session.fuzz_node: # which node (request) are we currently fuzzing. if self.session.fuzz_node.name: current_name = self.session.fuzz_node.name else: current_name = "[N/A]" # render sweet progress bars. progress_current = float(self.session.fuzz_node.mutant_index) / float(self.session.fuzz_node.num_mutations()) num_bars = int(progress_current * 50) progress_current_bar = "[" + "=" * num_bars + "&nbsp;" * (50 - num_bars) + "]" progress_current = "%.3f%%" % (progress_current * 100) progress_total = float(self.session.total_mutant_index) / float(self.session.total_num_mutations) num_bars = int(progress_total * 50) progress_total_bar = "[" + "=" * num_bars + "&nbsp;" * (50 - num_bars) + "]" progress_total = "%.3f%%" % (progress_total * 100) response %= \ { "current_mutant_index" : self.commify(self.session.fuzz_node.mutant_index), "current_name" : current_name, "current_num_mutations" : self.commify(self.session.fuzz_node.num_mutations()), "progress_current" : progress_current, "progress_current_bar" : progress_current_bar, "progress_total" : progress_total, "progress_total_bar" : progress_total_bar, "status" : status, "total_mutant_index" : self.commify(self.session.total_mutant_index), "total_num_mutations" : self.commify(self.session.total_num_mutations), } else: response %= \ { "current_mutant_index" : "", "current_name" : "", "current_num_mutations" : "", "progress_current" : "", "progress_current_bar" : "", "progress_total" : "", "progress_total_bar" : "", "status" : "<font color=yellow>UNAVAILABLE</font>", "total_mutant_index" : "", "total_num_mutations" : "", } return response ######################################################################################################################## class web_interface_server (BaseHTTPServer.HTTPServer): ''' http://docs.python.org/lib/module-BaseHTTPServer.html ''' def __init__(self, server_address, RequestHandlerClass, session): BaseHTTPServer.HTTPServer.__init__(self, server_address, RequestHandlerClass) self.RequestHandlerClass.session = session ######################################################################################################################## class web_interface_thread (threading.Thread): def __init__ (self, session): threading.Thread.__init__(self) self.session = session self.server = None def run (self): self.server = web_interface_server(('', self.session.web_port), web_interface_handler, self.session) self.server.serve_forever()
44,977
Python
.py
849
38.991755
199
0.50587
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,901
pedrpc.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pedrpc.py
import sys import struct import socket import cPickle import time ######################################################################################################################## class client: def __init__ (self, host, port): self.__host = host self.__port = port self.__dbg_flag = False self.__server_sock = None self.running_flag = True self.NOLINGER = struct.pack('HH', 1, 0) #################################################################################################################### def __getattr__ (self, method_name): ''' 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 handles missing methods by default ... with arguments. Now we are just as cool as Ruby. @type method_name: String @param method_name: The name of the requested and undefined attribute (or method in our case). @rtype: Lambda @return: Lambda magic passing control (and in turn the arguments we want) to self.method_missing(). ''' return lambda *args, **kwargs: self.__method_missing(method_name, *args, **kwargs) #################################################################################################################### def __connect (self): ''' Connect to the PED-RPC server. ''' # if we have a pre-existing server socket, ensure it's closed. self.__disconnect() # connect to the server, timeout on failure. 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)) err = 0 except Exception, e: sys.stderr.write("PED-RPC> unable to connect to server %s:%d\n" % (self.__host, self.__port)) print type(e) print e err = 1 # disable timeouts and lingering. self.__server_sock.settimeout(None) self.__server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, self.NOLINGER) return err #################################################################################################################### def __disconnect (self): ''' Ensure the socket is torn down. ''' if self.__server_sock != None: self.__debug("closing server socket") self.__server_sock.close() self.__server_sock = None #################################################################################################################### def __debug (self, msg): if self.__dbg_flag: print "PED-RPC> %s" % msg #################################################################################################################### def __method_missing (self, method_name, *args, **kwargs): ''' 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: Tuple @param *args: Tuple of arguments. @type **kwargs Dictionary @param **kwargs: Dictioanry of arguments. @rtype: Mixed @return: Return value of the mirrored method. ''' # return a value so lines of code like the following work: # x = pedrpc.client(host, port) # if x: # x.do_something() if method_name == "__nonzero__": return 1 # ignore all other attempts to access a private member. if method_name.startswith("__"): return # connect to the PED-RPC server. while self.__connect() == 1: sys.stderr.write("PED-RPC> Connect failed. Sleeping for 5 seconds") time.sleep(5) # transmit the method name and arguments. while self.running_flag: try: self.__pickle_send((method_name, (args, kwargs))) break except: # re-connect to the PED-RPC server if the sock died. self.__connect() # snag the return value. ret = self.__pickle_recv() # close the sock and return. self.__disconnect() return ret #################################################################################################################### def __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 received. @raise pdx: An exception is raised if the connection was severed. @rtype: Mixed @return: Whatever is received over the socket. ''' try: # XXX - this should NEVER fail, but alas, it does and for the time being i can't figure out why. # it gets worse. you would think that simply returning here would break things, but it doesn't. # gotta track this down at some point. 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> connection to server severed during recv()\n") raise Exception return cPickle.loads(received) #################################################################################################################### def __pickle_send (self, data): ''' 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 received. @type data: Mixed @param data: Data to marshal and transmit. Data can *pretty much* contain anything you throw at it. @raise pdx: An exception is raised if the connection was severed. ''' 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") raise Exception ######################################################################################################################## class server: def __init__ (self, host, port): self.__host = host self.__port = port self.__dbg_flag = False self.__client_sock = None self.__client_address = None try: # create a socket and bind to the specified port. self.__server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__server.settimeout(None) self.__server.bind((host, port)) self.__server.listen(1) except: sys.stderr.write("unable to bind to %s:%d\n" % (host, port)) sys.exit(1) #################################################################################################################### def __disconnect (self): ''' Ensure the socket is torn down. ''' if self.__client_sock != None: self.__debug("closing client socket") self.__client_sock.close() self.__client_sock = None #################################################################################################################### def __debug (self, msg): if self.__dbg_flag: print "PED-RPC> %s" % msg #################################################################################################################### def __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 received. @raise pdx: An exception is raised if the connection was severed. @rtype: Mixed @return: Whatever is received over the socket. ''' 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 during recv()\n") raise Exception return cPickle.loads(received) #################################################################################################################### def __pickle_send (self, data): ''' 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 received. @type data: Mixed @param data: Data to marshal and transmit. Data can *pretty much* contain anything you throw at it. @raise pdx: An exception is raised if the connection was severed. ''' 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") raise Exception #################################################################################################################### def serve_forever (self): self.__debug("serving up a storm") while 1: # close any pre-existing socket. self.__disconnect() # accept a client connection. (self.__client_sock, self.__client_address) = self.__server.accept() self.__debug("accepted connection from %s:%d" % (self.__client_address[0], self.__client_address[1])) # recieve the method name and arguments, continue on socket disconnect. try: (method_name, (args, kwargs)) = self.__pickle_recv() self.__debug("%s(args=%s, kwargs=%s)" % (method_name, args, kwargs)) except: print 'Exception in serve_forever receiving method name and args' continue # resolve a pointer to the requested method and call it. exec("method_pointer = self.%s" % method_name) ret = method_pointer(*args, **kwargs) # transmit the return value to the client, continue on socket disconnect. try: self.__pickle_send(ret) except: continue
12,290
Python
.py
240
40.916667
120
0.508021
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,902
pedrpc.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pedrpc.pyc
Ñò âпMc@sfddkZddkZddkZddkZddkZddd„ƒYZddd„ƒYZdS(iÿÿÿÿNtclientcBsPeZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z RS(cCsI||_||_t|_d|_t|_ti dddƒ|_ dS(NtHHii( t _client__hostt _client__porttFalset_client__dbg_flagtNonet_client__server_socktTruet running_flagtstructtpacktNOLINGER(tselfthosttport((s'/pentest/voiper/sulley/sulley/pedrpc.pyt__init__ s      cs‡‡fd†S(sË 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 handles missing methods by default ... with arguments. Now we are just as cool as Ruby. @type method_name: String @param method_name: The name of the requested and undefined attribute (or method in our case). @rtype: Lambda @return: Lambda magic passing control (and in turn the arguments we want) to self.method_missing(). csˆiˆ||ŽS((t_client__method_missing(targstkwargs(t method_nameR (s'/pentest/voiper/sulley/sulley/pedrpc.pyt<lambda> s((R R((RR s'/pentest/voiper/sulley/sulley/pedrpc.pyt __getattr__scCsÜ|iƒyQtititiƒ|_|iidƒ|ii|i|ifƒd}WnKt j o?}t i i d|i|ifƒt |ƒGH|GHd}nX|iidƒ|iititi|iƒ|S(s0 Connect to the PED-RPC server. g@is+PED-RPC> unable to connect to server %s:%d iN(t_client__disconnecttsockettAF_INETt SOCK_STREAMRt settimeouttconnectRRt ExceptiontsyststderrtwritettypeRt setsockoptt SOL_SOCKETt SO_LINGERR (R terrte((s'/pentest/voiper/sulley/sulley/pedrpc.pyt __connect$s     cCs;|idjo'|idƒ|iiƒd|_ndS(s1 Ensure the socket is torn down. sclosing server socketN(RRt_client__debugtclose(R ((s'/pentest/voiper/sulley/sulley/pedrpc.pyt __disconnect?s  cCs|io d|GHndS(Ns PED-RPC> %s(R(R tmsg((s'/pentest/voiper/sulley/sulley/pedrpc.pyt__debugKs cOs½|djodS|idƒodSx5|iƒdjo!tiidƒtidƒq*WxA|io6y|i|||ffƒPWqb|iƒqbXqbW|i ƒ}|i ƒ|S(sN 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: Tuple @param *args: Tuple of arguments. @type **kwargs Dictionary @param **kwargs: Dictioanry of arguments. @rtype: Mixed @return: Return value of the mirrored method. t __nonzero__it__Ns/PED-RPC> Connect failed. Sleeping for 5 secondsi( t startswitht_client__connectRRR ttimetsleepR t_client__pickle_sendt_client__pickle_recvR(R RRRtret((s'/pentest/voiper/sulley/sulley/pedrpc.pyt__method_missingQs$    c Cs£y&tid|iidƒƒd}WndSXyEd}x8|o0|ii|ƒ}||7}|t|ƒ8}q=WWntiidƒt‚nXt i |ƒS(s 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 received. @raise pdx: An exception is raised if the connection was severed. @rtype: Mixed @return: Whatever is received over the socket. s<LiiNts4PED-RPC> connection to server severed during recv() ( R tunpackRtrecvtlenRRR RtcPickletloads(R tlengthtreceivedtchunk((s'/pentest/voiper/sulley/sulley/pedrpc.pyt __pickle_recvƒs &  cCs†ti|ddƒ}|idt|ƒƒy6|iitidt|ƒƒƒ|ii|ƒWnti i dƒt ‚nXdS(s7 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 received. @type data: Mixed @param data: Data to marshal and transmit. Data can *pretty much* contain anything you throw at it. @raise pdx: An exception is raised if the connection was severed. tprotocolissending %d bytess<Ls4PED-RPC> connection to server severed during send() N( R;tdumpsR(R:RtsendR R RRR R(R tdata((s'/pentest/voiper/sulley/sulley/pedrpc.pyt __pickle_send¥s "( t__name__t __module__RRR0RR(RR4R3(((s'/pentest/voiper/sulley/sulley/pedrpc.pyRs    2 "tservercBs>eZd„Zd„Zd„Zd„Zd„Zd„ZRS(cCs·||_||_t|_d|_d|_yUtititi ƒ|_ |i i dƒ|i i ||fƒ|i i dƒWn.tiid||fƒtidƒnXdS(Nisunable to bind to %s:%d (t _server__hostt _server__portRt_server__dbg_flagRt_server__client_sockt_server__client_addressRRRt_server__serverRtbindtlistenRRR texit(R RR((s'/pentest/voiper/sulley/sulley/pedrpc.pyR¾s     cCs;|idjo'|idƒ|iiƒd|_ndS(s1 Ensure the socket is torn down. sclosing client socketN(RLRt_server__debugR)(R ((s'/pentest/voiper/sulley/sulley/pedrpc.pyR*Ñs  cCs|io d|GHndS(Ns PED-RPC> %s(RK(R R+((s'/pentest/voiper/sulley/sulley/pedrpc.pyR,Ýs cCs”ygtid|iidƒƒd}d}x8|o0|ii|ƒ}||7}|t|ƒ8}q.WWntiidƒt‚nXt i |ƒS(s 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 received. @raise pdx: An exception is raised if the connection was severed. @rtype: Mixed @return: Whatever is received over the socket. s<LiiR7s1PED-RPC> connection client severed during recv() ( R R8RLR9R:RRR RR;R<(R R=R>R?((s'/pentest/voiper/sulley/sulley/pedrpc.pyR@ãs "  cCs†ti|ddƒ}|idt|ƒƒy6|iitidt|ƒƒƒ|ii|ƒWnti i dƒt ‚nXdS(s7 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 received. @type data: Mixed @param data: Data to marshal and transmit. Data can *pretty much* contain anything you throw at it. @raise pdx: An exception is raised if the connection was severed. RAissending %d bytess<Ls4PED-RPC> connection to client severed during send() N( R;RBRRR:RLRCR R RRR R(R RD((s'/pentest/voiper/sulley/sulley/pedrpc.pyREýs "cBsâ|idƒxÎ|iƒ|iiƒ\|_|_|id|id|idfƒy6|iƒ\}\}}|id|||fƒWndGHqnXd|dUe||Ž}y|i|ƒWqqqXqdS(Nsserving up a stormsaccepted connection from %s:%diis%s(args=%s, kwargs=%s)s9Exception in serve_forever receiving method name and argssmethod_pointer = self.%s( RRt_server__disconnectRNtacceptRLRMt_server__pickle_recvtmethod_pointert_server__pickle_send(R RRRR5((s'/pentest/voiper/sulley/sulley/pedrpc.pyt serve_forevers"  % (RFRGRRSRRRURWRX(((s'/pentest/voiper/sulley/sulley/pedrpc.pyRH½s     (((RR RR;R1RRH(((s'/pentest/voiper/sulley/sulley/pedrpc.pyt<module>s     µ
10,405
Python
.py
96
102.78125
813
0.499612
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,903
primitives.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/primitives.pyc
—Ú ‚–øMc@sAddkZddkZddkZddkZdefdÑÉYZdefdÑÉYZdefdÑÉYZdefd ÑÉYZd efd ÑÉYZ gZ d ÑZ d dÑZ defdÑÉYZdefdÑÉYZ de fdÑÉYZde fdÑÉYZde fdÑÉYZde fdÑÉYZdS(iˇˇˇˇNtbase_primitivecBsDeZdZdÑZdÑZdÑZdÑZdÑZdÑZRS(sa The primitive base class implements common functionality shared across most primitives. cCsCt|_g|_t|_d|_d|_d|_d|_ dS(Nit( tFalset fuzz_completet fuzz_librarytTruetfuzzablet mutant_indextNonetoriginal_valuetrenderedtvalue(tself((s+/pentest/voiper/sulley/sulley/primitives.pyt__init__ s      cCs;|iÉ|i}t|_|iÉ|_|i|_|S(sõ Exhaust the possible mutations for this primitive. @rtype: Integer @return: The number of mutations to reach exhaustion (t num_mutationsRRRR R (R tnum((s+/pentest/voiper/sulley/sulley/primitives.pytexhausts   cCso|i|iÉjo t|_n|i p |io|i|_tS|i|i|_|id7_tS(sµ Mutate the primitive by stepping through the fuzz library, return False on completion. @rtype: Boolean @return: True on success, False otherwise. i( RRRRRR R RR(R ((s+/pentest/voiper/sulley/sulley/primitives.pytmutate's   cCs t|iÉS(sæ Calculate and return the total number of mutations for this individual primitive. @rtype: Integer @return: Number of mutated forms this primitive can take (tlenR(R ((s+/pentest/voiper/sulley/sulley/primitives.pyRAscCs|i|_|iS(sC Nothing fancy on render, simply return the value. (R R (R ((s+/pentest/voiper/sulley/sulley/primitives.pytrenderLs cCs"t|_d|_|i|_dS(sF Reset this primitive to the starting mutation state. iN(RRRR R (R ((s+/pentest/voiper/sulley/sulley/primitives.pytresetUs  ( t__name__t __module__t__doc__R RRRRR(((s+/pentest/voiper/sulley/sulley/primitives.pyRs   tdelimcBseZeddÑZRS(cCs∂||_|_||_||_d|_d|_t|_g|_d|_ |io•|ii |idÉ|ii |idÉ|ii |idÉ|ii |idÉ|ii |idÉ|ii |id É|ii |id Én|ii dÉ|id jo8|ii d É|ii d1É|ii d dÉn|ii d É|ii d É|ii d dÉ|ii ddÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii dÉ|ii ddÉ|ii ddÉ|ii d É|ii d!É|ii d"É|ii d#É|ii d$É|ii d%É|ii d&É|ii d'É|ii d(É|ii d)É|ii d*É|ii d+É|ii d,d-É|ii d,d.É|ii d,d/Éd0S(2s… Represent a delimiter such as :, , , ,=,>,< etc... Mutations include repetition, substitution and exclusion. @type value: Character @param value: Original value @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive RRiiii iidiÙiËt s s s t!t@t#t$t%t^t&t*t(t)t-t_t+t=t:s: s:7t;t's"t/s\t?t<t>t.t,s s s i@iÄiNs ( R R Rtnamets_typeR RRRRtappend(R R RR1((s+/pentest/voiper/sulley/sulley/primitives.pyR asr         N(RRRRR (((s+/pentest/voiper/sulley/sulley/primitives.pyR`stgroupcBs#eZdÑZdÑZdÑZRS(cCs®||_||_t|_d|_|id|_|id|_d|_t|_ d|_ |igjo5x2|iD]#}t |Ét jp t dÇqyWndS(s This primitive represents a list of static values, stepping through each one on mutation. You can tie a block to a group primitive to specify that the block should cycle through all possible mutations for *each* value within the group. The group primitive is useful for example for representing a list of valid opcodes. @type name: String @param name: Name of group @type values: List or raw data @param values: List of possible raw values this group can take. R4iRis/Value list may only contain strings or raw dataN(R1tvaluesRRR2R R R RRRttypetstrtAssertionError(R R1R5tval((s+/pentest/voiper/sulley/sulley/primitives.pyR ∑s        cCss|i|iÉjo t|_n|i p |io|id|_tS|i|i|_|id7_tS(sj Move to the next item in the values list. @rtype: False @return: False ii(RRRRRR5R R(R ((s+/pentest/voiper/sulley/sulley/primitives.pyR‘s cCs t|iÉS(sÑ Number of values in this primitive. @rtype: Integer @return: Number of values in this primitive. (RR5(R ((s+/pentest/voiper/sulley/sulley/primitives.pyRÌs(RRR RR(((s+/pentest/voiper/sulley/sulley/primitives.pyR4∂s  t random_datacBs,eZdeddÑZdÑZdÑZRS(icCskt|É|_|_||_||_||_||_||_d|_d|_ t |_ d|_ dS(s{ Generate a random chunk of data while maintaining a copy of the original. A random length range can be specified. For a static length, set min/max length to be the same. @type value: Raw @param value: Original value @type min_length: Integer @param min_length: Minimum length of random block @type max_length: Integer @param max_length: Maximum length of random block @type max_mutations: Integer @param max_mutations: (Optional, def=25) Number of mutations to make before reverting to default @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive R:RiN( R7R R t min_lengtht max_lengtht max_mutationsRR1R2R RRR(R R R;R<R=RR1((s+/pentest/voiper/sulley/sulley/primitives.pyR ˙s        cCsµ|i|iÉjo t|_n|i p |io|i|_tSti |i |i É}d|_x5t |ÉD]'}|it ti ddÉÉ7_qwW|id7_tS(sò Mutate the primitive value returning False on completion. @rtype: Boolean @return: True on success, False otherwise. Riiˇi(RRRRRR R RtrandomtrandintR;R<txrangetchr(R tlengthti((s+/pentest/voiper/sulley/sulley/primitives.pyRs     %cCs|iS(sæ Calculate and return the total number of mutations for this individual primitive. @rtype: Integer @return: Number of mutated forms this primitive can take (R=(R ((s+/pentest/voiper/sulley/sulley/primitives.pyR9sN(RRRRR RR(((s+/pentest/voiper/sulley/sulley/primitives.pyR:˘s tstaticcBs&eZddÑZdÑZdÑZRS(cCsJ||_|_||_t|_d|_d|_d|_t|_ dS(s˚ 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 iRDRN( R R R1RRRR2R RR(R R R1((s+/pentest/voiper/sulley/sulley/primitives.pyR Fs      cCstS(sL Do nothing. @rtype: False @return: False (R(R ((s+/pentest/voiper/sulley/sulley/primitives.pyRYscCsdS(sB Return 0. @rtype: 0 @return: 0 i((R ((s+/pentest/voiper/sulley/sulley/primitives.pyRdsN(RRRR RR(((s+/pentest/voiper/sulley/sulley/primitives.pyRDEs  cCsÜd}d}xs||joe||}ti|É||d}ti|É||d}ti|É|d7}d|}qWdS(s˘ 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. iiiNiÄ(t long_stringsR3(tsequencetmax_lenRBtpowert long_string((s+/pentest/voiper/sulley/sulley/primitives.pytadd_long_stringsss       i cCstd|Étd|Étd|Étd|Étd|Étd|Étd|Étd|Étd |Étd |Étd |Étd |Étd |Étd|Étd|Étd|Étd|Étd|Étd|Étd|Étd|Étd|Étd|Étd|Étd|Étd|Étd|Étd|Étd|Éd'}d}xê||joÇd|}x]d d!dd"dd#d$d%gD]=}|t|Éd ||t|Éd}ti|ÉqæW|d&7}d|}qàWdS((NtAtBt1t2R-R.R*s"R+s\R,R'sa=R R/R0R"R#t]t[RR!R$R&t{t}ss˛sˇiitR(R)s s s iiÄ(RJRRER3(RGRBRHtsR9ttmp((s+/pentest/voiper/sulley/sulley/primitives.pyt gen_stringsâsP                               * tstringcBs)eZdddeddÑZdÑZRS(iˇˇˇˇRStasciic 0Cs∑||_|_||_||_||_||_||_d|_d|_t |_ d|_ d|id|id|id|idd|idd|idddd d d d d d d d ddddddd dd dddddddddddddddddd dd!d"d#d$d%d&d'd(d)d*d*dd*dd*d+d*d,d-d+d.dd/dg/|_ |i i tÉydtd0d1É}xD|iÉD]6}|id.É}|djo|i i|Éq∞q∞W|iÉWnnXg} |id2joûxé|i D]É} t| É|ijo| |i } n9t| É|ijo"| |i|it| É} n| | jo| i| ÉqqW| |_ nd3S(4s# Primitive that cycles through a library of "bad" strings. @type value: String @param value: Default string value @type size: Integer @param size: (Optional, def=-1) Static size of this field, leave -1 for dynamic. @type padding: Character @param padding: (Optional, def="\x00") Value to use as padding to fill static field size. @type encoding: String @param encoding: (Optonal, def="ascii") String encoding, ex: utf_16_le for Microsoft Unicode. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive RWRiii ids˛s/.:/RKiàts/.../s)/.../.../.../.../.../.../.../.../.../.../s//../../../../../../../../../../../../etc/passwds-/../../../../../../../../../../../../boot.inis'..:..:..:..:..:..:..:..:..:..:..:..:..:s\\*s\\?\s/\s/.s!@#$%%^#$%#$@#$%$$@#$%^^**(()s%01%02%03%04%0a%0d%0aADSFs%01%02%03@%04%0a%0d%0aADSFs/%00/s%00/s%00s%u0000s%niÙs"%n"s%ss"%s"s|touch /tmp/SULLEYs;touch /tmp/SULLEY;s|notepads ;notepad;s notepad s 1;SELECT%20*s 'sqlattempt1s (sqlattempt2)sOR%201=1sfi≠æÔiËi'RSs s<>s .fuzz_stringstriˇˇˇˇN(R R tsizetpaddingtencodingRR1R2R RRRRtextendREtopent readlinestrstripR3tcloseR( R R R[R\R]RR1tfht fuzz_stringtunique_mutantstmutant((s+/pentest/voiper/sulley/sulley/primitives.pyR æsû               " cCs?y"t|iÉi|iÉ|_Wn|i|_nX|iS(s^ Render the primitive, encode the string according to the specified encoding. (R7R tencodeR]R (R ((s+/pentest/voiper/sulley/sulley/primitives.pyRAs "N(RRRRR R(((s+/pentest/voiper/sulley/sulley/primitives.pyRWºsÉt bit_fieldc BsSeZdddeeededÑZdÑZdÑZdddÑZdÑZ RS(R-tbinaryc  Cs«t|Étjpt|ÉtjptÇt|Étjpt|ÉtjptÇ||_|_| tjo(t|iÉ|_t|iÉ|_n||_||_ ||_ ||_ ||_ ||_ ||_| |_| |_d|_t|_g|_d|_|i d jo|id|É|_ nt|i Étjpt|i ÉtjptÇ|i o1x√td|i ÉD]} |ii| ÉqéWnñ|idÉ|i|i dÉ|i|i dÉ|i|i dÉ|i|i dÉ|i|i dÉ|i|i d É|i|i Éyxtd d É} xX| iÉD]J} yt| dÉ} Wn q`nX| |i jo|ii| Éq`q`W| iÉWnnXd S( s 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_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive @type hex_vals: Boolean @param hex_vals: (Optional, def=False) Only applicable when format="ascii". Return the hex representation of the fuzz values RiRMiiiiii s .fuzz_intsRZN(R6tinttlongR8R R Rthextwidthtmax_numtendiantformattsignedt full_rangeRR1thex_valsR RRRRRt to_decimalR@R3tadd_integer_boundariesR_R`Rb(R R RmRnRoRpRqRrRR1RsRCRctfuzz_int((s+/pentest/voiper/sulley/sulley/primitives.pyR Qs^--              3   cCsqxjtddÉD]Y}||}d|jo |ijno(||ijo|ii|ÉqiqqWdS(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 iˆˇˇˇi iN(R@RnRR3(R tintegerRCtcase((s+/pentest/voiper/sulley/sulley/primitives.pyRu´s  !c Cs,|i}|i}|i|ijo>|itjo.t|idÉ|_t|idÉ|_n|idjo¯d}d}|iddjo||iÉ7}n&dd|id}||iÉ7}xVtt |ÉdÉD]>}|d|d|d!}|t i d|i |ÉÉ7}q„W|i djo)t|É}|iÉdi|É}n||_n©|io^|iÉdd joG|i dd |id É}|i|@}||}d ||_nd |i|_|itjo tt|iÉÉd |_n||_||_|iS( s' Render the primitive. iRiRiit0RLR-RMis%di(R R RsRRjRpRmt to_binaryR@RtstructtpackRtRotlisttreversetjoinR RqRl( R ttmp_valt tmp_orig_valt bit_streamR RCtchunkRnR9((s+/pentest/voiper/sulley/sulley/primitives.pyRºs@  ##   !     cscàdjo |iân|djo |i}nditáfdÜt|dddÉÉÉS(s@ 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 Rcstà|?d@ÉS(i(R7(tx(tnumber(s+/pentest/voiper/sulley/sulley/primitives.pyt<lambda>siiˇˇˇˇN(RR RmRtmaptrange(R RÖt bit_count((RÖs+/pentest/voiper/sulley/sulley/primitives.pyRzs    cCs t|dÉS(s¬ Convert a binary string to a decimal number. @type binary: String @param binary: Binary string @rtype: Integer @return: Converted bit string i(Rj(R Ri((s+/pentest/voiper/sulley/sulley/primitives.pyRts N( RRRRRR RuRRzRt(((s+/pentest/voiper/sulley/sulley/primitives.pyRhPs !Z  KtbytecBs&eZddeeededÑZRS(R-Ric Csod|_t|Éttgjoti|d|Éd}nti||dd|||||||É dS(NRäRLii( R2R6RjRkR{tunpackRhR R( R R RoRpRqRrRR1Rs((s+/pentest/voiper/sulley/sulley/primitives.pyR -s N(RRRRRR (((s+/pentest/voiper/sulley/sulley/primitives.pyRä,stwordcBs&eZddeeededÑZRS(R-Ric Csod|_t|Éttgjoti|d|Éd}nti||dd|||||||É dS(NRåtHii( R2R6RjRkR{RãRhR R( R R RoRpRqRrRR1Rs((s+/pentest/voiper/sulley/sulley/primitives.pyR 7s N(RRRRRR (((s+/pentest/voiper/sulley/sulley/primitives.pyRå6stdwordcBs&eZddeeededÑZRS(R-Ric Csod|_t|Éttgjoti|d|Éd}nti||dd|||||||É dS(NRétLii ( R2R6RjRkR{RãRhR R( R R RoRpRqRrRR1Rs((s+/pentest/voiper/sulley/sulley/primitives.pyR As N(RRRRRR (((s+/pentest/voiper/sulley/sulley/primitives.pyRé@stqwordcBs&eZddeeededÑZRS(R-Ric Csod|_t|Éttgjoti|d|Éd}nti||dd|||||||É dS(NRêtQii@( R2R6RjRkR{RãRhR R( R R RoRpRqRrRR1Rs((s+/pentest/voiper/sulley/sulley/primitives.pyR Ks N(RRRRRR (((s+/pentest/voiper/sulley/sulley/primitives.pyRêJs(R>R{RWtostobjectRRR4R:RDRERJRVRhRäRåRéRê(((s+/pentest/voiper/sulley/sulley/primitives.pyt<module>s"    YVCL+  3î‹  
23,257
Python
.py
276
79.246377
2,393
0.40993
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,904
__init__.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/__init__.pyc
—Ú ‚–øMc@sÖddkZddkZddkZddkZddkZddkZddkZdZdZ ddÑZ dÑZ dÑZ dÑZdÑZd ÑZddddgd d ÑZdd ÑZd ddddÑZddddeddÑZdddeededdÑZdÑZddÑZeddÑZdÑZdhdÑZdeddÑZddÑZdddeddÑZddeeedd ÑZ ddeeedd!ÑZ!ddeeeded"ÑZ"ddeeeded#ÑZ#ddeeedd$ÑZ$eZ%Z&Z'eZ(e Z)Z*e!Z+e"Z,e#Z-Z.e$Z/eZ0d%ÑZ1d&ÑZ2d'ÑZ3d(ÑZ4e1e5d)ÉZ6e1e5d*ÉZ7e1e5d+ÉZ8e1e5d,ÉZ9e1e5d-ÉZ:e1e5d-ÉZ;d.ÑZ<e1e5d/ÉZ=e1e5d0ÉZ>d1ÑZ?e1e5d2ÉZ@e1e5d2ÉZAe1e5d2ÉZBe1e5d2ÉZCe1e5d2ÉZDe1e5d2ÉZEe1e5d2ÉZFe1e5d2ÉZGe1e5d2ÉZHe1e5d2ÉZIe1e5d2ÉZJe1e5d2ÉZKe1e5d2ÉZLe1e5d2ÉZMe1e5d2ÉZNe1e5d2ÉZOe1e5d2ÉZPe1e5d2ÉZQe1e5d2ÉZRe1e5d2ÉZSe1e5d2ÉZTe1e5d2ÉZUe1e5d2ÉZVe1e5d2ÉZWe1e5d2ÉZXdd3ÑZYdS(4iˇˇˇˇNt>t<cCsN|ptiSt|Étii|Éptid|ÉÇnti|S(s7 Return the request with the specified name or the current request if name is not specified. Use this to switch from global function style request manipulation to direct object manipulation. Example:: req = s_get("HTTP BASIC") print req.num_mutations() The selected request is also set as the default current. (ie: s_switch(name) is implied). @type name: String @param name: (Optional, def=None) Name of request to return or current request if name is None. @rtype: blocks.request @return: The requested request. sblocks.REQUESTS NOT FOUND: %s(tblockstCURRENTts_switchtREQUESTSthas_keytsexterror(tname((s)/pentest/voiper/sulley/sulley/__init__.pyts_gets  cCsTtii|Éotid|ÉÇnti|Éti|<ti|t_dS(sfl Initialize a new block request. All blocks / primitives generated after this call apply to the named request. Use s_switch() to jump between factories. @type name: String @param name: Name of request s"blocks.REQUESTS ALREADY EXISTS: %sN(RRRRRtrequestR(R ((s)/pentest/voiper/sulley/sulley/__init__.pyt s_initialize.s cCs tiiÉS(sı Mutate the current request and return False if mutations are exhausted, in which case the request has been reverted back to its normal form. @rtype: Boolean @return: True on mutation success, False if mutations exhausted. (RRtmutate(((s)/pentest/voiper/sulley/sulley/__init__.pyts_mutate>s cCs tiiÉS(sî Determine the number of repetitions we will be making. @rtype: Integer @return: Number of mutated forms this primitive can take. (RRt num_mutations(((s)/pentest/voiper/sulley/sulley/__init__.pyts_num_mutationsJscCs tiiÉS(s| Render out and return the entire contents of the current request. @rtype: Raw @return: Rendered contents (RRtrender(((s)/pentest/voiper/sulley/sulley/__init__.pyts_renderUscCs>tii|Éptid|ÉÇnti|t_dS(s~ Change the currect request to the one specified by "name". @type name: String @param name: Name of request sblocks.REQUESTS NOT FOUND: %sN(RRRRRR(R ((s)/pentest/voiper/sulley/sulley/__init__.pyR`ss==c Cs;ti|ti||||||É}tii|ÉtS(s´ Open a new block under the current request. This routine always returns True so you can make your fuzzer pretty with indenting:: if s_block_start("header"): s_static("\x00\x01") if s_block_start("body"): ... @type name: String @param name: Name of block being opened @type group: String @param group: (Optional, def=None) Name of group to associate this block with @type encoder: Function Pointer @param encoder: (Optional, def=None) Optional pointer to a function to pass rendered data to prior to return @type dep: String @param dep: (Optional, def=None) Optional primitive whose specific value this block is dependant on @type dep_value: Mixed @param dep_value: (Optional, def=None) Value that field "dep" must contain for block to be rendered @type dep_values: List of Mixed Types @param dep_values: (Optional, def=[]) Values that field "dep" may contain for block to be rendered @type dep_compare: String @param dep_compare: (Optional, def="==") Comparison method to use on dependency (==, !=, >, >=, <, <=) (RtblockRtpushtTrue(R tgrouptencodertdept dep_valuet dep_valuest dep_compareR((s)/pentest/voiper/sulley/sulley/__init__.pyt s_block_startrs'cCstiiÉdS(s’ Close the last opened block. Optionally specify the name of the block being closed (purely for aesthetic purposes). @type name: String @param name: (Optional, def=None) Name of block to closed. N(RRtpop(R ((s)/pentest/voiper/sulley/sulley/__init__.pyt s_block_endístcrc32icCs[|tiijotidÉÇnti|ti||||É}tii|ÉdS(sƒ Create a checksum block bound to the block with the specified name. You *can not* create a checksum for any currently open blocks. @type block_name: String @param block_name: Name of block to apply sizer to @type algorithm: String @param algorithm: (Optional, def=crc32) Checksum algorithm to use. (crc32, adler32, md5, sha1) @type length: Integer @param length: (Optional, def=0) Length of checksum, specify 0 to auto-calculate @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type name: String @param name: Name of this checksum field s9CAN N0T ADD A CHECKSUM FOR A BLOCK CURRENTLY IN THE STACKN(RRt block_stackRRtchecksumR(t block_namet algorithmtlengthtendianR R!((s)/pentest/voiper/sulley/sulley/__init__.pyt s_checksumùs!ic Cs;ti|ti||||||É}tii|ÉdS(su Repeat the rendered contents of the specified block cycling from min_reps to max_reps counting by step. By default renders to nothing. This block modifier is useful for fuzzing overflows in table entries. This block modifier MUST come after the block it is being applied to. @see: Aliases: s_repeater() @type block_name: String @param block_name: Name of block to apply sizer to @type min_reps: Integer @param min_reps: (Optional, def=0) Minimum number of block repetitions @type max_reps: Integer @param max_reps: (Optional, def=None) Maximum number of block repetitions @type step: Integer @param step: (Optional, def=1) Step count between min and max reps @type variable: Sulley Integer Primitive @param variable: (Optional, def=None) An integer primitive which will specify the number of repitions @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive N(RtrepeatRR(R"tmin_repstmax_repststeptvariabletfuzzableR R'((s)/pentest/voiper/sulley/sulley/__init__.pyts_repeat∂s'itbinaryc Csg|tiijotidÉÇnti|ti||||||||É } tii| ÉdS(s≠ Create a sizer block bound to the block with the specified name. You *can not* create a sizer for any currently open blocks. @see: Aliases: s_sizer() @type block_name: String @param block_name: Name of block to apply sizer to @type length: Integer @param length: (Optional, def=4) Length of sizer @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type inclusive: Boolean @param inclusive: (Optional, def=False) Should the sizer count its own length? @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type math: Function @param math: (Optional, def=None) Apply the mathematical operations defined in this function to the size @type fuzzable: Boolean @param fuzzable: (Optional, def=False) Enable/disable fuzzing of this sizer @type name: String @param name: Name of this sizer field s5CAN NOT ADD A SIZE FOR A BLOCK CURRENTLY IN THE STACKN(RRR RRtsizeR( R"R$R%tformatt inclusivetsignedtmathR,R R/((s)/pentest/voiper/sulley/sulley/__init__.pyts_size“s-cCsDtiii|Éptid|ÉÇn|tii|_dS(s· Update the value of the named primitive in the currently open request. @type name: String @param name: Name of object whose value we wish to update @type value: Mixed @param value: Updated value s1NO OBJECT WITH NAME '%s' FOUND IN CURRENT REQUESTN(RRtnamesRRRtvalue(R R6((s)/pentest/voiper/sulley/sulley/__init__.pyts_updateıs cCsÏ|}|iddÉ}|iddÉ}|iddÉ}|iddÉ}|iddÉ}|iddÉ}|iddÉ}d}x9|o1|d }|d }|tt|d ÉÉ7}qçWti||É}tii|Éd S( s0 Parse a variable format binary string into a static value and push it onto the current block stack. @type value: String @param value: Variable format binary string @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive t ts s s t,t0xs\xiiN(treplacetchrtintt primitiveststaticRRR(R6R tparsedtpairR@((s)/pentest/voiper/sulley/sulley/__init__.pyts_binary s   cCs)ti|||É}tii|ÉdS(sk Push a delimiter onto the current block stack. @type value: Character @param value: Original value @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive N(R?tdelimRRR(R6R,R RD((s)/pentest/voiper/sulley/sulley/__init__.pyts_delim(s cCs&ti||É}tii|ÉdS(sı This primitive represents a list of static values, stepping through each one on mutation. You can tie a block to a group primitive to specify that the block should cycle through all possible mutations for *each* value within the group. The group primitive is useful for example for representing a list of valid opcodes. @type name: String @param name: Name of group @type values: List or raw data @param values: List of possible raw values this group can take. N(R?RRRR(R tvaluesR((s)/pentest/voiper/sulley/sulley/__init__.pyts_group8s cCsÄdttiiÉ}tii|Éptid|ÉÇnti||ti||É}tii |Étii ÉdS(s; Legos are pre-built blocks... XXX finish this doc s LEGO_%08xsINVALID LEGO TYPE SPECIFIED: %sN( tlenRRR5tlegostBINRRRRR(t lego_typeR6toptionsR tlego((s)/pentest/voiper/sulley/sulley/__init__.pyts_legoHs icCs2ti||||||É}tii|ÉdS(s? Generate a random chunk of data while maintaining a copy of the original. A random length range can be specified. For a static length, set min/max length to be the same. @type value: Raw @param value: Original value @type min_length: Integer @param min_length: Minimum length of random block @type max_length: Integer @param max_length: Maximum length of random block @type num_mutations: Integer @param num_mutations: (Optional, def=25) Number of mutations to make before reverting to default @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive N(R?t random_dataRRR(R6t min_lengtht max_lengthRR,R trandom((s)/pentest/voiper/sulley/sulley/__init__.pyts_random[scCs&ti||É}tii|ÉdS(s! Push a static value onto the current block stack. @see: Aliases: s_dunno(), s_raw(), s_unknown() @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 N(R?R@RRR(R6R R@((s)/pentest/voiper/sulley/sulley/__init__.pyts_staticrs ttasciicCs2ti||||||É}tii|ÉdS(s› Push a string onto the current block stack. @type value: String @param value: Default string value @type size: Integer @param size: (Optional, def=-1) Static size of this field, leave -1 for dynamic. @type padding: Character @param padding: (Optional, def="\x00") Value to use as padding to fill static field size. @type encoding: String @param encoding: (Optonal, def="ascii") String encoding, ex: utf_16_le for Microsoft Unicode. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive N(R?tstringRRR(R6R/tpaddingtencodingR,R ts((s)/pentest/voiper/sulley/sulley/__init__.pyts_stringÇsc Cs8ti||||||||É}tii|ÉdS(s Push a variable length bit field onto the current block stack. @see: Aliases: s_bit(), s_bits() @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_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive N(R?t bit_fieldRRR( R6twidthR%R0R2t full_rangeR,R R\((s)/pentest/voiper/sulley/sulley/__init__.pyt s_bit_fieldòs$cCs5ti|||||||É}tii|ÉdS(sÆ Push a byte onto the current block stack. @see: Aliases: s_char() @type value: Integer @param value: Default integer value @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive N(R?tbyteRRR(R6R%R0R2R^R,R R`((s)/pentest/voiper/sulley/sulley/__init__.pyts_byte¥s!c Cs8ti||||||||É}tii|ÉdS(sQ Push a word onto the current block stack. @see: Aliases: s_short() @type value: Integer @param value: Default integer value @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive @type hex_vals: Boolean @param hex_vals: (Optional, def=False) Only applicable when format="ascii". Return the hex representation of the fuzz values N(R?twordRRR( R6R%R0R2R^R,R thex_valsRb((s)/pentest/voiper/sulley/sulley/__init__.pyts_wordŒs$c Cs8ti||||||||É}tii|ÉdS(s` Push a double word onto the current block stack. @see: Aliases: s_long(), s_int() @type value: Integer @param value: Default integer value @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive @type hex_vals: Boolean @param hex_vals: (Optional, def=False) Only applicable when format="ascii". Return the hex representation of the fuzz values N(R?tdwordRRR( R6R%R0R2R^R,R RcRe((s)/pentest/voiper/sulley/sulley/__init__.pyts_dwordÍs$cCs5ti|||||||É}tii|ÉdS(sµ Push a quad word onto the current block stack. @see: Aliases: s_double() @type value: Integer @param value: Default integer value @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive N(R?tqwordRRR(R6R%R0R2R^R,R Rg((s)/pentest/voiper/sulley/sulley/__init__.pyts_qwords!csááfdÜ}|S(Ncsàà|ÉÇdS(N((tx(tmsgtargument(s)/pentest/voiper/sulley/sulley/__init__.pyt_/s((RkRjRl((RjRks)/pentest/voiper/sulley/sulley/__init__.pyt custom_raise.scCst|dtÉS(R%(ts_longt LITTLE_ENDIAN(Ri((s)/pentest/voiper/sulley/sulley/__init__.pyt<lambda>3scCst|dtÉS(R%(ts_shortRo(Ri((s)/pentest/voiper/sulley/sulley/__init__.pyRp4scCst|dtÉS(R%(Rnt BIG_ENDIAN(Ri((s)/pentest/voiper/sulley/sulley/__init__.pyRp5ssMNotImplementedError: s_string_lf is not currently implemented, arguments weresQNotImplementedError: s_string_or_env is not currently implemented, arguments weresQNotImplementedError: s_string_repeat is not currently implemented, arguments weresSNotImplementedError: s_string_variable is not currently implemented, arguments weresTNotImplementedError: s_string_variables is not currently implemented, arguments werecCst|ddÉS(RYt utf_16_le(R[(Ri((s)/pentest/voiper/sulley/sulley/__init__.pyRp<ssVNotImplementedError: s_unistring_variable is not currently implemented, arguments weresOLegoNotUtilizedError: XDR strings are available in the XDR lego, arguments werecCst|ÉtdÉdS(NRU(R[RT(Ri((s)/pentest/voiper/sulley/sulley/__init__.pyt s_cstring@s sSSizerNotUtilizedError: Use the s_size primitive for including sizes, arguments werecCsMd}}x∏|D]∞}|ddjoq|d7}xL|D]D}t|Édjo!t|Édjo||7}q9|d7}q9W|d|7}d}n|d t|É7}||7}|d 7}qW|d}|djo|d d|d7}nxL|D]D}t|Édjo!t|Édjo||7}q˝|d7}q˝W|d S( sB Return the hex dump of the supplied data starting at the offset address specified. @type data: Raw @param data: Data to show hex dump of @type addr: Integer @param addr: (Optional, def=0) Offset to start displaying hex dump addresses from @rtype: String @return: Hex dump of raw data R9iiR8i i~t.s %04x: s%02x is s (tord(tdatataddrtdumptsliceR`tchart remainder((s)/pentest/voiper/sulley/sulley/__init__.pyt s_hex_dumpds0  &    &(Zt sulley.blockstsulleyt sulley.legost sulley.pedrpctsulley.primitivest sulley.sextsulley.sessionst sulley.utilsRrRotNoneR R RRRRRRR&RR-tFalseR4R7RCRERGRNRSRTR[R_RaRdRfRhts_dunnots_rawt s_unknownts_sizerts_bitts_bitsts_charRqRnts_intts_doublet s_repeaterRmt s_intelwordts_intelhalfwordt s_bigwordt ValueErrort s_string_lfts_string_or_envts_string_repeatts_string_variablets_string_variablests_binary_repeatt s_unistringts_unistring_variablet s_xdr_stringRtt0s_binary_block_size_intel_halfword_plus_variablet/s_binary_block_size_halfword_bigendian_variablet+s_binary_block_size_word_bigendian_plussomet+s_binary_block_size_word_bigendian_variablet+s_binary_block_size_halfword_bigendian_multt+s_binary_block_size_intel_halfword_variablet's_binary_block_size_intel_halfword_multt's_binary_block_size_intel_halfword_plust&s_binary_block_size_halfword_bigendiant(s_binary_block_size_word_intel_mult_plust's_binary_block_size_intel_word_variablet's_binary_block_size_word_bigendian_multt$s_blocksize_unsigned_string_variablet#s_binary_block_size_intel_word_plust"s_binary_block_size_intel_halfwordt"s_binary_block_size_word_bigendiant"s_blocksize_signed_string_variablet!s_binary_block_size_byte_variablets_binary_block_size_intel_wordts_binary_block_size_byte_plusts_binary_block_size_byte_multts_blocksize_asciihex_variablets_binary_block_size_bytets_blocksize_asciihexts_blocksize_stringR}(((s)/pentest/voiper/sulley/sulley/__init__.pyt<module>s†           !#            
27,000
Python
.py
313
81.485623
1,366
0.572962
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,905
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/__init__.py
import sulley.blocks import sulley.legos import sulley.pedrpc import sulley.primitives import sulley.sex import sulley.sessions import sulley.utils BIG_ENDIAN = ">" LITTLE_ENDIAN = "<" ######################################################################################################################## ### REQUEST MANAGEMENT ######################################################################################################################## def s_get (name=None): ''' Return the request with the specified name or the current request if name is not specified. Use this to switch from global function style request manipulation to direct object manipulation. Example:: req = s_get("HTTP BASIC") print req.num_mutations() The selected request is also set as the default current. (ie: s_switch(name) is implied). @type name: String @param name: (Optional, def=None) Name of request to return or current request if name is None. @rtype: blocks.request @return: The requested request. ''' if not name: return blocks.CURRENT # ensure this gotten request is the new current. s_switch(name) if not blocks.REQUESTS.has_key(name): raise sex.error("blocks.REQUESTS NOT FOUND: %s" % name) return blocks.REQUESTS[name] def s_initialize (name): ''' Initialize a new block request. All blocks / primitives generated after this call apply to the named request. Use s_switch() to jump between factories. @type name: String @param name: Name of request ''' if blocks.REQUESTS.has_key(name): raise sex.error("blocks.REQUESTS ALREADY EXISTS: %s" % name) blocks.REQUESTS[name] = blocks.request(name) blocks.CURRENT = blocks.REQUESTS[name] def s_mutate (): ''' Mutate the current request and return False if mutations are exhausted, in which case the request has been reverted back to its normal form. @rtype: Boolean @return: True on mutation success, False if mutations exhausted. ''' return blocks.CURRENT.mutate() def s_num_mutations (): ''' Determine the number of repetitions we will be making. @rtype: Integer @return: Number of mutated forms this primitive can take. ''' return blocks.CURRENT.num_mutations() def s_render (): ''' Render out and return the entire contents of the current request. @rtype: Raw @return: Rendered contents ''' return blocks.CURRENT.render() def s_switch (name): ''' Change the currect request to the one specified by "name". @type name: String @param name: Name of request ''' if not blocks.REQUESTS.has_key(name): raise sex.error("blocks.REQUESTS NOT FOUND: %s" % name) blocks.CURRENT = blocks.REQUESTS[name] ######################################################################################################################## ### BLOCK MANAGEMENT ######################################################################################################################## def s_block_start (name, group=None, encoder=None, dep=None, dep_value=None, dep_values=[], dep_compare="=="): ''' Open a new block under the current request. This routine always returns True so you can make your fuzzer pretty with indenting:: if s_block_start("header"): s_static("\\x00\\x01") if s_block_start("body"): ... @type name: String @param name: Name of block being opened @type group: String @param group: (Optional, def=None) Name of group to associate this block with @type encoder: Function Pointer @param encoder: (Optional, def=None) Optional pointer to a function to pass rendered data to prior to return @type dep: String @param dep: (Optional, def=None) Optional primitive whose specific value this block is dependant on @type dep_value: Mixed @param dep_value: (Optional, def=None) Value that field "dep" must contain for block to be rendered @type dep_values: List of Mixed Types @param dep_values: (Optional, def=[]) Values that field "dep" may contain for block to be rendered @type dep_compare: String @param dep_compare: (Optional, def="==") Comparison method to use on dependency (==, !=, >, >=, <, <=) ''' block = blocks.block(name, blocks.CURRENT, group, encoder, dep, dep_value, dep_values, dep_compare) blocks.CURRENT.push(block) return True def s_block_end (name=None): ''' Close the last opened block. Optionally specify the name of the block being closed (purely for aesthetic purposes). @type name: String @param name: (Optional, def=None) Name of block to closed. ''' blocks.CURRENT.pop() def s_checksum (block_name, algorithm="crc32", length=0, endian="<", name=None): ''' Create a checksum block bound to the block with the specified name. You *can not* create a checksum for any currently open blocks. @type block_name: String @param block_name: Name of block to apply sizer to @type algorithm: String @param algorithm: (Optional, def=crc32) Checksum algorithm to use. (crc32, adler32, md5, sha1) @type length: Integer @param length: (Optional, def=0) Length of checksum, specify 0 to auto-calculate @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type name: String @param name: Name of this checksum field ''' # you can't add a checksum for a block currently in the stack. if block_name in blocks.CURRENT.block_stack: raise sex.error("CAN N0T ADD A CHECKSUM FOR A BLOCK CURRENTLY IN THE STACK") checksum = blocks.checksum(block_name, blocks.CURRENT, algorithm, length, endian, name) blocks.CURRENT.push(checksum) def s_repeat (block_name, min_reps=0, max_reps=None, step=1, variable=None, fuzzable=True, name=None): ''' Repeat the rendered contents of the specified block cycling from min_reps to max_reps counting by step. By default renders to nothing. This block modifier is useful for fuzzing overflows in table entries. This block modifier MUST come after the block it is being applied to. @see: Aliases: s_repeater() @type block_name: String @param block_name: Name of block to apply sizer to @type min_reps: Integer @param min_reps: (Optional, def=0) Minimum number of block repetitions @type max_reps: Integer @param max_reps: (Optional, def=None) Maximum number of block repetitions @type step: Integer @param step: (Optional, def=1) Step count between min and max reps @type variable: Sulley Integer Primitive @param variable: (Optional, def=None) An integer primitive which will specify the number of repitions @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' repeat = blocks.repeat(block_name, blocks.CURRENT, min_reps, max_reps, step, variable, fuzzable, name) blocks.CURRENT.push(repeat) def s_size (block_name, length=4, endian="<", format="binary", inclusive=False, signed=False, math=None, fuzzable=False, name=None): ''' Create a sizer block bound to the block with the specified name. You *can not* create a sizer for any currently open blocks. @see: Aliases: s_sizer() @type block_name: String @param block_name: Name of block to apply sizer to @type length: Integer @param length: (Optional, def=4) Length of sizer @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type inclusive: Boolean @param inclusive: (Optional, def=False) Should the sizer count its own length? @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type math: Function @param math: (Optional, def=None) Apply the mathematical operations defined in this function to the size @type fuzzable: Boolean @param fuzzable: (Optional, def=False) Enable/disable fuzzing of this sizer @type name: String @param name: Name of this sizer field ''' # you can't add a size for a block currently in the stack. if block_name in blocks.CURRENT.block_stack: raise sex.error("CAN NOT ADD A SIZE FOR A BLOCK CURRENTLY IN THE STACK") size = blocks.size(block_name, blocks.CURRENT, length, endian, format, inclusive, signed, math, fuzzable, name) blocks.CURRENT.push(size) def s_update (name, value): ''' Update the value of the named primitive in the currently open request. @type name: String @param name: Name of object whose value we wish to update @type value: Mixed @param value: Updated value ''' if not blocks.CURRENT.names.has_key(name): raise sex.error("NO OBJECT WITH NAME '%s' FOUND IN CURRENT REQUEST" % name) blocks.CURRENT.names[name].value = value ######################################################################################################################## ### PRIMITIVES ######################################################################################################################## def s_binary (value, name=None): ''' Parse a variable format binary string into a static value and push it onto the current block stack. @type value: String @param value: Variable format binary string @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' # parse the binary string into. parsed = value parsed = parsed.replace(" ", "") parsed = parsed.replace("\t", "") parsed = parsed.replace("\r", "") parsed = parsed.replace("\n", "") parsed = parsed.replace(",", "") parsed = parsed.replace("0x", "") parsed = parsed.replace("\\x", "") value = "" while parsed: pair = parsed[:2] parsed = parsed[2:] value += chr(int(pair, 16)) static = primitives.static(value, name) blocks.CURRENT.push(static) def s_delim (value, fuzzable=True, name=None): ''' Push a delimiter onto the current block stack. @type value: Character @param value: Original value @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' delim = primitives.delim(value, fuzzable, name) blocks.CURRENT.push(delim) def s_group (name, values): ''' This primitive represents a list of static values, stepping through each one on mutation. You can tie a block to a group primitive to specify that the block should cycle through all possible mutations for *each* value within the group. The group primitive is useful for example for representing a list of valid opcodes. @type name: String @param name: Name of group @type values: List or raw data @param values: List of possible raw values this group can take. ''' group = primitives.group(name, values) blocks.CURRENT.push(group) def s_lego (lego_type, value=None, options={}): ''' Legos are pre-built blocks... XXX finish this doc ''' # as legos are blocks they must have a name. # generate a unique name for this lego. name = "LEGO_%08x" % len(blocks.CURRENT.names) if not legos.BIN.has_key(lego_type): raise sex.error("INVALID LEGO TYPE SPECIFIED: %s" % lego_type) lego = legos.BIN[lego_type](name, blocks.CURRENT, value, options) # push the lego onto the stack and immediately pop to close the block. blocks.CURRENT.push(lego) blocks.CURRENT.pop() def s_random (value, min_length, max_length, num_mutations=25, fuzzable=True, name=None): ''' Generate a random chunk of data while maintaining a copy of the original. A random length range can be specified. For a static length, set min/max length to be the same. @type value: Raw @param value: Original value @type min_length: Integer @param min_length: Minimum length of random block @type max_length: Integer @param max_length: Maximum length of random block @type num_mutations: Integer @param num_mutations: (Optional, def=25) Number of mutations to make before reverting to default @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' random = primitives.random_data(value, min_length, max_length, num_mutations, fuzzable, name) blocks.CURRENT.push(random) def s_static (value, name=None): ''' Push a static value onto the current block stack. @see: Aliases: s_dunno(), s_raw(), s_unknown() @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 ''' static = primitives.static(value, name) blocks.CURRENT.push(static) def s_string (value, size=-1, padding="\x00", encoding="ascii", fuzzable=True, name=None): ''' Push a string onto the current block stack. @type value: String @param value: Default string value @type size: Integer @param size: (Optional, def=-1) Static size of this field, leave -1 for dynamic. @type padding: Character @param padding: (Optional, def="\\x00") Value to use as padding to fill static field size. @type encoding: String @param encoding: (Optonal, def="ascii") String encoding, ex: utf_16_le for Microsoft Unicode. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' s = primitives.string(value, size, padding, encoding, fuzzable, name) blocks.CURRENT.push(s) def s_bit_field (value, width, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None): ''' Push a variable length bit field onto the current block stack. @see: Aliases: s_bit(), s_bits() @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_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' bit_field = primitives.bit_field(value, width, endian, format, signed, full_range, fuzzable, name) blocks.CURRENT.push(bit_field) def s_byte (value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None): ''' Push a byte onto the current block stack. @see: Aliases: s_char() @type value: Integer @param value: Default integer value @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' byte = primitives.byte(value, endian, format, signed, full_range, fuzzable, name) blocks.CURRENT.push(byte) def s_word (value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None, hex_vals=False): ''' Push a word onto the current block stack. @see: Aliases: s_short() @type value: Integer @param value: Default integer value @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive @type hex_vals: Boolean @param hex_vals: (Optional, def=False) Only applicable when format="ascii". Return the hex representation of the fuzz values ''' word = primitives.word(value, endian, format, signed, full_range, fuzzable, name, hex_vals) blocks.CURRENT.push(word) def s_dword (value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None, hex_vals=False): ''' Push a double word onto the current block stack. @see: Aliases: s_long(), s_int() @type value: Integer @param value: Default integer value @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive @type hex_vals: Boolean @param hex_vals: (Optional, def=False) Only applicable when format="ascii". Return the hex representation of the fuzz values ''' dword = primitives.dword(value, endian, format, signed, full_range, fuzzable, name, hex_vals) blocks.CURRENT.push(dword) def s_qword (value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None): ''' Push a quad word onto the current block stack. @see: Aliases: s_double() @type value: Integer @param value: Default integer value @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' qword = primitives.qword(value, endian, format, signed, full_range, fuzzable, name) blocks.CURRENT.push(qword) ######################################################################################################################## ### ALIASES ######################################################################################################################## s_dunno = s_raw = s_unknown = s_static s_sizer = s_size s_bit = s_bits = s_bit_field s_char = s_byte s_short = s_word s_long = s_int = s_dword s_double = s_qword s_repeater = s_repeat ### SPIKE Aliases def custom_raise (argument, msg): def _(x): raise msg, argument(x) return _ s_intelword = lambda x: s_long(x, endian=LITTLE_ENDIAN) s_intelhalfword = lambda x: s_short(x, endian=LITTLE_ENDIAN) s_bigword = lambda x: s_long(x, endian=BIG_ENDIAN) s_string_lf = custom_raise(ValueError, "NotImplementedError: s_string_lf is not currently implemented, arguments were") s_string_or_env = custom_raise(ValueError, "NotImplementedError: s_string_or_env is not currently implemented, arguments were") s_string_repeat = custom_raise(ValueError, "NotImplementedError: s_string_repeat is not currently implemented, arguments were") s_string_variable = custom_raise(ValueError, "NotImplementedError: s_string_variable is not currently implemented, arguments were") s_string_variables = custom_raise(ValueError, "NotImplementedError: s_string_variables is not currently implemented, arguments were") s_binary_repeat = custom_raise(ValueError, "NotImplementedError: s_string_variables is not currently implemented, arguments were") s_unistring = lambda x: s_string(x, encoding="utf_16_le") s_unistring_variable = custom_raise(ValueError, "NotImplementedError: s_unistring_variable is not currently implemented, arguments were") s_xdr_string = custom_raise(ValueError, "LegoNotUtilizedError: XDR strings are available in the XDR lego, arguments were") def s_cstring (x): s_string(x) s_static("\x00") s_binary_block_size_intel_halfword_plus_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_halfword_bigendian_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_word_bigendian_plussome = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_word_bigendian_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_halfword_bigendian_mult = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_intel_halfword_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_intel_halfword_mult = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_intel_halfword_plus = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_halfword_bigendian = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_word_intel_mult_plus = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_intel_word_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_word_bigendian_mult = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_blocksize_unsigned_string_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_intel_word_plus = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_intel_halfword = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_word_bigendian = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_blocksize_signed_string_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_byte_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_intel_word = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_byte_plus = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_byte_mult = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_blocksize_asciihex_variable = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_binary_block_size_byte = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_blocksize_asciihex = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") s_blocksize_string = custom_raise(ValueError, "SizerNotUtilizedError: Use the s_size primitive for including sizes, arguments were") ######################################################################################################################## ### MISC ######################################################################################################################## def s_hex_dump (data, addr=0): ''' Return the hex dump of the supplied data starting at the offset address specified. @type data: Raw @param data: Data to show hex dump of @type addr: Integer @param addr: (Optional, def=0) Offset to start displaying hex dump addresses from @rtype: String @return: Hex dump of raw data ''' dump = slice = "" for byte in data: if addr % 16 == 0: dump += " " for char in slice: if ord(char) >= 32 and ord(char) <= 126: dump += char else: dump += "." dump += "\n%04x: " % addr slice = "" dump += "%02x " % ord(byte) slice += byte addr += 1 remainder = addr % 16 if remainder != 0: dump += " " * (16 - remainder) + " " for char in slice: if ord(char) >= 32 and ord(char) <= 126: dump += char else: dump += "." return dump + "\n"
28,553
Python
.py
507
51.357002
162
0.658793
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,906
blocks.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/blocks.pyc
—Ú ‚–øMc @sΩddkZddkZddkZddkZddkZddkZhZdZdei fdÑÉYZ dd dÑÉYZ dd dÑÉYZ ddd ÑÉYZ d dd ÑÉYZdS(iˇˇˇˇNtrequestcBsSeZdÑZdÑZdÑZdÑZdÑZdÑZdÑZddÑZ RS( cCsg||_||_g|_g|_h|_h|_h|_d|_d|_d|_ d|_ dS(s0 Top level container instantiated by s_initialize(). Can hold any block structure or primitive. This can essentially be thought of as a super-block, root-block, daddy-block or whatever other alias you prefer. @type name: String @param name: Name of this request tiN( tnametlabeltstackt block_stackt closed_blockst callbackstnamestrenderedt mutant_indextNonetmutantt sent_data(tselfR((s'/pentest/voiper/sulley/sulley/blocks.pyt__init__s          cCswt}xP|iD]E}|io5|iÉo(t}t|tÉp ||_nPqqW|o|id7_n|S(Ni( tFalseRtfuzzabletmutatetTruet isinstancetblockR R (Rtmutatedtitem((s'/pentest/voiper/sulley/sulley/blocks.pyR's   cCs<d}x/|iD]$}|io||iÉ7}qqW|S(s§ Determine the number of repetitions we will be making. @rtype: Integer @return: Number of mutated forms this primitive can take. i(RRt num_mutations(RRR((s'/pentest/voiper/sulley/sulley/blocks.pyR9s   cCs.|iptidÉÇn|iiÉdS(sS The last open block was closed, so pop it off of the block stack. sBLOCK STACK OUT OF SYNCN(Rtsexterrortpop(R((s'/pentest/voiper/sulley/sulley/blocks.pyRJs cCsªt|dÉoQ|ioG|i|iiÉjotid|iÉÇn||i|i<n|ip|ii|Én|idi |Ét |t Éo|ii|ÉndS(sµ Push an item into the block structure. If no block is open, the item goes onto the request stack. otherwise, the item goes onto the last open blocks stack. RsBLOCK NAME ALREADY EXISTS: %siˇˇˇˇN( thasattrRRtkeysRRRRtappendtpushRR(RR((s'/pentest/voiper/sulley/sulley/blocks.pyRUs cCsª|io!tid|idiÉÇnx|iD]}|iÉq5Wx9|iiÉD](}x|i|D]}|iÉqmWqYWd|_x#|iD]}|i|i7_qòW|iS(NsUNCLOSED BLOCK: %siˇˇˇˇR( RRRRRtrenderRRR (RRtkey((s'/pentest/voiper/sulley/sulley/blocks.pyR os !   cCsBd|_h|_x)|iD]}|io|iÉqqWdS(sS Reset every block and primitives mutant state under this request. iN(R RRRtreset(RR((s'/pentest/voiper/sulley/sulley/blocks.pyR"Üs     ccsd|p |i}nxI|D]A}t|tÉo&x(|i|iÉD] }|VqDWq|VqWdS(s´ Recursively walk through and yield every primitive and block on the request stack. @rtype: Sulley Primitives @return: Sulley Primitives N(RRRtwalk(RRR((s'/pentest/voiper/sulley/sulley/blocks.pyR#ìs  N( t__name__t __module__RRRRRR R"R R#(((s'/pentest/voiper/sulley/sulley/blocks.pyRs      RcBsPeZddddgddÑZdÑZdÑZdÑZdÑZdÑZRS(s==c CsÇ||_||_||_||_||_||_||_||_g|_d|_ t |_ d|_ t |_d|_dS(sò The basic building block. Can contain primitives, sizers, checksums or other blocks. @type name: String @param name: Name of the new block @type request: s_request @param request: Request this block belongs to @type group: String @param group: (Optional, def=None) Name of group to associate this block with @type encoder: Function Pointer @param encoder: (Optional, def=None) Optional pointer to a function to pass rendered data to prior to return @type dep: String @param dep: (Optional, def=None) Optional primitive whose specific value this block is dependant on @type dep_value: Mixed @param dep_value: (Optional, def=None) Value that field "dep" must contain for block to be rendered @type dep_values: List of Mixed Types @param dep_values: (Optional, def=[]) Values that field "dep" may contain for block to be rendered @type dep_compare: String @param dep_compare: (Optional, def="==") Comparison method to apply to dependency (==, !=, >, >=, <, <=) RiN(RRtgrouptencodertdept dep_valuet dep_valuest dep_compareRR RRt group_idxRt fuzz_completeR ( RRRR&R'R(R)R*R+((s'/pentest/voiper/sulley/sulley/blocks.pyR©s             c CsËt}|iotS|io£|ii|iiÉ}|ii|ii|i|ii|i_xS|i D]H}|i o8|i Éo+t }t |tÉp||i_nPqoqoW|p¸|id7_|i|jo*|ii|ii|ii|i_qæ|ii|ii|i|ii|i_x)|i D]}|i o|iÉqBqBWxW|i D]H}|i o8|i Éo+t }t |tÉp||i_nPqnqnWqnWxS|i D]H}|i o8|i Éo+t }t |tÉp||i_nPqÃqÃW|oR|ioH|io!|id|ii|i_qq|i|ii|i_n|pAt |_|io*|ii|ii|ii|i_qπn|o$t |tÉp||i_q‰n|S(Nii(RR-R&RRRtvaluesR,tvalueRRRRRRR toriginal_valueR"R(R*R)(RRt group_countR((s'/pentest/voiper/sulley/sulley/blocks.pyR–s`  -  *-      !  .cCsjd}x/|iD]$}|io||iÉ7}qqW|io$|t|ii|iiÉ9}n|S(s§ Determine the number of repetitions we will be making. @rtype: Integer @return: Number of mutated forms this primitive can take. i(RRRR&tlenRRR.(RRR((s'/pentest/voiper/sulley/sulley/blocks.pyR4s   $cCs|ii|ÉdS(s@ Push an arbitrary item onto this blocks stack. N(RR(RR((s'/pentest/voiper/sulley/sulley/blocks.pyRIscCs—||ii|i<|io˚|idjou|io.|ii|ii|ijod|_dS|i o.|ii|ii|i jod|_dSn|idjoj|io.|ii|ii|ijod|_dS|ii|ii|i jod|_dSn|idjo.|i |ii|iijod|_dS|idjo.|i |ii|iijod|_dS|idjo.|i |ii|iijod|_dS|idjo.|i |ii|iijod|_dSnx|i D]}|i Éq"Wd|_x#|i D]}|i|i7_qIW|i o|i |iÉ|_n|ii i|iÉo,x)|ii |iD]}|i ÉqµWndS( sÄ Step through every item on this blocks stack and render it. Subsequent blocks recursively render their stacks. s==RNs!=t>s>=t<s<=(RRRR(R+R*RR/R R)RR R'Rthas_key(RR((s'/pentest/voiper/sulley/sulley/blocks.pyR QsR * +  *    0 0 0 0      cCsBt|_d|_x)|iD]}|io|iÉqqWdS(s[ Reset the primitives on this blocks stack to the starting mutation state. iN(RR-R,RRR"(RR((s'/pentest/voiper/sulley/sulley/blocks.pyR"òs     N( R$R%R RRRRR R"(((s'/pentest/voiper/sulley/sulley/blocks.pyR®s ' d   GtchecksumcBsQeZhdd6dd6dd6dd6Zdddd d ÑZd ÑZd ÑZRS( itcrc32tadler32itmd5itsha1iR4cCsÑ||_||_||_||_||_||_d|_t|_|i o-|i i |iÉo|i |i|_ndS(sU Create a checksum block bound to the block with the specified name. You *can not* create a checksm for any currently open blocks. @type block_name: String @param block_name: Name of block to apply sizer to @type request: s_request @param request: Request this block belongs to @type algorithm: String @param algorithm: (Optional, def=crc32) Checksum algorithm to use. (crc32, adler32, md5, sha1) @type length: Integer @param length: (Optional, def=0) Length of checksum, specify 0 to auto-calculate @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type name: String @param name: Name of this checksum field RN( t block_nameRt algorithmtlengthtendianRR RRtchecksum_lengthsR5(RR;RR<R=R>R((s'/pentest/voiper/sulley/sulley/blocks.pyR©s        !cCsót|iÉtjop|idjo!ti|idti|ÉÉS|idjo!ti|idti|ÉÉS|idjogt i |Éi É}|idjo=ti d|É\}}}}tid||||É}n|S|idjomt i |Éi É}|idjoCti d |É\}}}}}tid |||||É}n|St id |iÉÇn|i|ÉSd S( sÍ Calculate and return the checksum (in raw bytes) over the supplied data. @type data: Raw @param data: Rendered block data to calculate checksum over. @rtype: Raw @return: Checksum. R7tLR8R9R3s<LLLLs>LLLLR:s<LLLLLs>LLLLLs(INVALID CHECKSUM ALGORITHM SPECIFIED: %sN(ttypeR<tstrtstructtpackR>tzlibR7R8R9tdigesttunpacktshaRR(RtdataRFtatbtctdte((s'/pentest/voiper/sulley/sulley/blocks.pyR6 s& !!!"cCsôd|_|i|iijo,|ii|ii}|i|É|_nK|iii|iÉpg|ii|i<n|ii|ii|ÉdS(s^ Calculate the checksum of the specified block using the specified algorithm. RN(R R;RRR6RR5R(Rt block_data((s'/pentest/voiper/sulley/sulley/blocks.pyR ˆs N(R$R%R?R RR6R (((s'/pentest/voiper/sulley/sulley/blocks.pyR6¶s"! ,trepeatcBsVeZdZdd dd ed dÑZdÑZdÑZdÑZdÑZ dÑZ RS( s´ This block type is kind of special in that it is a hybrid between a block and a primitive (it can be fuzzed). The user does not need to be wary of this fact. iic Cso||_||_||_||_||_||_||_||_d|_d|_ |_ d|_ t |_ g|_d|_|i|iijotid|iÉÇn|idjo*|idjotid|iÉÇn|io9t|itiÉ o"|iGHtid|iÉÇn|ip&t|i|id|iÉ|_n t |_dS( s˚ Repeat the rendered contents of the specified block cycling from min_reps to max_reps counting by step. By default renders to nothing. This block modifier is useful for fuzzing overflows in table entries. This block modifier MUST come after the block it is being applied to. @type block_name: String @param block_name: Name of block to apply sizer to @type request: s_request @param request: Request this block belongs to @type min_reps: Integer @param min_reps: (Optional, def=0) Minimum number of block repetitions @type max_reps: Integer @param max_reps: (Optional, def=None) Maximum number of block repetitions @type step: Integer @param step: (Optional, def=1) Step count between min and max reps @type variable: Sulley Integer Primitive @param variable: (Optional, def=None) Repititions will be derived from this variable, disables fuzzing @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive RPRis/CAN NOT ADD REPEATER FOR NON-EXISTANT BLOCK: %ssAREPEATER FOR BLOCK %s DOES NOT HAVE A MIN/MAX OR VARIABLE BINDINGsDATTEMPT TO BIND THE REPEATER FOR BLOCK %s TO A NON INTEGER PRIMITIVEiN(R;Rtvariabletmin_repstmax_repststepRRts_typeR/R0R RR-t fuzz_libraryR RRRR Rt primitivest bit_fieldtrange( RR;RRRRSRTRQRR((s'/pentest/voiper/sulley/sulley/blocks.pyRs0              ! &cCs;|iÉ|i}t|_|iÉ|_|i|_|S(sõ Exhaust the possible mutations for this primitive. @rtype: Integer @return: The number of mutations to reach exhaustion (RR RR-R0R/(Rtnum((s'/pentest/voiper/sulley/sulley/blocks.pytexhaustLs   cCs–|ii|iiÉ|i|iijotid|iÉÇn|i|iÉjo t |_ n|i p |i o|i |_ tS|ii|i}|i|i|i|_ |id7_t S(sz Mutate the primitive by stepping through the fuzz library, return False on completion. If variable-bounding is specified then fuzzing is implicitly disabled. Instead, the render() routine will properly calculate the correct repitition and return the appropriate data. @rtype: Boolean @return: True on success, False otherwise. s,CAN NOT APPLY REPEATER TO UNCLOSED BLOCK: %si(RRR;R RRRR RRR-RR0R/RR RV(RR((s'/pentest/voiper/sulley/sulley/blocks.pyR\s   cCs t|iÉS(s§ Determine the number of repetitions we will be making. @rtype: Integer @return: Number of mutated forms this primitive can take. (R2RV(R((s'/pentest/voiper/sulley/sulley/blocks.pyRÄscCsz|i|iijotid|iÉÇn|io-|ii|i}|i|ii|_n|i|_|iS(sC Nothing fancy on render, simply return the value. s,CAN NOT APPLY REPEATER TO UNCLOSED BLOCK: %s(R;RRRRRQR R/(RR((s'/pentest/voiper/sulley/sulley/blocks.pyR ãs  cCs"t|_d|_|i|_dS(s9 Reset the fuzz state of this primitive. iN(RR-R R0R/(R((s'/pentest/voiper/sulley/sulley/blocks.pyR"ùs  N( R$R%t__doc__R RRR[RRR R"(((s'/pentest/voiper/sulley/sulley/blocks.pyRP s;  $ tsizec Bs\eZdZdddeed ed dÑZdÑZdÑZdÑZdÑZ d ÑZ RS( s´ This block type is kind of special in that it is a hybrid between a block and a primitive (it can be fuzzed). The user does not need to be wary of this fact. iR4tbinaryc Cs ||_||_||_||_||_||_||_||_| |_| |_ d|_ d|_ t i d|idd|id|id|iÉ|_ d|_|i i|_|i i|_|i i|_|i i|_|id jod Ñ|_nd S( sA Create a sizer block bound to the block with the specified name. You *can not* create a sizer for any currently open blocks. @type block_name: String @param block_name: Name of block to apply sizer to @type request: s_request @param request: Request this block belongs to @type length: Integer @param length: (Optional, def=4) Length of sizer @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type inclusive: Boolean @param inclusive: (Optional, def=False) Should the sizer count its own length? @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type math: Function @param math: (Optional, def=None) Apply the mathematical operations defined in this function to the size @type fuzzable: Boolean @param fuzzable: (Optional, def=False) Enable/disable fuzzing of this sizer @type name: String @param name: Name of this sizer field sN/AR]iiR>tformattsignedRcSs|S(((tx((s'/pentest/voiper/sulley/sulley/blocks.pyt<lambda>fisN(R;RR=R>R_t inclusiveR`tmathRRR0RURWRXR R-RVR R/R ( RR;RR=R>R_RcR`RdRR((s'/pentest/voiper/sulley/sulley/blocks.pyRÆs(            7 cCs;|iÉ|i}t|_|iÉ|_|i|_|S(sõ Exhaust the possible mutations for this primitive. @rtype: Integer @return: The number of mutations to reach exhaustion (RR RR-R0R/(RRZ((s'/pentest/voiper/sulley/sulley/blocks.pyR[·s   cCs |iiÉS(sù Wrap the mutation routine of the internal bit_field primitive. @rtype: Boolean @return: True on success, False otherwise. (RXR(R((s'/pentest/voiper/sulley/sulley/blocks.pyRÚscCs |iiÉS(s± Wrap the num_mutations routine of the internal bit_field primitive. @rtype: Integer @return: Number of mutated forms this primitive can take. (RXR(R((s'/pentest/voiper/sulley/sulley/blocks.pyR˝scCsd|_|io1|iio$|ii o|iiÉ|_n…|i|iijoh|i o |i }nd}|ii|i}|i t |iÉ|É|i_ |iiÉ|_nK|iii|iÉpg|ii|i<n|ii|ii|ÉdS(s# Render the sizer. RiN(R RRXR R-R R;RRRcR=RdR2R/RR5R(Rt self_sizeR((s'/pentest/voiper/sulley/sulley/blocks.pyR s % "cCs|iiÉdS(sM Wrap the reset routine of the internal bit_field primitive. N(RXR"(R((s'/pentest/voiper/sulley/sulley/blocks.pyR"$sN( R$R%R\RR RR[RRR R"(((s'/pentest/voiper/sulley/sulley/blocks.pyR]®s!3  (((((tpgraphRWRREthashlibRCtREQUESTSR tCURRENTtnodeRRR6RPR](((s'/pentest/voiper/sulley/sulley/blocks.pyt<module>s      ö˛eù
21,911
Python
.py
237
86.28692
674
0.437139
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,907
listen.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/listen.py
from socket import * s = socket(AF_INET, SOCK_DGRAM) s.bind(('127.0.0.1', 5060)) while 1: data = s.recvfrom(256) print data
138
Python
.py
6
19.666667
31
0.666667
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,908
sex.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/sex.py
# Sulley EXception Class class error (Exception): def __init__ (self, message): self.message = message def __str__ (self): return self.message
168
Python
.py
6
22.833333
33
0.63354
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,909
blocks.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/blocks.py
import pgraph import primitives import sex import zlib import hashlib # import md5 - deprecated - dookie #import sha - deprecated, covered by hashlib import struct REQUESTS = {} CURRENT = None ######################################################################################################################## class request (pgraph.node): def __init__ (self, name): ''' Top level container instantiated by s_initialize(). Can hold any block structure or primitive. This can essentially be thought of as a super-block, root-block, daddy-block or whatever other alias you prefer. @type name: String @param name: Name of this request ''' self.name = name self.label = name # node label for graph rendering. self.stack = [] # the request stack. self.block_stack = [] # list of open blocks, -1 is last open block. self.closed_blocks = {} # dictionary of closed blocks. self.callbacks = {} # dictionary of list of sizers / checksums that were unable to complete rendering. self.names = {} # dictionary of directly accessible primitives. self.rendered = "" # rendered block structure. self.mutant_index = 0 # current mutation index. self.mutant = None # current primitive being mutated. self.sent_data = "" # the actual data that was sent based on # callback modifications to the rendered data def mutate (self): mutated = False for item in self.stack: if item.fuzzable and item.mutate(): mutated = True if not isinstance(item, block): self.mutant = item break if mutated: self.mutant_index += 1 return mutated def num_mutations (self): ''' Determine the number of repetitions we will be making. @rtype: Integer @return: Number of mutated forms this primitive can take. ''' num_mutations = 0 for item in self.stack: if item.fuzzable: num_mutations += item.num_mutations() return num_mutations def pop (self): ''' The last open block was closed, so pop it off of the block stack. ''' if not self.block_stack: raise sex.error("BLOCK STACK OUT OF SYNC") self.block_stack.pop() def push (self, item): ''' Push an item into the block structure. If no block is open, the item goes onto the request stack. otherwise, the item goes onto the last open blocks stack. ''' # if the item has a name, add it to the internal dictionary of names. if hasattr(item, "name") and item.name: # ensure the name doesn't already exist. if item.name in self.names.keys(): raise sex.error("BLOCK NAME ALREADY EXISTS: %s" % item.name) self.names[item.name] = item # if there are no open blocks, the item gets pushed onto the request stack. # otherwise, the pushed item goes onto the stack of the last opened block. if not self.block_stack: self.stack.append(item) else: self.block_stack[-1].push(item) # add the opened block to the block stack. if isinstance(item, block): self.block_stack.append(item) def render (self): # ensure there are no open blocks lingering. if self.block_stack: raise sex.error("UNCLOSED BLOCK: %s" % self.block_stack[-1].name) # render every item in the stack. for item in self.stack: item.render() # process remaining callbacks. for key in self.callbacks.keys(): for item in self.callbacks[key]: item.render() # now collect, merge and return the rendered items. self.rendered = "" for item in self.stack: self.rendered += item.rendered return self.rendered def reset (self): ''' Reset every block and primitives mutant state under this request. ''' self.mutant_index = 1 self.closed_blocks = {} for item in self.stack: if item.fuzzable: item.reset() def walk (self, stack=None): ''' Recursively walk through and yield every primitive and block on the request stack. @rtype: Sulley Primitives @return: Sulley Primitives ''' if not stack: stack = self.stack for item in stack: # if the item is a block, step into it and continue looping. if isinstance(item, block): for item in self.walk(item.stack): yield item else: yield item ######################################################################################################################## class block: def __init__ (self, name, request, group=None, encoder=None, dep=None, dep_value=None, dep_values=[], dep_compare="=="): ''' The basic building block. Can contain primitives, sizers, checksums or other blocks. @type name: String @param name: Name of the new block @type request: s_request @param request: Request this block belongs to @type group: String @param group: (Optional, def=None) Name of group to associate this block with @type encoder: Function Pointer @param encoder: (Optional, def=None) Optional pointer to a function to pass rendered data to prior to return @type dep: String @param dep: (Optional, def=None) Optional primitive whose specific value this block is dependant on @type dep_value: Mixed @param dep_value: (Optional, def=None) Value that field "dep" must contain for block to be rendered @type dep_values: List of Mixed Types @param dep_values: (Optional, def=[]) Values that field "dep" may contain for block to be rendered @type dep_compare: String @param dep_compare: (Optional, def="==") Comparison method to apply to dependency (==, !=, >, >=, <, <=) ''' self.name = name self.request = request self.group = group self.encoder = encoder self.dep = dep self.dep_value = dep_value self.dep_values = dep_values self.dep_compare = dep_compare self.stack = [] # block item stack. self.rendered = "" # rendered block contents. self.fuzzable = True # blocks are always fuzzable because they may contain fuzzable items. self.group_idx = 0 # if this block is tied to a group, the index within that group. self.fuzz_complete = False # whether or not we are done fuzzing this block. self.mutant_index = 0 # current mutation index. def mutate (self): mutated = False # are we done with this block? if self.fuzz_complete: return False # # mutate every item on the stack for every possible group value. # if self.group: group_count = self.request.names[self.group].num_mutations() # update the group value to that at the current index. self.request.names[self.group].value = self.request.names[self.group].values[self.group_idx] # mutate every item on the stack at the current group value. for item in self.stack: if item.fuzzable and item.mutate(): mutated = True if not isinstance(item, block): self.request.mutant = item break # if the possible mutations for the stack are exhausted. if not mutated: # increment the group value index. self.group_idx += 1 # if the group values are exhausted, we are done with this block. if self.group_idx == group_count: # restore the original group value. self.request.names[self.group].value = self.request.names[self.group].original_value # otherwise continue mutating this group/block. else: # update the group value to that at the current index. self.request.names[self.group].value = self.request.names[self.group].values[self.group_idx] # this the mutate state for every item in this blocks stack. # NOT THE BLOCK ITSELF THOUGH! (hence why we didn't call self.reset()) for item in self.stack: if item.fuzzable: item.reset() # now mutate the first field in this block before continuing. # (we repeat a test case if we don't mutate something) for item in self.stack: if item.fuzzable and item.mutate(): mutated = True if not isinstance(item, block): self.request.mutant = item break # # no grouping, mutate every item on the stack once. # else: for item in self.stack: if item.fuzzable and item.mutate(): mutated = True if not isinstance(item, block): self.request.mutant = item break # if this block is dependant on another field, then manually update that fields value appropriately while we # mutate this block. we'll restore the original value of the field prior to continuing. if mutated and self.dep: # if a list of values was specified, use the first item in the list. if self.dep_values: self.request.names[self.dep].value = self.dep_values[0] # if a list of values was not specified, assume a single value is present. else: self.request.names[self.dep].value = self.dep_value # we are done mutating this block. if not mutated: self.fuzz_complete = True # if we had a dependancy, make sure we restore the original value. if self.dep: self.request.names[self.dep].value = self.request.names[self.dep].original_value if mutated: if not isinstance(item, block): self.request.mutant = item return mutated def num_mutations (self): ''' Determine the number of repetitions we will be making. @rtype: Integer @return: Number of mutated forms this primitive can take. ''' num_mutations = 0 for item in self.stack: if item.fuzzable: num_mutations += item.num_mutations() # if this block is associated with a group, then multiply out the number of possible mutations. if self.group: num_mutations *= len(self.request.names[self.group].values) return num_mutations def push (self, item): ''' Push an arbitrary item onto this blocks stack. ''' self.stack.append(item) def render (self): ''' Step through every item on this blocks stack and render it. Subsequent blocks recursively render their stacks. ''' # add the completed block to the request dictionary. self.request.closed_blocks[self.name] = self # # if this block is dependant on another field and the value is not met, render nothing. # if self.dep: if self.dep_compare == "==": if self.dep_values and self.request.names[self.dep].value not in self.dep_values: self.rendered = "" return elif not self.dep_values and self.request.names[self.dep].value != self.dep_value: self.rendered = "" return if self.dep_compare == "!=": if self.dep_values and self.request.names[self.dep].value in self.dep_values: self.rendered = "" return elif self.request.names[self.dep].value == self.dep_value: self.rendered = "" return if self.dep_compare == ">" and self.dep_value <= self.request.names[self.dep].value: self.rendered = "" return if self.dep_compare == ">=" and self.dep_value < self.request.names[self.dep].value: self.rendered = "" return if self.dep_compare == "<" and self.dep_value >= self.request.names[self.dep].value: self.rendered = "" return if self.dep_compare == "<=" and self.dep_value > self.request.names[self.dep].value: self.rendered = "" return # # otherwise, render and encode as usual. # # recursively render the items on the stack. for item in self.stack: item.render() # now collect and merge the rendered items. self.rendered = "" for item in self.stack: self.rendered += item.rendered # if an encoder was attached to this block, call it. if self.encoder: self.rendered = self.encoder(self.rendered) # the block is now closed, clear out all the entries from the request back splice dictionary. if self.request.callbacks.has_key(self.name): for item in self.request.callbacks[self.name]: item.render() def reset (self): ''' Reset the primitives on this blocks stack to the starting mutation state. ''' self.fuzz_complete = False self.group_idx = 0 for item in self.stack: if item.fuzzable: item.reset() ######################################################################################################################## class checksum: checksum_lengths = {"crc32":4, "adler32":4, "md5":16, "sha1":20} def __init__(self, block_name, request, algorithm="crc32", length=0, endian="<", name=None): ''' Create a checksum block bound to the block with the specified name. You *can not* create a checksm for any currently open blocks. @type block_name: String @param block_name: Name of block to apply sizer to @type request: s_request @param request: Request this block belongs to @type algorithm: String @param algorithm: (Optional, def=crc32) Checksum algorithm to use. (crc32, adler32, md5, sha1) @type length: Integer @param length: (Optional, def=0) Length of checksum, specify 0 to auto-calculate @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type name: String @param name: Name of this checksum field ''' self.block_name = block_name self.request = request self.algorithm = algorithm self.length = length self.endian = endian self.name = name self.rendered = "" self.fuzzable = False if not self.length and self.checksum_lengths.has_key(self.algorithm): self.length = self.checksum_lengths[self.algorithm] def checksum (self, data): ''' Calculate and return the checksum (in raw bytes) over the supplied data. @type data: Raw @param data: Rendered block data to calculate checksum over. @rtype: Raw @return: Checksum. ''' if type(self.algorithm) is str: if self.algorithm == "crc32": return struct.pack(self.endian+"L", zlib.crc32(data)) elif self.algorithm == "adler32": return struct.pack(self.endian+"L", zlib.adler32(data)) elif self.algorithm == "md5": digest = md5.md5(data).digest() # XXX - is this right? if self.endian == ">": (a, b, c, d) = struct.unpack("<LLLL", digest) digest = struct.pack(">LLLL", a, b, c, d) return digest elif self.algorithm == "sha1": digest = sha.sha(data).digest() # XXX - is this right? if self.endian == ">": (a, b, c, d, e) = struct.unpack("<LLLLL", digest) digest = struct.pack(">LLLLL", a, b, c, d, e) return digest else: raise sex.error("INVALID CHECKSUM ALGORITHM SPECIFIED: %s" % self.algorithm) else: return self.algorithm(data) def render (self): ''' Calculate the checksum of the specified block using the specified algorithm. ''' self.rendered = "" # if the target block for this sizer is already closed, render the checksum. if self.block_name in self.request.closed_blocks: block_data = self.request.closed_blocks[self.block_name].rendered self.rendered = self.checksum(block_data) # otherwise, add this checksum block to the requests callback list. else: if not self.request.callbacks.has_key(self.block_name): self.request.callbacks[self.block_name] = [] self.request.callbacks[self.block_name].append(self) ######################################################################################################################## class repeat: ''' This block type is kind of special in that it is a hybrid between a block and a primitive (it can be fuzzed). The user does not need to be wary of this fact. ''' def __init__ (self, block_name, request, min_reps=0, max_reps=None, step=1, variable=None, fuzzable=True, name=None): ''' Repeat the rendered contents of the specified block cycling from min_reps to max_reps counting by step. By default renders to nothing. This block modifier is useful for fuzzing overflows in table entries. This block modifier MUST come after the block it is being applied to. @type block_name: String @param block_name: Name of block to apply sizer to @type request: s_request @param request: Request this block belongs to @type min_reps: Integer @param min_reps: (Optional, def=0) Minimum number of block repetitions @type max_reps: Integer @param max_reps: (Optional, def=None) Maximum number of block repetitions @type step: Integer @param step: (Optional, def=1) Step count between min and max reps @type variable: Sulley Integer Primitive @param variable: (Optional, def=None) Repititions will be derived from this variable, disables fuzzing @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' self.block_name = block_name self.request = request self.variable = variable self.min_reps = min_reps self.max_reps = max_reps self.step = step self.fuzzable = fuzzable self.name = name self.s_type = 'repeat' self.value = self.original_value = "" # default to nothing! self.rendered = "" # rendered value self.fuzz_complete = False # flag if this primitive has been completely fuzzed self.fuzz_library = [] # library of static fuzz heuristics to cycle through. self.mutant_index = 0 # current mutation number # ensure the target block exists. if self.block_name not in self.request.names: raise sex.error("CAN NOT ADD REPEATER FOR NON-EXISTANT BLOCK: %s" % self.block_name) # ensure the user specified either a variable to tie this repeater to or a min/max val. if self.variable == None and self.max_reps == None: raise sex.error("REPEATER FOR BLOCK %s DOES NOT HAVE A MIN/MAX OR VARIABLE BINDING" % self.block_name) # if a variable is specified, ensure it is an integer type. if self.variable and not isinstance(self.variable, primitives.bit_field): print self.variable raise sex.error("ATTEMPT TO BIND THE REPEATER FOR BLOCK %s TO A NON INTEGER PRIMITIVE" % self.block_name) # if not binding variable was specified, propogate the fuzz library with the repetition counts. if not self.variable: self.fuzz_library = range(self.min_reps, self.max_reps + 1, self.step) # otherwise, disable fuzzing as the repitition count is determined by the variable. else: self.fuzzable = False def exhaust (self): ''' Exhaust the possible mutations for this primitive. @rtype: Integer @return: The number of mutations to reach exhaustion ''' num = self.num_mutations() - self.mutant_index self.fuzz_complete = True self.mutant_index = self.num_mutations() self.value = self.original_value return num def mutate (self): ''' Mutate the primitive by stepping through the fuzz library, return False on completion. If variable-bounding is specified then fuzzing is implicitly disabled. Instead, the render() routine will properly calculate the correct repitition and return the appropriate data. @rtype: Boolean @return: True on success, False otherwise. ''' # render the contents of the block we are repeating. self.request.names[self.block_name].render() # if the target block for this sizer is not closed, raise an exception. if self.block_name not in self.request.closed_blocks: raise sex.error("CAN NOT APPLY REPEATER TO UNCLOSED BLOCK: %s" % self.block_name) # if we've run out of mutations, raise the completion flag. if self.mutant_index == self.num_mutations(): self.fuzz_complete = True # if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored. if not self.fuzzable or self.fuzz_complete: self.value = self.original_value return False # set the current value as a multiple of the rendered block based on the current fuzz library count. block = self.request.closed_blocks[self.block_name] self.value = block.rendered * self.fuzz_library[self.mutant_index] # increment the mutation count. self.mutant_index += 1 return True def num_mutations (self): ''' Determine the number of repetitions we will be making. @rtype: Integer @return: Number of mutated forms this primitive can take. ''' return len(self.fuzz_library) def render (self): ''' Nothing fancy on render, simply return the value. ''' # if the target block for this sizer is not closed, raise an exception. if self.block_name not in self.request.closed_blocks: raise sex.error("CAN NOT APPLY REPEATER TO UNCLOSED BLOCK: %s" % self.block_name) # if a variable-bounding was specified then set the value appropriately. if self.variable: block = self.request.closed_blocks[self.block_name] self.value = block.rendered * self.variable.value self.rendered = self.value return self.rendered def reset (self): ''' Reset the fuzz state of this primitive. ''' self.fuzz_complete = False self.mutant_index = 0 self.value = self.original_value ######################################################################################################################## class size: ''' This block type is kind of special in that it is a hybrid between a block and a primitive (it can be fuzzed). The user does not need to be wary of this fact. ''' def __init__ (self, block_name, request, length=4, endian="<", format="binary", inclusive=False, signed=False, math=None, fuzzable=False, name=None): ''' Create a sizer block bound to the block with the specified name. You *can not* create a sizer for any currently open blocks. @type block_name: String @param block_name: Name of block to apply sizer to @type request: s_request @param request: Request this block belongs to @type length: Integer @param length: (Optional, def=4) Length of sizer @type endian: Character @param endian: (Optional, def=LITTLE_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type inclusive: Boolean @param inclusive: (Optional, def=False) Should the sizer count its own length? @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type math: Function @param math: (Optional, def=None) Apply the mathematical operations defined in this function to the size @type fuzzable: Boolean @param fuzzable: (Optional, def=False) Enable/disable fuzzing of this sizer @type name: String @param name: Name of this sizer field ''' self.block_name = block_name self.request = request self.length = length self.endian = endian self.format = format self.inclusive = inclusive self.signed = signed self.math = math self.fuzzable = fuzzable self.name = name self.original_value = "N/A" # for get_primitive self.s_type = "size" # for ease of object identification self.bit_field = primitives.bit_field(0, self.length*8, endian=self.endian, format=self.format, signed=self.signed) self.rendered = "" self.fuzz_complete = self.bit_field.fuzz_complete self.fuzz_library = self.bit_field.fuzz_library self.mutant_index = self.bit_field.mutant_index self.value = self.bit_field.value if self.math == None: self.math = lambda (x): x def exhaust (self): ''' Exhaust the possible mutations for this primitive. @rtype: Integer @return: The number of mutations to reach exhaustion ''' num = self.num_mutations() - self.mutant_index self.fuzz_complete = True self.mutant_index = self.num_mutations() self.value = self.original_value return num def mutate (self): ''' Wrap the mutation routine of the internal bit_field primitive. @rtype: Boolean @return: True on success, False otherwise. ''' return self.bit_field.mutate() def num_mutations (self): ''' Wrap the num_mutations routine of the internal bit_field primitive. @rtype: Integer @return: Number of mutated forms this primitive can take. ''' return self.bit_field.num_mutations() def render (self): ''' Render the sizer. ''' self.rendered = "" # if the sizer is fuzzable and we have not yet exhausted the the possible bit field values, use the fuzz value. if self.fuzzable and self.bit_field.mutant_index and not self.bit_field.fuzz_complete: self.rendered = self.bit_field.render() # if the target block for this sizer is already closed, render the size. elif self.block_name in self.request.closed_blocks: if self.inclusive: self_size = self.length else: self_size = 0 block = self.request.closed_blocks[self.block_name] self.bit_field.value = self.math(len(block.rendered) + self_size) self.rendered = self.bit_field.render() # otherwise, add this sizer block to the requests callback list. else: if not self.request.callbacks.has_key(self.block_name): self.request.callbacks[self.block_name] = [] self.request.callbacks[self.block_name].append(self) def reset (self): ''' Wrap the reset routine of the internal bit_field primitive. ''' self.bit_field.reset()
29,857
Python
.py
607
38.215815
153
0.578293
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,910
primitives.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/primitives.py
import random import struct import string import os ######################################################################################################################## class base_primitive (object): ''' The primitive base class implements common functionality shared across most primitives. ''' def __init__ (self): self.fuzz_complete = False # this flag is raised when the mutations are exhausted. self.fuzz_library = [] # library of static fuzz heuristics to cycle through. self.fuzzable = True # flag controlling whether or not the given primitive is to be fuzzed. self.mutant_index = 0 # current mutation index into the fuzz library. self.original_value = None # original value of primitive. self.rendered = "" # rendered value of primitive. self.value = None # current value of primitive. def exhaust (self): ''' Exhaust the possible mutations for this primitive. @rtype: Integer @return: The number of mutations to reach exhaustion ''' num = self.num_mutations() - self.mutant_index self.fuzz_complete = True self.mutant_index = self.num_mutations() self.value = self.original_value return num def mutate (self): ''' Mutate the primitive by stepping through the fuzz library, return False on completion. @rtype: Boolean @return: True on success, False otherwise. ''' # if we've ran out of mutations, raise the completion flag. if self.mutant_index == self.num_mutations(): self.fuzz_complete = True # if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored. if not self.fuzzable or self.fuzz_complete: self.value = self.original_value return False # update the current value from the fuzz library. self.value = self.fuzz_library[self.mutant_index] # increment the mutation count. self.mutant_index += 1 return True def num_mutations (self): ''' Calculate and return the total number of mutations for this individual primitive. @rtype: Integer @return: Number of mutated forms this primitive can take ''' return len(self.fuzz_library) def render (self): ''' Nothing fancy on render, simply return the value. ''' self.rendered = self.value return self.rendered def reset (self): ''' Reset this primitive to the starting mutation state. ''' self.fuzz_complete = False self.mutant_index = 0 self.value = self.original_value ######################################################################################################################## class delim (base_primitive): def __init__ (self, value, fuzzable=True, name=None): ''' Represent a delimiter such as :,\r,\n, ,=,>,< etc... Mutations include repetition, substitution and exclusion. @type value: Character @param value: Original value @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' self.value = self.original_value = value self.fuzzable = fuzzable self.name = name self.s_type = "delim" # for ease of object identification self.rendered = "" # rendered value self.fuzz_complete = False # flag if this primitive has been completely fuzzed self.fuzz_library = [] # library of fuzz heuristics self.mutant_index = 0 # current mutation number # # build the library of fuzz heuristics. # # if the default delim is not blank, repeat it a bunch of times. if self.value: self.fuzz_library.append(self.value * 2) self.fuzz_library.append(self.value * 5) self.fuzz_library.append(self.value * 10) self.fuzz_library.append(self.value * 25) self.fuzz_library.append(self.value * 100) self.fuzz_library.append(self.value * 500) self.fuzz_library.append(self.value * 1000) # try ommitting the delimiter. self.fuzz_library.append("") # if the delimiter is a space, try throwing out some tabs. if self.value == " ": self.fuzz_library.append("\t") self.fuzz_library.append("\t" * 2) self.fuzz_library.append("\t" * 100) # toss in some other common delimiters: self.fuzz_library.append(" ") self.fuzz_library.append("\t") self.fuzz_library.append("\t " * 100) self.fuzz_library.append("\t\r\n" * 100) self.fuzz_library.append("!") self.fuzz_library.append("@") self.fuzz_library.append("#") self.fuzz_library.append("$") self.fuzz_library.append("%") self.fuzz_library.append("^") self.fuzz_library.append("&") self.fuzz_library.append("*") self.fuzz_library.append("(") self.fuzz_library.append(")") self.fuzz_library.append("-") self.fuzz_library.append("_") self.fuzz_library.append("+") self.fuzz_library.append("=") self.fuzz_library.append(":") self.fuzz_library.append(": " * 100) self.fuzz_library.append(":7" * 100) self.fuzz_library.append(";") self.fuzz_library.append("'") self.fuzz_library.append("\"") self.fuzz_library.append("/") self.fuzz_library.append("\\") self.fuzz_library.append("?") self.fuzz_library.append("<") self.fuzz_library.append(">") self.fuzz_library.append(".") self.fuzz_library.append(",") self.fuzz_library.append("\r") self.fuzz_library.append("\n") self.fuzz_library.append("\r\n" * 64) self.fuzz_library.append("\r\n" * 128) self.fuzz_library.append("\r\n" * 512) ######################################################################################################################## class group (base_primitive): def __init__ (self, name, values): ''' This primitive represents a list of static values, stepping through each one on mutation. You can tie a block to a group primitive to specify that the block should cycle through all possible mutations for *each* value within the group. The group primitive is useful for example for representing a list of valid opcodes. @type name: String @param name: Name of group @type values: List or raw data @param values: List of possible raw values this group can take. ''' self.name = name self.values = values self.fuzzable = True self.s_type = "group" self.value = self.values[0] self.original_value = self.values[0] self.rendered = "" self.fuzz_complete = False self.mutant_index = 1 # XXX - should start mutating at 1, since the first item is the default. right? # sanity check that values list only contains strings (or raw data) if self.values != []: for val in self.values: assert type(val) is str, "Value list may only contain strings or raw data" def mutate (self): ''' Move to the next item in the values list. @rtype: False @return: False ''' if self.mutant_index == self.num_mutations(): self.fuzz_complete = True # if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored. if not self.fuzzable or self.fuzz_complete: self.value = self.values[0] return False # step through the value list. self.value = self.values[self.mutant_index] # increment the mutation count. self.mutant_index += 1 return True def num_mutations (self): ''' Number of values in this primitive. @rtype: Integer @return: Number of values in this primitive. ''' return len(self.values) ######################################################################################################################## class random_data (base_primitive): def __init__ (self, value, min_length, max_length, max_mutations=25, fuzzable=True, name=None): ''' Generate a random chunk of data while maintaining a copy of the original. A random length range can be specified. For a static length, set min/max length to be the same. @type value: Raw @param value: Original value @type min_length: Integer @param min_length: Minimum length of random block @type max_length: Integer @param max_length: Maximum length of random block @type max_mutations: Integer @param max_mutations: (Optional, def=25) Number of mutations to make before reverting to default @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' self.value = self.original_value = str(value) self.min_length = min_length self.max_length = max_length self.max_mutations = max_mutations self.fuzzable = fuzzable self.name = name self.s_type = "random_data" # for ease of object identification self.rendered = "" # rendered value self.fuzz_complete = False # flag if this primitive has been completely fuzzed self.mutant_index = 0 # current mutation number def mutate (self): ''' Mutate the primitive value returning False on completion. @rtype: Boolean @return: True on success, False otherwise. ''' # if we've ran out of mutations, raise the completion flag. if self.mutant_index == self.num_mutations(): self.fuzz_complete = True # if fuzzing was disabled or complete, and mutate() is called, ensure the original value is restored. if not self.fuzzable or self.fuzz_complete: self.value = self.original_value return False # select a random length for this string. length = random.randint(self.min_length, self.max_length) # reset the value and generate a random string of the determined length. self.value = "" for i in xrange(length): self.value += chr(random.randint(0, 255)) # increment the mutation count. self.mutant_index += 1 return True def num_mutations (self): ''' Calculate and return the total number of mutations for this individual primitive. @rtype: Integer @return: Number of mutated forms this primitive can take ''' return self.max_mutations ######################################################################################################################## class static (base_primitive): def __init__ (self, value, name=None): ''' 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 ''' self.value = self.original_value = value self.name = name self.fuzzable = False # every primitive needs this attribute. self.mutant_index = 0 self.s_type = "static" # for ease of object identification self.rendered = "" self.fuzz_complete = True def mutate (self): ''' Do nothing. @rtype: False @return: False ''' return False def num_mutations (self): ''' Return 0. @rtype: 0 @return: 0 ''' return 0 ######################################################################################################################## long_strings = [] #gen_strings() def add_long_strings(sequence, max_len): ''' 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. ''' length = 2**7 power = 7 while length <= max_len: long_string = sequence * length long_strings.append(long_string) long_string = sequence * (length + 1) long_strings.append(long_string) long_string = sequence * (length - 1) long_strings.append(long_string) power += 1 length = 2**power def gen_strings(max_len=8192): # add some long strings. add_long_strings("A", max_len) add_long_strings("B", max_len) add_long_strings("1", max_len) add_long_strings("2", max_len) add_long_strings("<", max_len) add_long_strings(">", max_len) add_long_strings("'", max_len) add_long_strings("\"", max_len) add_long_strings("/", max_len) add_long_strings("\\", max_len) add_long_strings("?", max_len) add_long_strings("=", max_len) add_long_strings("a=", max_len) add_long_strings("&", max_len) add_long_strings(".", max_len) add_long_strings(",", max_len) add_long_strings("(", max_len) add_long_strings(")", max_len) add_long_strings("]", max_len) add_long_strings("[", max_len) add_long_strings("%", max_len) add_long_strings("*", max_len) add_long_strings("-", max_len) add_long_strings("+", max_len) add_long_strings("{", max_len) add_long_strings("}", max_len) add_long_strings("\x14", max_len) add_long_strings("\xFE", max_len) # expands to 4 characters under utf16 add_long_strings("\xFF", max_len) # expands to 4 characters under utf16 # add some long strings with null bytes etc thrown in the middle of it. length = 2**7 power = 7 while length <= max_len: s = "B" * length for val in ['\x00', ':', '.', ';', ',', '\r\n', '\r', '\n']: tmp = s[:len(s)/2] + val + s[len(s)/2:] long_strings.append(tmp) power += 1 length = 2**power # add some long strings with non-repeating elements. An attempt to avoid overflow detection # chars = string.letters + string.digits # 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, 0xFFFF]: # long_strings.append(os.urandom(length)) class string (base_primitive): def __init__ (self, value, size=-1, padding="\x00", encoding="ascii", fuzzable=True, name=None): ''' Primitive that cycles through a library of "bad" strings. @type value: String @param value: Default string value @type size: Integer @param size: (Optional, def=-1) Static size of this field, leave -1 for dynamic. @type padding: Character @param padding: (Optional, def="\\x00") Value to use as padding to fill static field size. @type encoding: String @param encoding: (Optonal, def="ascii") String encoding, ex: utf_16_le for Microsoft Unicode. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive ''' 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" # for ease of object identification self.rendered = "" # rendered value self.fuzz_complete = False # flag if this primitive has been completely fuzzed self.mutant_index = 0 # current mutation number self.fuzz_library = \ [ # omission and repetition. "", self.value * 2, self.value * 10, self.value * 100, # UTF-8 self.value * 2 + "\xfe", self.value * 10 + "\xfe", self.value * 100 + "\xfe", # strings ripped from spike (and some others I added) "/.:/" + "A"*5000 + "\x00\x00", "/.../" + "A"*5000 + "\x00\x00", "/.../.../.../.../.../.../.../.../.../.../", "/../../../../../../../../../../../../etc/passwd", "/../../../../../../../../../../../../boot.ini", "..:..:..:..:..:..:..:..:..:..:..:..:..:", "\\\\*", "\\\\?\\", "/\\" * 5000, "/." * 5000, "!@#$%%^#$%#$@#$%$$@#$%^^**(()", "%01%02%03%04%0a%0d%0aADSF", "%01%02%03@%04%0a%0d%0aADSF", "/%00/", "%00/", "%00", "%u0000", # format strings. "%n" * 100, "%n" * 500, "\"%n\"" * 500, "%s" * 100, "%s" * 500, "\"%s\"" * 500, # command injection. "|touch /tmp/SULLEY", ";touch /tmp/SULLEY;", "|notepad", ";notepad;", "\nnotepad\n", # SQL injection. "1;SELECT%20*", "'sqlattempt1", "(sqlattempt2)", "OR%201=1", # some binary strings. "\xde\xad\xbe\xef", "\xde\xad\xbe\xef" * 10, "\xde\xad\xbe\xef" * 100, "\xde\xad\xbe\xef" * 1000, "\xde\xad\xbe\xef" * 10000, "\x00" * 1000, # miscellaneous. "\r\n" * 100, "<>" * 500, # sendmail crackaddr (http://lsd-pl.net/other/sendmail.txt) ] self.fuzz_library.extend(long_strings) # if the optional file '.fuzz_strings' is found, parse each line as a new entry for the fuzz library. try: fh = open(".fuzz_strings", "r") for fuzz_string in fh.readlines(): fuzz_string = fuzz_string.rstrip("\r\n") if fuzz_string != "": self.fuzz_library.append(fuzz_string) fh.close() except: pass # truncate fuzz library items to user-supplied length and pad, removing duplicates. unique_mutants = [] if self.size != -1: for mutant in self.fuzz_library: # truncate. if len(mutant) > self.size: mutant = mutant[:self.size] # pad. elif len(mutant) < self.size: mutant = mutant + self.padding * (self.size - len(mutant)) # add to unique list. if mutant not in unique_mutants: unique_mutants.append(mutant) # assign unique list as fuzz library. self.fuzz_library = unique_mutants def render (self): ''' Render the primitive, encode the string according to the specified encoding. ''' # try to encode the string properly and fall back to the default value on failure. try: self.rendered = str(self.value).encode(self.encoding) except: self.rendered = self.value return self.rendered ######################################################################################################################## class bit_field (base_primitive): def __init__ (self, value, width, max_num=None, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None, hex_vals=False): ''' 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_ENDIAN) Endianess of the bit field (LITTLE_ENDIAN: <, BIG_ENDIAN: >) @type format: String @param format: (Optional, def=binary) Output format, "binary" or "ascii" @type signed: Boolean @param signed: (Optional, def=False) Make size signed vs. unsigned (applicable only with format="ascii") @type full_range: Boolean @param full_range: (Optional, def=False) If enabled the field mutates through *all* possible values. @type fuzzable: Boolean @param fuzzable: (Optional, def=True) Enable/disable fuzzing of this primitive @type name: String @param name: (Optional, def=None) Specifying a name gives you direct access to a primitive @type hex_vals: Boolean @param hex_vals: (Optional, def=False) Only applicable when format="ascii". Return the hex representation of the fuzz values ''' assert(type(value) is int or type(value) is long) assert(type(width) is int or type(value) is long) self.value = self.original_value = value # if hex_vals is true then what we want to be in value is the hex equivalent of # whatever the value is. It has already been converted to an int so we just # convert it now to its hex string if hex_vals == True: self.value = hex(self.value) self.original_value = hex(self.original_value) self.width = width self.max_num = max_num self.endian = endian self.format = format self.signed = signed self.full_range = full_range self.fuzzable = fuzzable self.name = name self.hex_vals = hex_vals self.rendered = "" # rendered value self.fuzz_complete = False # flag if this primitive has been completely fuzzed self.fuzz_library = [] # library of fuzz heuristics self.mutant_index = 0 # current mutation number if self.max_num == None: self.max_num = self.to_decimal("1" * width) assert(type(self.max_num) is int or type(self.max_num) is long) # build the fuzz library. if self.full_range: # add all possible values. for i in xrange(0, self.max_num): self.fuzz_library.append(i) else: # try only "smart" values. self.add_integer_boundaries(0) self.add_integer_boundaries(self.max_num / 2) self.add_integer_boundaries(self.max_num / 3) self.add_integer_boundaries(self.max_num / 4) self.add_integer_boundaries(self.max_num / 8) self.add_integer_boundaries(self.max_num / 16) self.add_integer_boundaries(self.max_num / 32) self.add_integer_boundaries(self.max_num) # if the optional file '.fuzz_ints' is found, parse each line as a new entry for the fuzz library. try: fh = open(".fuzz_ints", "r") for fuzz_int in fh.readlines(): # convert the line into an integer, continue on failure. try: fuzz_int = long(fuzz_int, 16) except: continue if fuzz_int <= self.max_num: self.fuzz_library.append(fuzz_int) fh.close() except: pass def add_integer_boundaries (self, integer): ''' Add the supplied integer and border cases to the integer fuzz heuristics library. @type integer: Int @param integer: Integer to append to fuzz heuristics ''' for i in xrange(-10, 10): case = integer + i # ensure the border case falls within the valid range for this field. if 0 <= case <= self.max_num: if case not in self.fuzz_library: self.fuzz_library.append(case) def render (self): ''' Render the primitive. ''' # # binary formatting. # # if hex_vals is true the value has already been converted to a string of the hex representation # of the value so first convert it back for these operations e.g 0xFFFF would have been converted to # 65535 then to 'FFFF' and now we need 65535 back for a few operations. All of this is so I didn't have to # make major changes in Sulley. We only do this if it is the original_value in place, otherwise # no changes are needed tmp_val = self.value tmp_orig_val = self.original_value if self.value == self.original_value and self.hex_vals == True: self.value = int(self.value, 16) self.original_value = int(self.original_value, 16) if self.format == "binary": bit_stream = "" rendered = "" # pad the bit stream to the next byte boundary. if self.width % 8 == 0: bit_stream += self.to_binary() else: bit_stream = "0" * (8 - (self.width % 8)) bit_stream += self.to_binary() # convert the bit stream from a string of bits into raw bytes. for i in xrange(len(bit_stream) / 8): chunk = bit_stream[8*i:8*i+8] rendered += struct.pack("B", self.to_decimal(chunk)) # if necessary, convert the endianess of the raw bytes. if self.endian == "<": rendered = list(rendered) rendered.reverse() rendered = "".join(rendered) self.rendered = rendered # # ascii formatting. # else: # if the sign flag is raised and we are dealing with a signed integer (first bit is 1). if self.signed and self.to_binary()[0] == "1": max_num = self.to_decimal("0" + "1" * (self.width - 1)) # chop off the sign bit. val = self.value & max_num # account for the fact that the negative scale works backwards. val = max_num - val # toss in the negative sign. self.rendered = "%d" % ~val # unsigned integer or positive signed integer. else: self.rendered = "%d" % self.value # if we want the hex value in ascii form e.g A instead of 10 if self.hex_vals == True: self.rendered = hex(int(self.rendered))[2:] self.value = tmp_val self.original_value = tmp_orig_val return self.rendered def to_binary (self, number=None, bit_count=None): ''' 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 ''' if number == None: number = self.value if bit_count == None: bit_count = self.width return "".join(map(lambda x:str((number >> x) & 1), range(bit_count -1, -1, -1))) def to_decimal (self, binary): ''' Convert a binary string to a decimal number. @type binary: String @param binary: Binary string @rtype: Integer @return: Converted bit string ''' return int(binary, 2) ######################################################################################################################## class byte (bit_field): def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None, hex_vals=False): self.s_type = "byte" if type(value) not in [int, long]: value = struct.unpack(endian + "B", value)[0] bit_field.__init__(self, value, 8, None, endian, format, signed, full_range, fuzzable, name, hex_vals) ######################################################################################################################## class word (bit_field): def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None, hex_vals=False): self.s_type = "word" if type(value) not in [int, long]: value = struct.unpack(endian + "H", value)[0] bit_field.__init__(self, value, 16, None, endian, format, signed, full_range, fuzzable, name, hex_vals) ######################################################################################################################## class dword (bit_field): def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None, hex_vals=False): self.s_type = "dword" if type(value) not in [int, long]: value = struct.unpack(endian + "L", value)[0] bit_field.__init__(self, value, 32, None, endian, format, signed, full_range, fuzzable, name, hex_vals) ######################################################################################################################## class qword (bit_field): def __init__ (self, value, endian="<", format="binary", signed=False, full_range=False, fuzzable=True, name=None, hex_vals=False): self.s_type = "qword" if type(value) not in [int, long]: value = struct.unpack(endian + "Q", value)[0] bit_field.__init__(self, value, 64, None, endian, format, signed, full_range, fuzzable, name, hex_vals)
30,910
Python
.py
668
36.468563
155
0.546154
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,911
sessions.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/sessions.pyc
Ñò âпMc@s'ddkZddkZddkZddkZddkZddkZddkZddkZddkZddk Z ddk Z ddk Z dfd„ƒYZ de i i fd„ƒYZde ifd„ƒYZdeifd „ƒYZd eifd „ƒYZd eifd „ƒYZdS(iÿÿÿÿNttargetcBs eZdZd„Zd„ZRS(s& Target descriptor container. cKsU||_||_d|_d|_d|_h|_h|_h|_t |_ dS(s« @type host: String @param host: Hostname or IP address of target system @type port: Integer @param port: Port of target service N( thosttporttNonetnetmontprocmont vmcontroltnetmon_optionstprocmon_optionstvmcontrol_optionstTruet running_flag(tselfRRtkwargs((s)/pentest/voiper/sulley/sulley/sessions.pyt__init__s        cCs<|io’xO|ioDy|iiƒoPnWntiidƒnXtidƒq W|io2x/|ii ƒD]}t d||fƒqvWqœn|i o’xO|ioDy|i iƒoPnWntiidƒnXtidƒq©W|io2x/|i i ƒD]}t d||fƒqWq8ndS(sK # pass specified target parameters to the PED-RPC server. s8Procmon exception in sessions.py : self.procmon.alive() is/self.procmon.set_%s(self.procmon_options["%s"])s6Netmon exception in sessions.py : self.netmon.alive() s-self.netmon.set_%s(self.netmon_options["%s"])N( RR talivetsyststderrtwritettimetsleepRtkeystevalRR(R tkey((s)/pentest/voiper/sulley/sulley/sessions.pytpedrpc_connect+s4         (t__name__t __module__t__doc__RR(((s)/pentest/voiper/sulley/sulley/sessions.pyRs t connectioncBseZdd„ZRS(cCs&tiii|||ƒ||_dS(s* 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 the last edge along the current fuzz path to "node", session is a pointer to the session instance which is useful for snagging data such as sesson.last_recv which contains the data returned from the last socket transmission and sock is the live socket. A callback is also useful in situations where, for example, the size of the next packet is specified in the first packet. @type src: Integer @param src: Edge source ID @type dst: Integer @param dst: Edge destination ID @type callback: Function @param callback: (Optional, def=None) Callback function to pass received data to between node xmits N(tpgraphtedgeRtcallback(R tsrctdstR((s)/pentest/voiper/sulley/sulley/sessions.pyRSsN(RRRR(((s)/pentest/voiper/sulley/sulley/sessions.pyRRstsessionc BsþeZdddddddddddd„ Zd„Zd „Zd „Zddd „Zd „Zd „Z d„Z dgd„Z d„Z d„Z dd„Zdgd„Zd„Zd„Zd„Zd„Zd„Zed„Zd„Zd„ZRS(igš™™™™™É?ittcpg@i‘eic Cswtii|ƒ||_||_||_||_||_||_||_ ||_ | |_ | |_ | |_ d|_d|_d|_d|_g|_h|_h|_t|_t|_h|_|idjoti|_n7|idjoti|_ntid|iƒ‚|i ƒti!ƒ|_"d|i"_#|i"i#|i"_$d|_%|i&|i"ƒdS(s¨ 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 sleep_time: Float @kwarg sleep_time: (Optional, def=1.0) Time to sleep in between tests @type log_level: Integer @kwarg log_level: (Optional, def=2) Set the log level, higher number == more log messages @type proto: String @kwarg proto: (Optional, def="tcp") Communication protocol @type timeout: Float @kwarg timeout: (Optional, def=5.0) Seconds to wait for a send/recv prior to timing out @type restart_interval: Integer @kwarg restart_interval (Optional, def=0) Restart the target after n test cases, disable by setting to 0 @type crash_threshold: Integer @kwarg crash_threshold (Optional, def=3) Maximum number of crashes allowed before a node is exhaust iR#tudpsINVALID PROTOCOL SPECIFIED: %st __ROOT_NODE__N('RtgraphRtsession_filenamet audit_foldertskipt sleep_timet log_leveltprototrestart_intervalttimeouttweb_porttcrash_thresholdt trans_in_qttotal_num_mutationsttotal_mutant_indextcrashes_detectedRt fuzz_nodettargetstnetmon_resultstprocmon_resultstFalset pause_flagR R tcrashing_primitivestsockett SOCK_STREAMt SOCK_DGRAMtsexterrort import_filetnodetroottnametlabelt last_recvtadd_node( R R'R(R)R*R+R,R-R.R/R0R1((s)/pentest/voiper/sulley/sulley/sessions.pyRpsB                        cCs4|i|djo|i|8_n d|_dS(Ni(R3(R tval((s)/pentest/voiper/sulley/sulley/sessions.pytdecrement_total_mutant_indexµscCsRt|iƒ|_t|iƒ|_|ii|iƒp||i|i<n|S(së 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 (tlentnodestnumbertidthas_key(R RB((s)/pentest/voiper/sulley/sulley/sessions.pyRG»s cCs|iƒ|ii|ƒdS(s¹ 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 N(RR6tappend(R R((s)/pentest/voiper/sulley/sulley/sessions.pyt add_targetÎs cCsô|p|}|i}nt|ƒtjo|id|ƒ}nt|ƒtjo|id|ƒ}n||ijo(|id|iƒ o|i|ƒn|id|iƒp|i|ƒnt|i|i|ƒ}|i|ƒ|S(s� 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 must be connected to. Example:: sess = sessions.session() sess.connect(sess.root, s_get("HTTP")) If given only a single parameter, sess.connect() will default to attaching the supplied node to the root node. This is a convenient alias and is identical to the second line from the above example:: sess.connect(s_get("HTTP")) If you register callback method, it must follow this prototype:: def callback(session, node, edge, sock) Where node is the node about to be sent, edge is the last edge along the current fuzz path to "node", session is a pointer to the session instance which is useful for snagging data such as sesson.last_recv which contains the data returned from the last socket transmission and sock is the live socket. A callback is also useful in situations where, for example, the size of the next packet is specified in the first packet. As another example, if you need to fill in the dynamic IP address of the target register a callback that snags the IP from sock.getpeername()[0]. @type src: String or Request (Node) @param src: Source request name or request node @type dst: String or Request (Node) @param dst: Destination request name or request node @type callback: Function @param callback: (Optional, def=None) Callback function to pass received data to between node xmits @rtype: pgraph.edge @return: The edge between the src and dst. RD( RCttypetstrt find_nodeRDRGRRMtadd_edge(R R R!RR((s)/pentest/voiper/sulley/sulley/sessions.pytconnectÝs& ' cCs|ipdSh}|i|d<|i|d<|i|d<|i|d<|i|d<|i|d<|i|d<|i|d <|i|d <|i |d <|i |d <|i|d <|i |d<|i |d<|i |d<t|idƒ}|ititi|ddƒƒƒ|iƒdS(sR Dump various object values to disk. @see: import_file() NR'R)R*R+R,R4R-R.R/R0R2R3R7R8R:swb+tprotocoli(R'R3R*R+R,R4R-R.R/R0R2R7R8R:topenRtzlibtcompresstcPickletdumpstclose(R tdatatfh((s)/pentest/voiper/sulley/sulley/sessions.pyt export_files*                %cCsdS(s† This method should be overwritten by any fuzzer that needs to wait for the client to register after it has restarted N((R ((s)/pentest/voiper/sulley/sulley/sessions.pytwaitForRegister=scCsdS(s= This method should be overridden by the GUI N((R txty((s)/pentest/voiper/sulley/sulley/sessions.pytupdateProgressBarEsc Cs¯|pl|iptidƒ‚n|i|iiƒptidƒ‚n|i}y|iƒWqsdSXn|id}x|i|iƒD]ÿ}|i|i|_ |i i ƒ}|i |iijo|i |ƒndi g}|D]}||i|i iqó~ƒ}|d|i i7}|id|dƒ|id |i|ifdƒ|i|i|iƒ|i|iƒt} d} xÚ| pÒ|ipPn|iƒ|i iƒp|id dƒt} q–n|id 7_|i|ijof|iof|i|idjoO|id |iƒ|i|ƒ|iƒ|id |i i|fdƒnx—yú|io|ii |iƒn|i!o|i!i |iƒn|i"|_"|i#|_#t$i$t$i%|i&ƒ} | i'|i(ƒ|i | ƒx4|D],}|i|i } |i)| | ||ƒqW|i)| |i ||ƒ|i|i|iƒPWnStij oD}t*i+i,dƒt*i+i,d|i-ƒdƒt*i.d ƒnX|i/| ƒ|id|i"|i#fƒ|idƒ|i|ƒqx|i0| ƒ|i/| ƒ|id|i1dƒt2i3|i1ƒ|i4|ƒ|i5ƒq–q–W|ipPn|i6|i |ƒq“W|o|i7ƒndS(s· 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=[]) Nodes along the path to the current one being fuzzed. sNO TARGETS SPECIFIED IN SESSIONs NO REQUESTS SPECIFIED IN SESSIONNis -> s -> %sscurrent fuzz path: %sisfuzzed %d of %d total casess6all possible mutations for current fuzz node exhaustedisrestart interval of %d reachedsfuzzing %d of %dsCAUGHT SULLEY EXCEPTION s s sfailed connecting to %s:%ds"restarting target and trying againssleeping for %f secondsi(8R6R?R@t edges_fromRCRMt server_initRKR!R5t num_mutationsR ROtjoinRDtlogR3R2Rctupdate_GUI_crashesR4R9R tpausetmutateR R)R-trestart_targetR`t mutant_indexRtpre_sendRRRR<tAF_INETR,t settimeoutR.ttransmitRRRt__str__texitt close_sockett post_sendR*RRt poll_pedrpcR_tfuzztpop( R t this_nodetpathRRRft_[1]tet current_pathtdone_with_fuzz_nodet crash_counttsockRB((s)/pentest/voiper/sulley/sulley/sessions.pyRwLsœ     7   !  $           cCs|iƒdS(sš Closes a given socket. Meant to be overridden by VoIPER @type sock: Socket @param sock: The socket to be closed N(R\(R R€((s)/pentest/voiper/sulley/sulley/sessions.pyRtæscCsy>t|idƒ}titi|iƒƒƒ}|iƒWndSX|d|_|d|_|d|_ |d|_ |d|_ |d|_ |d |_ |d |_|d |_|d |_|d|_|d |_|d|_|d|_|d|_dS(sS Load varous object values from disk. @see: export_file() trbNR3R'R*R+R,R-R.R/R0R2R7R8R:R4(RWR'RZtloadsRXt decompresstreadR\R)R*R+R,R-R.R/R0R2R3R7R8R:R4(R R^R]((s)/pentest/voiper/sulley/sulley/sessions.pyRAñs*              icCs0|i|jodtidƒ|fGHndS(s² If the supplied message falls under the current log level, print the specified message to screen. @type msg: String @param msg: Message to log s[%s] %ss%I:%M.%SN(R+Rtstrftime(R tmsgtlevel((s)/pentest/voiper/sulley/sulley/sessions.pyRhscCs²|p|i}d|_nxv|i|iƒD]b}|i|i}|i|iƒ7_|i|iijo|i|ƒn|i||ƒq0W|o|i ƒn|iS(sF 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 fuzzed. @type path: List @param path: (Optional, def=[]) Nodes along the path to the current one being fuzzed. @rtype: Integer @return: Total number of mutations in this session. i( RCR2RdRMRKR!RfR RORx(R RyRzRt next_node((s)/pentest/voiper/sulley/sulley/sessions.pyRf s  cCs&x|iotidƒqPqdS(sZ If thet pause flag is raised, enter an endless loop until it is lowered. iN(R:RR(R ((s)/pentest/voiper/sulley/sulley/sessions.pyRjCs c CsÅ|io@|iiƒ}|id||ifdƒ||i|i<n|iomd}x|p|iiƒ}q]W|d}|d}|p*|id||ifƒ|id7_|i|iƒ|i i |i i dƒd|i |i i <|i i i p d}nd|i i i }|d|i i i|i i if7}|i|ƒ|d joD|iiƒ|i|i<|i|i|iid ƒddƒn|idjov|id t|i iƒd t|iƒd }t|dƒ}|i|i iƒ|iƒ|id|dƒn|i |i i |ijoZt|i |i i tiƒp6|i i iƒ} |id| ƒ|i| 7_q¦n|i|dt ƒqÁndS(sÈ 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 s*netmon captured %d bytes for test case #%diiis$procmon detected %s on test case #%dsprimitive lacks a name, sprimitive name: %s, stype: %s, default value: %ssaccess violations t/t_s .crashlogtwsFuzz request logged to sBcrash threshold reached for this primitive, exhausting %d mutants.t stop_firstN(!RRuRhR3R7RRR4RiR;tgetR5tmutantRDts_typetoriginal_valuetget_crash_synopsisR8tsplitR(RRRMRWRt sent_dataR\R0t isinstancet primitivestgrouptexhaustRlR9( R Rtbytestret_valRt crash_typeR†tcrash_log_namet crash_logtskipped((s)/pentest/voiper/sulley/sulley/sessions.pyRvPsH    , &  +2  cCsdS(sj Method to be overridden by a GUI that wants and update of the number of crashes detected N((R t num_crashes((s)/pentest/voiper/sulley/sulley/sessions.pyRi”scCsdS(sŸ 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: Connected socket to target N((R R€((s)/pentest/voiper/sulley/sulley/sessions.pyRu›scCsdS(sœ 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: Connected socket to target N((R R€((s)/pentest/voiper/sulley/sulley/sessions.pyRn¯scCs�|io|idƒ|iiƒnh|ioC|idƒ|o|iiƒn|iiƒtidƒn|idƒtidƒ|iƒdS(s 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 s!restarting target virtual machinesrestarting target processisDno vmcontrol or procmon channel available ... sleeping for 5 minutesi,N( RRhRlRt stop_targett start_targetRRR(R RRŒ((s)/pentest/voiper/sulley/sulley/sessions.pyRlÃs       cCs2d|_|iƒ|_t|ƒ}|iƒdS(sz Called by fuzz() on first run (not on recursive re-entry) to initialize variables, web interface, etc... iN(R3RfR2tweb_interface_threadtstart(R tt((s)/pentest/voiper/sulley/sulley/sessions.pyReæs  c CsÞd}|id|i|ifddƒ|io|i||||ƒ}n|p|iƒ}n|itijo%t |ƒdjo|d }qžn|i o2|i i t |d|i |ifd|fƒny)|i||i |ifƒ||_Wn*tj o}|id|dƒnX|itijoKy|idƒ|_Wq—tj o"}|id d ƒd |_q—Xn d |_t |iƒd jo-|id t |iƒ|ifddƒndS(sÐ 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 target: session.target @param target: Target we are transmitting to sxmitting: [%d.%d]R‡iiãÿgø?sSocket error, send: %sii'sNothing received on socket.itisreceived: [%d] %si N(RRhRMR3RtrenderR,R<R>RJR1tputR RRtsendtoR“t ExceptionR=trecvRF(R R€RBRRR]tinstR|((s)/pentest/voiper/sulley/sulley/sessions.pyRqôs2#  2  N(RRRRRIRGRPRUR_R`RcRwRtRARhRfRjRvRiRuRnR RlReRq(((s)/pentest/voiper/sulley/sulley/sessions.pyR"os**E   @  š " # D    # tweb_interface_handlercBsteZd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z d „Z RS( cCs&tii||||ƒd|_dS(N(tBaseHTTPServertBaseHTTPRequestHandlerRRR"(R trequesttclient_addresstserver((s)/pentest/voiper/sulley/sulley/sessions.pyR/scCsLt|ƒ}d}tidƒ}x$|o|id|ƒ\}}q$W|S(Nis^(-?\d+)(\d{3})s\1,\2(RRtretcompiletsubn(R RLt processingtregex((s)/pentest/voiper/sulley/sulley/sessions.pytcommify4s cCs|iƒdS(N(t do_everything(R ((s)/pentest/voiper/sulley/sulley/sessions.pytdo_GET?scCs|iƒdS(N(R·(R ((s)/pentest/voiper/sulley/sulley/sessions.pytdo_HEADCscCs|iƒdS(N(R·(R ((s)/pentest/voiper/sulley/sulley/sessions.pytdo_POSTGscCsÓd|ijot|i_nd|ijot|i_n|idƒ|iddƒ|iƒd|ijo|i|iƒ}n3d|ijo|i |iƒ}n |i ƒ}|i i |ƒdS(NRjtresumeiÈs Content-types text/htmlt view_crasht view_pcap( RzR R"R:R9t send_responset send_headert end_headersR¼R½t view_indextwfileR(R tresponse((s)/pentest/voiper/sulley/sulley/sessions.pyR·Ks   cOsdS(N((R targsR ((s)/pentest/voiper/sulley/sulley/sessions.pyt log_error`scOsdS(N((R RÄR ((s)/pentest/voiper/sulley/sulley/sessions.pyt log_messagedscCsdS(NsSulley Fuzz Session((R ((s)/pentest/voiper/sulley/sulley/sessions.pytversion_stringhscCs+t|idƒdƒ}d|ii|S(NR‰iÿÿÿÿs<html><pre>%s</pre></html>(tintR’R"R8(R Rzt test_number((s)/pentest/voiper/sulley/sulley/sessions.pyR¼lscCs|S(N((R Rz((s)/pentest/voiper/sulley/sulley/sessions.pyR½qsc Cs²d}|iiiƒ}|iƒx~|D]v}|ii|}d}|iii|ƒo|i|ii|ƒ}n|d|||idƒd|f7}q)W|d7}|iio d}nd}|ii o‡|ii i o|ii i }nd }t |ii i ƒt |ii i ƒƒ}t|d ƒ} d d | dd | d } d|d}t |iiƒt |iiƒ} t| d ƒ} d d | dd | d } d| d} |h |i|ii i ƒd6|d6|i|ii i ƒƒd6|d6| d6| d6| d6|d6|i|iiƒd6|i|iiƒd6;}nQ|h dd6dd6dd6dd6dd6dd6dd6dd6dd6dd6;}|S(NsÝ <html> <head> <title>Sulley Fuzz Control</title> <style> a:link {color: #FF8200; text-decoration: none;} a:visited {color: #FF8200; text-decoration: none;} a:hover {color: #C5C5C5; text-decoration: none;} body { background-color: #000000; font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #FFFFFF; } td { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #A0B0B0; } .fixed { font-family: Courier New; font-size: 12px; color: #A0B0B0; } .input { font-family: Arial, Helvetica, sans-serif; font-size: 11px; color: #FFFFFF; background-color: #333333; border: thin none; height: 20px; } </style> </head> <body> <center> <table border=0 cellpadding=5 cellspacing=0 width=750><tr><td> <!-- begin bounding table --> <table border=0 cellpadding=5 cellspacing=0 width="100%%"> <tr bgcolor="#333333"> <td><div style="font-size: 20px;">Sulley Fuzz Control</div></td> <td align=right><div style="font-weight: bold; font-size: 20px;">%(status)s</div></td> </tr> <tr bgcolor="#111111"> <td colspan=2 align="center"> <table border=0 cellpadding=0 cellspacing=5> <tr bgcolor="#111111"> <td><b>Total:</b></td> <td>%(total_mutant_index)s</td> <td>of</td> <td>%(total_num_mutations)s</td> <td class="fixed">%(progress_total_bar)s</td> <td>%(progress_total)s</td> </tr> <tr bgcolor="#111111"> <td><b>%(current_name)s:</b></td> <td>%(current_mutant_index)s</td> <td>of</td> <td>%(current_num_mutations)s</td> <td class="fixed">%(progress_current_bar)s</td> <td>%(progress_current)s</td> </tr> </table> </td> </tr> <tr> <td> <form method=get action="/pause"> <input class="input" type="submit" value="Pause"> </form> </td> <td align=right> <form method=get action="/resume"> <input class="input" type="submit" value="Resume"> </form> </td> </tr> </table> <!-- begin procmon results --> <table border=0 cellpadding=5 cellspacing=0 width="100%%"> <tr bgcolor="#333333"> <td nowrap>Test Case #</td> <td>Crash Synopsis</td> <td nowrap>Captured Bytes</td> </tr> s&nbsp;sc<tr><td class="fixed"><a href="/view_crash/%d">%06d</a></td><td>%s</td><td align=right>%s</td></tr>s is <!-- end procmon results --> </table> <!-- end bounding table --> </td></tr></table> </center> </body> </html> s<font color=red>PAUSED</font>s <font color=green>RUNNING</font>s[N/A]i2t[t=t]s%.3f%%idtcurrent_mutant_indext current_nametcurrent_num_mutationstprogress_currenttprogress_current_bartprogress_totaltprogress_total_bartstatusR3R2R¤s%<font color=yellow>UNAVAILABLE</font>(R"R8RtsortR7RNR¶R’R:R5RDtfloatRmRfRÈR3R2( R RÃRRRHR˜RÔRÎRÐtnum_barsRÑRÒRÓ((s)/pentest/voiper/sulley/sulley/sessions.pyRÁush` +    +" (RRRR¶R¸R¹RºR·RÅRÆRÇR¼R½RÁ(((s)/pentest/voiper/sulley/sulley/sessions.pyR«.s          tweb_interface_servercBseZdZd„ZRS(s? http://docs.python.org/lib/module-BaseHTTPServer.html cCs&tii|||ƒ||i_dS(N(R¬t HTTPServerRtRequestHandlerClassR"(R tserver_addressRÚR"((s)/pentest/voiper/sulley/sulley/sessions.pyR+s(RRRR(((s)/pentest/voiper/sulley/sulley/sessions.pyRØ&sR¡cBseZd„Zd„ZRS(cCs&tii|ƒ||_d|_dS(N(t threadingtThreadRR"RR°(R R"((s)/pentest/voiper/sulley/sulley/sessions.pyR2s cCs5td|iift|iƒ|_|iiƒdS(NR¤(RØR"R/R«R°t serve_forever(R ((s)/pentest/voiper/sulley/sulley/sessions.pytrun9s$(RRRRß(((s)/pentest/voiper/sulley/sulley/sessions.pyR¡1s (R±RRXRR<RZRÜR¬tpedrpcRR?R•RRRR&R"R­R«RÙRØRÝR¡(((s)/pentest/voiper/sulley/sulley/sessions.pyt<module>s&            AÿÿÁø
33,102
Python
.py
359
80.247911
1,101
0.435772
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,912
misc.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/utils/misc.pyc
Ñò âпMc@s:ddkZddkZdd„Zd„Zd„ZdS(iÿÿÿÿNicCs±g}xstdƒD]e}d}xItdƒD];}||Ad@o|d?dA}n |dL}|dL}q,W|i|ƒqWx.|D]&}|t|ƒ|d@A|d?A}qƒW|S(s6 CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1 iiiii iÿ(trangetappendtord(tstringtvaluet crc16_tabletbytetcrctbittch((s+/pentest/voiper/sulley/sulley/utils/misc.pytcrc16s   $c Cs[tid|d ƒ\}}}tid|dd!ƒ\}}}d||||||fS(s9 Convert a binary UUID to human readable string. s<LHHis>HHLis%08x-%04x-%04x-%04x-%04x%08x(tstructtunpack(tuuidtblock1tblock2tblock3tblock4tblock5tblock6((s+/pentest/voiper/sulley/sulley/utils/misc.pytuuid_bin_to_strs"cCsttid|ƒ}td„|iƒƒ\}}}}}}tid|||ƒ}|tid|||ƒ7}|S(sK Ripped from Core Impacket. Converts a UUID string to binary form. s^([\dA-Fa-f]{8})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})([\dA-Fa-f]{8})cSs t|dƒS(i(tlong(tx((s+/pentest/voiper/sulley/sulley/utils/misc.pyt<lambda>2ss<LHHs>HHL(tretmatchtmaptgroupsR tpack(R tmatchestuuid1tuuid2tuuid3tuuid4tuuid5tuuid6((s+/pentest/voiper/sulley/sulley/utils/misc.pytuuid_str_to_bin+s *(RR R RR$(((s+/pentest/voiper/sulley/sulley/utils/misc.pyt<module>s   
1,900
Python
.py
11
169.363636
491
0.403704
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,913
dcerpc.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/utils/dcerpc.py
import math import struct import misc ######################################################################################################################## def bind (uuid, version): ''' Generate the data necessary to bind to the specified interface. ''' major, minor = version.split(".") major = struct.pack("<H", int(major)) minor = struct.pack("<H", int(minor)) bind = "\x05\x00" # version 5.0 bind += "\x0b" # packet type = bind (11) bind += "\x03" # packet flags = last/first flag set bind += "\x10\x00\x00\x00" # data representation bind += "\x48\x00" # frag length: 72 bind += "\x00\x00" # auth length bind += "\x00\x00\x00\x00" # call id bind += "\xb8\x10" # max xmit frag (4280) bind += "\xb8\x10" # max recv frag (4280) bind += "\x00\x00\x00\x00" # assoc group bind += "\x01" # number of ctx items (1) bind += "\x00\x00\x00" # padding bind += "\x00\x00" # context id (0) bind += "\x01" # number of trans items (1) bind += "\x00" # padding bind += misc.uuid_str_to_bin(uuid) # abstract syntax bind += major # interface version bind += minor # interface version minor # transfer syntax 8a885d04-1ceb-11c9-9fe8-08002b104860 v2.0 bind += "\x04\x5d\x88\x8a\xeb\x1c\xc9\x11\x9f\xe8\x08\x00\x2b\x10\x48\x60" bind += "\x02\x00\x00\x00" return bind ######################################################################################################################## def bind_ack (data): ''' Ensure the data is a bind ack and that the ''' # packet type == bind ack (12)? if data[2] != "\x0c": return False # ack result == acceptance? if data[36:38] != "\x00\x00": return False return True ######################################################################################################################## def request (opnum, data): ''' Return a list of packets broken into 5k fragmented chunks necessary to make the RPC request. ''' frag_size = 1000 # max frag size = 5840? frags = [] num_frags = int(math.ceil(float(len(data)) / float(frag_size))) for i in xrange(num_frags): chunk = data[i * frag_size:(i+1) * frag_size] frag_length = struct.pack("<H", len(chunk) + 24) alloc_hint = struct.pack("<L", len(chunk)) flags = 0 if i == 0: flags |= 0x1 # first frag if i == num_frags - 1: flags |= 0x2 # last frag request = "\x05\x00" # version 5.0 request += "\x00" # packet type = request (0) request += struct.pack("B", flags) # packet flags request += "\x10\x00\x00\x00" # data representation request += frag_length # frag length request += "\x00\x00" # auth length request += "\x00\x00\x00\x00" # call id request += alloc_hint # alloc hint request += "\x00\x00" # context id (0) request += struct.pack("<H", opnum) # opnum request += chunk frags.append(request) # you don't have to send chunks out individually. so make life easier for the user and send them all at once. return "".join(frags)
3,706
Python
.py
74
44.22973
120
0.449488
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,914
dcerpc.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/utils/dcerpc.pyc
Ñò âпMc@sCddkZddkZddkZd„Zd„Zd„ZdS(iÿÿÿÿNcCs|idƒ\}}tidt|ƒƒ}tidt|ƒƒ}d}|d7}|d7}|d7}|d7}|d7}|d 7}|d 7}|d 7}|d 7}|d 7}|d 7}|d7}|d 7}|d 7}|ti|ƒ7}||7}||7}|d7}|d7}|S(sI Generate the data necessary to bind to the specified interface. t.s<Hss sstHtts¸stts]ˆŠëÉŸè+H`s(tsplittstructtpacktinttmisctuuid_str_to_bin(tuuidtversiontmajortminortbind((s-/pentest/voiper/sulley/sulley/utils/dcerpc.pyRs0                  cCs3|ddjotS|dd!djotStS(s4 Ensure the data is a bind ack and that the is i$i&R(tFalsetTrue(tdata((s-/pentest/voiper/sulley/sulley/utils/dcerpc.pytbind_ack+s c Cswd}g}ttitt|ƒƒt|ƒƒƒ}x0t|ƒD]"}||||d|!}tidt|ƒdƒ}tidt|ƒƒ}d} |djo| dO} n||djo| dO} nd} | d 7} | tid | ƒ7} | d 7} | |7} | d 7} | d 7} | |7} | d 7} | tid|ƒ7} | |7} |i| ƒqDWdi |ƒS(sf Return a list of packets broken into 5k fragmented chunks necessary to make the RPC request. ièis<His<LiisRtBsRRt( R tmathtceiltfloattlentxrangeRRtappendtjoin( topnumRt frag_sizetfragst num_fragstitchunkt frag_lengtht alloc_hinttflagstrequest((s-/pentest/voiper/sulley/sulley/utils/dcerpc.pyR'<s4+          (RRR RRR'(((s-/pentest/voiper/sulley/sulley/utils/dcerpc.pyt<module>s    % 
2,214
Python
.py
64
33.21875
336
0.369596
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,915
scada.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/utils/scada.py
import math import struct ######################################################################################################################## def dnp3 (data, control_code="\x44", src="\x00\x00", dst="\x00\x00"): num_packets = int(math.ceil(float(len(data)) / 250.0)) packets = [] for i in xrange(num_packets): slice = data[i*250 : (i+1)*250] p = "\x05\x64" p += chr(len(slice)) p += control_code p += dst p += src chksum = struct.pack("<H", crc16(p)) p += chksum num_chunks = int(math.ceil(float(len(slice) / 16.0))) # insert the fragmentation flags / sequence number. # first frag: 0x40, last frag: 0x80 frag_number = i if i == 0: frag_number |= 0x40 if i == num_packets - 1: frag_number |= 0x80 p += chr(frag_number) for x in xrange(num_chunks): chunk = slice[i*16 : (i+1)*16] chksum = struct.pack("<H", crc16(chunk)) p += chksum + chunk packets.append(p) return packets
1,118
Python
.py
30
28.7
120
0.461323
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,916
scada.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/utils/scada.pyc
Ñò âпMc@s.ddkZddkZdddd„ZdS(iÿÿÿÿNtDtcCs“ttitt|ƒƒdƒƒ}g}xat|ƒD]S}||d|dd!}d}|tt|ƒƒ7}||7}||7}||7}tidt |ƒƒ} || 7}ttitt|ƒdƒƒƒ} |} |djo| dO} n||djo| d O} n|t| ƒ7}xSt| ƒD]E} ||d |dd !} tidt | ƒƒ} || | 7}q5W|i |ƒq8W|S( Ng@o@iúisds<Hg0@ii@i€i( tinttmathtceiltfloattlentxrangetchrtstructtpacktcrc16tappend(tdatat control_codetsrctdstt num_packetstpacketstitslicetptchksumt num_chunkst frag_numbertxtchunk((s,/pentest/voiper/sulley/sulley/utils/scada.pytdnp3s4%     %  (RR R(((s,/pentest/voiper/sulley/sulley/utils/scada.pyt<module>s  
1,096
Python
.py
12
90.333333
332
0.35023
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,917
misc.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/utils/misc.py
import re import struct ######################################################################################################################## def crc16 (string, value=0): ''' CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1 ''' crc16_table = [] for byte in range(256): crc = 0 for bit in range(8): if (byte ^ crc) & 1: crc = (crc >> 1) ^ 0xa001 # polly else: crc >>= 1 byte >>= 1 crc16_table.append(crc) for ch in string: value = crc16_table[ord(ch) ^ (value & 0xff)] ^ (value >> 8) return value ######################################################################################################################## def uuid_bin_to_str (uuid): ''' Convert a binary UUID to human readable string. ''' (block1, block2, block3) = struct.unpack("<LHH", uuid[:8]) (block4, block5, block6) = struct.unpack(">HHL", uuid[8:16]) return "%08x-%04x-%04x-%04x-%04x%08x" % (block1, block2, block3, block4, block5, block6) ######################################################################################################################## def uuid_str_to_bin (uuid): ''' Ripped from Core Impacket. Converts a UUID string to binary form. ''' matches = re.match('([\dA-Fa-f]{8})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})([\dA-Fa-f]{8})', uuid) (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) = map(lambda x: long(x, 16), matches.groups()) uuid = struct.pack('<LHH', uuid1, uuid2, uuid3) uuid += struct.pack('>HHL', uuid4, uuid5, uuid6) return uuid
1,648
Python
.py
36
39.861111
126
0.426868
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,918
cluster.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pgraph/cluster.pyc
Ñò âпMc@s,dZddkZdefd„ƒYZdS(s™ @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org iÿÿÿÿNtclustercBsJeZdZdZgZdd„Zd„Zd„Zd„Z d„Z RS(s cCs||_g|_dS(s$ Class constructor. N(tidtnodes(tselfR((s//pentest/voiper/sulley/sulley/pgraph/cluster.pyt__init__!s cCs|ii|ƒ|S(sz Add a node to the cluster. @type node: pGRAPH Node @param node: Node to add to cluster (Rtappend(Rtnode((s//pentest/voiper/sulley/sulley/pgraph/cluster.pytadd_node+scCs=x6|iD]+}|i|jo|ii|ƒPq q W|S(s„ Remove a node from the cluster. @type node: pGRAPH Node @param node: Node to remove from cluster (RRtremove(Rtnode_idR((s//pentest/voiper/sulley/sulley/pgraph/cluster.pytdel_node9s   cCsGx@|iD]5}t||ƒot||ƒ|jo|Sq q WdS(sx 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. N(RthasattrtgetattrtNone(Rt attributetvalueR((s//pentest/voiper/sulley/sulley/pgraph/cluster.pyt find_nodeJs  cCsdS(N((R((s//pentest/voiper/sulley/sulley/pgraph/cluster.pytrender`sN( t__name__t __module__t__doc__R RRRRR RR(((s//pentest/voiper/sulley/sulley/pgraph/cluster.pyRs   (RRtobjectR(((s//pentest/voiper/sulley/sulley/pgraph/cluster.pyt<module>s 
2,359
Python
.py
36
60.222222
208
0.468966
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,919
cluster.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pgraph/cluster.py
# # pGRAPH # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' import node class cluster (object): ''' ''' id = None nodes = [] #################################################################################################################### def __init__ (self, id=None): ''' Class constructor. ''' self.id = id self.nodes = [] #################################################################################################################### def add_node (self, node): ''' Add a node to the cluster. @type node: pGRAPH Node @param node: Node to add to cluster ''' self.nodes.append(node) return self #################################################################################################################### def del_node (self, node_id): ''' Remove a node from the cluster. @type node: pGRAPH Node @param node: Node to remove from cluster ''' for node in self.nodes: if node.id == node_id: self.nodes.remove(node) break return self #################################################################################################################### def find_node (self, attribute, value): ''' 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. ''' for node in self.nodes: if hasattr(node, attribute): if getattr(node, attribute) == value: return node return None #################################################################################################################### def render (self): pass
2,963
Python
.py
73
33.863014
120
0.495989
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,920
node.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pgraph/node.pyc
—Ú ‚–øMc@s dZdefdÑÉYZdS(sô @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org tnodecBsòeZdZdZdZdZdZdZdZdZ dZ dZ dZ d Z d Zd ZdZdZdd ÑZd ÑZd ÑZdÑZdÑZRS(s iiˇ˜ÓiÓÓÓttboxgt1ig?t rectanglecCsy||_d|_d|_d|_d|_d|_d|_d|_d|_d|_ d |_ d |_ d |_ d S( s iiˇ˜ÓiÓÓÓRRgRig?RN( tidtnumbertcolort border_colortlabeltshapet gml_widtht gml_heightt gml_patternt gml_stippletgml_line_widthtgml_typetgml_width_shape(tselfR((s,/pentest/voiper/sulley/sulley/pgraph/node.pyt__init__2s            cCs d}d}xß|t|iÉjoêd}||t|iÉjoFxC|i||djp|i||djo|d8}qHWn||i|||!d7}||7}qW|ipt|iÉd|_n|ip t|iiÉÉd |_nd }|d |i7}|d 7}|d 7}|d|i7}||d7}|d7}|d|i7}|d|i7}|d|i7}|d|i7}|d|i 7}|d|i 7}|d|i 7}|d|i 7}|d|i 7}|d7}|d7}|S(s 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. Rii»s\t"is\ i is node [ s id %d s template "oreas:std:rect" s label "s <!--%08x-->\ s" s graphics [ s w %f s h %f s fill "#%06x" s line "#%06x" s pattern "%s" s stipple %d s lineWidth %f s type "%s" s width %f s ] s ] (tlenR R R tsplitRRRRR RRRR(Rtgrapht chunked_labeltcursortamountR((s,/pentest/voiper/sulley/sulley/pgraph/node.pytrender_node_gmlJsD 0        cCsddk}|i|iÉ}d|iidÉ|_|iiddÉ|_|i|_d|i|_d|i|_|S(s 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 iˇˇˇˇNs'<<font face="lucida console">%s</font>>s s\ns<br/>s#%06x( tpydottNodeRR trstriptreplaceR Rt fillcolor(RRRtdot_node((s,/pentest/voiper/sulley/sulley/pgraph/node.pytrender_node_graphvizÑs  cCs?|iiddÉ|_|iod|_d|i}nd}d|i}|d7}|d7}||7}|d |i7}|d |i7}|d |i7}|d 7}|d |i7}|d7}|d7}|d7}|i|iÉ}x+|D]#}||i|É7}|d7}qÚW|o|dd!}n|d7}|S(s 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. s s\ntimagesa("IMAGE","%s"),Rs l("%08x",sn("",t[sa("_GO","%s"),sa("COLOR","#%06x"),sa("OBJECT","%s"),sa("FONTFAMILY","courier"),sa("INFO","%s"),sa("BORDER","none")s],t,iiˇˇˇˇs]))( R Rt udraw_imageR RRt udraw_infot edges_fromtrender_edge_udraw(RRR&tudrawtedgestedge((s,/pentest/voiper/sulley/sulley/pgraph/node.pytrender_node_udrawùs4            cCs”|iiddÉ|_|iod|_d|i}nd}d|i}|d7}||7}|d|i7}|d |i7}|d |i7}|d 7}|d |i7}|d 7}|d7}|d7}|S(sø Render a node update description suitable for use in a uDraw file using the set internal attributes. @rtype: String @return: uDraw node update description. s s\nR#sa("IMAGE","%s"),Rsnew_node("%08x","",R$sa("_GO","%s"),sa("COLOR","#%06x"),sa("OBJECT","%s"),sa("FONTFAMILY","courier"),sa("INFO","%s"),sa("BORDER","none")t]t)(R RR&R RRR'(RR&R*((s,/pentest/voiper/sulley/sulley/pgraph/node.pytrender_node_udraw_updateŒs"          N(t__name__t __module__t__doc__RRRRR R R R R RRRRtNoneR&R'RRR"R-R0(((s,/pentest/voiper/sulley/sulley/pgraph/node.pyRs*  :  1N(R3tobjectR(((s,/pentest/voiper/sulley/sulley/pgraph/node.pyt<module>s
5,714
Python
.py
93
58.333333
506
0.402137
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,921
__init__.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pgraph/__init__.pyc
Ñò âпMc@s2dZddkTddkTddkTddkTdS(s™ @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org iÿÿÿÿ(t*N(t__doc__tclustertedgetgraphtnode(((s0/pentest/voiper/sulley/sulley/pgraph/__init__.pyt<module>s   
415
Python
.py
10
40.5
166
0.536946
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,922
edge.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pgraph/edge.py
# # pGRAPH # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' class edge (object): ''' ''' id = None src = None dst = None # general graph attributes. color = 0x000000 label = "" # gml relevant attributes. gml_arrow = "none" gml_stipple = 1 gml_line_width = 1.0 #################################################################################################################### def __init__ (self, src, dst): ''' Class constructor. @type src: Mixed @param src: Edge source @type dst: Mixed @param dst: Edge destination ''' # the unique id for any edge (provided that duplicates are not allowed) is the combination of the source and # the destination stored as a long long. self.id = (src << 32) + dst self.src = src self.dst = dst # general graph attributes. self.color = 0x000000 self.label = "" # gml relevant attributes. self.gml_arrow = "none" self.gml_stipple = 1 self.gml_line_width = 1.0 #################################################################################################################### def render_edge_gml (self, graph): ''' 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 ''' src = graph.find_node("id", self.src) dst = graph.find_node("id", self.dst) # ensure nodes exist at the source and destination of this edge. if not src or not dst: return "" edge = ' edge [\n' edge += ' source %d\n' % src.number edge += ' target %d\n' % dst.number edge += ' generalization 0\n' edge += ' graphics [\n' edge += ' type "line"\n' edge += ' arrow "%s"\n' % self.gml_arrow edge += ' stipple %d\n' % self.gml_stipple edge += ' lineWidth %f\n' % self.gml_line_width edge += ' fill "#%06x"\n' % self.color edge += ' ]\n' edge += ' ]\n' return edge #################################################################################################################### def render_edge_graphviz (self, graph): ''' 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 ''' import pydot # no need to validate if nodes exist for src/dst. graphviz takes care of that for us transparently. 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 #################################################################################################################### def render_edge_udraw (self, graph): ''' 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 ''' src = graph.find_node("id", self.src) dst = graph.find_node("id", self.dst) # ensure nodes exist at the source and destination of this edge. if not src or not dst: return "" # translate newlines for uDraw. self.label = self.label.replace("\n", "\\n") udraw = 'l("%08x->%08x",' % (self.src, self.dst) udraw += 'e("",' # open edge udraw += '[' # open attributes udraw += 'a("EDGECOLOR","#%06x"),' % self.color udraw += 'a("OBJECT","%s")' % self.label udraw += '],' # close attributes udraw += 'r("%08x")' % self.dst udraw += ')' # close edge udraw += ')' # close element return udraw #################################################################################################################### def render_edge_udraw_update (self): ''' Render an edge update description suitable for use in a GML file using the set internal attributes. @rtype: String @return: GML edge update description ''' # translate newlines for uDraw. 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 += ')' return udraw
6,271
Python
.py
140
37.235714
120
0.502381
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,923
edge.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pgraph/edge.pyc
Ñò âпMc@s dZdefd„ƒYZdS(s™ @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org tedgecBskeZdZd Zd Zd ZdZdZdZ dZ dZ d„Z d„Z d„Zd „Zd „ZRS( s ittnoneigð?cCsT|d>||_||_||_d|_d|_d|_d|_d|_dS(sž Class constructor. @type src: Mixed @param src: Edge source @type dst: Mixed @param dst: Edge destination i iRRigð?N(tidtsrctdsttcolortlabelt gml_arrowt gml_stippletgml_line_width(tselfRR((s,/pentest/voiper/sulley/sulley/pgraph/edge.pyt__init__)s       cCsá|id|iƒ}|id|iƒ}| p| odSd}|d|i7}|d|i7}|d7}|d7}|d7}|d |i7}|d |i7}|d |i7}|d |i7}|d 7}|d7}|S(s 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 RRs edge [ s source %d s target %d s generalization 0 s graphics [ s type "line" s arrow "%s" s stipple %d s lineWidth %f s fill "#%06x" s ] s ] (t find_nodeRRtnumberRR R R(R tgraphRRR((s,/pentest/voiper/sulley/sulley/pgraph/edge.pytrender_edge_gmlDs"      cCsRddk}|i|i|iƒ}|io|i|_nd|i|_|S(s! 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 iÿÿÿÿNs#%06x(tpydottEdgeRRRR(R RRtdot_edge((s,/pentest/voiper/sulley/sulley/pgraph/edge.pytrender_edge_graphvizgs  cCsÖ|id|iƒ}|id|iƒ}| p| odS|iiddƒ|_d|i|if}|d7}|d7}|d|i7}|d |i7}|d 7}|d |i7}|d 7}|d 7}|S( s 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 RRs s\nsl("%08x->%08x",se("",t[sa("EDGECOLOR","#%06x"),sa("OBJECT","%s")s],s r("%08x")t)(R RRRtreplaceR(R RRRtudraw((s,/pentest/voiper/sulley/sulley/pgraph/edge.pytrender_edge_udraw�s      cCsŒ|iiddƒ|_d|i|if}|d7}|d|i7}|d|i7}|d7}|d|i|if7}|d 7}|S( 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 s s\nsnew_edge("%08x->%08x","",Rsa("EDGECOLOR","#%06x"),sa("OBJECT","%s")s],s "%08x","%08x"R(RRRRR(R R((s,/pentest/voiper/sulley/sulley/pgraph/edge.pytrender_edge_udraw_update¤s    N(t__name__t __module__t__doc__tNoneRRRRRRR R R RRRR(((s,/pentest/voiper/sulley/sulley/pgraph/edge.pyRs  #  #N(RtobjectR(((s,/pentest/voiper/sulley/sulley/pgraph/edge.pyt<module>s
4,385
Python
.py
72
56.625
437
0.431723
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,924
graph.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pgraph/graph.py
# # pGRAPH # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' import node import edge import cluster import copy class graph (object): ''' @todo: Add support for clusters @todo: Potentially swap node list with a node dictionary for increased performance ''' id = None clusters = [] edges = {} nodes = {} #################################################################################################################### def __init__ (self, id=None): ''' ''' self.id = id self.clusters = [] self.edges = {} self.nodes = {} #################################################################################################################### def add_cluster (self, cluster): ''' Add a pgraph cluster to the graph. @type cluster: pGRAPH Cluster @param cluster: Cluster to add to graph ''' self.clusters.append(cluster) return self #################################################################################################################### def add_edge (self, edge, prevent_dups=True): ''' 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 ''' if prevent_dups: if self.edges.has_key(edge.id): return self # ensure the source and destination nodes exist. if self.find_node("id", edge.src) and self.find_node("id", edge.dst): self.edges[edge.id] = edge return self #################################################################################################################### def add_graph (self, other_graph): ''' 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. ''' return self.graph_cat(other_graph) #################################################################################################################### def add_node (self, node): ''' 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 ''' node.number = len(self.nodes) if not self.nodes.has_key(node.id): self.nodes[node.id] = node return self #################################################################################################################### def del_cluster (self, id): ''' Remove a cluster from the graph. @type id: Mixed @param id: Identifier of cluster to remove from graph ''' for cluster in self.clusters: if cluster.id == id: self.clusters.remove(cluster) break return self #################################################################################################################### def del_edge (self, id=None, src=None, dst=None): ''' 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: (Optional) Source of edge to remove from graph @type dst: Mixed @param dst: (Optional) Destination of edge to remove from graph ''' if not id: id = (src << 32) + dst if self.edges.has_key(id): del self.edges[id] return self #################################################################################################################### def del_graph (self, other_graph): ''' 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 ''' return self.graph_sub(other_graph) #################################################################################################################### def del_node (self, id): ''' Remove a node from the graph. @type node_id: Mixed @param node_id: Identifier of node to remove from graph ''' if self.nodes.has_key(id): del self.nodes[id] return self #################################################################################################################### def edges_from (self, id): ''' 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 ''' return [edge for edge in self.edges.values() if edge.src == id] #################################################################################################################### def edges_to (self, 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 ''' return [edge for edge in self.edges.values() if edge.dst == id] #################################################################################################################### def find_cluster (self, attribute, value): ''' 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. ''' for cluster in self.clusters: if hasattr(cluster, attribute): if getattr(cluster, attribute) == value: return cluster return None #################################################################################################################### def find_cluster_by_node (self, attribute, value): ''' 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 is matched. None otherwise. ''' for cluster in self.clusters: for node in cluster: if hasattr(node, attribute): if getattr(node, attribute) == value: return cluster return None #################################################################################################################### def find_edge (self, attribute, value): ''' 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. ''' # if the attribute to search for is the id, simply return the edge from the internal hash. if attribute == "id" and self.edges.has_key(value): return self.edges[value] # step through all the edges looking for the given attribute/value pair. else: for edges in self.edges.values(): if hasattr(edge, attribute): if getattr(edge, attribute) == value: return edge return None #################################################################################################################### def find_node (self, attribute, value): ''' 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. ''' # if the attribute to search for is the id, simply return the node from the internal hash. if attribute == "id" and self.nodes.has_key(value): return self.nodes[value] # step through all the nodes looking for the given attribute/value pair. else: for node in self.nodes.values(): if hasattr(node, attribute): if getattr(node, attribute) == value: return node return None #################################################################################################################### def graph_cat (self, other_graph): ''' 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. ''' 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 #################################################################################################################### def graph_down (self, from_node_id, max_depth=-1): ''' 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.graph @return: Down graph around specified node. ''' 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_process: next_level = [] if current_depth > max_depth and max_depth != -1: break for node in level: down_graph.add_node(copy.copy(node)) for edge in self.edges_from(node.id): to_add = self.find_node("id", edge.dst) if not down_graph.find_node("id", edge.dst): next_level.append(to_add) down_graph.add_node(copy.copy(to_add)) down_graph.add_edge(copy.copy(edge)) if next_level: levels_to_process.append(next_level) current_depth += 1 return down_graph #################################################################################################################### def graph_intersect (self, other_graph): ''' 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 ''' 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 #################################################################################################################### def graph_proximity (self, center_node_id, max_depth_up=2, max_depth_down=2): ''' 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 @param max_depth_down: (Optional, Def=2) Number of downward levels to include in proximity graph @rtype: pgraph.graph @return: Proximity graph around specified node. ''' 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 #################################################################################################################### def graph_sub (self, other_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 ''' 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 #################################################################################################################### def graph_up (self, from_node_id, max_depth=-1): ''' 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 @return: Up graph to the specified node. ''' 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 node in level: up_graph.add_node(copy.copy(node)) for edge in self.edges_to(node.id): to_add = self.find_node("id", edge.src) if not up_graph.find_node("id", edge.src): next_level.append(to_add) up_graph.add_node(copy.copy(to_add)) up_graph.add_edge(copy.copy(edge)) if next_level: levels_to_process.append(next_level) current_depth += 1 return up_graph #################################################################################################################### def render_graph_gml (self): ''' Render the GML graph description. @rtype: String @return: GML graph description. ''' gml = 'Creator "pGRAPH - Pedram Amini <pedram.amini@gmail.com>"\n' gml += 'directed 1\n' # open the graph tag. gml += 'graph [\n' # add the nodes to the GML definition. for node in self.nodes.values(): gml += node.render_node_gml(self) # add the edges to the GML definition. for edge in self.edges.values(): gml += edge.render_edge_gml(self) # close the graph tag. gml += ']\n' """ XXX - TODO: Complete cluster rendering # if clusters exist. if len(self.clusters): # open the rootcluster tag. gml += 'rootcluster [\n' # add the clusters to the GML definition. for cluster in self.clusters: gml += cluster.render() # add the clusterless nodes to the GML definition. for node in self.nodes: if not self.find_cluster_by_node("id", node.id): gml += ' vertex "%d"\n' % node.id # close the rootcluster tag. gml += ']\n' """ return gml #################################################################################################################### def render_graph_graphviz (self): ''' Render the graphviz graph structure. @rtype: pydot.Dot @return: Pydot object representing entire graph ''' 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 #################################################################################################################### def render_graph_udraw (self): ''' Render the uDraw graph description. @rtype: String @return: uDraw graph description. ''' udraw = '[' # render each of the nodes in the graph. # the individual nodes will handle their own edge rendering. for node in self.nodes.values(): udraw += node.render_node_udraw(self) udraw += ',' # trim the extraneous comment and close the graph. udraw = udraw[0:-1] + ']' return udraw #################################################################################################################### def render_graph_udraw_update (self): ''' Render the uDraw graph update description. @rtype: String @return: uDraw graph description. ''' 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 += ',' # trim the extraneous comment and close the graph. udraw = udraw[0:-1] + ']' return udraw #################################################################################################################### def update_node_id (self, current_id, new_id): ''' 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. ''' if not self.nodes.has_key(current_id): return # update the node. node = self.nodes[current_id] del self.nodes[current_id] node.id = new_id self.nodes[node.id] = node # update the edges. for edge in [edge for edge in self.edges.values() if current_id in (edge.src, edge.dst)]: del self.edges[edge.id] if edge.src == current_id: edge.src = new_id if edge.dst == current_id: edge.dst = new_id edge.id = (edge.src << 32) + edge.dst self.edges[edge.id] = edge #################################################################################################################### def sorted_nodes (self): ''' Return a list of the nodes within the graph, sorted by id. @rtype: List @return: List of nodes, sorted by id. ''' node_keys = self.nodes.keys() node_keys.sort() return [self.nodes[key] for key in node_keys]
21,768
Python
.py
478
35.740586
120
0.49706
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,925
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pgraph/__init__.py
# # pGRAPH # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' from cluster import * from edge import * from graph import * from node import *
1,012
Python
.py
24
41.125
119
0.764944
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,926
graph.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pgraph/graph.pyc
Ñò âпMc@sPdZddkZddkZddkZddkZdefd„ƒYZdS(s™ @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org iÿÿÿÿNtgraphcBs4eZdZdZgZhZhZdd„Zd„Z e d„Z d„Z d„Z d„Zdddd„Zd„Zd „Zd „Zd „Zd „Zd „Zd„Zd„Zd„Zdd„Zd„Zddd„Zd„Zdd„Zd„Zd„Zd„Z d„Z!d„Z"d„Z#RS(s€ @todo: Add support for clusters @todo: Potentially swap node list with a node dictionary for increased performance cCs(||_g|_h|_h|_dS(s N(tidtclusterstedgestnodes(tselfR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyt__init__)s   cCs|ii|ƒ|S(sŒ Add a pgraph cluster to the graph. @type cluster: pGRAPH Cluster @param cluster: Cluster to add to graph (Rtappend(Rtcluster((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyt add_cluster4scCsj|o|ii|iƒo|Sn|id|iƒo*|id|iƒo||i|i<n|S(sq 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 R(Rthas_keyRt find_nodetsrctdst(Rtedget prevent_dups((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytadd_edgeBs  ,cCs |i|ƒS(s 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. (t graph_cat(Rt other_graph((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyt add_graphXs cCs@t|iƒ|_|ii|iƒp||i|i<n|S(s 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 (tlenRtnumberR R(Rtnode((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytadd_nodegscCs=x6|iD]+}|i|jo|ii|ƒPq q W|S(sŠ Remove a cluster from the graph. @type id: Mixed @param id: Identifier of cluster to remove from graph (RRtremove(RRR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyt del_clusterxs   cCs>|p|d>|}n|ii|ƒo|i|=n|S(s! 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: (Optional) Source of edge to remove from graph @type dst: Mixed @param dst: (Optional) Destination of edge to remove from graph i (RR (RRR R ((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytdel_edge‰s cCs |i|ƒS(s3 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 (t graph_sub(RR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyt del_graph¥s cCs%|ii|ƒo|i|=n|S(sŽ Remove a node from the graph. @type node_id: Mixed @param node_id: Identifier of node to remove from graph (RR (RR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytdel_nodeµscCs<g}|iiƒD]!}|i|jo ||qq~S(sä 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 (RtvaluesR (RRt_[1]R((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyt edges_fromÄs cCs<g}|iiƒD]!}|i|jo ||qq~S(sÞ 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 (RRR (RRRR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytedges_toÓs cCsGx@|iD]5}t||ƒot||ƒ|jo|Sq q WdS(s~ 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. N(RthasattrtgetattrtNone(Rt attributetvalueR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyt find_clusterâs  cCsXxQ|iD]F}x=|D]5}t||ƒot||ƒ|jo|SqqWq WdS(sŸ 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 is matched. None otherwise. N(RR"R#R$(RR%R&RR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytfind_cluster_by_nodeøs cCsy|djo|ii|ƒo |i|SxF|iiƒD]5}tt|ƒott|ƒ|jotSq<q<WdS(sx 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. RN(RR RR"RR#R$(RR%R&R((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyt find_edges   cCsy|djo|ii|ƒo |i|SxF|iiƒD]5}t||ƒot||ƒ|jo|Sq<q<WdS(sx 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. RN(RR RR"R#R$(RR%R&R((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyR +s   cCsRx$|iiƒD]}|i|ƒqWx$|iiƒD]}|i|ƒq7W|S(sÖ 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. (RRRRR(RRt other_nodet other_edge((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyRGs iÿÿÿÿc CsYtƒ}|id|ƒ}|pd|GHt‚ng}d}|i|gƒx|D]ù}g}||jo|djoPnx©|D]¡} |iti| ƒƒx‚|i| iƒD]n} |id| iƒ} |id| iƒp|i| ƒn|iti| ƒƒ|i ti| ƒƒq¹WqŠW|o|i|ƒn|d7}qXW|S(s³ 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.graph @return: Down graph around specified node. Rsunable to resolve node %08xiiÿÿÿÿ( RR t ExceptionRRtcopyR RR R( Rt from_node_idt max_deptht down_grapht from_nodetlevels_to_processt current_depthtlevelt next_levelRRtto_add((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyt graph_down[s6   cCsŒxA|iiƒD]0}|id|iƒp|i|iƒqqWxA|iiƒD]0}|id|iƒp|i|iƒqTqTW|S(sé 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 R(RRR RRRR)R(RRRR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytgraph_intersect�s icCs/|i||ƒ}|i|i||ƒƒ|S(s7 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 @param max_depth_down: (Optional, Def=2) Number of downward levels to include in proximity graph @rtype: pgraph.graph @return: Proximity graph around specified node. (R7Rtgraph_up(Rtcenter_node_idt max_depth_uptmax_depth_downt prox_graph((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytgraph_proximity¥scCsax'|iiƒD]}|i|iƒqWx0|iiƒD]}|id|i|iƒq:W|S(s 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 N( RRRRRRR$R R (RRR*R+((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyR»s c Cs?tƒ}|id|ƒ}g}d}|i|gƒx|D]ù}g}||jo|djoPnx©|D]¡} |iti| ƒƒx‚|i| iƒD]n} |id| iƒ} |id| iƒp|i| ƒn|iti| ƒƒ|iti| ƒƒqŸWqpW|o|i|ƒn|d7}q>W|S(s« 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 @return: Up graph to the specified node. Riiÿÿÿÿ( RR RRR-R!RR R( RR.R/tup_graphR1R2R3R4R5RRR6((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyR9Ðs0 cCs‚d}|d7}|d7}x*|iiƒD]}||i|ƒ7}q*Wx*|iiƒD]}||i|ƒ7}qWW|d7}|S(st Render the GML graph description. @rtype: String @return: GML graph description. s9Creator "pGRAPH - Pedram Amini <pedram.amini@gmail.com>" s directed 1 sgraph [ s] (RRtrender_node_gmlRtrender_edge_gml(RtgmlRR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytrender_graph_gmls   cCs|ddk}|iƒ}x-|iiƒD]}|i|i|ƒƒq(Wx-|iiƒD]}|i|i|ƒƒqXW|S(sŠ Render the graphviz graph structure. @rtype: pydot.Dot @return: Pydot object representing entire graph iÿÿÿÿN( tpydottDotRRRtrender_node_graphvizRRtrender_edge_graphviz(RRDt dot_graphRR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytrender_graph_graphviz1s  cCsRd}x4|iiƒD]#}||i|ƒ7}|d7}qW|dd!d}|S(sx Render the uDraw graph description. @rtype: String @return: uDraw graph description. t[t,iiÿÿÿÿt](RRtrender_node_udraw(RtudrawR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytrender_graph_udrawGscCsƒd}x1|iiƒD] }||iƒ7}|d7}qWx1|iiƒD] }||iƒ7}|d7}qJW|dd!d}|S(s Render the uDraw graph update description. @rtype: String @return: uDraw graph description. RJRKiiÿÿÿÿRL(RRtrender_node_udraw_updateRtrender_edge_udraw_update(RRNRR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytrender_graph_udraw_update^scCs |ii|ƒpdS|i|}|i|=||_||i|i<x½g}|iiƒD]*}||i|ifjo ||q_q_~D]t}|i|i=|i|jo ||_n|i|jo ||_n|id>|i|_||i|i<q�WdS(sc 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. Ni (RR RRRR R (Rt current_idtnew_idRRR((s-/pentest/voiper/sulley/sulley/pgraph/graph.pytupdate_node_idws    H   cCs?|iiƒ}|iƒg}|D]}||i|q$~S(s‘ Return a list of the nodes within the graph, sorted by id. @rtype: List @return: List of nodes, sorted by id. (Rtkeystsort(Rt node_keysRtkey((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyt sorted_nodesšs N($t__name__t __module__t__doc__R$RRRRRR tTrueRRRRRRRR R!R'R(R)R RR7R8R>RR9RCRIRORRRURZ(((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyRs@               4   0 1    #(R]RRRR-tobjectR(((s-/pentest/voiper/sulley/sulley/pgraph/graph.pyt<module>s     
17,107
Python
.py
219
70.972603
557
0.474534
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,927
node.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/pgraph/node.py
# # pGRAPH # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' class node (object): ''' ''' id = 0 number = 0 # general graph attributes color = 0xEEF7FF border_color = 0xEEEEEE label = "" shape = "box" # gml relevant attributes. gml_width = 0.0 gml_height = 0.0 gml_pattern = "1" gml_stipple = 1 gml_line_width = 1.0 gml_type = "rectangle" gml_width_shape = 1.0 # udraw relevant attributes. udraw_image = None udraw_info = "" #################################################################################################################### def __init__ (self, id=None): ''' ''' self.id = id self.number = 0 # general graph attributes self.color = 0xEEF7FF self.border_color = 0xEEEEEE self.label = "" self.shape = "box" # gml relevant attributes. 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_width_shape = 1.0 #################################################################################################################### def render_node_gml (self, graph): ''' 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. ''' # GDE does not like lines longer then approx 250 bytes. within their their own GML files you won't find lines # longer then approx 210 bytes. wo we are forced to break long lines into chunks. chunked_label = "" cursor = 0 while cursor < len(self.label): amount = 200 # if the end of the current chunk contains a backslash or double-quote, back off some. if cursor + amount < len(self.label): while self.label[cursor+amount] == '\\' or self.label[cursor+amount] == '"': amount -= 1 chunked_label += self.label[cursor:cursor+amount] + "\\\n" cursor += amount # if node width and height were not explicitly specified, make a best effort guess to create something nice. if not self.gml_width: self.gml_width = len(self.label) * 10 if not self.gml_height: self.gml_height = len(self.label.split()) * 20 # construct the node definition. node = ' node [\n' node += ' id %d\n' % self.number node += ' template "oreas:std:rect"\n' node += ' label "' node += '<!--%08x-->\\\n' % self.id node += chunked_label + '"\n' node += ' graphics [\n' node += ' w %f\n' % self.gml_width node += ' h %f\n' % self.gml_height node += ' fill "#%06x"\n' % self.color node += ' line "#%06x"\n' % self.border_color node += ' pattern "%s"\n' % self.gml_pattern node += ' stipple %d\n' % self.gml_stipple node += ' lineWidth %f\n' % self.gml_line_width node += ' type "%s"\n' % self.gml_type node += ' width %f\n' % self.gml_width_shape node += ' ]\n' node += ' ]\n' return node #################################################################################################################### def render_node_graphviz (self, graph): ''' 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 ''' 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" % self.color return dot_node #################################################################################################################### def render_node_udraw (self, graph): ''' 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. ''' # translate newlines for uDraw. self.label = self.label.replace("\n", "\\n") # if an image was specified for this node, update the shape and include the image tag. 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("",' # open node udraw += '[' # open attributes udraw += udraw_image udraw += 'a("_GO","%s"),' % self.shape udraw += 'a("COLOR","#%06x"),' % self.color udraw += 'a("OBJECT","%s"),' % self.label udraw += 'a("FONTFAMILY","courier"),' udraw += 'a("INFO","%s"),' % self.udraw_info udraw += 'a("BORDER","none")' udraw += '],' # close attributes udraw += '[' # open edges edges = graph.edges_from(self.id) for edge in edges: udraw += edge.render_edge_udraw(graph) udraw += ',' if edges: udraw = udraw[0:-1] udraw += ']))' return udraw #################################################################################################################### def render_node_udraw_update (self): ''' Render a node update description suitable for use in a uDraw file using the set internal attributes. @rtype: String @return: uDraw node update description. ''' # translate newlines for uDraw. self.label = self.label.replace("\n", "\\n") # if an image was specified for this node, update the shape and include the image tag. 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"),' % self.shape udraw += 'a("COLOR","#%06x"),' % self.color udraw += 'a("OBJECT","%s"),' % self.label udraw += 'a("FONTFAMILY","courier"),' udraw += 'a("INFO","%s"),' % self.udraw_info udraw += 'a("BORDER","none")' udraw += ']' udraw += ')' return udraw
8,623
Python
.py
187
37.946524
120
0.483906
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,928
xdr.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/xdr.py
######################################################################################################################## ### XDR TYPES (http://www.freesoft.org/CIE/RFC/1832/index.htm) ######################################################################################################################## import struct from sulley import blocks, primitives, sex ######################################################################################################################## def xdr_pad (string): return "\x00" * ((4 - (len(string) & 3)) & 3) ######################################################################################################################## class string (blocks.block): ''' Note: this is not for fuzzing the XDR protocol but rather just representing an XDR string for fuzzing the actual client. ''' def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.error("MISSING LEGO.xdr_string DEFAULT VALUE") self.push(primitives.string(self.value)) def render (self): ''' We overload and extend the render routine in order to properly pad and prefix the string. [dword length][array][pad] ''' # let the parent do the initial render. blocks.block.render(self) # encode the empty string correctly: if self.rendered == "": self.rendered = "\x00\x00\x00\x00" else: self.rendered = struct.pack(">L", len(self.rendered)) + self.rendered + xdr_pad(self.rendered) return self.rendered
1,740
Python
.py
34
44.323529
120
0.451804
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,929
misc.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/misc.pyc
Ñò âпMc@s�ddkZddklZlZlZdeifd„ƒYZdeifd„ƒYZdeifd„ƒYZd eifd „ƒYZ dS( iÿÿÿÿN(tblockst primitivestsextip_address_asciicBseZhd„ZRS(cCsÿtii|||ddddƒ||_||_|iptidƒ‚n|idƒ}d}x’|D]Š}|djo0|i t i |ƒƒ|i t i dƒƒn>|i t i |ƒƒ|djo|i t i dƒƒn|d7}qmWdS(NsMISSING LEGO.tag DEFAULT VALUEt.iii(Rtblockt__init__tNonetvaluetoptionsRterrortsplittpushRtstringtdelimtstatic(tselftnametrequestRR tip_arrtctrtip_val((s+/pentest/voiper/sulley/sulley/legos/misc.pyRs "     (t__name__t __module__R(((s+/pentest/voiper/sulley/sulley/legos/misc.pyRstipv6_address_asciicBseZhd„ZRS(cCsÿtii|||ddddƒ||_||_|iptidƒ‚n|idƒ}d}x’|D]Š}|djo0|i t i |ƒƒ|i t i dƒƒn>|i t i |ƒƒ|djo|i t i dƒƒn|d7}qmWdS(NsMISSING LEGO.tag DEFAULT VALUEt:iii(RRRRRR RR R R RR RR(RRRRR thex_arrRthex_val((s+/pentest/voiper/sulley/sulley/legos/misc.pyRs "     (RRR(((s+/pentest/voiper/sulley/sulley/legos/misc.pyRst dns_hostnamecBseZhd„Zd„ZRS(cCsntii|||ddddƒ||_||_|iptidƒ‚n|it i |iƒƒdS(NsMISSING LEGO.tag DEFAULT VALUE( RRRRRR RR R RR (RRRRR ((s+/pentest/voiper/sulley/sulley/legos/misc.pyR4s "   cCsatii|ƒd}x4|iidƒD] }|tt|ƒƒ|7}q)W|d|_|iS(sj We overload and extend the render routine in order to properly insert substring lengths. tRt(RRtrendertrenderedR tstrtlen(Rtnew_strtpart((s+/pentest/voiper/sulley/sulley/legos/misc.pyR@s (RRRR(((s+/pentest/voiper/sulley/sulley/legos/misc.pyR3s ttagcBseZhd„ZRS(cCsštii|||ddddƒ||_||_|iptidƒ‚n|it i dƒƒ|it i |iƒƒ|it i dƒƒdS(NsMISSING LEGO.tag DEFAULT VALUEt<t>( RRRRRR RR R RRR (RRRRR ((s+/pentest/voiper/sulley/sulley/legos/misc.pyRVs"   (RRR(((s+/pentest/voiper/sulley/sulley/legos/misc.pyR%Us( tstructtsulleyRRRRRRRR%(((s+/pentest/voiper/sulley/sulley/legos/misc.pyt<module>s "
3,490
Python
.py
27
127.666667
475
0.361143
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,930
dcerpc.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/dcerpc.py
######################################################################################################################## ### MSRPC NDR TYPES ######################################################################################################################## import struct from sulley import blocks, primitives, sex ######################################################################################################################## def ndr_pad (string): return "\x00" * ((4 - (len(string) & 3)) & 3) ######################################################################################################################## class ndr_conformant_array (blocks.block): ''' Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual client. ''' def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.error("MISSING LEGO.ndr_conformant_array DEFAULT VALUE") self.push(primitives.string(self.value)) def render (self): ''' We overload and extend the render routine in order to properly pad and prefix the string. [dword length][array][pad] ''' # let the parent do the initial render. blocks.block.render(self) # encode the empty string correctly: if self.rendered == "": self.rendered = "\x00\x00\x00\x00" else: self.rendered = struct.pack("<L", len(self.rendered)) + self.rendered + ndr_pad(self.rendered) return self.rendered ######################################################################################################################## class ndr_string (blocks.block): ''' Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual client. ''' def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.error("MISSING LEGO.tag DEFAULT VALUE") self.push(primitives.string(self.value)) def render (self): ''' We overload and extend the render routine in order to properly pad and prefix the string. [dword length][dword offset][dword passed size][string][pad] ''' # let the parent do the initial render. blocks.block.render(self) # encode the empty string correctly: if self.rendered == "": self.rendered = "\x00\x00\x00\x00" else: # ensure null termination. self.rendered += "\x00" # format accordingly. length = len(self.rendered) self.rendered = struct.pack("<L", length) \ + struct.pack("<L", 0) \ + struct.pack("<L", length) \ + self.rendered \ + ndr_pad(self.rendered) return self.rendered ######################################################################################################################## class ndr_wstring (blocks.block): ''' Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual client. ''' def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.error("MISSING LEGO.tag DEFAULT VALUE") self.push(primitives.string(self.value)) def render (self): ''' We overload and extend the render routine in order to properly pad and prefix the string. [dword length][dword offset][dword passed size][string][pad] ''' # let the parent do the initial render. blocks.block.render(self) # encode the empty string correctly: if self.rendered == "": self.rendered = "\x00\x00\x00\x00" else: # unicode encode and null terminate. self.rendered = self.rendered.encode("utf-16le") + "\x00" # format accordingly. length = len(self.rendered) self.rendered = struct.pack("<L", length) \ + struct.pack("<L", 0) \ + struct.pack("<L", length) \ + self.rendered \ + ndr_pad(self.rendered) return self.rendered
4,841
Python
.py
102
37.754902
120
0.48904
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,931
ber.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/ber.pyc
Ñò âпMc@s^ddkZddklZlZlZdeifd„ƒYZdeifd„ƒYZdS(iÿÿÿÿN(tblockst primitivestsextstringcBs#eZdZhd„Zd„ZRS(sp [0x04][0x84][dword length][string] Where: 0x04 = string 0x84 = length is 4 bytes cCsÏtii|||ddddƒ||_||_|iddƒ|_|ipti dƒ‚nti|d|ƒ}|i t i |iƒƒ|i ti |d|dddtƒƒ|i |ƒdS(Ntprefixss%MISSING LEGO.ber_string DEFAULT VALUEt_STRtendiant>tfuzzable(Rtblockt__init__tNonetvaluetoptionstgetRRterrortpushRRtsizetTrue(tselftnametrequestR R t str_block((s*/pentest/voiper/sulley/sulley/legos/ber.pyR s"   )cCs.tii|ƒ|id|i|_|iS(Ns„(RR trenderRtrendered(R((s*/pentest/voiper/sulley/sulley/legos/ber.pyR%s(t__name__t __module__t__doc__R R(((s*/pentest/voiper/sulley/sulley/legos/ber.pyR s tintegercBs#eZdZhd„Zd„ZRS(sj [0x02][0x04][dword] Where: 0x02 = integer 0x04 = integer length is 4 bytes cCsttii|||ddddƒ||_||_|iptidƒ‚n|it i |iddƒƒdS(Ns&MISSING LEGO.ber_integer DEFAULT VALUERR( RR R R R R RRRRtdword(RRRR R ((s*/pentest/voiper/sulley/sulley/legos/ber.pyR 9s "   cCs'tii|ƒd|i|_|iS(Ns(RR RR(R((s*/pentest/voiper/sulley/sulley/legos/ber.pyREs(RRRR R(((s*/pentest/voiper/sulley/sulley/legos/ber.pyR/s (tstructtsulleyRRRR RR(((s*/pentest/voiper/sulley/sulley/legos/ber.pyt<module>s %
2,329
Python
.py
26
86.269231
362
0.382609
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,932
sip.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/sip.pyc
Ñò âпMc@sÛddkZddklZlZlZdeifd„ƒYZdeifd„ƒYZdeifd„ƒYZd eifd „ƒYZ d eifd „ƒYZ d eifd„ƒYZ deifd„ƒYZ dS(iÿÿÿÿN(tblockst primitivestsextq_valuecBseZhd„ZRS(c Csîtii|||ddddƒ||_||_|iidƒo|id}nt}|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i ddtdtdd ƒƒdS( Ntfuzzabletqt=t0t.itsignedtformattascii( Rtblockt__init__tNonetvaluetoptionsthas_keytTruetpushRtstringtdelimtdword(tselftnametrequestRRR((s*/pentest/voiper/sulley/sulley/legos/sip.pyR s"  (t__name__t __module__R (((s*/pentest/voiper/sulley/sulley/legos/sip.pyRststatic_challengecBseZhd„ZRS(cCs’tii|||ddddƒ||_||_|iidƒo|id}nt}|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒ|it i d ƒƒ|it i dƒƒ|it i d d|ƒƒ|it i d ƒƒ|it i d d|ƒƒ|it i dƒƒ|it i d d|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒdS(NRtDigestt trealmRs"s atlanta.comt,sdomain=ssip:ss1.carrier.coms",qop="tauthsauth-ints ",nonce="tf84f1cec41e6cbe5aea9c8e88d359s ",opaque="t 5ccc069c403ebaf9f0171e9517f40e41s",stale=tFALSEs ,algorithm=tMD5( RR R RRRRRRRRRtstatic(RRRRRR((s*/pentest/voiper/sulley/sulley/legos/sip.pyR s:"  (RRR (((s*/pentest/voiper/sulley/sulley/legos/sip.pyRststatic_credentialscBseZhd„ZRS(cCs˜tii|||ddddƒ||_||_|iidƒo|id}nt}|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒ|it i d ƒƒ|it i dƒƒ|it i dƒƒ|it i d d|ƒƒ|it i dƒƒ|it i dƒƒ|it i d ƒƒ|it i dƒƒ|it i d d|ƒƒ|it i dƒƒ|it i dƒƒ|it i d ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒ|it i dƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒ|it i dƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒ|it i dƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒdS(NRRRtusernameRs"tnnpR Rs atlanta.comsuri=shttp://www.unprotectedhex.com/s response=t f84f1cec41e6cbe5aea9c8e88d359defsqop=R!snc=tf84f1cescnonce=R"snonce=sopaque=R#( RR R RRRRRRRRRR&(RRRRRR((s*/pentest/voiper/sulley/sulley/legos/sip.pyR =sh"  (RRR (((s*/pentest/voiper/sulley/sulley/legos/sip.pyR'<st to_sip_uricBseZhd„ZRS(cCsZtii|||ddddƒ||_||_|iidƒo|id}nt}|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i d ƒƒ|it i d d|ƒƒ|it i d ƒƒ|it i d d|ƒƒ|it i d ƒƒ|it i d ƒƒ|it i d d|ƒƒ|it i d ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i d ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i d ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i d ƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒdS(NRtsipt:t TARGET_USERtpasswordt@tHOSTtPORTt;t transportRtudpsuser=sttl=t67smethod=tINVITEsmaddr=t?tsubjectthvalt&s hname2=hval( RR R RRRRRRRRRR&(RRRRRR((s*/pentest/voiper/sulley/sulley/legos/sip.pyR ‚sJ"  (RRR (((s*/pentest/voiper/sulley/sulley/legos/sip.pyR,�st from_sip_uricBseZhd„ZRS(cCsZtii|||ddddƒ||_||_|iidƒo|id}nt}|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i d ƒƒ|it i d d|ƒƒ|it i d ƒƒ|it i d d|ƒƒ|it i d ƒƒ|it i d ƒƒ|it i d d|ƒƒ|it i d ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i d ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i d ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i d ƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dƒƒdS(NRR-R.tUSERR0R1tLOCAL_IPR3R4R5RR6suser=sttl=R7smethod=R8smaddr=R9R:R;R<s hname2=hval( RR R RRRRRRRRRR&(RRRRRR((s*/pentest/voiper/sulley/sulley/legos/sip.pyR ³sJ"  (RRR (((s*/pentest/voiper/sulley/sulley/legos/sip.pyR=²stfrom_sip_uri_basiccBseZhd„ZRS(cCsxtii|||ddddƒ||_||_|iidƒo|id}nt}|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i d d|ƒƒ|it i d ƒƒ|it i d d|ƒƒdS( NRR-R.R>R1R?R3R4R5RR6( RR R RRRRRRRRR(RRRRRR((s*/pentest/voiper/sulley/sulley/legos/sip.pyR æs""  (RRR (((s*/pentest/voiper/sulley/sulley/legos/sip.pyR@åstto_sip_uri_basiccBseZhd„ZRS(cCsxtii|||ddddƒ||_||_|iidƒo|id}nt}|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i dd|ƒƒ|it i dƒƒ|it i d d|ƒƒ|it i d ƒƒ|it i d d|ƒƒdS( NRR-R.R/R1R2R3R4R5RR6( RR R RRRRRRRRR(RRRRRR((s*/pentest/voiper/sulley/sulley/legos/sip.pyR s""  (RRR (((s*/pentest/voiper/sulley/sulley/legos/sip.pyRAs( tstructtsulleyRRRR RRR'R,R=R@RA(((s*/pentest/voiper/sulley/sulley/legos/sip.pyt<module>s %E13
9,172
Python
.py
75
121.28
823
0.314575
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,933
__init__.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/__init__.pyc
Ñò âпMc@s0ddkZddkZddkZddkZddkZhZeied<eied<eied<ei ed<ei ed<ei ed<ei ed<ei ed <eied <ei ed<eied <eied <eied <eied<eied<eied<eied<eied<dS(iÿÿÿÿNt ber_stringt ber_integert dns_hostnametip_address_asciitndr_conformant_arrayt ndr_wstringt ndr_stringttagt xdr_stringtipv6_address_asciitstatic_credentialststatic_challengetq_valuet to_sip_urit from_sip_uritto_sip_uri_basictfrom_sip_uri_basic(tbertdcerpctmisctxdrtsiptBINtstringtintegerRRRRRRR R R R R RRR(((s//pentest/voiper/sulley/sulley/legos/__init__.pyt<module>s.                      
933
Python
.py
9
102.666667
190
0.456216
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,934
dcerpc.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/dcerpc.pyc
—Ú ‚–øMc@sÄddkZddklZlZlZdÑZdeifdÑÉYZdeifdÑÉYZdeifd ÑÉYZ dS( iˇˇˇˇN(tblockst primitivestsexcCsddt|Éd@d@S(Ntii(tlen(tstring((s-/pentest/voiper/sulley/sulley/legos/dcerpc.pytndr_pad stndr_conformant_arraycBs#eZdZhdÑZdÑZRS(sÜ Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual client. cCsntii|||ddddÉ||_||_|iptidÉÇn|it i |iÉÉdS(Ns/MISSING LEGO.ndr_conformant_array DEFAULT VALUE( Rtblockt__init__tNonetvaluetoptionsRterrortpushRR(tselftnametrequestR R ((s-/pentest/voiper/sulley/sulley/legos/dcerpc.pyR s "   cCsftii|É|idjo d|_n3tidt|iÉÉ|it|iÉ|_|iS(sè We overload and extend the render routine in order to properly pad and prefix the string. [dword length][array][pad] tts<L(RRtrendertrenderedtstructtpackRR(R((s-/pentest/voiper/sulley/sulley/legos/dcerpc.pyR!s  2(t__name__t __module__t__doc__R R(((s-/pentest/voiper/sulley/sulley/legos/dcerpc.pyRs t ndr_stringcBs#eZdZhdÑZdÑZRS(sÜ Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual client. cCsntii|||ddddÉ||_||_|iptidÉÇn|it i |iÉÉdS(NsMISSING LEGO.tag DEFAULT VALUE( RRR R R R RR RRR(RRRR R ((s-/pentest/voiper/sulley/sulley/legos/dcerpc.pyR ;s "   cCsõtii|É|idjo d|_nh|id7_t|iÉ}tid|ÉtiddÉtid|É|it|iÉ|_|iS(s± We overload and extend the render routine in order to properly pad and prefix the string. [dword length][dword offset][dword passed size][string][pad] RRRs<Li(RRRRRRRR(Rtlength((s-/pentest/voiper/sulley/sulley/legos/dcerpc.pyRGs I(RRRR R(((s-/pentest/voiper/sulley/sulley/legos/dcerpc.pyR5s t ndr_wstringcBs#eZdZhdÑZdÑZRS(sÜ Note: this is not for fuzzing the RPC protocol but rather just representing an NDR string for fuzzing the actual client. cCsntii|||ddddÉ||_||_|iptidÉÇn|it i |iÉÉdS(NsMISSING LEGO.tag DEFAULT VALUE( RRR R R R RR RRR(RRRR R ((s-/pentest/voiper/sulley/sulley/legos/dcerpc.pyR js "   cCs•tii|É|idjo d|_nr|iidÉd|_t|iÉ}tid|ÉtiddÉtid|É|it|iÉ|_|iS(s± We overload and extend the render routine in order to properly pad and prefix the string. [dword length][dword offset][dword passed size][string][pad] RRsutf-16leRs<Li( RRRRtencodeRRRR(RR((s-/pentest/voiper/sulley/sulley/legos/dcerpc.pyRvs I(RRRR R(((s-/pentest/voiper/sulley/sulley/legos/dcerpc.pyRds ( RtsulleyRRRRRRRR(((s-/pentest/voiper/sulley/sulley/legos/dcerpc.pyt<module>s  &/
4,273
Python
.py
36
114.611111
387
0.429752
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,935
sip.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/sip.py
import struct from sulley import blocks, primitives, sex class q_value (blocks.block): def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options # fuzz by default if self.options.has_key('fuzzable'): fuzzable = self.options['fuzzable'] else: fuzzable = True self.push(primitives.string("q" ,fuzzable=fuzzable)) self.push(primitives.delim("=")) self.push(primitives.string("0", fuzzable=fuzzable)) self.push(primitives.delim(".")) self.push(primitives.dword(5, fuzzable=True, signed=True, format="ascii")) class static_challenge (blocks.block): def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options # fuzz by default if self.options.has_key('fuzzable'): fuzzable = self.options['fuzzable'] else: fuzzable = True self.push(primitives.string("Digest" ,fuzzable=fuzzable)) self.push(primitives.delim(" ")) self.push(primitives.string("realm" ,fuzzable=fuzzable)) self.push(primitives.delim("=")) self.push(primitives.delim("\"")) self.push(primitives.string("atlanta.com" ,fuzzable=fuzzable)) self.push(primitives.delim("\"")) self.push(primitives.delim(",")) self.push(primitives.static("domain=")) self.push(primitives.static("\"")) self.push(primitives.string("sip:ss1.carrier.com" ,fuzzable=fuzzable)) self.push(primitives.static("\",qop=\"")) self.push(primitives.string("auth" ,fuzzable=fuzzable)) self.push(primitives.delim(",")) self.push(primitives.string("auth-int" ,fuzzable=fuzzable)) self.push(primitives.static("\",nonce=\"")) self.push(primitives.string("f84f1cec41e6cbe5aea9c8e88d359" ,fuzzable=fuzzable)) self.push(primitives.static("\",opaque=\"")) self.push(primitives.string("5ccc069c403ebaf9f0171e9517f40e41" ,fuzzable=fuzzable)) self.push(primitives.static("\",stale=")) self.push(primitives.string("FALSE" ,fuzzable=fuzzable)) self.push(primitives.static(",algorithm=")) self.push(primitives.static("MD5")) class static_credentials (blocks.block): def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options # fuzz by default if self.options.has_key('fuzzable'): fuzzable = self.options['fuzzable'] else: fuzzable = True self.push(primitives.string("Digest" ,fuzzable=fuzzable)) self.push(primitives.delim(" ")) self.push(primitives.string("username" ,fuzzable=fuzzable)) self.push(primitives.delim("=")) self.push(primitives.delim("\"")) self.push(primitives.string("nnp" ,fuzzable=fuzzable)) self.push(primitives.delim("\"")) self.push(primitives.delim(",")) self.push(primitives.static("realm")) self.push(primitives.static("=")) self.push(primitives.static("\"")) self.push(primitives.string("atlanta.com" ,fuzzable=fuzzable)) self.push(primitives.static("\"")) self.push(primitives.static(",")) self.push(primitives.static("uri=")) self.push(primitives.static("\"")) self.push(primitives.string("http://www.unprotectedhex.com/" ,fuzzable=fuzzable))# rquest-uri self.push(primitives.static("\"")) self.push(primitives.static(",")) self.push(primitives.static("response=")) self.push(primitives.static("\"")) self.push(primitives.string("f84f1cec41e6cbe5aea9c8e88d359def" ,fuzzable=fuzzable)) self.push(primitives.static("\"")) self.push(primitives.static(",")) self.push(primitives.static("qop=")) self.push(primitives.static("\"")) self.push(primitives.string("auth" ,fuzzable=fuzzable)) self.push(primitives.static("\"")) self.push(primitives.static(",")) self.push(primitives.static("nc=")) self.push(primitives.string("f84f1ce" ,fuzzable=fuzzable)) # 8LHEX self.push(primitives.static(",")) self.push(primitives.static("cnonce=")) self.push(primitives.static("\"")) self.push(primitives.string("f84f1cec41e6cbe5aea9c8e88d359" ,fuzzable=fuzzable)) self.push(primitives.static("\"")) self.push(primitives.static(",")) self.push(primitives.static("nonce=")) self.push(primitives.static("\"")) self.push(primitives.string("f84f1cec41e6cbe5aea9c8e88d359" ,fuzzable=fuzzable)) self.push(primitives.static("\"")) self.push(primitives.static(",")) self.push(primitives.static("opaque=")) self.push(primitives.static("\"")) self.push(primitives.string("5ccc069c403ebaf9f0171e9517f40e41" ,fuzzable=fuzzable)) self.push(primitives.static("\"")) class to_sip_uri (blocks.block): def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options # fuzz by default if self.options.has_key('fuzzable'): fuzzable = self.options['fuzzable'] else: fuzzable = True self.push(primitives.string("sip" ,fuzzable=fuzzable)) self.push(primitives.delim(":")) # userinfo self.push(primitives.string("TARGET_USER" ,fuzzable=fuzzable)) self.push(primitives.delim(":")) self.push(primitives.string("password" ,fuzzable=fuzzable)) self.push(primitives.delim("@")) # hostport self.push(primitives.string("HOST" ,fuzzable=fuzzable)) self.push(primitives.delim(":")) self.push(primitives.string("PORT" ,fuzzable=fuzzable)) # uri-parameters self.push(primitives.delim(";")) self.push(primitives.string("transport" ,fuzzable=fuzzable)) self.push(primitives.delim("=")) self.push(primitives.string("udp" ,fuzzable=fuzzable)) self.push(primitives.static(";")) self.push(primitives.static("user=")) self.push(primitives.string("udp" ,fuzzable=fuzzable)) self.push(primitives.static(";")) self.push(primitives.static("ttl=")) self.push(primitives.string("67" ,fuzzable=fuzzable)) self.push(primitives.static(";")) self.push(primitives.static("method=")) self.push(primitives.string("INVITE" ,fuzzable=fuzzable)) self.push(primitives.static(";")) self.push(primitives.static("maddr=")) self.push(primitives.string("HOST" ,fuzzable=fuzzable)) # headers self.push(primitives.delim("?")) self.push(primitives.string("subject" ,fuzzable=fuzzable)) self.push(primitives.delim("=")) self.push(primitives.string("hval" ,fuzzable=fuzzable)) self.push(primitives.delim("&")) self.push(primitives.static("hname2=hval")) class from_sip_uri (blocks.block): def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options # fuzz by default if self.options.has_key('fuzzable'): fuzzable = self.options['fuzzable'] else: fuzzable = True self.push(primitives.string("sip" ,fuzzable=fuzzable)) self.push(primitives.delim(":")) # userinfo self.push(primitives.string("USER" ,fuzzable=fuzzable)) self.push(primitives.delim(":")) self.push(primitives.string("password" ,fuzzable=fuzzable)) self.push(primitives.delim("@")) # hostport self.push(primitives.string("LOCAL_IP" ,fuzzable=fuzzable)) self.push(primitives.delim(":")) self.push(primitives.string("PORT" ,fuzzable=fuzzable)) # uri-parameters self.push(primitives.delim(";")) self.push(primitives.string("transport" ,fuzzable=fuzzable)) self.push(primitives.delim("=")) self.push(primitives.string("udp" ,fuzzable=fuzzable)) self.push(primitives.static(";")) self.push(primitives.static("user=")) self.push(primitives.string("udp" ,fuzzable=fuzzable)) self.push(primitives.static(";")) self.push(primitives.static("ttl=")) self.push(primitives.string("67" ,fuzzable=fuzzable)) self.push(primitives.static(";")) self.push(primitives.static("method=")) self.push(primitives.string("INVITE" ,fuzzable=fuzzable)) self.push(primitives.static(";")) self.push(primitives.static("maddr=")) self.push(primitives.string("LOCAL_IP" ,fuzzable=fuzzable)) # headers self.push(primitives.delim("?")) self.push(primitives.string("subject" ,fuzzable=fuzzable)) self.push(primitives.delim("=")) self.push(primitives.string("hval" ,fuzzable=fuzzable)) self.push(primitives.delim("&")) self.push(primitives.static("hname2=hval")) ######################################################################################################################## class from_sip_uri_basic (blocks.block): def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options # fuzz by default if self.options.has_key('fuzzable'): fuzzable = self.options['fuzzable'] else: fuzzable = True self.push(primitives.string("sip" ,fuzzable=fuzzable)) self.push(primitives.delim(":")) # userinfo self.push(primitives.string("USER" ,fuzzable=fuzzable)) self.push(primitives.delim("@")) # hostport self.push(primitives.string("LOCAL_IP" ,fuzzable=fuzzable)) self.push(primitives.delim(":")) self.push(primitives.string("PORT" ,fuzzable=fuzzable)) # uri-parameters self.push(primitives.delim(";")) self.push(primitives.string("transport" ,fuzzable=fuzzable)) self.push(primitives.delim("=")) self.push(primitives.string("udp" ,fuzzable=fuzzable)) ######################################################################################################################## class to_sip_uri_basic (blocks.block): def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options # fuzz by default if self.options.has_key('fuzzable'): fuzzable = self.options['fuzzable'] else: fuzzable = True self.push(primitives.string("sip" ,fuzzable=fuzzable)) self.push(primitives.delim(":")) # userinfo self.push(primitives.string("TARGET_USER" ,fuzzable=fuzzable)) self.push(primitives.delim("@")) # hostport self.push(primitives.string("HOST" ,fuzzable=fuzzable)) self.push(primitives.delim(":")) self.push(primitives.string("PORT" ,fuzzable=fuzzable)) # uri-parameters self.push(primitives.delim(";")) self.push(primitives.string("transport" ,fuzzable=fuzzable)) self.push(primitives.delim("=")) self.push(primitives.string("udp" ,fuzzable=fuzzable))
11,911
Python
.py
246
39
120
0.61894
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,936
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/__init__.py
import ber import dcerpc import misc import xdr import sip # all defined legos must be added to this bin. BIN = {} BIN["ber_string"] = ber.string BIN["ber_integer"] = ber.integer BIN["dns_hostname"] = misc.dns_hostname BIN["ip_address_ascii"] = misc.ip_address_ascii BIN["ndr_conformant_array"] = dcerpc.ndr_conformant_array BIN["ndr_wstring"] = dcerpc.ndr_wstring BIN["ndr_string"] = dcerpc.ndr_string BIN["tag"] = misc.tag BIN["xdr_string"] = xdr.string BIN["ip_address_ascii"] = misc.ip_address_ascii BIN["ipv6_address_ascii"] = misc.ipv6_address_ascii BIN["static_credentials"] = sip.static_credentials BIN["static_challenge"] = sip.static_challenge BIN["q_value"] = sip.q_value BIN["to_sip_uri"] = sip.to_sip_uri BIN["from_sip_uri"] = sip.from_sip_uri BIN["to_sip_uri_basic"] = sip.to_sip_uri_basic BIN["from_sip_uri_basic"] = sip.from_sip_uri_basic
935
Python
.py
25
36.28
57
0.675468
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,937
xdr.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/xdr.pyc
Ñò âпMc@sNddkZddklZlZlZd„Zdeifd„ƒYZdS(iÿÿÿÿN(tblockst primitivestsexcCsddt|ƒd@d@S(Ntii(tlen(tstring((s*/pentest/voiper/sulley/sulley/legos/xdr.pytxdr_pad sRcBs#eZdZhd„Zd„ZRS(s† Note: this is not for fuzzing the XDR protocol but rather just representing an XDR string for fuzzing the actual client. cCsntii|||ddddƒ||_||_|iptidƒ‚n|it i |iƒƒdS(Ns%MISSING LEGO.xdr_string DEFAULT VALUE( Rtblockt__init__tNonetvaluetoptionsRterrortpushRR(tselftnametrequestR R ((s*/pentest/voiper/sulley/sulley/legos/xdr.pyRs "   cCsftii|ƒ|idjo d|_n3tidt|iƒƒ|it|iƒ|_|iS(s� We overload and extend the render routine in order to properly pad and prefix the string. [dword length][array][pad] tts>L(RRtrendertrenderedtstructtpackRR(R((s*/pentest/voiper/sulley/sulley/legos/xdr.pyR!s  2(t__name__t __module__t__doc__RR(((s*/pentest/voiper/sulley/sulley/legos/xdr.pyRs (RtsulleyRRRRRR(((s*/pentest/voiper/sulley/sulley/legos/xdr.pyt<module>s  
1,685
Python
.py
15
108.866667
258
0.430539
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,938
._sip.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/._sip.py
Mac OS X  2°âATTR;šÉÿ✠œ com.apple.TextEncodingMACINTOSH;0This resource fork intentionally left blank ÿÿ
4,096
Python
.py
1
4,096
4,096
0.021484
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,939
ber.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/ber.py
######################################################################################################################## ### ASN.1 / BER TYPES (http://luca.ntop.org/Teaching/Appunti/asn1.html) ######################################################################################################################## import struct from sulley import blocks, primitives, sex ######################################################################################################################## class string (blocks.block): ''' [0x04][0x84][dword length][string] Where: 0x04 = string 0x84 = length is 4 bytes ''' def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options self.prefix = options.get("prefix", "\x04") if not self.value: raise sex.error("MISSING LEGO.ber_string DEFAULT VALUE") str_block = blocks.block(name + "_STR", request) str_block.push(primitives.string(self.value)) self.push(blocks.size(name + "_STR", request, endian=">", fuzzable=True)) self.push(str_block) def render (self): # let the parent do the initial render. blocks.block.render(self) self.rendered = self.prefix + "\x84" + self.rendered return self.rendered ######################################################################################################################## class integer (blocks.block): ''' [0x02][0x04][dword] Where: 0x02 = integer 0x04 = integer length is 4 bytes ''' def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.error("MISSING LEGO.ber_integer DEFAULT VALUE") self.push(primitives.dword(self.value, endian=">")) def render (self): # let the parent do the initial render. blocks.block.render(self) self.rendered = "\x02\x04" + self.rendered return self.rendered
2,229
Python
.py
49
38.265306
120
0.478422
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,940
misc.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/sulley/legos/misc.py
import struct from sulley import blocks, primitives, sex ######################################################################################################################## class ip_address_ascii (blocks.block): def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.error("MISSING LEGO.tag DEFAULT VALUE") ip_arr = value.split(".") ctr = 0 for ip_val in ip_arr: if ctr == 0: self.push(primitives.string(ip_val)) self.push(primitives.delim(".")) else: self.push(primitives.static(ip_val)) if ctr < 3: self.push(primitives.delim(".")) ctr += 1 ######################################################################################################################## class ipv6_address_ascii (blocks.block): def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.error("MISSING LEGO.tag DEFAULT VALUE") hex_arr = value.split(":") ctr = 0 for hex_val in hex_arr: if ctr == 0: self.push(primitives.string(hex_val)) self.push(primitives.delim(":")) else: self.push(primitives.static(hex_val)) if ctr < 7: self.push(primitives.static(":")) ctr += 1 ######################################################################################################################## class dns_hostname (blocks.block): def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.error("MISSING LEGO.tag DEFAULT VALUE") self.push(primitives.string(self.value)) def render (self): ''' We overload and extend the render routine in order to properly insert substring lengths. ''' # let the parent do the initial render. blocks.block.render(self) new_str = "" # replace dots (.) with the substring length. for part in self.rendered.split("."): new_str += str(len(part)) + part # be sure to null terminate too. self.rendered = new_str + "\x00" return self.rendered ######################################################################################################################## class tag (blocks.block): def __init__ (self, name, request, value, options={}): blocks.block.__init__(self, name, request, None, None, None, None) self.value = value self.options = options if not self.value: raise sex.error("MISSING LEGO.tag DEFAULT VALUE") # <example> # [delim][string][delim] self.push(primitives.delim("<")) self.push(primitives.string(self.value)) self.push(primitives.delim(">"))
3,377
Python
.py
75
34.786667
120
0.479532
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,941
uuid.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/uuid.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: uuid.py,v 1.4 2006/05/23 21:19:26 gera Exp $ # # Description: # Generate UUID compliant with http://www.webdav.org/specs/draft-leach-uuids-guids-01.txt. # A different, much simpler (not necessarily better) algorithm is used. # # Author: # Javier Kohen (jkohen) # import re from random import randrange from struct import pack, unpack def generate(): # UHm... crappy Python has an maximum integer of 2**31-1. top = (1L<<31)-1 return pack("IIII", randrange(top), randrange(top), randrange(top), randrange(top)) def bin_to_string(uuid): uuid1, uuid2, uuid3 = unpack('<LHH', uuid[:8]) uuid4, uuid5, uuid6 = unpack('>HHL', uuid[8:16]) return '%08X-%04X-%04X-%04X-%04X%08X' % (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) def string_to_bin(uuid): matches = re.match('([\dA-Fa-f]{8})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})([\dA-Fa-f]{8})', uuid) (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) = map(lambda x: long(x, 16), matches.groups()) uuid = pack('<LHH', uuid1, uuid2, uuid3) uuid += pack('>HHL', uuid4, uuid5, uuid6) return uuid def stringver_to_bin(s): (maj,min) = s.split('.') return pack('<H',int(maj)) + pack('<H',int(min)) def uuidtup_to_bin(tup): if len(tup) != 2: return return string_to_bin(tup[0]) + stringver_to_bin(tup[1]) #input: string #output: tuple (uuid,version) #if version is not found in the input string "1.0" is returned #example: # "00000000-0000-0000-0000-000000000000 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0') # "10000000-2000-3000-4000-500000000000 version 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0') # "10000000-2000-3000-4000-500000000000 v 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0') # "10000000-2000-3000-4000-500000000000" returns ('00000000-0000-0000-0000-000000000000','1.0') def string_to_uuidtup(s): g = re.search("([A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}).*?([0-9]{1,5}\.[0-9]{1,5})",s+" 1.0") if g: (u,v) = g.groups() return (u,v) return
2,352
Python
.py
52
42.25
135
0.651832
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,942
ImpactPacket.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/ImpactPacket.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: ImpactPacket.py,v 1.9 2006/05/23 22:25:34 gera Exp $ # # Description: # Network packet codecs basic building blocks. # Low-level packet codecs for various Internet protocols. # # Author: # Javier Burroni (javier) # Bruce Leidl (brl) # Javier Kohen (jkohen) import array import struct import socket import string import sys from binascii import hexlify """Classes to build network packets programmatically. Each protocol layer is represented by an object, and these objects are hierarchically structured to form a packet. This list is traversable in both directions: from parent to child and vice versa. All objects can be turned back into a raw buffer ready to be sent over the wire (see method get_packet). """ class ImpactPacketException: def __init__(self, value): self.value = value def __str__(self): return `self.value` class PacketBuffer: """Implement the basic operations utilized to operate on a packet's raw buffer. All the packet classes derive from this one. The byte, word, long and ip_address getters and setters accept negative indeces, having these the a similar effect as in a regular Python sequence slice. """ def __init__(self, length = None): "If 'length' is specified the buffer is created with an initial size" if length: self.__bytes = array.array('B', '\0' * length) else: self.__bytes = array.array('B') def set_bytes_from_string(self, data): "Sets the value of the packet buffer from the string 'data'" self.__bytes = array.array('B', data) def get_buffer_as_string(self): "Returns the packet buffer as a string object" return self.__bytes.tostring() def get_bytes(self): "Returns the packet buffer as an array" return self.__bytes def set_bytes(self, bytes): "Set the packet buffer from an array" # Make a copy to be safe self.__bytes = array.array('B', bytes.tolist()) def set_byte(self, index, value): "Set byte at 'index' to 'value'" index = self.__validate_index(index, 1) self.__bytes[index] = value def get_byte(self, index): "Return byte at 'index'" index = self.__validate_index(index, 1) return self.__bytes[index] def set_word(self, index, value, order = '!'): "Set 2-byte word at 'index' to 'value'. See struct module's documentation to understand the meaning of 'order'." index = self.__validate_index(index, 2) ary = array.array("B", struct.pack(order + 'H', value)) if -2 == index: self.__bytes[index:] = ary else: self.__bytes[index:index+2] = ary def get_word(self, index, order = '!'): "Return 2-byte word at 'index'. See struct module's documentation to understand the meaning of 'order'." index = self.__validate_index(index, 2) if -2 == index: bytes = self.__bytes[index:] else: bytes = self.__bytes[index:index+2] (value,) = struct.unpack(order + 'H', bytes.tostring()) return value def set_long(self, index, value, order = '!'): "Set 4-byte 'value' at 'index'. See struct module's documentation to understand the meaning of 'order'." index = self.__validate_index(index, 4) ary = array.array("B", struct.pack(order + 'L', value)) if -4 == index: self.__bytes[index:] = ary else: self.__bytes[index:index+4] = ary def get_long(self, index, order = '!'): "Return 4-byte value at 'index'. See struct module's documentation to understand the meaning of 'order'." index = self.__validate_index(index, 4) if -4 == index: bytes = self.__bytes[index:] else: bytes = self.__bytes[index:index+4] (value,) = struct.unpack(order + 'L', bytes.tostring()) return value def get_ip_address(self, index): "Return 4-byte value at 'index' as an IP string" index = self.__validate_index(index, 4) if -4 == index: bytes = self.__bytes[index:] else: bytes = self.__bytes[index:index+4] return socket.inet_ntoa(bytes.tostring()) def set_ip_address(self, index, ip_string): "Set 4-byte value at 'index' from 'ip_string'" index = self.__validate_index(index, 4) raw = socket.inet_aton(ip_string) (b1,b2,b3,b4) = struct.unpack("BBBB", raw) self.set_byte(index, b1) self.set_byte(index + 1, b2) self.set_byte(index + 2, b3) self.set_byte(index + 3, b4) def set_checksum_from_data(self, index, data): "Set 16-bit checksum at 'index' by calculating checksum of 'data'" self.set_word(index, self.compute_checksum(data)) def compute_checksum(self, anArray): "Return the one's complement of the one's complement sum of all the 16-bit words in 'anArray'" nleft = len(anArray) sum = 0 pos = 0 while nleft > 1: sum = anArray[pos] * 256 + (anArray[pos + 1] + sum) pos = pos + 2 nleft = nleft - 2 if nleft == 1: sum = sum + anArray[pos] * 256 return self.normalize_checksum(sum) def normalize_checksum(self, aValue): sum = aValue sum = (sum >> 16) + (sum & 0xFFFF) sum += (sum >> 16) sum = (~sum & 0xFFFF) return sum def __validate_index(self, index, size): """This method performs two tasks: to allocate enough space to fit the elements at positions index through index+size, and to adjust negative indeces to their absolute equivalent. """ orig_index = index curlen = len(self.__bytes) if index < 0: index = curlen + index diff = index + size - curlen if diff > 0: self.__bytes.fromstring('\0' * diff) if orig_index < 0: orig_index -= diff return orig_index class Header(PacketBuffer): "This is the base class from which all protocol definitions extend." packet_printable = filter(lambda c: c not in string.whitespace, string.printable) + ' ' ethertype = None protocol = None def __init__(self, length = None): PacketBuffer.__init__(self, length) self.__child = None self.__parent = None self.auto_checksum = 1 def contains(self, aHeader): "Set 'aHeader' as the child of this header" self.__child = aHeader aHeader.set_parent(self) def set_parent(self, my_parent): "Set the header 'my_parent' as the parent of this header" self.__parent = my_parent def child(self): "Return the child of this header" return self.__child def parent(self): "Return the parent of this header" return self.__parent def get_data_as_string(self): "Returns all data from children of this header as string" if self.__child: return self.__child.get_packet() else: return None def get_packet(self): """Returns the raw representation of this packet and its children as a string. The output from this method is a packet ready to be transmited over the wire. """ self.calculate_checksum() data = self.get_data_as_string() if data: return self.get_buffer_as_string() + data else: return self.get_buffer_as_string() def get_size(self): "Return the size of this header and all of it's children" tmp_value = self.get_header_size() if self.child(): tmp_value = tmp_value + self.child().get_size() return tmp_value def calculate_checksum(self): "Calculate and set the checksum for this header" pass def get_pseudo_header(self): "Pseudo headers can be used to limit over what content will the checksums be calculated." # default implementation returns empty array return array.array('B') def load_header(self, aBuffer): "Properly set the state of this instance to reflect that of the raw packet passed as argument." self.set_bytes_from_string(aBuffer) hdr_len = self.get_header_size() if(len(aBuffer) < hdr_len): #we must do something like this diff = hdr_len - len(aBuffer) for i in range(0, diff): aBuffer += '\x00' self.set_bytes_from_string(aBuffer[:hdr_len]) def get_header_size(self): "Return the size of this header, that is, not counting neither the size of the children nor of the parents." raise RuntimeError("Method %s.get_header_size must be overriden." % self.__class__) def list_as_hex(self, aList): if len(aList): ltmp = [] line = [] count = 0 for byte in aList: if not (count % 2): if (count % 16): ltmp.append(' ') else: ltmp.append(' '*4) ltmp.append(string.join(line, '')) ltmp.append('\n') line = [] if chr(byte) in Header.packet_printable: line.append(chr(byte)) else: line.append('.') ltmp.append('%.2x' % byte) count += 1 if (count%16): left = 16 - (count%16) ltmp.append(' ' * (4+(left / 2) + (left*2))) ltmp.append(string.join(line, '')) ltmp.append('\n') return ltmp else: return [] def __str__(self): ltmp = self.list_as_hex(self.get_bytes().tolist()) if self.__child: ltmp.append(['\n', self.__child.__str__()]) if len(ltmp)>0: return string.join(ltmp, '') else: return '' class Data(Header): """This packet type can hold raw data. It's normally employed to hold a packet's innermost layer's contents in those cases for which the protocol details are unknown, and there's a copy of a valid packet available. For instance, if all that's known about a certain protocol is that a UDP packet with its contents set to "HELLO" initiate a new session, creating such packet is as simple as in the following code fragment: packet = UDP() packet.contains('HELLO') """ def __init__(self, aBuffer = None): Header.__init__(self) if aBuffer: self.set_data(aBuffer) def set_data(self, data): self.set_bytes_from_string(data) def get_size(self): return len(self.get_bytes()) class Ethernet(Header): def __init__(self, aBuffer = None): Header.__init__(self, 14) if(aBuffer): self.load_header(aBuffer) def set_ether_type(self, aValue): "Set ethernet data type field to 'aValue'" self.set_word(12, aValue) def get_ether_type(self): "Return ethernet data type field" return self.get_word(12) def get_header_size(self): "Return size of Ethernet header" return 14 def get_packet(self): if self.child(): self.set_ether_type(self.child().ethertype) return Header.get_packet(self) def get_ether_dhost(self): "Return 48 bit destination ethernet address as a 6 byte array" return self.get_bytes()[0:6] def set_ether_dhost(self, aValue): "Set destination ethernet address from 6 byte array 'aValue'" for i in range(0, 6): self.set_byte(i, aValue[i]) def get_ether_shost(self): "Return 48 bit source ethernet address as a 6 byte array" return self.get_bytes()[6:12] def set_ether_shost(self, aValue): "Set source ethernet address from 6 byte array 'aValue'" for i in range(0, 6): self.set_byte(i + 6, aValue[i]) def as_eth_addr(self, anArray): tmp_list = anArray.tolist() if not tmp_list: return '' tmp_str = '%x' % tmp_list[0] for i in range(1, len(tmp_list)): tmp_str += ':%x' % tmp_list[i] return tmp_str def __str__(self): tmp_str = 'Ether: ' + self.as_eth_addr(self.get_ether_shost()) + ' -> ' tmp_str += self.as_eth_addr(self.get_ether_dhost()) if self.child(): tmp_str += '\n' + self.child().__str__() return tmp_str # Linux "cooked" capture encapsulation. # Used, for instance, for packets returned by the "any" interface. class LinuxSLL(Header): type_descriptions = [ "sent to us by somebody else", "broadcast by somebody else", "multicast by somebody else", "sent to somebody else to somebody else", "sent by us", ] def __init__(self, aBuffer = None): Header.__init__(self, 16) if (aBuffer): self.load_header(aBuffer) def set_type(self, type): "Sets the packet type field to type" self.set_word(0, type) def get_type(self): "Returns the packet type field" return self.get_word(0) def set_arphdr(self, value): "Sets the ARPHDR value for the link layer device type" self.set_word(2, type) def get_arphdr(self): "Returns the ARPHDR value for the link layer device type" return self.get_word(2) def set_addr_len(self, len): "Sets the length of the sender's address field to len" self.set_word(4, len) def get_addr_len(self): "Returns the length of the sender's address field" return self.get_word(4) def set_addr(self, addr): "Sets the sender's address field to addr. Addr must be at most 8-byte long." if (len(addr) < 8): addr += '\0' * (8 - len(addr)) self.get_bytes()[6:14] = addr def get_addr(self): "Returns the sender's address field" return self.get_bytes()[6:14].tostring() def set_ether_type(self, aValue): "Set ethernet data type field to 'aValue'" self.set_word(14, aValue) def get_ether_type(self): "Return ethernet data type field" return self.get_word(14) def get_header_size(self): "Return size of packet header" return 16 def get_packet(self): if self.child(): self.set_ether_type(self.child().ethertype) return Header.get_packet(self) def get_type_desc(self): type = self.get_type() if type < len(LinuxSLL.type_descriptions): return LinuxSLL.type_descriptions[type] else: return "Unknown" def __str__(self): ss = [] alen = self.get_addr_len() addr = hexlify(self.get_addr()[0:alen]) ss.append("Linux SLL: addr=%s type=`%s'" % (addr, self.get_type_desc())) if self.child(): ss.append(self.child().__str__()) return '\n'.join(ss) class IP(Header): ethertype = 0x800 def __init__(self, aBuffer = None): Header.__init__(self, 20) self.set_ip_v(4) self.set_ip_hl(5) self.set_ip_ttl(255) self.__option_list = [] if(aBuffer): self.load_header(aBuffer) if sys.platform.count('bsd'): self.is_BSD = True else: self.is_BSD = False def get_packet(self): # set protocol if self.get_ip_p() == 0 and self.child(): self.set_ip_p(self.child().protocol) # set total length if self.get_ip_len() == 0: self.set_ip_len(self.get_size()) child_data = self.get_data_as_string(); my_bytes = self.get_bytes() for op in self.__option_list: my_bytes.extend(op.get_bytes()) # Pad to a multiple of 4 bytes num_pad = (4 - (len(my_bytes) % 4)) % 4 if num_pad: my_bytes.fromstring("\0"* num_pad) # only change ip_hl value if options are present if len(self.__option_list): self.set_ip_hl(len(my_bytes) / 4) # set the checksum if the user hasn't modified it if self.auto_checksum: self.set_ip_sum(self.compute_checksum(my_bytes)) if child_data == None: return my_bytes.tostring() else: return my_bytes.tostring() + child_data # def calculate_checksum(self, buffer = None): # tmp_value = self.get_ip_sum() # if self.auto_checksum and (not tmp_value): # if buffer: # tmp_bytes = buffer # else: # tmp_bytes = self.bytes[0:self.get_header_size()] # # self.set_ip_sum(self.compute_checksum(tmp_bytes)) def get_pseudo_header(self): pseudo_buf = array.array("B") pseudo_buf.extend(self.get_bytes()[12:20]) pseudo_buf.fromlist([0]) pseudo_buf.extend(self.get_bytes()[9:10]) tmp_size = self.child().get_size() size_str = struct.pack("!H", tmp_size) pseudo_buf.fromstring(size_str) return pseudo_buf def add_option(self, option): self.__option_list.append(option) sum = 0 for op in self.__option_list: sum += op.get_len() if sum > 40: raise ImpactPacketException, "Options overflowed in IP packet with length: %d" % sum def get_ip_v(self): n = self.get_byte(0) return (n >> 4) def set_ip_v(self, value): n = self.get_byte(0) version = value & 0xF n = n & 0xF n = n | (version << 4) self.set_byte(0, n) def get_ip_hl(self): n = self.get_byte(0) return (n & 0xF) def set_ip_hl(self, value): n = self.get_byte(0) len = value & 0xF n = n & 0xF0 n = (n | len) self.set_byte(0, n) def get_ip_tos(self): return self.get_byte(1) def set_ip_tos(self,value): self.set_byte(1, value) def get_ip_len(self): if self.is_BSD: return self.get_word(2, order = '=') else: return self.get_word(2) def set_ip_len(self, value): if self.is_BSD: self.set_word(2, value, order = '=') else: self.set_word(2, value) def get_ip_id(self): return self.get_word(4) def set_ip_id(self, value): return self.set_word(4, value) def get_ip_off(self): if self.is_BSD: return self.get_word(6, order = '=') else: return self.get_word(6) def set_ip_off(self, aValue): if self.is_BSD: self.set_word(6, aValue, order = '=') else: self.set_word(6, aValue) def get_ip_offmask(self): return self.get_ip_off() & 0x1FFF def set_ip_offmask(self, aValue): tmp_value = self.get_ip_off() & 0xD000 tmp_value |= aValue self.set_ip_off(tmp_value) def get_ip_rf(self): return self.get_ip_off() & 0x8000 def set_ip_rf(self, aValue): tmp_value = self.get_ip_off() if aValue: tmp_value |= 0x8000 else: my_not = 0xFFFF ^ 0x8000 tmp_value &= my_not self.set_ip_off(tmp_value) def get_ip_df(self): return self.get_ip_off() & 0x4000 def set_ip_df(self, aValue): tmp_value = self.get_ip_off() if aValue: tmp_value |= 0x4000 else: my_not = 0xFFFF ^ 0x4000 tmp_value &= my_not self.set_ip_off(tmp_value) def get_ip_mf(self): return self.get_ip_off() & 0x2000 def set_ip_mf(self, aValue): tmp_value = self.get_ip_off() if aValue: tmp_value |= 0x2000 else: my_not = 0xFFFF ^ 0x2000 tmp_value &= my_not self.set_ip_off(tmp_value) def fragment_by_list(self, aList): if self.child(): proto = self.child().protocol else: proto = 0 child_data = self.get_data_as_string() if not child_data: return [self] ip_header_bytes = self.get_bytes() current_offset = 0 fragment_list = [] for frag_size in aList: ip = IP() ip.set_bytes(ip_header_bytes) # copy of original header ip.set_ip_p(proto) if frag_size % 8: # round this fragment size up to next multiple of 8 frag_size += 8 - (frag_size % 8) ip.set_ip_offmask(current_offset / 8) current_offset += frag_size data = Data(child_data[:frag_size]) child_data = child_data[frag_size:] ip.set_ip_len(20 + data.get_size()) ip.contains(data) if child_data: ip.set_ip_mf(1) fragment_list.append(ip) else: # no more data bytes left to add to fragments ip.set_ip_mf(0) fragment_list.append(ip) return fragment_list if child_data: # any remaining data? # create a fragment containing all of the remaining child_data ip = IP() ip.set_bytes(ip_header_bytes) ip.set_ip_offmask(current_offset) ip.set_ip_len(20 + len(child_data)) data = Data(child_data) ip.contains(data) fragment_list.append(ip) return fragment_list def fragment_by_size(self, aSize): data_len = len(self.get_data_as_string()) num_frags = data_len / aSize if data_len % aSize: num_frags += 1 size_list = [] for i in range(0, num_frags): size_list.append(aSize) return self.fragment_by_list(size_list) def get_ip_ttl(self): return self.get_byte(8) def set_ip_ttl(self, value): self.set_byte(8, value) def get_ip_p(self): return self.get_byte(9) def set_ip_p(self, value): self.set_byte(9, value) def get_ip_sum(self): return self.get_word(10) def set_ip_sum(self, value): self.auto_checksum = 0 self.set_word(10, value) def get_ip_src(self): return self.get_ip_address(12) def set_ip_src(self, value): self.set_ip_address(12, value) def get_ip_dst(self): return self.get_ip_address(16) def set_ip_dst(self, value): self.set_ip_address(16, value) def get_header_size(self): op_len = 0 for op in self.__option_list: op_len += op.get_len() num_pad = (4 - (op_len % 4)) % 4 return 20 + op_len + num_pad def load_header(self, aBuffer): self.set_bytes_from_string(aBuffer[:20]) opt_left = (self.get_ip_hl() - 5) * 4 opt_bytes = array.array('B', aBuffer[20:(20 + opt_left)]) if len(opt_bytes) != opt_left: raise ImpactPacketException, "Cannot load options from truncated packet" while opt_left: op_type = opt_bytes[0] if op_type == IPOption.IPOPT_EOL or op_type == IPOption.IPOPT_NOP: new_option = IPOption(op_type) op_len = 1 else: op_len = opt_bytes[1] if op_len > len(opt_bytes): raise ImpactPacketException, "IP Option length is too high" new_option = IPOption(op_type, op_len) new_option.set_bytes(opt_bytes[:op_len]) opt_bytes = opt_bytes[op_len:] opt_left -= op_len self.add_option(new_option) if op_type == IPOption.IPOPT_EOL: break def __str__(self): tmp_str = 'IP ' + self.get_ip_src() + ' -> ' + self.get_ip_dst() for op in self.__option_list: tmp_str += '\n' + op.__str__() if self.child(): tmp_str += '\n' + self.child().__str__() return tmp_str class IPOption(PacketBuffer): IPOPT_EOL = 0 IPOPT_NOP = 1 IPOPT_RR = 7 IPOPT_TS = 68 IPOPT_LSRR = 131 IPOPT_SSRR = 137 def __init__(self, opcode = 0, size = None): if size and (size < 3 or size > 39): raise ImpactPacketException, "IP Options must have a size between 3 and 39 bytes" if(opcode == IPOption.IPOPT_EOL): PacketBuffer.__init__(self, 1) self.set_code(IPOption.IPOPT_EOL) elif(opcode == IPOption.IPOPT_NOP): PacketBuffer.__init__(self, 1) self.set_code(IPOption.IPOPT_NOP) elif(opcode == IPOption.IPOPT_RR): if not size: size = 39 PacketBuffer.__init__(self, size) self.set_code(IPOption.IPOPT_RR) self.set_len(size) self.set_ptr(4) elif(opcode == IPOption.IPOPT_LSRR): if not size: size = 39 PacketBuffer.__init__(self, size) self.set_code(IPOption.IPOPT_LSRR) self.set_len(size) self.set_ptr(4) elif(opcode == IPOption.IPOPT_SSRR): if not size: size = 39 PacketBuffer.__init__(self, size) self.set_code(IPOption.IPOPT_SSRR) self.set_len(size) self.set_ptr(4) elif(opcode == IPOption.IPOPT_TS): if not size: size = 40 PacketBuffer.__init__(self, size) self.set_code(IPOption.IPOPT_TS) self.set_len(size) self.set_ptr(5) self.set_flags(0) else: if not size: raise ImpactPacketError, "Size required for this type" PacketBuffer.__init__(self,size) self.set_code(opcode) self.set_len(size) def append_ip(self, ip): op = self.get_code() if not (op == IPOption.IPOPT_RR or op == IPOption.IPOPT_LSRR or op == IPOption.IPOPT_SSRR or op == IPOption.IPOPT_TS): raise ImpactPacketException, "append_ip() not support for option type %d" % self.opt_type p = self.get_ptr() if not p: raise ImpactPacketException, "append_ip() failed, option ptr uninitialized" if (p + 4) > self.get_len(): raise ImpactPacketException, "append_ip() would overflow option" self.set_ip_address(p - 1, ip) p += 4 self.set_ptr(p) def set_code(self, value): self.set_byte(0, value) def get_code(self): return self.get_byte(0) def set_flags(self, flags): if not (self.get_code() == IPOption.IPOPT_TS): raise ImpactPacketException, "Operation only supported on Timestamp option" self.set_byte(3, flags) def get_flags(self, flags): if not (self.get_code() == IPOption.IPOPT_TS): raise ImpactPacketException, "Operation only supported on Timestamp option" return self.get_byte(3) def set_len(self, len): self.set_byte(1, len) def set_ptr(self, ptr): self.set_byte(2, ptr) def get_ptr(self): return self.get_byte(2) def get_len(self): return len(self.get_bytes()) def __str__(self): map = {IPOption.IPOPT_EOL : "End of List ", IPOption.IPOPT_NOP : "No Operation ", IPOption.IPOPT_RR : "Record Route ", IPOption.IPOPT_TS : "Timestamp ", IPOption.IPOPT_LSRR : "Loose Source Route ", IPOption.IPOPT_SSRR : "Strict Source Route "} tmp_str = "\tIP Option: " op = self.get_code() if map.has_key(op): tmp_str += map[op] else: tmp_str += "Code: %d " % op if op == IPOption.IPOPT_RR or op == IPOption.IPOPT_LSRR or op ==IPOption.IPOPT_SSRR: tmp_str += self.print_addresses() return tmp_str def print_addresses(self): p = 3 tmp_str = "[" if self.get_len() >= 7: # at least one complete IP address while 1: if p + 1 == self.get_ptr(): tmp_str += "#" tmp_str += self.get_ip_address(p) p += 4 if p >= self.get_len(): break else: tmp_str += ", " tmp_str += "] " if self.get_ptr() % 4: # ptr field should be a multiple of 4 tmp_str += "nonsense ptr field: %d " % self.get_ptr() return tmp_str class UDP(Header): protocol = 17 def __init__(self, aBuffer = None): Header.__init__(self, 8) if(aBuffer): self.load_header(aBuffer) def get_uh_sport(self): return self.get_word(0) def set_uh_sport(self, value): self.set_word(0, value) def get_uh_dport(self): return self.get_word(2) def set_uh_dport(self, value): self.set_word(2, value) def get_uh_ulen(self): return self.get_word(4) def set_uh_ulen(self, value): self.set_word(4, value) def get_uh_sum(self): return self.get_word(6) def set_uh_sum(self, value): self.set_word(6, value) self.auto_checksum = 0 def calculate_checksum(self): if self.auto_checksum and (not self.get_uh_sum()): # if there isn't a parent to grab a pseudo-header from we'll assume the user knows what they're doing # and won't meddle with the checksum or throw an exception if not self.parent: return buffer = self.parent().get_pseudo_header() buffer += self.get_bytes() data = self.get_data_as_string() if(data): buffer.fromstring(data) self.set_uh_sum(self.compute_checksum(buffer)) def get_header_size(self): return 8 def __str__(self): tmp_str = 'UDP %d -> %d' % (self.get_uh_sport(), self.get_uh_dport()) if self.child(): tmp_str += '\n' + self.child().__str__() return tmp_str def get_packet(self): # set total length if(self.get_uh_ulen() == 0): self.set_uh_ulen(self.get_size()) return Header.get_packet(self) class TCP(Header): protocol = 6 def __init__(self, aBuffer = None): Header.__init__(self, 20) self.set_th_off(5) self.__option_list = [] if aBuffer: self.load_header(aBuffer) def add_option(self, option): self.__option_list.append(option) sum = 0 for op in self.__option_list: sum += op.get_size() if sum > 40: raise ImpactPacketException, "Cannot add TCP option, would overflow option space" def get_options(self): return self.__option_list def swapSourceAndDestination(self): oldSource = self.get_th_sport() self.set_th_sport(self.get_th_dport()) self.set_th_dport(oldSource) # # Header field accessors # def set_th_sport(self, aValue): self.set_word(0, aValue) def get_th_sport(self): return self.get_word(0) def get_th_dport(self): return self.get_word(2) def set_th_dport(self, aValue): self.set_word(2, aValue) def get_th_seq(self): return self.get_long(4) def set_th_seq(self, aValue): self.set_long(4, aValue) def get_th_ack(self): return self.get_long(8) def set_th_ack(self, aValue): self.set_long(8, aValue) def get_th_flags(self): return self.get_word(12) def set_th_flags(self, aValue): self.set_word(12, aValue) def get_th_win(self): return self.get_word(14) def set_th_win(self, aValue): self.set_word(14, aValue) def set_th_sum(self, aValue): self.set_word(16, aValue) self.auto_checksum = 0 def get_th_sum(self): return self.get_long(16) def get_th_urp(self): return self.get_word(18) def set_th_urp(self, aValue): return self.set_word(18, aValue) # Flag accessors def get_th_off(self): tmp_value = self.get_th_flags() >> 12 return tmp_value def set_th_off(self, aValue): self.reset_flags(0xF000) self.set_flags(aValue << 12) def get_CWR(self): return self.get_flag(128) def set_CWR(self): return self.set_flags(128) def reset_CWR(self): return self.reset_flags(128) def get_ECE(self): return self.get_flag(64) def set_ECE(self): return self.set_flags(64) def reset_ECE(self): return self.reset_flags(64) def get_URG(self): return self.get_flag(32) def set_URG(self): return self.set_flags(32) def reset_URG(self): return self.reset_flags(32) def get_ACK(self): return self.get_flag(16) def set_ACK(self): return self.set_flags(16) def reset_ACK(self): return self.reset_flags(16) def get_PSH(self): return self.get_flag(8) def set_PSH(self): return self.set_flags(8) def reset_PSH(self): return self.reset_flags(8) def get_RST(self): return self.get_flag(4) def set_RST(self): return self.set_flags(4) def reset_RST(self): return self.reset_flags(4) def get_SYN(self): return self.get_flag(2) def set_SYN(self): return self.set_flags(2) def reset_SYN(self): return self.reset_flags(2) def get_FIN(self): return self.get_flag(1) def set_FIN(self): return self.set_flags(1) def reset_FIN(self): return self.reset_flags(1) # Overriden Methods def get_header_size(self): return 20 + len(self.get_padded_options()) def calculate_checksum(self): if not self.auto_checksum or not self.parent(): return self.set_th_sum(0) buffer = self.parent().get_pseudo_header() buffer += self.get_bytes() buffer += self.get_padded_options() data = self.get_data_as_string() if(data): buffer.fromstring(data) res = self.compute_checksum(buffer) self.set_th_sum(self.compute_checksum(buffer)) def get_packet(self): "Returns entire packet including child data as a string. This is the function used to extract the final packet" # only change th_off value if options are present if len(self.__option_list): self.set_th_off(self.get_header_size() / 4) self.calculate_checksum() bytes = self.get_bytes() + self.get_padded_options() data = self.get_data_as_string() if data: return bytes.tostring() + data else: return bytes.tostring() def load_header(self, aBuffer): self.set_bytes_from_string(aBuffer[:20]) opt_left = (self.get_th_off() - 5) * 4 opt_bytes = array.array('B', aBuffer[20:(20 + opt_left)]) if len(opt_bytes) != opt_left: raise ImpactPacketException, "Cannot load options from truncated packet" while opt_left: op_kind = opt_bytes[0] if op_kind == TCPOption.TCPOPT_EOL or op_kind == TCPOption.TCPOPT_NOP: new_option = TCPOption(op_kind) op_len = 1 else: op_len = opt_bytes[1] if op_len > len(opt_bytes): raise ImpactPacketException, "TCP Option length is too high" new_option = TCPOption(op_kind) new_option.set_bytes(opt_bytes[:op_len]) opt_bytes = opt_bytes[op_len:] opt_left -= op_len self.add_option(new_option) if op_kind == TCPOption.TCPOPT_EOL: break # # Private # def get_flag(self, bit): if self.get_th_flags() & bit: return 1 else: return 0 def reset_flags(self, aValue): tmp_value = self.get_th_flags() & (~aValue) return self.set_word(12, tmp_value) def set_flags(self, aValue): tmp_value = self.get_th_flags() | aValue return self.set_word(12, tmp_value) def get_padded_options(self): "Return an array containing all options padded to a 4 byte boundry" op_buf = array.array('B') for op in self.__option_list: op_buf += op.get_bytes() num_pad = (4 - (len(op_buf) % 4)) % 4 if num_pad: op_buf.fromstring("\0" * num_pad) return op_buf def __str__(self): tmp_str = 'TCP ' if self.get_ACK(): tmp_str += 'ack ' if self.get_FIN(): tmp_str += 'fin ' if self.get_PSH(): tmp_str += 'push ' if self.get_RST(): tmp_str += 'rst ' if self.get_SYN(): tmp_str += 'syn ' if self.get_URG(): tmp_str += 'urg ' tmp_str += '%d -> %d' % (self.get_th_sport(), self.get_th_dport()) for op in self.__option_list: tmp_str += '\n' + op.__str__() if self.child(): tmp_str += '\n' + self.child().__str__() return tmp_str class TCPOption(PacketBuffer): TCPOPT_EOL = 0 TCPOPT_NOP = 1 TCPOPT_MAXSEG = 2 TCPOPT_WINDOW = 3 TCPOPT_SACK_PERMITTED = 4 TCPOPT_SACK = 5 TCPOPT_TIMESTAMP = 8 TCPOPT_SIGNATURE = 19 def __init__(self, kind, data = None): if kind == TCPOption.TCPOPT_EOL: PacketBuffer.__init__(self, 1) self.set_kind(TCPOption.TCPOPT_EOL) elif kind == TCPOption.TCPOPT_NOP: PacketBuffer.__init__(self, 1) self.set_kind(TCPOption.TCPOPT_NOP) elif kind == TCPOption.TCPOPT_MAXSEG: PacketBuffer.__init__(self, 4) self.set_kind(TCPOption.TCPOPT_MAXSEG) self.set_len(4) if data: self.set_mss(data) else: self.set_mss(512) elif kind == TCPOption.TCPOPT_WINDOW: PacketBuffer.__init__(self, 3) self.set_kind(TCPOption.TCPOPT_WINDOW) self.set_len(3) if data: self.set_shift_cnt(data) else: self.set_shift_cnt(0) elif kind == TCPOption.TCPOPT_TIMESTAMP: PacketBuffer.__init__(self, 10) self.set_kind(TCPOption.TCPOPT_TIMESTAMP) self.set_len(10) if data: self.set_ts(data) else: self.set_ts(0) elif kind == TCPOption.TCPOPT_SACK_PERMITTED: PacketBuffer.__init__(self, 2) self.set_kind(TCPOption.TCPOPT_SACK_PERMITTED) self.set_len(2) def set_kind(self, kind): self.set_byte(0, kind) def get_kind(self): return self.get_byte(0) def set_len(self, len): if self.get_size() < 2: raise ImpactPacketException, "Cannot set length field on option of less than two bytes" self.set_byte(1, len) def get_len(self): if self.get_size() < 2: raise ImpactPacketException, "Cannot retrive length field from option of less that two bytes" return self.get_byte(1) def get_size(self): return len(self.get_bytes()) def set_mss(self, len): if self.get_kind() != TCPOption.TCPOPT_MAXSEG: raise ImpactPacketException, "Can only set MSS on TCPOPT_MAXSEG option" self.set_word(2, len) def get_mss(self): if self.get_kind() != TCPOption.TCPOPT_MAXSEG: raise ImpactPacketException, "Can only retrieve MSS from TCPOPT_MAXSEG option" return self.get_word(2) def set_shift_cnt(self, cnt): if self.get_kind() != TCPOption.TCPOPT_WINDOW: raise ImpactPacketException, "Can only set Shift Count on TCPOPT_WINDOW option" self.set_byte(2, cnt) def get_shift_cnt(self): if self.get_kind() != TCPOption.TCPOPT_WINDOW: raise ImpactPacketException, "Can only retrieve Shift Count from TCPOPT_WINDOW option" return self.get_byte(2) def get_ts(self): if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP: raise ImpactPacketException, "Can only retrieve timestamp from TCPOPT_TIMESTAMP option" return self.get_long(2) def set_ts(self, ts): if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP: raise ImpactPacketException, "Can only set timestamp on TCPOPT_TIMESTAMP option" self.set_long(2, ts) def get_ts_echo(self): if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP: raise ImpactPacketException, "Can only retrieve timestamp from TCPOPT_TIMESTAMP option" self.get_long(6) def set_ts_echo(self, ts): if self.get_kind() != TCPOption.TCPOPT_TIMESTAMP: raise ImpactPacketException, "Can only set timestamp on TCPOPT_TIMESTAMP option" def __str__(self): map = { TCPOption.TCPOPT_EOL : "End of List ", TCPOption.TCPOPT_NOP : "No Operation ", TCPOption.TCPOPT_MAXSEG : "Maximum Segment Size ", TCPOption.TCPOPT_WINDOW : "Window Scale ", TCPOption.TCPOPT_TIMESTAMP : "Timestamp " } tmp_str = "\tTCP Option: " op = self.get_kind() if map.has_key(op): tmp_str += map[op] else: tmp_str += " kind: %d " % op if op == TCPOption.TCPOPT_MAXSEG: tmp_str += " MSS : %d " % self.get_mss() elif op == TCPOption.TCPOPT_WINDOW: tmp_str += " Shift Count: %d " % self.get_shift_cnt() elif op == TCPOption.TCPOPT_TIMESTAMP: pass # TODO return tmp_str class ICMP(Header): protocol = 1 ICMP_ECHOREPLY = 0 ICMP_UNREACH = 3 ICMP_UNREACH_NET = 0 ICMP_UNREACH_HOST = 1 ICMP_UNREACH_PROTOCOL = 2 ICMP_UNREACH_PORT = 3 ICMP_UNREACH_NEEDFRAG = 4 ICMP_UNREACH_SRCFAIL = 5 ICMP_UNREACH_NET_UNKNOWN = 6 ICMP_UNREACH_HOST_UNKNOWN = 7 ICMP_UNREACH_ISOLATED = 8 ICMP_UNREACH_NET_PROHIB = 9 ICMP_UNREACH_HOST_PROHIB = 10 ICMP_UNREACH_TOSNET = 11 ICMP_UNREACH_TOSHOST = 12 ICMP_UNREACH_FILTERPROHIB = 13 ICMP_UNREACH_HOST_PRECEDENCE = 14 ICMP_UNREACH_PRECEDENCE_CUTOFF = 15 ICMP_SOURCEQUENCH = 4 ICMP_REDIRECT = 5 ICMP_REDIRECT_NET = 0 ICMP_REDIRECT_HOST = 1 ICMP_REDIRECT_TOSNET = 2 ICMP_REDIRECT_TOSHOST = 3 ICMP_ALTHOSTADDR = 6 ICMP_ECHO = 8 ICMP_ROUTERADVERT = 9 ICMP_ROUTERSOLICIT = 10 ICMP_TIMXCEED = 11 ICMP_TIMXCEED_INTRANS = 0 ICMP_TIMXCEED_REASS = 1 ICMP_PARAMPROB = 12 ICMP_PARAMPROB_ERRATPTR = 0 ICMP_PARAMPROB_OPTABSENT = 1 ICMP_PARAMPROB_LENGTH = 2 ICMP_TSTAMP = 13 ICMP_TSTAMPREPLY = 14 ICMP_IREQ = 15 ICMP_IREQREPLY = 16 ICMP_MASKREQ = 17 ICMP_MASKREPLY = 18 def __init__(self, aBuffer = None): Header.__init__(self, 8) if aBuffer: self.load_header(aBuffer) def get_header_size(self): anamolies = { ICMP.ICMP_TSTAMP : 20, ICMP.ICMP_TSTAMPREPLY : 20, ICMP.ICMP_MASKREQ : 12, ICMP.ICMP_MASKREPLY : 12 } if anamolies.has_key(self.get_icmp_type()): return anamolies[self.get_icmp_type()] else: return 8 def get_icmp_type(self): return self.get_byte(0) def set_icmp_type(self, aValue): self.set_byte(0, aValue) def get_icmp_code(self): return self.get_byte(1) def set_icmp_code(self, aValue): self.set_byte(1, aValue) def get_icmp_cksum(self): return self.get_word(2) def set_icmp_cksum(self, aValue): self.set_word(2, aValue) self.auto_checksum = 0 def get_icmp_gwaddr(self): return self.get_ip_address(4) def set_icmp_gwaddr(self, ip): self.set_ip_adress(4, ip) def get_icmp_id(self): return self.get_word(4) def set_icmp_id(self, aValue): self.set_word(4, aValue) def get_icmp_seq(self): return self.get_word(6) def set_icmp_seq(self, aValue): self.set_word(6, aValue) def get_icmp_void(self): return self.get_long(4) def set_icmp_void(self, aValue): self.set_long(4, aValue) def get_icmp_nextmtu(self): return self.get_word(6) def set_icmp_nextmtu(self, aValue): self.set_word(6, aValue) def get_icmp_num_addrs(self): return self.get_byte(4) def set_icmp_num_addrs(self, aValue): self.set_byte(4, aValue) def get_icmp_wpa(self): return self.get_byte(5) def set_icmp_wpa(self, aValue): self.set_byte(5, aValue) def get_icmp_lifetime(self): return self.get_word(6) def set_icmp_lifetime(self, aValue): self.set_word(6, aValue) def get_icmp_otime(self): return self.get_long(8) def set_icmp_otime(self, aValue): self.set_long(8, aValue) def get_icmp_rtime(self): return self.get_long(12) def set_icmp_rtime(self, aValue): self.set_long(12, aValue) def get_icmp_ttime(self): return self.get_long(16) def set_icmp_ttime(self, aValue): self.set_long(16, aValue) def get_icmp_mask(self): return self.get_ip_address(8) def set_icmp_mask(self, mask): self.set_ip_address(8, mask) def calculate_checksum(self): if self.auto_checksum and (not self.get_icmp_cksum()): buffer = self.get_buffer_as_string() data = self.get_data_as_string() if data: buffer += data tmp_array = array.array('B', buffer) self.set_icmp_cksum(self.compute_checksum(tmp_array)) def get_type_name(self, aType): tmp_type = {0:'ECHOREPLY', 3:'UNREACH', 4:'SOURCEQUENCH',5:'REDIRECT', 6:'ALTHOSTADDR', 8:'ECHO', 9:'ROUTERADVERT', 10:'ROUTERSOLICIT', 11:'TIMXCEED', 12:'PARAMPROB', 13:'TSTAMP', 14:'TSTAMPREPLY', 15:'IREQ', 16:'IREQREPLY', 17:'MASKREQ', 18:'MASKREPLY', 30:'TRACEROUTE', 31:'DATACONVERR', 32:'MOBILE REDIRECT', 33:'IPV6 WHEREAREYOU', 34:'IPV6 IAMHERE', 35:'MOBILE REGREQUEST', 36:'MOBILE REGREPLY', 39:'SKIP', 40:'PHOTURIS'} answer = tmp_type.get(aType, 'UNKNOWN') return answer def get_code_name(self, aType, aCode): tmp_code = {3:['UNREACH NET', 'UNREACH HOST', 'UNREACH PROTOCOL', 'UNREACH PORT', 'UNREACH NEEDFRAG', 'UNREACH SRCFAIL', 'UNREACH NET UNKNOWN', 'UNREACH HOST UNKNOWN', 'UNREACH ISOLATED', 'UNREACH NET PROHIB', 'UNREACH HOST PROHIB', 'UNREACH TOSNET', 'UNREACH TOSHOST', 'UNREACH FILTER PROHIB', 'UNREACH HOST PRECEDENCE', 'UNREACH PRECEDENCE CUTOFF', 'UNKNOWN ICMP UNREACH']} tmp_code[5] = ['REDIRECT NET', 'REDIRECT HOST', 'REDIRECT TOSNET', 'REDIRECT TOSHOST'] tmp_code[9] = ['ROUTERADVERT NORMAL', None, None, None, None, None, None, None, None, None, None, None, None, None, None, None,'ROUTERADVERT NOROUTE COMMON'] tmp_code[11] = ['TIMXCEED INTRANS ', 'TIMXCEED REASS'] tmp_code[12] = ['PARAMPROB ERRATPTR ', 'PARAMPROB OPTABSENT', 'PARAMPROB LENGTH'] tmp_code[40] = [None, 'PHOTURIS UNKNOWN INDEX', 'PHOTURIS AUTH FAILED', 'PHOTURIS DECRYPT FAILED'] if tmp_code.has_key(aType): tmp_list = tmp_code[aType] if ((aCode + 1) > len(tmp_list)) or (not tmp_list[aCode]): return 'UNKNOWN' else: return tmp_list[aCode] else: return 'UNKNOWN' def __str__(self): tmp_type = self.get_icmp_type() tmp_code = self.get_icmp_code() tmp_str = 'ICMP type: ' + self.get_type_name(tmp_type) tmp_str+= ' code: ' + self.get_code_name(tmp_type, tmp_code) if self.child(): tmp_str += '\n' + self.child().__str__() return tmp_str def isDestinationUnreachable(self): return self.get_icmp_type() == 3 def isError(self): return not self.isQuery() def isHostUnreachable(self): return self.isDestinationUnreachable() and (self.get_icmp_code() == 1) def isNetUnreachable(self): return self.isDestinationUnreachable() and (self.get_icmp_code() == 0) def isPortUnreachable(self): return self.isDestinationUnreachable() and (self.get_icmp_code() == 3) def isProtocolUnreachable(self): return self.isDestinationUnreachable() and (self.get_icmp_code() == 2) def isQuery(self): tmp_dict = {8:'', 9:'', 10:'', 13:'', 14:'', 15:'', 16:'', 17:'', 18:''} return tmp_dict.has_key(self.get_icmp_type()) class IGMP(Header): protocol = 2 def __init__(self, aBuffer = None): Header.__init__(self, 8) if aBuffer: self.load_header(aBuffer) def get_igmp_type(self): return self.get_byte(0) def set_igmp_type(self, aValue): self.set_byte(0, aValue) def get_igmp_code(self): return self.get_byte(1) def set_igmp_code(self, aValue): self.set_byte(1, aValue) def get_igmp_cksum(self): return self.get_word(2) def set_igmp_cksum(self, aValue): self.set_word(2, aValue) def get_igmp_group(self): return self.get_long(4) def set_igmp_group(self, aValue): self.set_long(4, aValue) def get_header_size(self): return 8 def get_type_name(self, aType): tmp_dict = {0x11:'HOST MEMBERSHIP QUERY ', 0x12:'v1 HOST MEMBERSHIP REPORT ', 0x13:'IGMP DVMRP ', 0x14:' PIM ', 0x16:'v2 HOST MEMBERSHIP REPORT ', 0x17:'HOST LEAVE MESSAGE ', 0x1e:'MTRACE REPLY ', 0X1f:'MTRACE QUERY '} answer = tmp_type.get(aType, 'UNKNOWN TYPE OR VERSION ') return answer def calculate_checksum(self): if self.__auto_checksum and (not self.get_igmp_cksum()): self.set_igmp_cksum(self.compute_checksum(self.get_buffer_as_string())) def __str__(self): knowcode = 0 tmp_str = 'IGMP: ' + self.get_type_name(self.get_igmp_type()) tmp_str += 'Group: ' + socket.inet_ntoa(pack('!L',self.get_igmp_group())) if self.child(): tmp_str += '\n' + self.child().__str__() return tmp_str class ARP(Header): ethertype = 0x806 def __init__(self, aBuffer = None): Header.__init__(self, 7) if aBuffer: self.load_header(aBuffer) def get_ar_hrd(self): return self.get_word(0) def set_ar_hrd(self, aValue): self.set_word(0, aValue) def get_ar_pro(self): return self.get_word(2) def set_ar_pro(self, aValue): self.set_word(2, aValue) def get_ar_hln(self): return self.get_byte(4) def set_ar_hln(self, aValue): self.set_byte(4, aValue) def get_ar_pln(self): return self.get_byte(5) def set_ar_pln(self, aValue): self.set_byte(5, aValue) def get_ar_op(self): return self.get_word(6) def set_ar_op(self, aValue): self.set_word(6, aValue) def get_ar_sha(self): tmp_size = self.get_ar_hln() return self.get_bytes().tolist()[8: 8 + tmp_size] def set_ar_sha(self, aValue): for i in range(0, self.get_ar_hln()): self.set_byte(i + 8, aValue[i]) def get_ar_spa(self): tmp_size = self.get_ar_pln() return self.get_bytes().tolist()[8 + self.get_ar_hln(): 8 + self.get_ar_hln() + tmp_size] def set_ar_spa(self, aValue): for i in range(0, self.get_ar_pln()): self.set_byte(i + 8 + self.get_ar_hln(), aValue[i]) def get_ar_tha(self): tmp_size = self.get_ar_hln() tmp_from = 8 + self.get_ar_hln() + self.get_ar_pln() return self.get_bytes().tolist()[tmp_from: tmp_from + tmp_size] def set_ar_tha(self, aValue): tmp_from = 8 + self.get_ar_hln() + self.get_ar_pln() for i in range(0, self.get_ar_hln()): self.set_byte(i + tmp_from, aValue[i]) def get_ar_tpa(self): tmp_size = self.get_ar_pln() tmp_from = 8 + ( 2 * self.get_ar_hln()) + self.get_ar_pln() return self.get_bytes().tolist()[tmp_from: tmp_from + tmp_size] def set_ar_tpa(self, aValue): tmp_from = 8 + (2 * self.get_ar_hln()) + self.get_ar_pln() for i in range(0, self.get_ar_pln()): self.set_byte(i + tmp_from, aValue[i]) def get_header_size(self): return 8 + (2 * self.get_ar_hln()) + (2 * self.get_ar_pln()) def get_op_name(self, ar_op): tmp_dict = {1:'REQUEST', 2:'REPLY', 3:'REVREQUEST', 4:'REVREPLY', 8:'INVREQUEST', 9:'INVREPLY'} answer = tmp_dict.get(ar_op, 'UNKNOWN') return answer def get_hrd_name(self, ar_hrd): tmp_dict = { 1:'ARPHRD ETHER', 6:'ARPHRD IEEE802', 15:'ARPHRD FRELAY'} answer = tmp_dict.get(ar_hrd, 'UNKNOWN') return answer def as_hrd(self, anArray): if not anArray: return '' tmp_str = '%x' % anArray[0] for i in range(1, len(anArray)): tmp_str += ':%x' % anArray[i] return tmp_str def as_pro(self, anArray): if not anArray: return '' tmp_str = '%d' % anArray[0] for i in range(1, len(anArray)): tmp_str += '.%d' % anArray[i] return tmp_str def __str__(self): tmp_op = self.get_ar_op() tmp_str = 'ARP format: ' + self.get_hrd_name(self.get_ar_hrd()) + ' ' tmp_str += 'opcode: ' + self.get_op_name(tmp_op) tmp_str += '\n' + self.as_hrd(self.get_ar_sha()) + ' -> ' tmp_str += self.as_hrd(self.get_ar_tha()) tmp_str += '\n' + self.as_pro(self.get_ar_spa()) + ' -> ' tmp_str += self.as_pro(self.get_ar_tpa()) if self.child(): tmp_str += '\n' + self.child().__str__() return tmp_str def example(): #To execute an example, remove this line a = Ethernet() b = ARP() c = Data('Hola loco!!!') b.set_ar_hln(6) b.set_ar_pln(4) #a.set_ip_dst('192.168.22.6') #a.set_ip_src('1.1.1.2') a.contains(b) b.contains(c) b.set_ar_op(2) b.set_ar_hrd(1) b.set_ar_spa((192, 168, 22, 6)) b.set_ar_tpa((192, 168, 66, 171)) a.set_ether_shost((0x0, 0xe0, 0x7d, 0x8a, 0xef, 0x3d)) a.set_ether_dhost((0x0, 0xc0, 0xdf, 0x6, 0x5, 0xe))
55,420
Python
.py
1,422
29.859353
433
0.57149
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,943
ntlm.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/ntlm.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: ntlm.py,v 1.2 2006/05/23 21:19:25 gera Exp $ # from impacket.structure import Structure try: from Crypto.Cipher import DES from Crypto.Hash import MD4 POW = None except Exception: try: import POW except Exception: pass NTLM_AUTH_NONE = 1 NTLM_AUTH_CONNECT = 2 NTLM_AUTH_CALL = 3 NTLM_AUTH_PKT = 4 NTLM_AUTH_PKT_INTEGRITY = 5 NTLM_AUTH_PKT_PRIVACY = 6 NTLMSSP_KEY_56 = 0x80000000 NTLMSSP_KEY_EXCHANGE = 0x40000000 NTLMSSP_KEY_128 = 0x20000000 # NTLMSSP_ = 0x10000000 # NTLMSSP_ = 0x08000000 # NTLMSSP_ = 0x04000000 # NTLMSSP_ = 0x02000000 # NTLMSSP_ = 0x01000000 NTLMSSP_TARGET_INFO = 0x00800000 # NTLMSSP_ = 0x00400000 # NTLMSSP_ = 0x00200000 # NTLMSSP_ = 0x00100000 NTLMSSP_NTLM2_KEY = 0x00080000 NTLMSSP_CHALL_NOT_NT = 0x00040000 NTLMSSP_CHALL_ACCEPT = 0x00020000 NTLMSSP_CHALL_INIT = 0x00010000 NTLMSSP_ALWAYS_SIGN = 0x00008000 # forces the other end to sign packets NTLMSSP_LOCAL_CALL = 0x00004000 NTLMSSP_WORKSTATION = 0x00002000 NTLMSSP_DOMAIN = 0x00001000 # NTLMSSP_ = 0x00000800 # NTLMSSP_ = 0x00000400 NTLMSSP_NTLM_KEY = 0x00000200 NTLMSSP_NETWARE = 0x00000100 NTLMSSP_LM_KEY = 0x00000080 NTLMSSP_DATAGRAM = 0x00000040 NTLMSSP_SEAL = 0x00000020 NTLMSSP_SIGN = 0x00000010 # means packet is signed, if verifier is wrong it fails # NTLMSSP_ = 0x00000008 NTLMSSP_TARGET = 0x00000004 NTLMSSP_OEM = 0x00000002 NTLMSSP_UNICODE = 0x00000001 class NTLMAuthHeader(Structure): commonHdr = ( ('auth_type', 'B=10'), ('auth_level','B'), ('auth_pad_len','B=0'), ('auth_rsvrd','"\x00'), ('auth_ctx_id','<L=747920'), ) structure = ( ('data',':'), ) class NTLMAuthNegotiate(NTLMAuthHeader): structure = ( ('','"NTLMSSP\x00'), ('message_type','<L=1'), ('flags','<L'), ('domain_len','<H-domain_name'), ('domain_max_len','<H-domain_name'), ('domain_offset','<L'), ('host_len','<H-host_name'), ('host_maxlen','<H-host_name'), ('host_offset','<L'), ('host_name',':'), ('domain_name',':')) def __init__(self): NTLMAuthHeader.__init__(self) self['flags']= ( NTLMSSP_KEY_128 | NTLMSSP_KEY_EXCHANGE| # NTLMSSP_LM_KEY | NTLMSSP_NTLM_KEY | NTLMSSP_UNICODE | # NTLMSSP_ALWAYS_SIGN | NTLMSSP_SIGN | NTLMSSP_SEAL | # NTLMSSP_TARGET | 0) self['host_name']='' self['domain_name']='' def __str__(self): self['host_offset']=32 self['domain_offset']=32+len(self['host_name']) return NTLMAuthHeader.__str__(self) class NTLMAuthChallenge(NTLMAuthHeader): structure = ( ('','"NTLMSSP\x00'), ('message_type','<L=2'), ('domain_len','<H-domain_name'), ('domain_max_len','<H-domain_name'), ('domain_offset','<L'), ('flags','<L'), ('challenge','8s'), ('reserved','"\x00\x00\x00\x00\x00\x00\x00\x00'), ('domain_name',':')) class NTLMAuthChallengeResponse(NTLMAuthHeader): structure = ( ('','"NTLMSSP\x00'), ('message_type','<L=3'), ('lanman_len','<H-lanman'), ('lanman_max_len','<H-lanman'), ('lanman_offset','<L'), ('ntlm_len','<H-ntlm'), ('ntlm_max_len','<H-ntlm'), ('ntlm_offset','<L'), ('domain_len','<H-domain_name'), ('domain_max_len','<H-domain_name'), ('domain_offset','<L'), ('user_len','<H-user_name'), ('user_max_len','<H-user_name'), ('user_offset','<L'), ('host_len','<H-host_name'), ('host_max_len','<H-host_name'), ('host_offset','<L'), ('session_key_len','<H-session_key'), ('session_key_max_len','<H-session_key'), ('session_key_offset','<L'), ('flags','<L'), ('domain_name',':'), ('user_name',':'), ('host_name',':'), ('lanman',':'), ('ntlm',':'), ('session_key',':')) def __init__(self, username, password, challenge): NTLMAuthHeader.__init__(self) self['session_key']='' self['user_name']=username.encode('utf-16le') self['domain_name']='' #"CLON".encode('utf-16le') self['host_name']='' #"BETS".encode('utf-16le') self['flags'] = ( #authResp['flags'] # we think (beto & gera) that his flags force a memory conten leakage when a windows 2000 answers using uninitializaed verifiers NTLMSSP_KEY_128 | NTLMSSP_KEY_EXCHANGE| # NTLMSSP_LM_KEY | NTLMSSP_NTLM_KEY | NTLMSSP_UNICODE | # NTLMSSP_ALWAYS_SIGN | NTLMSSP_SIGN | NTLMSSP_SEAL | # NTLMSSP_TARGET | 0) # Here we do the stuff if username and password: lmhash = compute_lmhash(password) nthash = compute_nthash(password) self['lanman']=get_ntlmv1_response(lmhash, challenge) self['ntlm']=get_ntlmv1_response(nthash, challenge) # This is not used for LM_KEY nor NTLM_KEY else: self['lanman'] = '' self['ntlm'] = '' if not self['host_name']: self['host_name'] = 'NULL'.encode('utf-16le') # for NULL session there must be a hostname def __str__(self): self['domain_offset']=64 self['user_offset']=64+len(self['domain_name']) self['host_offset']=self['user_offset']+len(self['user_name']) self['lanman_offset']=self['host_offset']+len(self['host_name']) self['ntlm_offset']=self['lanman_offset']+len(self['lanman']) self['session_key_offset']=self['ntlm_offset']+len(self['ntlm']) return NTLMAuthHeader.__str__(self) class ImpacketStructure(Structure): def set_parent(self, other): self.parent = other def get_packet(self): return str(self) def get_size(self): return len(self) class NTLMAuthVerifier(NTLMAuthHeader): structure = ( ('version','<L=1'), ('data','12s'), # ('_zero','<L=0'), # ('crc','<L=0'), # ('sequence','<L=0'), ) KNOWN_DES_INPUT = "KGS!@#$%" def __expand_DES_key( key): # Expand the key from a 7-byte password key into a 8-byte DES key key = key[:7] key += '\x00'*(7-len(key)) s = chr(((ord(key[0]) >> 1) & 0x7f) << 1) s = s + chr(((ord(key[0]) & 0x01) << 6 | ((ord(key[1]) >> 2) & 0x3f)) << 1) s = s + chr(((ord(key[1]) & 0x03) << 5 | ((ord(key[2]) >> 3) & 0x1f)) << 1) s = s + chr(((ord(key[2]) & 0x07) << 4 | ((ord(key[3]) >> 4) & 0x0f)) << 1) s = s + chr(((ord(key[3]) & 0x0f) << 3 | ((ord(key[4]) >> 5) & 0x07)) << 1) s = s + chr(((ord(key[4]) & 0x1f) << 2 | ((ord(key[5]) >> 6) & 0x03)) << 1) s = s + chr(((ord(key[5]) & 0x3f) << 1 | ((ord(key[6]) >> 7) & 0x01)) << 1) s = s + chr((ord(key[6]) & 0x7f) << 1) return s def __DES_block(key, msg): if POW: cipher = POW.Symmetric(POW.DES_ECB) cipher.encryptInit(__expand_DES_key(key)) return cipher.update(msg) else: cipher = DES.new(__expand_DES_key(key),DES.MODE_ECB) return cipher.encrypt(msg) def ntlmssp_DES_encrypt(key, challenge): answer = __DES_block(key[:7], challenge) answer += __DES_block(key[7:14], challenge) answer += __DES_block(key[14:], challenge) return answer def compute_lmhash(password): # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html) password = password.upper() lmhash = __DES_block(password[:7], KNOWN_DES_INPUT) lmhash += __DES_block(password[7:14], KNOWN_DES_INPUT) return lmhash def compute_nthash(password): # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html) password = unicode(password).encode('utf_16le') if POW: hash = POW.Digest(POW.MD4_DIGEST) else: hash = MD4.new() hash.update(password) return hash.digest() def get_ntlmv1_response(key, challenge): return ntlmssp_DES_encrypt(key, challenge)
9,115
Python
.py
235
30.280851
144
0.555135
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,944
ImpactDecoder.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/ImpactDecoder.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: ImpactDecoder.py,v 1.6 2006/05/23 22:25:34 gera Exp $ # # Description: # Convenience packet unpackers for various network protocols # implemented in the ImpactPacket module. # # Author: # Javier Burroni (javier) # Bruce Leidl (brl) import ImpactPacket """Classes to convert from raw packets into a hierarchy of ImpactPacket derived objects. The protocol of the outermost layer must be known in advance, and the packet must be fed to the corresponding decoder. From there it will try to decode the raw data into a hierarchy of ImpactPacket derived objects; if a layer's protocol is unknown, all the remaining data will be wrapped into a ImpactPacket.Data object. """ class Decoder: def decode(self, aBuffer): pass class EthDecoder(Decoder): def __init__(self): pass def decode(self, aBuffer): e = ImpactPacket.Ethernet(aBuffer) off = e.get_header_size() if e.get_ether_type() == ImpactPacket.IP.ethertype: self.ip_decoder = IPDecoder() packet = self.ip_decoder.decode(aBuffer[off:]) elif e.get_ether_type() == ImpactPacket.ARP.ethertype: self.arp_decoder = ARPDecoder() packet = self.arp_decoder.decode(aBuffer[off:]) else: self.data_decoder = DataDecoder() packet = self.data_decoder.decode(aBuffer[off:]) e.contains(packet) return e # Linux "cooked" capture encapsulation. # Used, for instance, for packets returned by the "any" interface. class LinuxSLLDecoder(Decoder): def __init__(self): pass def decode(self, aBuffer): e = ImpactPacket.LinuxSLL(aBuffer) off = 16 if e.get_ether_type() == ImpactPacket.IP.ethertype: self.ip_decoder = IPDecoder() packet = self.ip_decoder.decode(aBuffer[off:]) elif e.get_ether_type() == ImpactPacket.ARP.ethertype: self.arp_decoder = ARPDecoder() packet = self.arp_decoder.decode(aBuffer[off:]) else: self.data_decoder = DataDecoder() packet = self.data_decoder.decode(aBuffer[off:]) e.contains(packet) return e class IPDecoder(Decoder): def __init__(self): pass def decode(self, aBuffer): i = ImpactPacket.IP(aBuffer) off = i.get_header_size() if i.get_ip_p() == ImpactPacket.UDP.protocol: self.udp_decoder = UDPDecoder() packet = self.udp_decoder.decode(aBuffer[off:]) elif i.get_ip_p() == ImpactPacket.TCP.protocol: self.tcp_decoder = TCPDecoder() packet = self.tcp_decoder.decode(aBuffer[off:]) elif i.get_ip_p() == ImpactPacket.ICMP.protocol: self.icmp_decoder = ICMPDecoder() packet = self.icmp_decoder.decode(aBuffer[off:]) else: self.data_decoder = DataDecoder() packet = self.data_decoder.decode(aBuffer[off:]) i.contains(packet) return i class ARPDecoder(Decoder): def __init__(self): pass def decode(self, aBuffer): arp = ImpactPacket.ARP(aBuffer) off = arp.get_header_size() self.data_decoder = DataDecoder() packet = self.data_decoder.decode(aBuffer[off:]) arp.contains(packet) return arp class UDPDecoder(Decoder): def __init__(self): pass def decode(self, aBuffer): u = ImpactPacket.UDP(aBuffer) off = u.get_header_size() self.data_decoder = DataDecoder() packet = self.data_decoder.decode(aBuffer[off:]) u.contains(packet) return u class TCPDecoder(Decoder): def __init__(self): pass def decode(self, aBuffer): t = ImpactPacket.TCP(aBuffer) off = t.get_header_size() self.data_decoder = DataDecoder() packet = self.data_decoder.decode(aBuffer[off:]) t.contains(packet) return t class IPDecoderForICMP(Decoder): """This class was added to parse the IP header of ICMP unreachables packets If you use the "standard" IPDecoder, it might crash (see bug #4870) ImpactPacket.py because the TCP header inside the IP header is incomplete""" def __init__(self): pass def decode(self, aBuffer): i = ImpactPacket.IP(aBuffer) off = i.get_header_size() if i.get_ip_p() == ImpactPacket.UDP.protocol: self.udp_decoder = UDPDecoder() packet = self.udp_decoder.decode(aBuffer[off:]) else: self.data_decoder = DataDecoder() packet = self.data_decoder.decode(aBuffer[off:]) i.contains(packet) return i class ICMPDecoder(Decoder): def __init__(self): pass def decode(self, aBuffer): ic = ImpactPacket.ICMP(aBuffer) off = ic.get_header_size() if ic.get_icmp_type() == ImpactPacket.ICMP.ICMP_UNREACH: self.ip_decoder = IPDecoderForICMP() packet = self.ip_decoder.decode(aBuffer[off:]) else: self.data_decoder = DataDecoder() packet = self.data_decoder.decode(aBuffer[off:]) ic.contains(packet) return ic class DataDecoder(Decoder): def decode(self, aBuffer): d = ImpactPacket.Data(aBuffer) return d
5,509
Python
.py
148
29.797297
87
0.642375
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,945
smb.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/smb.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: smb.py,v 1.7 2006/05/23 21:19:25 gera Exp $ # # -*- mode: python; tab-width: 4 -*- # $Id: smb.py,v 1.7 2006/05/23 21:19:25 gera Exp $ # # Copyright (C) 2001 Michael Teo <michaelteo@bigfoot.com> # smb.py - SMB/CIFS library # # This software is provided 'as-is', without any express or implied warranty. # In no event will the author be held liable for any damages arising from the # use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # # 3. This notice cannot be removed or altered from any source distribution. # # Altered source done by Alberto Solino # Todo: # [ ] Try [SMB]transport fragmentation using Transact requests # [ ] Try other methods of doing write (write_raw, transact2, write, write_and_unlock, write_and_close, write_mpx) # [-] Try replacements for SMB_COM_NT_CREATE_ANDX (CREATE, T_TRANSACT_CREATE, OPEN_ANDX works # [x] Fix forceWriteAndx, which needs to send a RecvRequest, because recv() will not send it # [x] Fix Recv() when using RecvAndx and the answer comes splet in several packets # [ ] Try [SMB]transport fragmentation with overlaping segments # [ ] Try [SMB]transport fragmentation with out of order segments # [x] Do chained AndX requests import os, sys, socket, string, re, select, errno import nmb import types from random import randint from struct import * import ntlm from dcerpc import samr from structure import Structure unicode_support = 0 unicode_convert = 1 try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from binascii import a2b_hex CVS_REVISION = '$Revision: 1.7 $' # Shared Device Type SHARED_DISK = 0x00 SHARED_PRINT_QUEUE = 0x01 SHARED_DEVICE = 0x02 SHARED_IPC = 0x03 # Extended attributes mask ATTR_ARCHIVE = 0x020 ATTR_COMPRESSED = 0x800 ATTR_NORMAL = 0x080 ATTR_HIDDEN = 0x002 ATTR_READONLY = 0x001 ATTR_TEMPORARY = 0x100 ATTR_DIRECTORY = 0x010 ATTR_SYSTEM = 0x004 # Service Type SERVICE_DISK = 'A:' SERVICE_PRINTER = 'LPT1:' SERVICE_IPC = 'IPC' SERVICE_COMM = 'COMM' SERVICE_ANY = '?????' # Server Type (Can be used to mask with SMBMachine.get_type() or SMBDomain.get_type()) SV_TYPE_WORKSTATION = 0x00000001 SV_TYPE_SERVER = 0x00000002 SV_TYPE_SQLSERVER = 0x00000004 SV_TYPE_DOMAIN_CTRL = 0x00000008 SV_TYPE_DOMAIN_BAKCTRL = 0x00000010 SV_TYPE_TIME_SOURCE = 0x00000020 SV_TYPE_AFP = 0x00000040 SV_TYPE_NOVELL = 0x00000080 SV_TYPE_DOMAIN_MEMBER = 0x00000100 SV_TYPE_PRINTQ_SERVER = 0x00000200 SV_TYPE_DIALIN_SERVER = 0x00000400 SV_TYPE_XENIX_SERVER = 0x00000800 SV_TYPE_NT = 0x00001000 SV_TYPE_WFW = 0x00002000 SV_TYPE_SERVER_NT = 0x00004000 SV_TYPE_POTENTIAL_BROWSER = 0x00010000 SV_TYPE_BACKUP_BROWSER = 0x00020000 SV_TYPE_MASTER_BROWSER = 0x00040000 SV_TYPE_DOMAIN_MASTER = 0x00080000 SV_TYPE_LOCAL_LIST_ONLY = 0x40000000 SV_TYPE_DOMAIN_ENUM = 0x80000000 # Options values for SMB.stor_file and SMB.retr_file SMB_O_CREAT = 0x10 # Create the file if file does not exists. Otherwise, operation fails. SMB_O_EXCL = 0x00 # When used with SMB_O_CREAT, operation fails if file exists. Cannot be used with SMB_O_OPEN. SMB_O_OPEN = 0x01 # Open the file if the file exists SMB_O_TRUNC = 0x02 # Truncate the file if the file exists # Share Access Mode SMB_SHARE_COMPAT = 0x00 SMB_SHARE_DENY_EXCL = 0x10 SMB_SHARE_DENY_WRITE = 0x20 SMB_SHARE_DENY_READEXEC = 0x30 SMB_SHARE_DENY_NONE = 0x40 SMB_ACCESS_READ = 0x00 SMB_ACCESS_WRITE = 0x01 SMB_ACCESS_READWRITE = 0x02 SMB_ACCESS_EXEC = 0x03 TRANS_DISCONNECT_TID = 1 TRANS_NO_RESPONSE = 2 #*********************************** TEMP BEGIN ******************************** def set_key_odd_parity(key): "" for i in range(len(key)): for k in range(7): bit = 0 t = key[i] >> k bit = (t ^ bit) & 0x1 key[i] = (key[i] & 0xFE) | bit return key #*********************************** TEMP END ******************************** def strerror(errclass, errcode): if errclass == 0x01: return 'OS error', ERRDOS.get(errcode, 'Unknown error') elif errclass == 0x02: return 'Server error', ERRSRV.get(errcode, 'Unknown error') elif errclass == 0x03: return 'Hardware error', ERRHRD.get(errcode, 'Unknown error') # This is not a standard error class for SMB elif errclass == 0x80: return 'Browse error', ERRBROWSE.get(errcode, 'Unknown error') elif errclass == 0xff: return 'Bad command', 'Bad command. Please file bug report' else: return 'Unknown error', 'Unknown error' # Raised when an error has occured during a session class SessionError(Exception): # Error codes # SMB X/Open error codes for the ERRDOS error class ERRsuccess = 0 ERRbadfunc = 1 ERRbadfile = 2 ERRbadpath = 3 ERRnofids = 4 ERRnoaccess = 5 ERRbadfid = 6 ERRbadmcb = 7 ERRnomem = 8 ERRbadmem = 9 ERRbadenv = 10 ERRbadaccess = 12 ERRbaddata = 13 ERRres = 14 ERRbaddrive = 15 ERRremcd = 16 ERRdiffdevice = 17 ERRnofiles = 18 ERRgeneral = 31 ERRbadshare = 32 ERRlock = 33 ERRunsup = 50 ERRnetnamedel = 64 ERRnosuchshare = 67 ERRfilexists = 80 ERRinvalidparam = 87 ERRcannotopen = 110 ERRinsufficientbuffer = 122 ERRinvalidname = 123 ERRunknownlevel = 124 ERRnotlocked = 158 ERRrename = 183 ERRbadpipe = 230 ERRpipebusy = 231 ERRpipeclosing = 232 ERRnotconnected = 233 ERRmoredata = 234 ERRnomoreitems = 259 ERRbaddirectory = 267 ERReasnotsupported = 282 ERRlogonfailure = 1326 ERRbuftoosmall = 2123 ERRunknownipc = 2142 ERRnosuchprintjob = 2151 ERRinvgroup = 2455 # here's a special one from observing NT ERRnoipc = 66 # These errors seem to be only returned by the NT printer driver system ERRdriveralreadyinstalled = 1795 ERRunknownprinterport = 1796 ERRunknownprinterdriver = 1797 ERRunknownprintprocessor = 1798 ERRinvalidseparatorfile = 1799 ERRinvalidjobpriority = 1800 ERRinvalidprintername = 1801 ERRprinteralreadyexists = 1802 ERRinvalidprintercommand = 1803 ERRinvaliddatatype = 1804 ERRinvalidenvironment = 1805 ERRunknownprintmonitor = 3000 ERRprinterdriverinuse = 3001 ERRspoolfilenotfound = 3002 ERRnostartdoc = 3003 ERRnoaddjob = 3004 ERRprintprocessoralreadyinstalled = 3005 ERRprintmonitoralreadyinstalled = 3006 ERRinvalidprintmonitor = 3007 ERRprintmonitorinuse = 3008 ERRprinterhasjobsqueued = 3009 # Error codes for the ERRSRV class ERRerror = 1 ERRbadpw = 2 ERRbadtype = 3 ERRaccess = 4 ERRinvnid = 5 ERRinvnetname = 6 ERRinvdevice = 7 ERRqfull = 49 ERRqtoobig = 50 ERRinvpfid = 52 ERRsmbcmd = 64 ERRsrverror = 65 ERRfilespecs = 67 ERRbadlink = 68 ERRbadpermits = 69 ERRbadpid = 70 ERRsetattrmode = 71 ERRpaused = 81 ERRmsgoff = 82 ERRnoroom = 83 ERRrmuns = 87 ERRtimeout = 88 ERRnoresource = 89 ERRtoomanyuids = 90 ERRbaduid = 91 ERRuseMPX = 250 ERRuseSTD = 251 ERRcontMPX = 252 ERRbadPW = None ERRnosupport = 0 ERRunknownsmb = 22 # Error codes for the ERRHRD class ERRnowrite = 19 ERRbadunit = 20 ERRnotready = 21 ERRbadcmd = 22 ERRdata = 23 ERRbadreq = 24 ERRseek = 25 ERRbadmedia = 26 ERRbadsector = 27 ERRnopaper = 28 ERRwrite = 29 ERRread = 30 ERRgeneral = 31 ERRwrongdisk = 34 ERRFCBunavail = 35 ERRsharebufexc = 36 ERRdiskfull = 39 hard_msgs = { 19: ("ERRnowrite", "Attempt to write on write-protected diskette."), 20: ("ERRbadunit", "Unknown unit."), 21: ("ERRnotready", "Drive not ready."), 22: ("ERRbadcmd", "Unknown command."), 23: ("ERRdata", "Data error (CRC)."), 24: ("ERRbadreq", "Bad request structure length."), 25 : ("ERRseek", "Seek error."), 26: ("ERRbadmedia", "Unknown media type."), 27: ("ERRbadsector", "Sector not found."), 28: ("ERRnopaper", "Printer out of paper."), 29: ("ERRwrite", "Write fault."), 30: ("ERRread", "Read fault."), 31: ("ERRgeneral", "General failure."), 32: ("ERRbadshare", "An open conflicts with an existing open."), 33: ("ERRlock", "A Lock request conflicted with an existing lock or specified an invalid mode, or an Unlock requested attempted to remove a lock held by another process."), 34: ("ERRwrongdisk", "The wrong disk was found in a drive."), 35: ("ERRFCBUnavail", "No FCBs are available to process request."), 36: ("ERRsharebufexc", "A sharing buffer has been exceeded.") } dos_msgs = { ERRbadfunc: ("ERRbadfunc", "Invalid function."), ERRbadfile: ("ERRbadfile", "File not found."), ERRbadpath: ("ERRbadpath", "Directory invalid."), ERRnofids: ("ERRnofids", "No file descriptors available"), ERRnoaccess: ("ERRnoaccess", "Access denied."), ERRbadfid: ("ERRbadfid", "Invalid file handle."), ERRbadmcb: ("ERRbadmcb", "Memory control blocks destroyed."), ERRnomem: ("ERRnomem", "Insufficient server memory to perform the requested function."), ERRbadmem: ("ERRbadmem", "Invalid memory block address."), ERRbadenv: ("ERRbadenv", "Invalid environment."), 11: ("ERRbadformat", "Invalid format."), ERRbadaccess: ("ERRbadaccess", "Invalid open mode."), ERRbaddata: ("ERRbaddata", "Invalid data."), ERRres: ("ERRres", "reserved."), ERRbaddrive: ("ERRbaddrive", "Invalid drive specified."), ERRremcd: ("ERRremcd", "A Delete Directory request attempted to remove the server's current directory."), ERRdiffdevice: ("ERRdiffdevice", "Not same device."), ERRnofiles: ("ERRnofiles", "A File Search command can find no more files matching the specified criteria."), ERRbadshare: ("ERRbadshare", "The sharing mode specified for an Open conflicts with existing FIDs on the file."), ERRlock: ("ERRlock", "A Lock request conflicted with an existing lock or specified an invalid mode, or an Unlock requested attempted to remove a lock held by another process."), ERRunsup: ("ERRunsup", "The operation is unsupported"), ERRnosuchshare: ("ERRnosuchshare", "You specified an invalid share name"), ERRfilexists: ("ERRfilexists", "The file named in a Create Directory, Make New File or Link request already exists."), ERRinvalidname: ("ERRinvalidname", "Invalid name"), ERRbadpipe: ("ERRbadpipe", "Pipe invalid."), ERRpipebusy: ("ERRpipebusy", "All instances of the requested pipe are busy."), ERRpipeclosing: ("ERRpipeclosing", "Pipe close in progress."), ERRnotconnected: ("ERRnotconnected", "No process on other end of pipe."), ERRmoredata: ("ERRmoredata", "There is more data to be returned."), ERRinvgroup: ("ERRinvgroup", "Invalid workgroup (try the -W option)"), ERRlogonfailure: ("ERRlogonfailure", "Logon failure"), ERRdiskfull: ("ERRdiskfull", "Disk full"), ERRgeneral: ("ERRgeneral", "General failure"), ERRunknownlevel: ("ERRunknownlevel", "Unknown info level") } server_msgs = { 1: ("ERRerror", "Non-specific error code."), 2: ("ERRbadpw", "Bad password - name/password pair in a Tree Connect or Session Setup are invalid."), 3: ("ERRbadtype", "reserved."), 4: ("ERRaccess", "The requester does not have the necessary access rights within the specified context for the requested function. The context is defined by the TID or the UID."), 5: ("ERRinvnid", "The tree ID (TID) specified in a command was invalid."), 6: ("ERRinvnetname", "Invalid network name in tree connect."), 7: ("ERRinvdevice", "Invalid device - printer request made to non-printer connection or non-printer request made to printer connection."), 49: ("ERRqfull", "Print queue full (files) -- returned by open print file."), 50: ("ERRqtoobig", "Print queue full -- no space."), 51: ("ERRqeof", "EOF on print queue dump."), 52: ("ERRinvpfid", "Invalid print file FID."), 64: ("ERRsmbcmd", "The server did not recognize the command received."), 65: ("ERRsrverror","The server encountered an internal error, e.g., system file unavailable."), 67: ("ERRfilespecs", "The file handle (FID) and pathname parameters contained an invalid combination of values."), 68: ("ERRreserved", "reserved."), 69: ("ERRbadpermits", "The access permissions specified for a file or directory are not a valid combination. The server cannot set the requested attribute."), 70: ("ERRreserved", "reserved."), 71: ("ERRsetattrmode", "The attribute mode in the Set File Attribute request is invalid."), 81: ("ERRpaused", "Server is paused."), 82: ("ERRmsgoff", "Not receiving messages."), 83: ("ERRnoroom", "No room to buffer message."), 87: ("ERRrmuns", "Too many remote user names."), 88: ("ERRtimeout", "Operation timed out."), 89: ("ERRnoresource", "No resources currently available for request."), 90: ("ERRtoomanyuids", "Too many UIDs active on this session."), 91: ("ERRbaduid", "The UID is not known as a valid ID on this session."), 250: ("ERRusempx","Temp unable to support Raw, use MPX mode."), 251: ("ERRusestd","Temp unable to support Raw, use standard read/write."), 252: ("ERRcontmpx", "Continue in MPX mode."), 253: ("ERRreserved", "reserved."), 254: ("ERRreserved", "reserved."), 0xFFFF: ("ERRnosupport", "Function not supported.") } # Error clases ERRDOS = 0x1 error_classes = { 0: ("SUCCESS", {}), ERRDOS: ("ERRDOS", dos_msgs), 0x02: ("ERRSRV",server_msgs), 0x03: ("ERRHRD",hard_msgs), 0x04: ("ERRXOS", {} ), 0xE1: ("ERRRMX1", {} ), 0xE2: ("ERRRMX2", {} ), 0xE3: ("ERRRMX3", {} ), 0xFF: ("ERRCMD", {} ) } def __init__( self, str, error_class, error_code): self.args = str self.error_class = error_class self.error_code = error_code def get_error_class( self ): return self.error_class def get_error_code( self ): return self.error_code def __str__( self ): error_class = SessionError.error_classes.get( self.error_class, None ) if not error_class: error_code_str = self.error_code error_class_str = self.error_class else: error_class_str = error_class[0] error_code = error_class[1].get( self.error_code, None ) if not error_code: error_code_str = self.error_code else: error_code_str = '%s(%s)' % (error_code) return 'SessionError: %s, class: %s, code: %s' % (self.args, error_class_str, error_code_str) # Raised when an supported feature is present/required in the protocol but is not # currently supported by pysmb class UnsupportedFeature(Exception): pass # Contains information about a SMB shared device/service class SharedDevice: def __init__(self, name, type, comment): self.__name = name self.__type = type self.__comment = comment def get_name(self): return self.__name def get_type(self): return self.__type def get_comment(self): return self.__comment def __repr__(self): return '<SharedDevice instance: name=' + self.__name + ', type=' + str(self.__type) + ', comment="' + self.__comment + '">' # Contains information about the shared file/directory class SharedFile: def __init__(self, ctime, atime, mtime, filesize, allocsize, attribs, shortname, longname): self.__ctime = ctime self.__atime = atime self.__mtime = mtime self.__filesize = filesize self.__allocsize = allocsize self.__attribs = attribs try: self.__shortname = shortname[:string.index(shortname, '\0')] except ValueError: self.__shortname = shortname try: self.__longname = longname[:string.index(longname, '\0')] except ValueError: self.__longname = longname def get_ctime(self): return self.__ctime def get_ctime_epoch(self): return self.__convert_smbtime(self.__ctime) def get_mtime(self): return self.__mtime def get_mtime_epoch(self): return self.__convert_smbtime(self.__mtime) def get_atime(self): return self.__atime def get_atime_epoch(self): return self.__convert_smbtime(self.__atime) def get_filesize(self): return self.__filesize def get_allocsize(self): return self.__allocsize def get_attributes(self): return self.__attribs def is_archive(self): return self.__attribs & ATTR_ARCHIVE def is_compressed(self): return self.__attribs & ATTR_COMPRESSED def is_normal(self): return self.__attribs & ATTR_NORMAL def is_hidden(self): return self.__attribs & ATTR_HIDDEN def is_readonly(self): return self.__attribs & ATTR_READONLY def is_temporary(self): return self.__attribs & ATTR_TEMPORARY def is_directory(self): return self.__attribs & ATTR_DIRECTORY def is_system(self): return self.__attribs & ATTR_SYSTEM def get_shortname(self): return self.__shortname def get_longname(self): return self.__longname def __repr__(self): return '<SharedFile instance: shortname="' + self.__shortname + '", longname="' + self.__longname + '", filesize=' + str(self.__filesize) + '>' def __convert_smbtime(self, t): x = t >> 32 y = t & 0xffffffffL geo_cal_offset = 11644473600.0 # = 369.0 * 365.25 * 24 * 60 * 60 - (3.0 * 24 * 60 * 60 + 6.0 * 60 * 60) return ((x * 4.0 * (1 << 30) + (y & 0xfff00000L)) * 1.0e-7 - geo_cal_offset) # Contain information about a SMB machine class SMBMachine: def __init__(self, nbname, type, comment): self.__nbname = nbname self.__type = type self.__comment = comment def __repr__(self): return '<SMBMachine instance: nbname="' + self.__nbname + '", type=' + hex(self.__type) + ', comment="' + self.__comment + '">' class SMBDomain: def __init__(self, nbgroup, type, master_browser): self.__nbgroup = nbgroup self.__type = type self.__master_browser = master_browser def __repr__(self): return '<SMBDomain instance: nbgroup="' + self.__nbgroup + '", type=' + hex(self.__type) + ', master browser="' + self.__master_browser + '">' # Represents a SMB Packet class NewSMBPacket(Structure): structure = ( ('Signature', '"\xffSMB'), ('Command','B=0'), ('ErrorClass','B=0'), ('_reserved','B=0'), ('ErrorCode','<H=0'), ('Flags1','B=0'), ('Flags2','<H=0'), ('Padding','12s=""'), ('Tid','<H=0xffff'), ('Pid','<H=0'), ('Uid','<H=0'), ('Mid','<H=0'), ('Data','*:'), ) def __init__(self, **kargs): Structure.__init__(self, **kargs) if not kargs.has_key('data'): self['Data'] = [] def addCommand(self, command): if len(self['Data']) == 0: self['Command'] = command.command else: self['Data'][-1]['Parameters']['AndXCommand'] = command.command self['Data'][-1]['Parameters']['AndXOffset'] = len(self) self['Data'].append(command) def isMoreData(self): return (self['Command'] in [SMB.SMB_COM_TRANSACTION, SMB.SMB_COM_READ_ANDX, SMB.SMB_COM_READ_RAW] and self['ErrorClass'] == 1 and self['ErrorCode'] == SessionError.ERRmoredata) def isValidAnswer(self, cmd): # this was inside a loop reading more from the net (with recv_packet(None)) if self['Command'] == cmd: if (self['ErrorClass'] == 0x00 and self['ErrorCode'] == 0x00): return 1 elif self.isMoreData(): return 1 raise SessionError, ("SMB Library Error", self['ErrorClass'], self['ErrorCode']) else: raise UnsupportedFeature, ("Unexpected answer from server: Got %d, Expected %d" % (self['Command'], cmd)) class SMBPacket: def __init__(self,data = ''): # The uid attribute will be set when the client calls the login() method self._command = 0x0 self._error_class = 0x0 self._error_code = 0x0 self._flags = 0x0 self._flags2 = 0x0 self._pad = '\0' * 12 self._tid = 0x0 self._pid = 0x0 self._uid = 0x0 self._mid = 0x0 self._wordcount = 0x0 self._parameter_words = '' self._bytecount = 0x0 self._buffer = '' if data != '': self._command = ord(data[4]) self._error_class = ord(data[5]) self._error_code = unpack('<H',data[7:9])[0] self._flags = ord(data[9]) self._flags2 = unpack('<H',data[10:12])[0] self._tid = unpack('<H',data[24:26])[0] self._pid = unpack('<H',data[26:28])[0] self._uid = unpack('<H',data[28:30])[0] self._mid = unpack('<H',data[30:32])[0] self._wordcount = ord(data[32]) self._parameter_words = data[33:33+self._wordcount*2] self._bytecount = ord(data[33+self._wordcount*2]) self._buffer = data[35+self._wordcount*2:] def set_command(self,command): self._command = command def set_error_class(self, error_class): self._error_class = error_class def set_error_code(self,error_code): self._error_code = error_code def set_flags(self,flags): self._flags = flags def set_flags2(self, flags2): self._flags2 = flags2 def set_pad(self, pad): self._pad = pad def set_tid(self,tid): self._tid = tid def set_pid(self,pid): self._pid = pid def set_uid(self,uid): self._uid = uid def set_mid(self,mid): self._mid = mid def set_parameter_words(self,param): self._parameter_words = param self._wordcount = len(param)/2 def set_buffer(self,buffer): if type(buffer) is types.UnicodeType: raise Exception('SMBPacket: Invalid buffer. Received unicode') self._buffer = buffer self._bytecount = len(buffer) def get_command(self): return self._command def get_error_class(self): return self._error_class def get_error_code(self): return self._error_code def get_flags(self): return self._flags def get_flags2(self): return self._flags2 def get_pad(self): return self._pad def get_tid(self): return self._tid def get_pid(self): return self._pid def get_uid(self): return self._uid def get_mid(self): return self._mid def get_parameter_words(self): return self._parameter_words def get_wordcount(self): return self._wordcount def get_bytecount(self): return self._bytecount def get_buffer(self): return self._buffer def rawData(self): data = pack('<4sBBBHBH12sHHHHB','\xffSMB',self._command,self._error_class,0,self._error_code,self._flags, self._flags2,self._pad,self._tid, self._pid, self._uid, self._mid, self._wordcount) + self._parameter_words + pack('<H',self._bytecount) + self._buffer return data class TRANSHeader: def __init__(self,params = '', data = ''): self._total_param_count = 0 self._total_data_count = 0 self._max_param_count = 0 self._max_data_count = 0 self._max_setup_count = 0 self._flags = 0 self._timeout = 0 self._param_count = 0 self._param_offset = 0 self._data_count = 0 self._data_offset = 0 self._setup_count = 0 self._setup = 0 self._name = '' self._pad = '' self._parameters = 0 self._data = 0 if data != '' and params != '': self._total_param_count, self._total_data_count, _, self._param_count, self._param_offset, self._param_displacement, self._data_count, self._data_offset, self._data_displacement, self._setup_count, _ = unpack ('<HHHHHHHHHBB', params) self._data = data[-self._data_count:]; # Remove -potential- prefix padding. def set_flags(self, flags): self._flags = flags def set_name(self,name): self._name = name def set_setup(self,setup): self._setup = setup def set_parameters(self,parameters): self._parameters = parameters self._total_param_count = len(parameters) def set_data(self, data): self._data = data self._total_data_count = len(data) def set_max_data_count(self, max): self._max_data_count = max def set_max_param_count(self, max): self._max_param_count = max def get_rawParameters(self): self._param_offset = 32+3+28+len(self._setup)+len(self._name) self._data_offset = self._param_offset + len(self._parameters) return pack('<HHHHBBHLHHHHHBB', self._total_param_count, self._total_data_count, self._max_param_count, self._max_data_count, self._max_setup_count, 0,self._flags, self._timeout, 0, self._total_param_count, self._param_offset , self._total_data_count, self._data_offset, len(self._setup) / 2,0 ) + self._setup def get_data(self): return self._data def rawData(self): return self._name + self._parameters + self._data class SMBCommand(Structure): structure = ( ('WordCount', 'B=len(Parameters)/2'), ('_ParametersLength','_-Parameters','WordCount*2'), ('Parameters',':'), # default set by constructor ('ByteCount','<H-Data'), ('Data',':'), # default set by constructor ) def __init__(self, commandOrData = None, data = None, **kargs): if type(commandOrData) == type(0): self.command = commandOrData else: data = data or commandOrData Structure.__init__(self, data = data, **kargs) if data is None: self['Parameters'] = '' self['Data'] = '' class AsciiOrUnicodeStructure(Structure): def __init__(self, flags = 0, **kargs): if flags & SMB.FLAGS2_UNICODE: self.structure = self.UnicodeStructure else: self.structure = self.AsciiStructure return Structure.__init__(self, **kargs) class SMBCommand_Parameters(Structure): pass class SMBAndXCommand_Parameters(Structure): commonHdr = ( ('AndXCommand','B=0xff'), ('_reserved','B=0'), ('AndXOffset','<H=0'), ) structure = ( # default structure, overriden by subclasses ('Data',':=""'), ) class SMBSessionSetupAndX_Parameters(SMBAndXCommand_Parameters): structure = ( ('MaxBuffer','<H'), ('MaxMpxCount','<H'), ('VCNumber','<H'), ('SessionKey','<L'), ('AnsiPwdLength','<H'), ('UnicodePwdLength','<H'), ('_reserved','<L=0'), ('Capabilities','<L'), ) class SMBSessionSetupAndX_Data(AsciiOrUnicodeStructure): AsciiStructure = ( ('AnsiPwdLength','_-AnsiPwd'), ('UnicodePwdLength','_-UnicodePwd'), ('AnsiPwd',':=""'), ('UnicodePwd',':=""'), ('Account','z=""'), ('PrimaryDomain','z=""'), ('NativeOS','z=""'), ('NativeLanMan','z=""'), ) UnicodeStructure = ( ('AnsiPwdLength','_-AnsiPwd'), ('UnicodePwdLength','_-UnicodePwd'), ('AnsiPwd',':=""'), ('UnicodePwd',':=""'), ('Account','w=""'), ('PrimaryDomain','w=""'), ('NativeOS','w=""'), ('NativeLanMan','w=""'), ) class SMBSessionSetupAndXResponse_Parameters(SMBAndXCommand_Parameters): structure = ( ('Action','<H'), ) class SMBSessionSetupAndXResponse_Data(AsciiOrUnicodeStructure): AsciiStructure = ( ('NativeOS','z=""'), ('NativeLanMan','z=""'), ('PrimaryDomain','z=""'), ) UnicodeStructure = ( ('NativeOS','w=""'), ('NativeLanMan','w=""'), ('PrimaryDomain','w=""'), ) class SMBTreeConnect_Parameters(SMBCommand_Parameters): structure = ( ) class SMBTreeConnect_Data(SMBCommand_Parameters): structure = ( ('PathFormat','"\x04'), ('Path','z'), ('PasswordFormat','"\x04'), ('Password','z'), ('ServiceFormat','"\x04'), ('Service','z'), ) class SMBTreeConnectAndX_Parameters(SMBAndXCommand_Parameters): structure = ( ('Flags','<H=0'), ('PasswordLength','<H'), ) class SMBTreeConnectAndX_Data(SMBCommand_Parameters): structure = ( ('_PasswordLength','_-Password'), ('Password',':'), ('Path','z'), ('Service','z'), ) class SMBNtCreateAndX_Parameters(SMBAndXCommand_Parameters): structure = ( ('_reserved', 'B=0'), ('FileNameLength','<H'), ('CreateFlags','<L'), ('RootFid','<L=0'), ('AccessMask','<L'), ('AllocationSizeLo','<L=0'), ('AllocationSizeHi','<L=0'), ('FileAttributes','<L=0'), ('ShareAccess','<L=3'), ('Disposition','<L=1'), ('CreateOptions','<L'), ('Impersonation','<L=2'), ('SecurityFlags','B=3'), ) class SMBNtCreateAndXResponse_Parameters(SMBAndXCommand_Parameters): # XXX Is there a memory leak in the response for NTCreate (where the Data section would be) in Win 2000, Win XP, and Win 2003? structure = ( ('OplockLevel', 'B=0'), ('Fid','<H'), ('CreateAction','<L'), ('CraetionTimeLo','<L=0'), ('CraetionTimeHi','<L=0'), ('AccessTimeLo','<L=0'), ('AccessTimeHi','<L=0'), ('LastWriteTimeLo','<L=0'), ('LastWriteTimeHi','<L=0'), ('ChangeTimeLo','<L=0'), ('ChangeTimeHi','<L=0'), ('FileAttributes','<L=0x80'), ('AllocationSizeLo','<L=0'), ('AllocationSizeHi','<L=0'), ('EndOfFileLo','<L=0'), ('EndOfFileHi','<L=0'), ('FileType','<H=0'), ('IPCState','<H=0'), ('IsDirectory','B'), ) class SMBNtCreateAndX_Data(Structure): structure = ( ('FileName','z'), ) class SMBOpenAndX_Parameters(SMBAndXCommand_Parameters): structure = ( ('Flags','<H=0'), ('DesiredAccess','<H=0'), ('SearchAttributes','<H=0'), ('FileAttributes','<H=0'), ('CreationTime','<L=0'), ('OpenMode','<H=1'), # SMB_O_OPEN = 1 ('AllocationSize','<L=0'), ('Reserved','8s=""'), ) class SMBOpenAndX_Data(SMBNtCreateAndX_Data): pass class SMBOpenAndXResponse_Parameters(SMBAndXCommand_Parameters): structure = ( ('Fid','<H=0'), ('FileAttributes','<H=0'), ('LastWriten','<L=0'), ('FileSize','<L=0'), ('GrantedAccess','<H=0'), ('FileType','<H=0'), ('IPCState','<H=0'), ('Action','<H=0'), ('ServerFid','<L=0'), ('_reserved','<H=0'), ) class SMBWrite_Parameters(SMBCommand_Parameters): structure = ( ('Fid','<H'), ('Count','<H'), ('Offset','<L'), ('Remaining','<H'), ) class SMBWrite_Data(Structure): structure = ( ('BufferFormat','<B=1'), ('DataLength','<H-Data'), ('Data',':'), ) class SMBWriteAndX_Parameters(SMBAndXCommand_Parameters): structure = ( ('Fid','<H'), ('Offset','<L'), ('_reserved','<L=0xff'), ('WriteMode','<H=8'), ('Remaining','<H'), ('DataLength_Hi','<H=0'), ('DataLength','<H'), ('DataOffset','<H=0'), ('HighOffset','<L=0'), ) class SMBWriteRaw_Parameters(SMBCommand_Parameters): structure = ( ('Fid','<H'), ('Count','<H'), ('_reserved','<H=0'), ('Offset','<L'), ('Timeout','<L=0'), ('WriteMode','<H=0'), ('_reserved2','<L=0'), ('DataLength','<H'), ('DataOffset','<H=0'), ) class SMBRead_Parameters(SMBCommand_Parameters): structure = ( ('Fid','<H'), ('Count','<H'), ('Offset','<L'), ('Remaining','<H=Count'), ) class SMBReadResponse_Parameters(Structure): structure = ( ('Count','<H=0'), ('_reserved','"\0\0\0\0\0\0\0\0'), ) class SMBReadResponse_Data(Structure): structure = ( ('BufferFormat','<B'), ('DataLength','<H-Data'), ('Data',':'), ) class SMBReadRaw_Parameters(SMBCommand_Parameters): structure = ( ('Fid','<H'), ('Offset','<L'), ('MaxCount','<H'), ('MinCount','<H=MaxCount'), ('Timeout','<L=0'), ('_reserved','<H=0'), ) class SMBReadAndX_Parameters(SMBAndXCommand_Parameters): structure = ( ('Fid','<H'), ('Offset','<L'), ('MaxCount','<H'), ('MinCount','<H=MaxCount'), ('_reserved','<L=0xffffffff'), ('Remaining','<H=MaxCount'), ('HighOffset','<L=0'), ) class SMBReadAndXResponse_Parameters(SMBAndXCommand_Parameters): structure = ( ('Remaining','<H=0'), ('DataMode','<H=0'), ('_reserved','<H=0'), ('DataCount','<H'), ('DataOffset','<H'), ('DataCount_Hi','<L'), ('_reserved2','"\0\0\0\0\0\0'), ) class SMBOpen_Parameters(SMBCommand_Parameters): structure = ( ('DesiredAccess','<H=0'), ('SearchAttributes','<H=0'), ) class SMBOpen_Data(Structure): structure = ( ('FileNameFormat','"\x04'), ('FileName','z'), ) class SMBOpenResponse_Parameters(SMBCommand_Parameters): structure = ( ('Fid','<H=0'), ('FileAttributes','<H=0'), ('LastWriten','<L=0'), ('FileSize','<L=0'), ('GrantedAccess','<H=0'), ) class NTLMDialect(SMBPacket): def __init__(self,data=''): SMBPacket.__init__(self,data) self._selected_dialect = 0 self._security_mode = 0 self._max_mpx = 0 self._max_vc = 0 self._max_buffer = 0 self._max_raw = 0 self._session_key = 0 self._lsw_capabilities = 0 self._msw_capabilities = 0 self._utc_high = 0 self._utc_low = 0 self._minutes_utc = 0 self._encryption_key_len = 0 self._encryption_key = '' self._server_domain = '' self._server_name = '' if data: self._selected_dialect, self._security_mode, self._max_mpx, self._max_vc = unpack('<HBHH',self.get_parameter_words()[:7]) self._max_buffer,self._max_raw, self._session_key, self._lsw_capabilities, self._msw_capabilities = unpack('<lllHH', self.get_parameter_words()[7:16+7]) self._utc_low, self._utc_high,self._minutes_utc, self._encryption_key_len = unpack('<LLhB',self.get_parameter_words()[23:34]) if self._encryption_key_len > 0 and len(self.get_buffer()) >= self._encryption_key_len: self._encryption_key = self.get_buffer()[:self._encryption_key_len] buf = self.get_buffer() # Look for the server domain offset self._server_name = '<Unknown>' self._server_domain = '<Unknown>' try: if self._lsw_capabilities & 0x3: # is this unicode? offset = self._encryption_key_len if offset & 0x01: offset += 1 end = offset while ord(buf[end]) or ord(buf[end+1]): end += 2 self._server_domain = unicode(buf[offset:end],'utf_16_le') end += 2 offset = end while ord(buf[end]) or ord(buf[end+1]): end += 2 self._server_name = unicode(buf[offset:end],'utf_16_le') else: offset = self._encryption_key_len idx1 = string.find(buf,'\0',offset) if idx1 != -1: self._server_domain = buf[offset:idx1] idx2 = string.find(buf, '\0', idx1 + 1) if idx2 != -1: self._server_name = buf[idx1+1:idx2] except: pass else: self._encryption_key = '' def get_selected_dialect(self): return self._selected_dialect def get_security_mode(self): return self._security_mode def get_max_mpx(self): return self._max_mpx def get_max_vc(self): return self._max_vc def get_max_buffer(self): return self._max_buffer def get_max_raw(self): return self._max_raw def get_session_key(self): return self._session_key def get_lsw_capabilities(self): return self._lsw_capabilities def get_msw_capabilities(self): return self._msw_capabilities def get_utc(self): return self._utc_high, self._utc_low def get_minutes_utc(self): return self._minutes_utc def get_encryption_key_len(self): return self._encryption_key_len def get_encryption_key(self): return self._encryption_key def get_server_domain(self): return self._server_domain def get_server_name(self): return self._server_name def is_auth_mode(self): return self._security_mode & SMB.SECURITY_AUTH_MASK def is_share_mode(self): return self._security_mode & SMB.SECURITY_SHARE_MASK def is_rawmode(self): return self._lsw_capabilities & SMB.CAP_RAW_MODE class SMB: # SMB Command Codes SMB_COM_CREATE_DIRECTORY = 0x00 SMB_COM_DELETE_DIRECTORY = 0x01 SMB_COM_OPEN = 0x02 SMB_COM_CREATE = 0x03 SMB_COM_CLOSE = 0x04 SMB_COM_FLUSH = 0x05 SMB_COM_DELETE = 0x06 SMB_COM_RENAME = 0x07 SMB_COM_QUERY_INFORMATION = 0x08 SMB_COM_SET_INFORMATION = 0x09 SMB_COM_READ = 0x0A SMB_COM_WRITE = 0x0B SMB_COM_LOCK_BYTE_RANGE = 0x0C SMB_COM_UNLOCK_BYTE_RANGE = 0x0D SMB_COM_CREATE_TEMPORARY = 0x0E SMB_COM_CREATE_NEW = 0x0F SMB_COM_CHECK_DIRECTORY = 0x10 SMB_COM_PROCESS_EXIT = 0x11 SMB_COM_SEEK = 0x12 SMB_COM_LOCK_AND_READ = 0x13 SMB_COM_WRITE_AND_UNLOCK = 0x14 SMB_COM_READ_RAW = 0x1A SMB_COM_READ_MPX = 0x1B SMB_COM_READ_MPX_SECONDARY = 0x1C SMB_COM_WRITE_RAW = 0x1D SMB_COM_WRITE_MPX = 0x1E SMB_COM_WRITE_MPX_SECONDARY = 0x1F SMB_COM_WRITE_COMPLETE = 0x20 SMB_COM_QUERY_SERVER = 0x21 SMB_COM_SET_INFORMATION2 = 0x22 SMB_COM_QUERY_INFORMATION2 = 0x23 SMB_COM_LOCKING_ANDX = 0x24 SMB_COM_TRANSACTION = 0x25 SMB_COM_TRANSACTION_SECONDARY = 0x26 SMB_COM_IOCTL = 0x27 SMB_COM_IOCTL_SECONDARY = 0x28 SMB_COM_COPY = 0x29 SMB_COM_MOVE = 0x2A SMB_COM_ECHO = 0x2B SMB_COM_WRITE_AND_CLOSE = 0x2C SMB_COM_OPEN_ANDX = 0x2D SMB_COM_READ_ANDX = 0x2E SMB_COM_WRITE_ANDX = 0x2F SMB_COM_NEW_FILE_SIZE = 0x30 SMB_COM_CLOSE_AND_TREE_DISC = 0x31 SMB_COM_TRANSACTION2 = 0x32 SMB_COM_TRANSACTION2_SECONDARY = 0x33 SMB_COM_FIND_CLOSE2 = 0x34 SMB_COM_FIND_NOTIFY_CLOSE = 0x35 # Used by Xenix/Unix 0x60 - 0x6E SMB_COM_TREE_CONNECT = 0x70 SMB_COM_TREE_DISCONNECT = 0x71 SMB_COM_NEGOTIATE = 0x72 SMB_COM_SESSION_SETUP_ANDX = 0x73 SMB_COM_LOGOFF_ANDX = 0x74 SMB_COM_TREE_CONNECT_ANDX = 0x75 SMB_COM_QUERY_INFORMATION_DISK = 0x80 SMB_COM_SEARCH = 0x81 SMB_COM_FIND = 0x82 SMB_COM_FIND_UNIQUE = 0x83 SMB_COM_FIND_CLOSE = 0x84 SMB_COM_NT_TRANSACT = 0xA0 SMB_COM_NT_TRANSACT_SECONDARY = 0xA1 SMB_COM_NT_CREATE_ANDX = 0xA2 SMB_COM_NT_CANCEL = 0xA4 SMB_COM_NT_RENAME = 0xA5 SMB_COM_OPEN_PRINT_FILE = 0xC0 SMB_COM_WRITE_PRINT_FILE = 0xC1 SMB_COM_CLOSE_PRINT_FILE = 0xC2 SMB_COM_GET_PRINT_QUEUE = 0xC3 SMB_COM_READ_BULK = 0xD8 SMB_COM_WRITE_BULK = 0xD9 SMB_COM_WRITE_BULK_DATA = 0xDA # Security Share Mode (Used internally by SMB class) SECURITY_SHARE_MASK = 0x01 SECURITY_SHARE_SHARE = 0x00 SECURITY_SHARE_USER = 0x01 # Security Auth Mode (Used internally by SMB class) SECURITY_AUTH_MASK = 0x02 SECURITY_AUTH_ENCRYPTED = 0x02 SECURITY_AUTH_PLAINTEXT = 0x00 # Raw Mode Mask (Used internally by SMB class. Good for dialect up to and including LANMAN2.1) RAW_READ_MASK = 0x01 RAW_WRITE_MASK = 0x02 # Capabilities Mask (Used internally by SMB class. Good for dialect NT LM 0.12) CAP_RAW_MODE = 0x0001 CAP_MPX_MODE = 0x0002 CAP_UNICODE = 0x0004 CAP_LARGE_FILES = 0x0008 CAP_EXTENDED_SECURITY = 0x80000000 # Flags1 Mask FLAGS1_PATHCASELESS = 0x08 # Flags2 Mask FLAGS2_LONG_FILENAME = 0x0001 FLAGS2_USE_NT_ERRORS = 0x4000 FLAGS2_UNICODE = 0x8000 def __init__(self, remote_name, remote_host, my_name = None, host_type = nmb.TYPE_SERVER, sess_port = nmb.NETBIOS_SESSION_PORT, timeout=None): # The uid attribute will be set when the client calls the login() method self.__uid = 0 self.__server_os = '' self.__server_lanman = '' self.__server_domain = '' self.__remote_name = string.upper(remote_name) self.__is_pathcaseless = 0 self.__ntlm_dialect = 0 self.__sess = None if timeout==None: self.__timeout = 30 else: self.__timeout = timeout if not my_name: my_name = socket.gethostname() i = string.find(my_name, '.') if i > -1: my_name = my_name[:i] try: self.__sess = nmb.NetBIOSSession(my_name, remote_name, remote_host, host_type, sess_port, timeout) except socket.error, ex: raise ex # Initialize values __ntlm_dialect, __is_pathcaseless self.__neg_session() # If the following assertion fails, then mean that the encryption key is not sent when # encrypted authentication is required by the server. assert (self.__ntlm_dialect.is_auth_mode() == SMB.SECURITY_AUTH_PLAINTEXT) or (self.__ntlm_dialect.is_auth_mode() == SMB.SECURITY_AUTH_ENCRYPTED and self.__ntlm_dialect.get_encryption_key() and self.__ntlm_dialect.get_encryption_key_len() >= 8) # Call login() without any authentication information to setup a session if the remote server # is in share mode. if self.__ntlm_dialect.is_share_mode() == SMB.SECURITY_SHARE_SHARE: self.login('', '') def set_timeout(self, timeout): self.__timeout = timeout def __del__(self): if self.__sess: self.__sess.close() def __decode_smb(self, data): _, cmd, err_class, _, err_code, flags1, flags2, _, tid, pid, uid, mid, wcount = unpack('<4sBBBHBH12sHHHHB', data[:33]) param_end = 33 + wcount * 2 return cmd, err_class, err_code, flags1, flags2, tid, uid, mid, data[33:param_end], data[param_end + 2:] def recvSMB(self): r = self.__sess.recv_packet(self.__timeout) return NewSMBPacket(data = r.get_trailer()) def recv_packet(self): r = self.__sess.recv_packet(self.__timeout) return SMBPacket(r.get_trailer()) def __decode_trans(self, params, data): totparamcnt, totdatacnt, _, paramcnt, paramoffset, paramds, datacnt, dataoffset, datads, setupcnt = unpack('<HHHHHHHHHB', params[:19]) if paramcnt + paramds < totparamcnt or datacnt + datads < totdatacnt: has_more = 1 else: has_more = 0 paramoffset = paramoffset - 55 - setupcnt * 2 dataoffset = dataoffset - 55 - setupcnt * 2 return has_more, params[20:20 + setupcnt * 2], data[paramoffset:paramoffset + paramcnt], data[dataoffset:dataoffset + datacnt] def sendSMB(self,smb): smb['Uid'] = self.__uid smb['Pid'] = os.getpid() self.__sess.send_packet(str(smb)) def send_smb(self,s): s.set_uid(self.__uid) s.set_pid(os.getpid()) self.__sess.send_packet(s.rawData()) def __send_smb_packet(self, cmd, flags, flags2, tid, mid, params = '', data = ''): smb = NewSMBPacket() smb['Flags'] = flags smb['Flags2'] = flags2 smb['Tid'] = tid smb['Mid'] = mid cmd = SMBCommand(cmd) smb.addCommand(cmd) cmd['Parameters'] = params cmd['Data'] = data self.sendSMB(smb) def isValidAnswer(self, s, cmd): while 1: if s.rawData(): if s.get_command() == cmd: if s.get_error_class() == 0x00 and s.get_error_code() == 0x00: return 1 else: raise SessionError, ( "SMB Library Error", s.get_error_class(), s.get_error_code()) else: break # raise SessionError("Invalid command received. %x" % cmd) # s=self.recv_packet(None) return 0 def __neg_session(self): s = SMBPacket() s.set_command(SMB.SMB_COM_NEGOTIATE) s.set_buffer('\x02NT LM 0.12\x00') self.send_smb(s) while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_NEGOTIATE): self.__ntlm_dialect = NTLMDialect(s.rawData()) if self.__ntlm_dialect.get_selected_dialect() == 0xffff: raise UnsupportedFeature,"Remote server does not know NT LM 0.12" #NL LM 0.12 dialect selected if self.__ntlm_dialect.get_lsw_capabilities() & SMB.CAP_EXTENDED_SECURITY: raise UnsupportedFeature, "This version of pysmb does not support extended security validation. Please file a request for it." self.__is_pathcaseless = s.get_flags() & SMB.FLAGS1_PATHCASELESS return 1 else: return 0 def tree_connect(self, path, password = '', service = SERVICE_ANY): # return 0x800 if password: # Password is only encrypted if the server passed us an "encryption" during protocol dialect if self.__ntlm_dialect.get_encryption_key(): # this code is untested password = self.get_ntlmv1_response(ntlm.compute_lmhash(password)) if not unicode_support: if unicode_convert: path = str(path) else: raise Except('SMB: Can\t conver path from unicode!') smb = NewSMBPacket() smb['Flags1'] = 8 treeConnect = SMBCommand(SMB.SMB_COM_TREE_CONNECT) treeConnect['Parameters'] = SMBTreeConnect_Parameters() treeConnect['Data'] = SMBTreeConnect_Data() treeConnect['Data']['Path'] = path.upper() treeConnect['Data']['Password'] = password treeConnect['Data']['Service'] = service smb.addCommand(treeConnect) self.sendSMB(smb) while 1: smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_TREE_CONNECT): # XXX Here we are ignoring the rest of the response return smb['Tid'] return smb['Tid'] def tree_connect_andx(self, path, password = None, service = SERVICE_ANY): if password: # Password is only encrypted if the server passed us an "encryption" during protocol dialect if self.__ntlm_dialect.get_encryption_key(): # this code is untested password = self.get_ntlmv1_response(ntlm.compute_lmhash(password)) else: password = '\x00' if not unicode_support: if unicode_convert: path = str(path) else: raise Except('SMB: Can\t convert path from unicode!') smb = NewSMBPacket() smb['Flags1'] = 8 treeConnect = SMBCommand(SMB.SMB_COM_TREE_CONNECT_ANDX) treeConnect['Parameters'] = SMBTreeConnectAndX_Parameters() treeConnect['Data'] = SMBTreeConnectAndX_Data() treeConnect['Parameters']['PasswordLength'] = len(password) treeConnect['Data']['Password'] = password treeConnect['Data']['Path'] = path.upper() treeConnect['Data']['Service'] = service smb.addCommand(treeConnect) # filename = "\PIPE\epmapper" # ntCreate = SMBCommand(SMB.SMB_COM_NT_CREATE_ANDX) # ntCreate['Parameters'] = SMBNtCreateAndX_Parameters() # ntCreate['Data'] = SMBNtCreateAndX_Data() # ntCreate['Parameters']['FileNameLength'] = len(filename) # ntCreate['Parameters']['CreateFlags'] = 0 # ntCreate['Parameters']['AccessMask'] = 0x3 # ntCreate['Parameters']['CreateOptions'] = 0x0 # ntCreate['Data']['FileName'] = filename # smb.addCommand(ntCreate) self.sendSMB(smb) while 1: smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_TREE_CONNECT_ANDX): # XXX Here we are ignoring the rest of the response return smb['Tid'] return smb['Tid'] # backwars compatibility connect_tree = tree_connect_andx def get_server_name(self): return self.__ntlm_dialect.get_server_name() def get_session_key(self): return self.__ntlm_dialect.get_session_key() def get_server_time(self): high, low = self.__ntlm_dialect.get_utc() min = self.__ntlm_dialect.get_minutes_utc() return samr.display_time(high, low, min) def disconnect_tree(self, tid): smb = NewSMBPacket() smb['Tid'] = tid smb.addCommand(SMBCommand(SMB.SMB_COM_TREE_DISCONNECT)) self.sendSMB(smb) smb = self.recvSMB() def open(self, tid, filename, open_mode, desired_access): smb = NewSMBPacket() smb['Flags'] = 8 smb['Flags2'] = SMB.FLAGS2_LONG_FILENAME smb['Tid'] = tid openFile = SMBCommand(SMB.SMB_COM_OPEN) openFile['Parameters'] = SMBOpen_Parameters() openFile['Parameters']['DesiredAccess'] = desired_access openFile['Parameters']['OpenMode'] = open_mode openFile['Parameters']['SearchAttributes'] = ATTR_READONLY | ATTR_HIDDEN | ATTR_ARCHIVE openFile['Data'] = SMBOpen_Data() openFile['Data']['FileName'] = filename smb.addCommand(openFile) self.sendSMB(smb) smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_OPEN): # XXX Here we are ignoring the rest of the response openFileResponse = SMBCommand(smb['Data'][0]) openFileParameters = SMBOpenResponse_Parameters(openFileResponse['Parameters']) return ( openFileParameters['Fid'], openFileParameters['FileAttributes'], openFileParameters['LastWriten'], openFileParameters['FileSize'], openFileParameters['GrantedAccess'], ) def open_andx(self, tid, filename, open_mode, desired_access): smb = NewSMBPacket() smb['Flags'] = 8 smb['Flags2'] = SMB.FLAGS2_LONG_FILENAME smb['Tid'] = tid openFile = SMBCommand(SMB.SMB_COM_OPEN_ANDX) openFile['Parameters'] = SMBOpenAndX_Parameters() openFile['Parameters']['DesiredAccess'] = desired_access openFile['Parameters']['OpenMode'] = open_mode openFile['Parameters']['SearchAttributes'] = ATTR_READONLY | ATTR_HIDDEN | ATTR_ARCHIVE openFile['Data'] = SMBOpenAndX_Data() openFile['Data']['FileName'] = filename smb.addCommand(openFile) self.sendSMB(smb) smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_OPEN_ANDX): # XXX Here we are ignoring the rest of the response openFileResponse = SMBCommand(smb['Data'][0]) openFileParameters = SMBOpenAndXResponse_Parameters(openFileResponse['Parameters']) return ( openFileParameters['Fid'], openFileParameters['FileAttributes'], openFileParameters['LastWriten'], openFileParameters['FileSize'], openFileParameters['GrantedAccess'], openFileParameters['FileType'], openFileParameters['IPCState'], openFileParameters['Action'], openFileParameters['ServerFid'], ) def close(self, tid, fid): s = SMBPacket() s.set_command(SMB.SMB_COM_CLOSE) s.set_tid(tid) s.set_parameter_words(pack('<HL', fid, 0)) self.send_smb(s) s = self.recv_packet() def send_trans(self, tid, setup, name, param, data, noAnswer = 0): t = TRANSHeader() s = SMBPacket() s.set_tid(tid) s.set_command(SMB.SMB_COM_TRANSACTION) s.set_flags(self.__is_pathcaseless) s.set_flags2(SMB.FLAGS2_LONG_FILENAME) t.set_setup(setup) t.set_name(name) t.set_parameters(param) t.set_data(data) t.set_max_param_count(1024) # Saca esto y se muere remotamente t.set_max_data_count(65504) # Saca esto y se muere remotamente if noAnswer: t.set_flags(TRANS_NO_RESPONSE) s.set_parameter_words(t.get_rawParameters()) s.set_buffer(t.rawData()) self.send_smb(s) def __trans(self, tid, setup, name, param, data): data_len = len(data) name_len = len(name) param_len = len(param) setup_len = len(setup) assert setup_len & 0x01 == 0 param_offset = name_len + setup_len + 63 data_offset = param_offset + param_len self.__send_smb_packet(SMB.SMB_COM_TRANSACTION, self.__is_pathcaseless, SMB.FLAGS2_LONG_FILENAME, tid, 0, pack('<HHHHBBHLHHHHHBB', param_len, data_len, 1024, 65504, 0, 0, 0, 0, 0, param_len, param_offset, data_len, data_offset, setup_len / 2, 0) + setup, name + param + data) def trans2(self, tid, setup, name, param, data): data_len = len(data) name_len = len(name) param_len = len(param) setup_len = len(setup) assert setup_len & 0x01 == 0 param_offset = name_len + setup_len + 63 data_offset = param_offset + param_len self.__send_smb_packet(SMB.SMB_COM_TRANSACTION2, self.__is_pathcaseless, SMB.FLAGS2_LONG_FILENAME, tid, 0, pack('<HHHHBBHLHHHHHBB', param_len, data_len, 1024, self.__ntlm_dialect.get_max_buffer(), 0, 0, 0, 0, 0, param_len, param_offset, data_len, data_offset, setup_len / 2, 0) + setup, name + param + data) def query_file_info(self, tid, fid): self.trans2(tid, '\x07\x00', '\x00', pack('<HH', fid, 0x107), '') while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_TRANSACTION2): f1, f2 = unpack('<LL', s.get_buffer()[53:53+8]) return (f2 & 0xffffffffL) << 32 | f1 def __nonraw_retr_file(self, tid, fid, offset, datasize, callback): max_buf_size = self.__ntlm_dialect.get_max_buffer() & ~0x3ff # Read in multiple KB blocks read_offset = offset while read_offset < datasize: data = self.read_andx(tid, fid, read_offset, max_buf_size) callback(data) read_offset += len(data) def __raw_retr_file(self, tid, fid, offset, datasize, callback): max_buf_size = self.__ntlm_dialect.get_max_buffer() & ~0x3ff # Write in multiple KB blocks read_offset = offset while read_offset < datasize: data = self.read_raw(tid, fid, read_offset, 0xffff) if not data: # No data returned. Need to send SMB_COM_READ_ANDX to find out what is the error. data = self.read_andx(tid, fid, read_offset, max_buf_size) callback(data) read_offset += len(data) def __nonraw_stor_file(self, tid, fid, offset, datasize, callback): max_buf_size = self.__ntlm_dialect.get_max_buffer() & ~0x3ff # Write in multiple KB blocks write_offset = offset while 1: data = callback(max_buf_size) if not data: break self.__send_smb_packet(SMB.SMB_COM_WRITE_ANDX, 0, 0, tid, 0, pack('<BBHHLLHHHHH', 0xff, 0, 0, fid, write_offset, 0, 0, 0, 0, len(data), 59), data) while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_WRITE_ANDX): offset = unpack('<H', s.get_parameter_words()[2:4])[0] write_offset = write_offset + unpack('<H', s.get_parameter_words()[4:6])[0] break def __raw_stor_file(self, tid, fid, offset, datasize, callback): write_offset = offset while 1: read_data = callback(65535) if not read_data: break read_len = len(read_data) self.__send_smb_packet(SMB.SMB_COM_WRITE_RAW, 0, 0, tid, 0, pack('<HHHLLHLHH', fid, read_len, 0, write_offset, 0, 0, 0, 0, 59), '') while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_WRITE_RAW): self.__sess.send_packet(read_data) write_offset = write_offset + read_len break # We need to close fid to check whether the last raw packet is written successfully self.__send_smb_packet(SMB.SMB_COM_CLOSE, 0, 0, tid, 0, pack('<HL', fid, 0), '') while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_CLOSE): if s.get_error_class() == 0x00 and s.get_error_code() == 0x00: return def __browse_servers(self, server_flags, container_type, domain): tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\IPC$') buf = StringIO() try: if server_flags & 0x80000000: self.__trans(tid, '', '\\PIPE\\LANMAN\x00', '\x68\x00WrLehDz\x00' + 'B16BBDz\x00\x01\x00\xff\xff\x00\x00\x00\x80', '') else: self.__trans(tid, '', '\\PIPE\\LANMAN\x00', '\x68\x00WrLehDz\x00' + 'B16BBDz\x00\x01\x00\xff\xff' + pack('<l', server_flags) + domain + '\x00', '') servers = [ ] entry_count = 0 while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_TRANSACTION): has_more, _, transparam, transdata = self.__decode_trans(s.get_parameter_words(), s.get_buffer()) if not entry_count: status, convert, entry_count, avail_entry = unpack('<HHHH', transparam[:8]) if status and status != 234: # status 234 means have more data raise SessionError, ( 'Browse domains failed. (ErrClass: %d and ErrCode: %d)' % ( 0x80, status ), 0x80, status ) buf.write(transdata) if not has_more: server_data = buf.getvalue() for i in range(0, entry_count): server, _, server_type, comment_offset = unpack('<16s2sll', server_data[i * 26:i * 26 + 26]) idx = string.find(server, '\0') idx2 = string.find(server_data, '\0', comment_offset) if idx < 0: server = server[:idx] servers.append(container_type(server, server_type, server_data[comment_offset:idx2])) return servers finally: buf.close() self.disconnect_tree(tid) def get_server_domain(self): return self.__server_domain def get_server_os(self): return self.__server_os def get_server_lanman(self): return self.__server_lanman def is_login_required(self): # Login is required if share mode is user. Otherwise only public services or services in share mode # are allowed. return self.__ntlm_dialect.is_share_mode() == SMB.SECURITY_SHARE_USER def get_ntlmv1_response(self, key): challenge = self.__ntlm_dialect.get_encryption_key() return ntlm.get_ntlmv1_response(key, challenge) def hmac_md5(self, key, data): import POW h = POW.Hmac(POW.MD5_DIGEST, key) h.update(data) result = h.mac() return result def get_ntlmv2_response(self, hash): """ blob = RandomBytes( blobsize ); data = concat( ServerChallenge, 8, blob, blobsize ); hmac = hmac_md5( v2hash, 16, data, (8 + blobsize) ); v2resp = concat( hmac, 16, blob, blobsize ); """ return '' def login(self, user, password, domain = '', lmhash = '', nthash = ''): if password != '' or (password == '' and lmhash == '' and nthash == ''): self.login_plaintext_password(user, password) elif lmhash != '' or nthash != '': self.login_pass_the_hash(user, lmhash, nthash, domain) def _login(self, user, pwd_ansi, pwd_unicode, domain = ''): smb = NewSMBPacket() smb['Flags1'] = 8 sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX) sessionSetup['Parameters'] = SMBSessionSetupAndX_Parameters() sessionSetup['Data'] = SMBSessionSetupAndX_Data() sessionSetup['Parameters']['MaxBuffer'] = 65535 sessionSetup['Parameters']['MaxMpxCount'] = 2 sessionSetup['Parameters']['VCNumber'] = os.getpid() sessionSetup['Parameters']['SessionKey'] = self.__ntlm_dialect.get_session_key() sessionSetup['Parameters']['AnsiPwdLength'] = len(pwd_ansi) sessionSetup['Parameters']['UnicodePwdLength'] = len(pwd_unicode) sessionSetup['Parameters']['Capabilities'] = SMB.CAP_RAW_MODE sessionSetup['Data']['AnsiPwd'] = pwd_ansi sessionSetup['Data']['UnicodePwd'] = pwd_unicode sessionSetup['Data']['Account'] = str(user) sessionSetup['Data']['PrimaryDomain'] = str(domain) sessionSetup['Data']['NativeOS'] = str(os.name) sessionSetup['Data']['NativeLanMan'] = 'pysmb' smb.addCommand(sessionSetup) self.sendSMB(smb) smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX): # We will need to use this uid field for all future requests/responses self.__uid = smb['Uid'] sessionResponse = SMBCommand(smb['Data'][0]) sessionParameters = SMBSessionSetupAndXResponse_Parameters(sessionResponse['Parameters']) sessionData = SMBSessionSetupAndXResponse_Data(flags = smb['Flags2'], data = sessionResponse['Data']) self.__server_os = sessionData['NativeOS'] self.__server_lanman = sessionData['NativeLanMan'] self.__server_domain = sessionData['PrimaryDomain'] return 1 else: raise Exception('Error: Could not login successfully') def read(self, tid, fid, offset=0, max_size = None, wait_answer=1): if not max_size: max_size = self.__ntlm_dialect.get_max_buffer() # Read in multiple KB blocks # max_size is not working, because although it would, the server returns an error (More data avail) smb = NewSMBPacket() smb['Flags1'] = 0x18 smb['Flags2'] = 0 smb['Tid'] = tid read = SMBCommand(SMB.SMB_COM_READ) read['Parameters'] = SMBRead_Parameters() read['Parameters']['Fid'] = fid read['Parameters']['Offset'] = offset read['Parameters']['Count'] = max_size smb.addCommand(read) if wait_answer: answer = '' while 1: self.sendSMB(smb) ans = self.recvSMB() if ans.isValidAnswer(SMB.SMB_COM_READ): readResponse = SMBCommand(ans['Data'][0]) readParameters = SMBReadResponse_Parameters(readResponse['Parameters']) readData = SMBReadResponse_Data(readResponse['Data']) return readData['Data'] return None def read_andx(self, tid, fid, offset=0, max_size = None, wait_answer=1): if not max_size: max_size = self.__ntlm_dialect.get_max_buffer() # Read in multiple KB blocks # max_size is not working, because although it would, the server returns an error (More data avail) smb = NewSMBPacket() smb['Flags1'] = 0x18 smb['Flags2'] = 0 smb['Tid'] = tid readAndX = SMBCommand(SMB.SMB_COM_READ_ANDX) readAndX['Parameters'] = SMBReadAndX_Parameters() readAndX['Parameters']['Fid'] = fid readAndX['Parameters']['Offset'] = offset readAndX['Parameters']['MaxCount'] = max_size smb.addCommand(readAndX) if wait_answer: answer = '' while 1: self.sendSMB(smb) ans = self.recvSMB() if ans.isValidAnswer(SMB.SMB_COM_READ_ANDX): # XXX Here we are only using a few fields from the response readAndXResponse = SMBCommand(ans['Data'][0]) readAndXParameters = SMBReadAndXResponse_Parameters(readAndXResponse['Parameters']) offset = readAndXParameters['DataOffset'] count = readAndXParameters['DataCount']+0x10000*readAndXParameters['DataCount_Hi'] answer += str(ans)[offset:offset+count] if not ans.isMoreData(): return answer max_size = min(max_size, readAndXParameters['Remaining']) readAndX['Parameters']['Offset'] += count # XXX Offset is not important (apparently) return None def read_raw(self, tid, fid, offset=0, max_size = None, wait_answer=1): if not max_size: max_size = self.__ntlm_dialect.get_max_buffer() # Read in multiple KB blocks # max_size is not working, because although it would, the server returns an error (More data avail) smb = NewSMBPacket() smb['Flags1'] = 0x18 smb['Flags2'] = 0 smb['Tid'] = tid readRaw = SMBCommand(SMB.SMB_COM_READ_RAW) readRaw['Parameters'] = SMBReadRaw_Parameters() readRaw['Parameters']['Fid'] = fid readRaw['Parameters']['Offset'] = offset readRaw['Parameters']['MaxCount'] = max_size smb.addCommand(readRaw) self.sendSMB(smb) if wait_answer: data = self.__sess.recv_packet(self.__timeout).get_trailer() if not data: # If there is no data it means there was an error data = self.read_andx(tid, fid, offset, max_size) return data return None def write(self,tid,fid,data, offset = 0, wait_answer=1): smb = NewSMBPacket() smb['Flags1'] = 0x18 smb['Flags2'] = 0 smb['Tid'] = tid write = SMBCommand(SMB.SMB_COM_WRITE) smb.addCommand(write) write['Parameters'] = SMBWrite_Parameters() write['Data'] = SMBWrite_Data() write['Parameters']['Fid'] = fid write['Parameters']['Count'] = len(data) write['Parameters']['Offset'] = offset write['Parameters']['Remaining'] = len(data) write['Data']['Data'] = data self.sendSMB(smb) if wait_answer: smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_WRITE): return smb return None def write_andx(self,tid,fid,data, offset = 0, wait_answer=1): smb = NewSMBPacket() smb['Flags1'] = 0x18 smb['Flags2'] = 0 smb['Tid'] = tid writeAndX = SMBCommand(SMB.SMB_COM_WRITE_ANDX) smb.addCommand(writeAndX) writeAndX['Parameters'] = SMBWriteAndX_Parameters() writeAndX['Parameters']['Fid'] = fid writeAndX['Parameters']['Offset'] = offset writeAndX['Parameters']['WriteMode'] = 8 writeAndX['Parameters']['Remaining'] = len(data) writeAndX['Parameters']['DataLength'] = len(data) writeAndX['Parameters']['DataOffset'] = len(smb) # this length already includes the parameter writeAndX['Data'] = data self.sendSMB(smb) if wait_answer: smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_WRITE_ANDX): return smb return None def write_raw(self,tid,fid,data, offset = 0, wait_answer=1): smb = NewSMBPacket() smb['Flags1'] = 0x18 smb['Flags2'] = 0 smb['Tid'] = tid writeRaw = SMBCommand(SMB.SMB_COM_WRITE_RAW) smb.addCommand(writeRaw) writeRaw['Parameters'] = SMBWriteRaw_Parameters() writeRaw['Parameters']['Fid'] = fid writeRaw['Parameters']['Offset'] = offset writeRaw['Parameters']['Count'] = len(data) writeRaw['Parameters']['DataLength'] = 0 writeRaw['Parameters']['DataOffset'] = 0 self.sendSMB(smb) self.__sess.send_packet(data) if wait_answer: smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_WRITE_RAW): return smb return None def TransactNamedPipe(self, tid, fid, data = '', noAnswer = 0, waitAnswer = 1, offset = 0): self.send_trans(tid,pack('<HH', 0x26, fid),'\\PIPE\\\x00','',data, noAnswer = noAnswer) if noAnswer or not waitAnswer: return s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_TRANSACTION): trans = TRANSHeader(s.get_parameter_words(), s.get_buffer()) return trans.get_data() return None def nt_create_andx(self,tid,filename): smb = NewSMBPacket() smb['Flags1'] = 0x18 smb['Flags2'] = SMB.FLAGS2_LONG_FILENAME smb['Tid'] = tid ntCreate = SMBCommand(SMB.SMB_COM_NT_CREATE_ANDX) ntCreate['Parameters'] = SMBNtCreateAndX_Parameters() ntCreate['Data'] = SMBNtCreateAndX_Data() ntCreate['Parameters']['FileNameLength'] = len(filename) ntCreate['Parameters']['CreateFlags'] = 0x16 ntCreate['Parameters']['AccessMask'] = 0x2019f ntCreate['Parameters']['CreateOptions'] = 0x40 ntCreate['Data']['FileName'] = filename smb.addCommand(ntCreate) self.sendSMB(smb) while 1: smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_NT_CREATE_ANDX): # XXX Here we are ignoring the rest of the response ntCreateResponse = SMBCommand(smb['Data'][0]) ntCreateParameters = SMBNtCreateAndXResponse_Parameters(ntCreateResponse['Parameters']) return ntCreateParameters['Fid'] def login_pass_the_hash(self, user, lmhash, nthash, domain = ''): if len(lmhash) % 2: lmhash = '0%s' % lmhash if len(nthash) % 2: nthash = '0%s' % nthash if lmhash: lmhash = self.get_ntlmv1_response(a2b_hex(lmhash)) if nthash: nthash = self.get_ntlmv1_response(a2b_hex(nthash)) self._login(user, lmhash, nthash, domain) def login_plaintext_password(self, name, password, domain = ''): # Password is only encrypted if the server passed us an "encryption key" during protocol dialect negotiation if password and self.__ntlm_dialect.get_encryption_key(): lmhash = ntlm.compute_lmhash(password) nthash = ntlm.compute_nthash(password) lmhash = self.get_ntlmv1_response(lmhash) nthash = self.get_ntlmv1_response(nthash) else: lmhash = password nthash = '' self._login(name, lmhash, nthash, domain) def logoff(self): s = SMBPacket() s.set_command(SMB.SMB_COM_LOGOFF_ANDX) s.set_parameter_words('\xff\x00\x00\x00') self.send_smb(s) s = self.recv_packet() def list_shared(self): tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\IPC$') buf = StringIO() try: self.send_trans(tid, '', '\\PIPE\\LANMAN\0', '\x00\x00WrLeh\0B13BWz\0\x01\x00\xe0\xff', '') numentries = 0 share_list = [ ] while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_TRANSACTION): has_more, _, transparam, transdata = self.__decode_trans(s.get_parameter_words(), s.get_buffer()) if not numentries: status, data_offset, numentries = unpack('<HHH', transparam[:6]) buf.write(transdata) if not has_more: share_data = buf.getvalue() offset = 0 for i in range(0, numentries): name = share_data[offset:string.find(share_data, '\0', offset)] type, commentoffset = unpack('<HH', share_data[offset + 14:offset + 18]) comment = share_data[commentoffset-data_offset:share_data.find('\0', commentoffset-data_offset)] offset = offset + 20 share_list.append(SharedDevice(name, type, comment)) return share_list finally: buf.close() self.disconnect_tree(tid) def list_path(self, service, path = '*', password = None): path = string.replace(path, '/', '\\') tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: self.trans2(tid, '\x01\x00', '\x00', '\x16\x00\x00\x02\x06\x00\x04\x01\x00\x00\x00\x00' + path + '\x00', '') while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_TRANSACTION2): has_more, _, transparam, transdata = self.__decode_trans(s.get_parameter_words(), s.get_buffer()) sid, searchcnt, eos, erroffset, lastnameoffset = unpack('<HHHHH', transparam) files = [ ] offset = 0 data_len = len(transdata) while offset < data_len: nextentry, fileindex, lowct, highct, lowat, highat, lowmt, highmt, lowcht, hightcht, loweof, higheof, lowsz, highsz, attrib, longnamelen, easz, shortnamelen = unpack('<lL12LLlLB', transdata[offset:offset + 69]) files.append(SharedFile(highct << 32 | lowct, highat << 32 | lowat, highmt << 32 | lowmt, higheof << 32 | loweof, highsz << 32 | lowsz, attrib, transdata[offset + 70:offset + 70 + shortnamelen], transdata[offset + 94:offset + 94 + longnamelen])) offset = offset + nextentry if not nextentry: break return files finally: self.disconnect_tree(tid) def retr_file(self, service, filename, callback, mode = SMB_O_OPEN, offset = 0, password = None): filename = string.replace(filename, '/', '\\') fid = -1 tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: fid, attrib, lastwritetime, datasize, grantedaccess, filetype, devicestate, action, serverfid = self.open_andx(tid, filename, mode, SMB_ACCESS_READ | SMB_SHARE_DENY_WRITE) if not datasize: datasize = self.query_file_info(tid, fid) if self.__ntlm_dialect.is_rawmode(): self.__raw_retr_file(tid, fid, offset, datasize, callback) else: self.__nonraw_retr_file(tid, fid, offset, datasize, callback) finally: if fid >= 0: self.close(tid, fid) self.disconnect_tree(tid) def stor_file(self, service, filename, callback, mode = SMB_O_CREAT | SMB_O_TRUNC, offset = 0, password = None): filename = string.replace(filename, '/', '\\') fid = -1 tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: fid, attrib, lastwritetime, datasize, grantedaccess, filetype, devicestate, action, serverfid = self.open_andx(tid, filename, mode, SMB_ACCESS_WRITE | SMB_SHARE_DENY_WRITE) # If the max_transmit buffer size is more than 16KB, upload process using non-raw mode is actually # faster than using raw-mode. if self.__ntlm_dialect.get_max_buffer() < 16384 and self.__ntlm_dialect.is_rawmode(): # Once the __raw_stor_file returns, fid is already closed self.__raw_stor_file(tid, fid, offset, datasize, callback) fid = -1 else: self.__nonraw_stor_file(tid, fid, offset, datasize, callback) finally: if fid >= 0: self.close(tid, fid) self.disconnect_tree(tid) def copy(self, src_service, src_path, dest_service, dest_path, callback = None, write_mode = SMB_O_CREAT | SMB_O_TRUNC, src_password = None, dest_password = None): dest_path = string.replace(dest_path, '/', '\\') src_path = string.replace(src_path, '/', '\\') src_tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + src_service, src_password) dest_tid = -1 try: if src_service == dest_service: dest_tid = src_tid else: dest_tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + dest_service, dest_password) dest_fid = self.open_andx(dest_tid, dest_path, write_mode, SMB_ACCESS_WRITE | SMB_SHARE_DENY_WRITE)[0] src_fid, _, _, src_datasize, _, _, _, _, _ = self.open_andx(src_tid, src_path, SMB_O_OPEN, SMB_ACCESS_READ | SMB_SHARE_DENY_WRITE) if callback: callback(0, src_datasize) max_buf_size = (self.__ntlm_dialect.get_max_buffer() >> 10) << 10 read_offset = 0 write_offset = 0 while read_offset < src_datasize: self.__send_smb_packet(SMB.SMB_COM_READ_ANDX, 0, 0, src_tid, 0, pack('<BBHHLHHLH', 0xff, 0, 0, src_fid, read_offset, max_buf_size, max_buf_size, 0, 0), '') while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_READ_ANDX): offset = unpack('<H', s.get_parameter_words()[2:4])[0] data_len, dataoffset = unpack('<HH', s.get_parameter_words()[10+offset:14+offset]) if data_len == len(d): self.__send_smb_packet(SMB.SMB_COM_WRITE_ANDX, 0, 0, dest_tid, 0, pack('<BBHHLLHHHHH', 0xff, 0, 0, dest_fid, write_offset, 0, 0, 0, 0, data_len, 59), d) else: self.__send_smb_packet(SMB.SMB_COM_WRITE_ANDX, 0, 0, dest_tid, 0, pack('<BBHHLLHHHHH', 0xff, 0, 0, dest_fid, write_offset, 0, 0, 0, 0, data_len, 59), d[dataoffset - 59:dataoffset - 59 + data_len]) while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_WRITE_ANDX): offset = unpack('<H', s.get_parameter_words()[2:4])[0] write_offset = write_offset + unpack('<H', s.get_parameter_words()[4+offset:6+offset])[0] break read_offset = read_offset + data_len if callback: callback(read_offset, src_datasize) break finally: self.disconnect_tree(src_tid) if dest_tid > -1 and src_service != dest_service: self.disconnect_tree(dest_tid) def check_dir(self, service, path, password = None): tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: self.__send_smb_packet(SMB.SMB_COM_CHECK_DIRECTORY, 0x08, 0, tid, 0, '', '\x04' + path + '\x00') while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_CHECK_DIRECTORY): return finally: self.disconnect_tree(s.get_tid()) def remove(self, service, path, password = None): # Perform a list to ensure the path exists self.list_path(service, path, password) tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: self.__send_smb_packet(SMB.SMB_COM_DELETE, 0x08, 0, tid, 0, pack('<H', ATTR_HIDDEN | ATTR_SYSTEM | ATTR_ARCHIVE), '\x04' + path + '\x00') while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_DELETE): return finally: self.disconnect_tree(s.get_tid()) def rmdir(self, service, path, password = None): # Check that the directory exists self.check_dir(service, path, password) tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: self.__send_smb_packet(SMB.SMB_COM_DELETE_DIRECTORY, 0x08, 0, tid, 0, '', '\x04' + path + '\x00') while 1: s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_DELETE_DIRECTORY): return finally: self.disconnect_tree(s.get_tid()) def mkdir(self, service, path, password = None): tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: s = SMBPacket() s.set_command(SMB.SMB_COM_CREATE_DIRECTORY) s.set_flags(0x08) s.set_flags2(0) s.set_tid(tid) s.set_parameter_words('') # check this! don't know if i don'thave to put this s.set_buffer('\x04' + path + '\x00') self.send_smb(s) s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_CREATE_DIRECTORY): return 1 return 0 finally: self.disconnect_tree(s.get_tid()) def rename(self, service, old_path, new_path, password = None): tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: s = SMBPacket() s.set_command(SMB.SMB_COM_RENAME) s.set_flags(0x08) s.set_flags2(0) s.set_tid(tid) s.set_parameter_words(pack('<H', ATTR_SYSTEM | ATTR_HIDDEN | ATTR_DIRECTORY)) s.set_buffer('\x04' + old_path + '\x00\x04' + new_path + '\x00') self.send_smb(s) s = self.recv_packet() if self.isValidAnswer(s,SMB.SMB_COM_RENAME): return 1 return 0 finally: self.disconnect_tree(s.get_tid()) def browse_domains(self): return self.__browse_servers(SV_TYPE_DOMAIN_ENUM, SMBDomain, '') def browse_servers_for_domain(self, domain = None): if not domain: domain = self.__server_domain return self.__browse_servers(SV_TYPE_SERVER | SV_TYPE_PRINTQ_SERVER | SV_TYPE_WFW | SV_TYPE_NT, SMBMachine, domain) def get_socket(self): return self.__sess.get_socket() ERRDOS = { 1: 'Invalid function', 2: 'File not found', 3: 'Invalid directory', 4: 'Too many open files', 5: 'Access denied', 6: 'Invalid file handle. Please file a bug report.', 7: 'Memory control blocks destroyed', 8: 'Out of memory', 9: 'Invalid memory block address', 10: 'Invalid environment', 11: 'Invalid format', 12: 'Invalid open mode', 13: 'Invalid data', 15: 'Invalid drive', 16: 'Attempt to remove server\'s current directory', 17: 'Not the same device', 18: 'No files found', 32: 'Sharing mode conflicts detected', 33: 'Lock request conflicts detected', 80: 'File already exists' } ERRSRV = { 1: 'Non-specific error', 2: 'Bad password', 4: 'Access denied', 5: 'Invalid tid. Please file a bug report.', 6: 'Invalid network name', 7: 'Invalid device', 49: 'Print queue full', 50: 'Print queue full', 51: 'EOF on print queue dump', 52: 'Invalid print file handle', 64: 'Command not recognized. Please file a bug report.', 65: 'Internal server error', 67: 'Invalid path', 69: 'Invalid access permissions', 71: 'Invalid attribute mode', 81: 'Server is paused', 82: 'Not receiving messages', 83: 'No room to buffer messages', 87: 'Too many remote user names', 88: 'Operation timeout', 89: 'Out of resources', 91: 'Invalid user handle. Please file a bug report.', 250: 'Temporarily unable to support raw mode for transfer', 251: 'Temporarily unable to support raw mode for transfer', 252: 'Continue in MPX mode', 65535: 'Unsupported function' } ERRHRD = { 19: 'Media is write-protected', 20: 'Unknown unit', 21: 'Drive not ready', 22: 'Unknown command', 23: 'CRC error', 24: 'Bad request', 25: 'Seek error', 26: 'Unknown media type', 27: 'Sector not found', 28: 'Printer out of paper', 29: 'Write fault', 30: 'Read fault', 31: 'General failure', 32: 'Open conflicts with an existing open', 33: 'Invalid lock request', 34: 'Wrong disk in drive', 35: 'FCBs not available', 36: 'Sharing buffer exceeded' }
88,384
Python
.py
2,033
33.880472
316
0.58477
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,946
structure.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/structure.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: structure.py,v 1.2 2006/05/23 21:19:26 gera Exp $ # from struct import pack, unpack, calcsize class Structure: """ sublcasses can define commonHdr and/or structure. each of them is an tuple of either two: (fieldName, format) or three: (fieldName, ':', class) fields. [it can't be a dictionary, because order is important] where format specifies how the data in the field will be converted to/from bytes (string) class is the class to use when unpacking ':' fields. each field can only contain one value (or an array of values for *) i.e. struct.pack('Hl',1,2) is valid, but format specifier 'Hl' is not (you must use 2 dfferent fields) format specifiers: specifiers from module pack can be used with the same format see struct.__doc__ (pack/unpack is finally called) > [little endian] x [padding byte] c [character] b [signed byte] B [unsigned byte] h [signed short] H [unsigned short] l [signed long] L [unsigned long] i [signed integer] I [unsigned integer] q [signed long long (quad)] Q [unsigned long ong (quad)] s [string (array of chars), must be preceded with length in format specifier, padded with zeros] p [pascal string (includes byte count), must be preceded with length in format specifier, padded with zeros] f [float] d [double] = [native byte ordering, size and alignment] @ [native byte ordering, standard size and alignment] ! [network byte ordering] < [little endian] > [big endian] usual printf like specifiers can be used (if started with %) [not recommeneded, there is no why to unpack this] %08x will output an 8 bytes hex %s will output a string %s\x00 will output a NUL terminated string %d%d will output 2 decimal digits (against the very same specification of Structure) ... some additional format specifiers: : just copy the bytes from the field into the output string (input may be string, other structure, or anything responding to __str__()) (for unpacking, all what's left is returned) z same as :, but adds a NUL byte at the end (asciiz) (for unpacking the first NUL byte is used as terminator) [asciiz string] u same as z, but adds two NUL bytes at the end (after padding to an even size with NULs). (same for unpacking) [unicode string] w DCE-RPC/NDR string (it's a macro for [ '<L=(len(field)+1)/2','"\x00\x00\x00\x00','<L=(len(field)+1)/2',':' ] ?-field length of field named 'field', formated as specified with ? ('?' may be '!H' for example). The input value overrides the real length ?1*?2 array of elements. Each formated as '?2', the number of elements in the array is stored as specified by '?1' (?1 is optional, or can also be a constant (number), for unpacking) 'xxxx literal xxxx (field's value doesn't change the output. quotes must not be closed or escaped) "xxxx literal xxxx (field's value doesn't change the output. quotes must not be closed or escaped) _ will not pack the field. Accepts a third argument, which is an unpack code. See _Test_UnpackCode for an example ?=packcode will evaluate packcode in the context of the structure, and pack the result as specified by ?. Unpacking is made plain ?&fieldname "Address of field fieldname". For packing it will simply pack the id() of fieldname. Or use 0 if fieldname doesn't exists. For unpacking, it's used to know weather fieldname has to be unpacked or not, i.e. by adding a & field you turn another field (fieldname) in an optional field. """ commonHdr = () structure = () debug = 0 def __init__(self, data = None, alignment = 0): if not hasattr(self, 'alignment'): self.alignment = alignment self.fields = {} if data is not None: self.fromString(data) else: self.data = None def setAlignment(self, alignment): self.alignment = alignment def setData(self, data): self.data = data def packField(self, fieldName, format = None): if self.debug: print "packField( %s | %s )" % (fieldName, format) if format is None: format = self.formatForField(fieldName) if self.fields.has_key(fieldName): ans = self.pack(format, self.fields[fieldName], field = fieldName) else: ans = self.pack(format, None, field = fieldName) if self.debug: print "\tanswer %r" % ans return ans def getData(self): if self.data is not None: return self.data data = '' for field in self.commonHdr+self.structure: try: data += self.packField(field[0], field[1]) except Exception, e: if self.fields.has_key(field[0]): e.args += ("When packing field '%s | %s | %r' in %s" % (field[0], field[1], self[field[0]], self.__class__),) else: e.args += ("When packing field '%s | %s' in %s" % (field[0], field[1], self.__class__),) raise if self.alignment: if len(data) % self.alignment: data += ('\x00'*self.alignment)[:-(len(data) % self.alignment)] #if len(data) % self.alignment: data += ('\x00'*self.alignment)[:-(len(data) % self.alignment)] return data def fromString(self, data): for field in self.commonHdr+self.structure: if self.debug: print "fromString( %s | %s | %r )" % (field[0], field[1], data) size = self.calcUnpackSize(field[1], data, field[0]) dataClassOrCode = str if len(field) > 2: dataClassOrCode = field[2] try: self[field[0]] = self.unpack(field[1], data[:size], dataClassOrCode = dataClassOrCode, field = field[0]) except Exception,e: e.args += ("When unpacking field '%s | %s | %r[:%d]'" % (field[0], field[1], data, size),) raise size = self.calcPackSize(field[1], self[field[0]], field[0]) if self.alignment and size % self.alignment: size += self.alignment - (size % self.alignment) data = data[size:] return self def __setitem__(self, key, value): self.fields[key] = value self.data = None # force recompute def __getitem__(self, key): return self.fields[key] def __delitem__(self, key): del self.fields[key] def __str__(self): return self.getData() def __len__(self): # XXX: improve return len(self.getData()) def pack(self, format, data, field = None): if self.debug: print " pack( %s | %r | %s)" % (format, data, field) if field: addressField = self.findAddressFieldFor(field) if (addressField is not None) and (data is None): return '' # void specifier if format[:1] == '_': return '' # quote specifier if format[:1] == "'" or format[:1] == '"': return format[1:] # address specifier two = format.split('&') if len(two) == 2: try: return self.pack(two[0], data) except: if (self.fields.has_key(two[1])) and (self[two[1]] is not None): return self.pack(two[0], id(self[two[1]])) else: return self.pack(two[0], 0) # code specifier two = format.split('=') if len(two) >= 2: try: return self.pack(two[0], data) except: return self.pack(two[0], eval(two[1], {}, self.fields)) # length specifier two = format.split('-') if len(two) == 2: try: return self.pack(two[0],data) except: return self.pack(two[0], self.calcPackFieldSize(two[1])) # array specifier two = format.split('*') if len(two) == 2: answer = '' for each in data: answer += self.pack(two[1], each) if two[0]: if two[0].isdigit(): if int(two[0]) != len(data): raise Exception, "Array field has a constant size, and it doesn't match the actual value" else: return self.pack(two[0], len(data))+answer return answer # "printf" string specifier if format[:1] == '%': # format string like specifier return format % data # asciiz specifier if format[:1] == 'z': return str(data)+'\0' # unicode specifier if format[:1] == 'u': return str(data)+'\0\0' + (len(data) & 1 and '\0' or '') # DCE-RPC/NDR string specifier if format[:1] == 'w': if len(data) == 0: data = '\0\0' elif len(data) % 2: data += '\0' l = pack('<L', len(data)/2) return '%s\0\0\0\0%s%s' % (l,l,data) if data is None: raise Exception, "Trying to pack None" # literal specifier if format[:1] == ':': return str(data) # struct like specifier return pack(format, data) def unpack(self, format, data, dataClassOrCode = str, field = None): if self.debug: print " unpack( %s | %r )" % (format, data) if field: addressField = self.findAddressFieldFor(field) if addressField is not None: if not self[addressField]: return # void specifier if format[:1] == '_': if dataClassOrCode != str: return eval(dataClassOrCode, {}, self.fields) # quote specifier if format[:1] == "'" or format[:1] == '"': answer = format[1:] if answer != data: raise Exception, "Unpacked data doesn't match constant value '%r' should be '%r'" % (data, answer) return answer # address specifier two = format.split('&') if len(two) == 2: return self.unpack(two[0],data) # code specifier two = format.split('=') if len(two) >= 2: return self.unpack(two[0],data) # length specifier two = format.split('-') if len(two) == 2: return self.unpack(two[0],data) # array specifier two = format.split('*') if len(two) == 2: answer = [] sofar = 0 if two[0].isdigit(): number = int(two[0]) elif two[0]: sofar += self.calcUnpackSize(two[0], data) number = self.unpack(two[0], data[:sofar]) else: number = -1 while number and sofar < len(data): nsofar = sofar + self.calcUnpackSize(two[1],data[sofar:]) answer.append(self.unpack(two[1], data[sofar:nsofar], dataClassOrCode)) number -= 1 sofar = nsofar return answer # "printf" string specifier if format[:1] == '%': # format string like specifier return format % data # asciiz specifier if format == 'z': if data[-1] != '\x00': raise Exception, ("%s 'z' field is not NUL terminated: %r" % (field, data)) return data[:-1] # remove trailing NUL # unicode specifier if format == 'u': if data[-2:] != '\x00\x00': raise Exception, ("%s 'u' field is not NUL-NUL terminated: %r" % (field, data)) return data[:-2] # remove trailing NUL # DCE-RPC/NDR string specifier if format == 'w': l = unpack('<L', data[:4])[0] return data[12:12+l*2] # literal specifier if format == ':': return dataClassOrCode(data) # struct like specifier return unpack(format, data)[0] def calcPackSize(self, format, data, field = None): # # print " calcPackSize %s:%r" % (format, data) if field: addressField = self.findAddressFieldFor(field) if addressField is not None: if not self[addressField]: return 0 # void specifier if format[:1] == '_': return 0 # quote specifier if format[:1] == "'" or format[:1] == '"': return len(format)-1 # address specifier two = format.split('&') if len(two) == 2: return self.calcPackSize(two[0], data) # code specifier two = format.split('=') if len(two) >= 2: return self.calcPackSize(two[0], data) # length specifier two = format.split('-') if len(two) == 2: return self.calcPackSize(two[0], data) # array specifier two = format.split('*') if len(two) == 2: answer = 0 if two[0].isdigit(): if int(two[0]) != len(data): raise Exception, "Array field has a constant size, and it doesn't match the actual value" elif two[0]: answer += self.calcPackSize(two[0], len(data)) for each in data: answer += self.calcPackSize(two[1], each) return answer # "printf" string specifier if format[:1] == '%': # format string like specifier return len(format % data) # asciiz specifier if format[:1] == 'z': return len(data)+1 # asciiz specifier if format[:1] == 'u': l = len(data) return l + (l & 1 and 3 or 2) # DCE-RPC/NDR string specifier if format[:1] == 'w': l = len(data) return 12+l+l % 2 # literal specifier if format[:1] == ':': return len(data) # struct like specifier return calcsize(format) def calcUnpackSize(self, format, data, field = None): if self.debug: print " calcUnpackSize( %s | %s | %r)" % (field, format, data) addressField = self.findAddressFieldFor(field) if addressField is not None: if not self[addressField]: return 0 try: lengthField = self.findLengthFieldFor(field) return self[lengthField] except: pass # XXX: Try to match to actual values, raise if no match # void specifier if format[:1] == '_': return 0 # quote specifier if format[:1] == "'" or format[:1] == '"': return len(format)-1 # address specifier two = format.split('&') if len(two) == 2: return self.calcUnpackSize(two[0], data) # code specifier two = format.split('=') if len(two) >= 2: return self.calcUnpackSize(two[0], data) # length specifier two = format.split('-') if len(two) == 2: return self.calcUnpackSize(two[0], data) # array specifier two = format.split('*') if len(two) == 2: answer = 0 if two[0]: if two[0].isdigit(): number = int(two[0]) else: answer += self.calcUnpackSize(two[0], data) number = self.unpack(two[0], data[:answer]) while number: number -= 1 answer += self.calcUnpackSize(two[1], data[answer:]) else: while answer < len(data): answer += self.calcUnpackSize(two[1], data[answer:]) return answer # "printf" string specifier if format[:1] == '%': raise Exception, "Can't guess the size of a printf like specifier for unpacking" # asciiz specifier if format[:1] == 'z': return data.index('\x00')+1 # asciiz specifier if format[:1] == 'u': l = data.index('\x00\x00') return l + (l & 1 and 3 or 2) # DCE-RPC/NDR string specifier if format[:1] == 'w': l = unpack('<L', data[:4])[0] return 12+l*2 # literal specifier if format[:1] == ':': return len(data) # struct like specifier return calcsize(format) def calcPackFieldSize(self, fieldName, format = None): if format is None: format = self.formatForField(fieldName) return self.calcPackSize(format, self[fieldName]) def formatForField(self, fieldName): for field in self.commonHdr+self.structure: if field[0] == fieldName: return field[1] raise Exception, ("Field %s not found" % fieldName) def findAddressFieldFor(self, fieldName): descriptor = '&%s' % fieldName l = len(descriptor) for field in self.commonHdr+self.structure: if field[1][-l:] == descriptor: return field[0] return None def findLengthFieldFor(self, fieldName): descriptor = '-%s' % fieldName l = len(descriptor) for field in self.commonHdr+self.structure: if field[1][-l:] == descriptor: return field[0] return None def zeroValue(self, format): two = format.split('*') if len(two) == 2: if two[0].isdigit(): return (self.zeroValue(two[1]),)*int(two[0]) if not format.find('*') == -1: return () if 's' in format: return '' if format in ['z',':','u']: return '' if format == 'w': return '\x00\x00' return 0 def clear(self): for field in self.commonHdr + self.structure: self[field[0]] = self.zeroValue(field[1]) def dump(self, msg, indent = 0): import types ind = ' '*indent print "\n%s" % (msg) for i in self.fields.keys(): if isinstance(self[i], Structure): self[i].dump('%s:{' % i, indent = indent + 4) print "}" else: print "%s%s: {%r}" % (ind,i,self[i]) class _StructureTest: alignment = 0 def create(self,data = None): if data is not None: return self.theClass(data, alignment = self.alignment) else: return self.theClass(alignment = self.alignment) def run(self): print print "-"*70 testName = self.__class__.__name__ print "starting test: %s....." % testName a = self.create() self.populate(a) a.dump("packing.....") a_str = str(a) print "packed: %r" % a_str print "unpacking....." b = self.create(a_str) b.dump("unpacked.....") print "repacking....." b_str = str(b) if b_str != a_str: print "ERROR: original packed and repacked don't match" print "packed: %r" % b_str class _Test_simple(_StructureTest): class theClass(Structure): commonHdr = () structure = ( ('int1', '!L'), ('len1','!L-z1'), ('arr1','B*<L'), ('z1', 'z'), ('u1','u'), ('', '"COCA'), ('len2','!H-:1'), ('', '"COCA'), (':1', ':'), ('int3','>L'), ('code1','>L=len(arr1)*2+0x1000'), ) def populate(self, a): a['default'] = 'hola' a['int1'] = 0x3131 a['int3'] = 0x45444342 a['z1'] = 'hola' a['u1'] = 'hola'.encode('utf_16_le') a[':1'] = ':1234:' a['arr1'] = (0x12341234,0x88990077,0x41414141) # a['len1'] = 0x42424242 class _Test_fixedLength(_Test_simple): def populate(self, a): _Test_simple.populate(self, a) a['len1'] = 0x42424242 class _Test_simple_aligned4(_Test_simple): alignment = 4 class _Test_nested(_StructureTest): class theClass(Structure): class _Inner(Structure): structure = (('data', 'z'),) structure = ( ('nest1', ':', _Inner), ('nest2', ':', _Inner), ('int', '<L'), ) def populate(self, a): a['nest1'] = _Test_nested.theClass._Inner() a['nest2'] = _Test_nested.theClass._Inner() a['nest1']['data'] = 'hola manola' a['nest2']['data'] = 'chau loco' a['int'] = 0x12345678 class _Test_Optional(_StructureTest): class theClass(Structure): structure = ( ('pName','<L&Name'), ('pList','<L&List'), ('Name','w'), ('List','<H*<L'), ) def populate(self, a): a['Name'] = 'Optional test' a['List'] = (1,2,3,4) class _Test_Optional_sparse(_Test_Optional): def populate(self, a): _Test_Optional.populate(self, a) del a['Name'] class _Test_AsciiZArray(_StructureTest): class theClass(Structure): structure = ( ('head','<L'), ('array','B*z'), ('tail','<L'), ) def populate(self, a): a['head'] = 0x1234 a['tail'] = 0xabcd a['array'] = ('hola','manola','te traje') class _Test_UnpackCode(_StructureTest): class theClass(Structure): structure = ( ('leni','<L=len(uno)*2'), ('cuchi','_-uno','leni/2'), ('uno',':'), ('dos',':'), ) def populate(self, a): a['uno'] = 'soy un loco!' a['dos'] = 'que haces fiera' if __name__ == '__main__': _Test_simple().run() try: _Test_fixedLength().run() except: print "cannot repack because length is bogus" _Test_simple_aligned4().run() _Test_nested().run() _Test_Optional().run() _Test_Optional_sparse().run() _Test_AsciiZArray().run() _Test_UnpackCode().run()
23,356
Python
.py
575
29.161739
198
0.519438
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,947
nmb.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/nmb.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: nmb.py,v 1.4 2006/05/23 21:19:25 gera Exp $ # # -*- mode: python; tab-width: 4 -*- # # Copyright (C) 2001 Michael Teo <michaelteo@bigfoot.com> # nmb.py - NetBIOS library # # This software is provided 'as-is', without any express or implied warranty. # In no event will the author be held liable for any damages arising from the # use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # # 3. This notice cannot be removed or altered from any source distribution. # # Altered source done by Alberto Solino import os, sys, socket, string, re, select, errno from random import randint from struct import * CVS_REVISION = '$Revision: 1.4 $' # Taken from socket module reference INADDR_ANY = '' BROADCAST_ADDR = '<broadcast>' # Default port for NetBIOS name service NETBIOS_NS_PORT = 137 # Default port for NetBIOS session service NETBIOS_SESSION_PORT = 139 # Default port for SMB session service SMB_SESSION_PORT = 445 # Owner Node Type Constants NODE_B = 0x0000 NODE_P = 0x2000 NODE_M = 0x4000 NODE_RESERVED = 0x6000 NODE_GROUP = 0x8000 NODE_UNIQUE = 0x0 # Name Type Constants TYPE_UNKNOWN = 0x01 TYPE_WORKSTATION = 0x00 TYPE_CLIENT = 0x03 TYPE_SERVER = 0x20 TYPE_DOMAIN_MASTER = 0x1B TYPE_MASTER_BROWSER = 0x1D TYPE_BROWSER = 0x1E TYPE_NETDDE = 0x1F # Opcodes values OPCODE_QUERY = 0 OPCODE_REGISTRATION = 0x5 OPCODE_RELEASE = 0x6 OPCODE_WACK = 0x7 OPCODE_REFRESH = 0x8 OPCODE_REQUEST = 0 OPCODE_RESPONSE = 0x10 # NM_FLAGS NM_FLAGS_BROADCAST = 0x1 NM_FLAGS_UNICAST = 0 NM_FLAGS_RA = 0x8 NM_FLAGS_RD = 0x10 NM_FLAGS_TC = 0x20 NM_FLAGS_AA = 0x40 # QUESTION_TYPE QUESTION_TYPE_NB = 0x20 # NetBIOS general Name Service Resource Record QUESTION_TYPE_NBSTAT = 0x21 # NetBIOS NODE STATUS Resource Record # QUESTION_CLASS QUESTION_CLASS_IN = 0x1 # Internet class # RR_TYPE Resource Record Type code RR_TYPE_A = 0x1 # IP address Resource Record RR_TYPE_NS = 0x2 # Name Server Resource Record RR_TYPE_NULL = 0xA # NULL Resource Record RR_TYPE_NB = 0x20 # NetBIOS general Name Service Resource Record RR_TYPE_NBSTAT = 0x21 # NetBIOS NODE STATUS Resource Record # Resource Record Class RR_CLASS_IN = 1 # Internet class # RCODE values RCODE_FMT_ERR = 0x1 # Format Error. Request was invalidly formatted. RCODE_SRV_ERR = 0x2 # Server failure. Problem with NBNS, cannot process name. RCODE_IMP_ERR = 0x4 # Unsupported request error. Allowable only for challenging NBNS when gets an Update type # registration request. RCODE_RFS_ERR = 0x5 # Refused error. For policy reasons server will not register this name from this host. RCODE_ACT_ERR = 0x6 # Active error. Name is owned by another node. RCODE_CFT_ERR = 0x7 # Name in conflict error. A UNIQUE name is owned by more than one node. # NAME_FLAGS NAME_FLAGS_PRM = 0x0200 # Permanent Name Flag. If one (1) then entry is for the permanent node name. Flag is zero # (0) for all other names. NAME_FLAGS_ACT = 0x0400 # Active Name Flag. All entries have this flag set to one (1). NAME_FLAG_CNF = 0x0800 # Conflict Flag. If one (1) then name on this node is in conflict. NAME_FLAG_DRG = 0x1000 # Deregister Flag. If one (1) then this name is in the process of being deleted. NAME_TYPES = { TYPE_UNKNOWN: 'Unknown', TYPE_WORKSTATION: 'Workstation', TYPE_CLIENT: 'Client', TYPE_SERVER: 'Server', TYPE_MASTER_BROWSER: 'Master Browser', TYPE_BROWSER: 'Browser Server', TYPE_DOMAIN_MASTER: 'Domain Master' , TYPE_NETDDE: 'NetDDE Server'} # NetBIOS Session Types NETBIOS_SESSION_MESSAGE = 0x0 NETBIOS_SESSION_REQUEST = 0x81 NETBIOS_SESSION_POSITIVE_RESPONSE = 0x82 NETBIOS_SESSION_NEGATIVE_RESPONSE = 0x83 NETBIOS_SESSION_RETARGET_RESPONSE = 0x84 NETBIOS_SESSION_KEEP_ALIVE = 0x85 def strerror(errclass, errcode): if errclass == ERRCLASS_OS: return 'OS Error', os.strerror(errcode) elif errclass == ERRCLASS_QUERY: return 'Query Error', QUERY_ERRORS.get(errcode, 'Unknown error') elif errclass == ERRCLASS_SESSION: return 'Session Error', SESSION_ERRORS.get(errcode, 'Unknown error') else: return 'Unknown Error Class', 'Unknown Error' class NetBIOSError(Exception): pass class NetBIOSTimeout(Exception): def __init__(self, message = 'The NETBIOS connection with the remote host timed out.'): Exception.__init__(self, message) class NBResourceRecord: def __init__(self, data = 0): self._data = data try: if self._data: self.rr_name = (re.split('\x00',data))[0] offset = len(self.rr_name)+1 self.rr_type = unpack('>H', self._data[offset:offset+2])[0] self.rr_class = unpack('>H', self._data[offset+2: offset+4])[0] self.ttl = unpack('>L',self._data[offset+4:offset+8])[0] self.rdlength = unpack('>H', self._data[offset+8:offset+10])[0] self.rdata = data[offset+10:self.rdlength] offset = self.rdlength - 2 self.unit_id = data[offset:offset+6] else: self.rr_name = '' self.rr_type = 0 self.rr_class = 0 self.ttl = 0 self.rdlength = 0 self.rdata = '' self.unit_id = '' except Exception,e: raise NetBIOSError( 'Wrong packet format ' ) def set_rr_name(self, name): self.rr_name = name def set_rr_type(self, name): self.rr_type = name def set_rr_class(self,cl): self_rr_class = cl def set_ttl(self,ttl): self.ttl = ttl def set_rdata(self,rdata): self.rdata = rdata self.rdlength = len(rdata) def get_unit_id(self): return self.unit_id def get_rr_name(self): return self.rr_name def get_rr_class(self): return self.rr_class def get_ttl(self): return self.ttl def get_rdlength(self): return self.rdlength def get_rdata(self): return self.rdata def rawData(self): return self.rr_name + pack('!HHLH',self.rr_type, self.rr_class, self.ttl, self.rdlength) + self.rdata class NBNodeStatusResponse(NBResourceRecord): def __init__(self, data = 0): NBResourceRecord.__init__(self,data) self.num_names = 0 self.node_names = [ ] self.statstics = '' self.mac = '00-00-00-00-00-00' try: if data: self._data = self.get_rdata() self.num_names = unpack('>B',self._data[:1])[0] offset = 1 for i in range(0, self.num_names): name = self._data[offset:offset + 15] type,flags = unpack('>BH', self._data[offset + 15: offset + 18]) offset += 18 self.node_names.append(NBNodeEntry(name, type ,flags)) self.set_mac_in_hexa(self.get_unit_id()) except Exception,e: raise NetBIOSError( 'Wrong packet format ' ) def set_mac_in_hexa(self, data): data_aux = '' for d in data: if data_aux == '': data_aux = '%02x' % ord(d) else: data_aux += '-%02x' % ord(d) self.mac = string.upper(data_aux) def get_num_names(self): return self.num_names def get_mac(self): return self.mac def set_num_names(self, num): self.num_names = num def get_node_names(self): return self.node_names def add_node_name(self,node_names): self.node_names.append(node_names) self.num_names += 1 def rawData(self): res = pack('!B', self.num_names ) for i in range(0, self.num_names): res += self.node_names[i].rawData() class NBPositiveNameQueryResponse(NBResourceRecord): def __init__(self,data = 0): NBResourceRecord.__init__(self,data) self.add_entries = [ ] if data: self._data = self.get_rdata() class NetBIOSPacket: """ This is a packet as defined in RFC 1002 """ def __init__(self, data = 0): self.name_trn_id = 0x0 # Transaction ID for Name Service Transaction. # Requestor places a unique value for each active # transaction. Responder puts NAME_TRN_ID value # from request packet in response packet. self.opcode = 0 # Packet type code self.nm_flags = 0 # Flags for operation self.rcode = 0 # Result codes of request. self.qdcount = 0 # Unsigned 16 bit integer specifying the number of entries in the question section of a Name self.ancount = 0 # Unsigned 16 bit integer specifying the number of # resource records in the answer section of a Name # Service packet. self.nscount = 0 # Unsigned 16 bit integer specifying the number of # resource records in the authority section of a # Name Service packet. self.arcount = 0 # Unsigned 16 bit integer specifying the number of # resource records in the additional records # section of a Name Service packeT. self.questions = '' self.answers = '' if data == 0: self._data = '' else: try: self._data = data self.opcode = ord(data[2]) >> 3 self.nm_flags = ((ord(data[2]) & 0x3) << 4) | ((ord(data[3]) & 0xf0) >> 4) self.name_trn_id = unpack('>H', self._data[:2])[0] self.rcode = ord(data[3]) & 0x0f self.qdcount = unpack('>H', self._data[4:6])[0] self.ancount = unpack('>H', self._data[6:8])[0] self.nscount = unpack('>H', self._data[8:10])[0] self.arcount = unpack('>H', self._data[10:12])[0] self.answers = self._data[12:] except Exception,e: raise NetBIOSError( 'Wrong packet format ' ) def set_opcode(self, opcode): self.opcode = opcode def set_trn_id(self, trn): self.name_trn_id = trn def set_nm_flags(self, nm_flags): self.nm_flags = nm_flags def set_rcode(self, rcode): self.rcode = rcode def addQuestion(self, question, qtype, qclass): self.qdcount = self.qdcount + 1 self.questions += question + pack('!HH',qtype,qclass) def get_trn_id(self): return self.name_trn_id def get_rcode(self): return self.rcode def get_nm_flags(self): return self.name_trn_id def get_opcode(self): return self.opcode def get_qdcount(self): return self.qdcount def get_ancount(self): return self.ancount def get_nscount(self): return self.nscount def get_arcount(self): return self.arcount def rawData(self): secondWord = self.opcode << 11 secondWord = secondWord | (self.nm_flags << 4) secondWord = secondWord | self.rcode data = pack('!HHHHHH', self.name_trn_id, secondWord , self.qdcount, self.ancount, self.nscount, self.arcount) + self.questions + self.answers return data def get_answers(self): return self.answers class NBHostEntry: def __init__(self, nbname, nametype, ip): self.__nbname = nbname self.__nametype = nametype self.__ip = ip def get_nbname(self): return self.__nbname def get_nametype(self): return self.__nametype def get_ip(self): return self.__ip def __repr__(self): return '<NBHostEntry instance: NBname="' + self.__nbname + '", IP="' + self.__ip + '">' class NBNodeEntry: def __init__(self, nbname, nametype, flags): self.__nbname = string.ljust(nbname,17) self.__nametype = nametype self.__flags = flags self.__isgroup = flags & 0x8000 self.__nodetype = flags & 0x6000 self.__deleting = flags & 0x1000 self.__isconflict = flags & 0x0800 self.__isactive = flags & 0x0400 self.__ispermanent = flags & 0x0200 def get_nbname(self): return self.__nbname def get_nametype(self): return self.__nametype def is_group(self): return self.__isgroup def get_nodetype(self): return self.__nodetype def is_deleting(self): return self.__deleting def is_conflict(self): return self.__isconflict def is_active(self): return self.__isactive def is_permanent(self): return self.__ispermanent def set_nbname(self, name): self.__nbname = string.ljust(name,17) def set_nametype(self, type): self.__nametype = type def set_flags(self,flags): self.__flags = flags def __repr__(self): s = '<NBNodeEntry instance: NBname="' + self.__nbname + '" NameType="' + NAME_TYPES[self.__nametype] + '"' if self.__isactive: s = s + ' ACTIVE' if self.__isgroup: s = s + ' GROUP' if self.__isconflict: s = s + ' CONFLICT' if self.__deleting: s = s + ' DELETING' return s def rawData(self): return self.__nbname + pack('!BH',self.__nametype, self.__flags) class NetBIOS: # Creates a NetBIOS instance without specifying any default NetBIOS domain nameserver. # All queries will be sent through the servport. def __init__(self, servport = NETBIOS_NS_PORT): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) has_bind = 1 for i in range(0, 10): # We try to bind to a port for 10 tries try: s.bind(( INADDR_ANY, randint(10000, 60000) )) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) has_bind = 1 except socket.error, ex: pass if not has_bind: raise NetBIOSError, ( 'Cannot bind to a good UDP port', ERRCLASS_OS, errno.EAGAIN ) self.__sock = s self.__servport = NETBIOS_NS_PORT self.__nameserver = None self.__broadcastaddr = BROADCAST_ADDR self.mac = '00-00-00-00-00-00' # Set the default NetBIOS domain nameserver. def set_nameserver(self, nameserver): self.__nameserver = nameserver # Return the default NetBIOS domain nameserver, or None if none is specified. def get_nameserver(self): return self.__nameserver # Set the broadcast address to be used for query. def set_broadcastaddr(self, broadcastaddr): self.__broadcastaddr = broadcastaddr # Return the broadcast address to be used, or BROADCAST_ADDR if default broadcast address is used. def get_broadcastaddr(self): return self.__broadcastaddr # Returns a list of NBHostEntry instances containing the host information for nbname. # If a NetBIOS domain nameserver has been specified, it will be used for the query. # Otherwise, the query is broadcasted on the broadcast address. def gethostbyname(self, nbname, type = TYPE_WORKSTATION, scope = None, timeout = 1): return self.__queryname(nbname, self.__nameserver, type, scope, timeout) # Returns a list of NBNodeEntry instances containing node status information for nbname. # If destaddr contains an IP address, then this will become an unicast query on the destaddr. # Raises NetBIOSTimeout if timeout (in secs) is reached. # Raises NetBIOSError for other errors def getnodestatus(self, nbname, destaddr = None, type = TYPE_WORKSTATION, scope = None, timeout = 1): if destaddr: return self.__querynodestatus(nbname, destaddr, type, scope, timeout) else: return self.__querynodestatus(nbname, self.__nameserver, type, scope, timeout) def getmacaddress(self): return self.mac def __queryname(self, nbname, destaddr, type, scope, timeout): netbios_name = string.upper(nbname) trn_id = randint(1, 32000) p = NetBIOSPacket() p.set_trn_id(trn_id) netbios_name = string.upper(nbname) qn_label = encode_name(netbios_name, type, scope) p.addQuestion(qn_label, QUESTION_TYPE_NB, QUESTION_CLASS_IN) qn_label = encode_name(netbios_name, type, scope) if not destaddr: p.set_nm_flags(NM_FLAGS_BROADCAST) destaddr = self.__broadcastaddr wildcard_query = netbios_name == '*' req = p.rawData() self.__sock.sendto(req, 0, ( destaddr, self.__servport )) addrs = [ ] tries = 3 while 1: try: ready, _, _ = select.select([ self.__sock.fileno() ], [ ] , [ ], timeout) if not ready: if tries and not wildcard_query: # Retry again until tries == 0 self.__sock.sendto(req, 0, ( destaddr, self.__servport )) tries = tries - 1 elif wildcard_query: return addrs else: raise NetBIOSTimeout else: data, _ = self.__sock.recvfrom(65536, 0) res = NetBIOSPacket(data) if res.get_trn_id() == p.get_trn_id(): if res.get_rcode(): if res.get_rcode() == 0x03: return None else: raise NetBIOSError, ( 'Negative name query response', ERRCLASS_QUERY, res.get_rcode() ) answ = NBPositiveNameQueryResponse(res.get_answers()) if not wildcard_query: return addrs except select.error, ex: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise NetBIOSError, ( 'Error occurs while waiting for response', ERRCLASS_OS, ex[0] ) except socket.error, ex: pass def __querynodestatus(self, nbname, destaddr, type, scope, timeout): trn_id = randint(1, 32000) p = NetBIOSPacket() p.set_trn_id(trn_id) netbios_name = string.upper(nbname) qn_label = encode_name(netbios_name, type, scope) p.addQuestion(qn_label, QUESTION_TYPE_NBSTAT, QUESTION_CLASS_IN) if not destaddr: p.set_nm_flags(NM_FLAGS_BROADCAST) destaddr = self.__broadcastaddr req = p.rawData() tries = 3 while 1: try: self.__sock.sendto(req, 0, ( destaddr, self.__servport )) ready, _, _ = select.select([ self.__sock.fileno() ], [ ] , [ ], timeout) if not ready: if tries: # Retry again until tries == 0 tries = tries - 1 else: raise NetBIOSTimeout else: try: data, _ = self.__sock.recvfrom(65536, 0) except: # t_log(1,"No status response") return res = NetBIOSPacket(data) if res.get_trn_id() == p.get_trn_id(): if res.get_rcode(): if res.get_rcode() == 0x03: return None else: raise NetBIOSError, ( 'Negative name query response', ERRCLASS_QUERY, res.get_rcode() ) answ = NBNodeStatusResponse(res.get_answers()) self.mac = answ.get_mac() return answ.get_node_names() except select.error, ex: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise NetBIOSError, ( 'Error occurs while waiting for response', ERRCLASS_OS, ex[0] ) except socket.error, ex: pass # Perform first and second level encoding of name as specified in RFC 1001 (Section 4) def encode_name(name, type, scope): if name == '*': name = name + '\0' * 15 elif len(name) > 15: name = name[:15] + chr(type) else: name = string.ljust(name, 15) + chr(type) encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name) if scope: encoded_scope = '' for s in string.split(scope, '.'): encoded_scope = encoded_scope + chr(len(s)) + s return encoded_name + encoded_scope + '\0' else: return encoded_name + '\0' # Internal method for use in encode_name() def _do_first_level_encoding(m): s = ord(m.group(0)) return string.uppercase[s >> 4] + string.uppercase[s & 0x0f] def decode_name(name): name_length = ord(name[0]) assert name_length == 32 decoded_name = re.sub('..', _do_first_level_decoding, name[1:33]) if name[33] == '\0': return 34, decoded_name, '' else: decoded_domain = '' offset = 34 while 1: domain_length = ord(name[offset]) if domain_length == 0: break decoded_domain = '.' + name[offset:offset + domain_length] offset = offset + domain_length return offset + 1, decoded_name, decoded_domain def _do_first_level_decoding(m): s = m.group(0) return chr(((ord(s[0]) - ord('A')) << 4) | (ord(s[1]) - ord('A'))) class NetBIOSSessionPacket: def __init__(self, data = 0): self.type = 0x0 self.flags = 0x0 self.length = 0x0 if data == 0: self._trailer = '' else: try: self.type = ord(data[0]) self.flags = ord(data[1]) self.length = unpack('!H', data[2:4])[0] self._trailer = data[4:] except: raise NetBIOSError( 'Wrong packet format ' ) def set_type(self, type): self.type = type def get_type(self): return self.type def rawData(self): data = pack('!BBH',self.type,self.flags,self.length) + self._trailer return data def set_trailer(self,data): self._trailer = data self.length = len(data) def get_length(self): return self.length def get_trailer(self): return self._trailer class NetBIOSSession: def __init__(self, myname, remote_name, remote_host, remote_type = TYPE_SERVER, sess_port = NETBIOS_SESSION_PORT, timeout = None, local_type = TYPE_WORKSTATION): if len(myname) > 15: self.__myname = string.upper(myname[:15]) else: self.__myname = string.upper(myname) assert remote_name if len(remote_name) > 15: self.__remote_name = string.upper(remote_name[:15]) else: self.__remote_name = string.upper(remote_name) self.__remote_host = remote_host self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.__sock.connect(( remote_host, sess_port )) except socket.error, ex: raise ex if sess_port == NETBIOS_SESSION_PORT: self.__request_session(remote_type, local_type, timeout) def get_myname(self): return self.__myname def get_remote_host(self): return self.__remote_host def get_remote_name(self): return self.__remote_name def close(self): self.__sock.close() def send_packet(self, data): p = NetBIOSSessionPacket() p.set_type(NETBIOS_SESSION_MESSAGE) p.set_trailer(data) self.__sock.send(p.rawData()) def recv_packet(self, timeout = None): data = self.__read(timeout) return NetBIOSSessionPacket(data) def __request_session(self, remote_type, local_type, timeout = None): p = NetBIOSSessionPacket() remote_name = encode_name(self.__remote_name, remote_type, '') myname = encode_name(self.__myname, local_type, '') p.set_type(NETBIOS_SESSION_REQUEST) p.set_trailer(remote_name + myname) self.__sock.send(p.rawData()) while 1: p = self.recv_packet(timeout) if p.get_type() == NETBIOS_SESSION_NEGATIVE_RESPONSE: raise NetBIOSError, ( 'Cannot request session', ERRCLASS_SESSION, ord(p.get_trailer()[0]) ) elif p.get_type() == NETBIOS_SESSION_POSITIVE_RESPONSE: break else: # Ignore all other messages, most probably keepalive messages pass def __read(self, timeout = None): read_len = 4 data = '' while read_len > 0: try: ready, _, _ = select.select([self.__sock.fileno() ], [ ], [ ], timeout) if not ready: raise NetBIOSTimeout received = self.__sock.recv(read_len) if len(received)==0: raise NetBIOSError, ( 'Error while reading from remote', ERRCLASS_OS, None) data = data + received read_len = 4 - len(data) except select.error, ex: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise NetBIOSError, ( 'Error occurs while reading from remote', ERRCLASS_OS, ex[0] ) type, flags, length = unpack('>ccH', data) if ord(flags) & 0x01: length = length | 0x10000 read_len = length data2='' while read_len > 0: try: ready, _, _ = select.select([ self.__sock.fileno() ], [ ], [ ], timeout) if not ready: raise NetBIOSTimeout received = self.__sock.recv(read_len) if len(received)==0: raise NetBIOSError, ( 'Error while reading from remote', ERRCLASS_OS, None) data2 = data2 + received read_len = length - len(data2) except select.error, ex: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise NetBIOSError, ( 'Error while reading from remote', ERRCLASS_OS, ex[0] ) return data + data2 def get_socket(self): return self.__sock ERRCLASS_QUERY = 0x00 ERRCLASS_SESSION = 0xf0 ERRCLASS_OS = 0xff QUERY_ERRORS = { 0x01: 'Request format error. Please file a bug report.', 0x02: 'Internal server error', 0x03: 'Name does not exist', 0x04: 'Unsupported request', 0x05: 'Request refused' } SESSION_ERRORS = { 0x80: 'Not listening on called name', 0x81: 'Not listening for calling name', 0x82: 'Called name not present', 0x83: 'Sufficient resources', 0x8f: 'Unspecified error' } def main(): print if __name__ == '__main__': main()
28,399
Python
.py
670
32.423881
165
0.582235
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,948
svcctl.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/svcctl.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: svcctl.py,v 1.6 2006/05/23 21:19:26 gera Exp $ # # Description: # SVCCTL (Services Control) interface implementation. # import array from struct import * from impacket import ImpactPacket import dcerpc MSRPC_UUID_SVCCTL = '\x81\xbb\x7a\x36\x44\x98\xf1\x35\xad\x32\x98\xf0\x38\x00\x10\x03\x02\x00\x00\x00' class SVCCTLOpenSCManagerHeader(ImpactPacket.Header): OP_NUM = 0x1B __SIZE = 32 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLOpenSCManagerHeader.__SIZE) self.set_referent_id(0xFFFFFF) self.set_access_mask(0xF003F) if aBuffer: self.load_header(aBuffer) def get_referent_id(self): return self.get_long(0, '<') def set_referent_id(self, id): self.set_long(0, id, '<') def get_max_count(self): return self.get_long(4, '<') def set_max_count(self, num): self.set_long(4, num, '<') def get_offset(self): return self.get_long(8, '<') def set_offset(self, num): self.set_long(8, num, '<') def get_cur_count(self): return self.get_long(12, '<') def set_cur_count(self, num): self.set_long(12, num, '<') def get_machine_name(self): return self.get_bytes().tostring()[:20] def set_machine_name(self, name): assert len(name) <= 8 self.set_max_count(len(name) + 1) self.set_cur_count(len(name) + 1) self.get_bytes()[16:24] = array.array('B', name + (8 - len(name)) * '\x00') def get_access_mask(self): return self.get_long(28, '<') def set_access_mask(self, mask): self.set_long(28, mask, '<') def get_header_size(self): return SVCCTLOpenSCManagerHeader.__SIZE class SVCCTLRespOpenSCManagerHeader(ImpactPacket.Header): __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLRespOpenSCManagerHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_return_code(self): return self.get_long(20, '<') def set_return_code(self, code): self.set_long(20, code, '<') def get_header_size(self): return SVCCTLRespOpenSCManagerHeader.__SIZE class SVCCTLOpenServiceHeader(ImpactPacket.Header): OP_NUM = 0x1C __SIZE = 48 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLOpenServiceHeader.__SIZE) self.set_max_count(9) self.set_cur_count(9) # Write some unknown fluff. self.get_bytes()[40:] = array.array('B', '\x00\x10\x48\x60\xff\x01\x0f\x00') if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_max_count(self): return self.get_long(20, '<') def set_max_count(self, num): self.set_long(20, num, '<') def get_offset(self): return self.get_long(24, '<') def set_offset(self, num): self.set_long(24, num, '<') def get_cur_count(self): return self.get_long(28, '<') def set_cur_count(self, num): self.set_long(28, num, '<') def get_service_name(self): return self.get_bytes().tostring()[32:40] def set_service_name(self, name): assert len(name) <= 8 self.get_bytes()[32:40] = array.array('B', name + (8 - len(name)) * '\x00') def get_header_size(self): return SVCCTLOpenServiceHeader.__SIZE class SVCCTLRespOpenServiceHeader(ImpactPacket.Header): __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLRespOpenServiceHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_return_code(self): return self.get_long(20, '<') def set_return_code(self, code): self.set_long(20, code, '<') def get_header_size(self): return SVCCTLRespOpenServiceHeader.__SIZE class SVCCTLCloseServiceHeader(ImpactPacket.Header): OP_NUM = 0x0 __SIZE = 20 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLCloseServiceHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:] = array.array('B', handle) def get_header_size(self): return SVCCTLCloseServiceHeader.__SIZE class SVCCTLRespCloseServiceHeader(ImpactPacket.Header): __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLRespCloseServiceHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_return_code(self): return self.get_long(20, '<') def set_return_code(self, code): self.set_long(20, code, '<') def get_header_size(self): return SVCCTLRespCloseServiceHeader.__SIZE class SVCCTLCreateServiceHeader(ImpactPacket.Header): OP_NUM = 0x18 __SIZE = 132 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLCreateServiceHeader.__SIZE) self.set_name_max_count(9) self.set_name_cur_count(9) self.set_service_flags(0x110) self.set_start_mode(2) self.get_bytes()[40:48] = array.array('B', '\x00\x10\x48\x60\xe4\xa3\x40\x00') self.get_bytes()[68:76] = array.array('B', '\x00\x00\x00\x00\xff\x01\x0f\x00') self.get_bytes()[84:88] = array.array('B', '\x01\x00\x00\x00') if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_name_max_count(self): return self.get_long(4, '<') def set_name_max_count(self, num): self.set_long(20, num, '<') self.set_long(48, num, '<') def get_name_offset(self): return self.get_long(8, '<') def set_name_offset(self, num): self.set_long(24, num, '<') self.set_long(52, num, '<') def get_name_cur_count(self): return self.get_long(12, '<') def set_name_cur_count(self, num): self.set_long(28, num, '<') self.set_long(56, num, '<') def get_service_name(self): return self.get_bytes().tostring()[32:40] def set_service_name(self, name): self.get_bytes()[32:40] = array.array('B', name + (8 - len(name)) * '\x00') self.get_bytes()[60:68] = array.array('B', name + (8 - len(name)) * '\x00') # 0x0000100 = Allow service to interact with desktop (needed by vnc server for example) # 0x0000010 = Log as: Local System Account def get_service_flags(self): return self.get_long(76, '<') def set_service_flags(self, flags): self.set_long(76, flags, '<') # 2 Automatic # 3 Manual # 4 Disabled def get_start_mode(self): return self.get_long(80, '<') def set_start_mode(self, mode): self.set_long(80, mode, '<') def get_path_max_count(self): return self.get_long(88, '<') def set_path_max_count(self, num): self.set_long(88, num, '<') def get_path_offset(self): return self.get_long(92, '<') def set_path_offset(self, num): self.set_long(92, num, '<') def get_path_cur_count(self): return self.get_long(96, '<') def set_path_cur_count(self, num): self.set_long(96, num, '<') def get_service_path(self): return self.get_bytes().tostring()[100:-32] def set_service_path(self, path): self.get_bytes()[100:-32] = array.array('B', path) self.set_path_max_count(len(path)+1) self.set_path_cur_count(len(path)+1) def get_header_size(self): var_size = len(self.get_bytes()) - SVCCTLCreateServiceHeader.__SIZE assert var_size > 0 return SVCCTLCreateServiceHeader.__SIZE + var_size class SVCCTLRespCreateServiceHeader(ImpactPacket.Header): __SIZE = 28 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLRespCreateServiceHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[4:24] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[4:24] = array.array('B', handle) def get_return_code(self): return self.get_long(24, '<') def set_return_code(self, code): self.set_long(24, code, '<') def get_header_size(self): return SVCCTLRespCreateServiceHeader.__SIZE class SVCCTLDeleteServiceHeader(ImpactPacket.Header): OP_NUM = 0x2 __SIZE = 20 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLDeleteServiceHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_header_size(self): return SVCCTLDeleteServiceHeader.__SIZE class SVCCTLRespDeleteServiceHeader(dcerpc.MSRPCHeader): __SIZE = 4 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLRespDeleteServiceHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_return_code(self): return self.get_long(0, '<') def set_return_code(self, code): self.set_long(0, code, '<') def get_header_size(self): return SVCCTLRespDeleteServiceHeader.__SIZE class SVCCTLStopServiceHeader(ImpactPacket.Header): OP_NUM = 0x1 __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLStopServiceHeader.__SIZE) # Write some unknown fluff. self.get_bytes()[20:] = array.array('B', '\x01\x00\x00\x00') if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_header_size(self): return SVCCTLStopServiceHeader.__SIZE class SVCCTLRespStopServiceHeader(ImpactPacket.Header): __SIZE = 32 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLRespStopServiceHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_return_code(self): return self.get_long(28, '<') def set_return_code(self, code): self.set_long(28, code, '<') def get_header_size(self): return SVCCTLRespStopServiceHeader.__SIZE class SVCCTLStartServiceHeader(ImpactPacket.Header): OP_NUM = 0x1F __SIZE = 32 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLStartServiceHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_arguments(self): raise Exception, "method not implemented" def set_arguments(self, arguments): args_data = apply(pack, ['<' + 'L'*len(arguments)] + map(id, arguments) ) args_data += reduce(lambda a, b: a+b, map(lambda element: pack('<LLL', len(element)+1, 0, len(element)+1) + element + '\x00' + '\x00' * ((4 - (len(element) + 1) % 4) % 4), arguments), '') data = pack('<LLL', len(arguments), id(arguments), len(arguments)) + args_data self.get_bytes()[20:] = array.array('B', data) def get_header_size(self): var_size = len(self.get_bytes()) - SVCCTLStartServiceHeader.__SIZE assert var_size > 0 return SVCCTLStartServiceHeader.__SIZE + var_size class SVCCTLRespStartServiceHeader(ImpactPacket.Header): __SIZE = 4 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SVCCTLRespStartServiceHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_return_code(self): return self.get_long(0, '<') def set_return_code(self, code): self.set_long(0, code, '<') def get_header_size(self): return SVCCTLRespStartServiceHeader.__SIZE class DCERPCSvcCtl: def __init__(self, dcerpc): self._dcerpc = dcerpc def open_manager(self): hostname = 'IMPACT' opensc = SVCCTLOpenSCManagerHeader() opensc.set_machine_name(hostname) self._dcerpc.send(opensc) data = self._dcerpc.recv() retVal = SVCCTLRespOpenSCManagerHeader(data) return retVal def create_service(self, context_handle, service_name, service_path): creates = SVCCTLCreateServiceHeader() creates.set_context_handle(context_handle) creates.set_service_name(service_name) creates.set_service_path(service_path) self._dcerpc.send(creates) data = self._dcerpc.recv() retVal = SVCCTLRespCreateServiceHeader(data) return retVal def close_handle(self, context_handle): closeh = SVCCTLCloseServiceHeader() closeh.set_context_handle(context_handle) self._dcerpc.send(closeh) data = self._dcerpc.recv() retVal = SVCCTLRespCloseServiceHeader(data) return retVal def delete_service(self, context_handle): deletes = SVCCTLDeleteServiceHeader() deletes.set_context_handle(context_handle) self._dcerpc.send(deletes) data = self._dcerpc.recv() retVal = SVCCTLRespDeleteServiceHeader(data) return retVal def open_service(self, context_handle, service_name): opens = SVCCTLOpenServiceHeader() opens.set_context_handle(context_handle) opens.set_service_name(service_name) self._dcerpc.send(opens) data = self._dcerpc.recv() retVal = SVCCTLRespOpenServiceHeader(data) return retVal def stop_service(self, context_handle): stops = SVCCTLStopServiceHeader() stops.set_context_handle(context_handle) self._dcerpc.send(stops) data = self._dcerpc.recv() retVal = SVCCTLRespStopServiceHeader(data) return retVal def start_service(self, context_handle, arguments): starts = SVCCTLStartServiceHeader() starts.set_arguments( arguments ) starts.set_context_handle(context_handle) self._dcerpc.send(starts) data = self._dcerpc.recv() retVal = SVCCTLRespStartServiceHeader(data) return retVal
15,833
Python
.py
379
34.424802
173
0.638162
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,949
dcerpc_v4.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/dcerpc_v4.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: dcerpc_v4.py,v 1.10 2006/05/23 22:26:51 gera Exp $ # # Description: # Handle basic DCE/RPC protocol, version 4. # import array import socket import struct from impacket import ImpactPacket from impacket import uuid import dcerpc, conv class MSRPCHeader(ImpactPacket.Header): __SIZE = 80 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, MSRPCHeader.__SIZE) self.set_version(4) self.set_type(dcerpc.MSRPC_REQUEST) self.set_flags((0x08, 0x00)) self.set_representation((0x10, 0x00, 0x00)) self.set_serial((0, 0)) ## self.set_if_version(3) self.set_seq_num(0) self.set_if_hint(0xFFFF) self.set_activity_hint(0xFFFF) if aBuffer: self.load_header(aBuffer) def get_version(self): return self.get_byte(0) def set_version(self, version): self.set_byte(0, version) def get_type(self): return self.get_byte(1) def set_type(self, type): self.set_byte(1, type) def get_flags(self): """ This method returns a tuple in (flags1, flags2) form.""" return (self.get_byte(2), self.get_byte(3)) def set_flags(self, flags): """ This method takes a tuple in (flags1, flags2) form.""" self.set_byte(2, flags[0]) self.set_byte(3, flags[1]) def get_representation(self): """ This method returns a tuple in (major, minor) form.""" return (self.get_byte(4), self.get_byte(5), self.get_byte(6)) def set_representation(self, representation): """ This method takes a tuple in (major, minor) form.""" self.set_byte(4, representation[0]) self.set_byte(5, representation[1]) self.set_byte(6, representation[1]) def get_serial(self): """ This method returns a tuple in (high, low) form.""" return (self.get_byte(7), self.get_byte(79)) def set_serial(self, serial): """ This method takes a tuple in (high, low) form.""" self.set_byte(7, serial[0]) self.set_byte(79, serial[1]) def get_obj_binuuid(self): return self.get_bytes().tolist()[8:8+16] def set_obj_binuuid(self, binuuid): assert 16 == len(binuuid) self.get_bytes()[8:8+16] = array.array('B', binuuid) def get_if_binuuid(self): return self.get_bytes().tolist()[24:24+16] def set_if_binuuid(self, binuuid): assert 16 == len(binuuid) self.get_bytes()[24:24+16] = array.array('B', binuuid) def get_activity_binuuid(self): return self.get_bytes().tolist()[40:40+16] def set_activity_binuuid(self, binuuid): assert 16 == len(binuuid) self.get_bytes()[40:40+16] = array.array('B', binuuid) def get_server_boottime(self): return self.get_long(56, '<') def set_server_boottime(self, time): self.set_long(56, time, '<') def get_if_version(self): return self.get_long(60, '<') def set_if_version(self, version): self.set_long(60, version, '<') def get_seq_num(self): return self.get_long(64, '<') def set_seq_num(self, num): self.set_long(64, num, '<') def get_op_num(self): return self.get_word(68, '<') def set_op_num(self, op): self.set_word(68, op, '<') def get_if_hint(self): return self.get_word(70, '<') def set_if_hint(self, hint): self.set_word(70, hint, '<') def get_activity_hint(self): return self.get_word(72, '<') def set_activity_hint(self, hint): self.set_word(72, hint, '<') def get_frag_len(self): return self.get_word(74, '<') def set_frag_len(self, len): self.set_word(74, len, '<') def get_frag_num(self): return self.get_word(76, '<') def set_frag_num(self, num): self.set_word(76, num, '<') def get_auth_proto(self): return self.get_byte(78) def set_auth_proto(self, proto): self.set_byte(78, proto) def get_header_size(self): return MSRPCHeader.__SIZE def contains(self, aHeader): ImpactPacket.Header.contains(self, aHeader) if self.child(): contents_size = self.child().get_size() self.set_op_num(self.child().OP_NUM) self.set_frag_len(contents_size) def get_ctx_id(self): # return self.get_word(20, '<') return 0 def set_ctx_id(self, id): # self.set_word(20, id, '<') pass class DCERPC_v4(dcerpc.DCERPC): DEFAULT_FRAGMENT_SIZE = 1392 def __init__(self, transport): dcerpc.DCERPC.__init__(self, transport) self.__activity_uuid = uuid.generate() self.__seq_num = 0 self._bind = 0 # Don't attempt binding unless it explicitly requested. self.set_idempotent(0) def set_default_max_fragment_size(self): self.set_max_fragment_size(DCERPC_v4.DEFAULT_FRAGMENT_SIZE) def bind(self, uuid, bogus_binds = ''): """If idempotent is non-zero, the package will be sent with that flag enabled. Certain services react by skiping the CONV phase during the binding. """ self._bind = 1 # Will bind later, when the first packet is transferred. self.__if_uuid = uuid[:16] self.__if_version = struct.unpack('<L', uuid[16:20])[0] def get_idempotent(self): return self.__idempotent def set_idempotent(self, flag): self.__idempotent = flag def conv_bind(self): # Receive CONV handshake. # ImpactDecode: this block. data = self._transport.recv() rpc = MSRPCHeader(data) activity_uuid = rpc.get_activity_binuuid() _conv = conv.WhoAreYou(data[rpc.get_header_size():]) # ImpactDecode rpc = MSRPCHeader() rpc.set_type(dcerpc.MSRPC_RESPONSE) rpc.set_if_binuuid(conv.MSRPC_UUID_CONV) flags = rpc.get_flags() rpc.set_flags((flags[0], 0x04)) rpc.set_activity_binuuid(activity_uuid) _conv = conv.WhoAreYou2() rpc.contains(_conv) # The CONV response must be sent to the endpoint from where the request was received. old_address = self._transport.get_addr() peer_address = self._transport.get_recv_addr() self._transport.set_addr(peer_address) self._transport.send(rpc.get_packet()) self._transport.set_addr(old_address) def send(self, data): packet = data.get_packet() frag_num = 0 rpc = MSRPCHeader() self.set_ctx_id(self._ctx) rpc.set_if_binuuid(self.__if_uuid) rpc.set_if_version(self.__if_version) rpc.set_activity_binuuid(self.__activity_uuid) rpc.set_seq_num(self.__seq_num) frag = dcerpc.DCERPC_RawCall(data.OP_NUM) if self._max_frag: offset = 0 while 1: toSend = packet[offset:offset+self._max_frag] if not toSend: break flags = dcerpc.MSRPC_NOTAFRAG | dcerpc.MSRPC_RECRESPOND if self.__idempotent: flags |= dcerpc.MSRPC_NOTFORIDEMP offset += len(toSend) if offset == len(packet): flags |= dcerpc.MSRPC_LASTFRAG rpc.set_flags((flags, 0)) frag.setData(toSend) rpc.contains(frag) rpc.set_frag_num(frag_num) self._transport.send(rpc.get_packet()) frag_num += 1 if self._bind and not self.__idempotent: self._bind = 0 self.conv_bind() self.recv() # Discard RPC_ACK. else: if self.__idempotent: rpc.set_flags((dcerpc.MSRPC_NOTFORIDEMP, 0)) rpc.contains(data) self._transport.send(rpc.get_packet()) if self._bind and not self.__idempotent: self._bind = 0 self.conv_bind() self.recv() # Discard RPC_ACK. self.__seq_num += 1 def recv(self): data = self._transport.recv() rpc = MSRPCHeader(data) off = rpc.get_header_size() return data[off:]
8,418
Python
.py
214
30.799065
93
0.596934
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,950
dcerpc.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/dcerpc.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: dcerpc.py,v 1.7 2006/05/23 22:26:51 gera Exp $ # import array from binascii import crc32 try: from Crypto.Cipher import ARC4 from Crypto.Hash import MD4 POW = None except Exception: try: import POW except Exception: print "WARNING: Crypto package not found. Some features will fail." from impacket import ntlm from impacket import ImpactPacket from impacket.structure import Structure,pack,unpack # MS/RPC Constants MSRPC_REQUEST = 0x00 MSRPC_RESPONSE = 0x02 MSRPC_FAULT = 0x03 MSRPC_ACK = 0x07 MSRPC_BIND = 0x0B MSRPC_BINDACK = 0x0C MSRPC_BINDNAK = 0x0D MSRPC_ALTERCTX = 0x0E MSRPC_AUTH3 = 0x10 # MS/RPC Packet Flags MSRPC_FIRSTFRAG = 0x01 MSRPC_LASTFRAG = 0x02 MSRPC_NOTAFRAG = 0x04 MSRPC_RECRESPOND= 0x08 MSRPC_NOMULTIPLEX = 0x10 MSRPC_NOTFORIDEMP = 0x20 MSRPC_NOTFORBCAST = 0x40 MSRPC_NOUUID = 0x80 #Reasons for rejection of a context element, included in bind_ack result reason rpc_provider_reason = { 0 : 'reason_not_specified', 1 : 'abstract_syntax_not_supported', 2 : 'proposed_transfer_syntaxes_not_supported', 3 : 'local_limit_exceeded' } MSRPC_CONT_RESULT_ACCEPT = 0 MSRPC_CONT_RESULT_USER_REJECT = 1 MSRPC_CONT_RESULT_PROV_REJECT = 2 #Results of a presentation context negotiation rpc_cont_def_result = { 0 : 'acceptance', 1 : 'user_rejection', 2 : 'provider_rejection' } #status codes, references: #http://msdn.microsoft.com/library/default.asp?url=/library/en-us/rpc/rpc/rpc_return_values.asp #http://msdn.microsoft.com/library/default.asp?url=/library/en-us/randz/protocol/common_return_values.asp #winerror.h #http://www.opengroup.org/onlinepubs/9629399/apdxn.htm rpc_status_codes = { 0x00000005L : 'rpc_s_access_denied', 0x00000008L : 'Authentication type not recognized', 0x000006C6L : 'rpc_x_invalid_bound', # the arrays bound are invalid 0x000006F7L : 'rpc_x_bad_stub_data', # the stub data is invalid, doesn't match with the IDL definition 0x1C010001L : 'nca_s_comm_failure', # unable to get response from server: 0x1C010002L : 'nca_s_op_rng_error', # bad operation number in call 0x1C010003L : 'nca_s_unk_if', # unknown interface 0x1C010006L : 'nca_s_wrong_boot_time', # client passed server wrong server boot time 0x1C010009L : 'nca_s_you_crashed', # a restarted server called back a client 0x1C01000BL : 'nca_s_proto_error', # someone messed up the protocol 0x1C010013L : 'nca_s_out_args_too_big ', # output args too big 0x1C010014L : 'nca_s_server_too_busy', # server is too busy to handle call 0x1C010015L : 'nca_s_fault_string_too_long', # string argument longer than declared max len 0x1C010017L : 'nca_s_unsupported_type ', # no implementation of generic operation for object 0x1C000001L : 'nca_s_fault_int_div_by_zero', 0x1C000002L : 'nca_s_fault_addr_error ', 0x1C000003L : 'nca_s_fault_fp_div_zero', 0x1C000004L : 'nca_s_fault_fp_underflow', 0x1C000005L : 'nca_s_fault_fp_overflow', 0x1C000006L : 'nca_s_fault_invalid_tag', 0x1C000007L : 'nca_s_fault_invalid_bound ', 0x1C000008L : 'nca_s_rpc_version_mismatch', 0x1C000009L : 'nca_s_unspec_reject ', 0x1C00000AL : 'nca_s_bad_actid', 0x1C00000BL : 'nca_s_who_are_you_failed', 0x1C00000CL : 'nca_s_manager_not_entered ', 0x1C00000DL : 'nca_s_fault_cancel', 0x1C00000EL : 'nca_s_fault_ill_inst', 0x1C00000FL : 'nca_s_fault_fp_error', 0x1C000010L : 'nca_s_fault_int_overflow', 0x1C000012L : 'nca_s_fault_unspec', 0x1C000013L : 'nca_s_fault_remote_comm_failure ', 0x1C000014L : 'nca_s_fault_pipe_empty ', 0x1C000015L : 'nca_s_fault_pipe_closed', 0x1C000016L : 'nca_s_fault_pipe_order ', 0x1C000017L : 'nca_s_fault_pipe_discipline', 0x1C000018L : 'nca_s_fault_pipe_comm_error', 0x1C000019L : 'nca_s_fault_pipe_memory', 0x1C00001AL : 'nca_s_fault_context_mismatch ', 0x1C00001BL : 'nca_s_fault_remote_no_memory ', 0x1C00001CL : 'nca_s_invalid_pres_context_id', 0x1C00001DL : 'nca_s_unsupported_authn_level', 0x1C00001FL : 'nca_s_invalid_checksum ', 0x1C000020L : 'nca_s_invalid_crc', 0x1C000021L : 'nca_s_fault_user_defined', 0x1C000022L : 'nca_s_fault_tx_open_failed', 0x1C000023L : 'nca_s_fault_codeset_conv_error', 0x1C000024L : 'nca_s_fault_object_not_found ', 0x1C000025L : 'nca_s_fault_no_client_stub' } class MSRPCArray: def __init__(self, id=0, len=0, size=0): self._length = len self._size = size self._id = id self._max_len = 0 self._offset = 0 self._length2 = 0 self._name = '' def set_max_len(self, n): self._max_len = n def set_offset(self, n): self._offset = n def set_length2(self, n): self._length2 = n def get_size(self): return self._size def set_name(self, n): self._name = n def get_name(self): return self._name def get_id(self): return self._id def rawData(self): return pack('<HHLLLL', self._length, self._size, 0x12345678, self._max_len, self._offset, self._length2) + self._name.encode('utf-16le') class MSRPCNameArray: def __init__(self, data = None): self._count = 0 self._max_count = 0 self._elements = [] if data: self.load(data) def load(self, data): ptr = unpack('<L', data[:4])[0] index = 4 if 0 == ptr: # No data. May be a bug in certain versions of Samba. return self._count, _, self._max_count = unpack('<LLL', data[index:index+12]) index += 12 # Read each object's header. for i in range(0, self._count): aindex, length, size, _ = unpack('<LHHL', data[index:index+12]) self._elements.append(MSRPCArray(aindex, length, size)) index += 12 # Read the objects themselves. for element in self._elements: max_len, offset, curlen = unpack('<LLL', data[index:index+12]) index += 12 element.set_name(unicode(data[index:index+2*curlen], 'utf-16le')) element.set_max_len(max_len) element.set_offset(offset) element.set_length2(curlen) index += 2*curlen if curlen & 0x1: index += 2 # Skip padding. def elements(self): return self._elements def rawData(self): ret = pack('<LLLL', 0x74747474, self._count, 0x47474747, self._max_count) pos_ret = [] for i in xrange(0, self._count): ret += pack('<L', self._elements[i].get_id()) data = self._elements[i].rawData() ret += data[:8] pos_ret += data[8:] return ret + pos_ret class MSRPCHeader(ImpactPacket.Header): _SIZE = 16 commonHdr = ( # not used, just for doc and future use ('ver_major','B'), # 0 ('ver_minor','B'), # 1 ('type','B=MSRPC_REQUEST'), # 2 ('flags','B=MSRPC_FIRSTFRAG | MSRPC_LASTFRAG'), # 3 ('represntation','<L=0x10'), # 4 ('frag_len','<H=24+len(data)+len(auth_data)'), # 8 ('auth_len','<H=len(auth_data)-8'), # 10 ('call_id','<L=1'), # 12 <-- Common up to here (including this) ) structure = ( # not used, just for documentation and future use ('data',':'), # 24 ('auth_data',':'), ) def __init__(self, aBuffer = None, endianness = '<'): ImpactPacket.Header.__init__(self, self._SIZE) self.endianness = endianness self.set_version((5, 0)) self.set_flags(MSRPC_FIRSTFRAG | MSRPC_LASTFRAG) if endianness == '<': self.set_representation(0x10) else: self.set_representation(0x0) self.__frag_len_set = 0 self.set_auth_len(0) self.set_call_id(1) self.set_auth_data('') if aBuffer: self.load_header(aBuffer) def get_version(self): """ This method returns a tuple in (major, minor) form.""" return (self.get_byte(0), self.get_byte(1)) def set_version(self, version): """ This method takes a tuple in (major, minor) form.""" self.set_byte(0, version[0]) self.set_byte(1, version[1]) def get_type(self): return self.get_byte(2) def set_type(self, type): self.set_byte(2, type) def get_flags(self): return self.get_byte(3) def set_flags(self, flags): self.set_byte(3, flags) def get_representation(self): return self.get_long(4, self.endianness) def set_representation(self, representation): self.set_long(4, representation, self.endianness) def get_frag_len(self): return self.get_word(8, self.endianness) def set_frag_len(self, len): self.__frag_len_set == 1 self.set_word(8, len, self.endianness) def get_auth_len(self): return self.get_word(10, self.endianness) def set_auth_len(self, len): self.set_word(10, len, self.endianness) def set_auth_data(self, data): self._auth_data = data def get_call_id(self): return self.get_long(12, self.endianness) def set_call_id(self, id): self.set_long(12, id, self.endianness) def get_header_size(self): return self._SIZE def contains(self, aHeader): ImpactPacket.Header.contains(self, aHeader) if self.child(): self.set_op_num(self.child().OP_NUM) def set_alloc_hint(self, hint): pass def get_packet(self): if self._auth_data: self.set_auth_len(len(self._auth_data)-8) if self.child(): contents_size = self.child().get_size() else: contents_size = 0 contents_size += len(self._auth_data) if not self.__frag_len_set: self.set_frag_len(self.get_header_size() + contents_size) self.set_alloc_hint(contents_size) return ImpactPacket.Header.get_packet(self)+self._auth_data class MSRPCRequestHeader(MSRPCHeader): _SIZE = 24 structure = ( # not used, just for documentation and future use ('alloc_hint','<L=frag_len'), # 16 ('ctx_id','<H=0'), # 20 ('op_num','<H'), # 22 ('data',':'), # 24 ('auth_data',':'), ) def __init__(self, aBuffer = None, endianness = '<'): MSRPCHeader.__init__(self, aBuffer = aBuffer, endianness = endianness) self.set_type(MSRPC_REQUEST) self.set_ctx_id(0) self.set_alloc_hint(0) def get_alloc_hint(self): return self.get_long(16, self.endianness) def set_alloc_hint(self, len): self.set_long(16, len, self.endianness) def get_ctx_id(self): return self.get_word(20, self.endianness) def set_ctx_id(self, id): self.set_word(20, id, self.endianness) def get_op_num(self): return self.get_word(22, self.endianness) def set_op_num(self, op): self.set_word(22, op, self.endianness) class MSRPCRespHeader(MSRPCHeader): _SIZE = 24 structure = ( # not used, just for documentation and future use ('alloc_hint','<L=frag_len'), # 16 <-- Common up to here (including this) ('ctx_id','<H=0'), # 20 ('cancel_count','<B'), # 22 ('padding','<B=0'), # 23 ('data',':'), # 24 ('auth_data',':'), ) def __init__(self, aBuffer = None, endianness = '<'): MSRPCHeader.__init__(self, aBuffer = aBuffer, endianness = endianness) self.set_type(MSRPC_RESPONSE) self.set_ctx_id(0) self.set_alloc_hint(0) def get_alloc_hint(self): return self.get_long(16, self.endianness) def set_alloc_hint(self, len): self.set_long(16, len, self.endianness) def get_ctx_id(self): return self.get_word(20, self.endianness) def set_ctx_id(self, id): self.set_word(20, id, self.endianness) def get_cancel_count(self): return self.get_byte(22) class MSRPCBind(MSRPCHeader): _SIZE = 72-44 structure = ( # not used, just for documentation and future use ('max_tfrag','<H=4280'), ('max_rfrag','<H=4280'), ('assoc_group','<L=0'), ('ctx_num','B'), ) def __init__(self, aBuffer = None, endianness = '<'): MSRPCHeader.__init__(self, aBuffer = aBuffer, endianness = endianness) self.set_type(MSRPC_BIND) self.set_max_tfrag(4280) self.set_max_rfrag(4280) self.set_assoc_group(0) self.set_ctx_num(1) def get_max_tfrag(self): return self.get_word(16, self.endianness) def set_max_tfrag(self, size): self.set_word(16, size, self.endianness) def get_max_rfrag(self): return self.get_word(18, self.endianness) def set_max_rfrag(self, size): self.set_word(18, size, self.endianness) def get_assoc_group(self): return self.get_long(20, self.endianness) def set_assoc_group(self, id): self.set_long(20, id, self.endianness) def get_ctx_num(self): return self.get_byte(24) def set_ctx_num(self, num): self._SIZE = 28+num*44 self.set_byte(24, num) # --- next fields repeated for each interface to bind to def get_ctx_id(self, index = 0): return self.get_word(28+44*index, self.endianness) def set_ctx_id(self, id, index = 0): self.set_word(28+44*index, id, self.endianness) def get_trans_num(self, index = 0): return self.get_byte(30+44*index) def set_trans_num(self, op, index = 0): self.set_byte(30+44*index, op) self.set_byte(31+44*index, 0) def get_if_binuuid(self, index = 0): return self.get_bytes().tolist()[32+44*index:32+44*index+16] def set_if_binuuid(self, binuuid, index = 0): self.get_bytes()[32+44*index:32+len(binuuid)+44*index] = array.array('B', binuuid) def set_if_ver(self,ver,minor, index = 0): self.set_word(48+44*index, ver, self.endianness) self.set_word(50+44*index, minor, self.endianness) def get_if_ver(self, index = 0): return self.get_word(48+44*index, self.endianness) def get_if_ver_minor(self, index = 0): return self.get_word(50+44*index, self.endianness) def get_xfer_syntax_binuuid(self, index = 0): return self.get_bytes().tolist()[52+44*index:52+44*index+16] def set_xfer_syntax_binuuid(self, binuuid, index = 0): self.get_bytes()[52+44*index:52+len(binuuid)+44*index] = array.array('B', binuuid) def set_xfer_syntax_ver(self,ver, index = 0): self.set_long(68+44*index, ver, self.endianness) def get_xfer_syntax_ver(self, index = 0): self.get_long(68+44*index, ver, self.endianness) class MSRPCBindAck(ImpactPacket.Header): _SIZE = 56 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, self._SIZE) self.set_type(MSRPC_BINDACK) if aBuffer: self.load_header(aBuffer) def get_version(self): """ This method returns a tuple in (major, minor) form.""" return (self.get_byte(0), self.get_byte(1)) def set_version(self, version): """ This method takes a tuple in (major, minor) form.""" self.set_byte(0, version[0]) self.set_byte(1, version[1]) def get_type(self): return self.get_byte(2) def set_type(self, type): self.set_byte(2, type) def get_flags(self): return self.get_byte(3) def set_flags(self, flags): self.set_byte(3, flags) def get_representation(self): return self.get_long(4, '<') def set_representation(self, representation): self.set_long(4, representation, '<') def get_frag_len(self): return self.get_word(8, '<') def set_frag_len(self, len): self.set_word(8, len, '<') def get_auth_len(self): return self.get_word(10, '<') def set_auth_len(self, len): self.set_word(10, len, '<') def get_auth_data(self): data = self.get_bytes() return data[-self.get_auth_len()-8:] def get_call_id(self): return self.get_long(12, '<') def set_call_id(self, id): self.set_long(12, id, '<') def get_max_tfrag(self): return self.get_word(16, '<') def set_max_tfrag(self, size): self.set_word(16, size, '<') def get_max_rfrag(self): return self.get_word(18, '<') def set_max_rfrag(self, size): self.set_word(18, size, '<') def get_assoc_group(self): return self.get_long(20, '<') def set_assoc_group(self, id): self.set_long(20, id, '<') def get_secondary_addr_len(self): return self.get_word(24, '<') def set_secondary_addr_len(self, len): self.set_word(24, len, '<') def get_secondary_addr(self): return self.get_bytes().tolist()[26:26+self.get_secondary_addr_len()] def set_secondary_addr(self, addr): self.get_bytes()[26:26+self.get_secondary_addr_len()] = array.array('B', addr) self.set_secondary_addr_len(len(addr)) def _get_results_offset(self): answer = 26+self.get_secondary_addr_len() answer +=3 answer -= answer % 4 return answer+2 def get_results_num(self): return self.get_byte(self._get_results_offset()-2) def set_results_num(self, num): self.set_byte(self._get_results_offset()-2, num) def get_result(self, index = 0): return self.get_word(self._get_results_offset()+2*index, '<' ) def set_result(self, res, index = 0): self.set_word(self._get_results_offset()+2*index, '<' ) def get_xfer_syntax_binuuid(self): return self.get_bytes().tolist()[-20:] def set_xfer_syntax_binuuid(self, binuuid): assert 20 == len(binuuid) self.get_bytes()[-20:] = array.array('B', binuuid) def get_header_size(self): var_size = len(self.get_bytes()) - self._SIZE # assert var_size > 0 return self._SIZE + var_size def contains(self, aHeader): ImpactPacket.Header.contains(self, aHeader) if self.child(): contents_size = self.child().get_size() self.set_op_num(self.child().OP_NUM) self.set_frag_len(self.get_header_size() + contents_size) self.set_alloc_hint(contents_size) class MSRPCBindNak(ImpactPacket.Header): _SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, self._SIZE) self.set_type(MSRPC_BINDNAK) if aBuffer: self.load_header(aBuffer) def get_version(self): """ This method returns a tuple in (major, minor) form.""" return (self.get_byte(0), self.get_byte(1)) def set_version(self, version): """ This method takes a tuple in (major, minor) form.""" self.set_byte(0, version[0]) self.set_byte(1, version[1]) def get_type(self): return self.get_byte(2) def set_type(self, type): self.set_byte(2, type) def get_flags(self): return self.get_byte(3) def set_flags(self, flags): self.set_byte(3, flags) def get_representation(self): return self.get_long(4, '<') def set_representation(self, representation): self.set_long(4, representation, '<') def get_frag_len(self): return self.get_word(8, '<') def set_frag_len(self, len): self.set_word(8, len, '<') def get_auth_len(self): return self.get_word(10, '<') def set_auth_len(self, len): self.set_word(10, len, '<') def get_call_id(self): return self.get_long(12, '<') def set_call_id(self, id): self.set_long(12, id, '<') def get_reason(self): return self.get_word(16, '<') def set_reason(self, reason): self.set_word(16, reason, '<') def get_assoc_group(self): return self.get_long(20, '<') def set_assoc_group(self, id): self.set_long(20, id, '<') def get_header_size(self): return self._SIZE class DCERPC: _max_ctx = 0 def __init__(self,transport): self._transport = transport self.set_ctx_id(0) self._max_frag = None self.set_default_max_fragment_size() def set_ctx_id(self, ctx_id): self._ctx = ctx_id def connect(self): return self._transport.connect() def disconnect(self): return self._transport.disconnect() def set_max_fragment_size(self, fragment_size): # -1 is default fragment size: 0 for v5, 1300 y pico for v4 # 0 is don't fragment # other values are max fragment size if fragment_size == -1: self.set_default_max_fragment_size() else: self._max_frag = fragment_size def set_default_max_fragment_size(self): # default is 0: don'fragment. v4 will override this method self._max_frag = 0 def send(self, data): raise RuntimeError, 'virtual method. Not implemented in subclass' def recv(self): raise RuntimeError, 'virtual method. Not implemented in subclass' def alter_ctx(self, newUID, bogus_binds = ''): raise RuntimeError, 'virtual method. Not implemented in subclass' def set_credentials(self, username, password): pass def set_auth_level(self, auth_level): pass def get_idempotent(self): return 0 def set_idempotent(self, flag): pass def call(self, function, body): return self.send(DCERPC_RawCall(function, str(body))) class DCERPC_v5(DCERPC): endianness = '<' def __init__(self, transport): DCERPC.__init__(self, transport) self.__auth_level = ntlm.NTLM_AUTH_NONE self.__username = None self.__password = None def set_auth_level(self, auth_level): # auth level is ntlm.NTLM_AUTH_* self.__auth_level = auth_level def set_credentials(self, username, password): self.set_auth_level(ntlm.NTLM_AUTH_CONNECT) # self.set_auth_level(ntlm.NTLM_AUTH_CALL) # self.set_auth_level(ntlm.NTLM_AUTH_PKT_INTEGRITY) # self.set_auth_level(ntlm.NTLM_AUTH_PKT_PRIVACY) self.__username = username self.__password = password def bind(self, uuid, alter = 0, bogus_binds = 0): bind = MSRPCBind(endianness = self.endianness) syntax = '\x04\x5d\x88\x8a\xeb\x1c\xc9\x11\x9f\xe8\x08\x00\x2b\x10\x48\x60' if self.endianness == '>': syntax = unpack('<LHHBB6s', syntax) syntax = pack('>LHHBB6s', *syntax) uuid = list(unpack('<LHHBB6sHH', uuid)) uuid[-1] ^= uuid[-2] uuid[-2] ^= uuid[-1] uuid[-1] ^= uuid[-2] uuid = pack('>LHHBB6sHH', *uuid) ctx = 0 for i in range(bogus_binds): bind.set_ctx_id(self._ctx, index = ctx) bind.set_trans_num(1, index = ctx) bind.set_if_binuuid('A'*20, index = ctx) bind.set_xfer_syntax_binuuid(syntax, index = ctx) bind.set_xfer_syntax_ver(2, index = ctx) self._ctx += 1 ctx += 1 bind.set_ctx_id(self._ctx, index = ctx) bind.set_trans_num(1, index = ctx) bind.set_if_binuuid(uuid,index = ctx) bind.set_xfer_syntax_binuuid(syntax, index = ctx) bind.set_xfer_syntax_ver(2, index = ctx) bind.set_ctx_num(ctx+1) if alter: bind.set_type(MSRPC_ALTERCTX) if (self.__auth_level != ntlm.NTLM_AUTH_NONE): if (self.__username is None) or (self.__password is None): self.__username, self.__password, nth, lmh = self._transport.get_credentials() auth = ntlm.NTLMAuthNegotiate() auth['auth_level'] = self.__auth_level auth['auth_ctx_id'] = self._ctx + 79231 bind.set_auth_data(str(auth)) self._transport.send(bind.get_packet()) s = self._transport.recv() if s != 0: resp = MSRPCBindAck(s) else: return 0 #mmm why not None? if resp.get_type() == MSRPC_BINDNAK: resp = MSRPCBindNak(s) status_code = resp.get_reason() if rpc_status_codes.has_key(status_code): raise Exception(rpc_status_codes[status_code], resp) else: raise Exception('Unknown DCE RPC fault status code: %.8x' % status_code, resp) self.__max_xmit_size = resp.get_max_tfrag() if self.__auth_level != ntlm.NTLM_AUTH_NONE: authResp = ntlm.NTLMAuthChallenge(data = resp.get_auth_data().tostring()) self._ntlm_challenge = authResp['challenge'] response = ntlm.NTLMAuthChallengeResponse(self.__username,self.__password, self._ntlm_challenge) response['auth_ctx_id'] = self._ctx + 79231 response['auth_level'] = self.__auth_level if self.__auth_level in (ntlm.NTLM_AUTH_CONNECT, ntlm.NTLM_AUTH_PKT_INTEGRITY, ntlm.NTLM_AUTH_PKT_PRIVACY): if self.__password: key = ntlm.compute_nthash(self.__password) if POW: hash = POW.Digest(POW.MD4_DIGEST) else: hash = MD4.new() hash.update(key) key = hash.digest() else: key = '\x00'*16 if POW: cipher = POW.Symmetric(POW.RC4) cipher.encryptInit(key) self.cipher_encrypt = cipher.update else: cipher = ARC4.new(key) self.cipher_encrypt = cipher.encrypt if response['flags'] & ntlm.NTLMSSP_KEY_EXCHANGE: session_key = 'A'*16 # XXX Generate random session key response['session_key'] = self.cipher_encrypt(session_key) if POW: cipher = POW.Symmetric(POW.RC4) cipher.encryptInit(session_key) self.cipher_encrypt = cipher.update else: cipher = ARC4.new(session_key) self.cipher_encrypt = cipher.encrypt self.sequence = 0 auth3 = MSRPCHeader() auth3.set_type(MSRPC_AUTH3) auth3.set_auth_data(str(response)) self._transport.send(auth3.get_packet(), forceWriteAndx = 1) return resp # means packet is signed, if verifier is wrong it fails def _transport_send(self, rpc_packet, forceWriteAndx = 0, forceRecv = 0): if self.__auth_level == ntlm.NTLM_AUTH_CALL: if rpc_packet.get_type() == MSRPC_REQUEST: response = ntlm.NTLMAuthChallengeResponse(self.__username,self.__password, self._ntlm_challenge) response['auth_ctx_id'] = self._ctx + 79231 response['auth_level'] = self.__auth_level rpc_packet.set_auth_data(str(response)) if self.__auth_level in [ntlm.NTLM_AUTH_PKT_INTEGRITY, ntlm.NTLM_AUTH_PKT_PRIVACY]: verifier = ntlm.NTLMAuthVerifier() verifier['auth_level'] = self.__auth_level verifier['auth_ctx_id'] = self._ctx + 79231 verifier['data'] = ' '*12 rpc_packet.set_auth_data(str(verifier)) rpc_call = rpc_packet.child() if self.__auth_level == ntlm.NTLM_AUTH_PKT_PRIVACY: data = DCERPC_RawCall(rpc_call.OP_NUM) data.setData(self.cipher_encrypt(rpc_call.get_packet())) rpc_packet.contains(data) crc = crc32(rpc_call.get_packet()) data = pack('<LLL',0,crc,self.sequence) # XXX 0 can be anything: randomize data = self.cipher_encrypt(data) verifier['data'] = data rpc_packet.set_auth_data(str(verifier)) self.sequence += 1 self._transport.send(rpc_packet.get_packet(), forceWriteAndx = forceWriteAndx, forceRecv = forceRecv) def send(self, data): # This endianness does necesary have to be the same as the one used in the bind # however, the endianness of the stub data MUST be the same as the one in the bind # i.e. the endianness on the next call could be hardcoded to any rpc = MSRPCRequestHeader(endianness = self.endianness) rpc.set_ctx_id(self._ctx) max_frag = self._max_frag if data.get_size() > self.__max_xmit_size - 32: max_frag = self.__max_xmit_size - 32 # XXX: 32 is a safe margin for auth data if self._max_frag: max_frag = min(max_frag, self._max_frag) if max_frag: packet = str(data.get_bytes().tostring()) offset = 0 rawcall = DCERPC_RawCall(data.OP_NUM) while 1: toSend = packet[offset:offset+max_frag] if not toSend: break flags = 0 if offset == 0: flags |= MSRPC_FIRSTFRAG offset += len(toSend) if offset == len(packet): flags |= MSRPC_LASTFRAG rpc.set_flags(flags) rawcall.setData(toSend) rpc.contains(rawcall) self._transport_send(rpc, forceWriteAndx = 1, forceRecv = flags & MSRPC_LASTFRAG) else: rpc.contains(data) self._transport_send(rpc) def recv(self): self.response_data = self._transport.recv() self.response_header = MSRPCRespHeader(self.response_data) off = self.response_header.get_header_size() if self.response_header.get_type() == MSRPC_FAULT and self.response_header.get_frag_len() >= off+4: status_code = unpack("<L",self.response_data[off:off+4])[0] if rpc_status_codes.has_key(status_code): raise Exception(rpc_status_codes[status_code]) else: raise Exception('Unknown DCE RPC fault status code: %.8x' % status_code) answer = self.response_data[off:] auth_len = self.response_header.get_auth_len() if auth_len: auth_len += 8 auth_data = answer[-auth_len:] ntlmssp = ntlm.NTLMAuthHeader(data = auth_data) answer = answer[:-auth_len] if ntlmssp['auth_level'] == ntlm.NTLM_AUTH_PKT_PRIVACY: answer = self.cipher_encrypt(answer) if ntlmssp['auth_pad_len']: answer = answer[:-ntlmssp['auth_pad_len']] if ntlmssp['auth_level'] in [ntlm.NTLM_AUTH_PKT_INTEGRITY, ntlm.NTLM_AUTH_PKT_PRIVACY]: ntlmssp = ntlm.NTLMAuthVerifier(data = auth_data) data = self.cipher_encrypt(ntlmssp['data']) zero, crc, sequence = unpack('<LLL', data) self.sequence = sequence + 1 return answer def alter_ctx(self, newUID, bogus_binds = 0): answer = self.__class__(self._transport) answer.set_credentials(self.__username, self.__password) answer.set_auth_level(self.__auth_level) self._max_ctx += 1 answer.set_ctx_id(self._max_ctx) answer.bind(newUID, alter = 1, bogus_binds = bogus_binds) return answer class DCERPC_RawCall(ImpactPacket.Header): def __init__(self, op_num, data = ''): self.OP_NUM = op_num ImpactPacket.Header.__init__(self) self.setData(data) def setData(self, data): self.get_bytes()[:] = array.array('B', data) def get_header_size(self): return len(self.get_bytes())
32,566
Python
.py
750
34.718667
144
0.592478
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,951
transport.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/transport.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: transport.py,v 1.5 2006/05/23 21:19:26 gera Exp $ # # Description: # Transport implementations for the DCE/RPC protocol. # import re import socket from impacket import smb from impacket import nmb from impacket.structure import pack from impacket.dcerpc import dcerpc, dcerpc_v4 class DCERPCStringBinding: parser = re.compile(r'(?:([a-fA-F0-9-]{8}(?:-[a-fA-F0-9-]{4}){3}-[a-fA-F0-9-]{12})@)?' # UUID (opt.) +'([_a-zA-Z0-9]*):' # Protocol Sequence +'([^\[]*)' # Network Address (opt.) +'(?:\[([^\]]*)\])?') # Endpoint and options (opt.) def __init__(self, stringbinding): match = DCERPCStringBinding.parser.match(stringbinding) self.__uuid = match.group(1) self.__ps = match.group(2) self.__na = match.group(3) options = match.group(4) if options: options = options.split(',') self.__endpoint = options[0] try: self.__endpoint.index('endpoint=') self.__endpoint = self.__endpoint[len('endpoint='):] except: pass self.__options = options[1:] else: self.__endpoint = '' self.__options = [] def get_uuid(self): return self.__uuid def get_protocol_sequence(self): return self.__ps def get_network_address(self): return self.__na def get_endpoint(self): return self.__endpoint def get_options(self): return self.__options def __str__(self): return DCERPCStringBindingCompose(self.__uuid, self.__ps, self.__na, self.__endpoint, self.__options) def DCERPCStringBindingCompose(uuid=None, protocol_sequence='', network_address='', endpoint='', options=[]): s = '' if uuid: s += uuid + '@' s += protocol_sequence + ':' if network_address: s += network_address if endpoint or options: s += '[' + endpoint if options: s += ',' + ','.join(options) s += ']' return s def DCERPCTransportFactory(stringbinding): sb = DCERPCStringBinding(stringbinding) na = sb.get_network_address() ps = sb.get_protocol_sequence() if 'ncadg_ip_udp' == ps: port = sb.get_endpoint() if port: return UDPTransport(na, int(port)) else: return UDPTransport(na) elif 'ncacn_ip_tcp' == ps: port = sb.get_endpoint() if port: return TCPTransport(na, int(port)) else: return TCPTransport(na) elif 'ncacn_http' == ps: port = sb.get_endpoint() if port: return HTTPTransport(na, int(port)) else: return HTTPTransport(na) elif 'ncacn_np' == ps: named_pipe = sb.get_endpoint() if named_pipe: named_pipe = named_pipe[len(r'\pipe'):] return SMBTransport(na, filename = named_pipe) else: return SMBTransport(na) else: raise Exception, "Unknown protocol sequence." class DCERPCTransport: DCERPC_class = dcerpc.DCERPC_v5 def __init__(self, dstip, dstport): self.__dstip = dstip self.__dstport = dstport self._max_send_frag = None self._max_recv_frag = None self.set_credentials('','','','') def connect(self): raise RuntimeError, 'virtual function' def send(self,data=0, forceWriteAndx = 0, forceRecv = 0): raise RuntimeError, 'virtual function' def recv(self): raise RuntimeError, 'virtual function' def disconnect(self): raise RuntimeError, 'virtual function' def get_socket(self): raise RuntimeError, 'virtual function' def get_dip(self): return self.__dstip def set_dip(self, dip): "This method only makes sense before connection for most protocols." self.__dstip = dip def get_dport(self): return self.__dstport def set_dport(self, dport): "This method only makes sense before connection for most protocols." self.__dstport = dport def get_addr(self): return (self.get_dip(), self.get_dport()) def set_addr(self, addr): "This method only makes sense before connection for most protocols." self.set_dip(addr[0]) self.set_dport(addr[1]) def set_max_fragment_size(self, send_fragment_size): # -1 is default fragment size: 0 (don't fragment) # 0 is don't fragment # other values are max fragment size if send_fragment_size == -1: self.set_default_max_fragment_size() else: self._max_send_frag = send_fragment_size def set_default_max_fragment_size(self): # default is 0: don'fragment. # subclasses may override this method self._max_send_frag = 0 def get_credentials(self): return ( self._username, self._password, self._nt_hash, self._lm_hash) def set_credentials(self, username, password, lm_hash='', nt_hash=''): self._username = username self._password = password self._nt_hash = nt_hash self._lm_hash = lm_hash class UDPTransport(DCERPCTransport): "Implementation of ncadg_ip_udp protocol sequence" DCERPC_class = dcerpc_v4.DCERPC_v4 def __init__(self,dstip, dstport = 135): DCERPCTransport.__init__(self, dstip, dstport) self.__socket = 0 def connect(self): try: self.__socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.__socket.settimeout(30) except socket.error, msg: self.__socket = None raise Exception, "Could not connect: %s" % msg return 1 def disconnect(self): try: self.__socket.close() except socket.error, msg: self.__socket = None return 0 return 1 def send(self,data, forceWriteAndx = 0, forceRecv = 0): self.__socket.sendto(data,(self.get_dip(),self.get_dport())) def recv(self): buffer, self.__recv_addr = self.__socket.recvfrom(8192) return buffer def get_recv_addr(self): return self.__recv_addr def get_socket(self): return self.__socket class TCPTransport(DCERPCTransport): "Implementation of ncacn_ip_tcp protocol sequence" def __init__(self, dstip, dstport = 135): DCERPCTransport.__init__(self, dstip, dstport) self.__socket = 0 def connect(self): self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.__socket.settimeout(300) self.__socket.connect((self.get_dip(), self.get_dport())) except socket.error, msg: self.__socket.close() raise Exception, "Could not connect: %s" % msg return 1 def disconnect(self): try: self.__socket.close() except socket.error, msg: self.__socket = None return 0 return 1 def send(self,data, forceWriteAndx = 0, forceRecv = 0): if self._max_send_frag: offset = 0 while 1: toSend = data[offset:offset+self._max_send_frag] if not toSend: break self.__socket.send(toSend) offset += len(toSend) else: self.__socket.send(data) def recv(self): buffer = self.__socket.recv(8192) return buffer def get_socket(self): return self.__socket class HTTPTransport(TCPTransport): "Implementation of ncacn_http protocol sequence" def connect(self): TCPTransport.connect(self) self.__socket.send('RPC_CONNECT ' + self.get_dip() + ':593 HTTP/1.0\r\n\r\n') data = self.__socket.recv(8192) if data[10:13] != '200': raise Exception("Service not supported.") class SMBTransport(DCERPCTransport): "Implementation of ncacn_np protocol sequence" def __init__(self, dstip, dstport = 445, filename = '', username='', password='', lm_hash='', nt_hash=''): DCERPCTransport.__init__(self, dstip, dstport) self.__socket = None self.__smb_server = 0 self.__tid = 0 self.__filename = filename self.__handle = 0 self.__pending_recv = 0 self.set_credentials(username, password, lm_hash, nt_hash) def setup_smb_server(self): if not self.__smb_server: self.__smb_server = smb.SMB('*SMBSERVER',self.get_dip(), sess_port = self.get_dport()) def connect(self): self.setup_smb_server() if self.__smb_server.is_login_required(): if self._password != '' or (self._password == '' and self._nt_hash == '' and self._lm_hash == ''): self.__smb_server.login(self._username, self._password) elif self._nt_hash != '' or self._lm_hash != '': self.__smb_server.login(self._username, '', '', self._lm_hash, self._nt_hash) self.__tid = self.__smb_server.tree_connect_andx('\\\\*SMBSERVER\\IPC$') self.__handle = self.__smb_server.nt_create_andx(self.__tid, self.__filename) # self.__handle = self.__smb_server.open_file_andx(self.__tid, r"\\PIPE\%s" % self.__filename, smb.SMB_O_CREAT, smb.SMB_ACCESS_READ)[0] # self.__handle = self.__smb_server.open_file(self.__tid, r"\\PIPE\%s" % self.__filename, smb.SMB_O_CREAT, smb.SMB_ACCESS_READ)[0] self.__socket = self.__smb_server.get_socket() return 1 def disconnect(self): self.__smb_server.disconnect_tree(self.__tid) self.__smb_server.logoff() def send(self,data, noAnswer = 0, forceWriteAndx = 0, forceRecv = 0): if self._max_send_frag: offset = 0 while 1: toSend = data[offset:offset+self._max_send_frag] if not toSend: break self.__smb_server.write_andx(self.__tid, self.__handle, toSend, offset = offset) offset += len(toSend) else: if forceWriteAndx: self.__smb_server.write_andx(self.__tid, self.__handle, data) else: self.__smb_server.TransactNamedPipe(self.__tid,self.__handle,data, noAnswer = noAnswer, waitAnswer = 0) if forceRecv: self.__pending_recv += 1 def recv(self): if self._max_send_frag or self.__pending_recv: # _max_send_frag is checked because it's the same condition we checked # to decide whether to use write_andx() or send_trans() in send() above. if self.__pending_recv: self.__pending_recv -= 1 return self.__smb_server.read_andx(self.__tid, self.__handle, max_size = self._max_recv_frag) else: s = self.__smb_server.recv_packet() if self.__smb_server.isValidAnswer(s,smb.SMB.SMB_COM_TRANSACTION): trans = smb.TRANSHeader(s.get_parameter_words(), s.get_buffer()) data = trans.get_data() return data return None def get_smb_server(self): return self.__smb_server def get_socket(self): return self.__socket
11,565
Python
.py
289
30.820069
143
0.585714
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,952
conv.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/conv.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: conv.py,v 1.4 2006/05/23 21:19:26 gera Exp $ # # Description: # Implement CONV protocol, used to establish an RPC session over UDP. # import array from impacket import ImpactPacket MSRPC_UUID_CONV = '\x76\x22\x3a\x33\x00\x00\x00\x00\x0d\x00\x00\x80\x9c\x00\x00\x00' class WhoAreYou(ImpactPacket.Header): OP_NUM = 1 __SIZE = 20 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WhoAreYou.__SIZE) if aBuffer: self.load_header(aBuffer) def get_activity_binuuid(self): return self.get_bytes().tolist()[0:0+16] def set_activity_binuuid(self, binuuid): assert 16 == len(binuuid) self.get_bytes()[0:0+16] = array.array('B', binuuid) def get_boot_time(self): return self.get_long(16, '<') def set_boot_time(self, time): self.set_long(16, time, '<') def get_header_size(self): return WhoAreYou.__SIZE class WhoAreYou2(ImpactPacket.Header): OP_NUM = 1 __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WhoAreYou2.__SIZE) if aBuffer: self.load_header(aBuffer) def get_seq_num(self): return self.get_long(0, '<') def set_seq_num(self, num): self.set_long(0, num, '<') def get_cas_binuuid(self): return self.get_bytes().tolist()[4:4+16] def set_cas_binuuid(self, binuuid): assert 16 == len(binuuid) self.get_bytes()[4:4+16] = array.array('B', binuuid) def get_status(self): return self.get_long(20, '<') def set_status(self, status): self.set_long(20, status, '<') def get_header_size(self): return WhoAreYou2.__SIZE
1,918
Python
.py
52
31.384615
84
0.652597
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,953
epm.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/epm.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: epm.py,v 1.5 2006/05/23 21:19:26 gera Exp $ # import array import struct from impacket import ImpactPacket from impacket import uuid import dcerpc import ndrutils import transport MSRPC_UUID_PORTMAP ='\x08\x83\xaf\xe1\x1f\x5d\xc9\x11\x91\xa4\x08\x00\x2b\x14\xa0\xfa\x03\x00\x00\x00' class EPMLookupRequestHeader(ImpactPacket.Header): OP_NUM = 2 __SIZE = 76 def __init__(self, aBuffer = None, endianness = '<'): ImpactPacket.Header.__init__(self, EPMLookupRequestHeader.__SIZE) self.endianness = endianness self.set_inquiry_type(0) self.set_referent_id(1) self.set_referent_id2(2) self.set_max_entries(1) if aBuffer: self.load_header(aBuffer) def get_inquiry_type(self): return self.get_long(0, self.endianness) def set_inquiry_type(self, type): self.set_long(0, type, self.endianness) def get_referent_id(self): return self.get_long(4, self.endianness) def set_referent_id(self, id): self.set_long(4, id, self.endianness) def get_obj_binuuid(self): return self.get_bytes().tolist()[8:8+16] def set_obj_binuuid(self, binuuid): assert 16 == len(binuuid) self.get_bytes()[8:8+16] = array.array('B', binuuid) def get_referent_id2(self): return self.get_long(24, self.endianness) def set_referent_id2(self, id): self.set_long(24, id, self.endianness) def get_if_binuuid(self): return self.get_bytes().tolist()[28:28+20] def set_if_binuuid(self, binuuid): assert 20 == len(binuuid) self.get_bytes()[28:28+20] = array.array('B', binuuid) def get_version_option(self): return self.get_long(48, self.endianness) def set_version_option(self, opt): self.set_long(48, opt, self.endianness) def get_handle(self): return self.get_bytes().tolist()[52:52+20] def set_handle(self, handle): assert 20 == len(handle) self.get_bytes()[52:52+20] = array.array('B', handle) def get_max_entries(self): return self.get_long(72, self.endianness) def set_max_entries(self, num): self.set_long(72, num, self.endianness) def get_header_size(self): return EPMLookupRequestHeader.__SIZE class EPMRespLookupRequestHeader(ImpactPacket.Header): __SIZE = 28 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, EPMRespLookupRequestHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_handle(self): return self.get_bytes().tolist()[0:0+20] def set_handle(self, handle): assert 20 == len(handle) self.get_bytes()[0:0+20] = array.array('B', handle) def get_entries_num(self): return self.get_long(20, '<') def set_entries_num(self, num): self.set_long(20, num, '<') def get_entry(self): return ndrutils.NDREntries(self.get_bytes().tostring()[24:-4]) def set_entry(self, entry): raise Exception, "method not implemented" def get_status(self): off = self.get_entry().get_entries_len() return self.get_long(24 + off, '<') def set_status(self, status): off = self.get_entry().get_entries_len() self.set_long(24 + off, status, '<') def get_header_size(self): entries_size = self.get_entry().get_entries_len() return EPMRespLookupRequestHeader.__SIZE + entries_size class DCERPCEpm: endianness = '<' def __init__(self, dcerpc): self._dcerpc = dcerpc def portmap_dump(self, rpc_handle = '\x00'*20): if self.endianness == '>': from impacket.structure import unpack,pack try: rpc_handle = ''.join(map(chr, rpc_handle)) except: pass uuid = list(unpack('<LLHHBB6s', rpc_handle)) rpc_handle = pack('>LLHHBB6s', *uuid) lookup = EPMLookupRequestHeader(endianness = self.endianness) lookup.set_handle(rpc_handle); self._dcerpc.send(lookup) data = self._dcerpc.recv() resp = EPMRespLookupRequestHeader(data) return resp class EpmEntry: def __init__(self, uuid, version, annotation, objuuid, protocol, endpoint): self.__uuid = uuid self.__version = version self.__annotation = annotation self.__objuuid = objuuid self.__protocol = protocol self.__endpoint = endpoint def getUUID(self): return self.__uuid def setUUID(self, uuid): self.__uuid = uuid def getProviderName(self): return ndrutils.uuid_to_exe(uuid.string_to_bin(self.getUUID()) + struct.pack('<H', self.getVersion())) def getVersion(self): return self.__version def setVersion(self, version): self.__version = version def isZeroObjUUID(self): return self.__objuuid == '00000000-0000-0000-0000-000000000000' def getObjUUID(self): return self.__objuuid def setObjUUID(self, objuuid): self.__uuid = objuuid def getAnnotation(self): return self.__annotation def setAnnotation(self, annotation): self.__annotation = annotation def getProtocol(self): return self.__protocol def setProtocol(self, protocol): self.__protocol = protocol def getEndpoint(self): return self.__endpoint def setEndpoint(self, endpoint): self.__endpoint = endpoint def __str__(self): stringbinding = transport.DCERPCStringBindingCompose(self.getObjUUID(), self.getProtocol(), '', self.getEndpoint()) s = '[' if self.getAnnotation(): s += "Annotation: \"%s\", " % self.getAnnotation() s += "UUID=%s, version %d, %s]" % (self.getUUID(), self.getVersion(), stringbinding) return s def __cmp__(self, o): if (self.getUUID() == o.getUUID() and self.getVersion() == o.getVersion() and self.getAnnotation() == o.getAnnotation() and self.getObjUUID() == o.getObjUUID() and self.getProtocol() == o.getProtocol() and self.getEndpoint() == o.getEndpoint()): return 0 else: return -1 # or +1, for what we care.
6,484
Python
.py
162
32.481481
123
0.634867
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,954
ndrutils.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/ndrutils.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: ndrutils.py,v 1.7 2006/05/23 21:19:26 gera Exp $ # from struct import * import socket import random from impacket import uuid def uuid_hex(_uuid): for i in range(0,len(_uuid)): print "\\0x%.2x"%unpack('<B',_uuid[i]), print "" def uuid_to_exe(_uuid): KNOWN_UUIDS = { '\xb9\x99\x3f\x87\x4d\x1b\x10\x99\xb7\xaa\x00\x04\x00\x7f\x07\x01\x00\x00': 'ssmsrp70.dll', '\x90\x2c\xfe\x98\x42\xa5\xd0\x11\xa4\xef\x00\xa0\xc9\x06\x29\x10\x01\x00':'advapi32.dll', '\x44\xaf\x7d\x8c\xdc\xb6\xd1\x11\x9a\x4c\x00\x20\xaf\x6e\x7c\x57\x01\x00':'appmgmts.dll', '\xc0\xeb\x4f\xfa\x91\x45\xce\x11\x95\xe5\x00\xaa\x00\x51\xe5\x10\x04\x00':'autmgr32.exe', '\xe0\x42\xc7\x4f\x10\x4a\xcf\x11\x82\x73\x00\xaa\x00\x4a\xe6\x73\x03\x00':'dfssvc.exe', '\x98\xd0\xff\x6b\x12\xa1\x10\x36\x98\x33\x46\xc3\xf8\x74\x53\x2d\x01\x00':'DHCPSSVC.DLL', '\x20\x17\x82\x5b\x3b\xf6\xd0\x11\xaa\xd2\x00\xc0\x4f\xc3\x24\xdb\x01\x00':'DHCPSSVC.DLL', '\xfa\x9d\xd7\xd2\x00\x34\xd0\x11\xb4\x0b\x00\xaa\x00\x5f\xf5\x86\x01\x00':'dmadmin.exe', '\xa4\xc2\xab\x50\x4d\x57\xb3\x40\x9d\x66\xee\x4f\xd5\xfb\xa0\x76\x05\x00':'dns.exe', '\x90\x38\xa9\x65\xb9\xfa\xa3\x43\xb2\xa5\x1e\x33\x0a\xc2\x8f\x11\x02\x00':'dnsrslvr.dll', '\x65\x31\x0a\xea\x34\x48\xd2\x11\xa6\xf8\x00\xc0\x4f\xa3\x46\xcc\x04\x00':'faxsvc.exe', '\x64\x1d\x82\x0c\xfc\xa3\xd1\x11\xbb\x7a\x00\x80\xc7\x5e\x4e\xc1\x01\x00':'irftp.exe', '\xd0\xbb\xf5\x7a\x63\x60\xd1\x11\xae\x2a\x00\x80\xc7\x5e\x4e\xc1\x00\x00':'irmon.dll', '\x40\xb2\x9b\x20\x19\xb9\xd1\x11\xbb\xb6\x00\x80\xc7\x5e\x4e\xc1\x01\x00':'irmon.dll', '\xfb\xee\x0c\x13\x66\xe4\xd1\x11\xb7\x8b\x00\xc0\x4f\xa3\x28\x83\x02\x00':'ismip.dll', '\x86\xd4\xdc\x68\x9e\x66\xd1\x11\xab\x0c\x00\xc0\x4f\xc2\xdc\xd2\x01\x00':'ismserv.exe', '\x40\xfd\x2c\x34\x6c\x3c\xce\x11\xa8\x93\x08\x00\x2b\x2e\x9c\x6d\x00\x00':'llssrv.exe', '\xd0\x4c\x67\x57\x00\x52\xce\x11\xa8\x97\x08\x00\x2b\x2e\x9c\x6d\x01\x00':'llssrv.exe', '\xc4\x0c\x3c\xe3\x82\x04\x1a\x10\xbc\x0c\x02\x60\x8c\x6b\xa2\x18\x01\x00':'locator.exe', '\xf0\x0e\xd7\xd6\x3b\x0e\xcb\x11\xac\xc3\x08\x00\x2b\x1d\x29\xc3\x01\x00':'locator.exe', '\x14\xb5\xfb\xd3\x3b\x0e\xcb\x11\x8f\xad\x08\x00\x2b\x1d\x29\xc3\x01\x00':'locator.exe', '\xf0\x0e\xd7\xd6\x3b\x0e\xcb\x11\xac\xc3\x08\x00\x2b\x1d\x29\xc4\x01\x00':'locator.exe', '\x78\x57\x34\x12\x34\x12\xcd\xab\xef\x00\x01\x23\x45\x67\x89\xab\x00\x00':'lsasrv.dll', '\x88\xd4\x81\xc6\x50\xd8\xd0\x11\x8c\x52\x00\xc0\x4f\xd9\x0f\x7e\x01\x00':'lsasrv.dll', '\xf0\x09\x8f\xed\xb7\xce\x11\xbb\xd2\x00\x00\x1a\x18\x1c\xad\x00\x00\x00':'mprdim.dll', '\xe0\xca\x02\xec\xe0\xb9\xd2\x11\xbe\x62\x00\x20\xaf\xed\xdf\x63\x01\x00':'mq1repl.dll', '\x80\x7a\xdf\x77\x98\xf2\xd0\x11\x83\x58\x00\xa0\x24\xc4\x80\xa8\x01\x00':'mdqssrv.dll', '\x10\xca\x8c\x70\x69\x95\xd1\x11\xb2\xa5\x00\x60\x97\x7d\x81\x18\x01\x00':'mqdssrv.dll', '\x80\x35\x5b\x5b\xe0\xb0\xd1\x11\xb9\x2d\x00\x60\x08\x1e\x87\xf0\x01\x00':'mqqm.dll', '\xe0\x8e\x20\x41\x70\xe9\xd1\x11\x9b\x9e\x00\xe0\x2c\x06\x4c\x39\x01\x00':'mqqm.dll', '\x80\xa9\x88\x10\xe5\xea\xd0\x11\x8d\x9b\x00\xa0\x24\x53\xc3\x37\x01\x00':'mqqm.dll', '\xe0\x0c\x6b\x90\x0b\xc7\x67\x10\xb3\x17\x00\xdd\x01\x06\x62\xda\x01\x00':'msdtcprx.dll', '\xf8\x91\x7b\x5a\x00\xff\xd0\x11\xa9\xb2\x00\xc0\x4f\xb6\x36\xfc\x01\x00':'msgsvc.dll', '\x82\x06\xf7\x1f\x51\x0a\xe8\x30\x07\x6d\x74\x0b\xe8\xce\xe9\x8b\x01\x00':'mstask.exe', '\xb0\x52\x8e\x37\xa9\xc0\xcf\x11\x82\x2d\x00\xaa\x00\x51\xe4\x0f\x01\x00':'mstask.exe', '\x20\x32\x5f\x2f\x26\xc1\x76\x10\xb5\x49\x07\x4d\x07\x86\x19\xda\x01\x00':'netdde.exe', '\x78\x56\x34\x12\x34\x12\xcd\xab\xef\x00\x01\x23\x45\x67\xcf\xfb\x01\x00':'netlogon.dll', '\x18\x5a\xcc\xf5\x64\x42\x1a\x10\x8c\x59\x08\x00\x2b\x2f\x84\x26\x38\x00':'ntdsa.dll', '\x7c\x5a\xcc\xf5\x64\x42\x1a\x10\x8c\x59\x08\x00\x2b\x2f\x84\x26\x15\x00':'ntdsa.dll', '\x35\x42\x51\xe3\x06\x4b\xd1\x11\xab\x04\x00\xc0\x4f\xc2\xdc\xd2\x04\x00':'ntdsa.dll', '\x70\x0d\xec\xec\x03\xa6\xd0\x11\x96\xb1\x00\xa0\xc9\x1e\xce\x30\x01\x00':'ntdsbsrv.dll', '\x3a\xcf\xe0\x16\x04\xa6\xd0\x11\x96\xb1\x00\xa0\xc9\x1e\xce\x30\x01\x00':'ntdsbsrv.dll', '\xb4\x59\xcc\xf5\x64\x42\x1a\x10\x8c\x59\x08\x00\x2b\x2f\x84\x26\x01\x00':'ntfrs.exe', '\x86\xb1\x49\xd0\x4f\x81\xd1\x11\x9a\x3c\x00\xc0\x4f\xc9\xb2\x32\x01\x00':'ntfrs.exe', '\x1c\x02\x0c\xa0\xe2\x2b\xd2\x11\xb6\x78\x00\x00\xf8\x7a\x8f\x8e\x01\x00':'ntfrs.exe', '\xa0\x9e\xc0\x69\x09\x4a\x1b\x10\xae\x4b\x08\x00\x2b\x34\x9a\x02\x00\x00':'ole32.dll', '\x50\x38\xcd\x15\xca\x28\xce\x11\xa4\xe8\x00\xaa\x00\x61\x16\xcb\x01\x00':'pgpsdkserv.exe', '\xf6\xb8\x35\xd3\x31\xcb\xd0\x11\xb0\xf9\x00\x60\x97\xba\x4e\x54\x01\x00':'polagent.dll', '\xf0\xe4\x9c\x36\xdc\x0f\xd3\x11\xbd\xe8\x00\xc0\x4f\x8e\xee\x78\x01\x00':'profmap.dll', '\x36\x00\x61\x20\x22\xfa\xcf\x11\x98\x23\x00\xa0\xc9\x11\xe5\xdf\x01\x00':'rasmans.dll', '\x01\xd0\x8c\x33\x44\x22\xf1\x31\xaa\xaa\x90\x00\x38\x00\x10\x03\x01\x00':'regsvc.exe', '\x83\xaf\xe1\x1f\x5d\xc9\x11\x91\xa4\x08\x00\x2b\x14\xa0\xfa\x03\x00\x00':'rpcss.dll', '\x84\x65\x0a\x0b\x0f\x9e\xcf\x11\xa3\xcf\x00\x80\x5f\x68\xcb\x1b\x01\x00':'rpcss.dll', '\xb0\x01\x52\x97\xca\x59\xd0\x11\xa8\xd5\x00\xa0\xc9\x0d\x80\x51\x01\x00':'rpcss.dll', '\xe6\x73\x0c\xe6\xf9\x88\xcf\x11\x9a\xf1\x00\x20\xaf\x6e\x72\xf4\x02\x00':'rpcss.dll', '\xc4\xfe\xfc\x99\x60\x52\x1b\x10\xbb\xcb\x00\xaa\x00\x21\x34\x7a\x00\x00':'rpcss.dll', '\x1e\x24\x2f\x41\x2a\xc1\xce\x11\xab\xff\x00\x20\xaf\x6e\x7a\x17\x00\x00':'rpcss.dll', '\x36\x01\x00\x00\x00\x00\x00\x00\xc0\x00\x00\x00\x00\x00\x00\x46\x00\x00':'rpcss.dll', '\x72\xee\xf3\xc6\x7e\xce\xd1\x11\xb7\x1e\x00\xc0\x4f\xc3\x11\x1a\x01\x00':'rpcss.dll', '\xb8\x4a\x9f\x4d\x1c\x7d\xcf\x11\x86\x1e\x00\x20\xaf\x6e\x7c\x57\x00\x00':'rpcss.dll', '\xa0\x01\x00\x00\x00\x00\x00\x00\xc0\x00\x00\x00\x00x\00x\00\x46\x00\x00':'rpcss.dll', '\x60\x9e\xe7\xb9\x52\x3d\xce\x11\xaa\xa1\x00\x00\x69\x01\x29\x3f\x00\x00':'rpcss.dll', '\x78\x57\x34\x12\x34\x12\xcd\xab\xef\x00\x01\x23\x45\x67\x89\xac\x01\x00':'samsrv.dll', '\xa2\x9c\x14\x93\x3b\x97\xd1\x11\x8c\x39\x00\xc0\x4f\xb9\x84\xf9\x00\x00':'scesrv.dll', '\x24\xe4\xfb\x63\x29\x20\xd1\x11\x8d\xb8\x00\xaa\x00\x4a\xbd\x5e\x01\x00':'sens.dll', '\x66\x9f\x9b\x62\x6c\x55\xd1\x11\x8d\xd2\x00\xaa\x00\x4a\xbd\x5e\x02\x00':'sens.dll', '\x81\xbb\x7a\x36\x44\x98\xf1\x35\xad\x32\x98\xf0\x38\x00\x10\x03\x02\x00':'services.exe', '\x7c\xda\x83\x4f\xe8\xd2\x11\x98\x07\x00\xc0\x4f\x8e\xc8\x50\x02\x00\x00':'sfc.dll', '\xc8\x4f\x32\x4b\x70\x16\xd3\x01\x12\x78\x5a\x47\xbf\x6e\xe1\x88\x00\x00':'sfmsvc.exe', '\x78\x56\x34\x12\x34\x12\xcd\xab\xef\x00\x01\x23\x45\x67\x89\xab\x01\x00':'spoolsv.exe', '\xe0\x6d\x7a\x8c\x8d\x78\xd0\x11\x9e\xdf\x44\x45\x53\x54\x00\x00\x02\x00':'stisvc.exe', '\x20\x65\x5f\x2f\x46\xca\x67\x10\xb3\x19\x00\xdd\x01\x06\x62\xda\x01\x00':'tapisrv.dll', '\x60\xa7\xa4\x5c\xb1\xeb\xcf\x11\x86\x11\x00\xa0\x24\x54\x20\xed\x01\x00':'termsrv.exe', '\x22\xc4\xa1\x4d\x3d\x94\xd1\x11\xac\xae\x00\xc0\x4f\xc2\xaa\x3f\x01\x00':'trksvr.dll', '\x32\x35\x0f\x30\xcc\x38\xd0\x11\xa3\xf0\x00\x20\xaf\x6b\x0a\xdd\x01\x00':'trkwks.dll', '\x12\xfc\x99\x60\xff\x3e\xd0\x11\xab\xd0\x00\xc0\x4f\xd9\x1a\x4e\x03\x00':'winfax.dll', '\xc0\xe0\x4d\x89\x55\x0d\xd3\x11\xa3\x22\x00\xc0\x4f\xa3\x21\xa1\x01\x00':'winlogon.exe', '\x28\x2c\xf5\x45\x9f\x7f\x1a\x10\xb5\x2b\x08\x00\x2b\x2e\xfa\xbe\x01\x00':'wins.exe', '\xbf\x09\x11\x81\xe1\xa4\xd1\x11\xab\x54\x00\xa0\xc9\x1e\x9b\x45\x01\x00':'wins.exe', '\xa0\xb3\x02\xa0\xb7\xc9\xd1\x11\xae\x88\x00\x80\xc7\x5e\x4e\xc1\x01\x00':'wlnotify.dll', '\xd1\x51\xa9\xbf\x0e\x2f\xd3\x11\xbf\xd1\x00\xc0\x4f\xa3\x49\x0a\x01\x00':'aqueue.dll', '\x80x\42\xad\x82\x6b\x03\xcf\x11\x97\x2c\x00\xaa\x00\x68\x87\xb0\x02\x00':'infocomm.dll', '\x70\x5d\xfb\x8c\xa4\x31\xcf\x11\xa7\xd8\x00\x80\x5f\x48\xa1\x35\x03\x00':'smtpsvc.dll', '\x80\x42\xad\x82\x6b\x03\xcf\x11\x97\x2c\x00\xaa\x00\x68\x87\xb0\x02\x00':'infoadmn.dll', '\x00\xb9\x99\x3f\x87\x4d\x1b\x10\x99\xb7\xaa\x00\x04\x00\x7f\x07\x01\x00':'ssmsrpc.dll - Microsoft SQL Server', '\x60\xf4\x82\x4f\x21\x0e\xcf\x11\x90\x9e\x00\x80\x5f\x48\xa1\x35\x04\x00':'nntpsvc.dll', '\xc0\x47\xdf\xb3\x5a\xa9\xcf\x11\xaa\x26\x00\xaa\x00\xc1\x48\xb9\x09\x00':'mspadmin.exe - Microsoft ISA Server', '\x1f\xa7\x37\x21\x5e\xbb\x29\x4e\x8e\x7e\x2e\x46\xa6\x68\x1d\xbf\x09\x00':'wspsrv.exe - Microsoft ISA Server', '\xf8\x91\x7b\x5a\x00\xff\xd0\x11\xa9\xb2\x00\xc0\x4f\xb6\xe6\xfc\x01\x00':'msgsvc.dll' } if KNOWN_UUIDS.has_key(_uuid): return KNOWN_UUIDS[_uuid] else: return 'unknown' #Protocol ids, reference: http://www.opengroup.org/onlinepubs/9629399/apdxi.htm class NDRFloor: PROTO_ID = { 0x0: 'OSI OID', 0x2: 'UUID', 0x5: 'OSI TP4', 0x6: 'OSI CLNS or DNA Routing', 0x7: 'DOD TCP', 0x8: 'DOD UDP', 0x9: 'DOD IP', 0xa: 'RPC connectionless protocol', 0xb: 'RPC connection-oriented protocol', 0xd: 'UUID', 0x2: 'DNA Session Control', 0x3: 'DNA Session Control V3', 0x4: 'DNA NSP Transport', 0x0d: 'Netware SPX', 0x0e: 'Netware IPX', #someone read hexa as decimal? (0xe=0x14 in opengroup's list) 0x0f: 'Named Pipes', 0x10: 'Named Pipes', 0x11: 'NetBIOS', 0x12: 'NetBEUI', 0x13: 'Netware SPX', 0x14: 'Netware IPX', 0x16: 'Appletalk Stream', 0x17: 'Appletalk Datagram', 0x18: 'Appletalk', 0x19: 'NetBIOS', 0x1a: 'Vines SPP', 0x1b: 'Vines IPC', 0x1c: 'StreeTalk', 0x20: 'Unix Domain Socket', 0x21: 'null', 0x22: 'NetBIOS'} def __init__(self,data=''): self._lhs_len = 0 self._protocol = 0 self._uuid = '' self._rhs_len = 0 self._rhs = '' self._floor_len = 0 if data != 0: self._lhs_len, self._protocol = unpack('<HB',data[:3]) offset = 3 if self._protocol == 0x0d: # UUID self._uuid = data[offset:offset+self._lhs_len-1] offset += self._lhs_len-1 self._rhs_len = unpack('<H',data[offset:offset+2])[0] offset += 2 self._rhs = data[offset:offset+self._rhs_len] self._floor_len = offset + self._rhs_len def get_floor_len(self): return self._floor_len def get_protocol(self): return self._protocol def get_rhs(self): return self._rhs def get_rhs_len(self): return self._rhs_len def get_uuid(self): return self._uuid def get_protocol_string(self): if NDRFloor.PROTO_ID.has_key(self._protocol): return NDRFloor.PROTO_ID[self._protocol] else: return 'unknown' def get_uuid_string(self): if len(self._uuid) == 18: version = unpack('<H',self._uuid[16:18])[0] return "%s version: %d" % (parse_uuid(self._uuid), version) else: return '' def parse_uuid(_uuid): return uuid.bin_to_string(_uuid) class NDRTower: def __init__(self,data=''): self._length = 0 self._length2 = 0 self._number_of_floors = 0 self._floors = [] self._tower_len = 0 if data != 0: self._length, self._length2, self._number_of_floors = unpack('<LLH',data[:10]) offset = 10 for i in range(0,self._number_of_floors): self._floors.append(NDRFloor(data[offset:])) offset += self._floors[i].get_floor_len() self._tower_len = offset def get_tower_len(self): return self._tower_len def get_floors(self): return self._floors def get_number_of_floors(self): return self._number_of_floors class NDREntry: def __init__(self,data=''): self._objectid = '' self._entry_len = 0 self._tower = 0 self._referent_id = 0 self._annotation_offset = 0 self._annotation_len = 0 self._annotation = '' if data != 0: self._objectid = data[:16] self._referent_id = unpack('<L',data[16:20])[0] self._annotation_offset, self._annotation_len = unpack('<LL',data[20:28]) self._annotation = data[28:28+self._annotation_len-1] if self._annotation_len % 4: self._annotation_len += 4 - (self._annotation_len % 4) offset = 28 + self._annotation_len self._tower = NDRTower(data[offset:]) self._entry_len = offset + self._tower.get_tower_len() def get_entry_len(self): if self._entry_len % 4: self._entry_len += 4 - (self._entry_len % 4) return self._entry_len def get_annotation(self): return self._annotation def get_tower(self): return self._tower def get_uuid(self): binuuid = self._tower.get_floors()[0].get_uuid() return binuuid[:16] def get_objuuid(self): return self._objectid def get_version(self): binuuid = self._tower.get_floors()[0].get_uuid() return unpack('<H', binuuid[16:18])[0] def print_friendly(self): if self._tower <> 0: floors = self._tower.get_floors() print "IfId: %s [%s]" % (floors[0].get_uuid_string(), uuid_to_exe(floors[0].get_uuid())) if self._annotation: print "Annotation: %s" % self._annotation print "UUID: %s" % parse_uuid(self._objectid) print "Binding: %s" % self.get_string_binding() print '' def get_string_binding(self): if self._tower <> 0: tmp_address = '' tmp_address2 = '' floors = self._tower.get_floors() num_floors = self._tower.get_number_of_floors() for i in range(3,num_floors): if floors[i].get_protocol() == 0x07: tmp_address = 'ncacn_ip_tcp:%%s[%d]' % unpack('!H',floors[i].get_rhs()) elif floors[i].get_protocol() == 0x08: tmp_address = 'ncadg_ip_udp:%%s[%d]' % unpack('!H',floors[i].get_rhs()) elif floors[i].get_protocol() == 0x09: # If the address were 0.0.0.0 it would have to be replaced by the remote host's IP. tmp_address2 = socket.inet_ntoa(floors[i].get_rhs()) if tmp_address <> '': return tmp_address % tmp_address2 else: return 'IP: %s' % tmp_address2 elif floors[i].get_protocol() == 0x0c: tmp_address = 'ncacn_spx:~%%s[%d]' % unpack('!H',floors[i].get_rhs()) elif floors[i].get_protocol() == 0x0d: n = floors[i].get_rhs_len() tmp_address2 = ('%02X' * n) % unpack("%dB" % n, floors[i].get_rhs()) if tmp_address <> '': return tmp_address % tmp_address2 else: return 'SPX: %s' % tmp_address2 elif floors[i].get_protocol() == 0x0e: tmp_address = 'ncadg_ipx:~%%s[%d]' % unpack('!H',floors[i].get_rhs()) elif floors[i].get_protocol() == 0x0f: tmp_address = 'ncacn_np:%%s[%s]' % floors[i].get_rhs()[:floors[i].get_rhs_len()-1] elif floors[i].get_protocol() == 0x10: return 'ncalrpc:[%s]' % floors[i].get_rhs()[:floors[i].get_rhs_len()-1] elif floors[i].get_protocol() == 0x01 or floors[i].get_protocol() == 0x11: if tmp_address <> '': return tmp_address % floors[i].get_rhs()[:floors[i].get_rhs_len()-1] else: return 'NetBIOS: %s' % floors[i].get_rhs() elif floors[i].get_protocol() == 0x1f: tmp_address = 'ncacn_http:%%s[%d]' % unpack('!H',floors[i].get_rhs()) else: if floors[i].get_protocol_string() == 'unknown': return 'unknown_proto_0x%x:[0]' % floors[i].get_protocol() elif floors[i].get_protocol_string() <> 'UUID': return 'protocol: %s, value: %s' % (floors[i].get_protocol_string(), floors[i].get_rhs()) class NDREntries: def __init__(self,data=''): self._max_count = 0 self._offset = 0 self._actual_count = 0 self._entries_len = 0 self._entries = [] if data != 0: self._max_count, self._offset, self._actual_count = unpack('<LLL',data[:12]) self._entries_len = 12 for i in range (0,self._actual_count): self._entries.append(NDREntry(data[self._entries_len:])) self._entries_len += self._entries[i].get_entry_len() def get_max_count(self): return self._max_count def get_offset(self): return self._offset def get_actual_count(self): return self._actual_count def get_entries_len(self): return self._entries_len def get_entry(self): return self._entries[0] class NDRPointer: def __init__(self,data='',pointerType = None): self._referent_id = random.randint(0,65535) self._pointer = None if data != '': self._referent_id = unpack('<L',data[:4])[0] self._pointer = pointerType(data[4:]) def set_pointer(self, data): self._pointer = data def get_pointer(self): return self._pointer def rawData(self): return pack('<L',self._referent_id) + self._pointer.rawData() class NDRString: def __init__(self,data=''): self._string = '' self._max_len = 0 self._offset = 0 self._length = 0 if data != '': self._max_len, self._offset, self._length = unpack('<LLL',data[:12]) self._string = unicode(data[12:12 + self._length * 2], 'utf-16le') def get_string(self): return self._string def set_string(self,str): self._string = str self._max_len = self._length = len(str)+1 def rawData(self): if self._length & 0x1: self._tail = pack('<HH',0,0) else: self._tail = pack('<H',0) return pack('<LLL',self._max_len, self._offset, self._length) + self._string.encode('utf-16le') + self._tail def get_max_len(self): return self._max_len def get_length(self): return self._length
20,770
Python
.py
353
44.699717
133
0.552502
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,955
dcom.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/dcom.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: dcom.py,v 1.5 2006/05/23 21:19:26 gera Exp $ # import array from impacket import ImpactPacket import dcerpc import ndrutils from struct import * MSRPC_UUID_REMOTE_ACTIVATION ='\xb8\x4a\x9f\x4d\x1c\x7d\xcf\x11\x86\x1e\x00\x20\xaf\x6e\x7c\x57\x00\x00\x00\x00' MSRPC_UUID_SYSTEM_ACTIVATOR = '\xa0\x01\x00\x00\x00\x00\x00\x00\xc0\x00\x00\x00\x00\x00\x00\x46\x00\x00\x00\x00' class ORPCTHIS: __SIZE = 32 def __init__(self,data=0): self._version_hi = 5 self._version_low = 6 self._flags = 1 self._reserved1 = 0 self._cid = '\xf1\x59\xeb\x61\xfb\x1e\xd1\x11\xbc\xd9\x00\x60\x97\x92\xd2\x6c' self._extensions = '\x60\x5e\x0d\x00' def set_version(self, mayor, minor): self._version_hi = mayor self._version_low = minor def set_cid(self, uuid): self._cid = uuid def rawData(self): return pack('<HHLL', self._version_hi, self._version_low, self._flags, self._reserved1) + self._cid + self._extensions class UnknownOpnum3RequestHeader(ImpactPacket.Header): OP_NUM = 3 __SIZE = 48 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, UnknownOpnum3RequestHeader.__SIZE) ## self.parent().set_callid(19) self.set_bytes_from_string('\x05\x00\x06\x01\x00\x00\x00\x00' + '\x31'*32 + '\x00'*8) if aBuffer: self.load_header(aBuffer) def get_header_size(self): return UnknownOpnum3RequestHeader.__SIZE class UnknownOpnum4RequestHeader(ImpactPacket.Header): OP_NUM = 4 __SIZE = 48 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, UnknownOpnum4RequestHeader.__SIZE) ## self.parent().set_callid(19) ## self.set_bytes(self, '\x05\x00\x06\x01\x00\x00\x00\x00' + '\x31'*32 + '\x00'*8) self.get_bytes()[:32] = array.array('B', ORPCTHIS().rawData()) self.set_cls_binuuid('\x01\x00\x00\x00\x00\x00\x00\x00\x70\x5e\x0d\x00\x02\x00\x00\x00') if aBuffer: self.load_header(aBuffer) def get_c_binuuid(self): return self.get_bytes().tolist()[12:12+16] def set_c_binuuid(self, binuuid): assert 16 == len(binuuid) self.get_bytes()[12:12+16] = array.array('B', binuuid) def get_cls_binuuid(self): return self.get_bytes().tolist()[32:32+16] def set_cls_binuuid(self, binuuid): assert 16 == len(binuuid) self.get_bytes()[32:32+16] = array.array('B', binuuid) def get_header_size(self): return UnknownOpnum4RequestHeader.__SIZE class RemoteActivationRequestHeader(ImpactPacket.Header): OP_NUM = 0 __SIZE = 124 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, UnknownOpnum4RequestHeader.__SIZE) self.get_bytes()[:32] = array.array('B', ORPCTHIS().rawData()) self.set_cls_binuuid('\xbe\x1d\x8d\x47\xff\xd6\xe1\x4c\xac\x54\xaa\xd5\x4e\xf3\x45\xd3') self.set_client_implementation_level(2) self.set_interfaces_num(1) self.get_bytes()[68:76] = array.array('B', '\x80\x3f\x15\x00\x01\x00\x00\x00') self.set_pi_binuuid('\x00\x00\x00\x00\x00\x00\x00\x00\xc0\x00\x00\x00\x00\x00\x00\x46') self.get_bytes()[92:124] = array.array('B', '\x01\x00\x00\x00\x01\x00\x00\x00\x07\x00\x64\x00\x04\x00\x69\x00\x01\x00\x00\x00\x87\x03\xb2\xd6\x99\xee\xac\x65\xc7\x53\x81\xa4') if aBuffer: self.load_header(aBuffer) def get_c_binuuid(self): return self.get_bytes().tolist()[12:12+16] def set_c_binuuid(self, binuuid): assert 16 == len(binuuid) self.get_bytes()[12:12+16] = array.array('B', binuuid) def get_cls_binuuid(self): return self.get_bytes().tolist()[32:32+16] def set_cls_binuuid(self, binuuid): assert 16 == len(binuuid) self.get_bytes()[32:32+16] = array.array('B', binuuid) def get_object_name_len(self): return self.get_word(48, '<') def set_object_name_len(self, len): self.set_word(48, len, '<') def get_object_storage(self): return self.get_word(52, '<') def set_object_storage(self, storage): self.set_word(52, storage, '<') def get_client_implementation_level(self): return self.get_long(56, '<') def set_client_implementation_level(self, level): self.set_long(56, level, '<') def get_mode(self): return self.get_long(60, '<') def set_mode(self, mode): self.set_long(60, mode, '<') def get_interfaces_num(self): return self.get_long(64, '<') def set_interfaces_num(self, num): self.set_long(64, num, '<') def get_pi_binuuid(self): return self.get_bytes().tolist()[76:76+16] def set_pi_binuuid(self, binuuid): assert 16 == len(binuuid) self.get_bytes()[76:76+16] = array.array('B', binuuid) def get_header_size(self): return UnknownOpnum4RequestHeader.__SIZE class DCERPCDcom: def __init__(self, dcerpc): self._dcerpc = dcerpc def test(self): request = RemoteActivationRequestHeader() self._dcerpc.send(request) data = self._dcerpc.recv() return data def test2(self): request = UnknownOpnum3RequestHeader() self._dcerpc.send(request) def test_lsd(self): request = UnknownOpnum4RequestHeader() self._dcerpc.send(request)
5,597
Python
.py
127
37.440945
183
0.646321
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,956
srvsvc.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/srvsvc.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: srvsvc.py,v 1.2 2006/05/23 21:19:26 gera Exp $ # # Description: # SRVSVC interface implementation. # import array from struct import * import exceptions from impacket import ImpactPacket import dcerpc import ndrutils MSRPC_UUID_SRVSVC = '\xc8\x4f\x32\x4b\x70\x16\xd3\x01\x12\x78\x5a\x47\xbf\x6e\xe1\x88\x03\x00\x00\x00' class SRVSVCNetShareGetInfoHeader(ImpactPacket.Header): OP_NUM = 0x10 __SIZE = 32 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SRVSVCNetShareGetInfoHeader.__SIZE) self._set_shalen(0) self._set_serlen(0) self.set_server_referent_id(0x0011bf74) self.set_server_max_count(0) self.set_server_offset(0) self.set_server_actual_count(0) self.set_server('') self.set_share_max_count(0) self.set_share_offset(0) self.set_share_actual_count(0) self.set_share('') self.set_info_level(0) if aBuffer: self.load_header(aBuffer) def get_server_referent_id(self): return self.get_long(0, '<') def set_server_referent_id(self, id): self.set_long(0, id, '<') def get_server_max_count(self): return self.get_long(4, '<') def set_server_max_count(self, count): self.set_long(4, count, '<') def get_server_offset(self): return self.get_long(8, '<') def set_server_offset(self, offset): self.set_long(8, offset, '<') def get_server_actual_count(self): return self.get_long(12, '<') def set_server_actual_count(self, count): self.set_long(12, count, '<') def set_server(self, name): pad = '' if len(name) % 4: pad = '\0' * (4 - len(name) % 4) name = name + pad ## 4 bytes congruency self.get_bytes()[16:16 + len(name)] = array.array('B', name) self._set_serlen(len(name)) def _set_serlen(self, len): self._serlen = len def _get_serlen(self): return self._serlen def _set_shalen(self, len): self._shalen = len def _get_shalen(self): return self._shalen def get_share_max_count(self): server_max_count = self._get_serlen() return self.get_long(16 + server_max_count, '<') def set_share_max_count(self, count): server_max_count = self._get_serlen() self.set_long(16 + server_max_count, count, '<') def get_share_offset(self): server_max_count = self._get_serlen() return self.get_long(20 + server_max_count, '<') def set_share_offset(self, offset): server_max_count = self._get_serlen() self.set_long(20 + server_max_count, offset, '<') def get_share_actual_count(self): server_max_count = self._get_serlen() return self.get_long(24 + server_max_count, '<') def set_share_actual_count(self, count): server_max_count = self._get_serlen() self.set_long(24 + server_max_count, count, '<') def set_share(self, share): server_max_count = self._get_serlen() pad = '' if len(share) % 4: pad = '\0' * (4 - len(share) % 4) share = share + pad self.get_bytes()[28 + server_max_count:28 + len(share)] = array.array('B', share) self._set_shalen(len(share)) def get_info_level(self): server_max_count = self._get_serlen() share_max_count = self._get_shalen() return self.get_long(28 + server_max_count + share_max_count, '<') def set_info_level(self, level): server_max_count = self._get_serlen() share_max_count = self._get_shalen() self.set_long(28 + server_max_count + share_max_count, level, '<') def get_header_size(self): server_max_count = self._get_serlen() share_max_count = self._get_shalen() return SRVSVCNetShareGetInfoHeader.__SIZE + server_max_count + share_max_count class SRVSVCRespNetShareGetInfoHeader(ImpactPacket.Header): __SIZE = 8 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SRVSVCRespNetShareGetInfoHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_info_level(self): return self.get_long(0, '<') def set_info_level(self, level): self.set_long(0, level, '<') def set_share_info(self, info): raise exceptions.Exception, "method not implemented" def get_share_info(self): level = self.get_info_level() if level == 2: return ndrutils.NDRPointer(self.get_bytes()[4:-4].tostring(), ShareInfoLevel2Entry) else: raise exceptions.Exception, "Share Info level not supported" def get_return_code(self): return self.get_long(len(self.get_bytes())-4, '<') def get_header_size(self): return len(self.get_bytes()) class ShareInfoLevel2Entry: def __init__(self, data = ''): self.set_netname(0) self.set_remark(0) self.set_path(0) self.set_passwd(0) if data: p_netname, self._type, p_remark, self._permissions, self._max_uses, \ self._current_uses, p_path, p_passwd = unpack('<LLLLLLLL', data[: 8 * 4]) data = data[8 * 4:] if p_netname: self.set_netname(ndrutils.NDRString(data)) dlen = self.get_netname().get_max_len() * 2 pad = 0 if dlen % 4: pad = 4 - dlen % 4 data = data[12 + dlen + pad:] if p_remark: self.set_remark(ndrutils.NDRString(data)) dlen = self.get_remark().get_max_len() * 2 pad = 0 if dlen % 4: pad = 4 - dlen % 4 data = data[12 + dlen + pad:] if p_path: self.set_path(ndrutils.NDRString(data)) dlen = self.get_path().get_max_len() * 2 pad = 0 if dlen % 4: pad = 4 - dlen % 4 data = data[12 + dlen + pad:] if p_passwd: self.set_passwd(ndrutils.NDRString(data)) dlen = self.get_passwd().get_max_len() * 2 pad = 0 if dlen % 4: pad = 4 - dlen % 4 data = data[12 + dlen + pad:] def set_netname(self, netname): self._netname = netname def get_netname(self): return self._netname def set_remark(self, remark): self._remark = remark def get_remark(self): return self._remark def set_path(self, path): self._path = path def get_path(self): return self._path def set_passwd(self, passwd): self._passwd = passwd def get_passwd(self): return self._passwd def get_type(self): return self._type def get_permissions(self): return self._permissions def get_max_uses(self): return self._max_uses def get_current_uses(self): return self._current_uses class DCERPCSrvSvc: def __init__(self, dcerpc): self._dcerpc = dcerpc def get_share_info(self, server, share, level): server += '\0' share += '\0' server = server.encode('utf-16le') share = share.encode('utf-16le') info = SRVSVCNetShareGetInfoHeader() server_len = len(server) share_len = len(share) info.set_server_max_count(server_len / 2) info.set_server_actual_count(server_len / 2) info.set_server(server) info.set_share_max_count(share_len / 2) info.set_share_actual_count(share_len / 2) info.set_share(share) info.set_info_level(2) self._dcerpc.send(info) data = self._dcerpc.recv() retVal = SRVSVCRespNetShareGetInfoHeader(data) return retVal
8,196
Python
.py
211
29.7109
102
0.583925
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,957
printer.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/printer.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: printer.py,v 1.2 2006/05/23 21:19:26 gera Exp $ # from impacket.structure import Structure def zeroize(s): return '\x00'.join(str(s)) + '\x00' class SpoolSS_DevModeContainer(Structure): alignment = 4 structure = ( ('cbBuf','<L-DevMode'), ('pDevMode','<L&DevMode'), ('DevMode',':'), ) class SpoolSS_OpenPrinter(Structure): alignment = 4 opnum = 1 structure = ( ('pPrinterName','<L&PrinterName'), ('PrinterName','w'), # ('pDataType','<L&DataType'), ('pDevMode','<L&DevMode'), ('DevMode',':',SpoolSS_DevModeContainer), ('AccessRequired','<L'), ('DataType','w'), ) class SpoolSS_PrinterInfo1(Structure): alignment = 4 structure = ( ('level','<L=1'), ('_level','<L=1'), ('pPrinterInfo1','<L=0x08081200'), ('flags','<L'), ('pDescription','<L&Description'), ('pName','<L&Name'), ('pComment','<L&Comment'), ('Description','w'), ('Name','w'), ('Comment','w'), ) class SpoolSS_PrinterInfo2(Structure): alignment = 4 structure = ( ('level','<L=2'), ('_level','<L=2'), ('pPrinterInfo2','<L=0x08081200'), ('pServerName', '<L&ServerName'), ('pPrinterName', '<L&PrinterName'), ('pShareName', '<L&ShareName'), ('pPortName', '<L&PortName'), ('pDriverName', '<L&DriverName'), ('pComment', '<L&Comment'), ('pLocation', '<L&Location'), ('pDevMode', '<L&DevMode'), ('pSepFile', '<L&SepFile'), ('pPrintProcessor', '<L&PrintProcessor'), ('pDatatype', '<L&Datatype'), ('pParameters', '<L&Parameters'), ('pSecurityDescriptor', '<L&SecurityDescriptor'), ('Attributes', '<L=0'), ('Priority', '<L=0'), ('DefaultPriority', '<L=0'), ('StartTime', '<L=0'), ('UntilTime', '<L=0'), ('Status', '<L=0'), ('cjobs', '<L=0'), ('AveragePPM', '<L=0'), ('ServerName', 'w'), ('PrinterName', 'w'), ('ShareName', 'w'), ('PortName', 'w'), ('DriverName', 'w'), ('Comment', 'w'), ('Location', 'w'), ('DevMode', ':'), ('SepFile', 'w'), ('PrintProcessor', 'w'), ('Datatype', 'w'), ('Parameters', 'w'), ('SecurityDescriptor', ':'), ) class SpoolSS_AddPrinter(Structure): # opnum from http://bob.marlboro.edu/~msie/2003/it1/tools/ethereal/ethereal-0.9.7/packet-dcerpc-spoolss.h opnum = 5 alignment = 4 structure = ( ('pName','<L&Name'), ('Name','w'), ('info',':',SpoolSS_PrinterInfo2), ('blob',':'), ) class SpoolSS_DeletePrinter(Structure): opnum = 6 alignment = 4 structure = ( ('handle','<L'), ) class SpoolSS_AddPrinterEx(Structure): opnum = 0x46 alignment = 4 structure = ( ('pName','<L=0x12345678'), ('Name','w'), ('info',':',SpoolSS_PrinterInfo2), ('blob',':'), ) class SpoolSS_EnumPrinters(Structure): opnum = 0 alignment = 4 structure = ( ('flags','<L'), ('pName','<L&Name'), ('Name','w'), ('level','<L'), ('pPrinterEnum','<L&PrinterEnum'), ('_cbBuf','<L-PrinterEnum'), ('PrinterEnum',':'), ('cbBuf','<L-PrinterEnum'), ) class SpoolSS_EnumPrinters_answer(Structure): alignment = 4 structure = ( ('pPrinterEnum','<L&PrinterEnum'), ('cbPrinterEnum','<L-PrinterEnum'), ('PrinterEnum',':'), ('cbNeeded','<L'), ('cReturned','<L'), ) class SpoolSS_EnumPorts(Structure): # fields order (in the wire) from: # http://samba.vernstok.nl/docs/htmldocs/manpages-4/pidl.1.html opnum = 0x23 alignment = 4 structure = ( ('pName','<L&Name'), ('Name','w'), ('level','<L'), ('pPort','<L&Port'), ('_cbBuf','<L-Port'), ('Port',':'), ('cbBuf','<L-Port'), ) class SpoolSS_EnumPorts_answer(Structure): alignment = 4 structure = ( ('pPort','<L&Port'), ('cbPort','<L-Port'), ('Port',':'), ('cbNeeded','<L'), ('cReturned','<L'), ) class SpoolSS_AddPort(Structure): opnum = 37 alignment = 4 structure = ( ('pName','<L&Name'), ('Name','w'), ('hWnd','<L'), ('pMonitorName','<L&MonitorName'), ('MonitorName','w'), ) class SpoolSS_PortInfo1(Structure): alignment = 4 structure = ( ('level','<L=1'), ('_level','<L=1'), ('pPortInfo1','<L=0x08081200'), ('pName','<L&Name'), ('Name','w'), ) class SpoolSS_AddPortEx(Structure): opnum = 61 alignment = 4 structure = ( ('pName','<L&Name'), ('Name','w'), ('Port',':',SpoolSS_PortInfo1), ('cbMonitorData','<L-MonitorData'), ('MonitorData',':'), # ('pMonitorName','<L&MonitorName'), ('MonitorName','w'), ) class SpoolSS_AddPrintProcessor(Structure): opnum = 14 alignment = 4 structure = ( ('pName','<L&Name'), ('Name','w'), ('pEnvironment','<L&Environment'), ('pPathName','<L&PathName'), ('pPrintProcessorName','<L&PrintProcessorName'), ('Environment','w'), ('PathName','w'), ('PrintProcessorName','w'), ) class SpoolSS_EnumMonitors(Structure): # fields order (in the wire) from: # http://samba.vernstok.nl/docs/htmldocs/manpages-4/pidl.1.html opnum = 0x24 alignment = 4 structure = ( ('pName','<L&Name'), ('Name','w'), ('level','<L'), ('pMonitor','<L&Monitor'), ('_cbBuf','<L-Monitor'), ('Monitor',':'), ('cbBuf','<L-Monitor'), ) class SpoolSS_AddMonitor(Structure): # fields order (in the wire) from: # http://samba.vernstok.nl/docs/htmldocs/manpages-4/pidl.1.html opnum = 0x2e alignment = 4 structure = ( ('pHostName','<L&HostName'), ('HostName','w'), ('level','<L'), ('level','<L'), ('pLevel','<L&level'), ('pName','<L&Name'), ('pEnvironment','<L&Environment'), ('pDLLName','<L&DLLName'), ('Name','w'), ('Environment','w'), ('DLLName','w'), ) class SpoolSS_EnumMonitors_answer(Structure): alignment = 4 structure = ( ('pMonitor','<L&Monitor'), ('cbMonitor','<L-Monitor'), ('Monitor',':'), ('cbNeeded','<L'), ('cReturned','<L'), ) PRINTER_ENUM_DEFAULT = 0x00000001 PRINTER_ENUM_LOCAL = 0x00000002 PRINTER_ENUM_CONNECTIONS = 0x00000004 PRINTER_ENUM_FAVORITE = 0x00000004 PRINTER_ENUM_NAME = 0x00000008 PRINTER_ENUM_REMOTE = 0x00000010 PRINTER_ENUM_SHARED = 0x00000020 PRINTER_ENUM_NETWORK = 0x00000040 class PrintSpooler: def __init__(self, dce): self.dce = dce def doRequest(self, request, noAnswer = 0, checkReturn = 1): self.dce.call(request.opnum, request) if noAnswer: return else: answer = self.dce.recv() if checkReturn and answer[-4:] != '\x00\x00\x00\x00': raise Exception, 'DCE-RPC call returned an error.' return answer def enumPrinters(self, name, flags = 0, level = 1): # first get the number of bytes needed enumPrinters = SpoolSS_EnumPrinters() enumPrinters['level'] = level enumPrinters['flags'] = flags enumPrinters['Name'] = name enumPrinters['PrinterEnum'] = '' ans = SpoolSS_EnumPrinters_answer(self.doRequest(enumPrinters, checkReturn = 0)) self.logDebug("enumPrinters() needing %d bytes" % ans['cbNeeded']) if ans['cbNeeded'] > 4096: raise Exception, "Buffer is too big." # do the real request enumPrinters = SpoolSS_EnumPrinters() enumPrinters['level'] = level enumPrinters['flags'] = flags enumPrinters['Name'] = name enumPrinters['PrinterEnum'] = '\x00' * ans['cbNeeded'] ans = SpoolSS_EnumPrinters_answer(self.doRequest(enumPrinters, checkReturn = 0)) # ans.dump('answer') def openPrinter(self, printerName, dataType, devMode, accessRequired): openPrinter = SpoolSS_OpenPrinter() if printerName: openPrinter['PrinterName'] = zeroize(printerName+'\x00') if dataType: openPrinter['DataType'] = zeroize(dataType+'\x00') if devMode: devModeC = SpoolSS_DevModeContainer() # devModeC['DevMode'] = devModeC devModeC['cbBuf'] = 0 devModeC['pDevMode'] = 0 devModeC['DevMode'] = '' openPrinter['DevMode'] = '\x00\x00\x00\x00' openPrinter['pDevMode'] = 0 openPrinter['AccessRequired'] = accessRequired return self.doRequest(openPrinter, checkReturn = 0) def enumPorts(self, level = 1, noAnswer = 0): # this one calls ntdll_RtlAcquirePebLock and ntdll_RtlReleasePebLock # first get the number of bytes needed enumPorts = SpoolSS_EnumPorts() enumPorts['level'] = level enumPorts['Port'] = '' if noAnswer: self.doRequest(enumPorts, noAnswer = 1) else: ans = SpoolSS_EnumPorts_answer(self.doRequest(enumPorts, checkReturn = 0)) # do the real request enumPorts = SpoolSS_EnumPorts() # enumPorts['Name'] = '\\\x00\\\x00hola\x00\x00' enumPorts['level'] = level enumPorts['Port'] = '\x00'*ans['cbNeeded'] ans = SpoolSS_EnumPorts_answer(self.doRequest(enumPorts, checkReturn = 0)) # ans.dump('answer') def enumMonitors(self, level = 1): # first get the number of bytes needed enumMonitors = SpoolSS_EnumMonitors() enumMonitors['level'] = level enumMonitors['Monitor'] = '' ans = SpoolSS_EnumMonitors_answer(self.doRequest(enumMonitors, checkReturn = 0)) # do the real request enumMonitors = SpoolSS_EnumMonitors() # enumMonitors['Name'] = '\\\x00\\\x00hola\x00\x00' enumMonitors['level'] = level enumMonitors['Monitor'] = '\x00'*ans['cbNeeded'] ans = SpoolSS_EnumMonitors_answer(self.doRequest(enumMonitors, checkReturn = 0)) # ans.dump('answer') def addMonitor(self, name, monitorName, environment, dllName): addMonitor = SpoolSS_AddMonitor() addMonitor['level'] = 2 addMonitor['HostName'] = zeroize(name) addMonitor['Name'] = zeroize(monitorName) addMonitor['Environment'] = zeroize(environment) addMonitor['DLLName'] = zeroize(dllName) ans = self.doRequest(addMonitor, checkReturn = 0) print "%r" % ans def addPort(self): addPort = SpoolSS_AddPort() addPort['Name'] = zeroize('\\192.168.22.90\x00') addPort['hWnd'] = 0 addPort['MonitorName'] = zeroize('LanMan Print Services Port\x00') return self.doRequest(addPort) def addPortEx(self): port = SpoolSS_PortInfo1() port['Name'] = zeroize('Port Name\x00') addPortEx = SpoolSS_AddPortEx() addPortEx['Name'] = zeroize('\\\\192.168.22.90\x00') addPortEx['Port'] = port addPortEx['cbMonitorData'] = 0 addPortEx['MonitorData'] = '\x00'*4 addPortEx['MonitorName'] = zeroize('Monitor Name\x00') return self.doRequest(addPortEx) def addPrintProcessor(self): addPrintProcessor = SpoolSS_AddPrintProcessor() # addPrintProcessor['Name'] = zeroize('\\\\192.168.22.90\x00') addPrintProcessor['Environment'] = zeroize('Windows NT x86\x00') addPrintProcessor['PathName'] = zeroize('C:\\hola\\manola\x00') addPrintProcessor['PrintProcessorName'] = zeroize('chaucha\x00') return self.doRequest(addPrintProcessor) def deletePrinter(self, handle): deletePrinter = SpoolSS_DeletePrinter() deletePrinter['handle'] = handle self.doRequest(deletePrinter) def addPrinter(self, serverName, name, level = 1, flags = 0, comment = None, description = None): addPrinter = SpoolSS_AddPrinter() # length(Name)+length(PrinterName)+2+2 must be the size of the chunk following the overflown if serverName is not None: addPrinter['Name'] = serverName if level == 1: addPrinter['info'] = SpoolSS_PrinterInfo1() addPrinter['info']['Name'] = name addPrinter['info']['Description'] = description addPrinter['info']['flags'] = flags elif level == 2: addPrinter['info'] = SpoolSS_PrinterInfo2() addPrinter['info']['PrinterName'] = name else: raise Exception, "Unknown PRINTER_INFO level" addPrinter['info']['Comment'] = comment addPrinter['blob'] = ( # to be improved "\x00\x00\x00\x00"*4 ) # addPrinter.dump('addPrinter') # addPrinter['info'].dump('info') return self.doRequest(addPrinter, checkReturn = 0) def addPrinterEx(self, serverName, name, comment = None): addPrinterEx = SpoolSS_AddPrinterEx() # length(Name)+length(PrinterName)+2+2 must be the size of the chunk following the overflow in mem addPrinterEx['Name'] = serverName addPrinterEx['info'] = SpoolSS_PrinterInfo2() addPrinterEx['info']['PrinterName'] = name addPrinterEx['info']['Comment'] = comment addPrinterEx['blob'] = ( # to be improved "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x01\x00\x00\x00\x01\x00\x00\x00" "\xf8\xf3\x30\x00" "\x1c\x00\x00\x00" "\xf0\x62\xc9\x00" "\xe0\xf1\x30\x00" "\x93\x08\x00\x00" "\x03\x00\x00\x00" "\x00\x00\x00\x00" "\x00\x00\x00\x00" "\x08\x00\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00" # \\ERATO "\x5c\x00\x5c\x00\x45\x00\x52\x00\x41\x00\x54\x00\x4f\x00\x00\x00" "\x0e\x00\x00\x00\x00\x00\x00\x00\x0e\x00\x00\x00" # Administrator "\x41\x00\x64\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x73\x00\x74\x00" "\x72\x00\x61\x00\x74\x00\x6f\x00\x72\x00\x00\x00" ) return self.doRequest(addPrinterEx)
15,551
Python
.py
408
28.151961
109
0.540918
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,958
winreg.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/winreg.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: winreg.py,v 1.7 2006/05/23 21:19:26 gera Exp $ # # Description: # WinReg (Windows Registry) interface implementation. # import array import struct import dcerpc from impacket import ImpactPacket MSRPC_UUID_WINREG = '\x01\xd0\x8c\x33\x44\x22\xf1\x31\xaa\xaa\x90\x00\x38\x00\x10\x03\x01\x00\x00\x00' # Registry Security Access Mask values KEY_CREATE_LINK = 0x20 KEY_CREATE_SUB_KEY = 0x04 KEY_ENUMERATE_SUB_KEYS = 0x08 KEY_EXECUTE = 0x20019 KEY_NOTIFY = 0x10 KEY_QUERY_VALUE = 0x01 KEY_SET_VALUE = 0x02 KEY_ALL_ACCESS = 0xF003F KEY_READ = 0x20019 KEY_WRITE = 0x20006 # Registry Data types REG_NONE = 0 # No value type REG_SZ = 1 # Unico nul terminated string REG_EXPAND_SZ = 2 # Unicode nul terminated string # (with environment variable references) REG_BINARY = 3 # // Free form binary REG_DWORD = 4 # // 32-bit number REG_DWORD_LITTLE_ENDIAN = 4 # // 32-bit number (same as REG_DWORD) REG_DWORD_BIG_ENDIAN = 5 # // 32-bit number REG_LINK = 6 # // Symbolic Link (unicode) REG_MULTI_SZ = 7 # // Multiple Unicode strings REG_RESOURCE_LIST = 8 # // Resource list in the resource map REG_FULL_RESOURCE_DESCRIPTOR = 9 # Resource list in the hardware description REG_RESOURCE_REQUIREMENTS_LIST = 10 class WINREGCloseKey(ImpactPacket.Header): OP_NUM = 5 __SIZE = 20 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGCloseKey.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_header_size(self): return WINREGCloseKey.__SIZE class WINREGRespCloseKey(ImpactPacket.Header): __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGRespCloseKey.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_return_code(self): return self.get_long(20, '<') def set_return_code(self, code): self.set_long(20, code, '<') def get_header_size(self): return WINREGRespCloseKey.__SIZE class WINREGDeleteValue(ImpactPacket.Header): OP_NUM = 8 __SIZE = 40 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGDeleteValue.__SIZE) # Write some unknown fluff. self.get_bytes()[22:36] = array.array('B', '\x0a\x02\x00\xEC\xfd\x7f\x05\x01' + (6 * '\x00')) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_name(self): return unicode(self.get_bytes().tostring()[40:], 'utf-16le') def set_name(self, name): if not name.endswith('\0'): name += '\0' namelen = len(name) wlen = 2 * namelen if (wlen % 4): pad = ('\x00' * (4 - (wlen % 4))) else: pad = '' self.set_word(20, 2 * namelen, '<') self.set_long(36, namelen, '<') self.get_bytes()[40:] = array.array('B', name.encode('utf-16le') + pad) def get_header_size(self): var_size = len(self.get_bytes()) - WINREGDeleteValue.__SIZE assert var_size > 0 return WINREGDeleteValue.__SIZE + var_size class WINREGRespDeleteValue(ImpactPacket.Header): __SIZE = 4 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGRespDeleteValue.__SIZE) if aBuffer: self.load_header(aBuffer) def get_return_code(self): return self.get_long(0, '<') def set_return_code(self, code): self.set_long(0, code, '<') def get_header_size(self): return WINREGRespDeleteValue.__SIZE class WINREGDeleteKey(ImpactPacket.Header): OP_NUM = 7 __SIZE = 40 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGDeleteKey.__SIZE) # Write some unknown fluff. self.get_bytes()[22:36] = array.array('B', '\x0a\x02\x00\xEC\xfd\x7f\x05\x01' + (6 * '\x00')) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_key_name(self): return unicode(self.get_bytes().tostring()[40:], 'utf-16le') def set_key_name(self, name): if not name.endswith('\0'): name += '\0' namelen = len(name) wlen = 2 * namelen if (wlen % 4): pad = ('\x00' * (4 - (wlen % 4))) else: pad = '' self.set_word(20, 2 * namelen, '<') self.set_long(36, namelen, '<') self.get_bytes()[40:] = array.array('B', name.encode('utf-16le') + pad) def get_header_size(self): var_size = len(self.get_bytes()) - WINREGDeleteKey.__SIZE assert var_size > 0 return WINREGDeleteKey.__SIZE + var_size class WINREGRespDeleteKey(ImpactPacket.Header): __SIZE = 4 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGRespDeleteKey.__SIZE) if aBuffer: self.load_header(aBuffer) def get_return_code(self): return self.get_long(0, '<') def set_return_code(self, code): self.set_long(0, code, '<') def get_header_size(self): return WINREGRespDeleteKey.__SIZE class WINREGCreateKey(ImpactPacket.Header): OP_NUM = 6 __SIZE = 64 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGCreateKey.__SIZE) # Write some unknown fluff. self.get_bytes()[22:36] = array.array('B', '\x0a\x02\x00\xEC\xfd\x7f\x05\x01' + (6 * '\x00')) self.get_bytes()[-24:] = array.array('B', 15 * '\x00' + '\x02' + 8 * '\x00') if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_key_name(self): return unicode(self.get_bytes().tostring()[40:-24], 'utf-16le') def set_key_name(self, name): if not name.endswith('\0'): name += '\0' namelen = len(name) wlen = 2 * namelen if (wlen % 4): pad = ('\x00' * (4 - (wlen % 4))) else: pad = '' self.set_word(20, 2 * namelen, '<') self.set_long(36, namelen, '<') self.get_bytes()[40:-24] = array.array('B', name.encode('utf-16le') + pad) def get_header_size(self): var_size = len(self.get_bytes()) - WINREGCreateKey.__SIZE assert var_size > 0 return WINREGCreateKey.__SIZE + var_size class WINREGRespCreateKey(ImpactPacket.Header): __SIZE = 28 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGRespCreateKey.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_return_code(self): return self.get_long(24, '<') def set_return_code(self, code): self.set_long(24, code, '<') def get_header_size(self): return WINREGRespCreateKey.__SIZE #context handle # WORD LEN (counting the 0s) # DWORD LEN (in unicode, that is without counting the 0s) # KEYNAME in UNICODE # 6 bytes UNKNOWN (all 0s) # DWORD ACCESS_MASK class WINREGOpenKey(ImpactPacket.Header): OP_NUM = 15 __SIZE = 44 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGOpenKey.__SIZE) self.set_access_mask(KEY_READ) # Write some unknown fluff. self.get_bytes()[24:28] = array.array('B', '\x00\xEC\xfd\x7f') if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_key_name(self): return unicode(self.get_bytes().tostring()[40:-4], 'utf-16le') def set_key_name(self, name): if not name.endswith('\0'): name += '\0' namelen = len(name) padlen = 2 * (int((namelen + 2) / 4) * 4 + 2 - namelen) pad = '\x00' * padlen self.set_word(20, 2 * namelen, '<') self.set_word(22, 2 * namelen, '<') self.set_long(28, namelen, '<') self.set_long(36, namelen, '<') self.get_bytes()[40:-4] = array.array('B', name.encode('utf-16le') + pad) def get_access_mask(self): return self.get_long(-4, '<') def set_access_mask(self, mask): self.set_long(-4, mask, '<') def get_header_size(self): var_size = len(self.get_bytes()) - WINREGOpenKey.__SIZE assert var_size > 0 return WINREGOpenKey.__SIZE + var_size class WINREGRespOpenKey(ImpactPacket.Header): __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGRespOpenKey.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_return_code(self): return self.get_long(20, '<') def set_return_code(self, code): self.set_long(20, code, '<') def get_header_size(self): return WINREGRespOpenKey.__SIZE class WINREGSetValue(ImpactPacket.Header): OP_NUM = 22 __SIZE = 52 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGSetValue.__SIZE) # Write some unknown fluff. self.get_bytes()[24:28] = array.array('B', '\x00\xEC\xfd\x7f') self.namelen = 0 if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_name(self): return unicode(self.get_bytes().tostring()[40:40+self.namelen], 'utf-16le') def set_name(self, name): if not name.endswith('\0'): name += '\0' namelen = len(name) if namelen & 0x01: pad = '\x00\x00' else: pad = '' self.set_word(20, 2 * namelen, '<') self.set_word(22, 2 * namelen, '<') self.set_long(28, namelen, '<') self.set_long(36, namelen, '<') padded_name = array.array('B', name.encode('utf-16le') + pad) self.get_bytes()[40:40+self.namelen] = padded_name self.namelen = len(padded_name) def get_data_type(self): return self.get_long(40+self.namelen, '<') def set_data_type(self, type): self.set_long(40+self.namelen, type, '<') def get_data(self): data_type = self.get_data_type() data = self.get_bytes().tostring()[40+self.namelen+8:-4] if data_type == REG_DWORD: data = struct.unpack('<L', data)[0] elif data_type == REG_SZ: data = unicode(data, 'utf-16le') return data def set_data(self, data): data_type = self.get_data_type() pad = '' if data_type == REG_DWORD: data = struct.pack('<L', data) elif data_type == REG_SZ: if not data.endswith('\0'): data += '\0' if len(data) & 0x01: pad = '\x00\x00' data = data.encode('utf-16le') elif data_type == REG_BINARY: if len(data) & 0x01: pad = '\x00\x00' datalen = len(data) self.set_long(40+self.namelen+4, datalen, '<') self.set_long(-4, datalen, '<') self.get_bytes()[40+self.namelen+8:-4] = array.array('B', data + pad) def get_header_size(self): var_size = len(self.get_bytes()) - WINREGSetValue.__SIZE assert var_size > 0 return WINREGSetValue.__SIZE + var_size class WINREGRespSetValue(ImpactPacket.Header): __SIZE = 4 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGRespSetValue.__SIZE) if aBuffer: self.load_header(aBuffer) def get_return_code(self): return self.get_long(0, '<') def set_return_code(self, code): self.set_long(0, code, '<') def get_header_size(self): return WINREGRespSetValue.__SIZE # context_handle # len # \x0a\x02\x00\xec\xfd\x7f\x05\x01 \x00 * 6 # len /2 # valuename class WINREGQueryValue(ImpactPacket.Header): OP_NUM = 17 __SIZE = 80 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGQueryValue.__SIZE) self.set_data_len(0xC8) # Write some unknown fluff. self.get_bytes()[24:28] = array.array('B', '\x00\xEC\xfd\x7f') self.get_bytes()[-40:-28] = array.array('B', '\x8c\xfe\x12\x00\x69\x45\x13\x00\x69\x45\x13\x00') self.get_bytes()[-16:-12] = array.array('B', '\x94\xfe\x12\x00') self.get_bytes()[-8:-4] = array.array('B', '\x80\xfe\x12\x00') if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_name(self): return unicode(self.get_bytes().tostring()[40:-40], 'utf-16le') def set_name(self, name): if not name.endswith('\0'): name += '\0' namelen = len(name) if namelen & 0x01: pad = '\x00\x00' else: pad = '' self.set_word(20, 2 * namelen, '<') self.set_word(22, 2 * namelen, '<') self.set_long(28, namelen, '<') self.set_long(36, namelen, '<') self.get_bytes()[40:-40] = array.array('B', name.encode('utf-16le') + pad) def get_data_len(self): return self.get_long(-28, '<') def set_data_len(self, len): self.set_long(-28, len, '<') self.set_long(-12, len, '<') def get_header_size(self): var_size = len(self.get_bytes()) - WINREGQueryValue.__SIZE assert var_size > 0 return WINREGQueryValue.__SIZE + var_size class WINREGRespQueryValue(ImpactPacket.Header): __SIZE = 44 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGRespQueryValue.__SIZE) if aBuffer: self.load_header(aBuffer) def get_data_type(self): return self.get_long(4, '<') def set_data_type(self, type): self.set_long(4, type, '<') def get_data_len(self): return self.get_long(20, '<') def set_data_len(self, len): self.set_long(20, len, '<') self.set_long(28, len, '<') def get_data(self): data_type = self.get_data_type() data = self.get_bytes().tostring()[24:24+self.get_data_len()] if data_type == REG_DWORD: data = struct.unpack('<L', data)[0] elif data_type == REG_SZ: data = unicode(data, 'utf-16le') return data def set_data(self, len): raise Exception, "method not implemented" def get_return_code(self): return self.get_long(-4, '<') def set_return_code(self, code): self.set_long(-4, code, '<') def get_header_size(self): var_size = len(self.get_bytes()) - WINREGRespQueryValue.__SIZE assert var_size > 0 return WINREGRespQueryValue.__SIZE + var_size class WINREGOpenHK(ImpactPacket.Header): # OP_NUM is a "virtual" field. __SIZE = 12 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGOpenHK.__SIZE) self.set_long(0, 0x06f7c0, '<') # magic, apparently always the same self.set_long(4, 0x019b58, '<') # don't know exactly, can be almost anything so far self.set_access_mask(0x2000000) if aBuffer: self.load_header(aBuffer) def get_access_mask(self): return self.get_long(8, '<') def set_access_mask(self, mask): self.set_long(8, mask, '<') def get_header_size(self): return WINREGOpenHK.__SIZE class WINREGRespOpenHK(ImpactPacket.Header): __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, WINREGRespOpenHK.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_return_code(self): return self.get_long(20, '<') def set_return_code(self, code): self.set_long(20, code, '<') def get_header_size(self): return WINREGRespOpenHK.__SIZE class WINREGOpenHKCR(WINREGOpenHK): OP_NUM = 0 class WINREGOpenHKLM(WINREGOpenHK): OP_NUM = 2 class WINREGOpenHKU(WINREGOpenHK): OP_NUM = 4 class DCERPCWinReg: def __init__(self, dce): self._dce = dce def openHKCR(self): winregopen = WINREGOpenHKCR() self._dce.send(winregopen) data = self._dce.recv() retVal = WINREGRespOpenHK(data) return retVal def openHKU(self): winregopen = WINREGOpenHKU() self._dce.send(winregopen) data = self._dce.recv() retVal = WINREGRespOpenHK(data) return retVal def regCloseKey(self, context_handle): wreg_closekey = WINREGCloseKey() wreg_closekey.set_context_handle( context_handle ) self._dce.send(wreg_closekey) data = self._dce.recv() retVal = WINREGRespCloseKey(data) return retVal def regOpenKey(self, context_handle, aKeyname, anAccessMask): wreg_openkey = WINREGOpenKey() wreg_openkey.set_context_handle( context_handle ) wreg_openkey.set_key_name( aKeyname ) wreg_openkey.set_access_mask( anAccessMask ) self._dce.send(wreg_openkey) data = self._dce.recv() retVal = WINREGRespOpenKey(data) return retVal def regCreateKey(self, context_handle, aKeyname): wreg_createkey = WINREGCreateKey() wreg_createkey.set_context_handle( context_handle ) wreg_createkey.set_key_name( aKeyname ) self._dce.send(wreg_createkey) data = self._dce.recv() retVal = WINREGRespCreateKey(data) return retVal def regDeleteKey(self, context_handle, aKeyname): wreg_deletekey = WINREGDeleteKey() wreg_deletekey.set_context_handle( context_handle ) wreg_deletekey.set_key_name( aKeyname ) self._dce.send(wreg_deletekey) data = self._dce.recv() retVal = WINREGRespDeleteKey(data) return retVal def regDeleteValue(self, context_handle, aValuename): wreg_deletevalue = WINREGDeleteValue() wreg_deletevalue.set_context_handle( context_handle ) wreg_deletevalue.set_name( aValuename ) self._dce.send(wreg_deletevalue) data = self._dce.recv() retVal = WINREGRespDeleteValue(data) return retVal def regQueryValue(self, context_handle, aValueName, aDataLen): wreg_queryval = WINREGQueryValue() wreg_queryval.set_context_handle( context_handle ) wreg_queryval.set_name( aValueName ) wreg_queryval.set_data_len( aDataLen ) self._dce.send(wreg_queryval) data = self._dce.recv() retVal = WINREGRespQueryValue(data) return retVal def regSetValue(self, context_handle, aValueType, aValueName, aData): wreg_setval = WINREGSetValue() wreg_setval.set_context_handle( context_handle ) wreg_setval.set_data_type(aValueType) wreg_setval.set_name(aValueName) wreg_setval.set_data(aData) self._dce.send(wreg_setval) data = self._dce.recv() retVal = WINREGRespSetValue(data) return retVal def openHKLM(self): winregopen = WINREGOpenHKLM() self._dce.send(winregopen) data = self._dce.recv() retVal = WINREGRespOpenHK(data) return retVal
21,401
Python
.py
530
32.877358
104
0.604976
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,959
samr.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/impacket/dcerpc/samr.py
# Copyright (c) 2003-2006 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # $Id: samr.py,v 1.7 2006/05/23 21:19:26 gera Exp $ # # Description: # SAMR (Security Account Manager Remote) interface implementation. # import array from time import strftime, gmtime from struct import * from impacket import ImpactPacket import dcerpc import ndrutils MSRPC_UUID_SAMR = '\x78\x57\x34\x12\x34\x12\xcd\xab\xef\x00\x01\x23\x45\x67\x89\xac\x01\x00\x00\x00' OP_NUM_CREATE_USER_IN_DOMAIN = 0xC OP_NUM_ENUM_USERS_IN_DOMAIN = 0xD OP_NUM_CREATE_ALIAS_IN_DOMAIN = 0xE def display_time(filetime_high, filetime_low, minutes_utc=0): d = filetime_high*4.0*1.0*(1<<30) d += filetime_low d *= 1.0e-7 d -= (369.0*365.25*24*60*60-(3.0*24*60*60+6.0*60*60)) if minutes_utc == 0: r = (strftime("%a, %d %b %Y %H:%M:%S",gmtime(d)), minutes_utc/60)[0] else: r = "%s GMT %d " % (strftime("%a, %d %b %Y %H:%M:%S",gmtime(d)), minutes_utc/60) return r class MSRPCUserInfo: ITEMS = {'Account Name':0, 'Full Name':1, 'Home':2, 'Home Drive':3, 'Script':4, 'Profile':5, 'Description':6, 'Workstations':7, 'Comment':8, 'Parameters':9, 'Logon hours':10 } def __init__(self, data = None): self._logon_time_low = 0 self._logon_time_high = 0 self._logoff_time_low = 0 self._logoff_time_high = 0 self._kickoff_time_low = 0 self._kickoff_time_high = 0 self._pwd_last_set_low = 0 self._pwd_last_set_high = 0 self._pwd_can_change_low = 0 self._pwd_can_change_high = 0 self._pwd_must_change_low = 0 self._pwd_must_change_high = 0 self._items = [] self._rid = 0 self._group = 0 self._acct_ctrl = 0 self._bad_pwd_count = 0 self._logon_count = 0 self._country = 0 self._codepage = 0 self._nt_pwd_set = 0 self._lm_pwd_set = 0 if data: self.set_header(data) def set_header(self,data): index = 8 self._logon_time_low, self._logon_time_high, self._logoff_time_low, self._logoff_time_high, self._kickoff_time_low,self._kickoff_time_high, self._pwd_last_set_low,self._pwd_last_set_high, self._pwd_can_change_low,self._pwd_can_change_high, self._pwd_must_change_low, self._pwd_must_change_high = unpack('<LLLLLLLLLLLL',data[index:index+48]) index += 48 for i in range(0,len(MSRPCUserInfo.ITEMS)-1): length, size, id = unpack('<HHL',data[index:index+8]) self._items.append(dcerpc.MSRPCArray(length, size, id)) index += 8 index += 24 # salteo los unknowns item_count = unpack('<L',data[index:index+4])[0] index += 4 + (item_count+1) * 4 # Esto no lo se!! salteo buffer self._rid, self._group, self._acct_ctr,_ = unpack('<LLLL',data[index: index+16]) index += 16 logon_divisions, _, id = unpack('<HHL',data[index:index+8]) self._items.append(dcerpc.MSRPCArray(logon_divisions, _, id)) index += 8 self._bad_pwd_count, self._logon_count, self._country, self._codepage = unpack('<HHHH', data[index: index + 8]) index += 8 self._nt_pwd_set, self._lm_pwd_set,_,_= unpack('<BBBB', data[index:index+4]) index += 4 for item in self._items[:-1]: # Except LOGON_HOUNS if 0 == item.get_size(): continue max_len, offset, curlen = unpack('<LLL', data[index:index+12]) index += 12 item.set_name(unicode(data[index:index+2*curlen], 'utf-16le')) item.set_max_len(max_len) item.set_offset(offset) item.set_length2(curlen) index += 2*curlen if curlen & 0x1: index += 2 # Skip padding. # Process LOGON_HOURS. # This is a bitmask of logon_divisions bits. Normally logon_divisions is 168, one bit per hour of a whole week. item = self._items[10] max_len, offset, curlen = unpack('<LLL', data[index:index+12]) index += 12 item.set_name('Unlimited') # I admit this routine is not very clever. We could do a better mapping to human readable format. for b in data[index: index+curlen]: if 0xFF != ord(b): item.set_name('Unknown') def get_num_items(self): return len(self._items) def get_items(self): return self._items def get_logon_time(self): return display_time(self._logon_time_high, self._logon_time_low) def get_logoff_time(self): return display_time(self._logoff_time_high, self._logoff_time_low) def get_kickoff_time(self): return display_time(self._kickoff_time_high, self._kickoff_time_low) def get_pwd_last_set(self): return display_time(self._pwd_last_set_high, self._pwd_last_set_low) def get_pwd_can_change(self): return display_time(self._pwd_can_change_high, self._pwd_can_change_low) def get_group_id(self): return self._group def get_bad_pwd_count(self): return self._bad_pwd_count def get_logon_count(self): return self._logon_count def get_pwd_must_change(self): if self._pwd_must_change_low == 4294967295L: return "Infinity" else: return display_time(self._pwd_must_change_high, self._pwd_must_change_low) def is_enabled(self): return not (self._acct_ctr & 0x01) def print_friendly(self): print "Last Logon: " + display_time(self._logon_time_high, self._logon_time_low) print "Last Logoff: " + display_time(self._logoff_time_high, self._logoff_time_low) print "Kickoff Time: " + display_time(self._kickoff_time_high, self._kickoff_time_low) print "PWD Last Set: " + display_time(self._pwd_last_set_high, self._pwd_last_set_low) print "PWD Can Change: " + display_time(self._pwd_can_change_high, self._pwd_can_change_low) print "Group id: %d" % self._group print "Bad pwd count: %d" % self._bad_pwd_count print "Logon count: %d" % self._logon_count if self._pwd_must_change_low == 4294967295L: print "PWD Must Change: Infinity" else: print "PWD Must Change: " + display_time(self._pwd_must_change_high, self._pwd_must_change_low) for i in MSRPCUserInfo.ITEMS.keys(): print i + ': ' + self._items[MSRPCUserInfo.ITEMS[i]].get_name() print return class SAMRConnectHeader(ImpactPacket.Header): OP_NUM = 0x39 __SIZE = 4 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRConnectHeader.__SIZE) self.__sptr = ndrutils.NDRPointer() self.set_server('') self.set_access_mask(0x2000000) if aBuffer: self.load_header(aBuffer) def get_server(self): return ndrutils.NDRPointer(self.get_bytes()[:-4].tostring(), ndrutils.NDRString) def set_server(self, name): ss = ndrutils.NDRString() ss.set_string(name) self.__sptr.set_pointer(ss) data = self.__sptr.rawData() self.get_bytes()[:-4] = array.array('B', data) def get_access_mask(self): return self.get_long(-4, '<') def set_access_mask(self, mask): self.set_long(-4, mask, '<') def get_header_size(self): var_size = len(self.get_bytes()) - SAMRConnectHeader.__SIZE assert var_size > 0 return SAMRConnectHeader.__SIZE + var_size class SAMRRespConnectHeader(ImpactPacket.Header): __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRRespConnectHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tostring()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_return_code(self): return self.get_long(20, '<') def set_return_code(self, code): self.set_long(20, code, '<') def get_header_size(self): return SAMRRespConnectHeader.__SIZE class SAMREnumDomainsHeader(ImpactPacket.Header): OP_NUM = 0x6 __SIZE = 28 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMREnumDomainsHeader.__SIZE) self.set_pref_max_size(8192) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_resume_handle(self): return self.get_long(20, '<') def set_resume_handle(self, handle): self.set_long(20, handle, '<') def get_pref_max_size(self): return self.get_long(24, '<') def set_pref_max_size(self, size): self.set_long(24, size, '<') def get_header_size(self): return SAMREnumDomainsHeader.__SIZE class SAMRRespEnumDomainHeader(ImpactPacket.Header): __SIZE = 12 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRRespEnumDomainHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_resume_handle(self): return self.get_long(0, '<') def set_resume_handle(self, handle): self.set_long(0, handle, '<') def get_domains(self): return dcerpc.MSRPCNameArray(self.get_bytes()[4:-8].tostring()) def set_domains(self, domains): assert isinstance(domains, dcerpc.MSRPCNameArray) self.get_bytes()[4:-8] = array.array('B', domains.rawData()) def get_entries_num(self): return self.get_long(-8, '<') def set_entries_num(self, num): self.set_long(-8, num, '<') def get_return_code(self): return self.get_long(-4, '<') def set_return_code(self, code): self.set_long(-4, code, '<') def get_header_size(self): var_size = len(self.get_bytes()) - SAMRRespEnumDomainHeader.__SIZE assert var_size > 0 return SAMRRespEnumDomainHeader.__SIZE + var_size class SAMRLookupDomainHeader(ImpactPacket.Header): OP_NUM = 0x5 __SIZE = 20 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRLookupDomainHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_domain(self): return dcerpc.MSRPCArray(self.get_bytes().tolist()[20:]) def set_domain(self, domain): assert isinstance(domain, dcerpc.MSRPCArray) self.get_bytes()[20:] = array.array('B', domain.rawData()) def get_header_size(self): var_size = len(self.get_bytes()) - SAMRLookupDomainHeader.__SIZE assert var_size > 0 return SAMRLookupDomainHeader.__SIZE + var_size class SAMRRespLookupDomainHeader(ImpactPacket.Header): __SIZE = 36 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRRespLookupDomainHeader.__SIZE) if aBuffer: self.load_header(aBuffer) ## def get_sid_count(self): ## return self.get_long(4, '<') ## def set_sid_count(self, count): ## self.set_long(4, count, '<') ## def get_domain_sid(self): ## return self.get_bytes().tolist()[8:8+24] ## def set_domain_sid(self, sid): ## assert 24 == len(sid) ## self.get_bytes()[8:8+24] = array.array('B', sid) def get_domain_sid(self): return self.get_bytes().tolist()[4:4+28] def set_domain_sid(self, sid): assert 28 == len(sid) self.get_bytes()[4:4+28] = array.array('B', sid) def get_return_code(self): return self.get_long(32, '<') def set_return_code(self, code): self.set_long(32, code, '<') def get_header_size(self): return SAMRRespLookupDomainHeader.__SIZE class SAMROpenDomainHeader(ImpactPacket.Header): OP_NUM = 0x7 __SIZE = 52 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMROpenDomainHeader.__SIZE) self.set_access_mask(0x304) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_access_mask(self): return self.get_long(20, '<') def set_access_mask(self, mask): self.set_long(20, mask, '<') ## def get_sid_count(self): ## return self.get_long(24, '<') ## def set_sid_count(self, count): ## self.set_long(24, count, '<') ## def get_domain_sid(self): ## return self.get_bytes().tolist()[28:28+24] ## def set_domain_sid(self, sid): ## assert 24 == len(sid) ## self.get_bytes()[28:28+24] = array.array('B', sid) def get_domain_sid(self): return self.get_bytes().tolist()[24:24+28] def set_domain_sid(self, sid): assert 28 == len(sid) self.get_bytes()[24:24+28] = array.array('B', sid) def get_header_size(self): return SAMROpenDomainHeader.__SIZE class SAMRRespOpenDomainHeader(ImpactPacket.Header): __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRRespOpenDomainHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_return_code(self): return self.get_long(20, '<') def set_return_code(self, code): self.set_long(20, code, '<') def get_header_size(self): return SAMRRespOpenDomainHeader.__SIZE class SAMREnumDomainUsersHeader(ImpactPacket.Header): OP_NUM = OP_NUM_ENUM_USERS_IN_DOMAIN __SIZE = 32 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMREnumDomainUsersHeader.__SIZE) self.set_pref_max_size(3275) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_resume_handle(self): return self.get_long(20, '<') def set_resume_handle(self, handle): self.set_long(20, handle, '<') def get_account_control(self): return self.get_long(24, '<') def set_account_control(self, mask): self.set_long(24, mask, '<') def get_pref_max_size(self): return self.get_long(28, '<') def set_pref_max_size(self, size): self.set_long(28, size, '<') def get_header_size(self): return SAMREnumDomainUsersHeader.__SIZE class SAMRRespEnumDomainUsersHeader(ImpactPacket.Header): __SIZE = 16 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRRespEnumDomainUsersHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_resume_handle(self): return self.get_long(0, '<') def set_resume_handle(self, handle): self.set_long(0, handle, '<') def get_users(self): return dcerpc.MSRPCNameArray(self.get_bytes()[4:-8].tostring()) def set_users(self, users): assert isinstance(users, dcerpc.MSRPCNameArray) self.get_bytes()[4:-8] = array.array('B', users.rawData()) def get_entries_num(self): return self.get_long(-8, '<') def set_entries_num(self, num): self.set_long(-8, num, '<') def get_return_code(self): return self.get_long(-4, '<') def set_return_code(self, code): self.set_long(-4, code, '<') def get_header_size(self): var_size = len(self.get_bytes()) - SAMRRespEnumDomainUsersHeader.__SIZE assert var_size > 0 return SAMRRespEnumDomainUsersHeader.__SIZE + var_size class SAMROpenUserHeader(ImpactPacket.Header): OP_NUM = 0x22 __SIZE = 28 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMROpenUserHeader.__SIZE) self.set_access_mask(0x2011B) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_access_mask(self): return self.get_long(20, '<') def set_access_mask(self, mask): self.set_long(20, mask, '<') def get_rid(self): return self.get_long(24, '<') def set_rid(self, id): self.set_long(24, id, '<') def get_header_size(self): return SAMROpenUserHeader.__SIZE class SAMRRespOpenUserHeader(ImpactPacket.Header): __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRRespOpenUserHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_return_code(self): return self.get_long(20, '<') def set_return_code(self, code): self.set_long(20, code, '<') def get_header_size(self): return SAMRRespOpenUserHeader.__SIZE class SAMRQueryUserInfoHeader(ImpactPacket.Header): OP_NUM = 0x24 __SIZE = 22 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRQueryUserInfoHeader.__SIZE) self.set_level(21) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_level(self): return self.get_word(20, '<') def set_level(self, level): self.set_word(20, level, '<') def get_header_size(self): return SAMRQueryUserInfoHeader.__SIZE class SAMRRespQueryUserInfoHeader(ImpactPacket.Header): __SIZE = 4 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRRespQueryUserInfoHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_user_info(self): return MSRPCUserInfo(self.get_bytes()[:-4].tostring()) def set_user_info(self, info): assert isinstance(info, MSRPCUserInfo) self.get_bytes()[:-4] = array.array('B', info.rawData()) def get_return_code(self): return self.get_long(-4, '<') def set_return_code(self, code): self.set_long(-4, code, '<') def get_header_size(self): var_size = len(self.get_bytes()) - SAMRRespQueryUserInfoHeader.__SIZE assert var_size > 0 return SAMRRespQueryUserInfoHeader.__SIZE + var_size class SAMRCloseRequestHeader(ImpactPacket.Header): OP_NUM = 0x1 __SIZE = 20 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRCloseRequestHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_header_size(self): return SAMRCloseRequestHeader.__SIZE class SAMRRespCloseRequestHeader(ImpactPacket.Header): __SIZE = 24 def __init__(self, aBuffer = None): ImpactPacket.Header.__init__(self, SAMRRespCloseRequestHeader.__SIZE) if aBuffer: self.load_header(aBuffer) def get_context_handle(self): return self.get_bytes().tolist()[:20] def set_context_handle(self, handle): assert 20 == len(handle) self.get_bytes()[:20] = array.array('B', handle) def get_return_code(self): return self.get_long(20, '<') def set_return_code(self, code): self.set_long(20, code, '<') def get_header_size(self): return SAMRRespCloseRequestHeader.__SIZE class DCERPCSamr: def __init__(self, dcerpc): self._dcerpc = dcerpc def connect(self): samrcon = SAMRConnectHeader() samrcon.set_server('*SMBSERVER') self._dcerpc.send(samrcon) data = self._dcerpc.recv() retVal = SAMRRespConnectHeader(data) return retVal def enumdomains(self,context_handle): enumdom = SAMREnumDomainsHeader() enumdom.set_context_handle(context_handle) self._dcerpc.send(enumdom) data = self._dcerpc.recv() retVal = SAMRRespEnumDomainHeader(data) return retVal def lookupdomain(self,context_handle,domain): lookupdom = SAMRLookupDomainHeader() lookupdom.set_context_handle(context_handle) lookupdom.set_domain(domain) self._dcerpc.send(lookupdom) data = self._dcerpc.recv() retVal = SAMRRespLookupDomainHeader(data) return retVal def opendomain(self,context_handle,domain_sid): opendom = SAMROpenDomainHeader() opendom.set_context_handle(context_handle) opendom.set_domain_sid(domain_sid) self._dcerpc.send(opendom) data = self._dcerpc.recv() retVal = SAMRRespOpenDomainHeader(data) return retVal def enumusers(self,context_handle): enumusers = SAMREnumDomainUsersHeader() enumusers.set_context_handle(context_handle) self._dcerpc.send(enumusers) data = self._dcerpc.recv() retVal = SAMRRespEnumDomainUsersHeader(data) return retVal def openuser(self,context_handle, rid): openuser = SAMROpenUserHeader() openuser.set_context_handle(context_handle) openuser.set_rid(rid) self._dcerpc.send(openuser) data = self._dcerpc.recv() retVal = SAMRRespOpenUserHeader(data) return retVal def queryuserinfo(self,context_handle): userinfo = SAMRQueryUserInfoHeader() userinfo.set_context_handle(context_handle) self._dcerpc.send(userinfo) data = self._dcerpc.recv() retVal = SAMRRespQueryUserInfoHeader(data) return retVal def closerequest(self,context_handle): closereq = SAMRCloseRequestHeader() closereq.set_context_handle(context_handle) self._dcerpc.send(closereq) data = self._dcerpc.recv() retVal = SAMRRespCloseRequestHeader(data) return retVal
23,192
Python
.py
552
34.5
348
0.628021
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,960
crashbin_explorer.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/s_utils/crashbin_explorer.py
#!c:\\python\\python.exe import getopt import sys # this command should be ran from VoIPER/sulley but the following # should make it work from VoIPER/ as well # Ridiculously hack-y sys.path.append(r".") sys.path.append(r"sulley/sulley") sys.path.append(r"sulley") sys.path.append(r"s_utils") import s_utils import pgraph USAGE = "\nUSAGE: crashbin_explorer.py <xxx.crashbin>" \ "\n [-t|--test #] dump the crash synopsis for a specific test case number" \ "\n [-g|--graph name] generate a graph of all crash paths, save to 'name'.udg\n" # # parse command line options. # try: if len(sys.argv) < 2: raise Exception opts, args = getopt.getopt(sys.argv[2:], "t:g:", ["test=", "graph="]) except: print USAGE sys.exit(1) test_number = graph_name = graph = None for opt, arg in opts: if opt in ("-t", "--test"): test_number = int(arg) if opt in ("-g", "--graph"): graph_name = arg crashbin = s_utils.crash_binning.crash_binning() crashbin.import_file(sys.argv[1]) # # display the full crash dump of a specific test case # if test_number: for bin, crashes in crashbin.bins.iteritems(): for crash in crashes: if test_number == crash.extra: print crashbin.crash_synopsis(crash) sys.exit(0) # # display an overview of all recorded crashes. # if graph_name: graph = pgraph.graph() for bin, crashes in crashbin.bins.iteritems(): synopsis = crashbin.crash_synopsis(crashes[0]).split("\n")[0] if graph: crash_node = pgraph.node(crashes[0].exception_address) crash_node.count = len(crashes) crash_node.label = "[%d] %s.%08x" % (crash_node.count, crashes[0].exception_module, crash_node.id) graph.add_node(crash_node) print "[%d] %s" % (len(crashes), synopsis) print "\t", for crash in crashes: if graph: last = crash_node.id for entry in crash.stack_unwind: address = long(entry.split(":")[1], 16) n = graph.find_node("id", address) if not n: n = pgraph.node(address) n.count = 1 n.label = "[%d] %s" % (n.count, entry) graph.add_node(n) else: n.count += 1 n.label = "[%d] %s" % (n.count, entry) edge = pgraph.edge.edge(n.id, last) graph.add_edge(edge) last = n.id print "%d," % crash.extra, print "\n" if graph: fh = open("%s.udg" % graph_name, "w+") fh.write(graph.render_graph_udraw()) fh.close()
2,716
Python
.py
77
28.168831
106
0.57563
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,961
crash_binning.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/s_utils/crash_binning.py
# # Crash Binning # Copyright (C) 2006 Pedram Amini <pedram.amini@gmail.com> # # $Id: crash_binning.py 193 2007-04-05 13:30:01Z cameron $ # # This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with this program; if not, write to the Free # Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # ''' @author: Pedram Amini @license: GNU General Public License 2.0 or later @contact: pedram.amini@gmail.com @organization: www.openrce.org ''' import sys import zlib import cPickle class __crash_bin_struct__: exception_module = None exception_address = 0 write_violation = 0 violation_address = 0 violation_thread_id = 0 context = None context_dump = None disasm = None disasm_around = [] stack_unwind = [] seh_unwind = [] extra = None class crash_binning: ''' @todo: Add MySQL import/export. ''' bins = {} last_crash = None pydbg = None #################################################################################################################### def __init__ (self): ''' ''' self.bins = {} self.last_crash = None self.pydbg = None #################################################################################################################### def record_crash (self, pydbg, extra=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 by the exception address. @type pydbg: pydbg @param pydbg: Instance of pydbg @type extra: Mixed @param extra: (Optional, Def=None) Whatever extra data you want to store with this bin ''' self.pydbg = pydbg crash = __crash_bin_struct__() # add module name to the exception address. 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 = exception_module crash.exception_address = pydbg.dbg.u.Exception.ExceptionRecord.ExceptionAddress crash.write_violation = pydbg.dbg.u.Exception.ExceptionRecord.ExceptionInformation[0] crash.violation_address = pydbg.dbg.u.Exception.ExceptionRecord.ExceptionInformation[1] crash.violation_thread_id = pydbg.dbg.dwThreadId crash.context = pydbg.context crash.context_dump = pydbg.dump_context(pydbg.context, print_dots=False) crash.disasm = pydbg.disasm(crash.exception_address) crash.disasm_around = pydbg.disasm_around(crash.exception_address, 10) crash.stack_unwind = pydbg.stack_unwind() crash.seh_unwind = pydbg.seh_unwind() crash.extra = extra # add module names to the stack unwind. for i in xrange(len(crash.stack_unwind)): addr = crash.stack_unwind[i] module = pydbg.addr_to_module(addr) if module: module = module.szModule else: module = "[INVALID]" crash.stack_unwind[i] = "%s:%08x" % (module, addr) # add module names to the SEH unwind. for i in xrange(len(crash.seh_unwind)): (addr, handler) = crash.seh_unwind[i] module = pydbg.addr_to_module(handler) if module: module = module.szModule else: module = "[INVALID]" crash.seh_unwind[i] = (addr, handler, "%s:%08x" % (module, handler)) if not self.bins.has_key(crash.exception_address): self.bins[crash.exception_address] = [] self.bins[crash.exception_address].append(crash) self.last_crash = crash #################################################################################################################### def crash_synopsis (self, crash=None): ''' 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: crash_synopsis() @type crash: __crash_bin_struct__ @param crash: (Optional, def=None) Crash object to generate report on @rtype: String @return: Crash report ''' 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.exception_module, \ crash.exception_address, \ crash.disasm, \ crash.violation_thread_id, \ direction, \ crash.violation_address \ ) synopsis += crash.context_dump synopsis += "\ndisasm around:\n" for (ea, inst) in crash.disasm_around: synopsis += "\t0x%08x %s\n" % (ea, inst) if len(crash.stack_unwind): synopsis += "\nstack unwind:\n" for entry in crash.stack_unwind: synopsis += "\t%s\n" % entry if len(crash.seh_unwind): synopsis += "\nSEH unwind:\n" for (addr, handler, handler_str) in crash.seh_unwind: synopsis += "\t%08x -> %s\n" % (addr, handler_str) return synopsis + "\n" #################################################################################################################### def export_file (self, file_name): ''' Dump the entire object structure to disk. @see: import_file() @type file_name: String @param file_name: File name to export to @rtype: crash_binning @return: self ''' # null out what we don't serialize but save copies to restore after dumping to disk. 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 #################################################################################################################### def import_file (self, file_name): ''' Load the entire object structure from disk. @see: export_file() @type file_name: String @param file_name: File name to import from @rtype: crash_binning @return: self ''' fh = open(file_name, "rb") tmp = cPickle.loads(zlib.decompress(fh.read())) fh.close() self.bins = tmp.bins return self #################################################################################################################### def last_crash_synopsis (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 ''' 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_address, \ self.last_crash.disasm, \ self.last_crash.violation_thread_id, \ direction, \ self.last_crash.violation_address \ ) synopsis += self.last_crash.context_dump synopsis += "\ndisasm around:\n" for (ea, inst) in self.last_crash.disasm_around: synopsis += "\t0x%08x %s\n" % (ea, inst) if len(self.last_crash.stack_unwind): synopsis += "\nstack unwind:\n" for entry in self.last_crash.stack_unwind: synopsis += "\t%s\n" % entry if len(self.last_crash.seh_unwind): synopsis += "\nSEH unwind:\n" for (addr, handler, handler_str) in self.last_crash.seh_unwind: try: disasm = self.pydbg.disasm(handler) except: disasm = "[INVALID]" synopsis += "\t%08x -> %s %s\n" % (addr, handler_str, disasm) return synopsis + "\n"
10,054
Python
.py
220
36.431818
120
0.541927
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,962
ida_fuzz_library_extender.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/s_utils/ida_fuzz_library_extender.py
#!c:\python\python.exe # # Aaron Portnoy # TippingPoint Security Research Team # (C) 2007 # ######################################################################################################################## def get_string( ea): str_type = GetStringType(ea) if str_type == 0: string_buf = "" while Byte(ea) != 0x00: string_buf += "%c" % Byte(ea) ea += 1 return string_buf elif str_type == 3: string_buf = "" while Word(ea) != 0x0000: string_buf += "%c%c" % (Byte(ea), Byte(ea+1)) ea += 2 return string_buf else: pass ######################################################################################################################## def get_arguments(ea): xref_ea = ea args = 0 found = None if GetMnem(xref_ea) != "call": return False cur_ea = PrevHead(ea, xref_ea - 32) while (cur_ea < xref_ea - 32) or (args <= 6): cur_mnem = GetMnem(cur_ea); if cur_mnem == "push": args += 1 op_type = GetOpType(cur_ea, 0) if Comment(cur_ea): pass #print(" %s = %s," % (Comment(cur_ea), GetOpnd(cur_ea, 0))) else: if op_type == 1: pass #print(" %s" % GetOpnd(cur_ea, 0)) elif op_type == 5: found = get_string(GetOperandValue(cur_ea, 0)) elif cur_mnem == "call" or "j" in cur_mnem: break; cur_ea = PrevHead(cur_ea, xref_ea - 32) if found: return found ######################################################################################################################## def find_ints (start_address): constants = [] # loop heads for head in Heads(start_address, SegEnd(start_address)): # if it's code, check for cmp instruction if isCode(GetFlags(head)): mnem = GetMnem(head) op1 = int(GetOperandValue(head, 1)) # if it's a cmp and it's immediate value is unique, add it to the list if "cmp" in mnem and op1 not in constants: constants.append(op1) print "Found %d constant values used in compares." % len(constants) print "-----------------------------------------------------" for i in xrange(0, len(constants), 20): print constants[i:i+20] return constants ######################################################################################################################## def find_strings (start_address): strings = [] string_arg = None # do import checking import_ea = start_address while import_ea < SegEnd(start_address): import_name = Name(import_ea) if len(import_name) > 1 and "cmp" in import_name: xref_start = import_ea xref_cur = DfirstB(xref_start) while xref_cur != BADADDR: #print "Found call to ", import_name string_arg = get_arguments(xref_cur) if string_arg and string_arg not in strings: strings.append(string_arg) xref_cur = DnextB(xref_start, xref_cur) import_ea += 4 # now do FLIRT checking for function_ea in Functions(SegByName(".text"), SegEnd(start_address)): flags = GetFunctionFlags(function_ea) if flags & FUNC_LIB: lib_name = GetFunctionName(function_ea) if len(lib_name) > 1 and "cmp" in lib_name: # found one, now find xrefs to it and grab arguments xref_start = function_ea xref_cur = RfirstB(xref_start) while xref_cur != BADADDR: string_arg = get_arguments(xref_cur) if string_arg and string_arg not in strings: strings.append(string_arg) xref_cur = RnextB(xref_start, xref_cur) print "Found %d string values used in compares." % len(strings) print "-----------------------------------------------------" for i in xrange(0, len(strings), 5): print strings[i:i+5] return strings ######################################################################################################################## # get file names to save to constants_file = AskFile(1, ".fuzz_ints", "Enter filename for saving the discovered integers: ") strings_file = AskFile(1, ".fuzz_strings", "Enter filename for saving the discovered strings: ") # get integers start_address = SegByName(".text") constants = find_ints(start_address) constants = map(lambda x: "0x%x" % x, constants) print # get strings start_address = SegByName(".idata") strings = find_strings(start_address) # write integers fh = open(constants_file, 'w+') for c in constants: fh.write(c + "\n") fh.close() # write strings fh = open(strings_file, 'w+') for s in strings: fh.write(s + "\n") fh.close() print "Done."
5,064
Python
.py
126
31.65873
120
0.48616
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,963
pdml_parser.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/s_utils/pdml_parser.py
#!c:\python\python.exe import sys from xml.sax import make_parser from xml.sax import ContentHandler from xml.sax.handler import feature_namespaces ######################################################################################################################## class ParsePDML (ContentHandler): def __init__ (self): self.current = None self.start_parsing = False self.sulley = "" def startElement (self, name, attributes): if name == "proto": self.current = attributes["name"] # if parsing flag is set, we're past tcp if self.start_parsing: if not name == "field": print "Found payload with name %s" % attributes["name"] elif name == "field": if "value" in attributes.keys(): val_string = self.get_string(attributes["value"]) if val_string: self.sulley += "s_string(\"%s\")\n" % (val_string) print self.sulley #print "\tFound value: %s" % val_string else: # not string pass else: raise "WTFException" def characters (self, data): pass def endElement (self, name): # if we're closing a packet if name == "packet": self.start_parsing = False # if we're closing a proto tag if name == "proto": # and that proto is tcp, set parsing flag if self.current == "tcp": #print "Setting parsing flag to TRUE" self.start_parsing = True else: self.start_parsing = False def get_string(self, parsed): parsed = parsed.replace("\t", "") parsed = parsed.replace("\r", "") parsed = parsed.replace("\n", "") parsed = parsed.replace(",", "") parsed = parsed.replace("0x", "") parsed = parsed.replace("\\x", "") value = "" while parsed: pair = parsed[:2] parsed = parsed[2:] hex = int(pair, 16) if hex > 0x7f: return False value += chr(hex) value = value.replace("\t", "") value = value.replace("\r", "") value = value.replace("\n", "") value = value.replace(",", "") value = value.replace("0x", "") value = value.replace("\\x", "") return value def error (self, exception): print "Oh shitz: ", exception sys.exit(1) ######################################################################################################################## if __name__ == '__main__': # create the parser object parser = make_parser() # dont care about xml namespace parser.setFeature(feature_namespaces, 0) # make the document handler handler = ParsePDML() # point parser to handler parser.setContentHandler(handler) # parse parser.parse(sys.argv[1])
3,304
Python
.py
81
27.950617
120
0.477174
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,964
pcap_cleaner.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/s_utils/pcap_cleaner.py
#!c:\\python\\python.exe import os import sys sys.path.append(r"..\..\..\paimei") import utils USAGE = "\nUSAGE: pcap_cleaner.py <xxx.crashbin> <path to pcaps>\n" if len(sys.argv) != 3: print USAGE sys.exit(1) # # generate a list of all test cases that triggered a crash. # try: crashbin = utils.crash_binning.crash_binning() crashbin.import_file(sys.argv[1]) except: print "unable to open crashbin: '%s'." % sys.argv[1] sys.exit(1) test_cases = [] for bin, crashes in crashbin.bins.iteritems(): for crash in crashes: test_cases.append("%d.pcap" % crash.extra) # # step through the pcap directory and erase all files not pertaining to a crash. # for filename in os.listdir(sys.argv[2]): if filename not in test_cases: os.unlink("%s/%s" % (sys.argv[2], filename))
821
Python
.py
28
26.25
80
0.687101
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,965
ldap.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/requests/ldap.py
from sulley import * """ Application number Application 0 BindRequest 1 BindResponse 2 UnbindRequest 3 SearchRequest 4 SearchResponse 5 ModifyRequest 6 ModifyResponse 7 AddRequest 8 AddResponse 9 DelRequest 10 DelResponse 11 ModifyRDNRequest 12 ModifyRDNResponse 13 CompareRequest 14 CompareResponse 15 AbandonRequest """ ######################################################################################################################## s_initialize("anonymous bind") # all ldap messages start with this. s_static("\x30") # length of entire envelope. s_static("\x84") s_sizer("envelope", endian=">") if s_block_start("envelope"): s_static("\x02\x01\x01") # message id (always one) s_static("\x60") # bind request (0) s_static("\x84") s_sizer("bind request", endian=">") if s_block_start("bind request"): s_static("\x02\x01\x03") # version s_lego("ber_string", "anonymous") s_lego("ber_string", "foobar", options={"prefix":"\x80"}) # 0x80 is "simple" authentication s_block_end() s_block_end() ######################################################################################################################## s_initialize("search request") # all ldap messages start with this. s_static("\x30") # length of entire envelope. s_static("\x84") s_sizer("envelope", endian=">", fuzzable=True) if s_block_start("envelope"): s_static("\x02\x01\x02") # message id (always one) s_static("\x63") # search request (3) s_static("\x84") s_sizer("searchRequest", endian=">", fuzzable=True) if s_block_start("searchRequest"): s_static("\x04\x00") # static empty string ... why? s_static("\x0a\x01\x00") # scope: baseOjbect (0) s_static("\x0a\x01\x00") # deref: never (0) s_lego("ber_integer", 1000) # size limit s_lego("ber_integer", 30) # time limit s_static("\x01\x01\x00") # typesonly: false s_lego("ber_string", "objectClass", options={"prefix":"\x87"}) s_static("\x30") s_static("\x84") s_sizer("attributes", endian=">") if s_block_start("attributes"): s_lego("ber_string", "1.1") s_block_end("attributes") s_block_end("searchRequest") s_block_end("envelope")
2,324
Python
.py
66
31.227273
120
0.572066
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,966
ndmp.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/requests/ndmp.py
from sulley import * import struct import time ndmp_messages = \ [ # Connect Interface 0x900, # NDMP_CONNECT_OPEN 0x901, # NDMP_CONECT_CLIENT_AUTH 0x902, # NDMP_CONNECT_CLOSE 0x903, # NDMP_CONECT_SERVER_AUTH # Config Interface 0x100, # NDMP_CONFIG_GET_HOST_INFO 0x102, # NDMP_CONFIG_GET_CONNECTION_TYPE 0x103, # NDMP_CONFIG_GET_AUTH_ATTR 0x104, # NDMP_CONFIG_GET_BUTYPE_INFO 0x105, # NDMP_CONFIG_GET_FS_INFO 0x106, # NDMP_CONFIG_GET_TAPE_INFO 0x107, # NDMP_CONFIG_GET_SCSI_INFO 0x108, # NDMP_CONFIG_GET_SERVER_INFO # SCSI Interface 0x200, # NDMP_SCSI_OPEN 0x201, # NDMP_SCSI_CLOSE 0x202, # NDMP_SCSI_GET_STATE 0x203, # NDMP_SCSI_SET_TARGET 0x204, # NDMP_SCSI_RESET_DEVICE 0x205, # NDMP_SCSI_RESET_BUS 0x206, # NDMP_SCSI_EXECUTE_CDB # Tape Interface 0x300, # NDMP_TAPE_OPEN 0x301, # NDMP_TAPE_CLOSE 0x302, # NDMP_TAPE_GET_STATE 0x303, # NDMP_TAPE_MTIO 0x304, # NDMP_TAPE_WRITE 0x305, # NDMP_TAPE_READ 0x307, # NDMP_TAPE_EXECUTE_CDB # Data Interface 0x400, # NDMP_DATA_GET_STATE 0x401, # NDMP_DATA_START_BACKUP 0x402, # NDMP_DATA_START_RECOVER 0x403, # NDMP_DATA_ABORT 0x404, # NDMP_DATA_GET_ENV 0x407, # NDMP_DATA_STOP 0x409, # NDMP_DATA_LISTEN 0x40a, # NDMP_DATA_CONNECT # Notify Interface 0x501, # NDMP_NOTIFY_DATA_HALTED 0x502, # NDMP_NOTIFY_CONNECTED 0x503, # NDMP_NOTIFY_MOVER_HALTED 0x504, # NDMP_NOTIFY_MOVER_PAUSED 0x505, # NDMP_NOTIFY_DATA_READ # Log Interface 0x602, # NDMP_LOG_FILES 0x603, # NDMP_LOG_MESSAGE # File History Interface 0x703, # NDMP_FH_ADD_FILE 0x704, # NDMP_FH_ADD_DIR 0x705, # NDMP_FH_ADD_NODE # Mover Interface 0xa00, # NDMP_MOVER_GET_STATE 0xa01, # NDMP_MOVER_LISTEN 0xa02, # NDMP_MOVER_CONTINUE 0xa03, # NDMP_MOVER_ABORT 0xa04, # NDMP_MOVER_STOP 0xa05, # NDMP_MOVER_SET_WINDOW 0xa06, # NDMP_MOVER_READ 0xa07, # NDMP_MOVER_CLOSE 0xa08, # NDMP_MOVER_SET_RECORD_SIZE 0xa09, # NDMP_MOVER_CONNECT # Reserved for the vendor specific usage (from 0xf000 to 0xffff) 0xf000, # NDMP_VENDORS_BASE # Reserved for Prototyping (from 0xff00 to 0xffff) 0xff00, # NDMP_RESERVED_BASE ] ######################################################################################################################## s_initialize("Veritas NDMP_CONECT_CLIENT_AUTH") # the first bit is the last frag flag, we'll always set it and truncate our size to 3 bytes. # 3 bytes of size gives us a max 16mb ndmp message, plenty of space. s_static("\x80") s_size("request", length=3, endian=">") if s_block_start("request"): if s_block_start("ndmp header"): s_static(struct.pack(">L", 1), name="sequence") s_static(struct.pack(">L", time.time()), name="timestamp") s_static(struct.pack(">L", 0), name="message type") # request (0) s_static(struct.pack(">L", 0x901), name="NDMP_CONECT_CLIENT_AUTH") s_static(struct.pack(">L", 1), name="reply sequence") s_static(struct.pack(">L", 0), name="error") s_block_end("ndmp header") s_group("auth types", values=[struct.pack(">L", 190), struct.pack(">L", 5), struct.pack(">L", 4)]) if s_block_start("body", group="auth types"): # do random data. s_random(0, min_length=1000, max_length=50000, num_mutations=500) # random valid XDR string. #s_lego("xdr_string", "pedram") s_block_end("body") s_block_end("request") ######################################################################################################################## s_initialize("Veritas Proprietary Message Types") # the first bit is the last frag flag, we'll always set it and truncate our size to 3 bytes. # 3 bytes of size gives us a max 16mb ndmp message, plenty of space. s_static("\x80") s_size("request", length=3, endian=">") if s_block_start("request"): if s_block_start("ndmp header"): s_static(struct.pack(">L", 1), name="sequence") s_static(struct.pack(">L", time.time()), name="timestamp") s_static(struct.pack(">L", 0), name="message type") # request (0) s_group("prop ops", values = \ [ struct.pack(">L", 0xf315), # file list? struct.pack(">L", 0xf316), struct.pack(">L", 0xf317), struct.pack(">L", 0xf200), # struct.pack(">L", 0xf201), struct.pack(">L", 0xf202), struct.pack(">L", 0xf31b), struct.pack(">L", 0xf270), # send strings like NDMP_PROP_PEER_PROTOCOL_VERSION struct.pack(">L", 0xf271), struct.pack(">L", 0xf33b), struct.pack(">L", 0xf33c), ]) s_static(struct.pack(">L", 1), name="reply sequence") s_static(struct.pack(">L", 0), name="error") s_block_end("ndmp header") if s_block_start("body", group="prop ops"): s_random("\x00\x00\x00\x00", min_length=1000, max_length=50000, num_mutations=100) s_block_end("body") s_block_end("request")
5,380
Python
.py
128
35.140625
120
0.572522
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,967
jabber.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/requests/jabber.py
from sulley import * ######################################################################################################################## s_initialize("chat init") """ <?xml version="1.0" encoding="UTF-8" ?> <stream:stream to="192.168.200.17" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams"> """ # i'll fuzz these bitches later. # xxx - still need to figure out how to incorporate dynamic IPs s_static('<?xml version="1.0" encoding="UTF-8" ?>') s_static('<stream:stream to="152.67.137.126" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams">') ######################################################################################################################## s_initialize("chat message") s_static('<message to="TSR@GIZMO" type="chat">\n') s_static('<body></body>\n') s_static('<html xmlns="http://www.w3.org/1999/xhtml"><body></body></html><x xmlns="jabber:x:event">\n') s_static('<composing/>\n') s_static('<id></id>\n') s_static('</x>\n') s_static('</message>\n') # s_static('<message to="TSR@GIZMO" type="chat">\n') s_delim("<") s_string("message") s_delim(" ") s_string("to") s_delim("=") s_delim('"') s_string("TSR@GIZMO") s_delim('"') s_static(' type="chat"') s_delim(">") s_delim("\n") # s_static('<body>hello from python!</body>\n') s_static("<body>") s_string("hello from python!") s_static("</body>\n") # s_static('<html xmlns="http://www.w3.org/1999/xhtml"><body><font face="Helvetica" ABSZ="12" color="#000000">hello from python</font></body></html><x xmlns="jabber:x:event">\n') s_static('<html xmlns="http://www.w3.org/1999/xhtml"><body>') s_static("<") s_string("font") s_static(' face="') s_string("Helvetica") s_string('" ABSZ="') s_word(12, format="ascii", signed=True) s_static('" color="') s_string("#000000") s_static('">') s_string("hello from python") s_static('</font></body></html><x xmlns="jabber:x:event">\n') s_static('<composing/>\n') s_static('</x>\n') s_static('</message>\n')
1,969
Python
.py
52
36.673077
178
0.57892
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,968
sip_valid.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/requests/sip_valid.py
from sulley import * s_initialize("INVITE_VALID") s_static('\r\n'.join(['INVITE sip:tester@192.168.3.104 SIP/2.0', 'CSeq: 1 INVITE', 'Via: SIP/2.0/UDP 192.168.3.102:5068;branch=z9hG4bKlm4zshdowki1t8c7ep6j0yavq2ug5r3x;rport', 'From: "nnp" <sip:nnp@192.168.3.104>;tag=so08p5k39wuv1dczfnij7bet4l2m6hrq', 'Call-ID: rzxd6tm98v0eal1cifg2py7sj3wk54ub@ubuntu', 'To: <sip:nnp@192.168.3.101>', 'Max-Forwards: 70', 'Content-Type: application/sdp', '\r\n', 'v=0', 'o=somegimp 1190505265 1190505265 IN IP4 192.168.3.101', 's=Opal SIP Session', 'i=some information string', 'u=http://unprotectedhex.com/someuri.htm', 'e=email@address.com', 'c=IN IP4 192.168.3.101', 'b=CT:8', 't=0 1', 'm=audio 5028 RTP/AVP 101 96 107 110 0 8', 'a=rtpmap:101 telephone-event/8000', ])) ################################################################################ s_initialize("CANCEL_VALID") s_static('\r\n'.join(['CANCEL sip:tester@192.168.3.104 SIP/2.0', 'CSeq: 1 CANCEL', 'Via: SIP/2.0/UDP 192.168.3.102:5068;branch=z9hG4bKlm4zshdowki1t8c7ep6j0yavq2ug5r3x;rport', 'From: "nnp" <sip:nnp@192.168.3.104>;tag=so08p5k39wuv1dczfnij7bet4l2m6hrq', 'Call-ID: rzxd6tm98v0eal1cifg2py7sj3wk54ub@ubuntu', 'To: <sip:nnp@192.168.3.101>', 'Max-Forwards: 70', '\r\n' ]))
1,257
Python
.py
34
35.176471
91
0.677075
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,969
sip.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/requests/sip.py
import base64 import string import zlib from random import Random from sulley import * ''' Contains fuzz cases for INVITE (all headers and the base headers) and sdp ''' def base64_encode(val): return base64.b64encode(val) def gzip_encode(val): return zlib.compress(val) ################################################################################ s_initialize("INVITE_STRUCTURE") if s_block_start("invite"): if s_block_start("invite_sip"): if s_block_start("request_line"): s_static("INVITE sip:TARGET_USER@HOST SIP/2.0\r\n") s_block_end() s_repeat("request_line", min_reps=2, max_reps=100, step=10) if s_block_start("invite_header"): # repeat of a line that shouldn't appear multiple times if s_block_start("cseq"): s_static("CSeq: 1 INVITE\r\n") s_block_end() s_repeat("cseq", min_reps=2, max_reps=1000, step=10) # repeat of a line that could appear multiple times if s_block_start("via"): s_static("Via: SIP/2.0/UDP LOCAL_IP:PORT;branch=z9hG4bKsomebranchvalue;rport\r\n") s_block_end() s_repeat("via", min_reps=2, max_reps=1000, step=10) s_static("From: \"nnp\" <sip:USER@LOCAL_IP>;tag=somefromtagvalue\r\n") # Fuzz the structure of a line s_string("Call-ID") s_delim(" ") s_delim(":") if s_block_start("call_id_body"): s_delim(" ") s_static("somecallidvalue@ubuntu") s_delim("\r\n") s_block_end() # this test will test where one attribute runs into another e.g no EOL s_repeat("call_id_body", min_reps=0, max_reps=1, step=1) s_static("To:") if s_block_start("to_body"): s_static("<sip:TARGET_USER@HOST>") s_block_end() s_static("\r\n") # this test will test for an empty body s_repeat("to_body", min_reps=0, max_reps=1, step=1) # Line folding s_static("Contact: <sip:USER@LOCAL_IP:PORT;transport=udp>\r\n") if s_block_start("line_folding"): #line folding s_static(" ,<sip:meh@LOCAL_IP:PORT;transport=udp>\r\n") s_block_end() s_repeat("line_folding", min_reps=2, max_reps=1000, step=10) s_static("Max-Forwards: 70\r\n\r\n") s_block_end() # repetition of the header portion of the INVITE s_repeat("invite_header", min_reps=2, max_reps=1000, step=10) s_block_end() # repitition of the SIP portion of the request s_repeat("invite_sip", min_reps=2, max_reps=1000, step=10) if not s_block_start("invite_sdp"): s_static("v=0\r\n") s_static("o=- 1190505265 1190505265 IN IP4 LOCAL_IP\r\n") s_static("s=Opal SIP Session\r\n") s_static("c=IN IP4 LOCAL_IP\r\n") s_static("t=0 0\r\n") s_static("m=audio 5028 RTP/AVP 101 96 3 107 110 0 8\r\n") s_static("a=rtpmap:101 telephone-event/8000\r\n") s_static("a=fmtp:101 0-15\r\n") s_static("a=rtpmap:96 SPEEX/16000\r\n") s_static("a=rtpmap:3 GSM/8000\r\n") s_static("a=rtpmap:107 MS-GSM/8000\r\n") s_static("a=rtpmap:110 SPEEX/8000\r\n") s_static("a=rtpmap:0 PCMU/8000\r\n") s_static("a=rtpmap:8 PCMA/8000\r\n") s_static("m=video 5030 RTP/AVP 31\r\n") s_static("a=rtpmap:31 H261/90000\r\n") s_block_end() # repitition of the SDP portion of the message s_repeat("invite_sdp", min_reps=2, max_reps=1000, step=10) s_block_end() # repitition of the entire INVITE s_repeat("invite", min_reps=2, max_reps=1000, step=10) ################################################################################ s_initialize("INVITE_REQUEST_LINE") if s_block_start("invite_request_line"): #s_static("INVITE sip:TARGET_USER:secretword@192.168.3.101?subject=weeee&priority=urgent;transport=udp SIP/2.0\r\n") s_string("INVITE") s_delim(" ") s_string("sip") s_delim(":") # userinfo s_string("TARGET_USER") # asterisk doesn't like this # s_delim(":") #s_string("password") s_delim("@") # hostport s_string("HOST") s_delim(":") s_string("PORT") # uri-parameters s_delim(";") s_string("transport") s_delim("=") s_string("udp") s_static(";") s_static("user=") s_string("udp") s_static(";") s_static("ttl=") s_string("67") s_static(";") s_static("method=") s_string("INVITE") s_static(";") s_static("maddr=") s_string("HOST") # headers s_delim("?") s_string("subject=") s_delim("=") s_string("hval") s_delim("&") s_static("hname2=hval") s_delim(" ") s_string("SIP") s_delim("/") s_string("2.0") s_delim("\r\n") s_block_end() if s_block_start("invite_header"): s_static("CSeq: 1 INVITE\r\n") s_static("Via: SIP/2.0/UDP LOCAL_IP:PORT;branch=z9hG4bKsomebranchvalue;rport\r\n") s_static("From: \"nnp\" <sip:USER@LOCAL_IP>;tag=somefromtagvalue\r\n") s_static("Call-ID: somecallidvalue@ubuntu\r\n") s_static("To: <sip:TARGET_USER@HOST>\r\n") s_static("Contact: <sip:USER@LOCAL_IP:PORT;transport=udp>\r\n") s_static("Max-Forwards: 70\r\n\r\n") s_block_end() ################################################################################ s_initialize("INVITE_OTHER") if s_block_start("invite_request_line"): s_static("INVITE sip:TARGET_USER@HOST SIP/2.0\r\n") s_block_end() if s_block_start("invite_header"): s_static("CSeq: 1 INVITE\r\n") s_static("Via: SIP/2.0/UDP LOCAL_IP:5060;branch=z9hG4bKsomebranchvalue;rport\r\n") s_static("From: \"VoIPER\" <sip:USER@LOCAL_IP>;tag=somefromtagvalue\r\n") s_static("Call-ID: somecallidvalue@ubuntu\r\n") s_static("To: <sip:TARGET_USER@HOST>\r\n") s_static("Max-Forwards: 70\r\n") s_static("Contact: <sip:USER@LOCAL_IP:5060;transport=udp>\r\n") ## Date = "Date" HCOLON SIP-date ## SIP-date = rfc1123-date ## rfc1123-date = wkday "," SP date1 SP time SP "GMT" ## date1 = 2DIGIT SP month SP 4DIGIT ## ; day month year (e.g., 02 Jun 1982) ## time = 2DIGIT ":" 2DIGIT ":" 2DIGIT ## ; 00:00:00 - 23:59:59 #s_static("Date: Sat, 22 Sep 2007 23:54:25 GMT\r\n") s_static("Date: ") s_string("Sat") s_delim(",") s_delim(" ") s_dword(22, fuzzable=True, format="ascii", signed=True) s_delim(" ") s_string("Sep") s_delim(" ") s_dword(2007, fuzzable=True, format="ascii", signed=True) s_static(" ") s_dword(23, fuzzable=True, format="ascii", signed=True) s_delim(":") s_dword(59, fuzzable=True, format="ascii", signed=True) s_static(":") s_dword(25, fuzzable=True, format="ascii", signed=True) s_static(" ") s_string("GMT") s_static("\r\n") #s_static("Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE\r\n") s_static("Allow: ") s_string("INVITE") s_static(",") s_static("ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE") s_static("\r\n") # Fuzzed in the basic fuzzer s_static("Content-Type: application/sdp\r\n") # Content-Length s_static("Content-Length: ") s_sizer("invite_sdp", format="ascii", fuzzable=False, signed=True) s_static("\r\n") #s_static("Expires: 3600\r\n") s_static("Expires: ") s_string("3600") s_static("\r\n") #s_static("User-Agent: Ekiga/2.0.3\r\n") ## User-Agent = "User-Agent" HCOLON server-val *(LWS server-val) ## server-val = product / comment ## product = token [SLASH product-version] ## product-version = token s_static("User-Agent: ") s_string("VoIPER") s_delim("/") s_string("0.02") s_delim(" ") s_string("Clack/0.02") s_static("\r\n") #s_static("Subject: This is a subject header field\r\n") s_static("Subject: ") s_string("Commander Vimes has been attacked by a turnip") s_static("\r\n") #s_static("Organization: This is an organization field\r\n") s_static("Organization: ") s_string("Ankh Morpok City Watch") s_static("\r\n") #s_static("Accept-Encoding: compress;q=0.5, identity\r\n") ## Accept-Encoding = "Accept-Encoding" HCOLON ## [ encoding *(COMMA encoding) ] ## encoding = codings *(SEMI accept-param) ## codings = content-coding / "*" ## content-coding = token s_static("Accept-Encoding: ") s_string("compress") s_static(";") s_lego("q_value") s_delim(",") s_static("identity") s_static("\r\n") #s_static("Alert-Info: <http://www.examplesite.com/something.wav>\r\n") ## Alert-Info = "Alert-Info" HCOLON alert-param *(COMMA alert-param) ## alert-param = LAQUOT absoluteURI RAQUOT *( SEMI generic-param ) s_static("Alert-Info: ") s_delim("<") s_string("http://www.examplesite.com/") s_string("something.wav") s_delim(">") s_static(";") s_string("x") s_static("=") s_string("y") s_delim(",") s_string("<http://www.examplesite.com/something.wav>") s_static("\r\n") #s_static("Call-Info: <http:/www.example.com/icon.jpg> ;purpose=icon,<http:/www.example.com/alice/> \ # ;purpose=info,<http:/www.example.com/card.vcard> ;purpose=card\r\n") ## Call-Info = "Call-Info" HCOLON info *(COMMA info) ## info = LAQUOT absoluteURI RAQUOT *( SEMI info-param) ## info-param = ( "purpose" EQUAL ( "icon" / "info" ## / "card" / token ) ) / generic-param s_static("Call-Info: ") s_delim("<") s_string("http://www.examplesite.com/") s_string("something") s_delim(".") s_string("jpg") s_delim(">") s_delim(";") s_string("purpose") s_delim("=") s_group("call_info_params", values=['icon', 'info', 'card']) s_static(",") s_string("<http:/www.example.com/alice/>") s_static(";purpose=info,<http:/www.example.com/card.vcard> ;purpose=card\r\n") #s_static("Supported: 100rel\r\n") s_static("Supported: ") s_string("100rel") s_static(",") s_static("replaces") s_static("\r\n") #s_static("Content-Disposition: session\r\n") ## Content-Disposition = "Content-Disposition" HCOLON ## disp-type *( SEMI disp-param ) ## disp-type = "render" / "session" / "icon" / "alert" ## / disp-extension-token ## ## disp-param = handling-param / generic-param ## handling-param = "handling" EQUAL ## ( "optional" / "required" ## / other-handling ) ## other-handling = token ## disp-extension-token = token s_static("Content-Disposition: ") s_group("content_disposition_types", values=['session', 'icon', 'alert']) s_delim(";") s_static("handling") s_static("=") s_string("optional") s_static("\r\n") #s_static("Accept-Language: da,en-gb;q=0.8,en;q=0.7\r\n") ## Accept-Language = "Accept-Language" HCOLON ## [ language *(COMMA language) ] ## language = language-range *(SEMI accept-param) ## language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) / "*" ) s_static("Accept-Language: ") s_string("da") s_static(",") s_string("en") s_delim("-") s_string("gb") s_delim(";") s_lego("q_value") s_delim(",") s_string("en") s_static(";q=0.7\r\n") #s_static("Authorization: Digest username=\"nnp\", realm=\"bleh.com\", nonce=\"value\", response=\"value\"\r\n") s_static("Authorization: ") s_lego("static_credentials") s_static("\r\n") # fuzz this in an SDP fuzzer instead #s_static("Content-Encoding: gzip\r\n") #s_static("Content-Language: en,da\r\n") s_static("Content-Language: ") s_string("da") s_delim(",") s_string("en") s_delim("-") s_string("gb") s_static("\r\n") #s_static("In-Reply-To: 1447@example.com\r\n") s_static("In-Reply-To: ") s_string("1447") s_delim("@") s_string("example.com") s_delim(",") s_string("1445@example.com") s_static("\r\n") #s_static("Priority: emergency\r\n") s_static("Priority: ") s_string("emergency") s_static("\r\n") #s_static("Proxy-Require: 100rel\r\n") s_static("Proxy-Require: ") s_string("replaces") s_delim(",") s_string("replaces") s_static("\r\n") #s_static("Require: 100rel\r\n") s_static("Require: ") s_string("replaces") s_delim(",") s_string("replaces") s_static("\r\n") #s_static("Record-Route: <sip:server10.biloxi.com;lr>, <sip:server11.biloxi.com;lr>\r\n") if s_block_start("record_route"): s_static("Record-Route: ") s_string("bob") s_delim(" ") s_delim("<") s_string("sip") s_delim(":") s_string("unprotectedhex.com") s_delim(";") s_string("lr") s_delim(">") s_static("\r\n") s_block_end() s_repeat("record_route", min_reps=10, max_reps=1000, step=10) #s_static("Reply-To: Bob <sip:bob@biloxi.com>\r\n") s_static("Reply-To: ") s_string("bob") s_delim(" ") s_delim("<") s_string("sip") s_delim(":") s_string("unprotectedhex.com") s_delim(";") s_string("lr") s_delim(">") s_static("\r\n") #s_static("Route: <sip:server10.biloxi.com;lr>, <sip:server11.biloxi.com;lr>\r\n") s_static("Route: ") if s_block_start("route_attributes"): s_delim("<") s_string("sip") s_delim(":") s_string("unprotectedhex.com") s_delim(";") s_string("lr") s_delim(">") s_delim(",") s_string("<pbx.smashthestack.org;lr>") s_static(",") s_block_end() s_repeat("route_attributes", min_reps=10, max_reps=1000, step=10) s_static("\r\n") #s_static("Timestamp: 42\r\n") s_static("Timestamp: ") s_string("42") s_delim(".") s_string("42") s_static(" ") s_string("10") s_static("\r\n") #s_static("Accept: audio/*;q=0.2,audio/basic\r\n") s_static("Accept: ") s_string("audio") s_delim("/") s_string("*") s_delim(";") # should only be one of these if s_block_start("accept_q_value"): s_lego("q_value") s_block_end() s_repeat("accept_q_value", min_reps=2, max_reps=10, step=1) s_delim(",") s_string("audio/basic") s_static(";") s_string("meh") s_delim("=") s_string("bleh") s_static("\r\n") #s_static("MIME-Version: 1.0\r\n") s_static("MIME-Version: ") s_string("1") s_delim(".") s_string("0") s_static("\r\n") #s_static("Authentication-Info: nextnonce=\"somemd5value\",qop=\"auth\",rspauth=\"somehexvalue\",nc=deadcafe,cnonce=\"somecnonce\"") s_static("Authentication-Info: ") s_string("nextnonce") s_delim("=") s_delim("\"") s_string("f84f1cec41e6cbe5aea9c8e88d359") s_delim("\"") s_delim(",") s_static("qop=") s_delim("\"") s_string("auth") s_delim("\"") s_static(",rspauth=") s_delim("\"") s_static("deadcafe") s_delim("\"") s_static(",nc=") s_string("deadcafe") s_static(",cnonce=") s_delim("\"") s_string("f84f1cec41e6cbe5aea9c8e88d359") s_delim("\"") s_static("\r\n") #s_static("Min-Expires: 60") s_static("Min-Expires: ") s_string("60") s_static("\r\n") #s_static("Retry-After: 60(some comment text);duration=3600 s_static("Retry-After: ") s_string("60") s_delim("(") s_string("comment") s_delim(")") s_delim(";") s_string("duration") s_static("=") s_string("3600") s_static("\r\n") #s_static("Error-Info: <sip:not-in-service@atlanta.com>,<sip:not-in-service2@atlanta.com>") s_static("Error-Info: ") s_delim("<") s_string("sip:not-in-service@atlanta.com") s_delim(">") s_static(",<sip:not-in-service2@atlanta.com>") s_static("\r\n") #s_static("Unsupported: somestring, someotherstring") s_static("Unsupported: ") s_string("somestring") s_static(", bleh") s_static("\r\n") #s_static("Warning: 666 ServerName \"The Sky Is Falling\", 333 ServerName \"Says Chicken Little\"") s_static("Warning: ") s_dword(333, fuzzable=True, format="ascii", signed=True) s_delim(" ") s_string("ServerName") s_static(" ") s_delim("\"") s_string("The Sky Is Falling") s_delim("\"") s_static(",") s_string("333 ServerName \"Says Chicken Litle\"") s_static("\r\n") #s_static("Proxy-Authenticate: Digest realm=\"atlanta.com\",domain=\"sip:ss1.carrier.com\", \ #qop=\"auth\",nonce="f84f1cec41e6cbe5aea9c8e88d359",opaque=\"5ccc069c403ebaf9f0171e9517f40e41\", stale=FALSE, algorithm=MD5) # this is a repeat of earlier Authenticate. probably no point in fuzzing s_static("Proxy-Authenticate: ") s_lego("static_challenge", options={'fuzzable' : False}) s_static("\r\n") #s_static("Proxy-Authorization: Digest username=\"Alice\", realm=\"atlanta.com\", nonce=\"c60f3082ee1212b402a21831ae\",\ #response=\"245f23415f11432b3434341c022\"") # this is a repeat of earlier Authorization. probably no point in fuzzing s_static("Proxy-Authorization: ") s_lego("static_credentials", options={'fuzzable' : False}) s_static("\r\n") #s_static("Server: SomeServer v2") s_static("Server: ") s_string("Someserver") s_delim(" ") s_string("v2") s_static("\r\n") #s_static("WWW-Authenticate: Digest realm=\"atlanta.com\",domain=\"sip:ss1.carrier.com\", \ #qop=\"auth\",nonce="f84f1cec41e6cbe5aea9c8e88d359",opaque=\"5ccc069c403ebaf9f0171e9517f40e41\", stale=FALSE, algorithm=MD5) s_static("WWW-Authenticate: ") s_lego("static_challenge") s_static("\r\n") s_static("\r\n") s_block_end() if not s_block_start("invite_sdp"): s_static("v=0\r\n") s_static("o=- 1190505265 1190505265 IN IP4 LOCAL_IP\r\n") s_static("s=Opal SIP Session\r\n") s_static("c=IN IP4 LOCAL_IP\r\n") s_static("t=0 0\r\n") s_static("m=audio 5028 RTP/AVP 101 96 3 107 110 0 8\r\n") s_static("a=rtpmap:101 telephone-event/8000\r\n") s_static("a=fmtp:101 0-15\r\n") s_static("a=rtpmap:96 SPEEX/16000\r\n") s_static("a=rtpmap:3 GSM/8000\r\n") s_static("a=rtpmap:107 MS-GSM/8000\r\n") s_static("a=rtpmap:110 SPEEX/8000\r\n") s_static("a=rtpmap:0 PCMU/8000\r\n") s_static("a=rtpmap:8 PCMA/8000\r\n") s_static("m=video 5030 RTP/AVP 31\r\n") s_static("a=rtpmap:31 H261/90000\r\n") s_block_end() ################################################################################ s_initialize("INVITE_COMMON") if s_block_start("invite_request_line"): s_static("INVITE sip:TARGET_USER@HOST SIP/2.0\r\n") s_block_end() if s_block_start("invite_header"): #s_static("CSeq: 1 INVITE\r\n") ## CSeq = "CSeq" HCOLON 1*DIGIT LWS Method s_static("CSeq: ") s_dword(1, fuzzable=True, format="ascii") s_delim(" ") s_string("INVITE") s_static("\r\n") #s_static("Via: SIP/2.0/UDP 192.168.3.104:5068;branch=z9hG4bKsomebranchvalue;rport\r\n") ## Via = ( "Via" / "v" ) HCOLON via-parm *(COMMA via-parm) ## via-parm = sent-protocol LWS sent-by *( SEMI via-params ) ## via-params = via-ttl / via-maddr ## / via-received / via-branch ## / via-extension ## via-ttl = "ttl" EQUAL ttl ## via-maddr = "maddr" EQUAL host ## via-received = "received" EQUAL (IPv4address / IPv6address) ## via-branch = "branch" EQUAL token ## via-extension = generic-param ## sent-protocol = protocol-name SLASH protocol-version ## SLASH transport ## protocol-name = "SIP" / token ## protocol-version = token ## transport = "UDP" / "TCP" / "TLS" / "SCTP" ## / other-transport ## sent-by = host [ COLON port ] ## ttl = 1*3DIGIT ; 0 to 255 s_static("Via: ") s_string("SIP") s_delim("/") s_string("2.0") s_delim("/") s_string("UDP") s_static(" ") s_lego("ip_address_ascii", "192.168.99.99") s_delim(":") s_string("PORT") s_delim(";") s_string("branch") s_delim("=") s_string("z9hG4bK") s_string("somebranchvalue") s_static(";") s_static("ttl") s_static("=") s_string("70") s_static(";") s_static("maddr=") s_lego("ipv6_address_ascii", "aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa") s_static(";") s_static("received=") s_lego("ipv6_address_ascii", "aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa") s_static(";") s_string("rport") s_static("\r\n") #s_static("From: \"Negativa\" <sip:nnp@192.168.3.104>;tag=somefromtagvalue\r\n") ## From = ( "From" / "f" ) HCOLON from-spec ## from-spec = ( name-addr / addr-spec ) ## *( SEMI from-param ) ## from-param = tag-param / generic-param ## tag-param = "tag" EQUAL token ## name-addr = [ display-name ] LAQUOT addr-spec RAQUOT ## addr-spec = SIP-URI / SIPS-URI / absoluteURI s_static("From: ") s_delim("\"") s_string("VoIPER") s_delim("\"") s_delim(" ") s_delim("<") s_lego("from_sip_uri", options={'fuzzable' : True}) s_delim(">") s_delim(";") s_string("tag") s_string("=") s_string("somefromtagval") s_static("\r\n") #s_static("Call-ID: somecallidvalue@ubuntu\r\n") ## Call-ID = ( "Call-ID" / "i" ) HCOLON callid ## callid = word [ "@" word ] s_static("Call-ID: ") s_string("somecallidvalue") s_delim("@") s_string("TheKlatchianHead") s_static("\r\n") #s_static("To: <sip:nnp@192.168.1.1>\r\n") ## To = ( "To" / "t" ) HCOLON ( name-addr ## / addr-spec ) *( SEMI to-param ) ## to-param = tag-param / generic-param s_static("To: ") s_delim("\"") s_string("TARGET_USER") s_delim("\"") s_delim(" ") s_delim("<") s_lego("to_sip_uri", options={'fuzzable' : True}) s_delim(">") s_static("\r\n") #s_static("Contact: <sip:nnp@192.168.3.104:5068;transport=udp>\r\n") ## Contact = ("Contact" / "m" ) HCOLON ## ( STAR / (contact-param *(COMMA contact-param))) ## contact-param = (name-addr / addr-spec) *(SEMI contact-params) ## name-addr = [ display-name ] LAQUOT addr-spec RAQUOT ## addr-spec = SIP-URI / SIPS-URI / absoluteURI ## display-name = *(token LWS)/ quoted-string ## ## contact-params = c-p-q / c-p-expires ## / contact-extension ## c-p-q = "q" EQUAL qvalue ## c-p-expires = "expires" EQUAL delta-seconds ## contact-extension = generic-param s_static("Contact: ") s_delim("<") s_lego("from_sip_uri", options={'fuzzable' : True}) s_delim(">") s_lego("q_value") s_static(";") s_static("expires") s_static("=") s_string("1337") s_static(";") s_static("sometoken") s_delim("=") s_string("somevalue") s_static("\r\n") #s_static("Max-Forwards: 70\r\n") ## Max-Forwards = "Max-Forwards" HCOLON 1*DIGIT s_static("Max-Forwards: ") s_string("70") s_static("\r\n") #s_static("Content-Type: application/sdp\r\n") ## Content-Type = ( "Content-Type" / "c" ) HCOLON media-type ## media-type = m-type SLASH m-subtype *(SEMI m-parameter) ## m-type = discrete-type / composite-type ## discrete-type = "text" / "image" / "audio" / "video" ## / "application" / extension-token ## composite-type = "message" / "multipart" / extension-token ## extension-token = ietf-token / x-token ## ietf-token = token ## x-token = "x-" token ## m-subtype = extension-token / iana-token ## iana-token = token ## m-parameter = m-attribute EQUAL m-value ## m-attribute = token ## m-value = token / quoted-string s_static("Content-Type: ") s_group("content_type_discrete", values=['application', 'image', 'audio', 'video', 'text']) if s_block_start("content_type_media", group="content_type_discrete"): s_delim("/") s_string("sdp") s_delim(";") s_static("mattr") s_static("=") s_string("mvalue") s_block_end() s_static("\r\n") ## Content-Length = ( "Content-Length" / "l" ) HCOLON 1*DIGIT s_static("Content-Length: ") s_sizer("invite_sdp", format="ascii", fuzzable=True, signed=True) s_static("\r\n\r\n") s_block_end() if s_block_start("invite_sdp"): s_static("v=0\r\n") s_static("o=- 1190505265 1190505265 IN IP4 LOCAL_IP\r\n") s_static("s=Opal SIP Session\r\n") s_static("c=IN IP4 LOCAL_IP\r\n") s_static("t=0 0\r\n") s_static("m=audio 5028 RTP/AVP 101 96 3 107 110 0 8\r\n") s_static("a=rtpmap:101 telephone-event/8000\r\n") s_static("a=fmtp:101 0-15\r\n") s_static("a=rtpmap:96 SPEEX/16000\r\n") s_static("a=rtpmap:3 GSM/8000\r\n") s_static("a=rtpmap:107 MS-GSM/8000\r\n") s_static("a=rtpmap:110 SPEEX/8000\r\n") s_static("a=rtpmap:0 PCMU/8000\r\n") s_static("a=rtpmap:8 PCMA/8000\r\n") s_static("m=video 5030 RTP/AVP 31\r\n") s_static("a=rtpmap:31 H261/90000\r\n") s_block_end() ################################################################################ s_initialize("OPTIONS") ################################################################################ # This is a fairly basic SDP fuzz set based off a captured packet instead of the RFC # Todo: Make RFC compliant s_initialize("SDP") if s_block_start("invite_header"): s_static("INVITE sip:TARGET_USER@HOST SIP/2.0\r\n") s_static("CSeq: 1 INVITE\r\n") s_static("Via: SIP/2.0/UDP LOCAL_IP:PORT;branch=z9hG4bKsomebranchvalue;rport\r\n") s_static("From: \"VoIPER\" <sip:USER@LOCAL_IP>;tag=somefromtagvalue\r\n") s_static("Call-ID: somecallidvalue@ubuntu\r\n") s_static("To: <sip:TARGET_USER@HOST>\r\n") s_static("Contact: <sip:USER@LOCAL_IP:PORT;transport=udp>\r\n") s_static("Max-Forwards: 70\r\n") s_static("Content-Type: application/sdp\r\n") s_static("Content-Length: ") s_sizer("invite_sdp", format="ascii", fuzzable=False, signed=True) s_static("\r\n\r\n") s_block_end() if s_block_start("invite_sdp"): #s_static("v=0\r\n") s_static("v=") s_dword(0, format='ascii', signed=True) s_static('\r\n') #s_static("o=- 1190505265 1190505265 IN IP4 192.168.3.104\r\n") if s_block_start("o"): s_static("o=") s_string("somegimp") s_delim(" ") s_dword(1190505265, format="ascii", signed=True) s_static(" ") s_dword(1190505265, format="ascii", signed=True) s_static(" ") s_string("IN") s_static(" ") s_string("IP4") s_static(" ") s_lego("ip_address_ascii", "192.168.99.99") s_static("\r\n") s_block_end() s_repeat("o", min_reps=2, max_reps=1000, step=10) #s_static("s=Opal SIP Session\r\n") # take this opportunity to fuzz EOL chars and attribite=delim s_string("s") s_delim("=") s_string("Opal SIP Session") s_delim("\r\n") s_static("i=") s_string("some information string") s_static("\r\n") s_static("u=") s_string("http://unprotectedhex.com/someuri.htm") s_static("\r\n") s_static("e=") s_string("email@address.com") s_static(" ") s_delim("(") s_string("someones name") s_delim(")") s_static("\r\n") #s_static("c=IN IP4 192.168.3.102\r\n") # repeated c lines cause an overflow in Asterisk at one point if s_block_start("c"): s_static("c=") s_string("IN") s_static(" ") s_string("IP4") s_static(" ") s_lego("ip_address_ascii", "192.168.99.99") s_static("\r\n") s_block_end() s_repeat("c", min_reps=2, max_reps=1000, step=10) #s_static("t=0 0\r\n") s_static("t=") s_dword(0, format="ascii", signed=True) s_static(" ") s_dword(1, format="ascii", signed=True) s_static("\r\n") s_static("p=") s_dword(232, format="ascii", fuzzable=True, signed=True) s_delim("-") s_string("343434") s_static("\r\n") s_static("b=") s_string("CT") s_static(":") s_dword(8, format=True, signed=True) s_static("\r\n") s_static("r=") s_dword(604800, format="ascii", signed=True) s_static(" ") s_dword(3600, format="ascii", signed=True, fuzzable=False) s_static(" ") s_dword(0, format="ascii", signed=True, fuzzable=False) s_static(" ") s_dword(9000, format="ascii", signed=True, fuzzable=False) s_static("\r\n") s_static("z=") s_dword(2882844526, format="ascii", signed=True) s_static(" ") s_string("-1h") s_static(" ") s_dword(2898848070, format="ascii", fuzzable=False) s_static(" ") s_dword(0, format="ascii", fuzzable=False) s_static("\r\n") s_static("k=") s_group("enc_types", values=['clear', 'base64', 'uri']) s_delim(":") if s_block_start("b64_encoded_key", dep="enc_types", dep_value="base64",\ encoder=base64_encode): s_string("somefancypantsencryptionkey") s_block_end() if s_block_start("clear_key", dep="enc_types", dep_values=["clear", 'uri']): s_string("somefancypantsencryptionkey") s_block_end() s_static("\r\n") # end of session info, start of media config if s_block_start("audio_config"): #s_static("m=audio 5028 RTP/AVP 101 96 98 3 107 110 0 8\r\n") s_static("m=") s_string("audio") s_static(" ") s_dword(5028, format="ascii", signed=True) s_static(" ") s_string("RTP/AVP") s_delim(" ") s_dword(101, format="ascii", signed=True) s_static(" 96") s_delim(" ") s_string("107 110 0 8") s_static("\r\n") #s_static("a=rtpmap:101 telephone-event/8000\r\n") s_static("a=") s_string("rtpmap") s_delim(":") s_string("101") s_delim(" ") s_string("telephone-event") s_static("/") s_string("8000") s_static("\r\n") s_block_end() s_repeat("audio_config", min_reps=2, max_reps=1000, step=10) s_static("i=") s_string("some information string") s_static("\r\n") if s_block_start("a"): s_static("a=rtpmap:98 L16/16000/2\r\n") s_block_end() s_repeat("a", min_reps=10, max_reps=1000, step=10) #s_static("a=rtpmap:96 SPEEX/16000\r\n") s_static("a=rtpmap:") s_dword(96, format="ascii", signed=True) s_static(" ") s_string("SPEEX") s_delim("/") s_dword(16000, format="ascii", signed=True) s_static("\r\n") s_static("a=rtpmap:3 GSM/8000\r\n") s_static("a=rtpmap:107 MS-GSM/8000\r\n") s_static("a=rtpmap:110 SPEEX/8000\r\n") s_static("a=rtpmap:0 PCMU/8000\r\n") s_static("a=rtpmap:8 PCMA/8000\r\n") s_static("m=video") s_static(" ") s_dword(5030, format="ascii", signed=True) s_delim("/") s_dword(2, signed=True, format="ascii") s_static(" ") s_string("RTP") s_delim("/") s_static("AVP") s_static(" ") s_dword(31, format="ascii", signed=True) s_static("\r\n") #s_static("a=rtpmap:31 H261/90000\r\n") s_static("a=rtpmap:") s_dword(31, format="ascii", signed=True) s_static(" ") s_string("H261") s_delim("/") s_dword(90000, format="ascii", signed=True) s_static("\r\n") ''' # t38 stuff. There was an asterisk advisory about the processing # of this some time ago s_static("m=image ") s_dword(5004, format="ascii", signed=True) s_static(" UDPTL t38") s_static("\r\n") s_static("a=") s_string("T38FaxVersion") s_delim(":") s_dword(0, signed=True, format="ascii") s_static("\r\n") s_static("a=T38MaxBitRate:") s_string("14400") s_static("\r\n") s_static("a=T38FaxMaxBuffer:") s_dword(1024, signed=True, format="ascii") s_static("\r\n") s_static("a=T38FaxMaxDatagram:") s_dword(238, signed=True, format="ascii") s_static("\r\n") s_static("a=T38FaxRateManagement:") s_string("transferredTFC") s_static("\r\n") s_static("a=T38FaxUdpEC:") s_string("t38UDPRedundancy") s_static("a=T38FaxFillBitRemoval:") s_dword(0, signed=True, format="ascii") s_static("\r\n") s_static("a=T38FaxTranscodingMMR:") s_string("0") s_static("\r\n") s_static("a=T38FaxTranscodingJBIG:") s_dword(0, signed=True, format="ascii") s_static("\r\n") ''' s_block_end() ################################################################################ s_initialize("ACK") if s_block_start("ack_request_line"): s_static("ACK sip:TARGET_USER@HOST SIP/2.0\r\n") s_block_end() if s_block_start("invite_header"): s_static("CSeq: ") s_string("1") s_delim(" ") s_string("ACK") s_static("\r\n") s_string("Via: ") s_string("SIP") s_delim("/") s_string("2.0") s_delim("/") s_string("UDP") s_static(" ") s_lego("ip_address_ascii", "192.168.99.99") s_delim(":") s_string("5068") s_delim(";") s_string("branch") s_delim("=") s_string("z9hG4bK") s_string("somebranchvalue") s_static(";") s_static("ttl") s_static("=") s_string("70") s_static(";") s_static("maddr=") s_lego("ipv6_address_ascii", "aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa") s_static(";") s_static("received=") s_lego("ipv6_address_ascii", "aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa") s_static(";") s_string("rport") s_static("\r\n") s_static("From: ") s_delim("\"") s_string("Negativa") s_delim("\"") s_delim(" ") s_delim("<") s_lego("from_sip_uri_basic", options={'fuzzable' : True}) s_delim(">") s_delim(";") s_string("tag") s_string("=") s_string("somefromtagval") s_static("\r\n") s_static("Call-ID: ") s_string("somecallidvalue") s_delim("@") s_string("TheKlatchianHead") s_static("\r\n") s_static("To: ") s_delim("\"") s_string("Negativa") s_delim("\"") s_delim(" ") s_delim("<") s_lego("to_sip_uri_basic", options={'fuzzable' : True}) s_delim(">") s_static("\r\n") s_static("Max-Forwards: ") s_string("70") s_static("\r\n\r\n") s_block_end() ################################################################################ s_initialize("CANCEL") if s_block_start("cancel_request_line"): s_static("CANCEL sip:TARGET_USER@HOST SIP/2.0\r\n") s_block_end() if s_block_start("invite_header"): s_static("CSeq: ") s_string("1") s_delim(" ") s_string("CANCEL") s_static("\r\n") s_string("Via: ") s_string("SIP") s_delim("/") s_string("2.0") s_delim("/") s_string("UDP") s_static(" ") s_lego("ip_address_ascii", "192.168.99.99") s_delim(":") s_string("5068") s_delim(";") s_string("branch") s_delim("=") s_string("z9hG4bK") s_string("somebranchvalue") s_static(";") s_static("ttl") s_static("=") s_string("70") s_static(";") s_static("maddr=") s_lego("ipv6_address_ascii", "aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa") s_static(";") s_static("received=") s_lego("ipv6_address_ascii", "aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa") s_static(";") s_string("rport") s_static("\r\n") s_static("From: ") s_delim("\"") s_string("Negativa") s_delim("\"") s_delim(" ") s_delim("<") s_lego("from_sip_uri_basic", options={'fuzzable' : True}) s_delim(">") s_delim(";") s_string("tag") s_string("=") s_string("somefromtagval") s_static("\r\n") s_static("Call-ID: ") s_string("somecallidvalue") s_delim("@") s_string("TheKlatchianHead") s_static("\r\n") s_static("To: ") s_delim("\"") s_string("Negativa") s_delim("\"") s_delim(" ") s_delim("<") s_lego("to_sip_uri_basic", options={'fuzzable' : True}) s_delim(">") s_static("\r\n") s_static("Max-Forwards: ") s_string("70") s_static("\r\n\r\n") s_block_end() ################################################################################ s_initialize("REGISTER") if s_block_start("register_request_line"): s_static("REGISTER sip:USER@HOST SIP/2.0\r\n") s_block_end() if s_block_start("register_header"): #s_static("CSeq: 1 INVITE\r\n") ## CSeq = "CSeq" HCOLON 1*DIGIT LWS Method s_static("CSeq: ") s_dword(2, fuzzable=True, format="ascii") s_delim(" ") s_string("REGISTER") s_static("\r\n") #s_static("Via: SIP/2.0/UDP 192.168.3.104:5068;branch=z9hG4bKsomebranchvalue;rport\r\n") ## Via = ( "Via" / "v" ) HCOLON via-parm *(COMMA via-parm) ## via-parm = sent-protocol LWS sent-by *( SEMI via-params ) ## via-params = via-ttl / via-maddr ## / via-received / via-branch ## / via-extension ## via-ttl = "ttl" EQUAL ttl ## via-maddr = "maddr" EQUAL host ## via-received = "received" EQUAL (IPv4address / IPv6address) ## via-branch = "branch" EQUAL token ## via-extension = generic-param ## sent-protocol = protocol-name SLASH protocol-version ## SLASH transport ## protocol-name = "SIP" / token ## protocol-version = token ## transport = "UDP" / "TCP" / "TLS" / "SCTP" ## / other-transport ## sent-by = host [ COLON port ] ## ttl = 1*3DIGIT ; 0 to 255 s_static("Via: ") s_string("SIP") s_delim("/") s_string("2.0") s_delim("/") s_string("UDP") s_static(" ") s_lego("ip_address_ascii", "192.168.99.99") s_delim(":") s_string("PORT") s_delim(";") s_string("branch") s_delim("=") s_string("z9hG4bK") s_string("somebranchvalue") s_static(";") s_static("ttl") s_static("=") s_string("70") s_static(";") s_string("rport") s_static("\r\n") #s_static("From: \"Negativa\" <sip:nnp@192.168.3.104>;tag=somefromtagvalue\r\n") ## From = ( "From" / "f" ) HCOLON from-spec ## from-spec = ( name-addr / addr-spec ) ## *( SEMI from-param ) ## from-param = tag-param / generic-param ## tag-param = "tag" EQUAL token ## name-addr = [ display-name ] LAQUOT addr-spec RAQUOT ## addr-spec = SIP-URI / SIPS-URI / absoluteURI s_static("From: ") s_delim("\"") s_string("Negativa") s_delim("\"") s_delim(" ") s_delim("<") s_lego("from_sip_uri", options={'fuzzable' : True}) s_delim(">") s_delim(";") s_string("tag") s_string("=") s_string("somefromtagval") s_static("\r\n") #s_static("Call-ID: somecallidvalue@ubuntu\r\n") ## Call-ID = ( "Call-ID" / "i" ) HCOLON callid ## callid = word [ "@" word ] s_static("Call-ID: ") s_string("somecallidvalue") s_delim("@") s_string("TheKlatchianHead") s_static("\r\n") #s_static("To: <sip:nnp@192.168.1.1>\r\n") ## To = ( "To" / "t" ) HCOLON ( name-addr ## / addr-spec ) *( SEMI to-param ) ## to-param = tag-param / generic-param s_static("To: ") s_delim("\"") s_string("Negativa") s_delim("\"") s_delim(" ") s_delim("<") s_lego("to_sip_uri", options={'fuzzable' : True}) s_delim(">") s_static("\r\n") #s_static("Max-Forwards: 70\r\n") ## Max-Forwards = "Max-Forwards" HCOLON 1*DIGIT s_static("Max-Forwards: ") s_string("70") s_static("\r\n") ## Content-Length = ( "Content-Length" / "l" ) HCOLON 1*DIGIT s_static("Content-Length: ") s_dword(0, fuzzable=True, format="ascii") s_static("\r\n") #s_static("Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE\r\n") s_static("Allow: ") s_string("INVITE") s_static(",") s_static("ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE") s_static("\r\n") #s_static("Expires: 3600\r\n") s_static("Expires: ") s_string("3600") s_static("\r\n") #s_static("User-Agent: Ekiga/2.0.3\r\n") ## User-Agent = "User-Agent" HCOLON server-val *(LWS server-val) ## server-val = product / comment ## product = token [SLASH product-version] ## product-version = token s_static("User-Agent: ") s_string("VoIPER") s_delim("/") s_string("0.02") s_delim(" ") s_string("Clack/0.02") s_static("\r\n") #s_static("Authorization: Digest username=\"nnp\", realm=\"bleh.com\", nonce=\"value\", response=\"value\"\r\n") s_static("Authorization: ") s_lego("static_credentials") s_static("\r\n") s_static("Contact: ") s_delim("<") s_lego("from_sip_uri", options={'fuzzable' : True}) s_delim(">") s_static("\r\n") s_static("\r\n") s_block_end() ################################################################################ s_initialize("SUBSCRIBE") if s_block_start("subscribe_request_line"): s_static("SUBSCRIBE sip:USER@HOST SIP/2.0\r\n") s_block_end() if s_block_start("subscribe_header"): s_static("CSeq: ") s_dword(3, fuzzable=True, format="ascii") s_static(" ") s_string("SUBSCRIBE") s_string("\r\n") # Via: SIP/2.0/UDP 192.168.3.104:5062;branch=z9hG4bK9a485f36-ebfb-1810-9783-0007e9ca58f2;rport s_static("Via: ") s_string("SIP") s_delim("/") s_string("2.0") s_delim("/") s_string("UDP") s_static(" ") s_lego("ip_address_ascii", "192.168.99.99") s_delim(":") s_string("PORT") s_delim(";") s_string("branch") s_delim("=") s_string("z9hG4bK") s_string("somebranchvalue") s_static(";") s_static("ttl") s_static("=") s_dword(70, fuzzable=True, format="ascii") s_static(";") s_string("rport") s_static("\r\n") # User-Agent: Ekiga/2.0.9 s_static("User-Agent: ") s_string("VoIPER") s_delim("/") s_string("0.02") s_delim(" ") s_string("Clack/0.02") s_static("\r\n") # From: <sip:1001@192.168.3.101>;tag=9a485f36-ebfb-1810-9782-0007e9ca58f2 s_static("From: ") s_delim("\"") s_string("Negativa") s_delim("\"") s_delim(" ") s_delim("<") s_lego("from_sip_uri_basic", options={'fuzzable' : True}) s_delim(">") s_delim(";") s_string("tag") s_string("=") s_string("somefromtagval") s_static("\r\n") # Call-ID: 5cff5e36-ebfb-1810-9772-0007e9ca58f2@N0N4M3 s_static("Call-ID: ") s_string("somecallidvalue") s_delim("@") s_string("TheKlatchianHead") s_static("\r\n") # To: <sip:1001@192.168.3.101> # "To" is addressed to self in this case s_static("To: ") s_delim("\"") s_string("Negativa") s_delim("\"") s_delim(" ") s_delim("<") s_string("sip") s_delim(":") s_string("USER") s_delim("@") s_lego("ip_address_ascii", "192.168.96.69") s_delim(">") s_static("\r\n") # Contact: <sip:1001@192.168.3.104:5062;transport=udp> s_static("Contact: ") s_delim("<") s_lego("from_sip_uri_basic", options={'fuzzable' : True}) s_delim(">") s_static("\r\n") # Accept: application/simple-message-summary s_static("Accept: ") s_string("application") s_delim("/") s_string("simple-message-summary") s_static("\r\n") # Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE s_static("Allow: ") s_string("INVITE") s_static(",") s_static("ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE") s_static("\r\n") # Expires: 3600 s_static("Expires: ") s_dword(3600, fuzzable=True, format="ascii") s_static("\r\n") # Event: message-summary s_static("Event: ") s_string("message-summary") s_static("\r\n") s_static("Content-Length: ") s_dword(0, fuzzable=True, format="ascii") s_static("\r\n") s_static("Max-Forwards: ") s_dword(70, fuzzable=True, format="ascii") s_static("\r\n") s_static("\r\n") s_block_end() ################################################################################ s_initialize("NOTIFY") if s_block_start("notify_request_line"): s_static("NOTIFY sip:USER@HOST SIP/2.0\r\n") s_block_end() if s_block_start("notify_header"): s_static("CSeq: ") s_dword(3, fuzzable=True, format="ascii") s_string("SUBSCRIBE") s_string("\r\n") # Via: SIP/2.0/UDP 192.168.3.104:5062;branch=z9hG4bK9a485f36-ebfb-1810-9783-0007e9ca58f2;rport s_static("Via: ") s_string("SIP") s_delim("/") s_string("2.0") s_delim("/") s_string("UDP") s_static(" ") s_lego("ip_address_ascii", "192.168.99.99") s_delim(":") s_string("PORT") s_delim(";") s_string("branch") s_delim("=") s_string("z9hG4bK") s_string("somebranchvalue") s_static(";") s_static("ttl") s_static("=") s_dword(70, fuzzable=True, format="ascii") s_static(";") s_string("rport") s_static("\r\n") # User-Agent: Ekiga/2.0.9 s_static("User-Agent: ") s_string("VoIPER") s_delim("/") s_string("0.02") s_delim(" ") s_string("Clack/0.02") s_static("\r\n") # From: <sip:1001@192.168.3.101>;tag=9a485f36-ebfb-1810-9782-0007e9ca58f2 s_static("From: ") s_delim("\"") s_string("Negativa") s_delim("\"") s_delim(" ") s_delim("<") s_lego("from_sip_uri_basic", options={'fuzzable' : True}) s_delim(">") s_delim(";") s_string("tag") s_string("=") s_string("somefromtagval") s_static("\r\n") # Call-ID: 5cff5e36-ebfb-1810-9772-0007e9ca58f2@N0N4M3 s_static("Call-ID: ") s_string("somecallidvalue") s_delim("@") s_string("TheKlatchianHead") s_static("\r\n") # To: <sip:1001@192.168.3.101> s_static("To: ") s_delim("\"") s_string("Negativa") s_delim("\"") s_delim(" ") s_delim("<") s_lego("to_sip_uri_basic", options={'fuzzable' : True}) s_delim(">") s_static("\r\n") # Contact: <sip:1001@192.168.3.104:5062;transport=udp> s_static("Contact: ") s_delim("<") s_lego("from_sip_uri_basic", options={'fuzzable' : True}) s_delim(">") s_static("\r\n") # Accept: application/simple-message-summary s_static("Accept: ") s_string("application") s_delim("/") s_string("simple-message-summary") # Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE s_static("Allow: ") s_string("INVITE") s_static(",") s_static("ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE") s_static("\r\n") # Expires: 3600 s_static("Expires: ") s_dword(3600, fuzzable=True, format="ascii") s_static("\r\n") # Event: message-summary s_static("Event: ") s_string("message-summary") s_static("\r\n") s_static("Content-Length: ") s_dword(0, fuzzable=True, format="ascii") s_static("\r\n") s_static("Max-Forwards: ") s_dword(70, fuzzable=True, format="ascii") s_static("\r\n") # Supported: 100rel, precondition, timer s_static("Supported: ") if s_block_start("supported_block"): s_string("100rel") s_delim(",") s_block_end() s_repeat("supported_block", min_reps=2, max_reps=1000, step=10) s_string("precondition") s_static("\r\n") s_static("Allow-Events: ") if s_block_start("allow-events_block"): s_static("dialog, call-info, sla, include-session-description, presence.winfo, message-summary,") s_block_end() s_repeat("allow-events_block", min_reps=2, max_reps=1000, step=10) s_string("talk") s_static("\r\n") s_static("Subscription-State: ") s_string("terminated") s_delim(";") s_string("timeout") s_static("\r\n") s_string("Content-Type: ") s_string("application") s_delim("/") s_string("simple-message-summary") s_static("\r\n") s_static("Content-Length: ") s_sizer("notify_body", format="ascii", fuzzable=True, signed=True) s_static("\r\n") s_block_end() if s_block_start("notify_body"): s_string("Messages-Waiting: ") s_string("yes") s_delim("\r\n") s_static("Message-Account: ") s_lego("to_sip_uri_basic") s_static("\r\n") s_block_end() ################################################################################ ''' # Similar to the SDP fuzzer but the data is encoded # Todo: finish s_initialize("SDP_ENCODED") if s_block_start("invite_header"): s_static("INVITE sip:TARGET_USER@192.168.3.104 SIP/2.0\r\n") s_static("CSeq: 1 INVITE\r\n") s_static("Via: SIP/2.0/UDP 192.168.3.102:5068;branch=z9hG4bKsomebranchvalue;rport\r\n") s_static("From: \"VoIPER\" <sip:USER@192.168.3.104>;tag=somefromtagvalue\r\n") s_static("Call-ID: somecallidvalue@ubuntu\r\n") s_static("To: <sip:nnp@192.168.3.101>\r\n") s_static("Contact: <sip:nnp@192.168.3.102:5068;transport=udp>\r\n") s_static("Max-Forwards: 70\r\n") s_static("Content-Type: application/sdp\r\n") s_static("Content-Length: ") s_sizer("invite_sdp", format="ascii", fuzzable=True, signed=True) #s_static("Content-Encoding: gzip\r\n") s_static("Content-Encoding: ") s_string("gzip") s_static("\r\n\r\n") s_block_end() if s_block_start("invite_sdp", encoder=gzip_encode): s_static("v=0\r\n") s_static("o=- 1190505265 1190505265 IN IP4 192.168.3.104\r\n") s_static("s=Opal SIP Session\r\n") #s_static("c=IN IP4 192.168.3.102\r\n") # repeated c lines cause an overflow in Asterisk at one point if s_block_start("c"): s_static("c=") s_string("IN") s_static(" ") s_string("IP4") s_static(" ") s_lego("ip_address_ascii", "192.168.96.69") s_static("\r\n") s_block_end() s_repeat("c", min_reps=2, max_reps=1000, step=10) s_static("t=0 0\r\n") s_static("m=audio 5028 RTP/AVP 101 96 3 107 110 0 8\r\n") s_static("a=rtpmap:101 telephone-event/8000\r\n") s_static("a=fmtp:101 0-15\r\n") s_static("a=rtpmap:96 SPEEX/16000\r\n") s_static("a=rtpmap:3 GSM/8000\r\n") s_static("a=rtpmap:107 MS-GSM/8000\r\n") s_static("a=rtpmap:110 SPEEX/8000\r\n") s_static("a=rtpmap:0 PCMU/8000\r\n") s_static("a=rtpmap:8 PCMA/8000\r\n") s_static("m=video 5030 RTP/AVP 31\r\n") s_static("a=rtpmap:31 H261/90000\r\n") s_block_end() '''
51,877
Python
.py
1,513
28.615334
136
0.559639
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,970
xbox.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/requests/xbox.py
""" mediaconnect port 2869 """ from sulley import * ######################################################################################################################## s_initialize("mediaconnect: get album list") # POST /upnphost/udhisapi.dll?control=uuid:848a20cc-91bc-4a02-8180-187baa537527+urn:microsoft-com:serviceId:MSContentDirectory HTTP/1.1 s_group("verbs", values=["GET", "POST"]) s_delim(" ") s_delim("/") s_string("upnphost/udhisapi.dll") s_delim("?") s_string("control") s_delim("=") s_string("uuid") s_delim(":") s_string("848a20cc-91bc-4a02-8180-187baa537527") s_delim("+") s_static("urn") s_delim(":") s_string("microsoft-com:serviceId:MSContentDirectory") s_static(" HTTP/1.1\r\n") # User-Agent: Xbox/2.0.4552.0 UPnP/1.0 Xbox/2.0.4552.0 # we take this opportunity to fuzz headers in general. s_string("User-Agent") s_delim(":") s_delim(" ") s_string("Xbox") s_delim("/") s_string("2.0.4552.0 UPnP/1.0 Xbox/2.0.4552.0") s_static("\r\n") # Connection: Keep-alive s_static("Connection: ") s_string("Keep-alive") s_static("\r\n") # Host:10.10.20.111 s_static("Host: 10.10.20.111") s_static("\r\n") # SOAPACTION: "urn:schemas-microsoft-com:service:MSContentDirectory:1#Search" s_static("SOAPACTION: ") s_delim("\"") s_static("urn") s_delim(":") s_string("schemas-microsoft-com") s_static(":") s_string("service") s_static(":") s_string("MSContentDirectory") s_static(":") s_string("1") s_delim("#") s_string("Search") s_delim("\"") s_static("\r\n") # CONTENT-TYPE: text/xml; charset="utf-8" s_static("CONTENT-TYPE: text/xml; charset=\"utf-8\"") s_static("\r\n") # Content-Length: 547 s_static("Content-Length: ") s_sizer("content", format="ascii", signed=True, fuzzable=True) s_static("\r\n\r\n") if s_block_start("content"): # <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> s_delim("<") s_string("s") s_delim(":") s_string("Envelope") s_static(" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" ") s_static("s:") s_string("encodingStyle") s_delim("=") s_string("\"http://schemas.xmlsoap.org/soap/encoding/\"") s_delim(">") s_static("<s:Body>") s_static("<u:Search xmlns:u=\"urn:schemas-microsoft-com:service:MSContentDirectory:1\">") # <ContainerID>7</ContainerID> s_static("<ContainerID>") s_dword(7, format="ascii", signed=True) s_static("</ContainerID>") # <SearchCriteria>(upnp:class = &quot;object.container.album.musicAlbum&quot;)</SearchCriteria> s_static("<SearchCriteria>(upnp:class = &quot;") s_string("object.container.album.musicAlbum") s_static("&quot;)</SearchCriteria>") # <Filter>dc:title,upnp:artist</Filter> s_static("<Filter>") s_delim("dc") s_delim(":") s_string("title") s_delim(",") s_string("upnp") s_delim(":") s_string("artist") s_static("</Filter>") # <StartingIndex>0</StartingIndex> s_static("<StartingIndex>") s_dword(0, format="ascii", signed=True) s_static("</StartingIndex>") # <RequestedCount>1000</RequestedCount> s_static("<RequestedCount>") s_dword(1000, format="ascii", signed=True) s_static("</RequestedCount>") s_static("<SortCriteria>+dc:title</SortCriteria>") s_static("</u:Search>") s_static("</s:Body>") # </s:Envelope> s_delim("<") s_delim("/") s_delim("s") s_delim(":") s_string("Envelope") s_delim(">") s_block_end()
3,477
Python
.py
112
28.133929
135
0.638482
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,971
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/requests/__init__.py
import os __all__ = [] for filename in os.listdir(os.path.dirname(__file__)): if not filename.startswith("__") and filename.endswith(".py"): filename = filename.replace(".py", "") __all__.append(filename) # uncommenting the next line causes all requests to load into the namespace once 'requests' is imported. # this is not the desired behaviour, instead the user should import individual packages of requests. ie: # from requests import http, trend #__import__("requests."+filename)
542
Python
.py
10
47.6
112
0.668561
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,972
stun.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/requests/stun.py
""" STUN: Simple Traversal of UDP through NAT Gizmo binds this service on UDP port 5004 / 5005 http://www.vovida.org/ """ from sulley import * ######################################################################################################################## s_initialize("binding request") # message type 0x0001: binding request. s_static("\x00\x01") # message length. s_sizer("attributes", length=2, endian=">", name="message length", fuzzable=True) # message transaction id. s_static("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff") if s_block_start("attributes"): # attribute type # 0x0001: mapped address # 0x0003: change request # 0x0004: source address # 0x0005: changed address # 0x8020: xor mapped address # 0x8022: server s_word(0x0003, endian=">") s_sizer("attribute", length=2, endian=">", name="attribute length", fuzzable=True) if s_block_start("attribute"): # default valid null block s_string("\x00\x00\x00\x00") s_block_end() s_block_end() # toss out some large strings when the lengths are anything but valid. if s_block_start("fuzz block 1", dep="attribute length", dep_value=4, dep_compare="!="): s_static("A"*5000) s_block_end() # toss out some large strings when the lengths are anything but valid. if s_block_start("fuzz block 2", dep="message length", dep_value=8, dep_compare="!="): s_static("B"*5000) s_block_end() ######################################################################################################################## s_initialize("binding response") # message type 0x0101: binding response
1,652
Python
.py
40
38.275
120
0.595372
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,973
trend.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/requests/trend.py
from sulley import * import struct # crap ass trend xor "encryption" routine for control manager (20901) def trend_xor_encode (str): ''' Simple bidirectional XOR "encryption" routine used by this service. ''' key = 0xA8534344 ret = "" # pad to 4 byte boundary. pad = 4 - (len(str) % 4) if pad == 4: pad = 0 str += "\x00" * pad while str: dword = struct.unpack("<L", str[:4])[0] str = str[4:] dword ^= key ret += struct.pack("<L", dword) key = dword return ret # crap ass trend xor "encryption" routine for control manager (20901) def trend_xor_decode (str): key = 0xA8534344 ret = "" while str: dword = struct.unpack("<L", str[:4])[0] str = str[4:] tmp = dword tmp ^= key ret += struct.pack("<L", tmp) key = dword return ret # dce rpc request encoder used for trend server protect 5168 RPC service. # opnum is always zero. def rpc_request_encoder (data): return utils.dcerpc.request(0, data) ######################################################################################################################## s_initialize("20901") """ Trend Micro Control Manager (DcsProcessor.exe) http://bakemono/mediawiki/index.php/Trend_Micro:Control_Manager This fuzz found nothing! need to uncover more protocol details. See also: pedram's pwned notebook page 3, 4. """ # dword 1, error: 0x10000001, do something:0x10000002, 0x10000003 (>0x10000002) s_group("magic", values=["\x02\x00\x00\x10", "\x03\x00\x00\x10"]) # dword 2, size of body s_size("body") # dword 3, crc32(block) (copy from eax at 0041EE8B) # XXX - CRC is non standard, nop out jmp at 0041EE99 and use bogus value: #s_checksum("body", algorithm="crc32") s_static("\xff\xff\xff\xff") # the body of the trend request contains a variable number of (2-byte) TLVs if s_block_start("body", encoder=trend_xor_encode): s_word(0x0000, full_range=True) # completely fuzz the type s_size("string1", length=2) # valid length if s_block_start("string1"): # fuzz string s_string("A"*1000) s_block_end() s_random("\x00\x00", 2, 2) # random type s_size("string2", length=2) # valid length if s_block_start("string2"): # fuzz string s_string("B"*10) s_block_end() # try a table overflow. if s_block_start("repeat me"): s_random("\x00\x00", 2, 2) # random type s_size("string3", length=2) # valid length if s_block_start("string3"): # fuzz string s_string("C"*10) s_block_end() s_block_end() # repeat string3 a bunch of times. s_repeat("repeat me", min_reps=100, max_reps=1000, step=50) s_block_end("body") ######################################################################################################################## """ Trend Micro Server Protect (SpNTsvc.exe) This fuzz uncovered a bunch of DoS and code exec bugs. The obvious code exec bugs were documented and released to the vendor. See also: pedram's pwned notebook page 1, 2. // opcode: 0x00, address: 0x65741030 // uuid: 25288888-bd5b-11d1-9d53-0080c83a5c2c // version: 1.0 error_status_t rpc_opnum_0 ( [in] handle_t arg_1, // not sent on wire [in] long trend_req_num, [in][size_is(arg_4)] byte overflow_str[], [in] long arg_4, [out][size_is(arg_6)] byte arg_5[], // not sent on wire [in] long arg_6 ); """ for op, submax in [(0x1, 22), (0x2, 19), (0x3, 85), (0x5, 25), (0xa, 49), (0x1f, 25)]: s_initialize("5168: op-%x" % op) if s_block_start("everything", encoder=rpc_request_encoder): # [in] long trend_req_num, s_group("subs", values=map(chr, range(1, submax))) s_static("\x00") # subs is actually a little endian word s_static(struct.pack("<H", op)) # opcode # [in][size_is(arg_4)] byte overflow_str[], s_size("the string") if s_block_start("the string", group="subs"): s_static("A" * 0x5000, name="arg3") s_block_end() # [in] long arg_4, s_size("the string") # [in] long arg_6 s_static(struct.pack("<L", 0x5000)) # output buffer size s_block_end() ######################################################################################################################## s_initialize("5005") """ Trend Micro Server Protect (EarthAgent.exe) Some custom protocol listening on TCP port 5005 """ s_static("\x21\x43\x65\x87") # magic # command s_static("\x00\x00\x00\x00") # dunno s_static("\x01\x00\x00\x00") # dunno, but observed static # length s_static("\xe8\x03\x00\x00") # dunno, but observed static s_static("\x00\x00\x00\x00") # dunno, but observed static
4,922
Python
.py
122
35.114754
120
0.567017
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,974
http.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/requests/http.py
from sulley import * # GET /index.html HTTP/1.1 s_initialize("HTTP BASIC") s_group("verbs", values=["GET", "HEAD", "POST", "TRACE"]) if s_block_start("body", group="verbs"): s_delim(" ") s_delim("/") s_string("index.html") s_delim(" ") s_string("HTTP") s_delim("/") s_string("1") s_delim(".") s_string("1") s_static("\r\n\r\n") s_block_end()
383
Python
.py
16
20.375
57
0.565574
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,975
rendezvous.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/sulley/requests/rendezvous.py
from sulley import * ######################################################################################################################## s_initialize("trillian 1") s_static("\x00\x00") # transaction ID s_static("\x00\x00") # flags (standard query) s_word(1, endian=">") # number of questions s_word(0, endian=">", fuzzable=False) # answer RRs s_word(0, endian=">", fuzzable=False) # authority RRs s_word(0, endian=">", fuzzable=False) # additional RRs # queries s_lego("dns_hostname", "_presence._tcp.local") s_word(0x000c, endian=">") # type = pointer s_word(0x8001, endian=">") # class = flush ######################################################################################################################## s_initialize("trillian 2") if s_block_start("pamini.local"): if s_block_start("header"): s_static("\x00\x00") # transaction ID s_static("\x00\x00") # flags (standard query) s_word(2, endian=">") # number of questions s_word(0, endian=">", fuzzable=False) # answer RRs s_word(2, endian=">", fuzzable=False) # authority RRs s_word(0, endian=">", fuzzable=False) # additional RRs s_block_end() # queries s_lego("dns_hostname", "pamini.local") s_word(0x00ff, endian=">") # type = any s_word(0x8001, endian=">") # class = flush s_block_end() s_lego("dns_hostname", "pedram@PAMINI._presence._tcp") s_word(0x00ff, endian=">") # type = any s_word(0x8001, endian=">") # class = flush # authoritative nameservers s_static("\xc0") # offset specifier s_size("header", length=1) # offset to pamini.local s_static("\x00\x01") # type = A (host address) s_static("\x00\x01") # class = in s_static("\x00\x00\x00\xf0") # ttl 4 minutes s_static("\x00\x04") # data length s_static(chr(152) + chr(67) + chr(137) + chr(53)) # ip address s_static("\xc0") # offset specifier s_size("pamini.local", length=1) # offset to pedram@PAMINI... s_static("\x00\x21") # type = SRV (service location) s_static("\x00\x01") # class = in s_static("\x00\x00\x00\xf0") # ttl 4 minutes s_static("\x00\x08") # data length s_static("\x00\x00") # priority s_static("\x00\x00") # weight s_static("\x14\xb2") # port s_static("\xc0") # offset specifier s_size("header", length=1) # offset to pamini.local ######################################################################################################################## s_initialize("trillian 3") if s_block_start("pamini.local"): if s_block_start("header"): s_static("\x00\x00") # transaction ID s_static("\x00\x00") # flags (standard query) s_word(2, endian=">") # number of questions s_word(0, endian=">", fuzzable=False) # answer RRs s_word(2, endian=">", fuzzable=False) # authority RRs s_word(0, endian=">", fuzzable=False) # additional RRs s_block_end() # queries s_lego("dns_hostname", "pamini.local") s_word(0x00ff, endian=">") # type = any s_word(0x0001, endian=">") # class = in s_block_end() s_lego("dns_hostname", "pedram@PAMINI._presence._tcp") s_word(0x00ff, endian=">") # type = any s_word(0x0001, endian=">") # class = in # authoritative nameservers s_static("\xc0") # offset specifier s_size("header", length=1) # offset to pamini.local s_static("\x00\x01") # type = A (host address) s_static("\x00\x01") # class = in s_static("\x00\x00\x00\xf0") # ttl 4 minutes s_static("\x00\x04") # data length s_static(chr(152) + chr(67) + chr(137) + chr(53)) # ip address s_static("\xc0") # offset specifier s_size("pamini.local", length=1) # offset to pedram@PAMINI... s_static("\x00\x21") # type = SRV (service location) s_static("\x00\x01") # class = in s_static("\x00\x00\x00\xf0") # ttl 4 minutes s_static("\x00\x08") # data length s_static("\x00\x00") # priority s_static("\x00\x00") # weight s_static("\x14\xb2") # port s_static("\xc0") # offset specifier s_size("header", length=1) # offset to pamini.local
5,403
Python
.py
89
57.876404
120
0.427384
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,976
sip_utilities.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/sip_utilities.pyc
Ñò âпMc @sÔdZddkZddkZddkZddkZddkZddkZddkZddklZddk Tddk l Z ddd„ƒYZ ddd „ƒYZ d dd „ƒYZd dd „ƒYZdS(sÀ This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com iÿÿÿÿN(tQueue(t*(tLoggertSIPMessageGeneratorcBs/eZd„Zdd„Zd„Zd„ZRS(cCsZh dd6dd6dd6dd6d d 6d d 6d d6dd6dd6dd6dd6|_dS(sž This class parses SIP messages and extracts the values of the attributes, it the fills in a given response/request with these values sbranch\s*=\s*([\d\w-]+)s[BRANCH]sFrom.*;tag=([\w\d]+)s [FROMTAG]sCall-ID\s*:\s*(\S+)s [CALL-ID]sCSeq\s*:\s*(\d+?)s [CSEQ-NUM]sExpires\s*:\s*(\d+)s [EXPIRES]sTo\s*:\s*(.*) s[TO]sTo\s*:\s*([\w\d\.:<>@]+=);?s [TO-NOTAG]sFrom\s*:\s*(.*) s[FROM]s2[INVITE|CANCEL|REGISTER|OPTIONS]\s+(\S*)\s+SIP/2.0s [SIP-URI]sVia\s*:\s*([^( )]+)s[VIA]sVia\s*:\s*([\w\d\.:<>@/ ]+);s [VIA-URI]N(t regex_dict(tself((s//pentest/voiper/protocol_logic/sip_utilities.pyt__init__$s cCs)h}|i|||ƒ|i||ƒS(så Parses parse_msg for the all values defined in self.regex_dict and fills them into a template provided by fill_msg @type parse_msg: String @param parse_msg: The SIP message to parse @type fill_msg: String @param fill_msg: The SIP message to fill @type keys: List @param keys: The keys to fill from self.regex_dict @rtype: String @return: The filled in request/response (tparsetfill(Rt parse_msgtfill_msgtkeysttmp_dict((s//pentest/voiper/protocol_logic/sip_utilities.pytgenerate8scCs‘|djo|iiƒ}nxj|D]b}|i|}ti||tiƒ}|o0t|iƒƒdjo|idƒ||<q'q'WdS(sô Parses msg for the keys specified in dict and sets the value of the key to the value parsed from msg @type msg: String @param msg: The SIP message to parse @type dict: Dictionary @param dict: A dictionary who's keys correspond to the keys in self.regex_dict that you want to parse from the message. It will be filled with the values from msg @type keys: List @param keys: The keys to fill from self.regex_dict iiN( tNoneRR tretsearcht IGNORECASEtlentgroupstgroup(RtmsgtdictR t regex_nametregextvalue((s//pentest/voiper/protocol_logic/sip_utilities.pyRMs   cCsFx?|iƒD]1}||djo|i|||ƒ}q q W|S(s} Fills the msg with the data from dict by replacing the values in msg that correspond to the keys in dict @type msg: String @param msg: The request/response to fill in @type dict: Dictionary @param: The dictionary containing the data to insert @rtype: String @return: The filled in request/response t(R treplace(RRRt replace_name((s//pentest/voiper/protocol_logic/sip_utilities.pyRes  N(t__name__t __module__RRR RR(((s//pentest/voiper/protocol_logic/sip_utilities.pyR#s   tSIPInviteCancelercBs,eZd„Zd„Zd„Zd„ZRS(c Cs||_||_tdƒ|_||_tƒ|_tƒi|_t |_ d|_ x0t |i ƒD]}t id|iƒiƒqgWdiddddd d d d gƒ|_d iddddddddgƒd|_ddddddg|_dS(s} Cancels a given INVITE request. The publicly accessible cancel method puts the message to be cancelled onto a queue. Worker threads read from this queue and cancel the given messages after a specified timeout (default = 2.0 seconds). It also attempts to ACK any responses received to keep communications as normal as possible @type host: String @param host: The host to send the CANCEL to @type port: Integer @param port: The port to send the CANCEL to @type timeout: Float @param timeout: The timeout to wait before cancelling the INVITE iittargetRsACK [SIP-URI] SIP/2.0 s To: [TO] sFrom: [FROM] sCall-ID: [CALL-ID] s CSeq: 1 ACK s Via: [VIA] sMax-Forwards: 70 sContent-Length: 0 s sCANCEL [SIP-URI] SIP/2.0sCSeq: [CSEQ-NUM] CANCELs Via: [VIA]s From: [FROM]sCall-ID: [CALL-ID]sTo: [TO]sMax-Forwards: 70s3Contact: <sip:nnp@192.168.3.104:5068;transport=udp>s s'481 Call Leg/Transaction Does Not Exists488 Not Acceptable Heres487 Request Terminateds 603 Declines 486 Busy Heres400 Bad RequestN(thosttportRtqueuettimeoutRt sip_parserRtlogtTruetalivet num_threadstranget threadingtThreadt_SIPInviteCanceler__canceltstarttjointack_msgtcancel_templatetack_msgs(RR!R"R$tx((s//pentest/voiper/protocol_logic/sip_utilities.pyRzsB        c Csk|ii||idddddddgƒ}t|ƒdjo|d }n|ii||fƒd S( s8 Places a cancel for invite_data onto the cancellation queue @type sock: Socket @param sock: The socket that sent the INVITE request @type invite_data: String @param invite_data: An invite message used to initialise a call @todo: Add TCP support s [SIP-URI]s [CSEQ-NUM]s[VIA]s[BRANCH]s[FROM]s [CALL-ID]s[TO]iãÿN(R%R R1RR#tput(Rtsockt invite_datat cancel_msg((s//pentest/voiper/protocol_logic/sip_utilities.pytcancelµs    cCs.x't|iƒD]}|iidƒqWdS(N(NN(R*R)R#R4R(RR3((s//pentest/voiper/protocol_logic/sip_utilities.pytkill_cancel_threadsÌsc Csµx®|iiƒ\}}|p|pPnti|iƒtttƒ}|i|i |i fƒ|i |ƒx't dƒD]}t i ||ggg|iƒ\}}}t|ƒdjoÕxÓ|D]Æ}y|idƒ\} } Wn#tj o|idƒqÇnXx~|iD]s} | i| ƒdjoW|ii| |idgƒ} |ii|| ddd d gƒ} |i | d ƒqqWqÇWq}Pq}W|iƒ|iƒqd S( s[ This method attempts to cancel the call initiated by sending invite_data. It simply replaces the INVITE keyword with CANCEL and resends the data. It runs as a worker thread and gives a timeout of self.timeout before cancelling the INVITE @todo: Remove 'select' statement. Pointless when using UDP iiiãÿs;SocketError cancelling request. Ensure target is listening.iÿÿÿÿs[TO]s [CALL-ID]s[FROM]s [SIP-URI]s[VIA]N(R#tgetttimetsleepR$tsockettAF_INETt SOCK_DGRAMtconnectR!R"tsendR*tselectRtrecvfromterrorR&R2tfindR%R R0tclose( Rt invite_sockR7t cancel_sockR3t ready_to_readtready_to_writetbrokededt read_socktdatataddrt response_linetresponse((s//pentest/voiper/protocol_logic/sip_utilities.pyt__cancelÐs@        ! (RRRR8R9R-(((s//pentest/voiper/protocol_logic/sip_utilities.pyRys ;  tSIPCrashDetectorcBseZdd„Zd„ZRS(g@c Csntidƒ||_||_||_tƒi|_t|_di ddddddd d gƒ|_ d S( sM Attempts to detect a SIP device malfunctioning by sending an OPTIONS message to the host specified. All SIP implementations should respond to this when functioning correctly. If no response is received another request is sent, if this is also unanswered we assume the target has died a grisly death @type host: String @param host: The host to target @type port: Integer @param port: The port to target @type timeout: Float @param timeout: The timeout for waiting for a response to the probe iÂRs&OPTIONS sip:user@example.com SIP/2.0 sTo: sip:user@example.com s+From: sip:caller@192.168.3.102;tag=[RAND] s Call-ID: crashdetection.[RAND] sCSeq: [CSEQ-RAND] OPTIONS s:Via: SIP/2.0/UDP host1.example.com;branch=z9hG4bKk[RAND] sMax-Forwards: 70 sContent-Length: 0 N( trandomtseedR!R"R$RR&R'R(R/t options_msg(RR!R"R$((s//pentest/voiper/protocol_logic/sip_utilities.pyRs      c Csëtttƒ}|idƒ|i|iƒ|id ƒdig}tdƒD]}|t i t i ƒqP~ƒ}|i idtt iddƒƒƒ}|id |ƒ}tttƒ}|i|iƒ|i|i|ifƒ|i|ƒ|idƒt}xÊtd ƒD]¼}ti||ggg|iƒ\}} } t|ƒdjoxx_|D]W} y| id ƒ\} } Wn#tj o|id ƒq]nX| o t}Pq]q]W|tjoPqÏqPqW|iƒ|iƒ|S(sí Sends the OPTIONS message and waits for a response. We don't bother checking if the response to recieved is to the OPTIONS or to the INVITE as any sort of response should indicate the target is still alive. @type sock: Socket @param sock: The socket used to send the last fuzz case @rtype: Boolean @return: A boolean value indicating whether the target has is responding or not @todo: Add TCP support is0.0.0.0iÄRi s [CSEQ-RAND]ièi †s[RAND]i iãÿsDSocketError when checking target status. Ensure target is listening.(s0.0.0.0iÄ(R=R>R?t setblockingt settimeoutR$tbindR/txrangeRStchoicetstringtlettersRURtstrtrandintR@R!R"RAtFalseR*RBRRCRDR&R'RF(Rt recv_sockt_[1]R3t id_uniquet send_dataR5t respondingRIRJRKRLRMRN((s//pentest/voiper/protocol_logic/sip_utilities.pyt is_responding*sF  <     !      (RRRRe(((s//pentest/voiper/protocol_logic/sip_utilities.pyRRs "t SIPRegistrarcBs#eZd„Zd„Zd„ZRS(c CsŠ||_||_tƒ|_tƒi|_didddddddd d g ƒ|_hdd 6dd 6dd 6dd6dd6|_dS(sŒ This class plays the part of a registrar and allows clients to register with the fuzzer. This is required for clients that don't support P2P SIP calls and are required to first register with a service provider. @type ip: String @param ip: The IP address to listen on @type port: Integer @param port: The port to listen on RsSIP/2.0 200 OK s;Via: SIP/2.0/UDP someserver.bleh.com:5060;branch=[BRANCH] s*To: user <sip:bleh@bleh.com>;tag=4343454 s.From: user <sip:bleh@bleh.com>;tag=[FROMTAG] sCall-ID: [CALL-ID] sCSeq: [CSEQ-NUM] REGISTER sContact: <sip:bleh@bleh.com> sExpires: [EXPIRES] sContent-Length: 0 s[BRANCH]s [FROMTAG]s[CALLID]s[CSEQ]s [EXPIRES]N( tipR"RR%RR&R/tregister_ok_msgtattribute_dict(RRgR"((s//pentest/voiper/protocol_logic/sip_utilities.pyRks$     cCs tttƒ}|i|i|ifƒxg|idƒ\}}|idƒdjo9|idt |ƒƒ|idƒ|i ||ƒPq+q+|i ƒdS(s• This function sits and waits for a connection on 5060 containing a REGISTER request and responds authorizing the connection itREGISTERiÿÿÿÿs#[+] Register request received from s[+] Sending 200 OK responseN( R=R>R?RXRgR"RCRER&R]t allowRegisterRF(RR5RMt incoming_addr((s//pentest/voiper/protocol_logic/sip_utilities.pytwaitForRegisterŽs  cCsR|ii||iƒ}tttƒ}tidƒ|i||ƒ|i ƒdS(s; This responds to a REGISTER request with a 200 OK response. @type host: Tuple @param host: A tuple containing the IP and port to respond to the request on @type register_request: String @param register_request: The original register request from the client iN( R%R RhR=R>R?R;R<tsendtoRF(RR!tregister_requestRPt reply_sock((s//pentest/voiper/protocol_logic/sip_utilities.pyRk¢s   (RRRRmRk(((s//pentest/voiper/protocol_logic/sip_utilities.pyRfjs # (((((t__doc__RBR+RR;R[RStosRR=tmisc.utilitiesRRRRRRf(((s//pentest/voiper/protocol_logic/sip_utilities.pyt<module>s        VŽc
15,038
Python
.py
191
72.989529
453
0.513411
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,977
sip_agent.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/sip_agent.pyc
—Ú ‚–øMc@sTdZddkZddkZddkZddkZddkZddkZddkZddkZddk l Z ddkl Z ddk l Z ddk l Z ddk lZlZddklZd Zd Zd Zd dd ÑÉYZdddÑÉYZdddÑÉYZdddÑÉYZdddÑÉYZdddÑÉYZdS(s¿ This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com iˇˇˇˇN(tQueue(tRandom(tSIPTransaction(tTData(tEXTERNALt GENERATOR(t SIPParseriiitSIPAgentcBsAeZdÑZddÑZdÑZdÑZdÑZdÑZRS(cCs.tiÉ|_t|_||_||_dS(s: This class is responsible for playing the part of a SIP agent in a transaction. The process_transaction method takes a dictionary describing the transaction and attempts to process it. The dictionary describes expected response codes and the functions to be called when these response codes are detected. @type response_q: Queue @param response_q: A queue which we will read data from the network off @type request_q: Queue @param request_q: A queue which we will write any responses too N(t sip_parserRtsptTruetprevious_got_responsetin_queuet out_queue(tselft response_qt request_q((s+/pentest/voiper/protocol_logic/sip_agent.pyt__init__+s   c Csd}d}|djo|idÉo|d}nd}x¥|djo¶|iÉ}|dtijo;|i|i|||É\}}| o"|o|iditi }n||jo®||} | d} | djoUt } x3|iÉD]%}||ddjo t } q˘q˘W| oq@q;t }Pn| ||i |É| d}|p t }q§qÔ|djotidIJt}qÔtidIJt}q@|ti} | d} | d|i |É}| d}|p t }q@q@W|iÉ||fS(sC @type t_dict: Dictionary @param t_dict: A dictionary describing the possible states this transaction may traverse and what actions to take upon entering them. See fuzzer/fuzzer_parents.py for examples @type extra_params: Dictionary @param extra_params: A dictionary containing any possible extra paramaters transaction initiating methods might need e.g sending an OPTIONS @r_type: Integer @return: An integer describing the result of attempting to process the given t_dict göôôôôôÈ?tbranchiisSA: T_INCOMPLETEsSA: T_INVALID_STATEN(tNonethas_keytkeysRtr_SENDtget_transactionR t t_data_listtp_datatBRANCHtFalseR t T_COMPLETE_OKR tsyststderrt T_INCOMPLETEtT_INVALID_STATEt flush_queue( Rtt_dictt extra_paramst wait_timetstatust curr_branchtpossible_r_codestsip_ttr_codet action_tupletmethodt any_actions((s+/pentest/voiper/protocol_logic/sip_agent.pytprocess_transaction=sT  !               cCs(yx|iitÉqWnnXdS(s¡ Method to ensure any messages remaining on the input queue that have not been consumed are removed @type queue: Queue @param queue: The queue to flush N(R tgetR(R((s+/pentest/voiper/protocol_logic/sip_agent.pyR!ïs c Csód}d }d}tidt|ÉIJtidt|ÉIJx-||jod }yÙ|itÉ}|it|iÉd} | it i }| p | it i i |ÉdjoÉtidIJy7|i |Étidt|Éd t|ÉIJPWqItj o,tid t|Éd t|ÉIJqIXn d }d }WnnXti|É||7}qCW|o t|_n t|_||fS( s⁄ Method that attempts to retrieve a message with the given r_code from the queue @type queue: Queue @param queue: The queue to read off @type r_codes: List @param r_codes: A list of response codes that are considered a valid match @type wait_time: Float @param wait_time: The time to wait for responses before returning. This will be approached in intervals of .1 of a second. göôôôôôπ?is wait time s SA-EXPECTING iiˇˇˇˇsSA-GOT-CORRECT-BRANCHsSA-GOT-CORRECT-R-CODE s # sSA-GOT-UNEXPECTED-R-CODE N(RRRtstrR.RRtlenRRtRCODERtfindtindext ValueErrorttimetsleepR R ( Rtqueuetr_codesR&R$t sleep_timetq_r_codet slept_forR(t last_recv((s+/pentest/voiper/protocol_logic/sip_agent.pyR§s< (  %.    cCs.|o|d9}n|p|d9}n|S(NgöôôôôôÈ?((Rt previous_fuzzR R$((s+/pentest/voiper/protocol_logic/sip_agent.pytcalculate_wait_time€s cCsdS(N((Rtxtytz((s+/pentest/voiper/protocol_logic/sip_agent.pytrequireÊsN( t__name__t __module__RRR-R!RR>RB(((s+/pentest/voiper/protocol_logic/sip_agent.pyR*s   X  7 t SIPCancelcBs&eZddÑZdÑZdÑZRS(cCs|i||É}dS(sp Process the next response for the given SIP transaction and put it on the output queue N(t send_cancelR(RR(toutput_qR#terr((s+/pentest/voiper/protocol_logic/sip_agent.pytprocessÌscCsw|it|iÉd}|iti}|tijo9|i|idÉ}|it|t |i dfÉndS(s - We receive a 1XX provisional response to the initial INVITE which means we can now send the CANCEL @type sip_transaction: SIPTransaction @param sip_transaction: An object representing the entire transaction so far iig¯?N( RR0RRR1tr_1XXt create_canceltputR Rtaddr(Rtsip_transactionRGR<R)tcancel_request((s+/pentest/voiper/protocol_logic/sip_agent.pyRFˆs cCsø|i}d|tidgd|tidgd|tigd|tigd|tigd|tigdgg}g}x$|D]}|id i |ÉÉqàWd i |Éd }|S( ss Method to generate a cancel request for a given INVITE. According to the RFC the following fields must match (including tags) - Request URI - Call-ID - To - Numeric part of the CSeq - From - Via (should contain only a single Via header matching the top Via header from the INVITE) The method part of the Cseq header must have a value of CANCEL @type t_data: TData @param t_data: A TData object representing the INVITE to be cancelled @rtype: String @return: The cancel request for the INVITE in t_data tCANCELsSIP/2.0sCSeq:sVia:sTo:sFrom:sCall-ID:sMax-Forwards: 70t s s ( RRtRURItCSEQNUMtVIAtTOtFROMtCALLIDtappendtjoin(Rtt_dataRtcancel_templateROtline((s+/pentest/voiper/protocol_logic/sip_agent.pyRKs  N(RCRDRRIRFRK(((s+/pentest/voiper/protocol_logic/sip_agent.pyREÎs tSIPAckcBs&eZddÑZdÑZdÑZRS(cCs|i||É}dS(sU @type input_tuple: Tuple @param sinput_tuple: See SIPCancel N(tsend_ackR(RR(RGR#RH((s+/pentest/voiper/protocol_logic/sip_agent.pyRI2scCsf|it|iÉd}|iti}|i||idÉ}|it|t|i dfÉdS(s  We receive a 487 response indicating the INVITE has been cancelled. This must be ACK'ed @type sip_transaction: SIPTransaction @param sip_transaction: An object representing the entire transaction so far iig¯?N( RR0RRR1t create_ackRLR RRM(RRNRGR<R)t ack_request((s+/pentest/voiper/protocol_logic/sip_agent.pyR^<s cCs¨|i}|i}y|ti}Wntj o d}nXy|ti}Wntj o d}nXy|ti}Wntj o d}nXy|ti}Wntj o d}nXy|ti} Wntj o d} nXy|ti} Wntj o d} nXd|dgd |dgd |gd |gd | gd | gdgg} g} x$| D]} | i di | ÉÉquWdi | Éd} | S(s Method to create an ACK for a request. According to the SIP RFC the following fields must match the request that created the transaction - Call ID - From - Request URI - Via (should contain only a single Via header matching the top Via header from the INVITE) - Numeric part of the CSeq The To header should match the To header from request that is being acknowledged. @type request_to_ack: TData @param request_to_ack: The request that the ACK is being generated for @type orig_request: TData @param orig_request: The request that started the transaction @rtype: String @return: The ACK for the given request suser@192.168.3.100t3sSSIP/2.0/UDP 192.168.3.102:5068;branch=z9hG4bKlm4zshdowki1t8c7ep6j0yavq2ug5r3x;rports<sip:nnp@192.168.3.101>sB"nnp" <sip:nnp@192.168.3.104>;tag=so08p5k39wuv1dczfnij7bet4l2m6hrqs'rzxd6tm98v0eal1cifg2py7sj3wk54ub@voipertACKsSIP/2.0sCSeq:sVia:sTo:sFrom:sCall-ID:sMax-Forwards: 70RQs s ( RRRRtKeyErrorRSRTRURVRWRXRY(Rtrequest_to_ackt orig_requesttp_data_req_ackt p_data_origtr_uritcseq_numtviattotp_fromtcall_idt ack_templateR`R\((s+/pentest/voiper/protocol_logic/sip_agent.pyR_LsN               N(RCRDRRIR^R_(((s+/pentest/voiper/protocol_logic/sip_agent.pyR]0s t SIPOptionscBs#eZdÑZdÑZdÑZRS(cCsr|d|_|d|_|d|_|d|_d|_|idÉo|d|_n|i|É|iS(sÒ @type params: Dictionary @param params: A dictionary containing the host and port to send the OPTIONS to @type out_queue: Queue @param out_queue: A queue onto which the OPTIONS will be put to be sent thosttporttusert target_userRN(RpRqRrRsRRRt send_options(RR(R R#((s+/pentest/voiper/protocol_logic/sip_agent.pyRIôs      cCs8|iÉ}|it|t|i|ifdfÉdS(Ng¯?(tcreate_optionsRLR RRpRq(RR toptions_request((s+/pentest/voiper/protocol_logic/sip_agent.pyRtÆs c CsÓdid|igÉ}ditÉititidÉÉ}did|id|idgÉ}did|id|idd|gÉ}t i t i ÉÉ}|i odi|d |i gÉ}n"di|d |gÉ}||_ did |gÉ}did|igÉ}did|id|dgÉ} d |d gd t tiddÉÉd gd|gd|gd|gd|gdgdgdgd| gg } g} x$| D]} | idi| ÉÉq∑Wdi| Éd} | S(Ntssip:i s<sip:t@t>s"VoIPER" <sip:s;tag=s;branch=z9hG4bKksoptions.tOPTIONSsSIP/2.0sCSeq:iËi†ÜsVia: SIP/2.0/UDPsTo:sFrom:sCall-ID:sMax-Forwards: 70s9Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGEsAccept: application/sdpsContact:RQs s (RYRpRtsampletstringtascii_lowercasetdigitsRsRrtsockett gethostbynamet gethostnameRR/trandomtrandintRX( Rtsip_uritr_datatto_linet from_linetlocal_iptvia_linet call_id_lineturit contact_linetoptions_templateRvR\((s+/pentest/voiper/protocol_logic/sip_agent.pyRu≤s8($*  !     (RCRDRIRtRu(((s+/pentest/voiper/protocol_logic/sip_agent.pyRoós  t SIPRegistercBs>eZdÑZdÑZdÑZdÑZdÑZdÑZRS(cCsï|d}|d}|d}|d}d|_|idÉo|d|_n|o|i||||ÉdS|i||||É|iSdS(NRpRqRrtpasswordR(RRRtsend_register_finaltsend_register_init(RR(RGR#RpRqtusernameRè((s+/pentest/voiper/protocol_logic/sip_agent.pyRIÿs     cCsE|i||É}tidIJ|it|t||fdfÉdS(Nssending register initg¯?(tcreate_register_initRRRLR R(RRpRqRíRGtregister_request((s+/pentest/voiper/protocol_logic/sip_agent.pyRëÈs cCsU|id}|id}|i||||É}|it|t|idfÉdS(Niˇˇˇˇig¯?(Rtcreate_register_finalRLR RRM(RR(RGRíRèR<torig_regRî((s+/pentest/voiper/protocol_logic/sip_agent.pyRêÓs  c Cs|di|||gÉ}did|gÉ}ti|ÉiÉ}ti|ÉiÉ} tidi||| gÉÉiÉS(sk See RFC 3261 section 22 and RFC 2069 section 2.1.2 for details. @type username: String @param username: The username to register on the registrar @type password: String @param password: The password that goes with the given username @type realm: String @param realm: The 'realm' value which will be returned by the server in response to the initial REGISTER request as part of the WWW-Authenticate header @type uri: String @param uri: The SIP/SIPS uri from the original request line. Will be of the form 'sip:192.168.3.101', without the quotes. @type nonce: String @param nonce: The 'nonce' value which will be returned by the server in response to the initial REGISTER request as part of the WWW-Authenticate header t:tREGISTER(RYtmd5tnewt hexdigest( RRíRètrealmRãtnoncetA1tA2tmd5_A1tmd5_A2((s+/pentest/voiper/protocol_logic/sip_agent.pytcalculate_md5_responseıs c Csv|i}|i}tt|tiÉdÉ}|ti}|ti} |i||| |ti|É} di d|d| d|d|tid| dg É} d |tid gd |d gd |ti gd |ti gd|ti gd|ti gd| gdgd|tigdgdgg } g} x$| D]}| idi |ÉÉq?Wdi | Éd} | S(NiRwsDigest username="s ", realm="s ", nonce="s", uri="s", algorithm=md5, response="t"RòsSIP/2.0sCSeq:sVia:sTo:sFrom:sCall-ID:sAuthorization:s9Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGEsContact:s Expires: 3600sMax-Forwards: 70RQs s (RR/tintRRStWWW_AUTHEN_NONCEtWWW_AUTHEN_REALMR¢RRRYRTRURVRWtCONTACTRX(Rtinit_reg_requestt auth_responseRíRèt p_data_initt p_data_authRiRùRút md5_responset auth_stringtregister_templateRîR\((s+/pentest/voiper/protocol_logic/sip_agent.pyRïs:    "     c Cs∏ditÉititidÉÉ}did|d|dgÉ}di|d|gÉ}titiÉÉ}|i odi|d|i gÉ}n"||_ di|d|gÉ}did|gÉ}did |gÉ} did|d|dgÉ} d | d gd |gd |gd|gdt t i ddÉÉd gd|gdgdgd| gdgg } g} x$| D]} | i di| ÉÉqÅWdi| Éd} | S(NRwi s<sip:RxRys;tag=s;branch=z9hG4bKks register.ssip:RòsSIP/2.0sTo:sFrom:sCall-ID:sCSeq:iËi†ÜsVia: SIP/2.0/UDPsMax-Forwards: 70s9Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGEsContact:s Expires: 3600RQs s (RYRR{R|R}R~RRÄRÅRR/RÇRÉRX(Rt target_ipRrRÖRÜRáRàRâRäRãRåRÆRîR\((s+/pentest/voiper/protocol_logic/sip_agent.pyRì6s6(         (RCRDRIRëRêR¢RïRì(((s+/pentest/voiper/protocol_logic/sip_agent.pyRé÷s      $t SIPInvitecBs#eZdÑZdÑZdÑZRS(cCsï|d|_|d|_|d|_|idÉo|d|_n d|_d|_|idÉo|d|_n||_|iÉ|iS(NRpRqRrRsR( RpRqRrRRsRRRGt send_invite(RR(RGR#((s+/pentest/voiper/protocol_logic/sip_agent.pyRI[s       cCs;|iÉ}|iit|t|i|ifdfÉdS(Ng@(t create_inviteRGRLR RRpRq(Rtinvite_request((s+/pentest/voiper/protocol_logic/sip_agent.pyR±ns cCsØ|ioIdid|id|igÉ}did|id|idgÉ}n4did|igÉ}did|idgÉ}ditÉititidÉÉ}ti ti ÉÉ}did|i d|d|gÉ}|i o"did |d |i gÉ}n%||_ did |d |gÉ}di|gÉ}did|i d|dgÉ}d id |gÉ} d id | gÉ} did| d| dddddddddddgÉ} d|dgdt tidd ÉÉdgd!|gd"|gd#|gd$|gd%gd&gd'gd(|gd)t t| ÉÉgdgg } g} x$| D]}| id i|ÉÉqgWdi| É} di| | gÉ} | S(*sp According to the RFC the following headers SHOULD be present: - Allow - Supported Headers that MAY be present are not included by VoIPER. The following MUST be included: - From - Via - To - Call-ID - CSeq Content-type and Content-length are required for the SDP header Rwssip:Rxs<sip:Ryi s"VoIPER" <sip:s>;tag=s SIP/2.0/UDP s;branch=z9hG4bKkRQsc=IN IP4so=- 1212861461 1212861461s sv=0ss=VoIPER SIP Sessionst=0 0s.m=audio 5000 RTP/AVP 112 113 3 105 108 0 8 101sa=rtpmap:112 SPEEX/16000sa=rtpmap:113 iLBC/8000sa=rtpmap:3 GSM/8000sa=rtpmap:105 MS-GSM/8000sa=rtpmap:108 SPEEX/8000sa=rtpmap:0 PCMU/8000sa=rtpmap:8 PCMA/8000s!a=rtpmap:101 telephone-event/8000sa=fmtp:101 0-15tINVITEsSIP/2.0sCSeq:iËi†ÜsVia:sTo:sFrom:sCall-ID:sMax-Forwards: 70sContent-Type: application/sdps9Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGEsContact:sContent-Length:(RsRYRpRR{R|R}R~RRÄRÅRrRR/RÇRÉR0RX(RRÑRÜRÖRàRáRâRäRåtc_lineto_linet sdp_headertinvite_templateR≥R\((s+/pentest/voiper/protocol_logic/sip_agent.pyR≤rsd !(($ " !         (RCRDRIR±R≤(((s+/pentest/voiper/protocol_logic/sip_agent.pyR∞Ys  (((((((t__doc__R5t threadingRRÇR|RthashlibRRRtsip_transaction_managerRRRRRRR RRRER]RoRéR∞(((s+/pentest/voiper/protocol_logic/sip_agent.pyt<module>s.        ¡Eg?É
22,328
Python
.py
249
84.329317
740
0.466289
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,978
test_sip_parser.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/test_sip_parser.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' from sip_parser import * data1 = '\r\n'.join(['INVITE sip:nnp@192.168.3.104 SIP/2.0', 'Date: Sun, 23 Sep 2007 00:23:19 GMT', 'CSeq: 13456 INVITE', 'Via: SIP/2.0/UDP 192.168.3.102:5071;branch=z9hG4bKa8f5f4da-d867-dc11-8c7d-000c29da463b;rport', 'User-Agent: Ekiga/2.0.3', 'From: "nnp nnp" <sip:nnp@192.168.3.102>;tag=a68cf4d7-d867-dc11-8c7d-000c29da463b', 'Call-ID: MOFOID@ubuntu', 'To: <sip:nnp@192.168.3.104>', 'Contact: <sip:nnp@192.168.3.102:5062>', 'WWW-Authenticate: Digest algorithm=MD5, realm="192.168.3.101", nonce="6eec05-jhg6jhg"', 'Allow: INVITE', 'Content-Type: application/sdp', 'Content-Length: 389', 'Max-Forwards: 70']) + '\r\n\r\n' data1 = data1 + '\r\n'.join(['v=0', 'o=- 1190506999 1190506999 IN IP4 192.168.3.102', 's=Opal SIP Session', 'c=IN IP4 192.168.3.102', 't=0 0', 'm=audio 5040 RTP/AVP 101 96 3 107 110 0 8', 'a=rtpmap:101 telephone-event/8000', 'a=fmtp:101 0-15', 'a=rtpmap:96 SPEEX/-1', 'a=rtpmap:3 GSM/8000', 'a=rtpmap:107 MS-GSM/8000', 'a=rtpmap:110 SPEEX/-1', 'a=rtpmap:0 PCMU/8000', 'a=rtpmap:8 PCMA/8000', 'm=video 5042 RTP/AVP 31', 'a=rtpmap:31 H261/-1']) + '\r\n' data2 = """SIP/2.0 200 OK sip:nnp@192.168.3.104 SIP/2.0 Date: Sun, 23 Sep 2007 00:23:19 GMT CSeq: 1 INVITE Via: SIP/2.0/UDP 192.168.3.102:5071;branch=z9hG4bKa8f5f4da-d867-dc11-8c7d-000c29da463b;rport User-Agent: Ekiga/2.0.3 From: "nnp nnp" <sip:nnp@192.168.3.102>;tag=a68cf4d7-d867-dc11-8c7d-000c29da463b Call-ID: MOFOID@ubuntu To: <sip:nnp@192.168.3.104> Contact: <sip:nnp@192.168.3.102> Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE Content-Type: application/sdp Content-Length: 389 Max-Forwards: 70 """ data3 = """ACK sip:nnp@192.168.3.104 SIP/2.0 Date: Sun, 23 Sep 2007 00:23:19 GMT CSeq: 1 ACK Via: SIP/2.0/UDP 192.168.3.102:5071;branch=z9hG4bKa8f5f4da-d867-dc11-8c7d-000c29da463b;rport User-Agent: Ekiga/2.0.3 From: "nnp nnp" <sip:nnp@192.168.3.102>;tag=a68cf4d7-d867-dc11-8c7d-000c29da463b Call-ID: MOFOID@ubuntu To: <sip:nnp@192.168.3.104> Contact: <sip:nnp@192.168.3.102:5071;transport=udp> Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE Content-Type: application/sdp Content-Length: 389 Max-Forwards: 70 """ data4 = '\r\n'.join(['REGISTER sip:nnp@192.168.3.104 SIP/2.0', 'Date: Sun, 23 Sep 2007 00:23:19 GMT', 'CSeq: 1 REGISTER', 'Via: SIP/2.0/UDP 192.168.3.102:5071;branch=z9hG4bKa8f5f4da-d867-dc11-8c7d-000c29da463b;rport', 'User-Agent: Ekiga/2.0.3', 'From: "nnp nnp" <sip:nnp@192.168.3.102>;tag=a68cf4d7-d867-dc11-8c7d-000c29da463b', 'Call-ID: MOFOID@ubuntu', 'To: <sip:nnp@192.168.3.104>', 'Contact: <sip:nnp@192.168.3.102:5071;transport=udp>', 'WWW-Authenticate: Digest algorithm=MD5, realm="asterisk", nonce="6eec05"' 'Allow: INVITE', 'Content-Type: application/sdp', 'Max-Forwards: 70']) + '\r\n\r\n' parser = SIPParser() res = parser.parse(data1, [CONTACT]) assert(res == {CONTACT : '<sip:nnp@192.168.3.102:5062>'}) res = parser.parse(data2, [CONTACT]) assert(res == {CONTACT : '<sip:nnp@192.168.3.102>'}) res = parser.parse(data3, [CONTACT]) assert(res == {CONTACT : '<sip:nnp@192.168.3.102:5071;transport=udp>'}) res = parser.parse(data4, [WWW_AUTHEN_REALM]) assert(res == {WWW_AUTHEN_REALM : 'asterisk'}) res = parser.parse(data1, [WWW_AUTHEN_REALM]) assert(res == {WWW_AUTHEN_REALM : '192.168.3.101'}) res = parser.parse(data4, [WWW_AUTHEN_NONCE]) assert(res == {WWW_AUTHEN_NONCE : '6eec05'}) res = parser.parse(data1, [WWW_AUTHEN_NONCE]) assert(res == {WWW_AUTHEN_NONCE : '6eec05-jhg6jhg'}) res = parser.parse(data1, [BRANCH]) assert(res == {BRANCH : 'z9hG4bKa8f5f4da-d867-dc11-8c7d-000c29da463b'}) res = parser.parse(data1, [FROM]) assert(res == {FROM : '"nnp nnp" <sip:nnp@192.168.3.102>;tag=a68cf4d7-d867-dc11-8c7d-000c29da463b'}) res = parser.parse(data1, [TO]) assert(res == {TO : '<sip:nnp@192.168.3.104>'}) res = parser.parse(data1, [FROMTAG]) assert(res == {FROMTAG : 'a68cf4d7-d867-dc11-8c7d-000c29da463b'}) res = parser.parse(data1, [CALLID]) assert(res == {CALLID : 'MOFOID@ubuntu'}) res = parser.parse(data1, [CSEQNUM]) assert(res == {CSEQNUM : '13456'}) res = parser.parse(data2, [RCODE]) assert(res == {RCODE : r_2XX}) res = parser.parse(data4, [RCODE]) assert(res == {RCODE : r_REGISTER}) res = parser.parse(data3, [RCODE]) assert(res == {RCODE : r_ACK}) res = parser.parse(data1, [RURI]) assert(res == {RURI : 'sip:nnp@192.168.3.104'}) res = parser.parse(data1, [VIA]) assert(res == {VIA : 'SIP/2.0/UDP 192.168.3.102:5071;branch=z9hG4bKa8f5f4da-d867-dc11-8c7d-000c29da463b;rport'})
5,244
Python
.py
124
40.540323
112
0.717893
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,979
__init__.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/__init__.pyc
—Ú ‚–øMc@sdZdddddgZdS(s¿ This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com tsip_transaction_managert transceivert sip_agentt sip_parsert sip_utilitiesN(t__doc__t__all__(((s*/pentest/voiper/protocol_logic/__init__.pyt<module>s 
984
Python
.py
17
56.647059
149
0.715768
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,980
test_sip_cancel.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/test_sip_cancel.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' from sip_agent import SIPCancel from sip_agent import SIPAck from sip_transaction_manager import SIPTransactionManager from sip_transaction_manager import GENERATOR from Queue import Queue invite1 = '\r\n'.join(['INVITE sip:tester@192.168.3.102 SIP/2.0', 'Date: Sun, 23 Sep 2007 00:23:19 GMT', 'CSeq: 1 INVITE', 'Via: SIP/2.0/UDP 192.168.3.102:5071;branch=z9hG4bKa8f5f4da-d867-dc11-8c7d-000c29da463b;rport', 'User-Agent: Ekiga/2.0.3', 'From: "nnp nnp" <sip:nnp@192.168.3.102>;tag=a68cf4d7-d867-dc11-8c7d-000c29da463b', 'Call-ID: MOFOID@ubuntu', 'To: <sip:tester@192.168.3.102>', 'Contact: <sip:nnp@192.168.3.102:5071;transport=udp>', 'Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE', 'Content-Type: application/sdp', 'Content-Length: 389', 'Max-Forwards: 70']) + '\r\n\r\n' invite1 = invite1 + '\r\n'.join(['v=0', 'o=- 1190506999 1190506999 IN IP4 192.168.3.102', 's=Opal SIP Session', 'c=IN IP4 192.168.3.102', 't=0 0', 'm=audio 5040 RTP/AVP 101 96 3 107 110 0 8', 'a=rtpmap:101 telephone-event/8000', 'a=fmtp:101 0-15', 'a=rtpmap:96 SPEEX/-1', 'a=rtpmap:3 GSM/8000', 'a=rtpmap:107 MS-GSM/8000', 'a=rtpmap:110 SPEEX/-1', 'a=rtpmap:0 PCMU/8000', 'a=rtpmap:8 PCMA/8000', 'm=video 5042 RTP/AVP 31', 'a=rtpmap:31 H261/-1']) + '\r\n' sip_t_list = [] trans_in_queue = Queue(0) global_out_queue = Queue(0) SIPTransactionManager(trans_in_queue, global_out_queue).start() trans_in_queue.put((True, invite1, GENERATOR, ('192.168.3.102', 64064), 5.0)) print 'invite put on q' # request queue, response queue, error_message print 'entering cancel-ack' ret = ack.process(cancel.process((global_out_queue, trans_in_queue, None))) print 'getting' print ret[1].get() if ret[2]: print ret[2] else: print 'end good'
2,502
Python
.py
64
36.765625
95
0.747565
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,981
transceiver.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/transceiver.pyc
—Ú ‚–øMc @skdZddkZddkZddkZddklZddklZddkTdddÑÉYZdS( s¿ This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com iˇˇˇˇN(tselect(tQueue(t*tUDPTransceivercBsSeZdÑZdÑZedÑZdÑZdÑZdÑZdÑZ dÑZ RS(cCs:||_||_g|_g|_g|_t|_dS(s” @type port_list: List of Integers @param port_list: A list of ports to listen on @type lock: Lock @param lock: A lock object to be used when performing socket operations N(t port_listtlockt socket_listt to_close_listt notify_q_listtFalset listening(tselfRR((s-/pentest/voiper/protocol_logic/transceiver.pyt__init__s      cCsÑtttÉ}yStidIJt|Édjo|d }n|i||É|i|É|SWntj o}|GHdSXdS(sŸ Sends the provided data to the target host and port and adds the socket used to the listen queue so we can receive any responses. @type data: String @param data: The data to send @type addr: Tuple @param addr: The (host, port) tuple to send the data to @rtype: Socket @return: Returns the socket that was used to send the data. This should be closed when the transaction has timed out. stransceiver sendingi$N( tsockettAF_INETt SOCK_DGRAMtsyststderrtlentsendtot add_sockett ExceptiontNone(R tdatataddrtste((s-/pentest/voiper/protocol_logic/transceiver.pytsend0s  cCsä||_|ovxV|iD]K}tttÉ}|ittdÉ|id|fÉ|i i |ÉqWt i d|i ÉiÉndS(sÎ Start/Stop listening on sockets @type listening: Boolean @param listening: Whether to have sockets in a listening state or not. All required callbacks must be registered before calling this is0.0.0.0ttargetN(R RR RRt setsockoptt SOL_SOCKETt SO_REUSEADDRtbindRtappendt threadingtThreadt_UDPTransceiver__listentstart(R R tportt recv_sock((s-/pentest/voiper/protocol_logic/transceiver.pytlistenKs  c Cs˚xÙ|ioÈt|iÉdjo”t|iggdÉ\}}}xt|D]l}y|idÉ\}}Wntj o qKnXx1|iD]&}|dit|d|dfÉqçWqKWx+|i D] }|ii |É|i Éq≈Wg|_ qWdS( s• This method should not be called by anything other than the listen method of this class. It continues to run until listen(False) is called. ig{ÆG·zÑ?iiig¯?Ni( R RRRRtrecvfromterrortputtTrueRtremovetclose(R tr_readtr_writetbrokentsockRRtfunction_tuple((s-/pentest/voiper/protocol_logic/transceiver.pyt__listen\s" ! ( cCs|ii|ÉdS(sÔ Add a socket to the list of sockets being monitored. This socket should be removed from the list via remove_socket and closed at some stage. @type s: Socket @param s: The socket to add to the list N(RR!(R R((s-/pentest/voiper/protocol_logic/transceiver.pyRss cCs|ii|ÉdS(sã Close a socket from the socket list @type s: Socket @param s: The socket to remove from the list N(RR!(R R((s-/pentest/voiper/protocol_logic/transceiver.pyt close_socket~scCs|ii||fÉdS(s‰ Add a queue to the list of functions to be called when data is received on the given port. A tuple will be placed on the queue. The first element being the data received and the second being the address it was received from in the form ('ipaddress', port). @type queue: Queue @param queue: The queue to add to the list @type port: Integer @param port: The port the provided function is a callback for N(RR!(R tqueueR&((s-/pentest/voiper/protocol_logic/transceiver.pytadd_notify_queueàs cCs|ii||fÉdS(sfl Remove a queue from the notify queue list @type queue: Queue @param The queue to remove from the list @type port: Integer @param port: The port the queue is associated with N(RR-(R R6R&((s-/pentest/voiper/protocol_logic/transceiver.pytremove_notify_queueós ( t__name__t __module__R RR,R(R$RR5R7R8(((s-/pentest/voiper/protocol_logic/transceiver.pyRs     ((t__doc__R"ttimeRRRR R(((s-/pentest/voiper/protocol_logic/transceiver.pyt<module>s    
6,129
Python
.py
84
67.02381
359
0.531894
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,982
transceiver.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/transceiver.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import threading import time import sys from select import select from Queue import Queue from socket import * class UDPTransceiver: def __init__(self, port_list, lock): ''' @type port_list: List of Integers @param port_list: A list of ports to listen on @type lock: Lock @param lock: A lock object to be used when performing socket operations ''' self.port_list = port_list self.lock = lock self.socket_list = [] self.to_close_list = [] # these are tuples of queues connected to other classes that # will be notified when data arrives and the ports this queue # is interested in self.notify_q_list = [] self.listening = False def send(self, data, addr): ''' Sends the provided data to the target host and port and adds the socket used to the listen queue so we can receive any responses. @type data: String @param data: The data to send @type addr: Tuple @param addr: The (host, port) tuple to send the data to @rtype: Socket @return: Returns the socket that was used to send the data. This should be closed when the transaction has timed out. ''' s = socket(AF_INET, SOCK_DGRAM) try: print >>sys.stderr, 'transceiver sending' if len(data) > 9216: data = data[:9216] s.sendto(data, addr) self.add_socket(s) return s except Exception, e: print e return None def listen(self, listening=True): ''' Start/Stop listening on sockets @type listening: Boolean @param listening: Whether to have sockets in a listening state or not. All required callbacks must be registered before calling this ''' self.listening = listening if listening: for port in self.port_list: recv_sock = socket(AF_INET, SOCK_DGRAM) recv_sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) recv_sock.bind(('0.0.0.0', port)) self.socket_list.append(recv_sock) threading.Thread(target=self.__listen).start() def __listen(self): ''' This method should not be called by anything other than the listen method of this class. It continues to run until listen(False) is called. ''' while self.listening and len(self.notify_q_list) != 0: r_read, r_write, broken = select(self.socket_list, [], [], .01) for sock in r_read: try: data, addr = sock.recvfrom(2**16) except error: continue for function_tuple in self.notify_q_list: function_tuple[0].put((True, data, 1, addr, 1.5)) for sock in self.to_close_list: self.socket_list.remove(sock) sock.close() self.to_close_list = [] def add_socket(self, s): ''' Add a socket to the list of sockets being monitored. This socket should be removed from the list via remove_socket and closed at some stage. @type s: Socket @param s: The socket to add to the list ''' self.socket_list.append(s) def close_socket(self, s): ''' Close a socket from the socket list @type s: Socket @param s: The socket to remove from the list ''' self.to_close_list.append(s) def add_notify_queue(self, queue, port): ''' Add a queue to the list of functions to be called when data is received on the given port. A tuple will be placed on the queue. The first element being the data received and the second being the address it was received from in the form ('ipaddress', port). @type queue: Queue @param queue: The queue to add to the list @type port: Integer @param port: The port the provided function is a callback for ''' self.notify_q_list.append((queue, port)) def remove_notify_queue(self, queue, port): ''' Remove a queue from the notify queue list @type queue: Queue @param The queue to remove from the list @type port: Integer @param port: The port the queue is associated with ''' self.notify_q_list.remove((queue, port))
5,347
Python
.py
130
31.361538
83
0.618581
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,983
sip_parser.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/sip_parser.pyc
Ñò âпMc@sÑdZddkZdZdZdZdZdZdZd Zd Z d Z d Z d Z dZ dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdd!d „ƒYZdS("sÀ This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com iÿÿÿÿNiiiiiiiii i i i i icibiai`i_i^iYiXiWiViUiEiDi;i:t SIPParsercBs/eZd„Zdd„Zd„Zd„ZRS(cCsºh dt6dt6dt6dt6dt6dt6dt6dt6d t6d t 6d t 6d t 6|_ h|_ xM|i iƒD]<}|i |}ti|titiBƒ}||i |<qvWd S(s} A class to implement all the functionality required to parse the relevant fields from a SIP message s*^Via.*?branch\s*?=\s*?(?P<target>[\d\w-]+)s!^From.*?;tag=(?P<target>[\w\d-]+)s^Call-ID\s*?:\s*(?P<target>\S+)s^CSeq\s*?:\s*(?P<target>\d+)s^To\s*?:\s*(?P<target>.+)\r\ns^From\s*?:\s*(?P<target>.+)\r\ns>^(?P<target>INVITE|CANCEL|OPTIONS|REGISTER|SIP/2\.0 \d{3}|ACK)s<(INVITE|CANCEL|OPTIONS|REGISTER)\s+(?P<target>.+?)\s+SIP/2.0s^Via\s*?:\s*(?P<target>.+)\r\ns?^WWW-Authenticate\s*?:\s*Digest.+nonce="(?P<target>[\w\d\.-]+)"s?^WWW-Authenticate\s*?:\s*Digest.+realm="(?P<target>[\w\d\.@]+)"sT^Contact\s*?:\s*?(?P<target><sip:[\w\d]+@[\w\d\.]+(:[\d]+)?(;transport=(udp|tcp))?>)N(tBRANCHtFROMTAGtCALLIDtCSEQNUMtTOtFROMtRCODEtRURItVIAtWWW_AUTHEN_NONCEtWWW_AUTHEN_REALMtCONTACTt regex_dicttregex_ctkeystretcompilet IGNORECASEt MULTILINE(tselftr_nametr_valtr((s,/pentest/voiper/protocol_logic/sip_parser.pyt__init__9s$    cCs‘|djo|iiƒ}nh}x[|D]S}|i|i|ƒ}|o0t|iƒƒdjo|idƒ||<q-q-W|i|ƒS(sâ Parses the provided data and extracts the relevant fields and their values into a dictionary @type data: String @param data: The SIP message to be parsed @type field: List @param field: A list of the fields to parse identified by the constants defined in the __init__ of this class. If None all fields are parsed @rtype: Dictionary @return: A dictionary of fields to and their associated values ittargetN(tNoneRRtsearchtlentgroupstgrouptnormalise_rcodes(Rtdatatfieldstres_dictRtval((s,/pentest/voiper/protocol_logic/sip_parser.pytparseTs  cCsÆ|itƒo²|t}|iƒdjo t}n~|iƒdjo t}na|iƒdjo t}nD|iƒdjo t}n'|iƒdjo t}n |idƒdjoí|i dƒ}|d }|d d jo t }q´|d d jo t }q´|d d jo t }q´|d djo t }q´|d djo t}q´|d djo t}q´|djo t}q´|djo t}q´nt}||t<n|S(s© Method to change textual response codes to one of the constants defined in the __init__ method @type data_dict: Dictionary @param data_dict: A dictionary of message fields to their values parsed from a SIP message @rtype: Dictionary @return: A dictionary where the response code strings have been converted to constants defined in this class tACKtINVITEtREGISTERtOPTIONStCANCELsSIP/2.0iÿÿÿÿt iit1t2t3t4t5t6t401t180(thas_keyRtuppertr_ACKtr_INVITEt r_REGISTERt r_OPTIONStr_CANCELtfindtsplittr_1XXtr_2XXtr_3XXtr_4XXtr_5XXtr_6XXtr_401tr_180t r_UNKNOWN(Rt data_dicttr_codeR ((s,/pentest/voiper/protocol_logic/sip_parser.pyRnsD                cCsphdd6dd6dd6dd6d d 6d d 6d d6dd6dd6dd6dd6dd6dd6dd6}||S(s÷ Convert the int representation of a rcode to its textual value @type r_code: Integer @param r_code: The rcode to convert @rtype: String @return: The textual value corresponding to the given rcode R<icR=ibR>iaR?i`R@i_RAi^R5iYR6iXR7iWR8iVR9iURDiDRBi;RCi:((RRFtr_dict((s,/pentest/voiper/protocol_logic/sip_parser.pytdenormalise_rcode£s  N(t__name__t __module__RRR$RRH(((s,/pentest/voiper/protocol_logic/sip_parser.pyR8s   5((t__doc__RRRRRtTOTAGRRRRR R R R R<R=R>R?R@RAR5R6R7R8R9RDtr_SENDRBRCR(((s,/pentest/voiper/protocol_logic/sip_parser.pyt<module>s< 
6,048
Python
.py
93
61.376344
774
0.497814
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,984
test_sip_invite.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/test_sip_invite.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import sys from Queue import Queue import sip_parser from sip_transaction_manager import SIPTransactionManager from sip_agent import SIPCancel from sip_agent import SIPAck from sip_agent import SIPAgent from sip_agent import SIPRegister from sip_agent import SIPInvite response_q = Queue(0) request_q = Queue(0) sip_agent = SIPAgent() ack = SIPAck() cancel = SIPCancel() register = SIPRegister() invite = SIPInvite() SIPTransactionManager(request_q, response_q).start() invite_dict = {sip_parser.r_SEND : (invite.process, { sip_parser.r_1XX : (cancel.process, { sip_parser.r_1XX : (None, None), sip_parser.r_2XX : (None, None), sip_parser.r_6XX : (ack.process, None), sip_parser.r_4XX : (ack.process, None) } ) } ) } result = sip_agent.process_transaction( invite_dict, response_q, request_q, {'user' : sys.argv[1], 'host' : sys.argv[2], 'port' : int(sys.argv[3])} )
1,961
Python
.py
55
27.618182
86
0.629434
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,985
test_sip_options.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/test_sip_options.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import sys from Queue import Queue import sip_parser from sip_transaction_manager import SIPTransactionManager from sip_agent import SIPOptions from sip_agent import SIPAgent response_q = Queue(0) request_q = Queue(0) sip_agent = SIPAgent() options = SIPOptions() SIPTransactionManager(request_q, response_q).start() options_dict = {sip_parser.r_SEND : (options.process, { sip_parser.r_1XX : (None, None), sip_parser.r_2XX : (None, None), sip_parser.r_3XX : (None, None), sip_parser.r_4XX : (None, None), sip_parser.r_5XX : (None, None), sip_parser.r_6XX : (None, None), } ) } result = sip_agent.process_transaction( options_dict, response_q, request_q, { 'host' : sys.argv[1], 'port' : int(sys.argv[2]), 'user' : sys.argv[3], 'target_user' : sys.argv[4]} )
2,036
Python
.py
48
29.520833
133
0.565375
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,986
sip_transaction_manager.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/sip_transaction_manager.pyc
Ñò âпMc @s×dZddkZddkZddkZddkZddkZddklZddklZddk l Z ddk l Z dZ dZ d Zd dd „ƒYZd dd „ƒYZdeifd„ƒYZdS(sÀ This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com iÿÿÿÿN(tUDPTransceiver(t SIPParser(tQueue(tdeepcopyiiitTDatacBseZddd„ZRS(cCs1||_||_||_||_||_dS(s^ A data class to represent the data of a message in a transaction along with who sent it @type data: String @param data: The data of a message in a transaction @type p_data: Dictionary @param p_data: A dictionary returned by the message parser with mappings of fields to their values parsed from the data @type source: Integer @param source: Indicates where this t_data originated in our system and as a result, what do do with it. If '0' the t_data came from one of the protocol generators and the data will be sent to the address stored in t_data.addr and added to/create an appropriate SIPTransaction. If '1' the t_data arrived from the network and will be added to the appropriate transaction. All queues will also be notified of its arrival. If '2' the data originated from some external source e.g the fuzzer. It is assumed to already have been sent. If it has a t_data.socket this will be added to the sockets the transceiver is monitoring. It will be added to/create a SIPTransaction @type addr: Tuple @param addr: The (IP, port) tuple the data was sent to or received from @type socket: Socket @param socket: The socket that was used to send the data. Only necessary if this data structure was created outside the transaction manager and the data already sent. Without this we wouldn't be able to see any responses to this port N(tdatatp_datatsourcetaddrtsocket(tselfRRRRR ((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pyt__init__%s     N(t__name__t __module__tNoneR (((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pyR$stSIPTransactioncBseZdd„Zd„ZRS(cCs1||_||_||_||_g|_dS(sm Data class to represent a SIP transaction and required data regarding it @type branch: String @param branch: The branch value from the SIP transaction. Used to uniquely identify transactions @type t_data_list: List @param t_data_list: A list of TData objects representing the data of the message and who sent it @type timestamp: Integer @param timestamp: The timestamp for when this transaction was last updated @type timeout: Integer @param timeout: The timeout from the timestamp after which the transaction will be disgarded @type addr: Tuple @param addr: The (IP, port) tuple from the last message in the t_data list to be received. If None it is assumed the last message was sent out by VoIPER N(tbrancht t_data_listt timestampttimeouttsockets(R RRRRR((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pyR Ks     cCsnyD|iti}x-|iD]"}|iti|jotSqWWntj onX|ii|ƒtS(s² This method should be used to add a new t_data object to the t_data_list. It prevents retransmissions being added to the transaction record @type t_data: TData @param t_data: A TData object representing the request @rtype: Boolean @return: Returns True if the t_data is added and returns false otherwise i.e. the t_data was a retransmission of a previous request (Rt sip_parsertRCODERtFalsetKeyErrortappendtTrue(R tt_datat t_data_r_codet prev_data((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pyt add_responseis   N(R R RR R(((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pyRJs tSIPTransactionManagercBsGeZdd„Zd„Zdd„Zdd„Zd„Zd„ZRS(iÄcCs—||_||_||_tiƒ|_t|ig|iƒ|_|ii|i|iƒ|ii t ƒh|_ t ƒ|_ tii|ƒdS(sÀ @type add_trans_queue: Queue @param add_trans_queue: A queue that this class will listen on for tuples of the form identical to the parameters to the add_transaction method of this class except with an extra parameter at the start that can be False to indicate to this class to shutdown or True otherwise. The data this queue receives will be added to the transaction list this class is monitoring @type global_update_queue: Queue @param global_update_queue: A queue that will receive a SIPTransaction object every time an update from the network arrives for that SIPTransaction N(tadd_trans_queuetglobal_update_queuet listen_porttthreadt allocate_locktlockRt transceivertadd_notify_queuetlistenRttransaction_dictRRt threadingtThreadR (R R R!R"((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pyR „s     c Csñxêtoâd}y|iiƒ}WnnX|djo®|dtjotdIJt|IJdS|d}|d}|d}|d}d}|tjo|d}n|tjotidIJn|i |||||ƒqqWdS( Nis)tm returning cause tuple thingy was falseiiiiis&got something from generator off queue( RRR tgetRtstderrtEXTERNALt GENERATORtsystadd_data_to_transactions(R tnew_trans_tupleRRRRR ((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pytrun¢s.         cCsX|ii|ƒ}|itiƒo/t|||||ƒ}|i|d|ƒndS(NR(Rtparsethas_keytBRANCHRtadd_transaction(R RRRRR t data_dictR((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pyR1Ásc Csætiƒ}|i}t}|ii|tiƒo;|i|ti}|i|ƒ}|o ||_qn™y|ti }Wnt j o d}nX|i t jp |ti joG|tijo7t|ti|g||ƒ}||i|ti<ndS|i tjoGtidIJ|ii|i|iƒ}|o|ii|ƒqØnz|i t jo!|o|iit|ƒƒnI|i tjo8|io*|ii|iƒ|ii|iƒqØn|iƒdS(sà Function to add a SIP transaction to the list of the transactions this manager is taking care of. If a transaction with this branch already exists then this data and queue are appended to their lists and all other fields in the old sip_transaction are updated to the new values. If not a new SIPTransaction object is created with the provided details and added to the list. @type t_data: TData @param data: A TData object representing the data, its parsed fields and its origin @type timeout: Integer @param timeout: A timeout after which this transaction will no longer be monitored iÿÿÿÿNsSource is generator. Sending( ttimeRRR)R5RR6RRRRRtNETWORKtr_INVITEtr_CANCELRR/R0R-R&tsendRRRRR!tputRR.R t add_sockett&_SIPTransactionManager__check_timeouts( R RRRR8t t_data_addedtsip_ttr_codet send_sock((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pyR7Ès<       cCsštiƒ}tidt|iƒIJxm|iiƒD]\}|i|}||i|ijo2x!|iD]}|i i |ƒqjW|i|=q6q6WdS(sh Checks to see if any of the transactions have timed out and Removes them if so s#TM: %d transactions being monitoredN( R9R0R-tlenR)tkeysRRRR&t close_socket(R t curr_timeRt transactiontsock((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pyt__check_timeoutss   cCs |ii|i|ifƒdS(s„ Function to remove this transaction managers queue from the list of queues registered with the transceiver N(R&tremove_notify_queuetincoming_data_queueR"(R ((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pytunregister_from_transceiver sN( R R R R3RR1R7R@RN(((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pyRƒs     I (((t__doc__R9R*R#RR0R&RRRtcopyRR/R:R.RRR+R(((s9/pentest/voiper/protocol_logic/sip_transaction_manager.pyt<module>s     &9
10,866
Python
.py
132
74.969697
522
0.537184
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,987
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/__init__.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' __all__ = ['sip_transaction_manager', 'transceiver', 'sip_agent', 'sip_parser', 'sip_utilities']
820
Python
.py
17
46.294118
79
0.778195
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,988
sip_utilities.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/sip_utilities.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import select import threading import re import time import string import random import os from Queue import Queue from socket import * from misc.utilities import Logger class SIPMessageGenerator: def __init__(self): ''' This class parses SIP messages and extracts the values of the attributes, it the fills in a given response/request with these values ''' self.regex_dict = {'[BRANCH]' : r'branch\s*=\s*([\d\w-]+)', '[FROMTAG]' : r'From.*;tag=([\w\d]+)', '[CALL-ID]' : r'Call-ID\s*:\s*(\S+)', '[CSEQ-NUM]' : r'CSeq\s*:\s*(\d+?)', '[EXPIRES]' : r'Expires\s*:\s*(\d+)', '[TO]' : 'To\\s*:\\s*(.*)\r\n', '[TO-NOTAG]' : r'To\s*:\s*([\w\d\.:<>@]+=);?', '[FROM]' : 'From\\s*:\\s*(.*)\r\n', '[SIP-URI]' : \ r'[INVITE|CANCEL|REGISTER|OPTIONS]\s+(\S*)\s+SIP/2.0', '[VIA]' : 'Via\\s*:\\s*([^(\r\n)]+)', '[VIA-URI]' : r'Via\s*:\s*([\w\d\.:<>@/ ]+);', } def generate(self, parse_msg, fill_msg, keys=None): ''' Parses parse_msg for the all values defined in self.regex_dict and fills them into a template provided by fill_msg @type parse_msg: String @param parse_msg: The SIP message to parse @type fill_msg: String @param fill_msg: The SIP message to fill @type keys: List @param keys: The keys to fill from self.regex_dict @rtype: String @return: The filled in request/response ''' tmp_dict = {} self.parse(parse_msg, tmp_dict, keys) return self.fill(fill_msg, tmp_dict) def parse(self, msg, dict, keys): ''' Parses msg for the keys specified in dict and sets the value of the key to the value parsed from msg @type msg: String @param msg: The SIP message to parse @type dict: Dictionary @param dict: A dictionary who's keys correspond to the keys in self.regex_dict that you want to parse from the message. It will be filled with the values from msg @type keys: List @param keys: The keys to fill from self.regex_dict ''' if keys == None: keys = self.regex_dict.keys() for regex_name in keys: regex = self.regex_dict[regex_name] value = re.search(regex, msg, re.IGNORECASE) if value and len(value.groups()) != 0: dict[regex_name] = value.group(1) def fill(self, msg, dict): ''' Fills the msg with the data from dict by replacing the values in msg that correspond to the keys in dict @type msg: String @param msg: The request/response to fill in @type dict: Dictionary @param: The dictionary containing the data to insert @rtype: String @return: The filled in request/response ''' for replace_name in dict.keys(): if dict[replace_name] != '': msg = msg.replace(replace_name, dict[replace_name]) return msg class SIPInviteCanceler: def __init__(self, host, port, timeout): ''' Cancels a given INVITE request. The publicly accessible cancel method puts the message to be cancelled onto a queue. Worker threads read from this queue and cancel the given messages after a specified timeout (default = 2.0 seconds). It also attempts to ACK any responses received to keep communications as normal as possible @type host: String @param host: The host to send the CANCEL to @type port: Integer @param port: The port to send the CANCEL to @type timeout: Float @param timeout: The timeout to wait before cancelling the INVITE ''' self.host = host self.port = port self.queue = Queue(0) self.timeout = timeout self.sip_parser = SIPMessageGenerator() # get default logging method self.log = Logger().log self.alive = True # spawn off 30 worker threads # should never need more than timeoute * (fuzz msgs per second) + 1 or so self.num_threads = 30 for x in range(self.num_threads): threading.Thread(target=self.__cancel).start() self.ack_msg = ''.join(['ACK [SIP-URI] SIP/2.0\r\n', 'To: [TO]\r\n', 'From: [FROM]\r\n', 'Call-ID: [CALL-ID]\r\n', 'CSeq: 1 ACK\r\n', 'Via: [VIA]\r\n', 'Max-Forwards: 70\r\n', 'Content-Length: 0\r\n\r\n']) self.cancel_template = '\r\n'.join(['CANCEL [SIP-URI] SIP/2.0', 'CSeq: [CSEQ-NUM] CANCEL', #'Via: [VIA-URI];branch=[BRANCH];rport', 'Via: [VIA]', 'From: [FROM]', 'Call-ID: [CALL-ID]', #'To: [TO-NOTAG]', 'To: [TO]', 'Max-Forwards: 70', 'Contact: <sip:nnp@192.168.3.104:5068;transport=udp>']) + '\r\n\r\n' self.ack_msgs = ['481 Call Leg/Transaction Does Not Exist', '488 Not Acceptable Here', '487 Request Terminated', '603 Decline', '486 Busy Here', '400 Bad Request', ] def cancel(self, sock, invite_data): ''' Places a cancel for invite_data onto the cancellation queue @type sock: Socket @param sock: The socket that sent the INVITE request @type invite_data: String @param invite_data: An invite message used to initialise a call @todo: Add TCP support ''' cancel_msg = self.sip_parser.generate(invite_data, self.cancel_template, ['[SIP-URI]', '[CSEQ-NUM]', '[VIA]', '[BRANCH]', '[FROM]', '[CALL-ID]', '[TO]']) # truncate the data for udp sending if len(cancel_msg) > 65507: cancel_msg = cancel_msg[:65507] self.queue.put((sock, cancel_msg)) def kill_cancel_threads(self): for x in range(self.num_threads): self.queue.put((None, None)) def __cancel(self): ''' This method attempts to cancel the call initiated by sending invite_data. It simply replaces the INVITE keyword with CANCEL and resends the data. It runs as a worker thread and gives a timeout of self.timeout before cancelling the INVITE @todo: Remove 'select' statement. Pointless when using UDP ''' while 1: invite_sock, cancel_msg = self.queue.get() # die when done fuzzing if not (invite_sock or cancel_msg): break # allow sufficient time for the INVITE to be processed time.sleep(self.timeout) cancel_sock = socket(AF_INET, SOCK_DGRAM) cancel_sock.connect((self.host, self.port)) cancel_sock.send(cancel_msg) # Some implementations of SIP don't function correctly if they # don't receive an ACK for x in range(5): # Use select to avoid unecessary CPU hogging ready_to_read, ready_to_write, brokeded = \ select.select([cancel_sock, invite_sock], [], [], \ self.timeout) if len(ready_to_read) != 0: for read_sock in ready_to_read: try: data, addr = read_sock.recvfrom(65507) except error: self.log("SocketError cancelling request. Ensure target is listening.") continue for response_line in self.ack_msgs: if data.find(response_line) != -1: # according to the rfc the to field should come # from the response whereas the call id, from, via and request # uri should come from the INVITE request, which is # the same as the CANCEL here response = self.sip_parser.generate(data, \ self.ack_msg, ['[TO]']) response = self.sip_parser.generate(cancel_msg, \ response, ['[CALL-ID]', '[FROM]', \ '[SIP-URI]', '[VIA]']) invite_sock.send(response[:65507]) else: # nothing recieved, time to leave break cancel_sock.close() invite_sock.close() class SIPCrashDetector: def __init__(self, host, port, timeout=2.0): ''' Attempts to detect a SIP device malfunctioning by sending an OPTIONS message to the host specified. All SIP implementations should respond to this when functioning correctly. If no response is received another request is sent, if this is also unanswered we assume the target has died a grisly death @type host: String @param host: The host to target @type port: Integer @param port: The port to target @type timeout: Float @param timeout: The timeout for waiting for a response to the probe ''' random.seed(1986) self.host = host self.port = port self.timeout = timeout # get default logging method self.log = Logger().log self.alive = True self.options_msg = ''.join(['OPTIONS sip:user@example.com SIP/2.0\r\n', 'To: sip:user@example.com\r\n', 'From: sip:caller@192.168.3.102;tag=[RAND]\r\n', 'Call-ID: crashdetection.[RAND]\r\n', 'CSeq: [CSEQ-RAND] OPTIONS\r\n', 'Via: SIP/2.0/UDP host1.example.com;branch=z9hG4bKk[RAND]\r\n', 'Max-Forwards: 70\r\n', 'Content-Length: 0\r\n\r\n']) def is_responding(self): ''' Sends the OPTIONS message and waits for a response. We don't bother checking if the response to recieved is to the OPTIONS or to the INVITE as any sort of response should indicate the target is still alive. @type sock: Socket @param sock: The socket used to send the last fuzz case @rtype: Boolean @return: A boolean value indicating whether the target has is responding or not @todo: Add TCP support ''' # Ekiga seems to send 200 OK responses back to 5060 regardless of the # source port. Possibly should move this to the __init__ recv_sock = socket(AF_INET, SOCK_DGRAM) recv_sock.setblocking(0) recv_sock.settimeout(self.timeout) recv_sock.bind(('0.0.0.0', 5060)) id_unique = ''.join([random.choice(string.letters) for x in xrange(32)]) send_data = self.options_msg.replace('[CSEQ-RAND]', \ str(random.randint(1000, 100000))) send_data = send_data.replace('[RAND]', id_unique) sock = socket(AF_INET, SOCK_DGRAM) sock.settimeout(self.timeout) sock.connect((self.host, self.port)) sock.send(send_data) recv_sock.setblocking(0) responding = False # this checks the next 10 responses for the 200 OK response to the OPTIONS # if its not found we assume something went wrong - brutish but effective for x in range(10): ready_to_read, ready_to_write, brokeded = select.select([recv_sock, \ sock], [], [], self.timeout) if len(ready_to_read) != 0: for read_sock in ready_to_read: try: data, addr = read_sock.recvfrom(65507) except error: self.log("SocketError when checking target status. Ensure target is listening.") continue if data: responding = True break if responding == True: break else: # nothing was received and a correct response still hasn't been # received so we assume something has gone wrong break recv_sock.close() sock.close() return responding class SIPRegistrar: def __init__(self, ip, port): ''' This class plays the part of a registrar and allows clients to register with the fuzzer. This is required for clients that don't support P2P SIP calls and are required to first register with a service provider. @type ip: String @param ip: The IP address to listen on @type port: Integer @param port: The port to listen on ''' self.ip = ip self.port = port self.sip_parser = SIPMessageGenerator() # get default logging method self.log = Logger().log self.register_ok_msg = ''.join(['SIP/2.0 200 OK\r\n', 'Via: SIP/2.0/UDP someserver.bleh.com:5060;branch=[BRANCH]\r\n', 'To: user <sip:bleh@bleh.com>;tag=4343454\r\n', 'From: user <sip:bleh@bleh.com>;tag=[FROMTAG]\r\n', 'Call-ID: [CALL-ID]\r\n', 'CSeq: [CSEQ-NUM] REGISTER\r\n', 'Contact: <sip:bleh@bleh.com>\r\n', 'Expires: [EXPIRES]\r\n', 'Content-Length: 0\r\n\r\n']) self.attribute_dict = {'[BRANCH]' : '', '[FROMTAG]' : '', '[CALLID]' : '', '[CSEQ]' : '', '[EXPIRES]' : '', } def waitForRegister(self): ''' This function sits and waits for a connection on 5060 containing a REGISTER request and responds authorizing the connection ''' sock = socket(AF_INET, SOCK_DGRAM) sock.bind((self.ip, self.port)) while 1: data, incoming_addr = sock.recvfrom(1024) if data.find('REGISTER') != -1: self.log('[+] Register request received from ' + \ str(incoming_addr)) self.log('[+] Sending 200 OK response') self.allowRegister(incoming_addr, data) break sock.close() def allowRegister(self, host, register_request): ''' This responds to a REGISTER request with a 200 OK response. @type host: Tuple @param host: A tuple containing the IP and port to respond to the request on @type register_request: String @param register_request: The original register request from the client ''' response = self.sip_parser.generate(register_request,\ self.register_ok_msg) reply_sock = socket(AF_INET, SOCK_DGRAM) time.sleep(2) reply_sock.sendto(response, host) reply_sock.close()
16,376
Python
.py
361
32.301939
104
0.554328
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,989
sip_agent.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/sip_agent.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import time import threading import sip_parser import random import string import socket import hashlib # import md5 - this is deprecated - dookie import sys from Queue import Queue from random import Random from sip_transaction_manager import SIPTransaction from sip_transaction_manager import TData from sip_transaction_manager import EXTERNAL, GENERATOR from sip_parser import SIPParser T_INCOMPLETE = 1 T_INVALID_STATE = 2 T_COMPLETE_OK = 3 class SIPAgent: def __init__(self, response_q, request_q): ''' This class is responsible for playing the part of a SIP agent in a transaction. The process_transaction method takes a dictionary describing the transaction and attempts to process it. The dictionary describes expected response codes and the functions to be called when these response codes are detected. @type response_q: Queue @param response_q: A queue which we will read data from the network off @type request_q: Queue @param request_q: A queue which we will write any responses too ''' self.sp = sip_parser.SIPParser() self.previous_got_response = True self.in_queue = response_q self.out_queue = request_q def process_transaction(self, t_dict, extra_params=None): ''' @type t_dict: Dictionary @param t_dict: A dictionary describing the possible states this transaction may traverse and what actions to take upon entering them. See fuzzer/fuzzer_parents.py for examples @type extra_params: Dictionary @param extra_params: A dictionary containing any possible extra paramaters transaction initiating methods might need e.g sending an OPTIONS @r_type: Integer @return: An integer describing the result of attempting to process the given t_dict ''' #wait_time = self.calculate_wait_time(False, self.previous_got_response, 1) wait_time = .8 status = None if extra_params != None and extra_params.has_key('branch'): curr_branch = extra_params['branch'] else: curr_branch = None while status == None: possible_r_codes = t_dict.keys() if possible_r_codes[0] != sip_parser.r_SEND: # Attempt to get a response matching the r_codes we are expecting (sip_t, r_code) = self.get_transaction(self.in_queue, possible_r_codes, curr_branch, wait_time) if not curr_branch and sip_t: curr_branch = sip_t.t_data_list[0].p_data[sip_parser.BRANCH] # Only proceed if the transaction is in a valid states. Unexpected # responses invalidate the transaction state if r_code in possible_r_codes: action_tuple = t_dict[r_code] method = action_tuple[0] # Some requests can result in 2 responses. One of which may need no further # processing. e.g CANCEL can result in a 200 OK which can be ignored and a 487 # which must be ACK'ed if method == None: any_actions = False # check if any of the r_codes have actions associated with them. # If the don't we assume the transaction is considered complete # when any are received and we return. If they do then we just ignore # this response and get the next one off the queue for r_code in t_dict.keys(): if t_dict[r_code][0] != None: any_actions = True if any_actions: continue else: # No actions at this level and we got a response # so the transaction completed correctly status = T_COMPLETE_OK break method(sip_t, self.out_queue, extra_params) t_dict = action_tuple[1] if not t_dict: status = T_COMPLETE_OK else: # if sip_t == None: The transaction didn't complete correctly. This # is probably because the fuzz request was so messed up that it was # ignored. Otherwise we got a response but it did not conform to our # transaction description if sip_t == None: print >> sys.stderr, 'SA: T_INCOMPLETE' status = T_INCOMPLETE else: print >> sys.stderr, 'SA: T_INVALID_STATE' status = T_INVALID_STATE else: # Initiating transaction action_tuple = t_dict[sip_parser.r_SEND] method = action_tuple[0] # r_SEND means a new transaction is being created so update the branch curr_branch = method(None, self.out_queue, extra_params) t_dict = action_tuple[1] if not t_dict: status = T_COMPLETE_OK # Clear any remaining requests from the queue so as not to interfere # with the processing of the next transaction self.flush_queue() # if t_dict != None then we didn't complete the transaction mapping return (status, curr_branch) def flush_queue(self): ''' Method to ensure any messages remaining on the input queue that have not been consumed are removed @type queue: Queue @param queue: The queue to flush ''' try: while 1: self.in_queue.get(False) except: pass def get_transaction(self, queue, r_codes, curr_branch, wait_time): ''' Method that attempts to retrieve a message with the given r_code from the queue @type queue: Queue @param queue: The queue to read off @type r_codes: List @param r_codes: A list of response codes that are considered a valid match @type wait_time: Float @param wait_time: The time to wait for responses before returning. This will be approached in intervals of .1 of a second. ''' sleep_time = .1 q_r_code = None slept_for = 0 print >> sys.stderr, 'wait time ' + str(wait_time) print >> sys.stderr, 'SA-EXPECTING ' + str(r_codes) while slept_for <= wait_time: sip_t = None try: sip_t = queue.get(False) last_recv = sip_t.t_data_list[len(sip_t.t_data_list)-1] q_r_code = last_recv.p_data[sip_parser.RCODE] # Check the response is for the transaction we're interested in if not curr_branch or last_recv.p_data[sip_parser.BRANCH].find(curr_branch) != -1: print >> sys.stderr, 'SA-GOT-CORRECT-BRANCH' try: r_codes.index(q_r_code) print >> sys.stderr, 'SA-GOT-CORRECT-R-CODE ' + str(q_r_code) + ' # ' + str(r_codes) break except ValueError: # We got an unscheduled message. The transaction has proceeded into an # unexpected state. print >> sys.stderr, 'SA-GOT-UNEXPECTED-R-CODE ' + str(q_r_code) + ' # ' + str(r_codes) #return (sip_t, q_r_code) else: sip_t = None q_r_code = None except: pass time.sleep(sleep_time) slept_for += sleep_time if sip_t: self.previous_got_response = True else: self.previous_got_response = False return (sip_t, q_r_code) def calculate_wait_time(self, previous_fuzz, previous_got_response, wait_time): # not sure if including this is a good idea as you can't really predict the probability # of a fuzz request generating a response. Always set to true for now if previous_fuzz: wait_time *= .8 if not previous_got_response: wait_time *= .8 return wait_time def require(self, x, y, z): # this method acts as a placeholder anywhere in the transaction dictionary # where a request MUST arrive but no response to it is generated pass class SIPCancel: def process(self, sip_t, output_q, extra_params=None): ''' Process the next response for the given SIP transaction and put it on the output queue ''' err = self.send_cancel(sip_t, output_q) return None def send_cancel(self, sip_transaction, output_q): ''' - We receive a 1XX provisional response to the initial INVITE which means we can now send the CANCEL @type sip_transaction: SIPTransaction @param sip_transaction: An object representing the entire transaction so far ''' last_recv = sip_transaction.t_data_list[len(sip_transaction.t_data_list)-1] r_code = last_recv.p_data[sip_parser.RCODE] if r_code == sip_parser.r_1XX: # create and send CANCEL cancel_request = self.create_cancel(sip_transaction.t_data_list[0]) output_q.put((True, cancel_request, GENERATOR, last_recv.addr, 1.5)) def create_cancel(self, t_data): ''' Method to generate a cancel request for a given INVITE. According to the RFC the following fields must match (including tags) - Request URI - Call-ID - To - Numeric part of the CSeq - From - Via (should contain only a single Via header matching the top Via header from the INVITE) The method part of the Cseq header must have a value of CANCEL @type t_data: TData @param t_data: A TData object representing the INVITE to be cancelled @rtype: String @return: The cancel request for the INVITE in t_data ''' # retrieve the dictionary of parsed values p_data = t_data.p_data cancel_template = [['CANCEL', p_data[sip_parser.RURI], 'SIP/2.0'], ['CSeq:', p_data[sip_parser.CSEQNUM], 'CANCEL'], ['Via:', p_data[sip_parser.VIA]], ['To:', p_data[sip_parser.TO]], ['From:', p_data[sip_parser.FROM]], ['Call-ID:', p_data[sip_parser.CALLID]], ['Max-Forwards: 70']] cancel_request = [] for line in cancel_template: cancel_request.append(' '.join(line)) cancel_request = '\r\n'.join(cancel_request) + '\r\n\r\n' return cancel_request class SIPAck: def process(self, sip_t, output_q, extra_params=None): ''' @type input_tuple: Tuple @param sinput_tuple: See SIPCancel ''' err = self.send_ack(sip_t, output_q) return None def send_ack(self, sip_transaction, output_q): ''' We receive a 487 response indicating the INVITE has been cancelled. This must be ACK'ed @type sip_transaction: SIPTransaction @param sip_transaction: An object representing the entire transaction so far ''' last_recv = sip_transaction.t_data_list[len(sip_transaction.t_data_list)-1] r_code = last_recv.p_data[sip_parser.RCODE] ack_request = self.create_ack(last_recv, sip_transaction.t_data_list[0]) output_q.put((True, ack_request, GENERATOR, last_recv.addr, 1.5)) def create_ack(self, request_to_ack, orig_request): ''' Method to create an ACK for a request. According to the SIP RFC the following fields must match the request that created the transaction - Call ID - From - Request URI - Via (should contain only a single Via header matching the top Via header from the INVITE) - Numeric part of the CSeq The To header should match the To header from request that is being acknowledged. @type request_to_ack: TData @param request_to_ack: The request that the ACK is being generated for @type orig_request: TData @param orig_request: The request that started the transaction @rtype: String @return: The ACK for the given request ''' p_data_req_ack = request_to_ack.p_data p_data_orig = orig_request.p_data try: r_uri = p_data_orig[sip_parser.RURI] except KeyError: r_uri = 'user@192.168.3.100' try: cseq_num = p_data_orig[sip_parser.CSEQNUM] except KeyError: cseq_num = '3' try: via = p_data_orig[sip_parser.VIA] except KeyError: via = 'SIP/2.0/UDP 192.168.3.102:5068;branch=z9hG4bKlm4zshdowki1t8c7ep6j0yavq2ug5r3x;rport' try: to = p_data_req_ack[sip_parser.TO] except KeyError: to = '<sip:nnp@192.168.3.101>' try: p_from = p_data_orig[sip_parser.FROM] except KeyError: p_from = '"nnp" <sip:nnp@192.168.3.104>;tag=so08p5k39wuv1dczfnij7bet4l2m6hrq' try: call_id = p_data_orig[sip_parser.CALLID] except KeyError: call_id = 'rzxd6tm98v0eal1cifg2py7sj3wk54ub@voiper' ack_template = [['ACK', r_uri, 'SIP/2.0'], ['CSeq:', cseq_num, 'ACK'], ['Via:', via], ['To:', to], ['From:', p_from], ['Call-ID:', call_id], ['Max-Forwards: 70']] ack_request = [] for line in ack_template: ack_request.append(' '.join(line)) ack_request = '\r\n'.join(ack_request) + '\r\n\r\n' return ack_request class SIPOptions: def process(self, sip_t, out_queue, extra_params): ''' @type params: Dictionary @param params: A dictionary containing the host and port to send the OPTIONS to @type out_queue: Queue @param out_queue: A queue onto which the OPTIONS will be put to be sent ''' self.host = extra_params['host'] self.port = extra_params['port'] self.user = extra_params['user'] self.target_user = extra_params['target_user'] self.branch = None if extra_params.has_key('branch'): self.branch = extra_params['branch'] self.send_options(out_queue) return self.branch def send_options(self, out_queue): options_request = self.create_options() out_queue.put((True, options_request, GENERATOR, (self.host, self.port), 1.5)) def create_options(self): sip_uri = ''.join(['sip:', self.host]) r_data = ''.join(Random().sample(string.ascii_lowercase+string.digits, 32)) to_line = ''.join(['<sip:', self.target_user, '@', self.host, '>']) from_line = ''.join(['"VoIPER" <sip:', self.user, '@', self.host, '>', ';tag=', r_data]) local_ip = socket.gethostbyname(socket.gethostname()) if self.branch: via_line = ''.join([local_ip, ';branch=z9hG4bKk', self.branch]) else: via_line = ''.join([local_ip, ';branch=z9hG4bKk', r_data]) self.branch = r_data call_id_line = ''.join(['options.', r_data]) uri = ''.join(['sip:', self.host]) contact_line = ''.join(['<sip:', self.user, '@', local_ip, '>']) options_template = [['OPTIONS', sip_uri, 'SIP/2.0'], ['CSeq:', str(random.randint(1000, 100000)), 'OPTIONS'], ['Via: SIP/2.0/UDP', via_line], ['To:', to_line], ['From:', from_line], ['Call-ID:', call_id_line], ['Max-Forwards: 70'], ['Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE'], ['Accept: application/sdp'], ['Contact:', contact_line]] options_request = [] for line in options_template: options_request.append(' '.join(line)) options_request = '\r\n'.join(options_request) + '\r\n\r\n' return options_request class SIPRegister: def process(self, sip_t, output_q, extra_params): host = extra_params['host'] port = extra_params['port'] username = extra_params['user'] password = extra_params['password'] self.branch = None if extra_params.has_key('branch'): self.branch = extra_params['branch'] if sip_t: self.send_register_final(sip_t, output_q, username, password) return None else: self.send_register_init(host, port, username, output_q) return self.branch def send_register_init(self, host, port, username, output_q): register_request = self.create_register_init(host, username) print >> sys.stderr, 'sending register init' output_q.put((True, register_request, GENERATOR, (host, port), 1.5)) def send_register_final(self, sip_t, output_q, username, password): last_recv = sip_t.t_data_list[-1] orig_reg = sip_t.t_data_list[0] register_request = self.create_register_final(orig_reg, last_recv, username, password) output_q.put((True, register_request, GENERATOR, last_recv.addr, 1.5)) def calculate_md5_response(self, username, password, realm, uri, nonce): ''' See RFC 3261 section 22 and RFC 2069 section 2.1.2 for details. @type username: String @param username: The username to register on the registrar @type password: String @param password: The password that goes with the given username @type realm: String @param realm: The 'realm' value which will be returned by the server in response to the initial REGISTER request as part of the WWW-Authenticate header @type uri: String @param uri: The SIP/SIPS uri from the original request line. Will be of the form 'sip:192.168.3.101', without the quotes. @type nonce: String @param nonce: The 'nonce' value which will be returned by the server in response to the initial REGISTER request as part of the WWW-Authenticate header ''' A1 = ':'.join([username, realm, password]) A2 = ':'.join(['REGISTER', uri]) md5_A1 = md5.new(A1).hexdigest() md5_A2 = md5.new(A2).hexdigest() return md5.new(':'.join([md5_A1, nonce, md5_A2])).hexdigest() def create_register_final(self, init_reg_request, auth_response, username, password): p_data_init = init_reg_request.p_data p_data_auth = auth_response.p_data cseq_num = str(int(p_data_init[sip_parser.CSEQNUM]) + 1) nonce = p_data_auth[sip_parser.WWW_AUTHEN_NONCE] realm = p_data_auth[sip_parser.WWW_AUTHEN_REALM] md5_response = self.calculate_md5_response(username, password, realm, p_data_init[sip_parser.RURI], nonce) auth_string = ''.join(['Digest username="', username, '", realm="', realm, '", nonce="', nonce, '", uri="', p_data_init[sip_parser.RURI],'", algorithm=md5, response="', md5_response, '"']) register_template = [['REGISTER', p_data_init[sip_parser.RURI], 'SIP/2.0'], ['CSeq:', cseq_num, 'REGISTER'], ['Via:', p_data_init[sip_parser.VIA]], ['To:', p_data_init[sip_parser.TO]], ['From:', p_data_init[sip_parser.FROM]], ['Call-ID:', p_data_init[sip_parser.CALLID]], ['Authorization:', auth_string], ['Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE'], ['Contact:', p_data_init[sip_parser.CONTACT]], ['Expires: 3600'], ['Max-Forwards: 70']] register_request = [] for line in register_template: register_request.append(' '.join(line)) register_request = '\r\n'.join(register_request) + '\r\n\r\n' return register_request def create_register_init(self, target_ip, user): r_data = ''.join(Random().sample(string.ascii_lowercase+string.digits, 32)) to_line = ''.join(['<sip:', user, '@', target_ip, '>']) from_line = ''.join([to_line, ';tag=', r_data]) local_ip = socket.gethostbyname(socket.gethostname()) if self.branch: via_line = ''.join([local_ip, ';branch=z9hG4bKk', self.branch]) else: self.branch = r_data via_line = ''.join([local_ip, ';branch=z9hG4bKk', r_data]) call_id_line = ''.join(['register.', r_data]) uri = ''.join(['sip:', target_ip]) contact_line = ''.join(['<sip:', user, '@', local_ip, '>']) register_template = [['REGISTER', uri, 'SIP/2.0'], ['To:', to_line], ['From:', from_line], ['Call-ID:', call_id_line ], ['CSeq:', str(random.randint(1000, 100000)), 'REGISTER'], ['Via: SIP/2.0/UDP', via_line], ['Max-Forwards: 70'], ['Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE'], ['Contact:', contact_line], ['Expires: 3600']] register_request = [] for line in register_template: register_request.append(' '.join(line)) register_request = '\r\n'.join(register_request) + '\r\n\r\n' return register_request class SIPInvite: def process(self, sip_t, output_q, extra_params): self.host = extra_params['host'] self.port = extra_params['port'] self.user = extra_params['user'] if extra_params.has_key('target_user'): self.target_user = extra_params['target_user'] else: self.target_user = None self.branch = None if extra_params.has_key('branch'): self.branch = extra_params['branch'] self.output_q = output_q self.send_invite() return self.branch def send_invite(self): invite_request = self.create_invite() self.output_q.put((True, invite_request, GENERATOR, (self.host, self.port), 2.0)) def create_invite(self): ''' According to the RFC the following headers SHOULD be present: - Allow - Supported Headers that MAY be present are not included by VoIPER. The following MUST be included: - From - Via - To - Call-ID - CSeq Content-type and Content-length are required for the SDP header ''' if self.target_user: sip_uri = ''.join(['sip:', self.target_user, '@', self.host]) to_line = ''.join(['<sip:', self.target_user, '@', self.host, '>']) else: sip_uri = ''.join(['sip:', self.host]) to_line = ''.join(['<sip:', self.host, '>']) r_data = ''.join(Random().sample(string.ascii_lowercase+string.digits, 32)) local_ip = socket.gethostbyname(socket.gethostname()) from_line = ''.join(['"VoIPER" <sip:', self.user, '@', local_ip, '>;tag=', r_data]) if self.branch: via_line = ''.join(['SIP/2.0/UDP ', local_ip, ';branch=z9hG4bKk', self.branch]) else: self.branch = r_data via_line = ''.join(['SIP/2.0/UDP ',local_ip, ';branch=z9hG4bKk', r_data]) call_id_line = ''.join([r_data]) contact_line = ''.join(['<sip:', self.user, '@', local_ip, '>']) c_line = ' '.join(['c=IN IP4', local_ip]) o_line = ' '.join(['o=- 1212861461 1212861461', c_line]) # header ripped from ekiga 2.11 so it should # be compliant with most other SIP apps sdp_header = '\r\n'.join(['v=0', o_line, 's=VoIPER SIP Session', c_line, 't=0 0', 'm=audio 5000 RTP/AVP 112 113 3 105 108 0 8 101', 'a=rtpmap:112 SPEEX/16000', 'a=rtpmap:113 iLBC/8000', 'a=rtpmap:3 GSM/8000', 'a=rtpmap:105 MS-GSM/8000', 'a=rtpmap:108 SPEEX/8000', 'a=rtpmap:0 PCMU/8000', 'a=rtpmap:8 PCMA/8000', 'a=rtpmap:101 telephone-event/8000', 'a=fmtp:101 0-15']) invite_template = [['INVITE', sip_uri, 'SIP/2.0'], ['CSeq:', str(random.randint(1000, 100000)), 'INVITE'], ['Via:', via_line], ['To:', to_line], ['From:', from_line], ['Call-ID:', call_id_line], ['Max-Forwards: 70'], ['Content-Type: application/sdp'], ['Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE'], ['Contact:', contact_line], ['Content-Length:', str(len(sdp_header))], ['']] invite_request = [] for line in invite_template: invite_request.append(' '.join(line)) invite_request = '\r\n'.join(invite_request) invite_request = '\r\n'.join([invite_request, sdp_header]) return invite_request
26,958
Python
.py
569
34.906854
114
0.566787
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,990
test_sip_agent.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/test_sip_agent.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' from sip_agent import SIPCanceler from sip_parser import SIPParser from sip_transaction_manager import TData invite1 = '\r\n'.join(['INVITE sip:nnp@192.168.3.104 SIP/2.0', 'Date: Sun, 23 Sep 2007 00:23:19 GMT', 'CSeq: 1 INVITE', 'Via: SIP/2.0/UDP 192.168.3.102:5071;branch=z9hG4bKa8f5f4da-d867-dc11-8c7d-000c29da463b;rport', 'User-Agent: Ekiga/2.0.3', 'From: "nnp nnp" <sip:nnp@192.168.3.102>;tag=a68cf4d7-d867-dc11-8c7d-000c29da463b', 'Call-ID: MOFOID@ubuntu', 'To: <sip:nnp@192.168.3.104>', 'Contact: <sip:nnp@192.168.3.102:5071;transport=udp>', 'Allow: INVITE,ACK,OPTIONS,BYE,CANCEL,NOTIFY,REFER,MESSAGE', 'Content-Type: application/sdp', 'Content-Length: 389', 'Max-Forwards: 70']) + '\r\n\r\n' invite1 = invite1 + '\r\n'.join(['v=0', 'o=- 1190506999 1190506999 IN IP4 192.168.3.102', 's=Opal SIP Session', 'c=IN IP4 192.168.3.102', 't=0 0', 'm=audio 5040 RTP/AVP 101 96 3 107 110 0 8', 'a=rtpmap:101 telephone-event/8000', 'a=fmtp:101 0-15', 'a=rtpmap:96 SPEEX/-1', 'a=rtpmap:3 GSM/8000', 'a=rtpmap:107 MS-GSM/8000', 'a=rtpmap:110 SPEEX/-1', 'a=rtpmap:0 PCMU/8000', 'a=rtpmap:8 PCMA/8000', 'm=video 5042 RTP/AVP 31', 'a=rtpmap:31 H261/-1']) + '\r\n' cancel1 = '\r\n'.join(['CANCEL sip:nnp@192.168.3.104 SIP/2.0', 'CSeq: 1 CANCEL', 'Via: SIP/2.0/UDP 192.168.3.102:5071;branch=z9hG4bKa8f5f4da-d867-dc11-8c7d-000c29da463b;rport', 'To: <sip:nnp@192.168.3.104>', 'From: "nnp nnp" <sip:nnp@192.168.3.102>;tag=a68cf4d7-d867-dc11-8c7d-000c29da463b', 'Call-ID: MOFOID@ubuntu', 'Max-Forwards: 70']) + '\r\n\r\n' data_dict = SIPParser().parse(invite1) t_data = TData(invite1, data_dict, None) s_canceler= SIPCanceler(None, None) cancel_request = s_canceler.create_cancel(t_data) assert(cancel_request == cancel1)
2,470
Python
.py
59
39.915254
95
0.732969
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,991
test_sip_register.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/test_sip_register.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import sys from Queue import Queue import sip_parser from sip_transaction_manager import SIPTransactionManager from sip_agent import SIPCancel from sip_agent import SIPAck from sip_agent import SIPAgent from sip_agent import SIPRegister from sip_agent import SIPInvite response_q = Queue(0) request_q = Queue(0) sip_agent = SIPAgent() register = SIPRegister() SIPTransactionManager(request_q, response_q).start() register_dict = {sip_parser.r_SEND : (register.process, { sip_parser.r_4XX : (register.process, { sip_parser.r_2XX : (sip_agent.require, None), sip_parser.r_1XX : (None, None) } ), sip_parser.r_1XX : (None, None), sip_parser.r_2XX : (sip_agent.require, None), } ) } result = sip_agent.process_transaction( register_dict, response_q, request_q, {'user' : sys.argv[1], 'password' : sys.argv[2], 'host' : sys.argv[3], 'port' : int(sys.argv[4]),} )
1,905
Python
.py
53
28.528302
72
0.650907
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,992
sip_transaction_manager.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/sip_transaction_manager.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import time import threading import thread import sip_parser import sys from transceiver import UDPTransceiver from sip_parser import SIPParser from Queue import Queue from copy import deepcopy GENERATOR=0 NETWORK=1 EXTERNAL=2 class TData: def __init__(self, data, p_data, source, addr=None, socket=None): ''' A data class to represent the data of a message in a transaction along with who sent it @type data: String @param data: The data of a message in a transaction @type p_data: Dictionary @param p_data: A dictionary returned by the message parser with mappings of fields to their values parsed from the data @type source: Integer @param source: Indicates where this t_data originated in our system and as a result, what do do with it. If '0' the t_data came from one of the protocol generators and the data will be sent to the address stored in t_data.addr and added to/create an appropriate SIPTransaction. If '1' the t_data arrived from the network and will be added to the appropriate transaction. All queues will also be notified of its arrival. If '2' the data originated from some external source e.g the fuzzer. It is assumed to already have been sent. If it has a t_data.socket this will be added to the sockets the transceiver is monitoring. It will be added to/create a SIPTransaction @type addr: Tuple @param addr: The (IP, port) tuple the data was sent to or received from @type socket: Socket @param socket: The socket that was used to send the data. Only necessary if this data structure was created outside the transaction manager and the data already sent. Without this we wouldn't be able to see any responses to this port ''' self.data = data self.p_data = p_data self.source = source self.addr = addr self.socket = socket class SIPTransaction: def __init__(self, branch, t_data_list, timestamp, timeout, addr=None): ''' Data class to represent a SIP transaction and required data regarding it @type branch: String @param branch: The branch value from the SIP transaction. Used to uniquely identify transactions @type t_data_list: List @param t_data_list: A list of TData objects representing the data of the message and who sent it @type timestamp: Integer @param timestamp: The timestamp for when this transaction was last updated @type timeout: Integer @param timeout: The timeout from the timestamp after which the transaction will be disgarded @type addr: Tuple @param addr: The (IP, port) tuple from the last message in the t_data list to be received. If None it is assumed the last message was sent out by VoIPER ''' self.branch = branch self.t_data_list = t_data_list self.timestamp = timestamp self.timeout = timeout # a list of sockets associated with this transaction self.sockets = [] def add_response(self, t_data): ''' This method should be used to add a new t_data object to the t_data_list. It prevents retransmissions being added to the transaction record @type t_data: TData @param t_data: A TData object representing the request @rtype: Boolean @return: Returns True if the t_data is added and returns false otherwise i.e. the t_data was a retransmission of a previous request ''' try: t_data_r_code = t_data.p_data[sip_parser.RCODE] for prev_data in self.t_data_list: if prev_data.p_data[sip_parser.RCODE] == t_data_r_code: return False except KeyError: # It is possible that some of our fuzz requests will not # have a correct request code but thats OK pass self.t_data_list.append(t_data) return True class SIPTransactionManager(threading.Thread): def __init__(self, add_trans_queue, global_update_queue, listen_port=5060): ''' @type add_trans_queue: Queue @param add_trans_queue: A queue that this class will listen on for tuples of the form identical to the parameters to the add_transaction method of this class except with an extra parameter at the start that can be False to indicate to this class to shutdown or True otherwise. The data this queue receives will be added to the transaction list this class is monitoring @type global_update_queue: Queue @param global_update_queue: A queue that will receive a SIPTransaction object every time an update from the network arrives for that SIPTransaction ''' self.add_trans_queue = add_trans_queue self.global_update_queue = global_update_queue self.listen_port = listen_port self.lock = thread.allocate_lock() self.transceiver = UDPTransceiver([self.listen_port], self.lock) self.transceiver.add_notify_queue(self.add_trans_queue, self.listen_port) self.transceiver.listen(True) # A dictionary mapping branch values to SIPTransaction objects self.transaction_dict = {} self.sip_parser = SIPParser() threading.Thread.__init__(self) def run(self): while True: new_trans_tuple = None try: new_trans_tuple = self.add_trans_queue.get() except: pass if new_trans_tuple != None: #print >> sys.stderr, 'TM: Got data' if new_trans_tuple[0] == False: #signal to listener first to exit print >>stderr, 'tm returning cause tuple thingy was false' print >>stderr, new_trans_tuple return else: data = new_trans_tuple[1] source = new_trans_tuple[2] addr = new_trans_tuple[3] timeout = new_trans_tuple[4] socket = None # only interested in the socket if the data came from # a source outside the core. Sources inside the core # will be monitored by default if source == EXTERNAL: socket = new_trans_tuple[5] elif source == GENERATOR: print >>sys.stderr, 'got something from generator off queue' self.add_data_to_transactions(data, source, addr,\ timeout, socket) def add_data_to_transactions(self, data, source, addr, timeout, socket=None): data_dict = self.sip_parser.parse(data) # no branch no fun if data_dict.has_key(sip_parser.BRANCH): t_data = TData(data, data_dict, source, addr, socket) self.add_transaction(t_data, timeout=timeout) def add_transaction(self, t_data, timeout=None): ''' Function to add a SIP transaction to the list of the transactions this manager is taking care of. If a transaction with this branch already exists then this data and queue are appended to their lists and all other fields in the old sip_transaction are updated to the new values. If not a new SIPTransaction object is created with the provided details and added to the list. @type t_data: TData @param data: A TData object representing the data, its parsed fields and its origin @type timeout: Integer @param timeout: A timeout after which this transaction will no longer be monitored ''' # parse all fields timestamp = time.time() data_dict = t_data.p_data # First identify the transaction the data is for or create a new # transaction for it t_data_added = False if self.transaction_dict.has_key(data_dict[sip_parser.BRANCH]): sip_t = self.transaction_dict[data_dict[sip_parser.BRANCH]] t_data_added = sip_t.add_response(t_data) if timeout: sip_t.timeout = timeout else: # If the source is the network then check that the request is # of a type that is allowed to create a new transaction. For # now we only allow a few types. More may be added in the future if required try: r_code = data_dict[sip_parser.RCODE] except KeyError: # Some of our fuzz requests will not have a request code # matching the defined pattern due to fuzzing but thats OK r_code = -1 if t_data.source != NETWORK or (r_code <= sip_parser.r_INVITE and r_code >= sip_parser.r_CANCEL): sip_t = SIPTransaction(data_dict[sip_parser.BRANCH], [t_data], \ timestamp, timeout) self.transaction_dict[data_dict[sip_parser.BRANCH]] = sip_t else: return # Now perform some actions based on the source of the data if t_data.source == GENERATOR: # Data was generated by the SIP backend. Send it and add the socket # used to the list being monitored print >> sys.stderr, 'Source is generator. Sending' send_sock = self.transceiver.send(t_data.data, t_data.addr) if send_sock: sip_t.sockets.append(send_sock) elif t_data.source == NETWORK and t_data_added: # Data originated from another node on the network. Put on the # notify queue. A copy is used in case another update arrives # before this one is processed and cloaks this one in the t_data list self.global_update_queue.put(deepcopy(sip_t)) elif t_data.source == EXTERNAL: # Data came from an external source e.g the fuzzer and has already # been sent. We just need to monitor for responses if t_data.socket: sip_t.sockets.append(t_data.socket) self.transceiver.add_socket(t_data.socket) self.__check_timeouts() def __check_timeouts(self): ''' Checks to see if any of the transactions have timed out and Removes them if so ''' curr_time = time.time() print >>sys.stderr, 'TM: %d transactions being monitored' % len(self.transaction_dict) for branch in self.transaction_dict.keys(): transaction = self.transaction_dict[branch] if curr_time - transaction.timestamp >= transaction.timeout: for sock in transaction.sockets: self.transceiver.close_socket(sock) del self.transaction_dict[branch] def unregister_from_transceiver(self): ''' Function to remove this transaction managers queue from the list of queues registered with the transceiver ''' self.transceiver.remove_notify_queue((self.incoming_data_queue, self.listen_port))
12,475
Python
.py
254
37.291339
94
0.62309
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,993
sip_parser.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/protocol_logic/sip_parser.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import re BRANCH = 1 FROM = 2 TO = 3 RCODE = 4 TOTAG = 5 CALLID = 6 CSEQNUM = 7 FROMTAG = 8 RURI = 9 VIA = 10 WWW_AUTHEN_NONCE = 11 WWW_AUTHEN_REALM = 12 CONTACT = 13 r_1XX = 99 r_2XX = 98 r_3XX = 97 r_4XX = 96 r_5XX = 95 r_6XX = 94 r_ACK = 89 r_INVITE = 88 r_REGISTER = 87 r_OPTIONS = 86 r_CANCEL = 85 r_UNKNOWN = 69 r_SEND = 68 r_401 = 59 r_180 = 58 class SIPParser: def __init__(self): ''' A class to implement all the functionality required to parse the relevant fields from a SIP message ''' self.regex_dict = {BRANCH : r'^Via.*?branch\s*?=\s*?(?P<target>[\d\w-]+)', FROMTAG : r'^From.*?;tag=(?P<target>[\w\d-]+)', CALLID : r'^Call-ID\s*?:\s*(?P<target>\S+)', CSEQNUM : r'^CSeq\s*?:\s*(?P<target>\d+)', TO : r'^To\s*?:\s*(?P<target>.+)\r\n', FROM : r'^From\s*?:\s*(?P<target>.+)\r\n', RCODE : r'^(?P<target>INVITE|CANCEL|OPTIONS|REGISTER|SIP/2\.0 \d{3}|ACK)', RURI : r'(INVITE|CANCEL|OPTIONS|REGISTER)\s+(?P<target>.+?)\s+SIP/2.0', VIA : r'^Via\s*?:\s*(?P<target>.+)\r\n', WWW_AUTHEN_NONCE : r'^WWW-Authenticate\s*?:\s*Digest.+nonce="(?P<target>[\w\d\.-]+)"', WWW_AUTHEN_REALM : r'^WWW-Authenticate\s*?:\s*Digest.+realm="(?P<target>[\w\d\.@]+)"', CONTACT : r'^Contact\s*?:\s*?(?P<target><sip:[\w\d]+@[\w\d\.]+(:[\d]+)?(;transport=(udp|tcp))?>)', } self.regex_c = {} # compile those filthy regexs ;) for r_name in self.regex_dict.keys(): r_val = self.regex_dict[r_name] r = re.compile(r_val, re.IGNORECASE | re.MULTILINE) self.regex_c[r_name] = r def parse(self, data, fields=None): ''' Parses the provided data and extracts the relevant fields and their values into a dictionary @type data: String @param data: The SIP message to be parsed @type field: List @param field: A list of the fields to parse identified by the constants defined in the __init__ of this class. If None all fields are parsed @rtype: Dictionary @return: A dictionary of fields to and their associated values ''' if fields == None: fields = self.regex_c.keys() res_dict = {} for r_name in fields: val = self.regex_c[r_name].search(data) if val and len(val.groups()) != 0: res_dict[r_name] = val.group('target') return self.normalise_rcodes(res_dict) def normalise_rcodes(self, data_dict): ''' Method to change textual response codes to one of the constants defined in the __init__ method @type data_dict: Dictionary @param data_dict: A dictionary of message fields to their values parsed from a SIP message @rtype: Dictionary @return: A dictionary where the response code strings have been converted to constants defined in this class ''' if data_dict.has_key(RCODE): r_code = data_dict[RCODE] if r_code.upper() == 'ACK': r_code = r_ACK elif r_code.upper() == 'INVITE': r_code = r_INVITE elif r_code.upper() == 'REGISTER': r_code = r_REGISTER elif r_code.upper() == 'OPTIONS': r_code = r_OPTIONS elif r_code.upper() == 'CANCEL': r_code = r_CANCEL elif r_code.find('SIP/2.0') != -1: data = r_code.split(" ") r_code = data[1] if r_code[0] == '1': r_code = r_1XX elif r_code[0] == '2': r_code = r_2XX elif r_code[0] == '3': r_code = r_3XX elif r_code[0] == '4': r_code = r_4XX elif r_code[0] == '5': r_code = r_5XX elif r_code[0] == '6': r_code = r_6XX elif r_code == '401': r_code = r_401 elif r_code == '180': r_code = r_180 else: r_code = r_UNKNOWN data_dict[RCODE] = r_code return data_dict def denormalise_rcode(self, r_code): ''' Convert the int representation of a rcode to its textual value @type r_code: Integer @param r_code: The rcode to convert @rtype: String @return: The textual value corresponding to the given rcode ''' r_dict = { 99 : 'r_1XX', 98 : 'r_2XX', 97 : 'r_3XX', 96 : 'r_4XX', 95 : 'r_5XX', 94 : 'r_6XX', 89 : 'r_ACK', 88 : 'r_INVITE', 87 : 'r_REGISTER', 86 : 'r_OPTIONS', 85 : 'r_CANCEL', 68 : 'r_UNKNOWN', 59 : 'r_401', 58 : 'r_180', } return r_dict[r_code]
6,109
Python
.py
159
27.09434
118
0.511811
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,994
replay.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/torturer/replay.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import socket import os import re import sys from protocol_logic.sip_utilities import SIPCrashDetector class TortureMessage: def __init__(self, data, name, type, is_invite=False, invite_details=[]): ''' Represents a torture message @type data: String @param data: The data of the torture message @type name: String @param name: The name of the test case @type type: String @param name: Either 'valid' or 'invalid' @type is_invite: Boolean @param is_invite: Whether the message is an INVITE or not @type invite_details: List @param invite_details: The details from the INVITE necessary to cancel it ''' self.data = data self.name = name self.type = type self.response = "" self.is_invite = is_invite self.invite_details = invite_details def get_data(self): ''' Returns the data of the torture message @rtype: String @return: The data of the torture message ''' return self.data class Dispatcher: def __init__(self, host, port, messages, proto="udp", timeout="3.0", \ crash_detection=False): ''' Handles the dispatching of a group of SIP torture messages extracted from RFC 4475 @type host: String @param host: The host to send the test messages to @type port: Integer @param port: The port to send the test messages to @type messages: Dictionary @param messages: A dictionary containing lists of valid and invalid test messages @type proto: String @param proto: (Optional, def=udp) The protocol to encapsulate the test messages in @type timeout: Float @param timeout: (Optional, def=3.0) Timeout for all socket operations @type crash_detection: Boolean @param crash_detection: (Optional, def=False) Attempt to detect crashes using OPTIONS probes or not ''' self.host = host self.port = port self.proto = proto self.messages = messages self.timeout = timeout self.last_recv = "" self.crash_detection = crash_detection if self.crash_detection: self.crash_detector = SIPCrashDetector(self.host, self.port, \ timeout) def __target_responding(self): ''' Attempts to detect if the target application has crashed using the SIPCrashDetector class ''' return self.crash_detector.is_responding() def __send(self, torture_msg): ''' Send a torture message @type torture_msg: TortureMessage @param torture_msg: The torture message to be sent ''' data = torture_msg.get_data() if self.proto == "udp": sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(self.timeout) if len(data) > 9216: print "Too much data for UDP, truncating to 9216 bytes" data = data[:9216] sock.sendto(data, (self.host, self.port)) try: self.last_recv = sock.recvfrom(4096)[0] except Exception, e: self.last_recv = "" print '[=] Response : ' + self.last_recv elif self.proto == "tcp": sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(self.timeout) sock.connect((self.host, self.port)) total_sent = 0 while total_sent < len(data): sent = sock.send(data[totalSent:]) if sent == 0: raise RuntimeError("Error on socket.send()") total_sent += sent try: self.last_recv = sock.recv(4096) except Exception, e: self.last_recv = "" def dispatch(self, type="all"): ''' Dispatch all the test messages of which match the type @type type: String @param type: (Optional, def=all) The type of messages to send. Can be 'all', 'valid' or 'invalid' ''' valid_msgs = self.messages['valid'] invalid_msgs = self.messages['invalid'] if type == "all" or type == "valid": print '[+] Sending VALID messages' for msg in valid_msgs: print '[-] Sending ' + msg.name self.__send(msg) msg.response = self.last_recv if self.crash_detection: if not self.__target_responding(): print "Possible crash detected after test" + \ msg.name raw_input("Press any key to continue testing.....") if type == "all" or type == "invalid": print '[+] Sending INVALID messages' for msg in invalid_msgs: print '[-] Sending ' + msg.name self.__send(msg) msg.response = self.last_recv if self.crash_detection: if self.__detect_crash(): print "Possible crash detected after test" + \ msg.name raw_input("Press any key to continue testing.....") class Parser: def __init__(self, directory): ''' A parser for SIP test cases. Creates TortureMessage objects and stores them in a dictionary. @type directory: String @param directory: The directory in which to search for the SIP test cases ''' self.directory = directory self.messages = {'valid' : [], 'invalid' : [], } def parse(self): ''' Parses all the files in a given directory for valid/invalid SIP test cases. The files are identified as valid/invalid based on the filename. Files that are valid should have the extension '.valid' and invalid files the extension '.invalid' @rtype: Dictionary @return: A dictionary of valid and invalid TortureMessage @todo: Extract the REGISTER tests from RFC 4475 and save them along with the other tests ''' dirList = os.listdir(self.directory) for fname in dirList: if fname.find('.svn')!= -1: continue file = open(self.directory + '/' + fname, 'r') msg = self.__extract_packet(file) file.close() # detect INVITE messages so we can CANCEL them invite_msg = False invite_details = [] ''' Comment this stuff back in for cancelling sent INVITES if msg.find('INVITE') != -1: invite_msg = True invite_details = self.__extract_invite_details(msg) ''' if fname.find('.valid') != -1: torture_msg = TortureMessage(msg, fname, 'Valid', \ invite_msg, invite_details) self.messages['valid'].append(torture_msg) elif fname.find('.invalid') != -1: torture_msg = TortureMessage(msg, fname, 'Invalid', \ invite_msg, invite_details) self.messages['invalid'].append(torture_msg) return self.messages def __extract_invite_details(self, msg): ''' Parses out the details required to cancel an invite request @type msg: String @param msg: A SIP message @rtype: List @return: A list containing the details from the SIP message requires to cancel it @todo: Fix the regex's to work on the more screwed up test messages ''' try: call_id = re.search('Call-ID\s*:\s*([\d\w@\.]+)', msg, re.IGNORECASE).group(1) uri = re.search('INVITE\s+([\d\w@\.:;-]+)\s+SIP/\d\.0', msg, re.IGNORECASE).group(1) to = re.search('To\s*:[\s*|\n |\n ](.*)', msg, re.IGNORECASE).group(1) cseq_num = re.search('Cseq\s*:\s*(\d)+', msg, re.IGNORECASE).group(1) from_ = re.search('From\s*:\s*(.*)', msg, re.IGNORECASE).group(1) except IndexError, e: return None return [uri, call_id, to, cseq_num, from_] def __extract_packet(self, file): ''' Parses the data in the file according to a set of rules to create a packet that conforms with the intentions of RFC 4475 The tags <allOneLine>, <hex> and <repeat> are parsed in accordance with RFC 4475 @type file: File @param file: A file object containing a SIP message from RFC 4475 @rtype: String @return: The parsed SIP packet ''' # strip out any whitespace from the end of lines line_list = [line.rstrip() for line in file] packet = [] x = 0 while x < len(line_list): if line_list[x] == '<allOneLine>': y = x while line_list[y] != '</allOneLine>': y += 1 x += 1 line = ''.join(line_list[x: y]) x = y + 1 else: line = line_list[x] x += 1 # the order of these parsings is important ctr = 0 while line.find('<repeat') != -1: line = self.__parse_repeat(line) while line.find('<hex>') != -1: line = self.__parse_hex(line) packet.append(line) # end of packet == \r\n\r\n packet.append('\r\n') return '\r\n'.join(packet) def __parse_hex(self, line): ''' Parses a line that contains the <hex> tag @type line: String @param line: The line containing the <hex> tag @rtype: String @return: The line with the tags removed and the string between them replaced with the correct hex digits ''' x = 0 # save these for later pre = line[:line.find('<hex')] post = line[line.find('</hex>') + 6:] line = line[line.find('<hex>') + 5:line.find('</hex>')] new_line = [] while x < len(line): # get the next two hex digits tmp = ''.join(line[x:x+2]) escaped = ('\\x' + tmp).decode('string_escape') new_line.append(escaped) x += 2 return pre + ''.join(new_line) + post def __parse_repeat(self, line): ''' Parses a line that contains the <repeat> tag @type line: String @param line: The line containing the <repeat> tag @rtype: String @return: The line with the tags removed and the string between them replaced with repeated sequence 'count' number of times ''' # save these for later pre = line[:line.find('<repeat')] post = line[line.find('</repeat>') + 9:] m = re.search('<repeat count=(\d+)>(.*?)</repeat>', line) count = int(m.group(1)) text = m.group(2) return pre + text*count + post
12,177
Python
.py
293
30.078498
96
0.563381
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,995
test_replay.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/torturer/test_replay.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' from replay import * if __name__ == '__main__': # test Parser.extract_packet() with <allOneline> and <hex> expansion test_file = open('test_files/test_extract_packet', 'r') test_contents = test_file.read() test_file.close() parser = Parser('test_files') ret = parser._Parser__extract_packet(open('rfc4475_tests/unreason.valid', 'r')) assert(ret == test_contents) # test Parser.extract_packet() with <repeat> test_file = open('test_files/test_extract_packet_repeat', 'r') test_contents = test_file.read() test_file.close() parser = Parser('test_files') ret = parser._Parser__extract_packet(open('rfc4475_tests/scalar02.invalid', 'r')) assert(ret == test_contents) # test Parser.parse() dictionary = parser.parse() test_file = open('test_files/test_extract_packet', 'r') test_contents = test_file.read() test_file.close() assert(len(dictionary['valid']) == 1) assert(dictionary['valid'][0].name == 'unreason.valid') assert(dictionary['valid'][0].data == test_contents) test_file = open('test_files/test_extract_packet_repeat', 'r') test_contents = test_file.read() test_file.close() assert(len(dictionary['invalid']) == 1) assert(dictionary['invalid'][0].name == 'scalar02.invalid') assert(dictionary['invalid'][0].data == test_contents) ''' # test Parser.__extract_invite_details test_file = open('test_files/wsinv_test', 'r') msg = test_file.read() print parser._Parser__extract_invite_details(msg) '''
2,275
Python
.py
51
40.372549
85
0.70615
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,996
__init__.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/torturer/__init__.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' __all__ = ['replay']
733
Python
.py
16
44.5
68
0.794944
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,997
fuzzers.py
pwnieexpress_raspberry_pwn/src/pentest/voiper/fuzzer/fuzzers.py
''' This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com ''' import sys import os import string import time # modify import path instead of adding a __init__.py as I want to keep # a the Sulley install as unmodified as possible to facilitate easy updating # if there are changes to it. # Props to Pedram Amini and Aaron Portnoy for creating such a great framework sys.path.append(''.join([os.getcwd(), '/sulley'])) from random import Random from protocol_logic.sip_agent import T_COMPLETE_OK from protocol_logic.sip_utilities import SIPCrashDetector from protocol_logic.sip_utilities import SIPInviteCanceler from protocol_logic import sip_parser from misc.utilities import Logger from fuzzer_parents import AbstractFuzzer from fuzzer_parents import AbstractSIPFuzzer from fuzzer_parents import AbstractSIPInviteFuzzer from socket import * from sulley import * ################################################################################ class Callable: def __init__(self, anycallable): ''' Wrapper class so I can have unbound class methods. Apparently python doesn't allow these by default. This code/idiom came from some standard example on the Interwebs ''' self.__call__ = anycallable class SIPInviteStructureFuzzer(AbstractSIPInviteFuzzer): ''' Fuzz the structure of an INVITE request e.g repeats, line folding etc ''' def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("INVITE_STRUCTURE"), callback=self.generate_unique_attributes) self.sess.fuzz() def info(self=None): h = ["Name: SIPInviteStructureFuzzer\n", "Protocol: SIP\n", "Success Factor: Low\n", "Fuzzes the structure of a SIP request by repeating blocks, fuzzing delimiters and ", "generally altering how a SIP request is structured", ] return ''.join(h) info = Callable(info) class SIPInviteRequestLineFuzzer(AbstractSIPInviteFuzzer): def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("INVITE_REQUEST_LINE"), callback=self.generate_unique_attributes) self.sess.fuzz() def info(self=None): h = ["Name: SIPInviteRequestLineFuzzer\n", "Protocol: SIP\n", "Success Factor: Low\n", "Extensively tests the first line of an INVITE request by including all valid parts ", "specified in SIP RFC 3375" ] return ''.join(h) info = Callable(info) class SIPInviteCommonFuzzer(AbstractSIPInviteFuzzer): def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("INVITE_COMMON"), callback=self.generate_unique_attributes) self.sess.fuzz() def info(self=None): h = ["Name: SIPInviteCommonFuzzer\n", "Protocol: SIP\n", "Success Factor: High\n", "Fuzzes the headers commonly found and most likely to be processed in a SIP INVITE request\n" ] return ''.join(h) info = Callable(info) class SIPInviteOtherFuzzer(AbstractSIPInviteFuzzer): def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("INVITE_OTHER"), callback=self.generate_unique_attributes) self.sess.fuzz() def info(self=None): h = ["Name: SIPInviteOtherFuzzer\n", "Protocol: SIP\n", "Success Factor: Low\n", "Tests all other headers specified as part of an INVITE besides those found in the ", "SIPInviteCommonFuzzer. Many of these are seemingly unparsed and ignored by a lot of devices.\n" ] return ''.join(h) info = Callable(info) class SDPFuzzer(AbstractSIPInviteFuzzer): ''' Extends the Abstract INVITE fuzzer because it requires the INVITE cancelling functionality. Fuzzes the SDP content of an INVITE. ''' def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("SDP"), callback=self.generate_unique_attributes) self.sess.fuzz() def info(self=None): h = ["Name: SDPFuzzer\n", "Protocol: SDP\n", "Success Factor: High\n", "Fuzzes the SDP protocol as part of a SIP INVITE\n" ] return ''.join(h) info = Callable(info) class SIPDumbACKFuzzer(AbstractSIPFuzzer): ''' A dumb ACK fuzzer that doesn't wait for any kind of responses or what not. ''' def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("ACK"), callback=self.generate_unique_attributes) self.sess.fuzz() def info(self=None): h = ["Name: SIPDumbACKFuzzer\n", "Protocol: SIP\n", "Success Factor: Unknown\n", "A dumb ACK fuzzer with no transaction state awareness. \n", ] return ''.join(h) info = Callable(info) class SIPDumbCANCELFuzzer(AbstractSIPFuzzer): ''' A dumb CANCEL fuzzer that doesn't wait for any kind of responses or what not. ''' def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("CANCEL"), callback=self.generate_unique_attributes) self.sess.fuzz() def info(self=None): h = ["Name: SIPDumbCANCELFuzzer\n", "Protocol: SIP\n", "Success Factor: Unknown\n", "A dumb CANCEL request fuzzer with no transaction state awareness\n", ] return ''.join(h) info = Callable(info) class SIPDumbREGISTERFuzzer(AbstractSIPFuzzer): def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("REGISTER"), callback=self.generate_unique_attributes) self.sess.fuzz() def info(self=None): h = ["Name: SIPDumbREGISTERFuzzer\n", "Protocol: SIP\n", "Success Factor: Unknown\n", "A dumb REGISTER request fuzzer with no transaction state awareness\n", ] return ''.join(h) info = Callable(info) class SIPSUBSCRIBEFuzzer(AbstractSIPFuzzer): def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("SUBSCRIBE"), callback=self.generate_unique_attributes) self.sess.fuzz() def info(self=None): h = ["Name: SIPSUBSCRIBEFuzzer\n", "Protocol: SIP\n", "Success Factor: Unknown\n", "A fuzzer for the SUBSCRIBE SIP verb\n", ] return ''.join(h) info = Callable(info) class SIPNOTIFYFuzzer(AbstractSIPFuzzer): def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("NOTIFY"), callback=self.generate_unique_attributes) self.sess.fuzz() def info(self=None): h = ["Name: SIPNOTIFYFuzzer\n", "Protocol: SIP\n", "Success Factor: Unknown\n", "A fuzzer for the NOTIFY SIP verb\n", ] return ''.join(h) info = Callable(info) class SIPACKFuzzer(AbstractSIPFuzzer): def fuzz(self): self.invite_cancel_dict = { sip_parser.r_SEND : (self.invite.process, {sip_parser.r_1XX : (self.cancel.process, {sip_parser.r_4XX : (None, None), sip_parser.r_5XX : (None, None), sip_parser.r_6XX : (None, None), sip_parser.r_2XX : (None, None), } ) } ) } self.pre_send_functions.append(self.invite_cancel) self.sess.add_target(self.target) self.sess.connect(s_get("ACK"), callback=self.generate_unique_attributes) self.sess.fuzz() def info(self=None): h = ["Name: SIPACKFuzzer\n", "Protocol: SIP\n", "Success Factor: Unknown\n", "A fuzzer for the ACK SIP verb that first attempts to manipulate the target device into a state where it would expect an ACK\n", ] return ''.join(h) info = Callable(info) def invite_cancel(self, sock): result = None while result != T_COMPLETE_OK: result, self.curr_invite_branch = self.sip_agent.process_transaction( self.invite_cancel_dict, self.response_q, self.request_q, {'user' : self.user, 'target_user' : self.target_user, 'host' : self.host, 'port' : self.port} ) if result != T_COMPLETE_OK: print >>sys.stderr, 'Invite cancel for ACK fuzz didnt complete. Trying again' time.sleep(.2) ''' class SDPEncodedFuzzer(AbstractSIPInviteFuzzer): def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("SDP_ENCODED"), callback=self.generate_unique_attributes) self.sess.fuzz() class OptionsFuzzer(AbstractSIPFuzzer): def fuzz(self): self.sess.add_target(self.target) self.sess.connect(s_get("OPTIONS"), callback=self.generate_unique_attributes) self.sess.fuzz() ''' ################################################################################
10,273
Python
.py
244
32.413934
141
0.620098
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,998
fuzzers.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/fuzzer/fuzzers.pyc
Ñò âпMc@sdZddkZddkZddkZddkZeiidieiƒdgƒƒddk l Z ddk l Z ddk lZddk lZdd klZdd klZdd klZdd klZdd klZddkTddkTdd'd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZdefd„ƒYZ defd„ƒYZ!defd „ƒYZ"d!efd"„ƒYZ#d#efd$„ƒYZ$d%efd&„ƒYZ%dS((sÀ This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com iÿÿÿÿNts/sulley(tRandom(t T_COMPLETE_OK(tSIPCrashDetector(tSIPInviteCanceler(t sip_parser(tLogger(tAbstractFuzzer(tAbstractSIPFuzzer(tAbstractSIPInviteFuzzer(t*tCallablecBseZd„ZRS(cCs ||_dS(sÇ Wrapper class so I can have unbound class methods. Apparently python doesn't allow these by default. This code/idiom came from some standard example on the Interwebs N(t__call__(tselft anycallable((s!/pentest/voiper/fuzzer/fuzzers.pyt__init__1s(t__name__t __module__R(((s!/pentest/voiper/fuzzer/fuzzers.pyR 0stSIPInviteStructureFuzzercBs/eZdZd„Zdd„ZeeƒZRS(sO Fuzz the structure of an INVITE request e.g repeats, line folding etc cCsC|ii|iƒ|iitdƒd|iƒ|iiƒdS(NtINVITE_STRUCTUREtcallback(tsesst add_targetttargettconnectts_gettgenerate_unique_attributestfuzz(R ((s!/pentest/voiper/fuzzer/fuzzers.pyR=scCs"dddddg}di|ƒS(NsName: SIPInviteStructureFuzzer sProtocol: SIP sSuccess Factor: Low sRFuzzes the structure of a SIP request by repeating blocks, fuzzing delimiters and s2generally altering how a SIP request is structuredR(tjoin(R th((s!/pentest/voiper/fuzzer/fuzzers.pytinfoBs  N(RRt__doc__RtNoneRR (((s!/pentest/voiper/fuzzer/fuzzers.pyR9s  tSIPInviteRequestLineFuzzercBs)eZd„Zdd„ZeeƒZRS(cCsC|ii|iƒ|iitdƒd|iƒ|iiƒdS(NtINVITE_REQUEST_LINER(RRRRRRR(R ((s!/pentest/voiper/fuzzer/fuzzers.pyRNscCs"dddddg}di|ƒS(Ns!Name: SIPInviteRequestLineFuzzer sProtocol: SIP sSuccess Factor: Low sSExtensively tests the first line of an INVITE request by including all valid parts sspecified in SIP RFC 3375R(R(R R((s!/pentest/voiper/fuzzer/fuzzers.pyRSs  N(RRRR RR (((s!/pentest/voiper/fuzzer/fuzzers.pyR!Ms  tSIPInviteCommonFuzzercBs)eZd„Zdd„ZeeƒZRS(cCsC|ii|iƒ|iitdƒd|iƒ|iiƒdS(Nt INVITE_COMMONR(RRRRRRR(R ((s!/pentest/voiper/fuzzer/fuzzers.pyR_scCsddddg}di|ƒS(NsName: SIPInviteCommonFuzzer sProtocol: SIP sSuccess Factor: High sZFuzzes the headers commonly found and most likely to be processed in a SIP INVITE request R(R(R R((s!/pentest/voiper/fuzzer/fuzzers.pyRds  N(RRRR RR (((s!/pentest/voiper/fuzzer/fuzzers.pyR#^s  tSIPInviteOtherFuzzercBs)eZd„Zdd„ZeeƒZRS(cCsC|ii|iƒ|iitdƒd|iƒ|iiƒdS(Nt INVITE_OTHERR(RRRRRRR(R ((s!/pentest/voiper/fuzzer/fuzzers.pyRoscCs"dddddg}di|ƒS(NsName: SIPInviteOtherFuzzer sProtocol: SIP sSuccess Factor: Low sRTests all other headers specified as part of an INVITE besides those found in the s]SIPInviteCommonFuzzer. Many of these are seemingly unparsed and ignored by a lot of devices. R(R(R R((s!/pentest/voiper/fuzzer/fuzzers.pyRts  N(RRRR RR (((s!/pentest/voiper/fuzzer/fuzzers.pyR%ns  t SDPFuzzercBs/eZdZd„Zdd„ZeeƒZRS(sŽ Extends the Abstract INVITE fuzzer because it requires the INVITE cancelling functionality. Fuzzes the SDP content of an INVITE. cCsC|ii|iƒ|iitdƒd|iƒ|iiƒdS(NtSDPR(RRRRRRR(R ((s!/pentest/voiper/fuzzer/fuzzers.pyR…scCsddddg}di|ƒS(NsName: SDPFuzzer sProtocol: SDP sSuccess Factor: High s0Fuzzes the SDP protocol as part of a SIP INVITE R(R(R R((s!/pentest/voiper/fuzzer/fuzzers.pyRŠs  N(RRRRR RR (((s!/pentest/voiper/fuzzer/fuzzers.pyR's  tSIPDumbACKFuzzercBs/eZdZd„Zdd„ZeeƒZRS(sX A dumb ACK fuzzer that doesn't wait for any kind of responses or what not. cCsC|ii|iƒ|iitdƒd|iƒ|iiƒdS(NtACKR(RRRRRRR(R ((s!/pentest/voiper/fuzzer/fuzzers.pyR™scCsddddg}di|ƒS(NsName: SIPDumbACKFuzzer sProtocol: SIP sSuccess Factor: Unknown s8A dumb ACK fuzzer with no transaction state awareness. R(R(R R((s!/pentest/voiper/fuzzer/fuzzers.pyRžs  N(RRRRR RR (((s!/pentest/voiper/fuzzer/fuzzers.pyR)”s  tSIPDumbCANCELFuzzercBs/eZdZd„Zdd„ZeeƒZRS(s[ A dumb CANCEL fuzzer that doesn't wait for any kind of responses or what not. cCsC|ii|iƒ|iitdƒd|iƒ|iiƒdS(NtCANCELR(RRRRRRR(R ((s!/pentest/voiper/fuzzer/fuzzers.pyR­scCsddddg}di|ƒS(NsName: SIPDumbCANCELFuzzer sProtocol: SIP sSuccess Factor: Unknown sAA dumb CANCEL request fuzzer with no transaction state awareness R(R(R R((s!/pentest/voiper/fuzzer/fuzzers.pyR²s  N(RRRRR RR (((s!/pentest/voiper/fuzzer/fuzzers.pyR+¨s  tSIPDumbREGISTERFuzzercBs)eZd„Zdd„ZeeƒZRS(cCsC|ii|iƒ|iitdƒd|iƒ|iiƒdS(NtREGISTERR(RRRRRRR(R ((s!/pentest/voiper/fuzzer/fuzzers.pyR¾scCsddddg}di|ƒS(NsName: SIPDumbREGISTERFuzzer sProtocol: SIP sSuccess Factor: Unknown sCA dumb REGISTER request fuzzer with no transaction state awareness R(R(R R((s!/pentest/voiper/fuzzer/fuzzers.pyRÃs  N(RRRR RR (((s!/pentest/voiper/fuzzer/fuzzers.pyR-¼s  tSIPSUBSCRIBEFuzzercBs)eZd„Zdd„ZeeƒZRS(cCsC|ii|iƒ|iitdƒd|iƒ|iiƒdS(Nt SUBSCRIBER(RRRRRRR(R ((s!/pentest/voiper/fuzzer/fuzzers.pyRÏscCsddddg}di|ƒS(NsName: SIPSUBSCRIBEFuzzer sProtocol: SIP sSuccess Factor: Unknown s$A fuzzer for the SUBSCRIBE SIP verb R(R(R R((s!/pentest/voiper/fuzzer/fuzzers.pyRÔs  N(RRRR RR (((s!/pentest/voiper/fuzzer/fuzzers.pyR/Ís  tSIPNOTIFYFuzzercBs)eZd„Zdd„ZeeƒZRS(cCsC|ii|iƒ|iitdƒd|iƒ|iiƒdS(NtNOTIFYR(RRRRRRR(R ((s!/pentest/voiper/fuzzer/fuzzers.pyRàscCsddddg}di|ƒS(NsName: SIPNOTIFYFuzzer sProtocol: SIP sSuccess Factor: Unknown s!A fuzzer for the NOTIFY SIP verb R(R(R R((s!/pentest/voiper/fuzzer/fuzzers.pyRås  N(RRRR RR (((s!/pentest/voiper/fuzzer/fuzzers.pyR1Þs  t SIPACKFuzzercBs2eZd„Zdd„ZeeƒZd„ZRS(cCs³h|iih|iihdti6dti6dti6dti6fti 6fti 6|_ |i i |iƒ|ii|iƒ|iitdƒd|iƒ|iiƒdS(NR*R(NN(NN(NN(NN(tinvitetprocesstcancelR Rtr_4XXtr_5XXtr_6XXtr_2XXtr_1XXtr_SENDtinvite_cancel_dicttpre_send_functionstappendt invite_cancelRRRRRRR(R ((s!/pentest/voiper/fuzzer/fuzzers.pyRñs     $cCsddddg}di|ƒS(NsName: SIPACKFuzzer sProtocol: SIP sSuccess Factor: Unknown s|A fuzzer for the ACK SIP verb that first attempts to manipulate the target device into a state where it would expect an ACK R(R(R R((s!/pentest/voiper/fuzzer/fuzzers.pyRs  cCsŸd}x’|tjo„|ii|i|i|ih|id6|id6|i d6|i d6ƒ\}|_ |tjot i dIJtidƒq q WdS(Ntusert target_userthosttports7Invite cancel for ACK fuzz didnt complete. Trying againgš™™™™™É?(R Rt sip_agenttprocess_transactionR=t response_qt request_qRARBRCRDtcurr_invite_branchtsyststderrttimetsleep(R tsocktresult((s!/pentest/voiper/fuzzer/fuzzers.pyR@s       N(RRRR RR R@(((s!/pentest/voiper/fuzzer/fuzzers.pyR3ïs   ((&RRJtoststringRLtpathR?RtgetcwdtrandomRtprotocol_logic.sip_agentRtprotocol_logic.sip_utilitiesRRtprotocol_logicRtmisc.utilitiesRtfuzzer_parentsRRR tsockettsulleyR RR!R#R%R'R)R+R-R/R1R3(((s!/pentest/voiper/fuzzer/fuzzers.pyt<module>s:    %   <
12,387
Python
.py
94
129.914894
822
0.46249
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
19,999
__init__.pyc
pwnieexpress_raspberry_pwn/src/pentest/voiper/fuzzer/__init__.pyc
—Ú ‚–øMc@sdZddgZdS(s¿ This file is part of VoIPER. VoIPER is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. VoIPER is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VoIPER. If not, see <http://www.gnu.org/licenses/>. Copyright 2008, http://www.unprotectedhex.com Contact: nnp@unprotectedhex.com tfuzzerstfuzzer_parentsN(t__doc__t__all__(((s"/pentest/voiper/fuzzer/__init__.pyt<module>s
905
Python
.py
16
55.3125
139
0.717833
pwnieexpress/raspberry_pwn
1,024
184
8
GPL-3.0
9/5/2024, 5:12:22 PM (Europe/Amsterdam)