Exemplo n.º 1
0
def main():
    from optparse import OptionParser
    from datetime import datetime
    import anydbm
    import os
    from sys import exit
    import logging
    import pickle
    from libs.svhelper import resumeFrom, calcloglevel
    from libs.svhelper import standardoptions, standardscanneroptions
    from libs.svhelper import getRange

    usage = "usage: %prog [options] target\r\n"
    usage += "examples:\r\n"
    usage += "%prog -e100-999 10.0.0.1\r\n"
    usage += "%prog -d dictionary.txt 10.0.0.2\r\n"
    parser = OptionParser(usage,
                          version="%prog v" + str(__version__) + __GPL__)
    parser = standardoptions(parser)
    parser = standardscanneroptions(parser)
    parser.add_option(
        "-d",
        "--dictionary",
        dest="dictionary",
        type="string",
        help="specify a dictionary file with possible extension names",
        metavar="DICTIONARY")
    parser.add_option(
        "-m",
        "--method",
        dest="method",
        type="string",
        help=
        "specify a request method. The default is REGISTER. Other possible methods are OPTIONS and INVITE",
        default="REGISTER",
        metavar="OPTIONS")
    parser.add_option(
        "-e",
        "--extensions",
        dest="range",
        default='100-999',
        help=
        "specify an extension or extension range\r\nexample: -e 100-999,1000-1500,9999",
        metavar="RANGE")
    parser.add_option("-z",
                      "--zeropadding",
                      dest="zeropadding",
                      type="int",
                      help="""the number of zeros used to padd the username.
                  the options "-e 1-9999 -z 4" would give 0001 0002 0003 ... 9999""",
                      default=0,
                      metavar="PADDING")
    parser.add_option('--force',
                      dest="force",
                      action="store_true",
                      default=False,
                      help="Force scan, ignoring initial sanity checks.")
    parser.add_option(
        '--template',
        '-T',
        action="store",
        dest="template",
        help=
        """A format string which allows us to specify a template for the extensions
                      example svwar.py -e 1-999 --template="123%#04i999" would scan between 1230001999 to 1230999999"
                      """)
    parser.add_option('--enabledefaults',
                      '-D',
                      action="store_true",
                      dest="defaults",
                      default=False,
                      help="""Scan for default / typical extensions such as
                      1000,2000,3000 ... 1100, etc. This option is off by default.
                      Use --enabledefaults to enable this functionality""")
    parser.add_option(
        '--maximumtime',
        action='store',
        dest='maximumtime',
        type="int",
        default=10,
        help="""Maximum time in seconds to keep sending requests without
                      receiving a response back""")
    parser.add_option(
        '--domain',
        dest="domain",
        help=
        "force a specific domain name for the SIP message, eg. -d example.org")
    parser.add_option("--debug",
                      dest="printdebug",
                      help="Print SIP messages received",
                      default=False,
                      action="store_true")

    (options, args) = parser.parse_args()
    exportpath = None
    logging.basicConfig(level=calcloglevel(options))
    logging.debug('started logging')
    if options.force:
        initialcheck = False
    else:
        initialcheck = True
    if options.template is not None:
        try:
            options.template % 1
        except TypeError:
            logging.critical(
                "The format string template is not correct. Please provide an appropiate one"
            )
            exit(1)
    if options.resume is not None:
        exportpath = os.path.join(os.path.expanduser('~'), '.sipvicious',
                                  __prog__, options.resume)
        if os.path.exists(os.path.join(exportpath, 'closed')):
            logging.error("Cannot resume a session that is complete")
            exit(1)
        if not os.path.exists(exportpath):
            logging.critical('A session with the name %s was not found' %
                             options.resume)
            exit(1)
        optionssrc = os.path.join(exportpath, 'options.pkl')
        previousresume = options.resume
        previousverbose = options.verbose
        options, args = pickle.load(open(optionssrc, 'r'))
        options.resume = previousresume
        options.verbose = previousverbose
    elif options.save is not None:
        exportpath = os.path.join(os.path.expanduser('~'), '.sipvicious',
                                  __prog__, options.save)
    if len(args) != 1:
        parser.error("provide one hostname")
    else:
        host = args[0]
    if options.dictionary is not None:
        guessmode = 2
        try:
            dictionary = open(options.dictionary, 'r')
        except IOError:
            logging.error("could not open %s" % options.dictionary)
            exit(1)
        if options.resume is not None:
            lastextensionsrc = os.path.join(exportpath, 'lastextension.pkl')
            previousposition = pickle.load(open(lastextensionsrc, 'r'))
            dictionary.seek(previousposition)
        guessargs = dictionary
    else:
        guessmode = 1
        if options.resume is not None:
            lastextensionsrc = os.path.join(exportpath, 'lastextension.pkl')
            try:
                previousextension = pickle.load(open(lastextensionsrc, 'r'))
            except IOError:
                logging.critical('Could not read from %s' % lastipsrc)
                exit(1)
            logging.debug('Previous range: %s' % options.range)
            options.range = resumeFrom(previousextension, options.range)
            logging.debug('New range: %s' % options.range)
            logging.info('Resuming from %s' % previousextension)
        extensionstotry = getRange(options.range)
        guessargs = (extensionstotry, options.zeropadding, options.template,
                     options.defaults)
    if options.save is not None:
        if options.resume is None:
            exportpath = os.path.join(os.path.expanduser('~'), '.sipvicious',
                                      __prog__, options.save)
            if os.path.exists(exportpath):
                logging.warn(
                    'we found a previous scan with the same name. Please choose a new session name'
                )
                exit(1)
            logging.debug('creating an export location %s' % exportpath)
            try:
                os.makedirs(exportpath, mode=0700)
            except OSError:
                logging.critical('could not create the export location %s' %
                                 exportpath)
                exit(1)
            optionsdst = os.path.join(exportpath, 'options.pkl')
            logging.debug('saving options to %s' % optionsdst)
            pickle.dump([options, args], open(optionsdst, 'w'))
    if options.autogetip:
        tmpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tmpsocket.connect(("msn.com", 80))
        options.externalip = tmpsocket.getsockname()[0]
        tmpsocket.close()
    enableack = False
    if options.method.upper() == 'INVITE':
        enableack = True
    sipvicious = TakeASip(
        host,
        port=options.port,
        selecttime=options.selecttime,
        method=options.method,
        compact=options.enablecompact,
        guessmode=guessmode,
        guessargs=guessargs,
        sessionpath=exportpath,
        initialcheck=initialcheck,
        externalip=options.externalip,
        enableack=enableack,
        maxlastrecvtime=options.maximumtime,
        localport=options.localport,
        domain=options.domain,
        printdebug=options.printdebug,
    )
    start_time = datetime.now()
    #logging.info("scan started at %s" % str(start_time))
    logging.info("start your engines")
    try:
        sipvicious.start()
        if exportpath is not None:
            open(os.path.join(exportpath, 'closed'), 'w').close()
    except KeyboardInterrupt:
        logging.warn('caught your control^c - quiting')
    except Exception, err:
        import traceback
        from libs.svhelper import reportBugToAuthor
        if options.reportBack:
            logging.critical(
                "Got unhandled exception : sending report to author")
            reportBugToAuthor(traceback.format_exc())
        else:
            logging.critical(
                "Unhandled exception - please run same command with the -R option to send me an automated report"
            )
            pass
        logging.exception("Exception")
Exemplo n.º 2
0
     if options.resume is not None:
         lastextensionsrc = os.path.join(exportpath,'lastextension.pkl')
         previousposition = pickle.load(open(lastextensionsrc,'r'))
         dictionary.seek(previousposition)
     guessargs = dictionary
 else:
     guessmode = 1
     if options.resume is not None:
         lastextensionsrc = os.path.join(exportpath,'lastextension.pkl')
         try:
             previousextension = pickle.load(open(lastextensionsrc,'r'))
         except IOError:
             logging.critical('Could not read from %s' % lastipsrc)
             exit(1)
         logging.debug('Previous range: %s' % options.range)
         options.range = resumeFrom(previousextension,options.range)
         logging.debug('New range: %s' % options.range)
         logging.info('Resuming from %s' % previousextension)
     extensionstotry = getRange(options.range)
     guessargs = (extensionstotry,options.zeropadding,options.template,options.defaults)
 if options.save is not None:
     if options.resume is None:
         exportpath = os.path.join(os.path.expanduser('~'),'.sipvicious',__prog__,options.save)
         if os.path.exists(exportpath):
             logging.warn('we found a previous scan with the same name. Please choose a new session name')
             exit(1)
         logging.debug('creating an export location %s' % exportpath)
         try:
             os.makedirs(exportpath,mode=0700)
         except OSError:
             logging.critical('could not create the export location %s' % exportpath)
Exemplo n.º 3
0
    def main(self):
        #Here is the main function of the class.
        #Note that it's just a name unlike java...
        #See below for the entry point of the program.

        from optparse import OptionParser
        from datetime import datetime
        from libs.svhelper import getRange, resumeFrom,calcloglevel
        from sys import exit
        import logging
        import pickle
        from libs.svhelper import standardoptions, standardscanneroptions

        usage = "usage: %prog -u username [options] target\r\n"
        usage += "examples:\r\n"
        usage += "%prog svcrack -u100 -d dictionary.txt 10.0.0.1\r\n"
        usage += "%prog svcrack -u100 -r1-9999 -z4 10.0.0.1\r\n"
        # Parse arguments.
        # The OptionParser constructor has no required arguments, but a number of optional keyword arguments.
        # You should always pass them as keyword arguments, i.e. do not rely on the order in which the arguments are declared.
        # More about this method of parsing, see there http://docs.python.org/2/library/optparse.html#optparse.OptionParser
        parser = OptionParser(usage,version="%prog v"+str(__version__))
        parser = standardoptions(parser)
        parser = standardscanneroptions(parser)
        parser.add_option("-u", "--username", dest="username",
                      help="username to try crack", metavar="USERNAME")
        parser.add_option("-d", "--dictionary", dest="dictionary", type="string",
                      help="specify a dictionary file with passwords",
                      metavar="DICTIONARY")
        parser.add_option("-r", "--range", dest="range", default="100-999",
                      help="specify a range of numbers. example: 100-200,300-310,400",
                      metavar="RANGE")
        parser.add_option("-e", "--extension", dest="extension",
                      help="Extension to crack. Only specify this when the extension is different from the username.",
                      metavar="EXTENSION")
        parser.add_option("-z", "--zeropadding", dest="zeropadding", type="int", default=0,
                      help="""the number of zeros used to padd the password.
                      the options "-r 1-9999 -z 4" would give 0001 0002 0003 ... 9999""",
                      metavar="PADDING")
        parser.add_option("-n", "--reusenonce", dest="reusenonce", default=False,
                      help="Reuse nonce. Some SIP devices don't mind you reusing the nonce (making them vulnerable to replay attacks). Speeds up the cracking.",
                      action="store_true",
                      )
        parser.add_option('--template', '-T', action="store", dest="template",
                      help="""A format string which allows us to specify a template for the extensions
                      example svwar.py -e 1-999 --template="123%#04i999" would scan between 1230001999 to 1230999999"
                      """)
        parser.add_option('--maximumtime', action='store', dest='maximumtime', type="int",
                      default=10,
                      help="""Maximum time in seconds to keep sending requests without
                      receiving a response back""")
        parser.add_option('--enabledefaults', '-D', action="store_true", dest="defaults",
                      default=False, help="""Scan for default / typical passwords such as
                      1000,2000,3000 ... 1100, etc. This option is off by default.
                      Use --enabledefaults to enable this functionality""")
        parser.add_option('--domain', dest="domain",
                      help="force a specific domain name for the SIP message, eg. -d example.org")
        (options, args) = parser.parse_args()
        exportpath = None
        # Does basic configuration for the logging system by creating a StreamHandler with a default
        # Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and
        # critical() will call basicConfig() automatically if no handlers are defined for the root logger.
        logging.basicConfig(level=calcloglevel(options))
        logging.debug('started logging')

        if options.resume is not None:
            exportpath = os.path.join('.sipvicious',__prog__,options.resume)
            if os.path.exists(os.path.join(exportpath,'closed')):
                # Logs a message with level ERROR on the root logger.
                logging.error("Cannot resume a session that is complete")
                exit(1)
            if not os.path.exists(exportpath):
                # Logs a message with level CRITICAL on the root logger.
                logging.critical('A session with the name %s was not found'% options.resume)
                exit(1)
            optionssrc = os.path.join(exportpath,'options.pkl')
            previousresume = options.resume
            previousverbose = options.verbose
            # Read a string from the open file object file and interpret it as a pickle data stream,
            # reconstructing and returning the original object hierarchy. This is equivalent to Unpickler(file).load().
            # More about pickle http://docs.python.org/2/library/pickle.html
            options,args = pickle.load(open(optionssrc,'r'))
            options.resume = previousresume
            options.verbose = previousverbose
        elif options.save is not None:
            exportpath = os.path.join('.sipvicious',__prog__,options.save)
            logging.debug('Session path: %s' % exportpath)
    
        if options.resume is not None:
            exportpath = os.path.join('.sipvicious',__prog__,options.resume)
            if not os.path.exists(exportpath):
                logging.critical('A session with the name %s was not found'% options.resume)
                exit(1)
            optionssrc = os.path.join(exportpath,'options.pkl')
            previousresume = options.resume
            previousverbose = options.verbose
            options,args = pickle.load(open(optionssrc,'r'))
            options.resume = previousresume
            options.verbose = previousverbose
        elif options.save is not None:
            exportpath = os.path.join('.sipvicious',__prog__,options.save)
        # Check that there is no empty arg.
        if len(args) == 1:
            parser.error("provide one hostname")
        else:
            host=args[1]
        
        if options.username is None:
            parser.error("provide one username to crack")

        if options.dictionary is not None:
            crackmode=2
            try:
                dictionary = open(options.dictionary,'r')
            except IOError:
                # Logs a message with level ERROR on the root logger.
                logging.error("could not open %s" % options.dictionary)
            if options.resume is not None:
                lastpasswdsrc = os.path.join(exportpath,'lastpasswd.pkl')
                previousposition = pickle.load(open(lastpasswdsrc,'r'))
                dictionary.seek(previousposition)
            crackargs = dictionary
        else:
            crackmode = 1
            if options.resume is not None:
                lastpasswdsrc = os.path.join(exportpath,'lastpasswd.pkl')
                try:
                    previouspasswd = pickle.load(open(lastpasswdsrc,'r'))
                except IOError:
                    logging.critical('Could not read from %s' % lastpasswdsrc)
                    exit(1)
                # Logs a message with level DEBUG on the root logger.
                logging.debug('Previous range: %s' % options.range)
                options.range = resumeFrom(previouspasswd,options.range)
                logging.debug('New range: %s' % options.range)
                # Logs a message with level INFO on the root logger.
                logging.info('Resuming from %s' % previouspasswd)
            rangelist = getRange(options.range)
            crackargs = (rangelist,options.zeropadding,options.template,options.defaults,[options.username])
        if options.save is not None:
            if options.resume is None:
                exportpath = os.path.join('.sipvicious',__prog__,options.save)
                if os.path.exists(exportpath):
                    logging.warn('we found a previous scan with the same name. Please choose a new session name')
                    exit(1)
                logging.debug('creating an export location %s' % exportpath)
                try:
                    # Change permission for directory
                    os.makedirs(exportpath,mode=0700)
                except OSError:
                    logging.critical('could not create the export location %s' % exportpath)
                    exit(1)
                optionsdst = os.path.join(exportpath,'options.pkl')
                logging.debug('saving options to %s' % optionsdst)
                # Write a pickled representation of obj to the open file object file.
                pickle.dump([options,args],open(optionsdst,'w'))
        if options.autogetip:
            # Create a new socket using the given address family, socket type and protocol number.
            # The address family should be AF_INET (the default), AF_INET6 or AF_UNIX. The socket type should be
            # SOCK_STREAM (the default), SOCK_DGRAM or perhaps one of the other SOCK_ constants. The protocol number
            # is usually zero and may be omitted in that case.
            tmpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            # Connect to a remote socket at address.
            tmpsocket.connect(("msn.com",80))
            # Return the socket's own address. This is useful to find out the port number of an IPv4/v6 socket, for instance.
            options.externalip=tmpsocket.getsockname()[0]
            # Close the socket. All future operations on the socket object will fail.
            tmpsocket.close()
        #We call an instance of the class ASipOfRedWine defined above
        sipvicious = ASipOfRedWine(
                        host,
                        username=options.username,
                        selecttime=options.selecttime,
                        compact=options.enablecompact,
                        crackmode=crackmode,
                        crackargs=crackargs,
                        reusenonce=options.reusenonce,
                        extension=options.extension,
                        sessionpath=exportpath,
                        port=options.port,
                        externalip=options.externalip,
                        maxlastrecvtime=options.maximumtime,
                        localport=options.localport,
                        domain=options.domain
                        )
        # Get current date and time
        start_time = datetime.now()
        logging.info("scan started at %s" % str(start_time))
        try:
            # Call method start. That will start perform crack operations
            sipvicious.start()
            if exportpath is not None:
                open(os.path.join(exportpath,'closed'),'w').close()
        except KeyboardInterrupt:
            logging.warn('caught your control^c - quiting')
        except Exception, err:
            logging.exception( "Exception" )
Exemplo n.º 4
0
Arquivo: svwar.py Projeto: realvoip/14
     if options.resume is not None:
         lastextensionsrc = os.path.join(exportpath, 'lastextension.pkl')
         previousposition = pickle.load(open(lastextensionsrc, 'r'))
         dictionary.seek(previousposition)
     guessargs = dictionary
 else:
     guessmode = 1
     if options.resume is not None:
         lastextensionsrc = os.path.join(exportpath, 'lastextension.pkl')
         try:
             previousextension = pickle.load(open(lastextensionsrc, 'r'))
         except IOError:
             logging.critical('Could not read from %s' % lastipsrc)
             exit(1)
         logging.debug('Previous range: %s' % options.range)
         options.range = resumeFrom(previousextension, options.range)
         logging.debug('New range: %s' % options.range)
         logging.info('Resuming from %s' % previousextension)
     extensionstotry = getRange(options.range)
     guessargs = (extensionstotry, options.zeropadding, options.template,
                  options.defaults)
 if options.save is not None:
     if options.resume is None:
         exportpath = os.path.join('.sipvicious', __prog__, options.save)
         if os.path.exists(exportpath):
             logging.warn(
                 'we found a previous scan with the same name. Please choose a new session name'
             )
             exit(1)
         logging.debug('creating an export location %s' % exportpath)
         try:
Exemplo n.º 5
0
def main():
    from optparse import OptionParser
    from datetime import datetime
    from libs.svhelper import getRange, resumeFrom, calcloglevel
    import anydbm
    import os
    from sys import exit
    import logging
    import pickle
    from libs.svhelper import standardoptions, standardscanneroptions

    usage = "usage: %prog -u username [options] target\r\n"
    usage += "examples:\r\n"
    usage += "%prog -u100 -d dictionary.txt 10.0.0.1\r\n"
    usage += "%prog -u100 -r1-9999 -z4 10.0.0.1\r\n"
    parser = OptionParser(usage,
                          version="%prog v" + str(__version__) + __GPL__)
    parser = standardoptions(parser)
    parser = standardscanneroptions(parser)
    parser.add_option("-u",
                      "--username",
                      dest="username",
                      help="username to try crack",
                      metavar="USERNAME")
    parser.add_option("-d",
                      "--dictionary",
                      dest="dictionary",
                      type="string",
                      help="specify a dictionary file with passwords",
                      metavar="DICTIONARY")
    parser.add_option(
        "-r",
        "--range",
        dest="range",
        default="100-999",
        help="specify a range of numbers. example: 100-200,300-310,400",
        metavar="RANGE")
    parser.add_option(
        "-e",
        "--extension",
        dest="extension",
        help=
        "Extension to crack. Only specify this when the extension is different from the username.",
        metavar="EXTENSION")
    parser.add_option("-z",
                      "--zeropadding",
                      dest="zeropadding",
                      type="int",
                      default=0,
                      help="""the number of zeros used to padd the password.
                  the options "-r 1-9999 -z 4" would give 0001 0002 0003 ... 9999""",
                      metavar="PADDING")
    parser.add_option(
        "-n",
        "--reusenonce",
        dest="reusenonce",
        default=False,
        help=
        "Reuse nonce. Some SIP devices don't mind you reusing the nonce (making them vulnerable to replay attacks). Speeds up the cracking.",
        action="store_true",
    )
    parser.add_option(
        '--template',
        '-T',
        action="store",
        dest="template",
        help=
        """A format string which allows us to specify a template for the extensions
                      example svwar.py -e 1-999 --template="123%#04i999" would scan between 1230001999 to 1230999999"
                      """)
    parser.add_option(
        '--maximumtime',
        action='store',
        dest='maximumtime',
        type="int",
        default=10,
        help="""Maximum time in seconds to keep sending requests without
                      receiving a response back""")
    parser.add_option('--enabledefaults',
                      '-D',
                      action="store_true",
                      dest="defaults",
                      default=False,
                      help="""Scan for default / typical passwords such as
                      1000,2000,3000 ... 1100, etc. This option is off by default.
                      Use --enabledefaults to enable this functionality""")
    parser.add_option(
        '--domain',
        dest="domain",
        help=
        "force a specific domain name for the SIP message, eg. -d example.org")
    (options, args) = parser.parse_args()
    exportpath = None
    logging.basicConfig(level=calcloglevel(options))
    logging.debug('started logging')
    if options.resume is not None:
        exportpath = os.path.join(os.path.expanduser('~'), '.sipvicious',
                                  __prog__, options.resume)
        if os.path.exists(os.path.join(exportpath, 'closed')):
            logging.error("Cannot resume a session that is complete")
            exit(1)
        if not os.path.exists(exportpath):
            logging.critical('A session with the name %s was not found' %
                             options.resume)
            exit(1)
        optionssrc = os.path.join(exportpath, 'options.pkl')
        previousresume = options.resume
        previousverbose = options.verbose
        options, args = pickle.load(open(optionssrc, 'r'))
        options.resume = previousresume
        options.verbose = previousverbose
    elif options.save is not None:
        exportpath = os.path.join(os.path.expanduser('~'), '.sipvicious',
                                  __prog__, options.save)
        logging.debug('Session path: %s' % exportpath)

    if options.resume is not None:
        exportpath = os.path.join(os.path.expanduser('~'), '.sipvicious',
                                  __prog__, options.resume)
        if not os.path.exists(exportpath):
            logging.critical('A session with the name %s was not found' %
                             options.resume)
            exit(1)
        optionssrc = os.path.join(exportpath, 'options.pkl')
        previousresume = options.resume
        previousverbose = options.verbose
        options, args = pickle.load(open(optionssrc, 'r'))
        options.resume = previousresume
        options.verbose = previousverbose
    elif options.save is not None:
        exportpath = os.path.join(os.path.expanduser('~'), '.sipvicious',
                                  __prog__, options.save)
    if len(args) != 1:
        parser.error("provide one hostname")
    else:
        host = args[0]

    if options.username is None:
        parser.error("provide one username to crack")

    if options.dictionary is not None:
        crackmode = 2
        try:
            dictionary = open(options.dictionary, 'r')
        except IOError:
            logging.error("could not open %s" % options.dictionary)
        if options.resume is not None:
            lastpasswdsrc = os.path.join(exportpath, 'lastpasswd.pkl')
            previousposition = pickle.load(open(lastpasswdsrc, 'r'))
            dictionary.seek(previousposition)
        crackargs = dictionary
    else:
        crackmode = 1
        if options.resume is not None:
            lastpasswdsrc = os.path.join(exportpath, 'lastpasswd.pkl')
            try:
                previouspasswd = pickle.load(open(lastpasswdsrc, 'r'))
            except IOError:
                logging.critical('Could not read from %s' % lastpasswdsrc)
                exit(1)
            logging.debug('Previous range: %s' % options.range)
            options.range = resumeFrom(previouspasswd, options.range)
            logging.debug('New range: %s' % options.range)
            logging.info('Resuming from %s' % previouspasswd)
        rangelist = getRange(options.range)
        crackargs = (rangelist, options.zeropadding, options.template,
                     options.defaults, [options.username])
    if options.save is not None:
        if options.resume is None:
            exportpath = os.path.join(os.path.expanduser('~'), '.sipvicious',
                                      __prog__, options.save)
            if os.path.exists(exportpath):
                logging.warn(
                    'we found a previous scan with the same name. Please choose a new session name'
                )
                exit(1)
            logging.debug('creating an export location %s' % exportpath)
            try:
                os.makedirs(exportpath, mode=0700)
            except OSError:
                logging.critical('could not create the export location %s' %
                                 exportpath)
                exit(1)
            optionsdst = os.path.join(exportpath, 'options.pkl')
            logging.debug('saving options to %s' % optionsdst)
            pickle.dump([options, args], open(optionsdst, 'w'))
    if options.autogetip:
        tmpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tmpsocket.connect(("msn.com", 80))
        options.externalip = tmpsocket.getsockname()[0]
        tmpsocket.close()
    sipvicious = ASipOfRedWine(host,
                               username=options.username,
                               selecttime=options.selecttime,
                               compact=options.enablecompact,
                               crackmode=crackmode,
                               crackargs=crackargs,
                               reusenonce=options.reusenonce,
                               extension=options.extension,
                               sessionpath=exportpath,
                               port=options.port,
                               externalip=options.externalip,
                               maxlastrecvtime=options.maximumtime,
                               localport=options.localport,
                               domain=options.domain)

    start_time = datetime.now()
    logging.info("scan started at %s" % str(start_time))
    try:
        sipvicious.start()
        if exportpath is not None:
            open(os.path.join(exportpath, 'closed'), 'w').close()
    except KeyboardInterrupt:
        logging.warn('caught your control^c - quiting')
    except Exception, err:
        import traceback
        from libs.svhelper import reportBugToAuthor
        if options.reportBack:
            logging.critical(
                "Got unhandled exception : sending report to author")
            reportBugToAuthor(traceback.format_exc())
        else:
            logging.critical(
                "Unhandled exception - please run same command with the -R option to send me an automated report"
            )
            pass
        logging.exception("Exception")
Exemplo n.º 6
0
     if options.resume is not None:
         lastpasswdsrc = os.path.join(exportpath, 'lastpasswd.pkl')
         previousposition = pickle.load(open(lastpasswdsrc, 'r'))
         dictionary.seek(previousposition)
     crackargs = dictionary
 else:
     crackmode = 1
     if options.resume is not None:
         lastpasswdsrc = os.path.join(exportpath, 'lastpasswd.pkl')
         try:
             previouspasswd = pickle.load(open(lastpasswdsrc, 'r'))
         except IOError:
             logging.critical('Could not read from %s' % lastpasswdsrc)
             exit(1)
         logging.debug('Previous range: %s' % options.range)
         options.range = resumeFrom(previouspasswd, options.range)
         logging.debug('New range: %s' % options.range)
         logging.info('Resuming from %s' % previouspasswd)
     rangelist = getRange(options.range)
     crackargs = (rangelist, options.zeropadding, options.template,
                  options.defaults, [options.username])
 if options.save is not None:
     if options.resume is None:
         exportpath = os.path.join(os.path.expanduser('~'), '.sipvicious',
                                   __prog__, options.save)
         if os.path.exists(exportpath):
             logging.warn(
                 'we found a previous scan with the same name. Please choose a new session name'
             )
             exit(1)
         logging.debug('creating an export location %s' % exportpath)
Exemplo n.º 7
0
     if options.resume is not None:
         lastpasswdsrc = os.path.join(exportpath,'lastpasswd.pkl')
         previousposition = pickle.load(open(lastpasswdsrc,'r'))
         dictionary.seek(previousposition)
     crackargs = dictionary
 else:
     crackmode = 1
     if options.resume is not None:
         lastpasswdsrc = os.path.join(exportpath,'lastpasswd.pkl')
         try:
             previouspasswd = pickle.load(open(lastpasswdsrc,'r'))
         except IOError:
             logging.critical('Could not read from %s' % lastpasswdsrc)
             exit(1)
         logging.debug('Previous range: %s' % options.range)
         options.range = resumeFrom(previouspasswd,options.range)
         logging.debug('New range: %s' % options.range)
         logging.info('Resuming from %s' % previouspasswd)
     rangelist = getRange(options.range)        
     crackargs = (rangelist,options.zeropadding,options.template,options.defaults,[options.username])
 if options.save is not None:
     if options.resume is None:
         exportpath = os.path.join(os.path.expanduser('~'),'.sipvicious',__prog__,options.save)
         if os.path.exists(exportpath):
             logging.warn('we found a previous scan with the same name. Please choose a new session name')
             exit(1)
         logging.debug('creating an export location %s' % exportpath)
         try:
             os.makedirs(exportpath,mode=0700)
         except OSError:
             logging.critical('could not create the export location %s' % exportpath)
Exemplo n.º 8
0
    def main(self):
        #Here is the main function of the class.
        #Note that it's just a name unlike java...
        #See below for the entry point of the program.

        from optparse import OptionParser
        from datetime import datetime
        import os
        from sys import exit
        import logging
        from libs.svhelper import resumeFrom, calcloglevel
        from libs.svhelper import standardoptions, standardscanneroptions
        from libs.svhelper import getRange
    
        usage = "usage: %prog svwar [options] target\r\n"
        usage += "examples:\r\n"
        usage += "%prog svwar -e100-999 10.0.0.1\r\n"
        usage += "%prog svwar -d dictionary.txt 10.0.0.2\r\n"
        # Parse arguments.
        # The OptionParser constructor has no required arguments, but a number of optional keyword arguments.
        # You should always pass them as keyword arguments, i.e. do not rely on the order in which the arguments are declared.
        # More about this method of parsing, see there http://docs.python.org/2/library/optparse.html#optparse.OptionParser
        parser = OptionParser(usage,version="%prog v"+str(__version__))
        parser = standardoptions(parser)
        parser = standardscanneroptions(parser)
        parser.add_option("-d", "--dictionary", dest="dictionary", type="string",
                      help="specify a dictionary file with possible extension names",
                      metavar="DICTIONARY")
        parser.add_option("-m", "--method", dest="method", type="string",
                      help="specify a request method. The default is REGISTER. Other possible methods are OPTIONS and INVITE",
                      default="REGISTER",
                      metavar="OPTIONS")
        parser.add_option("-e", "--extensions", dest="range", default='100-999',
                      help="specify an extension or extension range\r\nexample: -e 100-999,1000-1500,9999",
                      metavar="RANGE")
        parser.add_option("-z", "--zeropadding", dest="zeropadding", type="int",
                      help="""the number of zeros used to padd the username.
                      the options "-e 1-9999 -z 4" would give 0001 0002 0003 ... 9999""",
                      default=0,
                      metavar="PADDING")
        parser.add_option('--force', dest="force", action="store_true",
                      default=False,
                      help="Force scan, ignoring initial sanity checks.")
        parser.add_option('--template', '-T', action="store", dest="template",
                      help="""A format string which allows us to specify a template for the extensions
                      example svwar.py -e 1-999 --template="123%#04i999" would scan between 1230001999 to 1230999999"
                      """)
        parser.add_option('--enabledefaults', '-D', action="store_true", dest="defaults",
                      default=False, help="""Scan for default / typical extensions such as
                      1000,2000,3000 ... 1100, etc. This option is off by default.
                      Use --enabledefaults to enable this functionality""")
        parser.add_option('--maximumtime', action='store', dest='maximumtime', type="int",
                      default=10,
                      help="""Maximum time in seconds to keep sending requests without
                      receiving a response back""")
        parser.add_option('--domain', dest="domain",
                      help="force a specific domain name for the SIP message, eg. -d example.org")
        parser.add_option("--debug", dest="printdebug",
                      help="Print SIP messages received",
                      default=False, action="store_true"
                      )

        (options, args) = parser.parse_args()
        exportpath = None
        # Does basic configuration for the logging system by creating a StreamHandler with a default
        # Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and
        # critical() will call basicConfig() automatically if no handlers are defined for the root logger.
        logging.basicConfig(level=calcloglevel(options))
        logging.debug('started logging')
        if options.force:
            initialcheck = False
        else:
            initialcheck = True
        if options.template is not None:
            try:
                options.template % 1
            except TypeError:
                logging.critical("The format string template is not correct. Please provide an appropiate one")
                exit(1)
        if options.resume is not None:
            exportpath = os.path.join('.sipvicious',__prog__,options.resume)
            if os.path.exists(os.path.join(exportpath,'closed')):
                logging.error("Cannot resume a session that is complete")
                exit(1)
            if not os.path.exists(exportpath):
                logging.critical('A session with the name %s was not found'% options.resume)
                exit(1)
            optionssrc = os.path.join(exportpath,'options.pkl')
            previousresume = options.resume
            previousverbose = options.verbose
            # Read a string from the open file object file and interpret it as a pickle data stream,
            # reconstructing and returning the original object hierarchy. This is equivalent to Unpickler(file).load().
            # More about pickle http://docs.python.org/2/library/pickle.html
            options,args = pickle.load(open(optionssrc,'r'))
            options.resume = previousresume
            options.verbose = previousverbose
        elif options.save is not None:
            exportpath = os.path.join('.sipvicious',__prog__,options.save)
        # Check that there is no empty arg.
        if len(args) != 1:
            parser.error("provide one hostname")
        else:
            host=args[0]
        if options.dictionary is not None:
            guessmode=2
            try:
                dictionary = open(options.dictionary,'r')
            except IOError:
                logging.error( "could not open %s" % options.dictionary )
                exit(1)
            if options.resume is not None:
                lastextensionsrc = os.path.join(exportpath,'lastextension.pkl')
                previousposition = pickle.load(open(lastextensionsrc,'r'))
                dictionary.seek(previousposition)
            guessargs = dictionary
        else:
            guessmode = 1
            if options.resume is not None:
                lastextensionsrc = os.path.join(exportpath,'lastextension.pkl')
                try:
                    previousextension = pickle.load(open(lastextensionsrc,'r'))
                except IOError:
                    logging.critical('Could not read from %s' % lastextensionsrc)
                    exit(1)
                # Logs a message with level DEBUG on the root logger.
                logging.debug('Previous range: %s' % options.range)
                options.range = resumeFrom(previousextension,options.range)
                logging.debug('New range: %s' % options.range)
                # Logs a message with level INFO on the root logger.
                logging.info('Resuming from %s' % previousextension)
            # Create range of port
            extensionstotry = getRange(options.range)
            guessargs = (extensionstotry,options.zeropadding,options.template,options.defaults)
        if options.save is not None:
            if options.resume is None:
                exportpath = os.path.join('.sipvicious',__prog__,options.save)
                if os.path.exists(exportpath):
                    logging.warn('we found a previous scan with the same name. Please choose a new session name')
                    exit(1)
                logging.debug('creating an export location %s' % exportpath)
                try:
                    # Change permission for directory
                    os.makedirs(exportpath,mode=0700)
                except OSError:
                    logging.critical('could not create the export location %s' % exportpath)
                    exit(1)
                optionsdst = os.path.join(exportpath,'options.pkl')
                logging.debug('saving options to %s' % optionsdst)
                # Write a pickled representation of obj to the open file object file.
                pickle.dump([options,args],open(optionsdst,'w'))
        if options.autogetip:
            # Create a new socket using the given address family, socket type and protocol number.
            # The address family should be AF_INET (the default), AF_INET6 or AF_UNIX. The socket type should be
            # SOCK_STREAM (the default), SOCK_DGRAM or perhaps one of the other SOCK_ constants. The protocol number
            # is usually zero and may be omitted in that case.
            tmpsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            # Connect to a remote socket at address.
            tmpsocket.connect(("msn.com",80))
            # Return the socket's own address. This is useful to find out the port number of an IPv4/v6 socket, for instance.
            options.externalip=tmpsocket.getsockname()[0]
            # Cloase socket
            tmpsocket.close()
        enableack = False
        if options.method.upper() == 'INVITE':
            enableack = True
        #We call an instance of the class TakeASip defined above
        sipvicious = TakeASip(
                        host,
                        port=options.port,
                        selecttime=options.selecttime,
                        method=options.method,
                        compact=options.enablecompact,
                        guessmode=guessmode,
                        guessargs=guessargs,
                        sessionpath=exportpath,
                        initialcheck=initialcheck,
                        externalip=options.externalip,
                        enableack=enableack,
                        maxlastrecvtime=options.maximumtime,
                        localport=options.localport,
                        domain=options.domain,
                        printdebug=options.printdebug,
                        )
        start_time = datetime.now()
        #logging.info("scan started at %s" % str(start_time))
        logging.info( "start your engines" )
        try:
            sipvicious.start()
            if exportpath is not None:
                open(os.path.join(exportpath,'closed'),'w').close()
        except KeyboardInterrupt:
            logging.warn('caught your control^c - quiting')
        except Exception, err:
            import traceback
            from libs.svhelper import reportBugToAuthor
            if options.reportBack:
                logging.critical( "Got unhandled exception : sending report to author" )
                reportBugToAuthor(traceback.format_exc())
            else:
                logging.critical( "Unhandled exception - please run same command with the -R option to send me an automated report")
                pass
            logging.exception( "Exception" )