Example #1
0
         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)
Example #2
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" )
Example #3
0
 logging.basicConfig(level=calcloglevel(options))
 logging.debug('started logging')
 scanrandomstore = None
 if options.input is not None:
     db = os.path.join('.sipvicious', __prog__, options.input, 'resultua')
     if dbexists(db):
         scaniter = scanfromdb(db, options.method.split(','))
     else:
         logging.error(
             "the session name does not exist. Please use svreport to list existing scans"
         )
         exit(1)
 elif options.randomscan:
     logging.debug('making use of random scan')
     logging.debug('parsing range of ports: %s' % options.port)
     portrange = getRange(options.port)
     internetranges = [[16777216, 167772159], [184549376, 234881023],
                       [251658240, 2130706431], [2147549184L, 2851995647L],
                       [2852061184L,
                        2886729727L], [2886795264L, 3221159935L],
                       [3221226240L,
                        3227017983L], [3227018240L, 3232235519L],
                       [3232301056L, 3323068415L],
                       [3323199488L, 3758096127L]]
     scanrandomstore = '.sipviciousrandomtmp'
     resumescan = False
     if options.save is not None:
         scanrandomstore = os.path.join(exportpath, 'random')
         resumescan = True
     scaniter = scanrandom(internetranges,
                           portrange,
Example #4
0
         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)
Example #5
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" )
Example #6
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 anydbm
        import os
        from libs.svhelper import standardoptions, standardscanneroptions, calcloglevel
        from sys import exit
        import logging
        usage = "usage: %prog [options] host1 host2 hostrange\r\n"
        usage += 'Scans for SIP devices on a given network\r\n\r\n'
        usage += "examples:\r\n\r\n"
        usage += "%prog 10.0.0.1-10.0.0.255 "
        usage += "172.16.131.1 sipvicious.org/22 10.0.1.1/24"
        usage += "1.1.1.1-20 1.1.2-20.* 4.1.*.*\r\n\r\n"
        usage += "%prog svmap -s session1 --randomize 10.0.0.1/8\r\n\r\n"
        usage += "%prog svmap --resume session1 -v\r\n\r\n"
        usage += "%prog svmap -p5060-5062 10.0.0.3-20 -m INVITE\r\n\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("--randomscan", dest="randomscan", action="store_true",
                      default=False,
                      help="Scan random IP addresses")
        parser.add_option("-i", "--input", dest="input",
                      help="Scan IPs which were found in a previous scan. Pass the session name as the argument", metavar="scan1")
        parser.add_option("-I", "--inputtext", dest="inputtext",
                      help="Scan IPs from a text file - use the same syntax as command line but with new lines instead of commas. Pass the file name as the argument", metavar="scan1")
        parser.add_option("-m", "--method", dest="method",
                      help="Specify the request method - by default this is OPTIONS.",
                      default='OPTIONS'
                  )
        parser.add_option("-d", "--debug", dest="printdebug",
                      help="Print SIP messages received",
                      default=False, action="store_true"
                  )
        parser.add_option("--first", dest="first",
                      help="Only send the first given number of messages (i.e. usually used to scan only X IPs)",
                      type="long",
                  )
        parser.add_option("-e", "--extension", dest="extension", default='100',
                      help="Specify an extension - by default this is not set")
        parser.add_option("--randomize", dest="randomize", action="store_true",
                      default=False,
                      help="Randomize scanning instead of scanning consecutive ip addresses")
        parser.add_option("--srv", dest="srvscan", action="store_true",
                      default=False,
                      help="Scan the SRV records for SIP on the destination domain name." \
                       "The targets have to be domain names - example.org domain1.com")
        parser.add_option('--fromname',dest="fromname", default="sipvicious",
                      help="specify a name for the from header")
        (options, args) = parser.parse_args()
        from libs.svhelper import getRange, scanfromfile, scanlist, scanrandom, getranges,\
            ip4range, resumeFromIP, scanfromdb, dbexists, getTargetFromSRV
        exportpath = None
        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):
                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)
        # Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and
        # adding it to the root logger.
        logging.basicConfig(level=calcloglevel(options))
        logging.debug('started logging')
        scanrandomstore = None
        if options.input is not None:
            db = os.path.join('.sipvicious',__prog__,options.input,'resultua')
            if dbexists(db):
                scaniter = scanfromdb(db,options.method.split(','))
            else:
                logging.error("the session name does not exist. Please use svreport to list existing scans")
                exit(1)
        # Create random scan
        elif options.randomscan:
            logging.debug('making use of random scan')
            logging.debug('parsing range of ports: %s' % options.port)
            portrange = getRange(options.port)
            internetranges =[[16777216,167772159],
                            [184549376,234881023],
                            [251658240,2130706431],
                            [2147549184L,2851995647L],
                            [2852061184L,2886729727L],
                            [2886795264L,3221159935L],
                            [3221226240L,3227017983L],
                            [3227018240L,3232235519L],
                            [3232301056L,3323068415L],
                            [3323199488L,3758096127L]
                            ]
            scanrandomstore = '.sipviciousrandomtmp'
            resumescan = False
            if options.save is not None:
                scanrandomstore = os.path.join(exportpath,'random')
                resumescan = True
            # Make a scan
            scaniter = scanrandom(
                            internetranges,
                            portrange,
                            options.method.split(','),
                            randomstore=scanrandomstore,
                            resume=resumescan
                            )
        elif options.inputtext:
            logging.debug('Using IP addresses from input text file')
            try:
                # Open for reading. Should contains list of IPs
                f = open(options.inputtext,'r')
                # Read one entire line from the file.
                args = f.readlines()
                # Close file
                f.close()
            except IOError:
                logging.critical('Could not open %s' % options.inputtext)
                exit(1)
            args = map(lambda x: x.strip(), args)
            args = filter(lambda x: len(x) > 0, args)
            logging.debug('ip addresses %s' % args)
            try:
                iprange = ip4range(*args)
            except ValueError,err:
                logging.error(err)
                exit(1)
            # Create range of port
            portrange = getRange(options.port)
            if options.randomize:
                scanrandomstore = '.sipviciousrandomtmp'
                resumescan = False
                if options.save is not None:
                    scanrandomstore = os.path.join(exportpath,'random')
                    resumescan = True
                # Make a scan
                scaniter = scanrandom(map(getranges,args),portrange,options.method.split(','),randomstore=scanrandomstore,resume=resumescan)
            else:
                # Make a scan from a list
                scaniter = scanlist(iprange,portrange,options.method.split(','))
Example #7
0
         if options.save is not None:
             scanrandomstore = os.path.join(exportpath,'random')
             resumescan = True
         # Make a scan
         scaniter = scanrandom(map(getranges,args),portrange,options.method.split(','),randomstore=scanrandomstore,resume=resumescan)
     else:
         # Make a scan from a list
         scaniter = scanlist(iprange,portrange,options.method.split(','))
 else:
     # Check that there is no empty arg.
     if len(args) < 1:
         parser.error('Provide at least one target')
         exit(1)
     logging.debug('parsing range of ports: %s' % options.port)
     # Generate port range
     portrange = getRange(options.port)
     if options.randomize:
         scanrandomstore = '.sipviciousrandomtmp'
         resumescan = False
         if options.save is not None:
             scanrandomstore = os.path.join(exportpath,'random')
             resumescan = True
         # Make a scan
         scaniter = scanrandom(map(getranges,args),portrange,options.method.split(','),randomstore=scanrandomstore,resume=resumescan)
     elif options.srvscan:
         logging.debug("making use of SRV records")
         scaniter = getTargetFromSRV(args,options.method.split(','))
     else:
         if options.resume is not None:
             lastipsrc = os.path.join(exportpath,'lastip.pkl')
             try:
Example #8
0
def main():
    from optparse import OptionParser
    from datetime import datetime
    from libs.svhelper import getRange, resumeFrom, calcloglevel
    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")
    parser.add_option(
        '--requesturi',
        dest="requesturi",
        help=
        "force the first line URI to a specific value; e.g. sip:[email protected]"
    )
    parser.add_option('-6',
                      dest="ipv6",
                      action="store_true",
                      help="scan an IPv6 address")
    parser.add_option('-m', '--method', dest='method', default='REGISTER')
    (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,
        requesturi=options.requesturi,
        ipv6=options.ipv6,
        method=options.method,
    )

    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")
Example #9
0
         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=0o700)
         except OSError: