iqzer0
iqzer0

Reputation: 163

How do i make it stop and say connection timeout if it takes too long to connect?

How can i make it stop if the connection is taking too long, it gets stuck at

** Checking Host: http://221.22.145.11 **


working host: http://50.22.1.238:8090

a host which is down: http://221.22.145.11

            # coding: utf-8
    # JexBoss v1.0. @autor: João Filho Matos Figueiredo ([email protected])
    # Updates: https://github.com/joaomatosf/jexboss
    # Free for distribution and modification, but the authorship should be preserved.


    import httplib, sys, urllib, os, time
    from urllib import urlencode

    RED = '\x1b[91m'
    RED1 = '\033[31m'
    BLUE = '\033[94m'
    GREEN = '\033[32m'
    BOLD = '\033[1m'
    NORMAL = '\033[0m'
    ENDC = '\033[0m'

    def getHost(url):
        tokens = url.split("://")
        if len(tokens) == 2: #foi fornecido protocolo
            return tokens[1].split(":")[0]
        else:
            return tokens.split(":")[0]

    def getProtocol(url):
        tokens = url.split("://")
        if tokens[0] == "https":
            return "https"
        else:
            return "http"

    def getPort(url):
        token = url[6:].split(":")
        if len(token) == 2:
            return token[1]
        elif getProtocol(url) == "https":
            return 443
        else:
            return 80

    def getConnection(url):
        if getProtocol(url) == "https":
            return httplib.HTTPSConnection(getHost(url), getPort(url))
        else:
            return httplib.HTTPConnection(getHost(url), getPort(url))


    def getSuccessfully(url, path):
            result = 404
            time.sleep(5)
            conn = getConnection(url)
            conn.request("GET", path)
            result = conn.getresponse().status
            if result == 404:
                conn.close()
                time.sleep(7)
                conn = getConnection(url)
                conn.request("GET", path)
                result = conn.getresponse().status
                conn.close()
            return result

    def checkVul(url):

        print ( GREEN +" ** Checking Host: %s **\n" %url )

        path = { "jmx-console"       : "/jmx-console/HtmlAdaptor?action=inspectMBean&name=jboss.system:type=ServerInfo",
                 "web-console"       : "/web-console/ServerInfo.jsp",
                 "JMXInvokerServlet" : "/invoker/JMXInvokerServlet"}

        for i in path.keys():
            try:
                print GREEN + " * Checking %s: \t" %i + ENDC,
                conn = getConnection(url)
                conn.request("HEAD", path[i])
                path[i] = conn.getresponse().status
                if path[i] == 200 or path[i] == 500:
                    print RED + "[ VULNERABLE ]" + ENDC
                else: print GREEN + "[ OK ]"
                conn.close()
            except:
                print RED + "\n * An error ocurred while contaction the host %s\n" %url + ENDC
                path[i] = 505

        return path

    def clear():
        if os.name == 'posix':
            os.system('clear')
        elif os.name == ('ce', 'nt', 'dos'):
            os.system('cls')

    def checkArgs(args):
        if len(args) < 2 or args[1].count('.') < 1:
            return 1,"You must provide the host name or IP address you want to test."
        elif len(args[1].split('://')) == 1:
            return 2, 'Changing address "%s" to "http://%s"' %(args[1], args[1])
        elif args[1].count('http') == 1 and args[1].count('.') > 1:
            return 0, ""
        else:
            return 1, 'Parâmetro inválido'

    def banner():
        clear()
        print (RED1+"\n * --- JexBoss: Jboss verify and EXploitation Tool  --- *\n"
                  " |                                                      |\n"
                  " | @author:  João Filho Matos Figueiredo                |\n"
                  " | @contact: [email protected]                       |\n"
                  " |                                                      |\n"
                  " | @update: https://github.com/joaomatosf/jexboss       |\n"
                  " #______________________________________________________#\n\n" )

    banner()
    # check python version
    if sys.version_info[0] == 3:
        print (RED + "\n * Not compatible with version 3 of python.\n"
                      "   Please run it with version 2.7 or lower.\n\n"
                +BLUE+" * Example:\n"
                      "   python2.7 " + sys.argv[0]+ " https://example.com\n\n"+ENDC )
        sys.exit(1)

    # check Args
    status, message = checkArgs(sys.argv)
    if status == 0:
        url = sys.argv[1]
    elif status == 1:
        print RED + "\n * Error: %s" %message
        print BLUE + "\n Example:\n python %s https://site.com.br\n" %sys.argv[0] + ENDC
        sys.exit(status)
    elif status == 2:
        url = ''.join(['http://',sys.argv[1]])

    # check vulnerabilities
    mapResult = checkVul(url)

    # performs exploitation
    for i in ["jmx-console", "web-console", "JMXInvokerServlet"]:
        if mapResult[i] == 200 or mapResult[i] == 500:
            print BLUE + ("\n\n * Do you want to try to run an automated exploitation via \""+BOLD+i+NORMAL+"\" ?\n"
                          "   This operation will provide a simple command shell to execute commands on the server..\n"
                     +RED+"   Continue only if you have permission!" +ENDC)
            if raw_input("   yes/NO ? ").lower() == "yes":
                autoExploit(url, i)

    # resume results
    if mapResult.values().count(200) > 0:
        banner()
        print RED+ " Results: potentially compromised server!" +ENDC
        print (GREEN+" * - - - - - - -  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*\n\n"
                  " Recommendations: \n"
                  " - If possible, discard this server!\n\n"
                  " * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*\n" )
    elif mapResult.values().count(505) == 0:
        print ( GREEN+ "\n\n * Results: \n"
                "   The server is not vulnerable to bugs tested ... :D\n\n" + ENDC)

    # infos 
    print (ENDC+" * Info: review, suggestions, updates, etc: \n"
                 "   https://github.com/joaomatosf/jexboss\n"
                 "   [email protected]\n")

    print ENDC

the full code is at https://raw.githubusercontent.com/joaomatosf/jexboss/master/jexboss.py

Upvotes: 0

Views: 672

Answers (1)

Iron Fist
Iron Fist

Reputation: 10951

Use the REQUEST_TIMEOUT status code, this way (take from Python Docs):

>>> res = conn.getresponse()
>>> print res.status, res.reason
408 REQUEST_TIMEOUT

Just like you did for checking the response status code, in your code:

path[i] = conn.getresponse().status
     if path[i] == 408:
         print 'Connection TimeOut'
     else: 'Connected'

EDIT: Setup your required timeout in your getConnection(url) function, this way:

def getConnection(url):
    if getProtocol(url) == "https":
        return httplib.HTTPSConnection(getHost(url), getPort(url),timeout=5)
    else:
        return httplib.HTTPConnection(getHost(url), getPort(url),timeout=5)

In this example, the function will try to connect to your url and will timeout within 5seconds if no connection could be established.

Upvotes: 1

Related Questions