def __init__(self, args, dbh=None):
        opt = parse(args)
        self.dbh = dbh

        self.adj = opt.adj

        # We don't really need this module here, because we do not operate
        # multithreaded, however it is convenient to use the mkIP2 and isUp
        # functions to preprocess the target ips
        self.ig_targets = cTuples.cInputGenerator(data=opt.targets,
                                                  filename=opt.target_fn,
                                                  circle=False,
                                                  #prepare_cb=cUtil.isUp,
                                                  expand_cb=lambda t: cUtil.mkIP2(t,
                                                                                  ports=[opt.port],
                                                                                  #noResolve=True
                                                                                  ),
                                                  )
        self.ig_targets.start()

        # we don't want to overload the server with too many parallel login
        # attempts as it might influence the delay times
        # so anyway thats why i use one seperate list of user names per server
        # instaed of zipping them to the targets
        if opt.U:
            self.users = it.chain(__builtin__.openany(opt.U, 'r').readlines(), opt.u)
        elif opt.u:
            self.users = opt.u
        else:
            self.users = it.chain(__builtin__.openshared('usernames.log', 'r').readlines())
        prep_targets.bignore = opt.bignore
        test_user.pw = 'a' * opt.l
    def run(self):
        f = __builtin__.openany(self.filename, "w")

        try:

            # run until a stop event is received
            while not self.stop_event.isSet():

                # wait maximal 1 second for an element
                # otherwise raise 'empty' exception
                try:
                    ip = TxtWorker.Results.get(True, 1)
                except (Queue.Empty, EOFError):
                    # If no element is available, continue.
                    # Though, it check whether thread is
                    # needed.
                    continue

                logger.debug("writing %s to file.." % ip)
                ip_clean = ip.replace(" ", "")
                #f.write(ip_clean + "\n")
                print(ip_clean)
                TxtWorker.Results.task_done()

        except EOFError:
            pass

        except Exception as err:
            raise err

        finally:
            f.close()

        logger.debug('txtWorker is finished - so exiting run method')
 def runmultimode(self, localusername):
     f2 = __builtin__.openany(self.userfile2, "r")
     for remoteusername in f2.readlines():
         remoteusername = remoteusername.strip()
         if self.passwordfile:
             self.runrloginpassword(localusername, remoteusername)
         else:
             self.testrlogin(localusername, remoteusername, None)
Exemple #4
0
 def runmultimode(self, localusername):
     f2 = __builtin__.openany(self.userfile2, "r")
     for remoteusername in f2.readlines():
         remoteusername = remoteusername.strip()
         if self.passwordfile:
             self.runrloginpassword(localusername, remoteusername)
         else:
             self.testrlogin(localusername, remoteusername, None)
    def lines(self):

        """ Iterates over non cComment lines of a db file """

        try:
            #db_file = codecs.open(self.filename, 'r', 'utf-8')
            db_file = __builtin__.openany(self.filename, 'r')
        except Exception, e:
            logger.error('Failed to open database. Exception %s' % e)
            raise StopIteration
    def run(self):
        print("Starting rsh brute force...")

        f1 = __builtin__.openany(self.userfile1, "r")
        for username in f1.readlines():
            username = username.strip()
            if self.mode == "singlemode":
                self.runsinglemode(username)
            else:
                self.runmultimode(username)
        f1.close()
    def run(self):
        print("Starting rsh brute force...")

        f1 = __builtin__.openany(self.userfile1, "r")
        for username in f1.readlines():
            username = username.strip()
            if self.mode == "singlemode":
                self.runsinglemode(username)
            else:
                self.runmultimode(username)
        f1.close()
def sshlogin(args, logger):
    """ sshlogin function """

    #is ccd calling us? if so put it to 1
    #callback = 1

    logger.debug("creating sshClass..")
    sshC = sshClass()

    logger.debug("creating socketClass..")
#    socC = socketClass()

    server, port, sshC.user, sshC.password, sshC.method, sshC.keyfile = args
#    socC.tHost = (server,port)

    #test line -- comment out
    #socC.tSocks = tuple(('127.0.0.1',9090))

    if sshC.method=='key':
        sshC.keyfile = __builtin__.openany(sshC.keyfile)

    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        s.connect((server, port))
    except Exception as e:
        print 'Connection to %s:%d failed: %s' % (server, port, str(e))
        sys.exit(1)

    logger.debug("assigning socket to sshC")
    sshC.s = s

    print "Connecting %s@%s:%d " % (sshC.user,server,port)

    logger.debug("creating ssh..")
    sshC.createSSH()

    logger.debug("authenticate ssh..")
    r = sshC.authSSH()
    if not r == sshC.LOGIN_SUCCESSFUL:
        print 'Authentication failed!'
        sys.exit(1)

    sess = sshC.pm.open_channel('session')
    sess.get_pty()
    sess.invoke_shell()
    #after calling everything is f****d up obviously a fd problem
    #please FIXME
    interactive.interactive_shell(sess)

    logging.debug("close")
    sess.close()

    return -1
def read_rpc():
    names = None
    try:
        names = __builtin__.openany(RPC_PATH, 'r')
    except:
            names = open(RPC_PATH, 'r')
    for line in names.read().splitlines():
        if not line or line[0] == '#':
            continue
        data = list(line.split())
        RPC_NAMES[data[0].upper()] = int(data[1])
        RRPC_NAMES[int(data[1])] = data[0].upper()
Exemple #10
0
def sshlogin(args, logger):
    """ sshlogin function """

    #is ccd calling us? if so put it to 1
    #callback = 1

    logger.debug("creating sshClass..")
    sshC = sshClass()

    logger.debug("creating socketClass..")
    #    socC = socketClass()

    server, port, sshC.user, sshC.password, sshC.method, sshC.keyfile = args
    #    socC.tHost = (server,port)

    #test line -- comment out
    #socC.tSocks = tuple(('127.0.0.1',9090))

    if sshC.method == 'key':
        sshC.keyfile = __builtin__.openany(sshC.keyfile)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((server, port))
    except Exception as e:
        print 'Connection to %s:%d failed: %s' % (server, port, str(e))
        sys.exit(1)

    logger.debug("assigning socket to sshC")
    sshC.s = s

    print "Connecting %s@%s:%d " % (sshC.user, server, port)

    logger.debug("creating ssh..")
    sshC.createSSH()

    logger.debug("authenticate ssh..")
    r = sshC.authSSH()
    if not r == sshC.LOGIN_SUCCESSFUL:
        print 'Authentication failed!'
        sys.exit(1)

    sess = sshC.pm.open_channel('session')
    sess.get_pty()
    sess.invoke_shell()
    #after calling everything is f****d up obviously a fd problem
    #please FIXME
    interactive.interactive_shell(sess)

    logging.debug("close")
    sess.close()

    return -1
    def __init__(self, conf_file):
        self.var = {}
        fd = None
        try:
            fd = __builtin__.openany(conf_file, 'r')
        except Exception as e:
            print 'Error opening %s' % conf_file
            sys.exit(1)

        for l in fd.readlines():
            l = l.rstrip('\n')
            idx = l.find('#')
            if idx >= 0:
                l = l[0:idx].rstrip()
            if not l:
                continue
            k, v = l.split('=')
            self.var[k] = v.split(' ')
    def __init__(self,
                 args,
                 dbh=None):

        logger.debug('Init RpcScanner')
        opt = parse(args)
        # file containing RPC program
        if opt.fn_rpc:
            cRpc.RPC_PATH = opt.fn_rpc

        # check if rpc file is readable
        try:
            fd = __builtin__.openany(cRpc.RPC_PATH, "r")
            fd.close()
        except:
            print 'Error: Could not open RPC program number data base %s' % cRpc.RPC_PATH
            sys.exit(1)

        self.port = opt.port
        # database handle
        self.dbh = dbh

        try:
            ig_targets = cTuples.cInputGenerator(filename=opt.target_fn,
                                                 data=opt.targets,
                                                 maxthreads=opt.nthreads,
                                                 circle=False,
                                                 expand_cb=lambda t: cUtil.mkIP2(t,
                                                                                 ports=[opt.port],
                                                                                 noResolve=True
                                                                                 ),
                                                 )
        except cTuples.ENoInput:
            print 'Error: No Targets specified, please use the -t/T parameter to set target(s)'
            sys.exit(1)

        ig_targets.start()
        self.tuples = cTuples.cTuples(inputs=[ig_targets],
                                      prep_callback=rpcinfo,
                                      maxthreads=opt.nthreads,
                                      delay=opt.delay)
        self.tuples.start()
    def __init__(self, args, dbh=None):

        logger.debug('Init %s' % __name__)

        # database handle
        self.dbh = dbh
        opt = self.parse(args)

        if opt.fn_rpc:
            cRpc.RPC_PATH = opt.fn_rpc

        # check if rpc file is readable
        try:
            fd = __builtin__.openany(cRpc.RPC_PATH, "r")
            fd.close()
        except:
            print 'Error: Could not open RPC program number data base %s' % cRpc.RPC_PATH
            sys.exit(1)

        showmount.version = 1

        try:
            ig_targets = cTuples.cInputGenerator(
                filename=opt.target_fn,
                data=opt.targets,
                maxthreads=opt.nthreads,
                circle=False,
                expand_cb=lambda t: cUtil.mkIP2(
                    t, ports=[opt.port], noResolve=True),
            )
        except cTuples.ENoInput:
            print 'Error: No Targets specified, please use the -t/T parameter to set target(s)'
            sys.exit(1)

        ig_targets.start()
        self.tuples = cTuples.cTuples(inputs=[ig_targets],
                                      prep_callback=showmount,
                                      maxthreads=opt.nthreads,
                                      delay=opt.delay)
        self.tuples.start()
    def run(self):
        if self.filename:
            f = __builtin__.openany(self.filename, "w")
        else:
            f = None

        try:

            # run until a stop event is received
            while not self.stop_event.isSet():

                # wait maximal 1 second for an element
                # otherwise raise 'empty' exception
                try:
                    netname = NetnameWorker.Results.get(True, 1)
                except (Queue.Empty, EOFError):
                    # If no element is available, continue.
                    # Though, it check whether thread is
                    # needed.
                    continue

                logger.debug("writing %s to file.." % netname)
                f.write(netname + "\n")

                NetnameWorker.Results.task_done()

        except EOFError:
            pass

        except Exception as err:
            raise err

        finally:
            if f:
                f.close()

        logger.debug('netnameWorker is finished - so exiting run method')
    def __init__(self, args, dbh=None):
        opt = parse(args)
        self.dbh = dbh

        self.adj = opt.adj

        # We don't really need this module here, because we do not operate
        # multithreaded, however it is convenient to use the mkIP2 and isUp
        # functions to preprocess the target ips
        self.ig_targets = cTuples.cInputGenerator(
            data=opt.targets,
            filename=opt.target_fn,
            circle=False,
            #prepare_cb=cUtil.isUp,
            expand_cb=lambda t: cUtil.mkIP2(
                t,
                ports=[opt.port],
                #noResolve=True
            ),
        )
        self.ig_targets.start()

        # we don't want to overload the server with too many parallel login
        # attempts as it might influence the delay times
        # so anyway thats why i use one seperate list of user names per server
        # instaed of zipping them to the targets
        if opt.U:
            self.users = it.chain(
                __builtin__.openany(opt.U, 'r').readlines(), opt.u)
        elif opt.u:
            self.users = opt.u
        else:
            self.users = it.chain(
                __builtin__.openshared('usernames.log', 'r').readlines())
        prep_targets.bignore = opt.bignore
        test_user.pw = 'a' * opt.l
def checkiffileexists(path):
    try:
        __builtin__.openany(path, "r")
    except IOError:
        print("Unable to open " + path)
        exit(1)
 def runmultimode(self, localusername):
     f2 = __builtin__.openany(self.userfile2, "r")
     for remoteusername in f2.readlines():
         remoteusername = remoteusername.strip()
         self.testrsh(localusername, remoteusername)
 def runmultimode(self, localusername):
     f2 = __builtin__.openany(self.userfile2, "r")
     for remoteusername in f2.readlines():
         remoteusername = remoteusername.strip()
         self.testrsh(localusername, remoteusername)
def parse(args):
    parser = argparse.ArgumentParser(
        prog=__plgname__,
        description='dir_bruteforce.py checks HTTP response codes for several path- & file-names one one specified host',
        epilog='Ex: dir_bruteforce.py -nt 1 -t www.curesec.com -i input.txt -r -d 4 -w 2')

    parser.add_argument('-nt',
                        dest='nthreads',
                        type=int,
                        default=1,
                        help='Number of threads ex: -t 20 (default 1)')
    parser.add_argument('-t',
                        dest='base_url',
                        required=True,
                        help='Target host ex: -t www.curesec.com')
    parser.add_argument('-i',
                        dest='pathlist_fn',
                        required=True,
                        help='Path file, containing newline seperated paths ex: -i input.txt')
    parser.add_argument('-r',
                        dest='recurse',
                        action='store_true',
                        help='Recursively add new paths to search (default off)')
    parser.add_argument('-d',
                        dest='depth',
                        type=int,
                        default=0,
                        help='Maximum recursion depth (default 0)')
    parser.add_argument('-w',
                        dest='wait',
                        type=int,
                        default=1,
                        help='Wait x seconds between requests - only enforced per thread (default 2)')

    # print help and exit
    if len(args) == 0:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args(args)

    files = []
    dirs = []

    # read dirs and filenames
    if args.pathlist_fn:
        fd = None
        try:
            fd = __builtin__.openany(args.pathlist_fn, 'r')
        except:
            fd = open(args.pathlist_fn, 'r')

        for line in fd.read().splitlines():
            # if string contains a '.' -> assume its a filename
            # TODO ...
            try:
                line.index('.')
                files.append(line)
            # otherwise it is a directory
            except:
                dirs.append(line)

    return args.base_url, files, dirs, args.nthreads, args.recurse, args.depth, args.wait, None
def sshsnitch(args, logger):
    """ sshsnitchy """

    #is ccd calling us? if so put it to 1
    #callback = 1

    logger.debug("creating sshClass..")
    sshC = sshClass()

    logger.debug("creating socketClass..")

    server, port, sshC.user, sshC.password, sshC.method, sshC.keyfile, verbose = args

    if sshC.method == 'key':
        sshC.keyfile = __builtin__.openany(sshC.keyfile)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((server, port))

    logger.debug("assigning socket to sshC")
    sshC.s = s

    print "Connecting %s@%s:%d " % (sshC.user, server, port)

    logger.debug("creating ssh..")
    sshC.createSSH()

    logger.debug("authenticate ssh..")
    sshC.authSSH()

    fu = __builtin__.openany("unix_snitch.txt", "r")
    usnitch = fu.readlines()

    #add better loop for recv data
    #FIXME
    pwflag = False
    pw = ''
    for cmd in usnitch:
        if not cmd.startswith("#"):

            print "Executing: %s" % (cmd)
            sess = sshC.pm.open_channel('session')
            sess.exec_command(cmd)
            if cmd == "cat /etc/passwd\n":
                print "got passwd"
                pwflag = True
            # added time.sleep here as the remote system sometimes is quite slow in filling the pipe
            # however we dont want to miss anything, there is probably a better solution, but this one works as well ;)
            while 1:
                time.sleep(0.5)
                if sess.recv_ready():
                    data = sess.recv(8096)
                    print data
                    if pwflag:
                        pw = pw.join(data)
                else:
                    break

            pwflag = False
            #lets get errors as well
            if verbose:
                data = sess.recv_stderr(8096)
                print data
            print "-" * 80
        else:
            print "Section or Comment: %s" % cmd

    print "Unix Snitch got returned."
    print "And found passwd, lets analyse it"
    print pw
    pw = pw.split("\n")
    pw.remove('')

    fu.close()

    fu = __builtin__.openany("unix_snitch_home.txt", "r")
    homesearch = []
    homesearch = fu.readlines()

    for line in pw:
        pwsp = line.split(":")
        user = pwsp[0]
        shell = pwsp[6]
        uhome = pwsp[5]
        print "Checking user [%s] with shell [%s]" % (user, shell)

        for hs in homesearch:
            cmd = "cat %s/%s" % (uhome, hs)
            if not hs.startswith("#"):

                print "Executing: %s" % (cmd)
                sess = sshC.pm.open_channel('session')
                sess.exec_command(cmd)
                while 1:
                    time.sleep(0.5)
                    if sess.recv_ready():
                        data = sess.recv(8096)
                        print data
                    else:
                        break
                #lets get errors as well
                if verbose:
                    data = sess.recv_stderr(8096)
                    print data
                print "-" * 80
            else:
                print "Section or Comment: %s" % cmd

    logging.debug("close")
    sess.close()

    return -1
    def extract(self):
        """
        extract the inetnums, matching the searchterms, from the ripe database
        """

        fout = None
        if self.extractfile:
            fout = __builtin__.openany(self.extractfile, "w")
            fout = codecs.getwriter('ISO-8859-1')(fout)
            #fout = codecs.open(self.extractfile, "w", 'utf-8')

        f = __builtin__.openshared(self.dbfile, "r")

        # handle possible gzip compression:
        #   read magic byte
        #   first lines are just comments anyway so no one cares about 2 missing bytes
        mb = f.read(2)
        if mb == '\x1f\x8b':
            # probably a gzipped file
            # good enough check for our restricted case
            #f.close()
            #f = gzip.open(self.dbfile, 'r')
            f.seek(0)
            f = gzip.GzipFile(fileobj=f)
        else:
            #f.close()
            f.seek(0)
            f = codecs.getreader('ISO-8859-1')(f)
            #f = __builtin__.openany(self.dbfile, "r")
            #f = codecs.open(self.dbfile, "r", 'ISO-8859-1')

        # match any of the searchstrings
        pat = re.compile('|'.join(map(re.escape, self.searchstrings)),
                         re.IGNORECASE)

        pos = 0
        # process ripe file in batches
        out_q = multiprocessing.Queue()
        data_buf = ''
        chunk = self.batchsize / self.nthreads
        done = False
        out_lock = None
        if self.extractfile:
            out_lock = threading.Lock()
        while not done:
            procs = []
            # read data to feed n threads
            for i in range(self.nthreads):
                # we may have some data buffered from the previous round
                data = data_buf
                l_buf = len(data_buf)
                data_buf = ''
                try:
                    data += f.read(chunk - l_buf)
                except:
                    done = True
                if not data:
                    done = True
                    break
                l_buf = 0
                # don't forget to clear the buffer
                # read until entry is complete, so we don't have
                # to deal with searching inet nums across
                # multiple data chunks
                while not done and data[-2:] != '\n\n':
                    try:
                        data_buf += f.read(1024)
                    except:
                        done = True
                        break
                    if not data_buf:
                        done = True
                        break
                    idx = data_buf.find('\n\n')
                    # we have found the end of our entry
                    if idx >= 0:
                        data += data_buf[:idx + 2]
                        data_buf = data_buf[idx + 2:]
                        break
                pos += len(data)
                if data:
                    sys.stdout.write(
                        row_fmt.format('', '', 'processed: %d byte' % pos) +
                        "\r")
                    sys.stdout.flush()
                    p = multiprocessing.Process(
                        target=MatchWorker,
                        args=[data, pat, out_q, fout, out_lock])
                    procs.append(p)
                    p.start()
                if done:
                    break
            # join threads so that we dont flood the ram
            for p in procs:
                p.join()
            # get results:
        while True:
            try:
                m, mstr, line = out_q.get(False)
                #self.inetnums[m.upper()].append(line)
                self.inetnums[mstr] = line
            except Queue.Empty:
                break
        if self.extractfile:
            fout.close()
Exemple #22
0
def sshsnitch(args, logger):
    """ sshsnitchy """

    #is ccd calling us? if so put it to 1
    #callback = 1

    logger.debug("creating sshClass..")
    sshC = sshClass()

    logger.debug("creating socketClass..")

    server, port, sshC.user, sshC.password, sshC.method, sshC.keyfile, verbose = args

    if sshC.method == 'key':
        sshC.keyfile = __builtin__.openany(sshC.keyfile)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((server, port))

    logger.debug("assigning socket to sshC")
    sshC.s = s

    print "Connecting %s@%s:%d " % (sshC.user, server, port)

    logger.debug("creating ssh..")
    sshC.createSSH()

    logger.debug("authenticate ssh..")
    sshC.authSSH()

    fu = __builtin__.openany("unix_snitch.txt", "r")
    usnitch = fu.readlines()

    #add better loop for recv data
    #FIXME
    pwflag = False
    pw = ''
    for cmd in usnitch:
        if not cmd.startswith("#"):

            print "Executing: %s" % (cmd)
            sess = sshC.pm.open_channel('session')
            sess.exec_command(cmd)
            if cmd == "cat /etc/passwd\n":
                print "got passwd"
                pwflag = True
            # added time.sleep here as the remote system sometimes is quite slow in filling the pipe
            # however we dont want to miss anything, there is probably a better solution, but this one works as well ;)
            while 1:
                time.sleep(0.5)
                if sess.recv_ready():
                    data = sess.recv(8096)
                    print data
                    if pwflag:
                        pw = pw.join(data)
                else:
                    break

            pwflag = False
            #lets get errors as well
            if verbose:
                data = sess.recv_stderr(8096)
                print data
            print "-" * 80
        else:
            print "Section or Comment: %s" % cmd

    print "Unix Snitch got returned."
    print "And found passwd, lets analyse it"
    print pw
    pw = pw.split("\n")
    pw.remove('')

    fu.close()

    fu = __builtin__.openany("unix_snitch_home.txt", "r")
    homesearch = []
    homesearch = fu.readlines()

    for line in pw:
        pwsp = line.split(":")
        user = pwsp[0]
        shell = pwsp[6]
        uhome = pwsp[5]
        print "Checking user [%s] with shell [%s]" % (user, shell)

        for hs in homesearch:
            cmd = "cat %s/%s" % (uhome, hs)
            if not hs.startswith("#"):

                print "Executing: %s" % (cmd)
                sess = sshC.pm.open_channel('session')
                sess.exec_command(cmd)
                while 1:
                    time.sleep(0.5)
                    if sess.recv_ready():
                        data = sess.recv(8096)
                        print data
                    else:
                        break
                #lets get errors as well
                if verbose:
                    data = sess.recv_stderr(8096)
                    print data
                print "-" * 80
            else:
                print "Section or Comment: %s" % cmd

    logging.debug("close")
    sess.close()

    return -1
 def runrloginpassword(self, localusername, remoteusername):
     f3 = __builtin__.openany(self.passwordfile, "r")
     for password in f3.readlines():
         password = password.strip()
         self.testrlogin(localusername, remoteusername, password)
def parse(args):
    # parse cmd line options
    parser = argparse.ArgumentParser(
        prog=__plgname__,
        description="""Bruteforce ssh logins""",
        epilog="""Examples:
        ssh_bruteforce.plg -v vstrings.txt host -t 192.168.1.136 -U users.txt -P pass.txt
        ssh_bruteforce.plg -v vstrings.txt -nt 100 uph -B uph_file.txt""",
        formatter_class=argparse.RawTextHelpFormatter
    )  # TODO

    parser.add_argument('-nt',
                        dest='nthreads',
                        type=int,
                        default=2,
                        help='threads ex: -nt 20')
    parser.add_argument('-v',
                        dest='ssh_versions',
                        help='SSH version file ex: -v versions.txt')
    parser.add_argument('-delay',
                        help='delay in between requests',
                        dest='delay',
                        default=0.0,
                        type=float
                        )

    subparsers = parser.add_subparsers()

    # host sub program, for single host bruteforcing
    parser_host = subparsers.add_parser('host', help='single host')
    parser_host.add_argument('-T',
                             help='files containing host:port entries',
                             default='',
                             dest='target_fn'
                             )
    parser_host.add_argument('-t',
                             help='target hosts',
                             default=[],
                             nargs='+',
                             dest='targets',
                             )
    parser_host.add_argument('-port',
                             help='target port (default 22)',
                             dest='port',
                             default=22,
                             type=int
                             )
    parser_host.add_argument('-u',
                             help='usernames',
                             default=[],
                             nargs='+',
                             dest='users',
                             )
    parser_host.add_argument('-p',
                             help='passwords',
                             default=[],
                             nargs='+',
                             dest='passw',
                             )
    parser_host.add_argument('-U',
                             help='file containing one username per line',
                             default='',
                             dest='user_fn',
                             )
    parser_host.add_argument('-P',
                             help='file containing one password per line',
                             default='',
                             dest='passw_fn',
                             )
    parser_host.set_defaults(which='host')

    # uph sub program, for bruteforcing multiple hosts
    parser_uph = subparsers.add_parser('uph', help='multiple hosts')
    parser_uph.add_argument('-B',
                            dest='uph_lists',
                            required=True,
                            help='bf against multiple hosts specified in a uph file of the format ' +
                            'user:password:host[:port] ex: -B uph_file.txt')
    parser_uph.set_defaults(which='uph')

    if not args:
        parser.print_help()
        print '\nSingle host mode'
        print '----------------'
        parser_host.print_help()
        print '\nMulti host mode'
        print '----------------'
        parser_uph.print_help()
        sys.exit(1)

    try:
        opt = parser.parse_args(args)
    except:
        parser.print_help()
        sys.exit(1)

    if opt.ssh_versions:
        brute.ssh_versions = it.cycle(__builtin__.openany(opt.ssh_versions).readlines())
    else:
        brute.ssh_versions = None
    return opt
    def __init__(self, args, dbh=None):
        """
        Search the RIPE database or save it to disk

        input:
            args:       cmd line arguments sys.argv[1:]
            dbh:        handler for result database
        """

        logger.info('starting plugin %s', __name__)
        start_time = datetime.now()

        # parse arguments
        opts = parse(args)

        self.extractfile = opts.extractfile
        self.dbfile = opts.dbfile
        self.timeout = opts.timeout
        self.nthreads = opts.nthreads
        self.batchsize = opts.batchsize

        # only update the database file, then quit, nothing else
        if opts.update:
            if not self.dbfile:
                print 'Please give me a location to save the data to (-dbfile)'
                sys.exit(1)

            # read config
            config = ConfigParser.ConfigParser()
            with __builtin__.openany(opts.config, 'r') as config_fd:
                config.readfp(config_fd)

            self.ripedb_mirror = config.get('mirror',
                                            'ripedb_mirror').split(':')
            retry_interval = config.getfloat('mirror', 'retry_interval')
            max_retries = config.get('mirror', 'max_retries')

            retries = 0
            print 'Updating %s' % self.dbfile
            r = None
            while retries < max_retries:
                try:
                    r = self.update_db()
                except Exception as e:
                    logger.warning('Error updating ripe database: %s', e)
                if r:
                    print 'Update successful'
                    break
                else:
                    print 'Update failed'
                    print 'Automatic Retry in %fs ...' % retry_interval
                    retries += 1
                    time.sleep(retry_interval)
            if r is None:
                print 'Update failed, terminating %s' % __name__
                sys.exit(1)
        else:
            # do the search
            self.searchstrings = []
            if opts.searchstring:
                self.searchstrings = map(unicode.upper,
                                         map(unicode, opts.searchstring))
            if opts.searchfile:
                # lets just assume that there wont be huuuge amounts of search
                # strings, so we can load all of them without clogging up the ram
                with codecs.getreader('ISO-8859-1' (__builtin__.openany(
                        opts.searchfile, 'r'))) as f:
                    self.searchstrings.extend(
                        map(unicode.upper,
                            f.read().splitlines()))

            # create dictionary searchstring -> results
            self.inetnums = {}

            self.dbh = dbh
            self.extract()
            self.processinetnums()
            self.output()

        print("\nfinished in %fs" % secs(start_time))
Exemple #26
0
 def runrloginpassword(self, localusername, remoteusername):
     f3 = __builtin__.openany(self.passwordfile, "r")
     for password in f3.readlines():
         password = password.strip()
         self.testrlogin(localusername, remoteusername, password)
def checkiffileexists(path):
    try:
        __builtin__.openany(path, "r")
    except IOError:
        print("Unable to open " + path)
        exit(1)
Exemple #28
0
def parse(args):
    parser = argparse.ArgumentParser(
        prog=__plgname__,
        description=
        'dir_bruteforce.py checks HTTP response codes for several path- & file-names one one specified host',
        epilog=
        'Ex: dir_bruteforce.py -nt 1 -t www.curesec.com -i input.txt -r -d 4 -w 2'
    )

    parser.add_argument('-nt',
                        dest='nthreads',
                        type=int,
                        default=1,
                        help='Number of threads ex: -t 20 (default 1)')
    parser.add_argument('-t',
                        dest='base_url',
                        required=True,
                        help='Target host ex: -t www.curesec.com')
    parser.add_argument(
        '-i',
        dest='pathlist_fn',
        required=True,
        help='Path file, containing newline seperated paths ex: -i input.txt')
    parser.add_argument(
        '-r',
        dest='recurse',
        action='store_true',
        help='Recursively add new paths to search (default off)')
    parser.add_argument('-d',
                        dest='depth',
                        type=int,
                        default=0,
                        help='Maximum recursion depth (default 0)')
    parser.add_argument(
        '-w',
        dest='wait',
        type=int,
        default=1,
        help=
        'Wait x seconds between requests - only enforced per thread (default 2)'
    )

    # print help and exit
    if len(args) == 0:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args(args)

    files = []
    dirs = []

    # read dirs and filenames
    if args.pathlist_fn:
        fd = None
        try:
            fd = __builtin__.openany(args.pathlist_fn, 'r')
        except:
            fd = open(args.pathlist_fn, 'r')

        for line in fd.read().splitlines():
            # if string contains a '.' -> assume its a filename
            # TODO ...
            try:
                line.index('.')
                files.append(line)
            # otherwise it is a directory
            except:
                dirs.append(line)

    return args.base_url, files, dirs, args.nthreads, args.recurse, args.depth, args.wait, None
Exemple #29
0
    def __init__(self,
                 filename='',
                 filenames=[],
                 data=[],
                 ie_size=42,
                 circle=False,
                 expand_cb=None,
                 prepare_cb=None,
                 maxthreads=MAXTHREADS,
                 sentinel=SENTINEL):

        """
        A class to abstract input generation and caching.

        Input:
            filename        Input file
            data            Input array
            ie_size         Estimated size of one element
            circle          I the buffer read more than once? Controls caching.
            expand_cb       Input expansion callback function, e.g. mkIP.
                            This callback should be an iterator and yield 0 or more tupes.
                            It gets input directly from the data array and the file content.
            prepare_cb      Input preparation callback.
                            It should modify the input in a way that the actual bruteforce function can work with it.
                            If one item is to be discarded from further processing, it should return None.
                            The prep. callback gets the return values from the expand callback as input.
            maxthreads      Maximum number of threads per pool, there are max. 2 pools active at the same time.
            sentinel        Marks the end of the queue/buffer
        """

        super(cInputGenerator, self).__init__()

        logger.debug('Init cInputGenerator %s + %s' % (filename, repr(data)))
        self.filename = filename
        self.filenames = filenames
        self.data = data
        self.ie_size = ie_size
        self.maxthreads = maxthreads

        try:
            self.datasize = len(data)
        except:
            self.datasize = 0

        if filename:
            self.filenames.append(filename)

        for filename in self.filenames:
            #print filename
            try:
                fd = __builtin__.openany(filename, 'r')
            except Exception as e:
                print '[!] WARNING: Can not open file \'%s\': %s' % (filename, e)
                self.items = data
            else:
                logger.debug('opened %s', fd.name)
                self.items = it.chain(fd.readlines(), data)
                #print repr(self.items)
                self.datasize += os.stat(fd.name).st_size
                logger.debug('size %d' % self.datasize)

        if not filenames:
            self.items = data

        #print repr(self.items)
        if not self.items:
            print 'No input specified'
            raise ENoInput('No input specified')

        if expand_cb:
            self.expand_cb = lambda i: map(i[0].put, expand_cb(i[1]))
        else:
            self.expand_cb = None

        if prepare_cb:
            prepare_cb = prepare_cb
            self.prepare_cb = prepare_cb
        else:
            self.prepare_cb = None

        qsize = cMon.ask_for_rampercent(
            perc=0.25,
            max_ram=cInputGenerator.MAXITEMS * self.ie_size
        )
        qsize = qsize / self.ie_size
        if circle:
            self.out = cCircCash._circ_cash(
                threshold=cInputGenerator.ITEMTHRESH,
                maxsize=cInputGenerator.MAXITEMS,
                circle=True)
        else:
            self.out = cTHQueue(
                threshold=cInputGenerator.ITEMTHRESH,
                maxsize=cInputGenerator.MAXITEMS)
        self.sentinel = sentinel
Exemple #30
0
def parse(args):
    # parse cmd line options
    parser = argparse.ArgumentParser(
        prog=__plgname__,
        description="""Bruteforce ssh logins""",
        epilog="""Examples:
        ssh_bruteforce.plg -v vstrings.txt host -t 192.168.1.136 -U users.txt -P pass.txt
        ssh_bruteforce.plg -v vstrings.txt -nt 100 uph -B uph_file.txt""",
        formatter_class=argparse.RawTextHelpFormatter)  # TODO

    parser.add_argument('-nt',
                        dest='nthreads',
                        type=int,
                        default=2,
                        help='threads ex: -nt 20')
    parser.add_argument('-v',
                        dest='ssh_versions',
                        help='SSH version file ex: -v versions.txt')
    parser.add_argument('-delay',
                        help='delay in between requests',
                        dest='delay',
                        default=0.0,
                        type=float)

    subparsers = parser.add_subparsers()

    # host sub program, for single host bruteforcing
    parser_host = subparsers.add_parser('host', help='single host')
    parser_host.add_argument('-T',
                             help='files containing host:port entries',
                             default='',
                             dest='target_fn')
    parser_host.add_argument(
        '-t',
        help='target hosts',
        default=[],
        nargs='+',
        dest='targets',
    )
    parser_host.add_argument('-port',
                             help='target port (default 22)',
                             dest='port',
                             default=22,
                             type=int)
    parser_host.add_argument(
        '-u',
        help='usernames',
        default=[],
        nargs='+',
        dest='users',
    )
    parser_host.add_argument(
        '-p',
        help='passwords',
        default=[],
        nargs='+',
        dest='passw',
    )
    parser_host.add_argument(
        '-U',
        help='file containing one username per line',
        default='',
        dest='user_fn',
    )
    parser_host.add_argument(
        '-P',
        help='file containing one password per line',
        default='',
        dest='passw_fn',
    )
    parser_host.set_defaults(which='host')

    # uph sub program, for bruteforcing multiple hosts
    parser_uph = subparsers.add_parser('uph', help='multiple hosts')
    parser_uph.add_argument(
        '-B',
        dest='uph_lists',
        required=True,
        help='bf against multiple hosts specified in a uph file of the format '
        + 'user:password:host[:port] ex: -B uph_file.txt')
    parser_uph.set_defaults(which='uph')

    if not args:
        parser.print_help()
        print '\nSingle host mode'
        print '----------------'
        parser_host.print_help()
        print '\nMulti host mode'
        print '----------------'
        parser_uph.print_help()
        sys.exit(1)

    try:
        opt = parser.parse_args(args)
    except:
        parser.print_help()
        sys.exit(1)

    if opt.ssh_versions:
        brute.ssh_versions = it.cycle(
            __builtin__.openany(opt.ssh_versions).readlines())
    else:
        brute.ssh_versions = None
    return opt