def update(): ''' check updates from https://github.com/jm33-m0/mec ''' os.chdir(MECROOT) # current version # pylint: disable=unused-variable old_ver = get_version() # refresh local git repo try: check = "git remote -v update" out = subprocess.check_output(["/bin/sh", "-c", check], stderr=subprocess.STDOUT, timeout=30) check_res = out.decode("utf-8") except subprocess.CalledProcessError as exc: console.print_error( f"[-] Failed to check for updates: {exc},\n{check_res}\npress enter to continue..." ) return if "[up to date]" in check_res: return # pull if needed pull = "git pull; echo '[mec-update-success]'" try: out = subprocess.check_output(["/bin/sh", "-c", pull], stderr=subprocess.STDOUT, timeout=30) pull_res = out.decode("utf-8") except subprocess.CalledProcessError as exc: console.print_error(f"[-] Failed to update mec: {exc}\n{pull_res}") return if "[mec-update-success]" in pull_res: if "error:" in pull_res: console.print_error( f"[-] Failed to update mec:\n{pull_res}, press enter to continue..." ) return console.print_success( f"[+] mec has been updated: {old_ver} -> {get_version()}\n") actions(act="restart")
def run_set(**kwargs): """ set mec config, you can write whatever opt:val you like """ session = kwargs.get("session", None) if session is None: console.print_error("[-] session not exist") return try: opt = kwargs.get("args")[0] val = kwargs.get("args")[1] except IndexError: console.print_error("[-] Set what?") return # read old configs new_config_lines = [] if os.path.isfile(session.config_file): for line in open(session.config_file).readlines(): line = line.strip().lower() if line.startswith(opt): continue new_config_lines.append(line) new_setting = f"{opt}: {val}" if len(new_config_lines) == 0: new_setting = f"{opt}: {val}\n" new_config_lines.append(new_setting) futil.write_file(text='\n'.join(new_config_lines), filepath=session.config_file, append=True) session.read_config() console.print_success(f"[+] {opt} has been set to {val}")
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 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: 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 call_update(self, silent=False): """ update mec record update result and act accordingly """ if self.auto_update: console.print_success("[-] auto-update is enabled") def update(res): ''' check updates from https://github.com/jm33-m0/mec ''' # current version old_ver = get_version() if old_ver == "": res['status'] = "[-] cannot get version" return os.chdir(MECROOT) # pull all tags try: check = "git pull --tags" out = subprocess.check_output( ["/bin/sh", "-c", check], stderr=subprocess.STDOUT, timeout=30) check_res = out.decode("utf-8") except KeyboardInterrupt: return except BaseException: res['status'] = f"[-] Failed to check for updates:\n{traceback.format_exc()}" return if "Already up to date" in check_res: res['status'] = "[+] already up to date" return # pull if needed pull = "git pull" try: out = subprocess.check_output( ["/bin/sh", "-c", pull], stderr=subprocess.STDOUT, timeout=30) pull_res = out.decode("utf-8") except KeyboardInterrupt: return except BaseException: res['status'] = f"[-] Failed to update mec: {traceback.format_exc()}" return if "error:" in pull_res: res['status'] = f"[-] Failed to update mec:\n{pull_res}, press enter to continue..." return res['status'] = f"[+] mec has been updated:\n{old_ver}->{get_version()}" return # update in child process if silent: res = {} update_job = Process(target=update, args=(res,)) update_job.start() return # check for result res = Manager().dict() update_job = Process(target=update, args=(res,)) update_job.start() # print status console.print_status( "[*] fetching updates from github...", update_job) update_job.join() # wait for result try: status = res['status'] except BaseException: status = "" if "[+]" in status: console.print_success(status) if "already up to date" in status: return if console.yes_no("[?] Exit mec (to apply updates) ?"): sys.exit(0) elif "[-]" in status: console.print_error(status)
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)