def GetMOSDEFlibc(os, proc=None, version=None): import sys global __MOSDEFlibc_cache if proc: proc = proc.lower() if proc not in __procfamily_table.keys(): for procfamily in __procfamily_table.keys(): if proc in __procfamily_table[procfamily]: proc = procfamily break if proc in __procname_table.keys(): proc = __procname_table[proc] sysnamekey = "%s_%s_%s" % (os, proc, version) if __MOSDEFlibc_cache.has_key(sysnamekey): #print "returning %s from cache" % sysnamekey, __MOSDEFlibc_cache[sysnamekey] return __MOSDEFlibc_cache[sysnamekey] old_path = sys.path # TODO: fix sys.path here sys.path = ['MOSDEFlibc', 'MOSDEF/MOSDEFlibc'] + old_path sysname = os if proc: sysname += '_' + proc else: proc = "Generic" devlog("MOSDEFLibC", "Importing %s.%s" % (os, sysname)) libc = getattr(__import__(os), sysname)(version) setattr(libc, "_names", {'os': os, 'proc': proc, 'version': version}) sys.path = old_path libc.postinit() libc.initStaticFunctions() __MOSDEFlibc_cache[sysnamekey] = libc return libc
def handle(self): if self.clientsock == None: devlog("smbserver", "ERROR: Trying to handle, but no client socket") return 0 devlog("smbserver", "Attempting to handle a request from the client") try: data = recvnetbios_server(self.clientsock) except IndexError: devlog("smbserver", "Connection closed.") return 0 except AssertionError: devlog("smbserver", "Connection closed.") return 0 except timeoutsocket.Timeout: devlog("smbserver", "timeout while waiting for query") self.clientsock.close() return 0 except: import traceback traceback.print_exc(file=sys.stdout) self.clientsock.close() return 0 self.respond_to_netbios_request(data) return 1
def run_module(self, args, spawn=False): devlog("cli", "Run module: %s"%repr(args)) try: # flush engine log to clear pending output self.rpc.proxy.flush_log() sys.stdout.write('[+] Running module: %s\n' % args[1]) # spawns a thread for the module in the engine i = self.rpc.proxy.run_module(args[1], ' '.join(args[2:])) if not spawn: # polls the thread to see if it's done yet(tm) thread_done = False while thread_done == False: thread_done = self.rpc.proxy.poll_commandline_thread(i) if thread_done == False: time.sleep(0.1) sys.stdout.flush() sys.stdout.write('[+] Done running module\n') else: sys.stdout.write('[+] Spawned module: %s\n'%i) except xmlrpclib.Fault: import traceback traceback.print_exc(file=sys.stderr) return
def node_removal(self, node): """ Takes a GAPHAS node, finds all its children & connectors, removes them from the GAPHAS canvas, and cleans up all the dictionaries etc where they are registered """ ##Find all the gaphas items children and connectors, remove from the ## gaphas canvas and pass back a list of canvasNodes for the caller to ## remove from the engine children_to_kill = self.find_node_children(node) for item in children_to_kill: self.gaphas_view.canvas.remove(item) try: ##remove from canvas to gaphas mapping dictionary del self.node_to_ui_obj_dict[item.node.getname()] except AttributeError: ##Connector lines have no node attribute so just skip pass except KeyError: ##can't find that item? devlog( "gui", "Could not find item to delete: %s" % item.node.getname()) pass ##If that node was currently selected AND there was no other node ## selected we should selected localNode if len(self.gaphas_view.selected_items) == 0: self.gaphas_view.select_item(self.lNode)
def runcommand(self,command): """ Running a command is easy with a shell """ result="" command = command.strip() if command[ len(command)-1 ] == ";": command = command[: len(command)-1 ] try: resp = self.m.query("xp_cmdshell \"%s\"" % command) if not resp: #returns an empty string on failure #typically, recv failed return "Failed to get SQL Command Executed" for a in resp.tokens: if a[0] == 0xd1: result+= str(a[1]) + "\n" elif a[0] == 0xAA: result=a[1][3] elif a[0] == 0x81: #TDS 7+ results #tds results... print "Token type 0x81" result=a[1][-1] else: devlog("mssql", "Token type not needed %x"%a[0]) except mssql.MSSQLError, msg: result=str(msg)
def normalizergb(x, y, data, alpha=3): """ Windows screengrabs are in BGRA order, and need to be flipped Set alpha=3 for no alpha, 4 for alpha """ #can't do self.log here #print "Normalizing RGB for win32" ret = [] length = len(data) if length % alpha != 0: devlog("screengrab", "Very strange - is not mod %s clean!" % alpha) for i in range(0, y): #for each scanline for j in range(0, x): #for each pixel #print "Doing: %s:%s"%(i,j) b = data[x * i * alpha + alpha * j + 0] g = data[x * i * alpha + alpha * j + 1] r = data[x * i * alpha + alpha * j + 2] ret += [r, g, b] data = "".join(ret) #print "Returning %s"%len(data) return data
def move_nodeui_to_absolute(self, node_ui, new_x, new_y): """ Moves a NodeUI to an absolute place in the View TODO: Should this really be using the canvas.get_matrix_i2c() ? There's some confusion in my head regarding whether we want to use gaphas view projections or gaphas canvas projections. Right now we use gaphas view projections, but this seems to be less correct. """ isinstance(node_ui, NodeItem) #help WingIDE devlog( "gui", "Absolute move of %s requested to %s, %s" % (node_ui.node.getname(), new_x, new_y)) i2v = self.gaphas_view.get_matrix_i2v(node_ui) x, y = i2v.transform_point(0, 0) devlog( "gui", "Node %s moving from: x=%s, y=%s" % (node_ui.node.getname(), x, y)) node_ui.matrix.translate(-x, -y) #move me to origin node_ui.matrix.translate(new_x, new_y) #move me to where I need to go ##update and show this node (queued requests are delayed gratification ##here, so we go for immediate action) self.gaphas_view.canvas.request_update(node_ui) node_ui.x_pos = new_x node_ui.y_pos = new_y
def parse_argv(self, argv=None): """ only longopt for now. --opt -> opt=True --opt=a -> opt=a --no-opt -> opt=False """ if argv == None: import sys argv = sys.argv[1:] if type(argv) == type(""): # dangerous? argv = argv.split(' ') assert type(argv) == type( []), "expecting a list for argv, got %s" % type(argv) for arg in argv: val = True name = arg[2:] if name[:3] == 'no-': val = False name = name[3:] if '=' in name: s = name.split('=') name = s[0] val = s[1] if val in ['no', 'False']: val = False devlog('Config::ParseArgv', "%s: %s" % (name, val)) self.__setitem__(name, val)
def getprocaddress(self, functionspec): """ emulate getprocaddress from windows functionspec can be of the form 'library|symbol' or 'symbol' we detect this and dispatch accordingly return address of function if found or throw exception otherwise """ devlog("unix", "getprocaddress: %s" % functionspec) try: functionkey = self.remotefunctioncache[functionspec] except KeyError: functionkey = False if functionkey: devlog("unix", "Returning Cached value for %s->%x" % (functionspec, functionkey)) return functionkey self.log("%s not in cache - retrieving remotely." % functionspec) tokens = functionspec.split('|') tokens_size = len(tokens) if tokens_size == 1: # Simple symbol resolution return self.getprocaddress_real(None, functionspec) elif tokens_size == 2: # Library load + symbol resolution return self.getprocaddress_real(tokens[0], tokens[1]) else: raise ResolveException('malformed function specifier %s in getprocaddress()' % functionspec)
def handle_command_line(self, line): command = line.split(' ') if command[0].upper() not in self.commands: return False else: # checks for matching amount of args, -1 means variable n args if self.commands[command[0].upper()][1][0] != -1: if len(command) - 1 not in self.commands[command[0].upper()][1]: sys.stdout.write('Usage: ' + command[0].upper() + ' ' +\ self.commands[command[0].upper()][0] + '\n') return False else: # variable command args with no args ... dump usage if not len(command) - 1: sys.stdout.write('Usage: ' + command[0].upper() + ' ' +\ self.commands[command[0].upper()][0] + '\n') return False # call the handler for that command # handlers are responsible for type conversion try: devlog("cli", "Running command: %s"%command[0].upper()) self.commands[command[0].upper()][2](command) except socket.error: sys.stdout.write('[+] Failed to connect to RPC Server!\n') return False except: import traceback traceback.print_exc(file=sys.stderr) sys.stdout.write('[+] Check your command please\n') return False return True
def connect(self, addr, port=None, dumbhack=None): # In case we were called as connect(host, port) if port != None: addr = (addr, port) # Shortcuts sock = self._sock timeout = self._timeout blocking = self._blocking # First, make a non-blocking call to connect try: sock.setblocking(0) devlog('TimeoutSocket::connect', "addr: %s" % str(addr)) sock.connect(addr) sock.setblocking(blocking) return except Error, why: devlog('TimeoutSocket::connect', "error: %s" % str(why)) # Set the socket's blocking mode back sock.setblocking(blocking) # If we are not blocking, re-raise if not blocking: raise # If we are already connected, then return success. # If we got a genuine error, re-raise it. errcode = why[0] if dumbhack and errcode in _IsConnected: return elif errcode not in _ConnectBusy: raise
def view_hosts_knowledge(self, host): """ Show all of the knowledge a node knows about a hosts in a pretty pop up window """ knowledge = self.node.hostsknowledge.get_known_host(host.interface) if knowledge: kb = knowledge.get_all_knowledge_as_text() dname = "all_knowledge_dialog" wTree2 = gtk_glade_hook.XML(get_glade_file(), dname) tBuf = gtk.TextBuffer() tBuf.set_text(kb) dialog = wTree2.get_widget(dname) dialog.set_title("All knowledge about host %s from %s" % (host.interface, self.name)) ##UPDATE TITLE WITallH HOST IP kb_display = wTree2.get_widget("kb_txt") kb_display.set_buffer(tBuf) response = dialog.run() dialog.destroy() return else: devlog("gui", "No knowledge to show :( ")
def startup(self): """ Returns True on successful startup. """ if self.exploit: devlog("rtsp","Using canvas exploit to set up listener on port %d"%self.port) if self.protocol=="TCP": self.listen_sock=self.exploit.gettcplistener(self.port) elif self.protocol=="UDP": self.listen_host=self.exploit.getudplistener(self.port) if not self.listen_sock: self.log("Failed to listen on that port") return False else: self.listen_sock=socket.socket() self.listen_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) try: self.listen_sock.bind((self.listen_host,self.port)) self.listen_sock.listen(5) except socket.error, msg: self.listen_sock.close() self.log("Could not listen on that host:port: %s:%d - %s"%(self.listen_host,self.port,msg)) #import traceback #traceback.print_exc() return False
def __getitem__(self, *kargs): value = False name = kargs[0] if type(name) == type(()): name, value = name[:2] if DictType.__contains__(self, name): value = DictType.__getitem__(self, name) devlog('Config::GetItem', "%s = %s" % (name, value)) return value
def canvas_push(self, line): devlog("cli", "CANVAS_PUSH: %s"%line) line = line.lstrip() #remove spaces off the front (this confuses CANVAS) self.buffer.append(line) source = '\n'.join(self.buffer) more = self.runscript(source) if not more: self.resetbuffer() return more
def smbclose(self, header, params, body): devlog("smbserver", "smb close") flags = 0x88 flags2 = 0xc001 params = "" data = "" self.sendsmb(SMB_CLOSE, SMB_SUCCESS, flags, flags2, self.tid, self.mid, params, data) return 1
def trans2(self, header, params, body): devlog("smbserver", "trans2") flags = 0x88 flags2 = 0xc001 outparams = "" outdata = "" cmd = header[1] wordcount = header[10] paramstring = "<HHHHBBHLHHHHHBBH" paramsize = struct.calcsize(paramstring) #print "Paramsize=%d len params=%d"%(paramsize,len(params)) #print "Params=%s"%hexprint(params) tup = struct.unpack(paramstring, params[:paramsize]) (totalparamcount, totaldatacount, maxparamcount, maxdatacount, maxsetupcount, _, trans2flags, timeout, _, paramcount, paramoffset, datacount, dataoffset, setupcount, _, subcommand) = tup realparamoffset = paramoffset - 33 - wordcount * 2 realparams = body[realparamoffset:realparamoffset + paramcount] #print "realparams=%s"%hexprint(realparams) realdataoffset = paramoffset + dataoffset #??? #need to strip off the body count and the padding here... realdataoffset += 3 #TODO: see if this is always true. realdata = body[realdataoffset:realdataoffset + datacount] #print "realdata=%s"%hexprint(realdata) success, outparams, outdata = self.trans2_response_functions[ subcommand](tup, realparams, realdata) outsetup = "" totalparamcount = len(outparams) totaldatacount = len(outdata) reserved = 0 timeout = 0 paramcount = len(outparams) setupcount = len(outsetup) paramoffset = 56 + setupcount paramdisplacement = 0 datadisplacement = 0 dataoffset = paramoffset + paramcount datacount = len(outdata) paramfs = "<HHHHHHHHHBB" padnum = 0 padding = "\x00" * padnum tup = (totalparamcount, totaldatacount, reserved, paramcount, paramoffset, paramdisplacement, datacount, dataoffset, datadisplacement, setupcount, reserved) params = struct.pack(paramfs, *tup) self.sendsmb(cmd, success, flags, flags2, self.tid, self.mid, params, padding + outparams + outsetup + outdata) return 1
def getString(self, data): devlog("mssql", "getString: %s" % prettyprint(data[:20])) length = ord(data[0]) try: text = data[1:1 + length * 2] except IndexError: raise MSSQLError, "Error parsing a 8bit length -> string field" return (length * 2 + 1, text)
def checkdirectory(self, header, params, body): devlog("smbserver", "Sessionsetup") flags = 0x88 flags2 = 0xc001 params = "" data = "" self.sendsmb(SMB_CHECK_DIRECTORY, SMB_SUCCESS, flags, flags2, self.tid, self.mid, params, data) return 1
def treedisconnect(self, header, params, body): cmd = header[1] flags = 0x88 flags2 = 0xc001 params = "" data = "" devlog("smbserver", "tree disconnect") self.sendsmb(cmd, SMB_SUCCESS, flags, flags2, self.tid, self.mid, params, data) return 1
def close(self): """ close the listening fd. """ if self.s: self.s.close() else: devlog("smbserver", "smb server close() called but no socket to close!") return
def respond_to_netbios_request(self, data): """Respond to a packet""" devlog("smbserver", "Responding to netbios request") if ord(data[0]) == NETBIOS_SESSION_REQUEST: #we have to respond to a session request if we are on port 139 devlog("smbserver", "Session request ... responding with success") netbiosresponse = "\x82" + "\x00" * 3 #simple self.clientsock.sendall(netbiosresponse) else: #just handle the smb request now... self.respond_to_smb_request(data[4:])
def set_file_data(self, name, data): """any file you retrieve from the server with a particular name is this file""" devlog("smbserver", "Got data for filename: %s" % name) name = normalize_file(name) #add directories: directory = "\\".join(name.split("\\")[:-1]) self.directories[directory] = True devlog("smbserver", "Set directory information on %s = true" % directory) self.files[normalize_file(name.split("\\")[-1])] = data return
def get_menu(self): devlog("listenerLine", "Listener ArgsDict=%s" % self.argsDict) if self.busy != 0: busy = ["Clear busy flag"] else: busy = [] return [ "Set as current listener", "Check for connection", "Kill Listener" ] + busy
def load_configfile(self, filename = ConfigFile): devlog('Config::ParseFile', "parsing file %s" % filename) try: fd = file(filename) except IOError: #failed to open CANVAS.conf print "Could not open CANVAS.conf!" return for line in fd.readlines(): self.__parse_configline(line, 'Config::ParseFile') fd.close()
def query(self, data): try: data = UrlTokenEncode(data) response = spkproxy.urlopen(self.url + data) if self.detect(response) == 1: devlog('oracle', self.url + data) return 1 return 0 except Exception: return 0
def echo(self, header, params, body): devlog("smbserver", "Echo called") cmd = header[1] wordcount = header[10] data = body flags = 0x88 flags2 = 0xc001 echocount = struct.unpack("<H", params)[0] echodata = data * echocount self.sendsmb(cmd, SMB_SUCCESS, flags, flags2, self.tid, self.mid, "", echodata) return 1
def query(self, sql_txt): """ Returns a Response() instance or an empty string (on failure) """ q = Query() q.setQuery(sql_txt) devlog("mssql", "Query: %s" % prettyprint(sql_txt)) self.s.send(q.raw()) resp = self.get_response() #resp is an instance, not a string #devlog("mssql","Response: %s"%prettyprint(resp)) return resp
def connect(self): if self.exploit: self.s = self.exploit.gettcpsock() else: self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) try: self.s.connect((self.hostname, self.port)) except: devlog("PJLDevice", "Connect Error") return None return 1
def on_button_press(self, event): """ Overide the default click handler for the tool """ devlog("gui", "on_button_press in nodeview. Event.button=%s" % event.button) view = self.view ##What Node has been clicked in our display - gaphas does all the co-ordinate mapping for us !! YAY cNode = view.get_item_at_point((event.x, event.y)) ##cNode == None indicates the underlying gaphas canvas has been clicked if not cNode: del view.selected_items return True ##We do not want to select the connector items if getattr(cNode, "is_connector", False): return False if event.button in self._buttons: ##This is our left click event - we call into the prebuilt gaphas tool for our selection stuff and then call the leftclick handler ## of our node object to convey selection/deselection up into the CANVAS engine ##select / move node - call into the ItemTool super class for this ret = super(MenuTool, self).on_button_press(event) if len(view.selected_items) == 1: ##Single node selected (left click on node) for n in view.selected_items: cNode.select_single_node(n) elif cNode not in view.selected_items: ##Single node UNselected (ctrl left click on node that was previously selected) cNode.deselect_node() else: ##Multiple nodes selected (ctrl left click on node that was previously UNselected while another node was also already selected) for n in view.selected_items: n.append_nodes() view.queue_draw_refresh() return ret elif event.button == 3: ##right click menu cNode.right_click(event, cNode) return True return False