Example #1
0
def check_for_stored_sessions(url, http_request_method):

  if not menu.options.ignore_session:
    if os.path.isfile(settings.SESSION_FILE) and not settings.REQUIRED_AUTHENTICATION:
      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
        return True

  if menu.options.flush_session:
    session_handler.flush(url)        
Example #2
0
def check_for_stored_sessions(url, http_request_method):

    if not menu.options.ignore_session:
        if os.path.isfile(settings.SESSION_FILE
                          ) and not settings.REQUIRED_AUTHENTICATION:
            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
                return True

    if menu.options.flush_session:
        session_handler.flush(url)
Example #3
0
def main(filename, url):

    try:
        # Ignore the mathematic calculation part (Detection phase).
        if menu.options.skip_calc:
            settings.SKIP_CALC = True

        if menu.options.enable_backticks:
            settings.USE_BACKTICKS = True

        # Target URL reload.
        if menu.options.url_reload and menu.options.data:
            settings.URL_RELOAD = True

        if menu.options.header is not None and settings.INJECT_TAG in menu.options.header or \
           menu.options.headers is not None and settings.INJECT_TAG in menu.options.headers:
            info_msg = "Injection marker found in option '--header(s)/--user-agent/--referer/--cookie'."
            print(settings.print_info_msg(info_msg))
            if menu.options.test_parameter:
                err_msg = "The options '-p' and the injection marker cannot be used "
                err_msg += "simultaneously (i.e. only one option must be set)."
                print(settings.print_critical_msg(err_msg))
                raise SystemExit

        if menu.options.test_parameter and menu.options.skip_parameter:
            if type(menu.options.test_parameter) is bool:
                menu.options.test_parameter = None
            else:
                err_msg = "The options '-p' and '--skip' cannot be used "
                err_msg += "simultaneously (i.e. only one option must be set)."
                print(settings.print_critical_msg(err_msg))
                raise SystemExit

        if menu.options.ignore_session:
            # Ignore session
            session_handler.ignore(url)

        # Check provided parameters for tests
        if menu.options.test_parameter or menu.options.skip_parameter:
            if menu.options.test_parameter != None:
                if menu.options.test_parameter.startswith("="):
                    menu.options.test_parameter = menu.options.test_parameter[
                        1:]
                settings.TEST_PARAMETER = menu.options.test_parameter.split(
                    settings.PARAMETER_SPLITTING_REGEX)

            elif menu.options.skip_parameter != None:
                if menu.options.skip_parameter.startswith("="):
                    menu.options.skip_parameter = menu.options.skip_parameter[
                        1:]
                settings.TEST_PARAMETER = menu.options.skip_parameter.split(
                    settings.PARAMETER_SPLITTING_REGEX)

            for i in range(0, len(settings.TEST_PARAMETER)):
                if "=" in settings.TEST_PARAMETER[i]:
                    settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[
                        i].split("=")[0]

        # Check injection level, due to the provided testable parameters.
        if menu.options.level < 2 and menu.options.test_parameter != None:
            checks.check_injection_level()

        # Check if defined character used for splitting cookie values.
        if menu.options.cdel:
            settings.COOKIE_DELIMITER = menu.options.cdel

        # Check for skipping injection techniques.
        if menu.options.skip_tech:
            if menu.options.tech:
                err_msg = "The options '--technique' and '--skip-technique' cannot be used "
                err_msg += "simultaneously (i.e. only one option must be set)."
                print(settings.print_critical_msg(err_msg))
                raise SystemExit

            settings.SKIP_TECHNIQUES = True
            menu.options.tech = menu.options.skip_tech

        # Check if specified wrong injection technique
        if menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES:
            found_tech = False

            # Convert injection technique(s) to lowercase
            menu.options.tech = menu.options.tech.lower()

            # Check if used the ',' separator
            if settings.PARAMETER_SPLITTING_REGEX in menu.options.tech:
                split_techniques_names = menu.options.tech.split(
                    settings.PARAMETER_SPLITTING_REGEX)
            else:
                split_techniques_names = menu.options.tech.split()
            if split_techniques_names:
                for i in range(0, len(split_techniques_names)):
                    if len(menu.options.tech) <= 4:
                        split_first_letter = list(menu.options.tech)
                        for j in range(0, len(split_first_letter)):
                            if split_first_letter[
                                    j] in settings.AVAILABLE_TECHNIQUES:
                                found_tech = True
                            else:
                                found_tech = False

            if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and \
               found_tech == False:
                err_msg = "You specified wrong value '" + split_techniques_names[
                    i]
                err_msg += "' as injection technique. "
                err_msg += "The value for '"
                if not settings.SKIP_TECHNIQUES:
                    err_msg += "--technique"
                else:
                    err_msg += "--skip-technique"

                err_msg += "' must be a string composed by the letters C, E, T, F. "
                err_msg += "Refer to the official wiki for details."
                print(settings.print_critical_msg(err_msg))
                raise SystemExit()

        # Check if specified wrong alternative shell
        if menu.options.alter_shell:
            if menu.options.alter_shell.lower(
            ) not in settings.AVAILABLE_SHELLS:
                err_msg = "'" + menu.options.alter_shell + "' shell is not supported!"
                print(settings.print_critical_msg(err_msg))
                raise SystemExit()

        # Check the file-destination
        if menu.options.file_write and not menu.options.file_dest or \
        menu.options.file_upload  and not menu.options.file_dest:
            err_msg = "Host's absolute filepath to write and/or upload, must be specified (i.e. '--file-dest')."
            print(settings.print_critical_msg(err_msg))
            raise SystemExit()

        if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None:
            err_msg = "You must enter the '--file-write' or '--file-upload' parameter."
            print(settings.print_critical_msg(err_msg))
            raise SystemExit()

        # Check if defined "--url" or "-m" option.
        if url:
            if menu.options.auth_cred and menu.options.auth_cred and settings.VERBOSITY_LEVEL >= 1:
                success_msg = "Used a valid pair of " + menu.options.auth_type
                success_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'."
                print(settings.print_success_msg(success_msg))
            # Load the crawler
            if menu.options.crawldepth > 0 or menu.options.sitemap_url:
                url = crawler.crawler(url)
            try:
                if menu.options.flush_session:
                    session_handler.flush(url)
                # Check for CGI scripts on url
                checks.check_CGI_scripts(url)
                # Modification on payload
                if not menu.options.shellshock:
                    if not settings.USE_BACKTICKS:
                        settings.SYS_USERS = "echo $(" + settings.SYS_USERS + ")"
                        settings.SYS_PASSES = "echo $(" + settings.SYS_PASSES + ")"
                # Check if defined "--file-upload" option.
                if menu.options.file_upload:
                    checks.file_upload()
                    try:
                        _urllib.request.urlopen(menu.options.file_upload)
                    except _urllib.error.HTTPError as err_msg:
                        print(settings.print_critical_msg(str(err_msg.code)))
                        raise SystemExit()
                    except _urllib.error.URLError as err_msg:
                        print(
                            settings.print_critical_msg(
                                str(err_msg.args[0]).split("] ")[1] + "."))
                        raise SystemExit()
                try:
                    # Webpage encoding detection.
                    requests.encoding_detection(response)
                    if response.info()['server']:
                        server_banner = response.info()['server']
                        # Procedure for target server's operating system identification.
                        requests.check_target_os(server_banner)
                        # Procedure for target server identification.
                        requests.server_identification(server_banner)
                        # Procedure for target application identification
                        requests.application_identification(server_banner, url)
                        # Store the Server's root dir
                        settings.DEFAULT_WEB_ROOT = settings.WEB_ROOT
                        if menu.options.is_admin or menu.options.is_root and not menu.options.current_user:
                            menu.options.current_user = True
                        # Define Python working directory.
                        checks.define_py_working_dir()
                        # Check for wrong flags.
                        checks.check_wrong_flags()
                    else:
                        found_os_server = checks.user_defined_os()
                except KeyError:
                    pass
                # Load tamper scripts
                if menu.options.tamper:
                    checks.tamper_scripts()

            except _urllib.error.HTTPError as err_msg:
                # Check the codes of responses
                if str(err_msg.getcode()) == settings.INTERNAL_SERVER_ERROR:
                    print("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]")
                    content = err_msg.read()
                    raise SystemExit()

                # Invalid permission to access target URL page.
                elif str(err_msg.getcode()) == settings.FORBIDDEN_ERROR:
                    if settings.VERBOSITY_LEVEL < 2:
                        print("[ " + Fore.RED + "FAILED" + Style.RESET_ALL +
                              " ]")
                    err_msg = "You don't have permission to access this page."
                    print(settings.print_critical_msg(err_msg))
                    raise SystemExit()

                # The target host seems to be down!
                elif str(err_msg.getcode()) == settings.NOT_FOUND_ERROR:
                    if settings.VERBOSITY_LEVEL < 2:
                        print("[ " + Fore.RED + "FAILED" + Style.RESET_ALL +
                              " ]")
                    err_msg = "The host seems to be down!"
                    print(settings.print_critical_msg(err_msg))
                    raise SystemExit()

                else:
                    raise

            # The target host seems to be down!
            except _urllib.error.URLError as e:
                if settings.VERBOSITY_LEVEL < 2:
                    print("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]")
                err_msg = "The host seems to be down"
                try:
                    err_msg += " (" + str(e.args[0]).split("] ")[1] + ")."
                except IndexError:
                    err_msg += "."
                    pass
                print(settings.print_critical_msg(err_msg))
                raise SystemExit()

            except _http_client.BadStatusLine as err_msg:
                if settings.VERBOSITY_LEVEL < 2:
                    print("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]")
                if len(err_msg.line) > 2:
                    print(err_msg.line, err_msg.message)
                pass

            except AttributeError:
                pass

        else:
            err_msg = "You must specify the target URL."
            print(settings.print_critical_msg(err_msg))
            raise SystemExit()

        # Retrieve everything from the supported enumeration options.
        if menu.options.enum_all:
            checks.enable_all_enumeration_options()

        # Launch injection and exploitation controller.
        controller.do_check(url, filename)
        return filename

    # Accidental stop / restart of the target host server.
    except _http_client.BadStatusLine as err_msg:
        if err_msg.line == "" or err_msg.message == "":
            err_msg = "The target host is not responding."
            err_msg += " Please ensure that is up and try again."
            print("\n\n" + settings.print_critical_msg(err_msg))
            logs.print_logs_notification(filename, url)
        else:
            err_msg = err_msg.line + err_msg.message
            print(settings.print_critical_msg(err_msg) + "\n")
        session_handler.clear(url)
        raise SystemExit()

    # Connection reset by peer
    except SocketError as err_msg:
        if settings.VERBOSITY_LEVEL >= 1:
            print("")
        err_msg = "The target host is not responding."
        err_msg += " Please ensure that is up and try again."
        print("\n" + settings.print_critical_msg(err_msg))
        logs.print_logs_notification(filename, url)
Example #4
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)
Example #5
0
def main(filename, url):
  try:
    # Ignore the mathematic calculation part (Detection phase).
    if menu.options.skip_calc:
      settings.SKIP_CALC = True

    if menu.options.enable_backticks:
      settings.USE_BACKTICKS = True

    # Target URL reload.
    if menu.options.url_reload and menu.options.data:
      settings.URL_RELOAD = True

    if menu.options.test_parameter and menu.options.skip_parameter:
      if type(menu.options.test_parameter) is bool:
        menu.options.test_parameter = None
      else:
        err_msg = "The options '-p' and '--skip' cannot be used "
        err_msg += "simultaneously (i.e. only one option must be set)."
        print settings.print_critical_msg(err_msg)
        raise SystemExit

    # Check provided parameters for tests
    if menu.options.test_parameter or menu.options.skip_parameter:     
      if menu.options.test_parameter != None :
        if menu.options.test_parameter.startswith("="):
          menu.options.test_parameter = menu.options.test_parameter[1:]
        settings.TEST_PARAMETER = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX)  
      
      elif menu.options.skip_parameter != None :
        if menu.options.skip_parameter.startswith("="):
          menu.options.skip_parameter = menu.options.skip_parameter[1:]
        settings.TEST_PARAMETER = menu.options.skip_parameter.split(settings.PARAMETER_SPLITTING_REGEX)

      for i in range(0,len(settings.TEST_PARAMETER)):
        if "=" in settings.TEST_PARAMETER[i]:
          settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0]
          
    # Check injection level, due to the provided testable parameters.
    if menu.options.level < 2 and menu.options.test_parameter != None:
      checks.check_injection_level()

    # Check if defined character used for splitting cookie values.
    if menu.options.cdel:
     settings.COOKIE_DELIMITER = menu.options.cdel

    # Check for skipping injection techniques.
    if menu.options.skip_tech:
      if menu.options.tech:
        err_msg = "The options '--technique' and '--skip-technique' cannot be used "
        err_msg += "simultaneously (i.e. only one option must be set)."
        print settings.print_critical_msg(err_msg)
        raise SystemExit

      settings.SKIP_TECHNIQUES = True
      menu.options.tech = menu.options.skip_tech

    # Check if specified wrong injection technique
    if menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES:
      found_tech = False

      # Convert injection technique(s) to lowercase
      menu.options.tech = menu.options.tech.lower()

      # Check if used the ',' separator
      if settings.PARAMETER_SPLITTING_REGEX in menu.options.tech:
        split_techniques_names = menu.options.tech.split(settings.PARAMETER_SPLITTING_REGEX)
      else:
        split_techniques_names = menu.options.tech.split()
      if split_techniques_names:
        for i in range(0,len(split_techniques_names)):
          if len(menu.options.tech) <= 4:
            split_first_letter = list(menu.options.tech)
            for j in range(0,len(split_first_letter)):
              if split_first_letter[j] in settings.AVAILABLE_TECHNIQUES:
                found_tech = True
              else:  
                found_tech = False  
                          
      if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and \
         found_tech == False:
        err_msg = "You specified wrong value '" + split_techniques_names[i] 
        err_msg += "' as injection technique. "
        err_msg += "The value for '"
        if not settings.SKIP_TECHNIQUES :
          err_msg += "--technique"
        else:
          err_msg += "--skip-technique"
          
        err_msg += "' must be a string composed by the letters C, E, T, F. "
        err_msg += "Refer to the official wiki for details."
        print settings.print_critical_msg(err_msg)
        sys.exit(0)

    # Check if specified wrong alternative shell
    if menu.options.alter_shell:
      if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS:
        err_msg = "'" + menu.options.alter_shell + "' shell is not supported!"
        print settings.print_critical_msg(err_msg)
        sys.exit(0)

    # Check the file-destination
    if menu.options.file_write and not menu.options.file_dest or \
    menu.options.file_upload  and not menu.options.file_dest:
      err_msg = "Host's absolute filepath to write and/or upload, must be specified (i.e. '--file-dest')."
      print settings.print_critical_msg(err_msg)
      sys.exit(0)

    if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None :
      err_msg = "You must enter the '--file-write' or '--file-upload' parameter."
      print settings.print_critical_msg(err_msg)
      sys.exit(0)
  
    # Check if defined "--url" or "-m" option.
    if url:

      # Load the crawler
      if menu.options.crawldepth > 0 or menu.options.sitemap_url:
        if menu.options.crawldepth > 0:
          menu.options.DEFAULT_CRAWLDEPTH_LEVEL = menu.options.crawldepth
        else:  
          if menu.options.sitemap_url:
            while True:
              if not menu.options.batch:
                question_msg = "Do you want to change the crawling depth level? [Y/n] > "
                sys.stdout.write(settings.print_question_msg(question_msg))
                change_depth_level = sys.stdin.readline().replace("\n","").lower()
              else:
                change_depth_level = ""
              if len(change_depth_level) == 0:
                 change_depth_level = "y"              
              if change_depth_level in settings.CHOICE_YES or change_depth_level in settings.CHOICE_NO:
                break  
              elif change_depth_level in settings.CHOICE_QUIT:
                sys.exit(0)
              else:
                err_msg = "'" + change_depth_level + "' is not a valid answer."  
                print settings.print_error_msg(err_msg)
                pass

            # Change the crawling depth level.
            if change_depth_level in settings.CHOICE_YES:
              while True:
                question_msg = "Please enter the crawling depth level (1-2) > "
                sys.stdout.write(settings.print_question_msg(question_msg))
                depth_level = sys.stdin.readline().replace("\n","").lower()
                if len(depth_level) == 0:
                  depth_level = 1
                  break
                elif str(depth_level) != "1" and str(depth_level) != "2":
                  err_msg = "Depth level '" + depth_level + "' is not a valid answer."  
                  print settings.print_error_msg(err_msg)
                  pass
                else: 
                  menu.options.DEFAULT_CRAWLDEPTH_LEVEL = depth_level
                  break

        # Crawl the url.        
        url = crawler.crawler(url)

      try:
        # Check for URL redirection
        if not menu.options.ignore_redirects:
          url = redirection.do_check(url)

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

        # Check for CGI scripts on url
        checks.check_CGI_scripts(url)

        # Modification on payload
        if not menu.options.shellshock:
          if not settings.USE_BACKTICKS:
            settings.SYS_USERS  = "echo $(" + settings.SYS_USERS + ")"
            settings.SYS_PASSES  = "echo $(" + settings.SYS_PASSES + ")"

        # Load tamper scripts
        if menu.options.tamper:
          checks.tamper_scripts()

        # Check if defined "--file-upload" option.
        if menu.options.file_upload:
          if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload):

            # Check if not defined URL for upload.
            while True:
              if not menu.options.batch:
                question_msg = "Do you want to enable an HTTP server? [Y/n] > "
                sys.stdout.write(settings.print_question_msg(question_msg))
                enable_HTTP_server = sys.stdin.readline().replace("\n","").lower()
              else:
                enable_HTTP_server = ""
              if len(enable_HTTP_server) == 0:
                 enable_HTTP_server = "y"              
              if enable_HTTP_server in settings.CHOICE_YES:

                # Check if file exists
                if not os.path.isfile(menu.options.file_upload):
                  err_msg = "The '" + menu.options.file_upload + "' file, does not exist."
                  sys.stdout.write(settings.print_critical_msg(err_msg) + "\n")
                  sys.exit(0)

                # Setting the local HTTP server.
                if settings.LOCAL_HTTP_IP == None:
                  while True:
                    question_msg = "Please enter your interface IP address > "
                    sys.stdout.write(settings.print_question_msg(question_msg))
                    ip_addr = sys.stdin.readline().replace("\n","").lower()

                    # check if IP address is valid
                    ip_check = simple_http_server.is_valid_ipv4(ip_addr)
                    if ip_check == False:
                      err_msg = "The provided IP address seems not valid."  
                      print settings.print_error_msg(err_msg)
                      pass
                    else:
                      settings.LOCAL_HTTP_IP = ip_addr
                      break

                # Check for invalid HTTP server's port.
                if settings.LOCAL_HTTP_PORT < 1 or settings.LOCAL_HTTP_PORT > 65535:
                  err_msg = "Invalid HTTP server's port (" + str(settings.LOCAL_HTTP_PORT) + ")." 
                  print settings.print_critical_msg(err_msg)
                  sys.exit(0)
                
                http_server = "http://" + str(settings.LOCAL_HTTP_IP) + ":" + str(settings.LOCAL_HTTP_PORT) + "/"
                info_msg = "Setting the HTTP server on '" + http_server + "'. "  
                print settings.print_info_msg(info_msg)
                menu.options.file_upload = http_server + menu.options.file_upload
                simple_http_server.main()
                break

              elif enable_HTTP_server in settings.CHOICE_NO:
                if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload):
                  err_msg = "The '" + menu.options.file_upload + "' is not a valid URL. "
                  print settings.print_critical_msg(err_msg)
                  sys.exit(0)
                break  
              elif enable_HTTP_server in settings.CHOICE_QUIT:
                sys.exit(0)
              else:
                err_msg = "'" + enable_HTTP_server + "' is not a valid answer."  
                print settings.print_error_msg(err_msg)
                pass

          try:
            urllib2.urlopen(menu.options.file_upload)
          except urllib2.HTTPError, err_msg:
            print settings.print_critical_msg(str(err_msg.code))
            sys.exit(0)

          except urllib2.URLError, err_msg:
            print settings.print_critical_msg(str(err_msg.args[0]).split("] ")[1] + ".")
            sys.exit(0)

        # Used a valid pair of valid credentials
        if menu.options.auth_cred:
          success_msg = Style.BRIGHT + "Identified a valid pair of credentials '" 
          success_msg += menu.options.auth_cred + Style.RESET_ALL 
          success_msg += Style.BRIGHT + "'." + Style.RESET_ALL
          print settings.print_success_msg(success_msg)

        try:
          if response.info()['server'] :
            server_banner = response.info()['server']
            found_os_server = False
            if menu.options.os and checks.user_defined_os():
              user_defined_os = settings.TARGET_OS

            if settings.VERBOSITY_LEVEL >= 1:
              info_msg = "Identifying the target operating system... " 
              sys.stdout.write(settings.print_info_msg(info_msg))
              sys.stdout.flush()

            # Procedure for target OS identification.
            for i in range(0,len(settings.SERVER_OS_BANNERS)):
              if settings.SERVER_OS_BANNERS[i].lower() in server_banner.lower():
                found_os_server = True
                settings.TARGET_OS = settings.SERVER_OS_BANNERS[i].lower()
                if settings.TARGET_OS == "win" or settings.TARGET_OS == "microsoft" :
                  identified_os = "Windows"
                  if menu.options.os and user_defined_os != "win":
                    if not checks.identified_os():
                      settings.TARGET_OS = user_defined_os

                  settings.TARGET_OS = identified_os[:3].lower()
                  if menu.options.shellshock:
                    err_msg = "The shellshock module is not available for " 
                    err_msg += identified_os + " targets."
                    print settings.print_critical_msg(err_msg)
                    raise SystemExit()
                else:
                  identified_os = "Unix-like (" + settings.TARGET_OS + ")"
                  if menu.options.os and user_defined_os == "win":
                    if not checks.identified_os():
                      settings.TARGET_OS = user_defined_os

            if settings.VERBOSITY_LEVEL >= 1 :
              if found_os_server:
                print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"
                success_msg = "The target operating system appears to be " 
                success_msg += identified_os.title() + Style.RESET_ALL + "."
                print settings.print_success_msg(success_msg)
              else:
                print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                warn_msg = "Heuristics have failed to identify server's operating system."
                print settings.print_warning_msg(warn_msg)

            # Procedure for target server identification.
            found_server_banner = False
            if settings.VERBOSITY_LEVEL >= 1:
              info_msg = "Identifying the target server... " 
              sys.stdout.write(settings.print_info_msg(info_msg))
              sys.stdout.flush()

            for i in range(0,len(settings.SERVER_BANNERS)):
              if settings.SERVER_BANNERS[i].lower() in server_banner.lower():
                if settings.VERBOSITY_LEVEL >= 1:
                  print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"
                if settings.VERBOSITY_LEVEL >= 1:
                  success_msg = "The target server was identified as " 
                  success_msg += server_banner + Style.RESET_ALL + "."
                  print settings.print_success_msg(success_msg)
                settings.SERVER_BANNER = server_banner
                found_server_banner = True

                # Set up default root paths
                if settings.SERVER_BANNERS[i].lower() == "apache":
                  if settings.TARGET_OS == "win":
                    settings.WEB_ROOT = "\\htdocs"
                  else:
                    settings.WEB_ROOT = "/var/www"
                if settings.SERVER_BANNERS[i].lower() == "nginx": 
                  settings.WEB_ROOT = "/usr/share/nginx"
                if settings.SERVER_BANNERS[i].lower() == "microsoft-iis":
                  settings.WEB_ROOT = "\\inetpub\\wwwroot"
                break

            if not found_server_banner:
              if settings.VERBOSITY_LEVEL >= 1:
                print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
              warn_msg = "Heuristics have failed to identify target server."
              print settings.print_warning_msg(warn_msg)

            # Procedure for target application identification
            found_application_extension = False
            if settings.VERBOSITY_LEVEL >= 1:
              info_msg = "Identifying the target application ... " 
              sys.stdout.write(settings.print_info_msg(info_msg))
              sys.stdout.flush()
            root, application_extension = splitext(urlparse(url).path)
            settings.TARGET_APPLICATION = application_extension[1:].upper()
            
            if settings.TARGET_APPLICATION:
              found_application_extension = True
              if settings.VERBOSITY_LEVEL >= 1:
                print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"           
                success_msg = "The target application was identified as " 
                success_msg += settings.TARGET_APPLICATION + Style.RESET_ALL + "."
                print settings.print_success_msg(success_msg)

              # Check for unsupported target applications
              for i in range(0,len(settings.UNSUPPORTED_TARGET_APPLICATION)):
                if settings.TARGET_APPLICATION.lower() in settings.UNSUPPORTED_TARGET_APPLICATION[i].lower():
                  err_msg = settings.TARGET_APPLICATION + " exploitation is not yet supported."  
                  print settings.print_critical_msg(err_msg)
                  raise SystemExit()

            if not found_application_extension:
              if settings.VERBOSITY_LEVEL >= 1:
                print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
              warn_msg = "Heuristics have failed to identify target application."
              print settings.print_warning_msg(warn_msg)

            # Store the Server's root dir
            settings.DEFAULT_WEB_ROOT = settings.WEB_ROOT

            if menu.options.is_admin or menu.options.is_root and not menu.options.current_user:
              menu.options.current_user = True

            # Define Python working directory.
            if settings.TARGET_OS == "win" and menu.options.alter_shell:
              while True:
                if not menu.options.batch:
                  question_msg = "Do you want to use '" + settings.WIN_PYTHON_DIR 
                  question_msg += "' as Python working directory on the target host? [Y/n] > "
                  sys.stdout.write(settings.print_question_msg(question_msg))
                  python_dir = sys.stdin.readline().replace("\n","").lower()
                else:
                  python_dir = ""  
                if len(python_dir) == 0:
                   python_dir = "y" 
                if python_dir in settings.CHOICE_YES:
                  break
                elif python_dir in settings.CHOICE_NO:
                  question_msg = "Please provide a custom working directory for Python (e.g. '" 
                  question_msg += settings.WIN_PYTHON_DIR + "') > "
                  sys.stdout.write(settings.print_question_msg(question_msg))
                  settings.WIN_PYTHON_DIR = sys.stdin.readline().replace("\n","").lower()
                  break
                else:
                  err_msg = "'" + python_dir + "' is not a valid answer."  
                  print settings.print_error_msg(err_msg)
                  pass
              settings.USER_DEFINED_PYTHON_DIR = True

            # Check for wrong flags.
            if settings.TARGET_OS == "win":
              if menu.options.is_root :
                warn_msg = "Swithing '--is-root' to '--is-admin' because the "
                warn_msg += "target has been identified as windows."
                print settings.print_warning_msg(warn_msg)
              if menu.options.passwords:
                warn_msg = "The '--passwords' option, is not yet available for Windows targets."
                print settings.print_warning_msg(warn_msg)  
              if menu.options.file_upload :
                warn_msg = "The '--file-upload' option, is not yet available for windows targets. "
                warn_msg += "Instead, use the '--file-write' option."
                print settings.print_warning_msg(warn_msg)  
                sys.exit(0)
            else: 
              if menu.options.is_admin : 
                warn_msg = "Swithing the '--is-admin' to '--is-root' because "
                warn_msg += "the target has been identified as unix-like. "
                print settings.print_warning_msg(warn_msg)  

            if found_os_server == False and not menu.options.os:
              # If "--shellshock" option is provided then,
              # by default is a Linux/Unix operating system.
              if menu.options.shellshock:
                pass 
              else:
                if menu.options.batch:
                  if not settings.CHECK_BOTH_OS:
                    settings.CHECK_BOTH_OS = True
                    check_type = "unix-based"
                  elif settings.CHECK_BOTH_OS:
                    settings.TARGET_OS = "win"
                    settings.CHECK_BOTH_OS = False
                    settings.PERFORM_BASIC_SCANS = True
                    check_type = "windows-based"
                  info_msg = "Setting the " + check_type + " payloads."
                  print settings.print_info_msg(info_msg)
                else:
                  while True:
                    question_msg = "Do you recognise the server's operating system? "
                    question_msg += "[(W)indows/(U)nix/(q)uit] > "
                    sys.stdout.write(settings.print_question_msg(question_msg))
                    got_os = sys.stdin.readline().replace("\n","").lower()
                    if got_os.lower() in settings.CHOICE_OS :
                      if got_os.lower() == "w":
                        settings.TARGET_OS = "win"
                        break
                      elif got_os.lower() == "u":
                        break
                      elif got_os.lower() == "q":
                        raise SystemExit()
                    else:
                      err_msg = "'" + got_os + "' is not a valid answer."  
                      print settings.print_error_msg(err_msg)
                      pass

            if not menu.options.os:
              if found_server_banner == False:
                warn_msg = "The server which was identified as " 
                warn_msg += server_banner + " seems unknown."
                print settings.print_warning_msg(warn_msg)
          else:
            found_os_server = checks.user_defined_os()
        except KeyError:
          pass

        # Webpage encoding detection.
        requests.encoding_detection(response)
Example #6
0
def main(filename, url):
    try:
        # Ignore the mathematic calculation part (Detection phase).
        if menu.options.skip_calc:
            settings.SKIP_CALC = True

        if menu.options.enable_backticks:
            settings.USE_BACKTICKS = True

        # Target URL reload.
        if menu.options.url_reload and menu.options.data:
            settings.URL_RELOAD = True

        if menu.options.test_parameter and menu.options.skip_parameter:
            if type(menu.options.test_parameter) is bool:
                menu.options.test_parameter = None
            else:
                err_msg = "The options '-p' and '--skip' cannot be used "
                err_msg += "simultaneously (i.e. only one option must be set)."
                print settings.print_critical_msg(err_msg)
                raise SystemExit

        # Ignore session
        if menu.options.ignore_session:
            session_handler.ignore(url)

        # Check provided parameters for tests
        if menu.options.test_parameter or menu.options.skip_parameter:
            if menu.options.test_parameter != None:
                if menu.options.test_parameter.startswith("="):
                    menu.options.test_parameter = menu.options.test_parameter[
                        1:]
                settings.TEST_PARAMETER = menu.options.test_parameter.split(
                    settings.PARAMETER_SPLITTING_REGEX)

            elif menu.options.skip_parameter != None:
                if menu.options.skip_parameter.startswith("="):
                    menu.options.skip_parameter = menu.options.skip_parameter[
                        1:]
                settings.TEST_PARAMETER = menu.options.skip_parameter.split(
                    settings.PARAMETER_SPLITTING_REGEX)

            for i in range(0, len(settings.TEST_PARAMETER)):
                if "=" in settings.TEST_PARAMETER[i]:
                    settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[
                        i].split("=")[0]

        # Check injection level, due to the provided testable parameters.
        if menu.options.level < 2 and menu.options.test_parameter != None:
            checks.check_injection_level()

        # Check if defined character used for splitting cookie values.
        if menu.options.cdel:
            settings.COOKIE_DELIMITER = menu.options.cdel

        # Check for skipping injection techniques.
        if menu.options.skip_tech:
            if menu.options.tech:
                err_msg = "The options '--technique' and '--skip-technique' cannot be used "
                err_msg += "simultaneously (i.e. only one option must be set)."
                print settings.print_critical_msg(err_msg)
                raise SystemExit

            settings.SKIP_TECHNIQUES = True
            menu.options.tech = menu.options.skip_tech

        # Check if specified wrong injection technique
        if menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES:
            found_tech = False

            # Convert injection technique(s) to lowercase
            menu.options.tech = menu.options.tech.lower()

            # Check if used the ',' separator
            if settings.PARAMETER_SPLITTING_REGEX in menu.options.tech:
                split_techniques_names = menu.options.tech.split(
                    settings.PARAMETER_SPLITTING_REGEX)
            else:
                split_techniques_names = menu.options.tech.split()
            if split_techniques_names:
                for i in range(0, len(split_techniques_names)):
                    if len(menu.options.tech) <= 4:
                        split_first_letter = list(menu.options.tech)
                        for j in range(0, len(split_first_letter)):
                            if split_first_letter[
                                    j] in settings.AVAILABLE_TECHNIQUES:
                                found_tech = True
                            else:
                                found_tech = False

            if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and \
               found_tech == False:
                err_msg = "You specified wrong value '" + split_techniques_names[
                    i]
                err_msg += "' as injection technique. "
                err_msg += "The value for '"
                if not settings.SKIP_TECHNIQUES:
                    err_msg += "--technique"
                else:
                    err_msg += "--skip-technique"

                err_msg += "' must be a string composed by the letters C, E, T, F. "
                err_msg += "Refer to the official wiki for details."
                print settings.print_critical_msg(err_msg)
                raise SystemExit()

        # Check if specified wrong alternative shell
        if menu.options.alter_shell:
            if menu.options.alter_shell.lower(
            ) not in settings.AVAILABLE_SHELLS:
                err_msg = "'" + menu.options.alter_shell + "' shell is not supported!"
                print settings.print_critical_msg(err_msg)
                raise SystemExit()

        # Check the file-destination
        if menu.options.file_write and not menu.options.file_dest or \
        menu.options.file_upload  and not menu.options.file_dest:
            err_msg = "Host's absolute filepath to write and/or upload, must be specified (i.e. '--file-dest')."
            print settings.print_critical_msg(err_msg)
            raise SystemExit()

        if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None:
            err_msg = "You must enter the '--file-write' or '--file-upload' parameter."
            print settings.print_critical_msg(err_msg)
            raise SystemExit()

        # Check if defined "--url" or "-m" option.
        if url:
            # Load the crawler
            if menu.options.crawldepth > 0 or menu.options.sitemap_url:
                url = crawler.crawler(url)
            try:
                if menu.options.flush_session:
                    session_handler.flush(url)
                # Check for CGI scripts on url
                checks.check_CGI_scripts(url)
                # Used a valid pair of valid credentials
                if menu.options.auth_cred:
                    success_msg = Style.BRIGHT + "Identified a valid pair of credentials '"
                    success_msg += menu.options.auth_cred + Style.RESET_ALL
                    success_msg += Style.BRIGHT + "'." + Style.RESET_ALL
                    print settings.print_success_msg(success_msg)
                # Modification on payload
                if not menu.options.shellshock:
                    if not settings.USE_BACKTICKS:
                        settings.SYS_USERS = "echo $(" + settings.SYS_USERS + ")"
                        settings.SYS_PASSES = "echo $(" + settings.SYS_PASSES + ")"
                # Check if defined "--file-upload" option.
                if menu.options.file_upload:
                    checks.file_upload()
                    try:
                        urllib2.urlopen(menu.options.file_upload)
                    except urllib2.HTTPError, err_msg:
                        print settings.print_critical_msg(str(err_msg.code))
                        raise SystemExit()
                    except urllib2.URLError, err_msg:
                        print settings.print_critical_msg(
                            str(err_msg.args[0]).split("] ")[1] + ".")
                        raise SystemExit()
                try:
                    # Webpage encoding detection.
                    requests.encoding_detection(response)
                    if response.info()['server']:
                        server_banner = response.info()['server']
                        # Procedure for target server's operating system identification.
                        requests.check_target_os(server_banner)
                        # Procedure for target server identification.
                        requests.server_identification(server_banner)
                        # Procedure for target application identification
                        requests.application_identification(server_banner, url)
                        # Store the Server's root dir
                        settings.DEFAULT_WEB_ROOT = settings.WEB_ROOT
                        if menu.options.is_admin or menu.options.is_root and not menu.options.current_user:
                            menu.options.current_user = True
                        # Define Python working directory.
                        checks.define_py_working_dir()
                        # Check for wrong flags.
                        checks.check_wrong_flags()
                    else:
                        found_os_server = checks.user_defined_os()
                except KeyError:
                    pass
                # Load tamper scripts
                if menu.options.tamper:
                    checks.tamper_scripts()
Example #7
0
def main(filename, url):
    try:

        # Ignore the mathematic calculation part (Detection phase).
        if menu.options.skip_calc:
            settings.SKIP_CALC = True

        # Target URL reload.
        if menu.options.url_reload and menu.options.data:
            settings.URL_RELOAD = True

        # Check provided parameters for tests
        if menu.options.test_parameter:
            if menu.options.test_parameter.startswith("="):
                menu.options.test_parameter = menu.options.test_parameter[1:]
            settings.TEST_PARAMETER = menu.options.test_parameter.split(
                settings.PARAMETER_SPLITTING_REGEX)
            for i in range(0, len(settings.TEST_PARAMETER)):
                if "=" in settings.TEST_PARAMETER[i]:
                    settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[
                        i].split("=")[0]

        # Check if defined character used for splitting parameter values.
        if menu.options.pdel:
            settings.PARAMETER_DELIMITER = menu.options.pdel

        # Check if defined character used for splitting cookie values.
        if menu.options.cdel:
            settings.COOKIE_DELIMITER = menu.options.cdel

        # Check if specified wrong injection technique
        if menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES:
            found_tech = False
            # Convert injection technique(s) to lowercase
            menu.options.tech = menu.options.tech.lower()
            # Check if used the ',' separator
            if settings.PARAMETER_SPLITTING_REGEX in menu.options.tech:
                split_techniques_names = menu.options.tech.split(
                    settings.PARAMETER_SPLITTING_REGEX)
            else:
                split_techniques_names = menu.options.tech.split()
            if split_techniques_names:
                for i in range(0, len(split_techniques_names)):
                    if len(menu.options.tech) <= 4:
                        split_first_letter = list(menu.options.tech)
                        for j in range(0, len(split_first_letter)):
                            if split_first_letter[
                                    j] in settings.AVAILABLE_TECHNIQUES:
                                found_tech = True
                            else:
                                found_tech = False

            if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and \
               found_tech == False:
                err_msg = "You specified wrong value '" + split_techniques_names[
                    i]
                err_msg += "' as injection technique. "
                err_msg += "The value, must be a string composed by the letters (C)lassic, (E)val-based, "
                err_msg += "(T)ime-based, (F)ile-based (with or without commas)."
                print settings.print_critical_msg(err_msg)
                sys.exit(0)

        # Check if specified wrong alternative shell
        if menu.options.alter_shell:
            if menu.options.alter_shell.lower(
            ) not in settings.AVAILABLE_SHELLS:
                err_msg = "'" + menu.options.alter_shell + "' shell is not supported!"
                print settings.print_critical_msg(err_msg)
                sys.exit(0)

        # Check the file-destination
        if menu.options.file_write and not menu.options.file_dest or \
        menu.options.file_upload  and not menu.options.file_dest:
            err_msg = "Host's absolute filepath to write and/or upload, must be specified (--file-dest)."
            print settings.print_critical_msg(err_msg)
            sys.exit(0)

        if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None:
            err_msg = "You must enter the '--file-write' or '--file-upload' parameter."
            print settings.print_critical_msg(err_msg)
            sys.exit(0)

        # Check if defined "--random-agent" option.
        if menu.options.random_agent:
            menu.options.agent = random.choice(settings.USER_AGENT_LIST)

        # Check if defined "--url" or "-m" option.
        if url:
            # Check if http / https
            url = checks.check_http_s(url)

            # Load the crawler
            if menu.options.crawldepth > 0 or menu.options.sitemap_url:
                if menu.options.crawldepth > 0:
                    menu.options.DEFAULT_CRAWLDEPTH_LEVEL = menu.options.crawldepth
                else:
                    if menu.options.sitemap_url:
                        while True:
                            if not menu.options.batch:
                                question_msg = "Do you want to change the crawling depth level? [Y/n] > "
                                sys.stdout.write(
                                    settings.print_question_msg(question_msg))
                                change_depth_level = sys.stdin.readline(
                                ).replace("\n", "").lower()
                            else:
                                change_depth_level = ""
                            if len(change_depth_level) == 0:
                                change_depth_level = "y"
                            if change_depth_level in settings.CHOICE_YES or change_depth_level in settings.CHOICE_NO:
                                break
                            elif change_depth_level in settings.CHOICE_QUIT:
                                sys.exit(0)
                            else:
                                err_msg = "'" + change_depth_level + "' is not a valid answer."
                                print settings.print_error_msg(err_msg)
                                pass

                        # Change the crawling depth level.
                        if change_depth_level in settings.CHOICE_YES:
                            while True:
                                question_msg = "Please enter the crawling depth level (1-2) > "
                                sys.stdout.write(
                                    settings.print_question_msg(question_msg))
                                depth_level = sys.stdin.readline().replace(
                                    "\n", "").lower()
                                if int(depth_level) >= 3:
                                    err_msg = "Depth level '" + depth_level + "' is not a valid answer."
                                    print settings.print_error_msg(err_msg)
                                    pass
                                else:
                                    menu.options.DEFAULT_CRAWLDEPTH_LEVEL = depth_level
                                    break

                # Crawl the url.
                url = crawler.crawler(url)

            try:
                # Check if defined POST data
                if menu.options.data:
                    request = urllib2.Request(url, menu.options.data)
                else:
                    request = urllib2.Request(url)

                headers.do_check(request)
                #headers.check_http_traffic(request)
                # Check if defined any HTTP Proxy (--proxy option).
                if menu.options.proxy:
                    proxy.do_check(url)

                # Check if defined Tor (--tor option).
                elif menu.options.tor:
                    tor.do_check()

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

                info_msg = "Checking connection to the target URL... "
                sys.stdout.write(settings.print_info_msg(info_msg))
                sys.stdout.flush()
                if settings.VERBOSITY_LEVEL >= 2:
                    print ""

                headers.check_http_traffic(request)

                try:
                    # Check if defined any HTTP Proxy (--proxy option).
                    if menu.options.proxy:
                        response = proxy.use_proxy(request)
                    # Check if defined Tor (--tor option).
                    elif menu.options.tor:
                        response = tor.use_tor(request)
                    else:
                        try:
                            response = urllib2.urlopen(request)
                        except ValueError:
                            # Invalid format for the '--headers' option.
                            if settings.VERBOSITY_LEVEL < 2:
                                print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                            err_msg = "Use '--headers=\"HEADER_NAME:HEADER_VALUE\"' "
                            err_msg += "to provide an HTTP header or"
                            err_msg += " '--headers=\"HEADER_NAME:" + settings.WILDCARD_CHAR + "\"' "
                            err_msg += "if you want to try to exploit the provided HTTP header."
                            print settings.print_critical_msg(err_msg)
                            sys.exit(0)

                except urllib2.HTTPError, e:
                    if settings.VERBOSITY_LEVEL < 2:
                        print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                    err_msg = str(e).replace(": ", " (") + ")."
                    print settings.print_critical_msg(err_msg)
                    raise SystemExit

                html_data = content = response.read()
                if settings.VERBOSITY_LEVEL < 2:
                    print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"

                # Check for CGI scripts on url
                checks.check_CGI_scripts(url)

                # Modification on payload
                if not menu.options.shellshock:
                    #settings.CURRENT_USER = "******" + settings.CURRENT_USER + ")"
                    settings.SYS_USERS = "echo $(" + settings.SYS_USERS + ")"
                    settings.SYS_PASSES = "echo $(" + settings.SYS_PASSES + ")"

                # Check if defined "--file-upload" option.
                if menu.options.file_upload:
                    if not re.match(settings.VALID_URL_FORMAT,
                                    menu.options.file_upload):
                        # Check if not defined URL for upload.
                        while True:
                            if not menu.options.batch:
                                question_msg = "Do you want to enable an HTTP server? [Y/n] > "
                                sys.stdout.write(
                                    settings.print_question_msg(question_msg))
                                enable_HTTP_server = sys.stdin.readline(
                                ).replace("\n", "").lower()
                            else:
                                enable_HTTP_server == ""
                            if len(enable_HTTP_server) == 0:
                                enable_HTTP_server = "y"
                            if enable_HTTP_server in settings.CHOICE_YES:
                                # Check if file exists
                                if not os.path.isfile(
                                        menu.options.file_upload):
                                    err_msg = "The '" + menu.options.file_upload + "' file, does not exists."
                                    sys.stdout.write(
                                        settings.print_critical_msg(err_msg) +
                                        "\n")
                                    sys.exit(0)

                                if settings.LOCAL_HTTP_IP == None:
                                    while True:
                                        question_msg = "Please enter your interface IP address > "
                                        sys.stdout.write(
                                            settings.print_question_msg(
                                                question_msg))
                                        ip_addr = sys.stdin.readline().replace(
                                            "\n", "").lower()

                                        # check if IP address is valid
                                        ip_check = simple_http_server.is_valid_ipv4(
                                            ip_addr)
                                        if ip_check == False:
                                            err_msg = "The provided IP address seems not valid."
                                            print settings.print_error_msg(
                                                err_msg)
                                            pass
                                        else:
                                            settings.LOCAL_HTTP_IP = ip_addr
                                            break

                                http_server = "http://" + str(
                                    settings.LOCAL_HTTP_IP) + ":" + str(
                                        settings.LOCAL_HTTP_PORT) + "/"
                                info_msg = "Setting the HTTP server on '" + http_server + "'. "
                                print settings.print_info_msg(info_msg)
                                menu.options.file_upload = http_server + menu.options.file_upload
                                simple_http_server.main()
                                break
                            elif enable_HTTP_server in settings.CHOICE_NO:
                                if not re.match(settings.VALID_URL_FORMAT,
                                                menu.options.file_upload):
                                    err_msg = "The '" + menu.options.file_upload + "' is not a valid URL. "
                                    print settings.print_critical_msg(err_msg)
                                    sys.exit(0)
                                break
                            elif enable_HTTP_server in settings.CHOICE_QUIT:
                                sys.exit(0)
                            else:
                                err_msg = "'" + enable_HTTP_server + "' is not a valid answer."
                                print settings.print_error_msg(err_msg)
                                pass
                    try:
                        urllib2.urlopen(menu.options.file_upload)
                    except urllib2.HTTPError, err_msg:
                        print settings.print_critical_msg(str(err_msg.code))
                        sys.exit(0)
                    except urllib2.URLError, err_msg:
                        print settings.print_critical_msg(
                            str(err_msg.args[0]).split("] ")[1] + ".")
                        sys.exit(0)
Example #8
0
def main():
    try:
        # Check if defined "--version" option.
        if menu.options.version:
            version.show_version()
            sys.exit(0)

        # Checkall the banner
        menu.banner()

        # Check python version number.
        version.python_version()

        # Check if defined "--dependencies" option.
        # For checking (non-core) third party dependenices.
        if menu.options.noncore_dependencies:
            checks.third_party_dependencies()
            sys.exit(0)

        # Check if defined "--update" option.
        if menu.options.update:
            update.updater()

        # Check if defined "--install" option.
        if menu.options.install:
            install.installer()
            sys.exit(0)

        # Check arguments
        if len(sys.argv) == 1:
            menu.parser.print_help()
            print ""
            sys.exit(0)

        # Define the level of verbosity.
        if menu.options.verbose > 4:
            err_msg = "The value for option '-v' "
            err_msg += "must be an integer value from range [0, 4]."
            print settings.print_critical_msg(err_msg)
            sys.exit(0)
        else:
            settings.VERBOSITY_LEVEL = menu.options.verbose

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

        # Define the level of tests to perform.
        if menu.options.level > 3:
            err_msg = "The value for option '--level' "
            err_msg += "must be an integer value from range [1, 3]."
            print settings.print_critical_msg(err_msg)
            sys.exit(0)

        # Define the local path where Metasploit Framework is installed.
        if menu.options.msf_path:
            settings.METASPLOIT_PATH = menu.options.msf_path

        # Parse target / data from HTTP proxy logs (i.e Burp / WebScarab).
        if menu.options.logfile:
            parser.logfile_parser()

        # Ignore the mathematic calculation part (Detection phase).
        if menu.options.skip_calc:
            settings.SKIP_CALC = True

        # Target URL reload.
        if menu.options.url_reload and menu.options.data:
            settings.URL_RELOAD = True

        # Check provided parameters for tests
        if menu.options.test_parameter:
            if menu.options.test_parameter.startswith("="):
                menu.options.test_parameter = menu.options.test_parameter[1:]
            settings.TEST_PARAMETER = menu.options.test_parameter.split(
                settings.PARAMETER_SPLITTING_REGEX)
            for i in range(0, len(settings.TEST_PARAMETER)):
                if "=" in settings.TEST_PARAMETER[i]:
                    settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[
                        i].split("=")[0]

        # Check if ".git" exists and check for updated version!
        if os.path.isdir("./.git") and settings.CHECK_FOR_UPDATES_ON_START:
            update.check_for_update()

        # Check if defined character used for splitting parameter values.
        if menu.options.pdel:
            settings.PARAMETER_DELIMITER = menu.options.pdel

        # Check if defined character used for splitting cookie values.
        if menu.options.cdel:
            settings.COOKIE_DELIMITER = menu.options.cdel

        # Check if specified wrong injection technique
        if menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES:
            found_tech = False
            # Convert injection technique(s) to lowercase
            menu.options.tech = menu.options.tech.lower()
            # Check if used the ',' separator
            if settings.PARAMETER_SPLITTING_REGEX in menu.options.tech:
                split_techniques_names = menu.options.tech.split(
                    settings.PARAMETER_SPLITTING_REGEX)
            else:
                split_techniques_names = menu.options.tech.split()
            if split_techniques_names:
                for i in range(0, len(split_techniques_names)):
                    if len(menu.options.tech) <= 4:
                        split_first_letter = list(menu.options.tech)
                        for j in range(0, len(split_first_letter)):
                            if split_first_letter[
                                    j] in settings.AVAILABLE_TECHNIQUES:
                                found_tech = True
                            else:
                                found_tech = False

            if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and \
               found_tech == False:
                err_msg = "You specified wrong value '" + split_techniques_names[
                    i]
                err_msg += "' as injection technique. "
                err_msg += "The value, must be a string composed by the letters (C)lassic, (E)val-based, "
                err_msg += "(T)ime-based, (F)ile-based (with or without commas)."
                print settings.print_critical_msg(err_msg)
                sys.exit(0)

        # Check if specified wrong alternative shell
        if menu.options.alter_shell:
            if menu.options.alter_shell.lower(
            ) not in settings.AVAILABLE_SHELLS:
                err_msg = "'" + menu.options.alter_shell + "' shell is not supported!"
                print settings.print_critical_msg(err_msg)
                sys.exit(0)

        # Check the file-destination
        if menu.options.file_write and not menu.options.file_dest or \
        menu.options.file_upload  and not menu.options.file_dest:
            err_msg = "Host's absolute filepath to write and/or upload, must be specified (--file-dest)."
            print settings.print_critical_msg(err_msg)
            sys.exit(0)

        if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None:
            err_msg = "You must enter the '--file-write' or '--file-upload' parameter."
            print settings.print_critical_msg(err_msg)
            sys.exit(0)

        # Check if defined "--random-agent" option.
        if menu.options.random_agent:
            menu.options.agent = random.choice(settings.USER_AGENT_LIST)

        # Check if defined "--url" option.
        if menu.options.url:
            url = menu.options.url

            # Check if http / https
            url = checks.check_http_s(url)

            # Load the crawler
            if menu.options.crawldepth > 0:
                menu.options.DEFAULT_CRAWLDEPTH_LEVEL = menu.options.crawldepth
                url = crawler.crawler(url)

            if menu.options.output_dir:
                output_dir = menu.options.output_dir
            else:
                output_dir = settings.OUTPUT_DIR

            # One directory up, if Windows or if the script is being run under "/src".
            if settings.IS_WINDOWS or "/src" in os.path.dirname(
                    os.path.abspath(__file__)):
                os.chdir("..")

            output_dir = os.path.dirname(output_dir)

            try:
                os.stat(output_dir)
            except:
                os.mkdir(output_dir)

            # The logs filename construction.
            filename = logs.create_log_file(url, output_dir)
            try:

                # Check if defined POST data
                if menu.options.data:
                    request = urllib2.Request(url, menu.options.data)
                else:
                    request = urllib2.Request(url)

                headers.do_check(request)
                #headers.check_http_traffic(request)
                # Check if defined any HTTP Proxy (--proxy option).
                if menu.options.proxy:
                    proxy.do_check(url)

                # Check if defined Tor (--tor option).
                elif menu.options.tor:
                    tor.do_check()

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

                info_msg = "Checking connection to the target URL... "
                sys.stdout.write(settings.print_info_msg(info_msg))
                sys.stdout.flush()
                if settings.VERBOSITY_LEVEL >= 2:
                    print ""

                headers.check_http_traffic(request)

                try:
                    # Check if defined any HTTP Proxy (--proxy option).
                    if menu.options.proxy:
                        response = proxy.use_proxy(request)
                    # Check if defined Tor (--tor option).
                    elif menu.options.tor:
                        response = tor.use_tor(request)
                    else:
                        try:
                            response = urllib2.urlopen(request)
                        except ValueError:
                            # Invalid format for the '--headers' option.
                            if settings.VERBOSITY_LEVEL < 2:
                                print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                            err_msg = "Use '--headers=\"HEADER_NAME:HEADER_VALUE\"' "
                            err_msg += "to provide an HTTP header or"
                            err_msg += " '--headers=\"HEADER_NAME:" + settings.WILDCARD_CHAR + "\"' "
                            err_msg += "if you want to try to exploit the provided HTTP header."
                            print settings.print_critical_msg(err_msg)
                            sys.exit(0)

                except urllib2.HTTPError, e:
                    if settings.VERBOSITY_LEVEL < 2:
                        print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                    err_msg = str(e).replace(": ", " (") + ")."
                    print settings.print_critical_msg(err_msg)
                    raise SystemExit

                html_data = content = response.read()
                if settings.VERBOSITY_LEVEL < 2:
                    print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"

                # Check for CGI scripts on url
                checks.check_CGI_scripts(url)

                # Modification on payload
                if not menu.options.shellshock:
                    #settings.CURRENT_USER = "******" + settings.CURRENT_USER + ")"
                    settings.SYS_USERS = "echo $(" + settings.SYS_USERS + ")"
                    settings.SYS_PASSES = "echo $(" + settings.SYS_PASSES + ")"

                # Check if defined "--file-upload" option.
                if menu.options.file_upload:
                    if not re.match(settings.VALID_URL_FORMAT,
                                    menu.options.file_upload):
                        # Check if not defined URL for upload.
                        while True:
                            question_msg = "Do you want to enable an HTTP server? [Y/n/q] > "
                            sys.stdout.write(
                                settings.print_question_msg(question_msg))
                            enable_HTTP_server = sys.stdin.readline().replace(
                                "\n", "").lower()
                            if len(enable_HTTP_server) == 0:
                                enable_HTTP_server = "y"
                            if enable_HTTP_server in settings.CHOICE_YES:
                                # Check if file exists
                                if not os.path.isfile(
                                        menu.options.file_upload):
                                    err_msg = "The '" + menu.options.file_upload + "' file, does not exists."
                                    sys.stdout.write(
                                        settings.print_critical_msg(err_msg) +
                                        "\n")
                                    sys.exit(0)
                                http_server = "http://" + str(
                                    settings.LOCAL_HTTP_IP) + ":" + str(
                                        settings.LOCAL_HTTP_PORT) + "/"
                                info_msg = "Setting the HTTP server on '" + http_server + "'. "
                                print settings.print_info_msg(info_msg)
                                menu.options.file_upload = http_server + menu.options.file_upload
                                simple_http_server.main()
                                break
                            elif enable_HTTP_server in settings.CHOICE_NO:
                                if not re.match(settings.VALID_URL_FORMAT,
                                                menu.options.file_upload):
                                    err_msg = "The '" + menu.options.file_upload + "' is not a valid URL. "
                                    print settings.print_critical_msg(err_msg)
                                    sys.exit(0)
                                break
                            elif enable_HTTP_server in settings.CHOICE_QUIT:
                                sys.exit(0)
                            else:
                                err_msg = "'" + enable_HTTP_server + "' is not a valid answer."
                                print settings.print_error_msg(err_msg)
                                pass
                    try:
                        urllib2.urlopen(menu.options.file_upload)
                    except urllib2.HTTPError, err_msg:
                        print settings.print_critical_msg(err_msg)
                        sys.exit(0)
                    except urllib2.URLError, err_msg:
                        print settings.print_critical_msg(err_msg)
                        sys.exit(0)
Example #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

  # 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)
Example #10
0
def main():
  try:
    # Check if defined "--version" option.
    if menu.options.version:
      version.show_version()
      sys.exit(0)

    # Checkall the banner
    menu.banner()
        
    # Check python version number.
    version.python_version()

    # Check if defined "--dependencies" option. 
    # For checking (non-core) third party dependenices.
    if menu.options.noncore_dependencies:
      checks.third_party_dependencies()
      sys.exit(0)
      
    # Check if defined "--update" option.        
    if menu.options.update:
      update.updater()
        
    # Check if defined "--install" option.        
    if menu.options.install:
      install.installer()
      sys.exit(0)
    
    # Check arguments
    if len(sys.argv) == 1:
      menu.parser.print_help()
      print ""
      sys.exit(0)

    # Define the level of verbosity.
    if menu.options.verbose > 4:
      err_msg = "The value for option '-v' "
      err_msg += "must be an integer value from range [0, 4]."
      print settings.print_critical_msg(err_msg)
      sys.exit(0)
    else:  
      settings.VERBOSITY_LEVEL = menu.options.verbose

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

    # Define the level of tests to perform.
    if menu.options.level > 3:
      err_msg = "The value for option '--level' "
      err_msg += "must be an integer value from range [1, 3]."
      print settings.print_critical_msg(err_msg)
      sys.exit(0)

    # Define the local path where Metasploit Framework is installed.
    if menu.options.msf_path:
      settings.METASPLOIT_PATH = menu.options.msf_path

    # Parse target / data from HTTP proxy logs (i.e Burp / WebScarab).
    if menu.options.logfile:
      parser.logfile_parser()

    # Ignore the mathematic calculation part (Detection phase).
    if menu.options.skip_calc:
      settings.SKIP_CALC = True

    # Target URL reload.
    if menu.options.url_reload and menu.options.data:
      settings.URL_RELOAD = True

    # Check provided parameters for tests
    if menu.options.test_parameter:
      if menu.options.test_parameter.startswith("="):
        menu.options.test_parameter = menu.options.test_parameter[1:]
      settings.TEST_PARAMETER = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX)
      for i in range(0,len(settings.TEST_PARAMETER)):
        if "=" in settings.TEST_PARAMETER[i]:
          settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0]
    
    # Check if ".git" exists and check for updated version!
    if os.path.isdir("./.git") and settings.CHECK_FOR_UPDATES_ON_START:
      update.check_for_update()

    # Check if defined character used for splitting parameter values.
    if menu.options.pdel:
     settings.PARAMETER_DELIMITER = menu.options.pdel

    # Check if defined character used for splitting cookie values.
    if menu.options.cdel:
     settings.COOKIE_DELIMITER = menu.options.cdel

    # Check if specified wrong injection technique
    if menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES:
      found_tech = False
      # Convert injection technique(s) to lowercase
      menu.options.tech = menu.options.tech.lower()
      # Check if used the ',' separator
      if settings.PARAMETER_SPLITTING_REGEX in menu.options.tech:
        split_techniques_names = menu.options.tech.split(settings.PARAMETER_SPLITTING_REGEX)
      else:
        split_techniques_names = menu.options.tech.split()
      if split_techniques_names:
        for i in range(0,len(split_techniques_names)):
          if len(menu.options.tech) <= 4:
            split_first_letter = list(menu.options.tech)
            for j in range(0,len(split_first_letter)):
              if split_first_letter[j] in settings.AVAILABLE_TECHNIQUES:
                found_tech = True
              else:  
                found_tech = False  
                          
      if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and \
         found_tech == False:
        err_msg = "You specified wrong value '" + split_techniques_names[i] 
        err_msg += "' as injection technique. "
        err_msg += "The value, must be a string composed by the letters (C)lassic, (E)val-based, "
        err_msg += "(T)ime-based, (F)ile-based (with or without commas)."
        print settings.print_critical_msg(err_msg)
        sys.exit(0)

    # Check if specified wrong alternative shell
    if menu.options.alter_shell:
      if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS:
        err_msg = "'" + menu.options.alter_shell + "' shell is not supported!"
        print settings.print_critical_msg(err_msg)
        sys.exit(0)

    # Check the file-destination
    if menu.options.file_write and not menu.options.file_dest or \
    menu.options.file_upload  and not menu.options.file_dest:
      err_msg = "Host's absolute filepath to write and/or upload, must be specified (--file-dest)."
      print settings.print_critical_msg(err_msg)
      sys.exit(0)

    if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None :
      err_msg = "You must enter the '--file-write' or '--file-upload' parameter."
      print settings.print_critical_msg(err_msg)
      sys.exit(0)

    # Check if defined "--random-agent" option.
    if menu.options.random_agent:
      menu.options.agent = random.choice(settings.USER_AGENT_LIST)
  
    # Check if defined "--url" option.
    if menu.options.url:
      url = menu.options.url
      
      # Check if http / https
      url = checks.check_http_s(url)

      # Load the crawler
      if menu.options.crawldepth > 0:
        menu.options.DEFAULT_CRAWLDEPTH_LEVEL = menu.options.crawldepth
        url = crawler.crawler(url)

      if menu.options.output_dir:
        output_dir = menu.options.output_dir
      else:
        output_dir = settings.OUTPUT_DIR
      
      # One directory up, if Windows or if the script is being run under "/src".
      if settings.IS_WINDOWS or "/src" in os.path.dirname(os.path.abspath(__file__)):
        os.chdir("..")
        
      output_dir = os.path.dirname(output_dir)
     
      try:
        os.stat(output_dir)
      except:
        os.mkdir(output_dir)   

      # The logs filename construction.
      filename = logs.create_log_file(url, output_dir)
      try:
        
        # Check if defined POST data
        if menu.options.data:
          request = urllib2.Request(url, menu.options.data)
        else:
          request = urllib2.Request(url)

        headers.do_check(request)  
        #headers.check_http_traffic(request)
        # Check if defined any HTTP Proxy (--proxy option).
        if menu.options.proxy:
          proxy.do_check(url)
        
        # Check if defined Tor (--tor option).
        elif menu.options.tor:
          tor.do_check()

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

        info_msg = "Checking connection to the target URL... "
        sys.stdout.write(settings.print_info_msg(info_msg))
        sys.stdout.flush()
        if settings.VERBOSITY_LEVEL >= 2:
          print ""

        headers.check_http_traffic(request)
        
        try:
          # Check if defined any HTTP Proxy (--proxy option).
          if menu.options.proxy:
            response = proxy.use_proxy(request)
          # Check if defined Tor (--tor option).  
          elif menu.options.tor:
            response = tor.use_tor(request)
          else:
            try:
              response = urllib2.urlopen(request)
            except ValueError:
              # Invalid format for the '--headers' option.
              if settings.VERBOSITY_LEVEL < 2:
                print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
              err_msg = "Use '--headers=\"HEADER_NAME:HEADER_VALUE\"' "
              err_msg += "to provide an HTTP header or"
              err_msg += " '--headers=\"HEADER_NAME:" + settings.WILDCARD_CHAR  + "\"' "
              err_msg += "if you want to try to exploit the provided HTTP header."
              print settings.print_critical_msg(err_msg)
              sys.exit(0)
        except:
          raise

        html_data = content = response.read()
        if settings.VERBOSITY_LEVEL < 2:
          print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"
        
        # Check for CGI scripts on url
        checks.check_CGI_scripts(url)

        # Modification on payload
        if not menu.options.shellshock:
          #settings.CURRENT_USER = "******" + settings.CURRENT_USER + ")"
          settings.SYS_USERS  = "echo $(" + settings.SYS_USERS + ")"
          settings.SYS_PASSES  = "echo $(" + settings.SYS_PASSES + ")"

        # Check if defined "--file-upload" option.
        if menu.options.file_upload:
          if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload):
            # Check if not defined URL for upload.
            while True:
              question_msg = "Do you want to enable an HTTP server? [Y/n/q] > "
              sys.stdout.write(settings.print_question_msg(question_msg))
              enable_HTTP_server = sys.stdin.readline().replace("\n","").lower()
              if len(enable_HTTP_server) == 0:
                 enable_HTTP_server = "y"              
              if enable_HTTP_server in settings.CHOICE_YES:
                # Check if file exists
                if not os.path.isfile(menu.options.file_upload):
                  err_msg = "The '" + menu.options.file_upload + "' file, does not exists."
                  sys.stdout.write(settings.print_critical_msg(err_msg) + "\n")
                  sys.exit(0)
                http_server = "http://" + str(settings.LOCAL_HTTP_IP) + ":" + str(settings.LOCAL_HTTP_PORT) + "/"
                info_msg = "Setting the HTTP server on '" + http_server + "'. "  
                print settings.print_info_msg(info_msg)
                menu.options.file_upload = http_server + menu.options.file_upload
                simple_http_server.main()
                break
              elif enable_HTTP_server in settings.CHOICE_NO:
                if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload):
                  err_msg = "The '" + menu.options.file_upload + "' is not a valid URL. "
                  print settings.print_critical_msg(err_msg)
                  sys.exit(0)
                break  
              elif enable_HTTP_server in settings.CHOICE_QUIT:
                sys.exit(0)
              else:
                err_msg = "'" + enable_HTTP_server + "' is not a valid answer."  
                print settings.print_error_msg(err_msg)
                pass
          try:
            urllib2.urlopen(menu.options.file_upload)
          except urllib2.HTTPError, err_msg:
            print settings.print_critical_msg(err_msg)
            sys.exit(0)
          except urllib2.URLError, err_msg:
            print settings.print_critical_msg(err_msg)
            sys.exit(0)

        # Used a valid pair of valid credentials
        if menu.options.auth_cred:
          success_msg = Style.BRIGHT + "Identified a valid pair of credentials '" 
          success_msg += menu.options.auth_cred + Style.RESET_ALL 
          success_msg += Style.BRIGHT + "'." + Style.RESET_ALL
          print settings.print_success_msg(success_msg)

        try:
          if response.info()['server'] :
            server_banner = response.info()['server']
            found_os_server = False
            if menu.options.os and checks.user_defined_os():
              user_defined_os = settings.TARGET_OS

            # Procedure for target OS identification.
            for i in range(0,len(settings.SERVER_OS_BANNERS)):
              if settings.SERVER_OS_BANNERS[i].lower() in server_banner.lower():
                found_os_server = True
                settings.TARGET_OS = settings.SERVER_OS_BANNERS[i].lower()
                if settings.TARGET_OS == "win" or settings.TARGET_OS == "microsoft" :
                  identified_os = "Windows"
                  if menu.options.os and user_defined_os != "win":
                    if not checks.identified_os():
                      settings.TARGET_OS = user_defined_os

                  settings.TARGET_OS = identified_os[:3].lower()
                  if menu.options.shellshock:
                    err_msg = "The shellshock module is not available for " 
                    err_msg += identified_os + " targets."
                    print settings.print_critical_msg(err_msg)
                    raise SystemExit()
                else:
                  identified_os = "Unix-like (" + settings.TARGET_OS + ")"
                  if menu.options.os and user_defined_os == "win":
                    if not checks.identified_os():
                      settings.TARGET_OS = user_defined_os

            # Procedure for target server identification.
            found_server_banner = False
            if settings.VERBOSITY_LEVEL >= 1:
              info_msg = "Identifying the target server... " 
              sys.stdout.write(settings.print_info_msg(info_msg))
              sys.stdout.flush()

            for i in range(0,len(settings.SERVER_BANNERS)):
              if settings.SERVER_BANNERS[i].lower() in server_banner.lower():
                if settings.VERBOSITY_LEVEL >= 1:
                  print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"
                if settings.VERBOSITY_LEVEL >= 1:
                  success_msg = "The target server was identified as " 
                  success_msg += server_banner + Style.RESET_ALL + "."
                  print settings.print_success_msg(success_msg)
                settings.SERVER_BANNER = server_banner
                found_server_banner = True

                # Set up default root paths
                if settings.SERVER_BANNERS[i].lower() == "apache":
                  if settings.TARGET_OS == "win":
                    settings.SRV_ROOT_DIR = "\\htdocs"
                  else:
                    settings.SRV_ROOT_DIR = "/var/www"
                if settings.SERVER_BANNERS[i].lower() == "nginx": 
                  settings.SRV_ROOT_DIR = "/usr/share/nginx"
                if settings.SERVER_BANNERS[i].lower() == "microsoft-iis":
                  settings.SRV_ROOT_DIR = "\\inetpub\\wwwroot"
                break

            if not found_server_banner:
              if settings.VERBOSITY_LEVEL >= 1:
                print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
              warn_msg = "Heuristics have failed to identify target server."
              print settings.print_warning_msg(warn_msg)

            # Procedure for target application identification
            found_application_extension = False
            if settings.VERBOSITY_LEVEL >= 1:
              info_msg = "Identifying the target application ... " 
              sys.stdout.write(settings.print_info_msg(info_msg))
              sys.stdout.flush()
            root, application_extension = splitext(urlparse(url).path)
            settings.TARGET_APPLICATION = application_extension[1:].upper()
            
            if settings.TARGET_APPLICATION:
              found_application_extension = True
              if settings.VERBOSITY_LEVEL >= 1:
                print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"           
                success_msg = "The target application was identified as " 
                success_msg += settings.TARGET_APPLICATION + Style.RESET_ALL + "."
                print settings.print_success_msg(success_msg)

              # Check for unsupported target applications
              for i in range(0,len(settings.UNSUPPORTED_TARGET_APPLICATION)):
                if settings.TARGET_APPLICATION.lower() in settings.UNSUPPORTED_TARGET_APPLICATION[i].lower():
                  err_msg = settings.TARGET_APPLICATION + " exploitation is not yet supported."  
                  print settings.print_critical_msg(err_msg)
                  raise SystemExit()

            if not found_application_extension:
              if settings.VERBOSITY_LEVEL >= 1:
                print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
              warn_msg = "Heuristics have failed to identify target application."
              print settings.print_warning_msg(warn_msg)

            # Load tamper scripts
            if menu.options.tamper:
              checks.tamper_scripts()

            # Store the Server's root dir
            settings.DEFAULT_SRV_ROOT_DIR = settings.SRV_ROOT_DIR

            if menu.options.is_admin or menu.options.is_root and not menu.options.current_user:
              menu.options.current_user = True

            # Define Python working directory.
            if settings.TARGET_OS == "win" and menu.options.alter_shell:
              while True:
                question_msg = "Do you want to use '" + settings.WIN_PYTHON_DIR 
                question_msg += "' as Python working directory on the target host? [Y/n] > "
                sys.stdout.write(settings.print_question_msg(question_msg))
                python_dir = sys.stdin.readline().replace("\n","").lower()
                if len(python_dir) == 0:
                   python_dir = "y" 
                if python_dir in settings.CHOICE_YES:
                  break
                elif python_dir in settings.CHOICE_NO:
                  question_msg = "Please provide a custom working directory for Python (e.g. '" 
                  question_msg += settings.WIN_PYTHON_DIR + "') > "
                  sys.stdout.write(settings.print_question_msg(question_msg))
                  settings.WIN_PYTHON_DIR = sys.stdin.readline().replace("\n","").lower()
                  break
                else:
                  err_msg = "'" + python_dir + "' is not a valid answer."  
                  print settings.print_error_msg(err_msg)
                  pass
              settings.USER_DEFINED_PYTHON_DIR = True

            # Check for wrong flags.
            if settings.TARGET_OS == "win":
              if menu.options.is_root :
                warn_msg = "Swithing '--is-root' to '--is-admin' because the "
                warn_msg += "target has been identified as windows."
                print settings.print_warning_msg(warn_msg)
              if menu.options.passwords:
                warn_msg = "The '--passwords' option, is not yet available for Windows targets."
                print settings.print_warning_msg(warn_msg)  
              if menu.options.file_upload :
                warn_msg = "The '--file-upload' option, is not yet available for windows targets. "
                warn_msg += "Instead, use the '--file-write' option."
                print settings.print_warning_msg(warn_msg)  
                sys.exit(0)
            else: 
              if menu.options.is_admin : 
                warn_msg = "Swithing the '--is-admin' to '--is-root' because "
                warn_msg += "the target has been identified as unix-like. "
                print settings.print_warning_msg(warn_msg)  
            
            if found_os_server == False and \
               not menu.options.os:
              # If "--shellshock" option is provided then,
              # by default is a Linux/Unix operating system.
              if menu.options.shellshock:
                pass 
              else:
                warn_msg = "Heuristics have failed to identify server's operating system."
                print settings.print_warning_msg(warn_msg)
                while True:
                  question_msg = "Do you recognise the server's operating system? "
                  question_msg += "[(W)indows/(U)nix/(q)uit] > "
                  sys.stdout.write(settings.print_question_msg(question_msg))
                  got_os = sys.stdin.readline().replace("\n","").lower()
                  if got_os.lower() in settings.CHOICE_OS :
                    if got_os.lower() == "w":
                      settings.TARGET_OS = "win"
                      break
                    elif got_os.lower() == "u":
                      break
                    elif got_os.lower() == "q":
                      raise SystemExit()
                  else:
                    if got_os == "":
                      got_os = "y"
                    err_msg = "'" + got_os + "' is not a valid answer."  
                    print settings.print_error_msg(err_msg)
                    pass

            if not menu.options.os:
              if found_server_banner == False:
                warn_msg = "The server which was identified as " 
                warn_msg += server_banner + " seems unknown."
                print settings.print_warning_msg(warn_msg)
          else:
            found_os_server = checks.user_defined_os()
        except KeyError:
          pass

        # Charset detection.
        requests.charset_detection(response)
Example #11
0
def main(filename, url):
  try:
    # Ignore the mathematic calculation part (Detection phase).
    if menu.options.skip_calc:
      settings.SKIP_CALC = True

    if menu.options.enable_backticks:
      settings.USE_BACKTICKS = True

    # Target URL reload.
    if menu.options.url_reload and menu.options.data:
      settings.URL_RELOAD = True

    if menu.options.test_parameter and menu.options.skip_parameter:
      if type(menu.options.test_parameter) is bool:
        menu.options.test_parameter = None
      else:
        err_msg = "The options '-p' and '--skip' cannot be used "
        err_msg += "simultaneously (i.e. only one option must be set)."
        print settings.print_critical_msg(err_msg)
        raise SystemExit

    if menu.options.ignore_session:
      # Ignore session
      session_handler.ignore(url)      

    # Check provided parameters for tests
    if menu.options.test_parameter or menu.options.skip_parameter:     
      if menu.options.test_parameter != None :
        if menu.options.test_parameter.startswith("="):
          menu.options.test_parameter = menu.options.test_parameter[1:]
        settings.TEST_PARAMETER = menu.options.test_parameter.split(settings.PARAMETER_SPLITTING_REGEX)  
      
      elif menu.options.skip_parameter != None :
        if menu.options.skip_parameter.startswith("="):
          menu.options.skip_parameter = menu.options.skip_parameter[1:]
        settings.TEST_PARAMETER = menu.options.skip_parameter.split(settings.PARAMETER_SPLITTING_REGEX)

      for i in range(0,len(settings.TEST_PARAMETER)):
        if "=" in settings.TEST_PARAMETER[i]:
          settings.TEST_PARAMETER[i] = settings.TEST_PARAMETER[i].split("=")[0]
          
    # Check injection level, due to the provided testable parameters.
    if menu.options.level < 2 and menu.options.test_parameter != None:
      checks.check_injection_level()

    # Check if defined character used for splitting cookie values.
    if menu.options.cdel:
     settings.COOKIE_DELIMITER = menu.options.cdel

    # Check for skipping injection techniques.
    if menu.options.skip_tech:
      if menu.options.tech:
        err_msg = "The options '--technique' and '--skip-technique' cannot be used "
        err_msg += "simultaneously (i.e. only one option must be set)."
        print settings.print_critical_msg(err_msg)
        raise SystemExit

      settings.SKIP_TECHNIQUES = True
      menu.options.tech = menu.options.skip_tech

    # Check if specified wrong injection technique
    if menu.options.tech and menu.options.tech not in settings.AVAILABLE_TECHNIQUES:
      found_tech = False

      # Convert injection technique(s) to lowercase
      menu.options.tech = menu.options.tech.lower()

      # Check if used the ',' separator
      if settings.PARAMETER_SPLITTING_REGEX in menu.options.tech:
        split_techniques_names = menu.options.tech.split(settings.PARAMETER_SPLITTING_REGEX)
      else:
        split_techniques_names = menu.options.tech.split()
      if split_techniques_names:
        for i in range(0,len(split_techniques_names)):
          if len(menu.options.tech) <= 4:
            split_first_letter = list(menu.options.tech)
            for j in range(0,len(split_first_letter)):
              if split_first_letter[j] in settings.AVAILABLE_TECHNIQUES:
                found_tech = True
              else:  
                found_tech = False  
                          
      if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and \
         found_tech == False:
        err_msg = "You specified wrong value '" + split_techniques_names[i] 
        err_msg += "' as injection technique. "
        err_msg += "The value for '"
        if not settings.SKIP_TECHNIQUES :
          err_msg += "--technique"
        else:
          err_msg += "--skip-technique"
          
        err_msg += "' must be a string composed by the letters C, E, T, F. "
        err_msg += "Refer to the official wiki for details."
        print settings.print_critical_msg(err_msg)
        raise SystemExit()

    # Check if specified wrong alternative shell
    if menu.options.alter_shell:
      if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS:
        err_msg = "'" + menu.options.alter_shell + "' shell is not supported!"
        print settings.print_critical_msg(err_msg)
        raise SystemExit()

    # Check the file-destination
    if menu.options.file_write and not menu.options.file_dest or \
    menu.options.file_upload  and not menu.options.file_dest:
      err_msg = "Host's absolute filepath to write and/or upload, must be specified (i.e. '--file-dest')."
      print settings.print_critical_msg(err_msg)
      raise SystemExit()

    if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None:
      err_msg = "You must enter the '--file-write' or '--file-upload' parameter."
      print settings.print_critical_msg(err_msg)
      raise SystemExit()
  
    # Check if defined "--url" or "-m" option.
    if url:
      if menu.options.auth_cred and menu.options.auth_cred and settings.VERBOSITY_LEVEL >= 1:
        success_msg = "Used a valid pair of " + menu.options.auth_type 
        success_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'." 
        print settings.print_success_msg(success_msg)
      # Load the crawler
      if menu.options.crawldepth > 0 or menu.options.sitemap_url:  
        url = crawler.crawler(url)
      try:
        if menu.options.flush_session:
          session_handler.flush(url)
        # Check for CGI scripts on url
        checks.check_CGI_scripts(url)
        # Modification on payload
        if not menu.options.shellshock:
          if not settings.USE_BACKTICKS:
            settings.SYS_USERS  = "echo $(" + settings.SYS_USERS + ")"
            settings.SYS_PASSES  = "echo $(" + settings.SYS_PASSES + ")"
        # Check if defined "--file-upload" option.
        if menu.options.file_upload:
          checks.file_upload()
          try:
            urllib2.urlopen(menu.options.file_upload)
          except urllib2.HTTPError, err_msg:
            print settings.print_critical_msg(str(err_msg.code))
            raise SystemExit()
          except urllib2.URLError, err_msg:
            print settings.print_critical_msg(str(err_msg.args[0]).split("] ")[1] + ".")
            raise SystemExit()
        try:
          # Webpage encoding detection.
          requests.encoding_detection(response)
          if response.info()['server'] :
            server_banner = response.info()['server']
            # Procedure for target server's operating system identification.
            requests.check_target_os(server_banner)
            # Procedure for target server identification.
            requests.server_identification(server_banner)
            # Procedure for target application identification
            requests.application_identification(server_banner, url)
            # Store the Server's root dir
            settings.DEFAULT_WEB_ROOT = settings.WEB_ROOT
            if menu.options.is_admin or menu.options.is_root and not menu.options.current_user:
              menu.options.current_user = True
            # Define Python working directory.
            checks.define_py_working_dir()
            # Check for wrong flags.
            checks.check_wrong_flags() 
          else:
            found_os_server = checks.user_defined_os()
        except KeyError:
          pass
        # Load tamper scripts
        if menu.options.tamper:
          checks.tamper_scripts()