Welcome to mirror list, hosted at ThFree Co, Russian Federation.

bruter_lib.py - github.com/Tim55667757/pwd_brut.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1acb67441922c8d6e2a61650329f8c3794f3d5ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Gilmullin T.M.

# This file describes support utils for Bruter.


# Importing config file
import config

# Importing Selenium WebDriver classes
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

# Other imports
import traceback
import os
import sys
from datetime import datetime
import time
import threading
import random
import argparse
import re
import functools


# Working Directory.
workDir = os.path.abspath(os.curdir)

# List of threads.
threads = []

# List of browsers - one browser in every thread.
browsers = []


def ParseArgs():
    """
    Function get and parse command line keys.
    """
    args = []
    try:
        parser = argparse.ArgumentParser()
        parser.add_argument("-t", "--target", type=str,
                            help="Target URL for Bruter. For example: '--target=http://mysite.com/admin/'")
        parser.add_argument("-b", "--browser", type=str,
                            help="Browser for Bruter (*firefox, *ie, *chrome). *firefox by default.")
        parser.add_argument("-r", "--random", type=str,
                            help="If this key is True then Bruter uses random user and password in every iteration.")
        parser.add_argument("-T", "--threads", type=int, help="Thread's number.")
        parser.add_argument("-w", "--wait", type=int, help="Waiting for operation's finish (sec.).")
        parser.add_argument("-p", "--period", type=int,
                            help="Rump up period shows time (sec.) in which all test suite threads will start.")
        parser.add_argument("-L", "--logins", type=str, help="Path to user's list. Default: dict/users.txt")
        parser.add_argument("-P", "--passwords", type=str, help="Path to password's list. Default: dict/pwd.txt")
        parser.add_argument("-R", "--results", type=str, help="Path to result file. Default: result.txt")
        parser.add_argument("-g", "--generator", type=str,
                            help="Generate a lot of random strings for Bruter. Example: '-g [100,8,1,1,1,0,0,0]'.\n" +
                                 "This means:\n" +
                                 "1 number - number of strings, 2 - string's length, 3 - use or not Numbers," +
                                 "4 - use or not Latin Upper Case Chars, 5 - use or not Latin Lower Case Chars" +
                                 "6 - use or not Russian Upper case chars, 7 - use or not Russian Lower Case Chars,"
                                 "8 - use or not Special Simbols. Output file: dict/rnd_<date_time>.txt")
        args = parser.parse_args()
        if args.target != None:
            config.target = args.target
        if (args.browser == '*chrome') or (args.browser == '*ie'):
            config.selBrowserString = args.browser
        else:
            config.selBrowserString = '*firefox'
        if args.random != None:
            if args.random == 'True':
                config.randomCredentials = True
            else:
                config.randomCredentials = False
        if args.threads != None:
            config.brutThreads = args.threads
        if args.wait != None:
            config.timeout = args.wait
        if args.period != None:
            config.rumpUpPeriod = args.period
        if args.logins != None:
            if os.path.exists(args.logins):
                config.usersFile = args.logins
            else:
                config.usersFile = 'dict/users.txt'
        if args.passwords != None:
            if os.path.exists(args.passwords):
                config.passwordsFile = args.passwords
            else:
                config.passwordsFile = 'dict/pwd.txt'
        if args.results != None:
            if os.path.exists(args.results):
                config.resultFile = args.results
            else:
                config.resultFile = 'result.txt'
        if args.generator != None:
            params = []
            try:
                params = StringOfNumToNumsList(args.generator)
            except:
                pass
            finally:
                if len(params) >= 8:
                    config.randomGeneratorParameter = params
                else:
                    print('%s - Generator using default parameters from config file: %s' %
                          (datetime.now().strftime('%H:%M:%S %d.%m.%Y'), config.randomGeneratorParameter))
        print('%s - Parsing command line arguments, status: oK' % datetime.now().strftime('%H:%M:%S %d.%m.%Y'))
    except BaseException:
        print('%s - Parsing command line arguments, status: error' % datetime.now().strftime('%H:%M:%S %d.%m.%Y'))
        traceback.print_exc()
    finally:
        return args


def EstimateTime(numLogins=0, numPasswords=0, waitInSec=1, timeForStartingTreads=0):
    """
    Function returns info about estimate time.
    """
    try:
        es = numLogins * numPasswords * waitInSec + timeForStartingTreads
        eh = round(es / 3600)
        info = 'Users: %d, Passwords: %d, Full Estimated Time: %d sec. (~%d hours).' %\
               (numLogins, numPasswords, es, eh)
    except BaseException:
        traceback.print_exc()
        return 'Can\'t compute estimate time!'
    return info


def DurationOperation(func):
    """
    This is decorator for compute duration operation of functions. It works only with functions returning number >= 0.
    """

    def wrapper(*args, **kwargs):
        startTime = datetime.now()
        print('%s - Thread #%d, %s, starting ...' % (startTime.strftime('%H:%M:%S %d.%m.%Y'), args[0], str(func)))
        status = func(*args, **kwargs)
        stopTime = datetime.now()
        if status == 0:
            print('%s - Thread #%d, %s, status: oK' % (stopTime.strftime('%H:%M:%S %d.%m.%Y'), args[0], str(func)))
        else:
            print('%s - Thread #%d, %s, status: error' % (stopTime.strftime('%H:%M:%S %d.%m.%Y'), args[0], str(func)))
        duration = stopTime - startTime
        print('%s - Thread #%d, %s, duration operation: %s' %
              (stopTime.strftime('%H:%M:%S %d.%m.%Y'), args[0], str(func), str(duration)))
        return status

    return wrapper


def StringOfNumToNumsList(string):
    """
    Get some string with numbers and other simbols, for example:'[572,573,604,650]' or similar
    and convert it to list of numbers as [572, 573, 604, 650].
    """
    numList = []
    try:
        while len(string) != 0:
            s = ''
            i = 0
            flag = True
            while flag and i < len(string):
                if string[i] in '0123456789':
                    s = s + string[i]
                    i += 1
                else:
                    flag = False
            if s != '':
                numList.append(int(s))
            string = string[i + 1:]
    except:
        print('%s - Can\'t parse your string of numbers to list of numbers!' %
              datetime.now().strftime('%H:%M:%S %d.%m.%Y'))
        traceback.print_exc()
        return []
    return numList


def GetListFromFile(file):
    """
    This function get strings from file and put into list. Text-file must have #13#10
    """
    listFromFile = []
    if os.path.exists(file):
        try:
            with open(file) as fh:
                allStrings = fh.read()
                listFromFile = allStrings.split('\n')
        except BaseException:
            print('%s - Can\'t get list from file: %s' % (datetime.now().strftime('%H:%M:%S %d.%m.%Y'), file))
            traceback.print_exc()
            return []
    return listFromFile


def SeparateListByPieces(fullList, piecesNum):
    """
    Function get full list of objects and then divided into a number of parts. Last part may be bigger, than other.
    Function return a list of part of full list.
    """
    separate = []
    listLen = len(fullList)
    if (listLen > 0) and (piecesNum > 1):
        try:
            objectsInPieces = listLen // piecesNum
            for i in range(piecesNum):
                piece = [fullList[i * objectsInPieces + k] for k in range(objectsInPieces)]
                separate.append(piece)
            separate[piecesNum - 1] += fullList[piecesNum * objectsInPieces:]
        except BaseException:
            print('%s - Can\'t separate list of objects!' % datetime.now().strftime('%H:%M:%S %d.%m.%Y'))
            traceback.print_exc()
            return [fullList]
    else:
        separate = [fullList]
    return separate


@DurationOperation
def Reporting(instance=0, file='result.txt', creds=None, users=None, passwords=None, actualTime=0):
    """
    This function print results to file.
    """
    try:
        if os.path.exists(file):
            fileTo = open(file, 'a')
        else:
            fileTo = open(file, 'w')
        fileTo.write('\n%s - Thread #%d, Bruter finished check for\n' %
                     (datetime.now().strftime('%H:%M:%S %d.%m.%Y'), instance) +
                     'users = [\'%s\', ..., \'%s\'], %d items,\n' % (users[0], users[-1], len(users)) +
                     'passwords = [\'%s\', ..., \'%s\'], %d items.\n' % (passwords[0], passwords[-1], len(passwords)) +
                     'Actual time worked: %s\n' % str(actualTime))
        if (creds != None) and (creds != {}):
            fileTo.write('Suitable credentials: %s\n' % str(creds))
        else:
            fileTo.write('Bruter can\'t find suitable credentials.\n')
        print('%s - Thread #%d, Updating report file: \'%s\'' %
              (datetime.now().strftime('%H:%M:%S %d.%m.%Y'), instance, file))
        fileTo.close()
    except BaseException:
        traceback.print_exc()
        return 1
    return 0


@DurationOperation
def OpenBrowser(instance=0, opTimeout=10, browserString='*firefox', ffProfile=None):
    """
    Commands for opening new instance of WebDriver browser.
    """
    try:
        # Get new browser instance and put it into browser array. One browser for one thread.
        if browserString == '*chrome':
            chromeOptions = webdriver.ChromeOptions()
            chromeOptions.add_argument('--start-maximized')
            chromeOptions.add_argument('--log-path=' + workDir + '/browser_drivers/chromedriver.log')
            os.chdir(workDir + '/browser_drivers')
            browsers.append(webdriver.Chrome(executable_path=workDir + '/browser_drivers/chromedriver.exe',
                                             chrome_options=chromeOptions))
            os.chdir(workDir)
        elif browserString == '*ie':
            browsers.append(webdriver.Ie(executable_path=workDir + '/browser_drivers/IEDriverServer.exe',
                                         log_file=workDir + '/browser_drivers/iedriver.log'))
            browsers[len(browsers) - 1].maximize_window()
        else:
            ffp = webdriver.FirefoxProfile(ffProfile)
            browsers.append(webdriver.Firefox(firefox_profile=ffp, timeout=opTimeout))
            browsers[len(browsers) - 1].maximize_window()
    except BaseException:
        traceback.print_exc()
        return 1
    return 0


@DurationOperation
def GoingToTarget(instance=0, opTimeout=10, targetURL='', loginField="//input[@name='login']",
                  passwordField="//input[@name='password']", acceptButton="//input[@type='submit']"):
    """
    This funcion going to target's URL with form-based auth.
    """
    try:
        page = browsers[instance]
        page.get(targetURL)
        WebDriverWait(page, opTimeout).until(
            lambda el: el.find_element_by_xpath(loginField).is_displayed() and
                       el.find_element_by_xpath(passwordField).is_displayed() and
                       el.find_element_by_xpath(acceptButton).is_displayed(), 'Timeout while opening auth page.')
    except BaseException:
        traceback.print_exc()
        return 1
    return 0


@DurationOperation
def CloseBrowser(instance=0):
    """
    Try to close WebDriver browser.
    """
    if len(browsers) > 0:
        if browsers[instance] != None:
            try:
                browsers[instance].close()
                browsers[instance] = None
            except BaseException:
                traceback.print_exc()
                return 1
    return 0


def Cleaner():
    """
    Finalization step for Bruter.
    """
    status = 0
    try:
        # Stopping compute threads and closing browsers.
        for t in threads:
            if t != None:
                t._stop()
                t = None
        for b in range(len(browsers)):
            status += CloseBrowser(b)
        if status == 0:
            print('%s - Bruter finalize, status: oK' % datetime.now().strftime('%H:%M:%S %d.%m.%Y'))
    except BaseException:
        print('%s - Bruter finalize, status: error' % datetime.now().strftime('%H:%M:%S %d.%m.%Y'))
        traceback.print_exc()
        return 1
    return status


def GenerateRandomString(length=8, useNum=True, useEngUp=True, useEngLo=True, useRuUp=False, useRuLo=False,
                         useSpecial=False):
    """
    Function return random text-string definite length, that will be use as login or password.
    1 number - number of strings, 2 - string's length, 3 - use or not Numbers,
    4 - use or not English Upper Case Chars, 5 - use or not English Lower Case Chars,
    6 - use or not Russian Upper case chars, 7 - use or not Russian Lower Case Chars, 8 - use or not Special Simbols.
    """
    # There are possible simbols in alphabet.
    alphabet = {
        'dicNum': '1234567890',
        'dicEngCharUpperCase': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'dicEngCharLowerCase': 'abcdefghijklmnopqrstuvwxyz',
        'dicRuCharUpperCase': 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЫЪЭЮЯ',
        'dicRuCharLowerCase': 'абвгдеёжзийклмнопрстуфхцчшщьыъэюя',
        'dicSpecial': '!@#$%^&*()-_+=.,<>[]{}\|/`~"\':;'}

    # Preparing user's alphabet.
    usersAlphabet = ''
    if useNum:
        usersAlphabet += alphabet['dicNum']
    if useEngUp:
        usersAlphabet += alphabet['dicEngCharUpperCase']
    if useEngLo:
        usersAlphabet += alphabet['dicEngCharLowerCase']
    if useRuUp:
        usersAlphabet += alphabet['dicRuCharUpperCase']
    if useRuLo:
        usersAlphabet += alphabet['dicRuCharLowerCase']
    if useSpecial:
        usersAlphabet += alphabet['dicSpecial']
    usersAlpLen = len(usersAlphabet)

    # Generating random string with user prefers.
    textString = ''
    try:
        if (length > 0) and (usersAlphabet != ''):
            for i in range(length):
                textString += usersAlphabet[random.randint(0, usersAlpLen - 1)]
    except BaseException:
        textString = ''
        print('%s - Can\'t generate random string!' % datetime.now().strftime('%H:%M:%S %d.%m.%Y'))
        traceback.print_exc()
    finally:
        return textString


def GenerateListOfRandomStrings(numbers=10, length=8, useNum=True, useEngUp=True, useEngLo=True,
                                useRuUp=False, useRuLo=False, useSpecial=False):
    """
    Function return list of random text-string definite length, that will be use as login or password.
    1 number - number of strings, 2 - string's length, 3 - use or not Numbers,
    4 - use or not English Upper Case Chars, 5 - use or not English Lower Case Chars,
    6 - use or not Russian Upper case chars, 7 - use or not Russian Lower Case Chars, 8 - use or not Special Simbols.
    """
    rndList = []
    try:
        if numbers > 0:
            for i in range(numbers):
                rndList.append(GenerateRandomString(length, useNum, useEngUp, useEngLo, useRuUp, useRuLo, useSpecial))
    except BaseException:
        rndList = []
        print('%s - Can\'t generate list of random string!' % datetime.now().strftime('%H:%M:%S %d.%m.%Y'))
        traceback.print_exc()
    finally:
        return rndList


def GenerateFileWithRandomStrings(par=None):
    """
    Function create file with random text-string, that will be use as login or password.
    Example: Par = [100, 5, 1, 1, 1, 0, 0, 0]
    1 number - number of strings, 2 - string's length, 3 - use or not Numbers,
    4 - use or not English Upper Case Chars, 5 - use or not English Lower Case Chars,
    6 - use or not Russian Upper case chars, 7 - use or not Russian Lower Case Chars, 8 - use or not Special Simbols.
    """
    file = 'dict/rnd_' + datetime.now().strftime('%d_%m_%Y_%H_%M_%S') + '.txt'
    try:
        if not (os.path.exists('dict')):
            os.mkdir('dict')
        fileTo = open(file, 'a')
        if len(par) >= 8:
            for i in range(2, 8):
                if par[i] == 1:
                    par[i] = True
                else:
                    par[i] = False
            rndList = GenerateListOfRandomStrings(par[0], par[1], par[2], par[3], par[4], par[5], par[6], par[7])
        else:
            rndList = GenerateListOfRandomStrings(numbers=10, length=8, useNum=True, useEngUp=True, useEngLo=True,
                                                  useRuUp=False, useRuLo=False, useSpecial=False)
        if len(rndList) > 0:
            for string in rndList:
                fileTo.write(string + '\n')
        print('%s - Generate file with random strings: %s' % (datetime.now().strftime('%H:%M:%S %d.%m.%Y'), file))
        fileTo.close()
    except BaseException:
        print('%s - Can\'t generate file with random strings!' % datetime.now().strftime('%H:%M:%S %d.%m.%Y'))
        traceback.print_exc()
        return 1
    return 0


@DurationOperation
def Bruter(instance=0, opTimeout=3, loginField="", passwordField="", acceptButton="", successAuth="", failAuth="",
           users=None, passwords=None, randomization=False, result='result.txt'):
    """
    This function loops through user IDs and passwords and finds suitable credentials.
    """
    # Dictionary {user:pass} for suitable user and password.
    suitableCredentials = {}
    startTime = datetime.now()
    try:
        page = browsers[instance]
        modUsers = users[:]
        modPasswords = passwords[:]
        if randomization:
            print('%s - Thread #%d, shuffling users and passwords ...' %
                  (datetime.now().strftime('%H:%M:%S %d.%m.%Y'), instance))
            random.shuffle(modUsers)
            random.shuffle(modPasswords)
        print('%s - Thread #%d, trying to use credentials ...' %
              (datetime.now().strftime('%H:%M:%S %d.%m.%Y'), instance))
        for user in modUsers:
            for pwd in modPasswords:
                try:
                    page.find_element_by_xpath(loginField).clear()
                    page.find_element_by_xpath(loginField).send_keys(user)
                    page.find_element_by_xpath(passwordField).clear()
                    page.find_element_by_xpath(passwordField).send_keys(pwd)
                    page.find_element_by_xpath(acceptButton).click()
                    WebDriverWait(page, opTimeout).until(
                        lambda el: el.find_element_by_xpath(successAuth).is_displayed(), '')
                    suitableCredentials = {user: pwd}
                    print('%s - Thread #%d, found valid credentials: %s' %
                          (datetime.now().strftime('%H:%M:%S %d.%m.%Y'), instance, str({user: pwd})))
                    break
                except:
                    try:
                        WebDriverWait(page, opTimeout).until(
                            lambda el: el.find_element_by_xpath(failAuth).is_displayed(),
                            '%s - Thread #%d, Can\'t find auth fields! Possible connection problem.' %
                            (datetime.now().strftime('%H:%M:%S %d.%m.%Y'), instance))
                    except:
                        pass
            if suitableCredentials != {}:
                break
        threads[instance] = None
        Reporting(instance, result, suitableCredentials, users, passwords, datetime.now() - startTime)
    except:
        traceback.print_exc()
        return 1
    return 0


# This is only library.
if __name__ == "__main__":
    pass